[BUGFIX] Missing column in t3lib_TCEmain::getPreviousLocalizedRecordUid
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_tceforms_inline.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2006-2011 Oliver Hader <oliver@typo3.org>
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * The Inline-Relational-Record-Editing (IRRE) functions as part of the TCEforms.
29 *
30 * @author Oliver Hader <oliver@typo3.org>
31 */
32
33
34 class t3lib_TCEforms_inline {
35 const Structure_Separator = '-';
36 const Disposal_AttributeName = 'Disposal_AttributeName';
37 const Disposal_AttributeId = 'Disposal_AttributeId';
38
39 /**
40 * Reference to the calling TCEforms instance
41 *
42 * @var t3lib_TCEforms
43 */
44 var $fObj;
45 var $backPath; // Reference to $fObj->backPath
46
47 var $isAjaxCall = FALSE; // Indicates if a field is rendered upon an AJAX call
48 var $inlineStructure = array(); // the structure/hierarchy where working in, e.g. cascading inline tables
49 var $inlineFirstPid; // the first call of an inline type appeared on this page (pid of record)
50 var $inlineNames = array(); // keys: form, object -> hold the name/id for each of them
51 var $inlineData = array(); // inline data array used for JSON output
52 var $inlineView = array(); // expanded/collapsed states for the current BE user
53 var $inlineCount = 0; // count the number of inline types used
54 var $inlineStyles = array();
55
56 var $prependNaming = 'data'; // how the $this->fObj->prependFormFieldNames should be set ('data' is default)
57 var $prependFormFieldNames; // reference to $this->fObj->prependFormFieldNames
58 var $prependCmdFieldNames; // reference to $this->fObj->prependCmdFieldNames
59
60 protected $hookObjects = array(); // array containing instances of hook classes called once for IRRE objects
61
62
63 /**
64 * Intialize an instance of t3lib_TCEforms_inline
65 *
66 * @param t3lib_TCEforms $tceForms: Reference to an TCEforms instance
67 * @return void
68 */
69 function init(&$tceForms) {
70 $this->fObj = $tceForms;
71 $this->backPath =& $tceForms->backPath;
72 $this->prependFormFieldNames =& $this->fObj->prependFormFieldNames;
73 $this->prependCmdFieldNames =& $this->fObj->prependCmdFieldNames;
74 $this->inlineStyles['margin-right'] = '5';
75 $this->initHookObjects();
76 }
77
78
79 /**
80 * Initialized the hook objects for this class.
81 * Each hook object has to implement the interface t3lib_tceformsInlineHook.
82 *
83 * @return void
84 */
85 protected function initHookObjects() {
86 $this->hookObjects = array();
87 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['tceformsInlineHook'])) {
88 $tceformsInlineHook =& $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['tceformsInlineHook'];
89 if (is_array($tceformsInlineHook)) {
90 foreach ($tceformsInlineHook as $classData) {
91 $processObject = t3lib_div::getUserObj($classData);
92
93 if (!($processObject instanceof t3lib_tceformsInlineHook)) {
94 throw new UnexpectedValueException('$processObject must implement interface t3lib_tceformsInlineHook', 1202072000);
95 }
96
97 $processObject->init($this);
98 $this->hookObjects[] = $processObject;
99 }
100 }
101 }
102 }
103
104
105 /**
106 * Generation of TCEform elements of the type "inline"
107 * This will render inline-relational-record sets. Relations.
108 *
109 * @param string $table: The table name of the record
110 * @param string $field: The field name which this element is supposed to edit
111 * @param array $row: The record data array where the value(s) for the field can be found
112 * @param array $PA: An array with additional configuration options.
113 * @return string The HTML code for the TCEform field
114 */
115 function getSingleField_typeInline($table, $field, $row, &$PA) {
116 // check the TCA configuration - if FALSE is returned, something was wrong
117 if ($this->checkConfiguration($PA['fieldConf']['config']) === FALSE) {
118 return FALSE;
119 }
120
121 $item = '';
122
123 // count the number of processed inline elements
124 $this->inlineCount++;
125
126 // Init:
127 $config = $PA['fieldConf']['config'];
128 $foreign_table = $config['foreign_table'];
129 t3lib_div::loadTCA($foreign_table);
130
131 if (t3lib_BEfunc::isTableLocalizable($table)) {
132 $language = intval($row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
133 }
134 $minitems = t3lib_utility_Math::forceIntegerInRange($config['minitems'], 0);
135 $maxitems = t3lib_utility_Math::forceIntegerInRange($config['maxitems'], 0);
136 if (!$maxitems) {
137 $maxitems = 100000;
138 }
139
140 // Register the required number of elements:
141 $this->fObj->requiredElements[$PA['itemFormElName']] = array($minitems, $maxitems, 'imgName' => $table . '_' . $row['uid'] . '_' . $field);
142
143 // remember the page id (pid of record) where inline editing started first
144 // we need that pid for ajax calls, so that they would know where the action takes place on the page structure
145 if (!isset($this->inlineFirstPid)) {
146 // if this record is not new, try to fetch the inlineView states
147 // @TODO: Add checking/cleaning for unused tables, records, etc. to save space in uc-field
148 if (t3lib_utility_Math::canBeInterpretedAsInteger($row['uid'])) {
149 $inlineView = unserialize($GLOBALS['BE_USER']->uc['inlineView']);
150 $this->inlineView = $inlineView[$table][$row['uid']];
151 }
152 // If the parent is a page, use the uid(!) of the (new?) page as pid for the child records:
153 if ($table == 'pages') {
154 $liveVersionId = t3lib_BEfunc::getLiveVersionIdOfRecord('pages', $row['uid']);
155 $this->inlineFirstPid = (is_null($liveVersionId) ? $row['uid'] : $liveVersionId);
156 // If pid is negative, fetch the previous record and take its pid:
157 } elseif ($row['pid'] < 0) {
158 $prevRec = t3lib_BEfunc::getRecord($table, abs($row['pid']));
159 $this->inlineFirstPid = $prevRec['pid'];
160 // Take the pid as it is:
161 } else {
162 $this->inlineFirstPid = $row['pid'];
163 }
164 }
165 // add the current inline job to the structure stack
166 $this->pushStructure($table, $row['uid'], $field, $config);
167 // e.g. data[<table>][<uid>][<field>]
168 $nameForm = $this->inlineNames['form'];
169 // e.g. data-<pid>-<table1>-<uid1>-<field1>-<table2>-<uid2>-<field2>
170 $nameObject = $this->inlineNames['object'];
171 // get the records related to this inline record
172 $relatedRecords = $this->getRelatedRecords($table, $field, $row, $PA, $config);
173 // set the first and last record to the config array
174 $relatedRecordsUids = array_keys($relatedRecords['records']);
175 $config['inline']['first'] = reset($relatedRecordsUids);
176 $config['inline']['last'] = end($relatedRecordsUids);
177
178 // Tell the browser what we have (using JSON later):
179 $top = $this->getStructureLevel(0);
180 $this->inlineData['config'][$nameObject] = array(
181 'table' => $foreign_table,
182 'md5' => md5($nameObject),
183 );
184 $this->inlineData['config'][$nameObject . self::Structure_Separator . $foreign_table] = array(
185 'min' => $minitems,
186 'max' => $maxitems,
187 'sortable' => $config['appearance']['useSortable'],
188 'top' => array(
189 'table' => $top['table'],
190 'uid' => $top['uid'],
191 ),
192 );
193 // Set a hint for nested IRRE and tab elements:
194 $this->inlineData['nested'][$nameObject] = $this->fObj->getDynNestedStack(FALSE, $this->isAjaxCall);
195
196 // if relations are required to be unique, get the uids that have already been used on the foreign side of the relation
197 if ($config['foreign_unique']) {
198 // If uniqueness *and* selector are set, they should point to the same field - so, get the configuration of one:
199 $selConfig = $this->getPossibleRecordsSelectorConfig($config, $config['foreign_unique']);
200 // Get the used unique ids:
201 $uniqueIds = $this->getUniqueIds($relatedRecords['records'], $config, $selConfig['type'] == 'groupdb');
202 $possibleRecords = $this->getPossibleRecords($table, $field, $row, $config, 'foreign_unique');
203 $uniqueMax = $config['appearance']['useCombination'] || $possibleRecords === FALSE ? -1 : count($possibleRecords);
204 $this->inlineData['unique'][$nameObject . self::Structure_Separator . $foreign_table] = array(
205 'max' => $uniqueMax,
206 'used' => $uniqueIds,
207 'type' => $selConfig['type'],
208 'table' => $config['foreign_table'],
209 'elTable' => $selConfig['table'], // element/record table (one step down in hierarchy)
210 'field' => $config['foreign_unique'],
211 'selector' => $selConfig['selector'],
212 'possible' => $this->getPossibleRecordsFlat($possibleRecords),
213 );
214 }
215
216 // if it's required to select from possible child records (reusable children), add a selector box
217 if ($config['foreign_selector'] && $config['appearance']['showPossibleRecordsSelector'] !== FALSE) {
218 // if not already set by the foreign_unique, set the possibleRecords here and the uniqueIds to an empty array
219 if (!$config['foreign_unique']) {
220 $possibleRecords = $this->getPossibleRecords($table, $field, $row, $config);
221 $uniqueIds = array();
222 }
223 $selectorBox = $this->renderPossibleRecordsSelector($possibleRecords, $config, $uniqueIds);
224 $item .= $selectorBox;
225 }
226
227 // wrap all inline fields of a record with a <div> (like a container)
228 $item .= '<div id="' . $nameObject . '">';
229
230 // define how to show the "Create new record" link - if there are more than maxitems, hide it
231 if ($relatedRecords['count'] >= $maxitems || ($uniqueMax > 0 && $relatedRecords['count'] >= $uniqueMax)) {
232 $config['inline']['inlineNewButtonStyle'] = 'display: none;';
233 }
234
235 // Render the level links (create new record, localize all, synchronize):
236 if ($config['appearance']['levelLinksPosition'] != 'none') {
237 $levelLinks = $this->getLevelInteractionLink('newRecord', $nameObject . self::Structure_Separator . $foreign_table, $config);
238
239 if ($language > 0 && $row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] > 0) {
240 // Add the "Localize all records" link before all child records:
241 if (isset($config['appearance']['showAllLocalizationLink']) && $config['appearance']['showAllLocalizationLink']) {
242 $levelLinks .= $this->getLevelInteractionLink('localize', $nameObject . self::Structure_Separator . $foreign_table, $config);
243 }
244 // Add the "Synchronize with default language" link before all child records:
245 if (isset($config['appearance']['showSynchronizationLink']) && $config['appearance']['showSynchronizationLink']) {
246 $levelLinks .= $this->getLevelInteractionLink('synchronize', $nameObject . self::Structure_Separator . $foreign_table, $config);
247 }
248 }
249 }
250 // Add the level links before all child records:
251 if (in_array($config['appearance']['levelLinksPosition'], array('both', 'top'))) {
252 $item .= $levelLinks;
253 }
254
255 $item .= '<div id="' . $nameObject . '_records">';
256 $relationList = array();
257 if (count($relatedRecords['records'])) {
258 foreach ($relatedRecords['records'] as $rec) {
259 $item .= $this->renderForeignRecord($row['uid'], $rec, $config);
260 if (!isset($rec['__virtual']) || !$rec['__virtual']) {
261 $relationList[] = $rec['uid'];
262 }
263 }
264 }
265 $item .= '</div>';
266
267 // Add the level links after all child records:
268 if (in_array($config['appearance']['levelLinksPosition'], array('both', 'bottom'))) {
269 $item .= $levelLinks;
270 }
271
272 if (is_array($config['customControls'])) {
273 $item .= '<div id="' . $nameObject . '_customControls">';
274 foreach ($config['customControls'] as $customControlConfig) {
275 $parameters = array(
276 'table' => $table,
277 'field' => $field,
278 'row' => $row,
279 'nameObject' => $nameObject,
280 'nameForm' => $nameForm,
281 'config' => $config
282 );
283 $item .= t3lib_div::callUserFunction($customControlConfig, $parameters, $this);
284 }
285 $item .= '</div>';
286 }
287
288 // add Drag&Drop functions for sorting to TCEforms::$additionalJS_post
289 if (count($relationList) > 1 && $config['appearance']['useSortable']) {
290 $this->addJavaScriptSortable($nameObject . '_records');
291 }
292 // publish the uids of the child records in the given order to the browser
293 $item .= '<input type="hidden" name="' . $nameForm . '" value="' . implode(',', $relationList) . '" class="inlineRecord" />';
294 // close the wrap for all inline fields (container)
295 $item .= '</div>';
296
297 // on finishing this section, remove the last item from the structure stack
298 $this->popStructure();
299
300 // if this was the first call to the inline type, restore the values
301 if (!$this->getStructureDepth()) {
302 unset($this->inlineFirstPid);
303 }
304
305 return $item;
306 }
307
308
309 /*******************************************************
310 *
311 * Regular rendering of forms, fields, etc.
312 *
313 *******************************************************/
314
315
316 /**
317 * Render the form-fields of a related (foreign) record.
318 *
319 * @param string $parentUid: The uid of the parent (embedding) record (uid or NEW...)
320 * @param array $rec: The table record of the child/embedded table (normaly post-processed by t3lib_transferData)
321 * @param array $config: content of $PA['fieldConf']['config']
322 * @return string The HTML code for this "foreign record"
323 */
324 function renderForeignRecord($parentUid, $rec, $config = array()) {
325 $foreign_table = $config['foreign_table'];
326 $foreign_field = $config['foreign_field'];
327 $foreign_selector = $config['foreign_selector'];
328
329 // Register default localization content:
330 $parent = $this->getStructureLevel(-1);
331 if (isset($parent['localizationMode']) && $parent['localizationMode'] != FALSE) {
332 $this->fObj->registerDefaultLanguageData($foreign_table, $rec);
333 }
334 // Send a mapping information to the browser via JSON:
335 // e.g. data[<curTable>][<curId>][<curField>] => data-<pid>-<parentTable>-<parentId>-<parentField>-<curTable>-<curId>-<curField>
336 $this->inlineData['map'][$this->inlineNames['form']] = $this->inlineNames['object'];
337
338 // Set this variable if we handle a brand new unsaved record:
339 $isNewRecord = t3lib_utility_Math::canBeInterpretedAsInteger($rec['uid']) ? FALSE : TRUE;
340 // Set this variable if the record is virtual and only show with header and not editable fields:
341 $isVirtualRecord = (isset($rec['__virtual']) && $rec['__virtual']);
342 // If there is a selector field, normalize it:
343 if ($foreign_selector) {
344 $rec[$foreign_selector] = $this->normalizeUid($rec[$foreign_selector]);
345 }
346
347 if (!$this->checkAccess(($isNewRecord ? 'new' : 'edit'), $foreign_table, $rec['uid'])) {
348 return FALSE;
349 }
350
351 // Get the current naming scheme for DOM name/id attributes:
352 $nameObject = $this->inlineNames['object'];
353 $appendFormFieldNames = '[' . $foreign_table . '][' . $rec['uid'] . ']';
354 $objectId = $nameObject . self::Structure_Separator . $foreign_table . self::Structure_Separator . $rec['uid'];
355 // Put the current level also to the dynNestedStack of TCEforms:
356 $this->fObj->pushToDynNestedStack('inline', $objectId);
357
358 if (!$isVirtualRecord) {
359 // Get configuration:
360 $collapseAll = (isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll']);
361 $expandAll = (isset($config['appearance']['collapseAll']) && !$config['appearance']['collapseAll']);
362 $ajaxLoad = (isset($config['appearance']['ajaxLoad']) && !$config['appearance']['ajaxLoad']) ? FALSE : TRUE;
363
364 if ($isNewRecord) {
365 // show this record expanded or collapsed
366 $isExpanded = ($expandAll || (!$collapseAll ? 1 : 0));
367 } else {
368 $isExpanded = ($config['renderFieldsOnly'] || (!$collapseAll && $this->getExpandedCollapsedState($foreign_table, $rec['uid'])) || $expandAll);
369 }
370 // Render full content ONLY IF this is a AJAX-request, a new record, the record is not collapsed or AJAX-loading is explicitly turned off
371 if ($isNewRecord || $isExpanded || !$ajaxLoad) {
372 $combination = $this->renderCombinationTable($rec, $appendFormFieldNames, $config);
373
374 $overruleTypesArray = isset($config['foreign_types']) ? $config['foreign_types'] : array();
375 $fields = $this->renderMainFields($foreign_table, $rec, $overruleTypesArray);
376 $fields = $this->wrapFormsSection($fields);
377 // Replace returnUrl in Wizard-Code, if this is an AJAX call
378 $ajaxArguments = t3lib_div::_GP('ajax');
379 if (isset($ajaxArguments[2]) && trim($ajaxArguments[2]) != '') {
380 $fields = str_replace('P[returnUrl]=%2F' . rawurlencode(TYPO3_mainDir) . 'ajax.php', 'P[returnUrl]=' . rawurlencode($ajaxArguments[2]), $fields);
381 }
382 } else {
383 $combination = '';
384 // This string is the marker for the JS-function to check if the full content has already been loaded
385 $fields = '<!--notloaded-->';
386 }
387 if ($isNewRecord) {
388 // get the top parent table
389 $top = $this->getStructureLevel(0);
390 $ucFieldName = 'uc[inlineView][' . $top['table'] . '][' . $top['uid'] . ']' . $appendFormFieldNames;
391 // set additional fields for processing for saving
392 $fields .= '<input type="hidden" name="' . $this->prependFormFieldNames . $appendFormFieldNames . '[pid]" value="' . $rec['pid'] . '"/>';
393 $fields .= '<input type="hidden" name="' . $ucFieldName . '" value="' . $isExpanded . '" />';
394 } else {
395 // set additional field for processing for saving
396 $fields .= '<input type="hidden" name="' . $this->prependCmdFieldNames . $appendFormFieldNames . '[delete]" value="1" disabled="disabled" />';
397 }
398 // if this record should be shown collapsed
399 if (!$isExpanded) {
400 $appearanceStyleFields = ' style="display: none;"';
401 }
402 }
403
404 if ($config['renderFieldsOnly']) {
405 $out = $fields . $combination;
406 } else {
407 // set the record container with data for output
408 $out = '<div class="t3-form-field-record-inline" id="' . $objectId . '_fields"' . $appearanceStyleFields . '>' . $fields . $combination . '</div>';
409 $header = $this->renderForeignRecordHeader($parentUid, $foreign_table, $rec, $config, $isVirtualRecord);
410 $out = '<div class="t3-form-field-header-inline" id="' . $objectId . '_header">' . $header . '</div>' . $out;
411 // wrap the header, fields and combination part of a child record with a div container
412 $classMSIE = ($this->fObj->clientInfo['BROWSER'] == 'msie' && $this->fObj->clientInfo['VERSION'] < 8 ? 'MSIE' : '');
413 $class = 'inlineDiv' . $classMSIE . ($isNewRecord ? ' inlineIsNewRecord' : '');
414 $out = '<div id="' . $objectId . '_div" class="t3-form-field-container-inline ' . $class . '">' . $out . '</div>';
415 }
416 // Remove the current level also from the dynNestedStack of TCEforms:
417 $this->fObj->popFromDynNestedStack();
418
419 return $out;
420 }
421
422
423 /**
424 * Wrapper for TCEforms::getMainFields().
425 *
426 * @param string $table: The table name
427 * @param array $row: The record to be rendered
428 * @param array $overruleTypesArray: Overrule TCA [types] array, e.g to overrride [showitem] configuration of a particular type
429 * @return string The rendered form
430 */
431 protected function renderMainFields($table, array $row, array $overruleTypesArray = array()) {
432 // The current render depth of t3lib_TCEforms:
433 $depth = $this->fObj->renderDepth;
434 // If there is some information about already rendered palettes of our parent, store this info:
435 if (isset($this->fObj->palettesRendered[$depth][$table])) {
436 $palettesRendered = $this->fObj->palettesRendered[$depth][$table];
437 }
438 // Render the form:
439 $content = $this->fObj->getMainFields($table, $row, $depth, $overruleTypesArray);
440 // If there was some info about rendered palettes stored, write it back for our parent:
441 if (isset($palettesRendered)) {
442 $this->fObj->palettesRendered[$depth][$table] = $palettesRendered;
443 }
444 return $content;
445 }
446
447
448 /**
449 * Renders the HTML header for a foreign record, such as the title, toggle-function, drag'n'drop, etc.
450 * Later on the command-icons are inserted here.
451 *
452 * @param string $parentUid: The uid of the parent (embedding) record (uid or NEW...)
453 * @param string $foreign_table: The foreign_table we create a header for
454 * @param array $rec: The current record of that foreign_table
455 * @param array $config: content of $PA['fieldConf']['config']
456 * @param boolean $isVirtualRecord:
457 * @return string The HTML code of the header
458 */
459 function renderForeignRecordHeader($parentUid, $foreign_table, $rec, $config, $isVirtualRecord = FALSE) {
460 // Init:
461 $objectId = $this->inlineNames['object'] . self::Structure_Separator . $foreign_table . self::Structure_Separator . $rec['uid'];
462 $expandSingle = $config['appearance']['expandSingle'] ? 1 : 0;
463 // we need the returnUrl of the main script when loading the fields via AJAX-call (to correct wizard code, so include it as 3rd parameter)
464 $onClick = "return inline.expandCollapseRecord('" . htmlspecialchars($objectId) . "', $expandSingle, '" . rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI')) . "')";
465
466 // Pre-Processing:
467 $isOnSymmetricSide = t3lib_loadDBGroup::isOnSymmetricSide($parentUid, $config, $rec);
468 $hasForeignLabel = !$isOnSymmetricSide && $config['foreign_label'] ? TRUE : FALSE;
469 $hasSymmetricLabel = $isOnSymmetricSide && $config['symmetric_label'] ? TRUE : FALSE;
470 // Get the record title/label for a record:
471 // render using a self-defined user function
472 if ($GLOBALS['TCA'][$foreign_table]['ctrl']['label_userFunc']) {
473 $params = array(
474 'table' => $foreign_table,
475 'row' => $rec,
476 'title' => '',
477 'isOnSymmetricSide' => $isOnSymmetricSide,
478 'parent' => array(
479 'uid' => $parentUid,
480 'config' => $config,
481 ),
482 );
483 $null = NULL; // callUserFunction requires a third parameter, but we don't want to give $this as reference!
484 t3lib_div::callUserFunction($GLOBALS['TCA'][$foreign_table]['ctrl']['label_userFunc'], $params, $null);
485 $recTitle = $params['title'];
486 // render the special alternative title
487 } elseif ($hasForeignLabel || $hasSymmetricLabel) {
488 $titleCol = $hasForeignLabel ? $config['foreign_label'] : $config['symmetric_label'];
489 $foreignConfig = $this->getPossibleRecordsSelectorConfig($config, $titleCol);
490 // Render title for everything else than group/db:
491 if ($foreignConfig['type'] != 'groupdb') {
492 $recTitle = t3lib_BEfunc::getProcessedValueExtra($foreign_table, $titleCol, $rec[$titleCol], 0, 0, FALSE);
493 // Render title for group/db:
494 } else {
495 // $recTitle could be something like: "tx_table_123|...",
496 $valueParts = t3lib_div::trimExplode('|', $rec[$titleCol]);
497 $itemParts = t3lib_div::revExplode('_', $valueParts[0], 2);
498 $recTemp = t3lib_befunc::getRecordWSOL($itemParts[0], $itemParts[1]);
499 $recTitle = t3lib_BEfunc::getRecordTitle($itemParts[0], $recTemp, FALSE);
500 }
501 $recTitle = t3lib_BEfunc::getRecordTitlePrep($recTitle);
502 if (!strcmp(trim($recTitle), '')) {
503 $recTitle = t3lib_BEfunc::getNoRecordTitle(TRUE);
504 }
505 // render the standard
506 } else {
507 $recTitle = t3lib_BEfunc::getRecordTitle($foreign_table, $rec, TRUE);
508 }
509
510 $altText = t3lib_BEfunc::getRecordIconAltText($rec, $foreign_table);
511 $iconImg = t3lib_iconWorks::getSpriteIconForRecord($foreign_table, $rec, array('title' => htmlspecialchars($altText), 'id' => $objectId . '_icon'));
512 $label = '<span id="' . $objectId . '_label">' . $recTitle . '</span>';
513 if (!$isVirtualRecord) {
514 $iconImg = $this->wrapWithAnchor($iconImg, '#', array('onclick' => $onClick));
515 $label = $this->wrapWithAnchor($label, '#', array('onclick' => $onClick, 'style' => 'display: block;'));
516 }
517
518 $ctrl = $this->renderForeignRecordHeaderControl($parentUid, $foreign_table, $rec, $config, $isVirtualRecord);
519
520 // @TODO: Check the table wrapping and the CSS definitions
521 $header =
522 '<table cellspacing="0" cellpadding="0" border="0" width="100%" style="margin-right: ' . $this->inlineStyles['margin-right'] . 'px;"' .
523 ($this->fObj->borderStyle[2] ? ' background="' . htmlspecialchars($this->backPath . $this->fObj->borderStyle[2]) . '"' : '') .
524 ($this->fObj->borderStyle[3] ? ' class="' . htmlspecialchars($this->fObj->borderStyle[3]) . '"' : '') . '>' .
525 '<tr class="class-main12"><td width="18" id="' . $objectId . '_iconcontainer">' . $iconImg . '</td><td align="left"><strong>' . $label . '</strong></td><td align="right">' . $ctrl . '</td></tr></table>';
526
527 return $header;
528 }
529
530
531 /**
532 * Render the control-icons for a record header (create new, sorting, delete, disable/enable).
533 * Most of the parts are copy&paste from class.db_list_extra.inc and modified for the JavaScript calls here
534 *
535 * @param string $parentUid: The uid of the parent (embedding) record (uid or NEW...)
536 * @param string $foreign_table: The table (foreign_table) we create control-icons for
537 * @param array $rec: The current record of that foreign_table
538 * @param array $config: (modified) TCA configuration of the field
539 * @return string The HTML code with the control-icons
540 */
541 function renderForeignRecordHeaderControl($parentUid, $foreign_table, $rec, $config = array(), $isVirtualRecord = FALSE) {
542 // Initialize:
543 $cells = array();
544 $isNewItem = substr($rec['uid'], 0, 3) == 'NEW';
545
546 $tcaTableCtrl =& $GLOBALS['TCA'][$foreign_table]['ctrl'];
547 $tcaTableCols =& $GLOBALS['TCA'][$foreign_table]['columns'];
548
549 $isPagesTable = $foreign_table == 'pages' ? TRUE : FALSE;
550 $isOnSymmetricSide = t3lib_loadDBGroup::isOnSymmetricSide($parentUid, $config, $rec);
551 $enableManualSorting = $tcaTableCtrl['sortby'] || $config['MM'] || (!$isOnSymmetricSide && $config['foreign_sortby']) || ($isOnSymmetricSide && $config['symmetric_sortby']) ? TRUE : FALSE;
552
553 $nameObject = $this->inlineNames['object'];
554 $nameObjectFt = $nameObject . self::Structure_Separator . $foreign_table;
555 $nameObjectFtId = $nameObjectFt . self::Structure_Separator . $rec['uid'];
556
557 $calcPerms = $GLOBALS['BE_USER']->calcPerms(
558 t3lib_BEfunc::readPageAccess($rec['pid'], $GLOBALS['BE_USER']->getPagePermsClause(1))
559 );
560
561 // If the listed table is 'pages' we have to request the permission settings for each page:
562 if ($isPagesTable) {
563 $localCalcPerms = $GLOBALS['BE_USER']->calcPerms(t3lib_BEfunc::getRecord('pages', $rec['uid']));
564 }
565
566 // This expresses the edit permissions for this particular element:
567 $permsEdit = ($isPagesTable && ($localCalcPerms & 2)) || (!$isPagesTable && ($calcPerms & 16));
568
569 // Controls: Defines which controls should be shown
570 $enabledControls = $config['appearance']['enabledControls'];
571 // Hook: Can disable/enable single controls for specific child records:
572 foreach ($this->hookObjects as $hookObj) {
573 $hookObj->renderForeignRecordHeaderControl_preProcess($parentUid, $foreign_table, $rec, $config, $isVirtualRecord, $enabledControls);
574 }
575
576 // Icon to visualize that a required field is nested in this inline level:
577 $cells['required'] = '<img name="' . $nameObjectFtId . '_req" src="clear.gif" width="10" height="10" hspace="4" vspace="3" alt="" />';
578
579 if (isset($rec['__create'])) {
580 $cells['localize.isLocalizable'] = t3lib_iconWorks::getSpriteIcon('actions-edit-localize-status-low', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xml:localize.isLocalizable', TRUE)));
581 } elseif (isset($rec['__remove'])) {
582 $cells['localize.wasRemovedInOriginal'] = t3lib_iconWorks::getSpriteIcon('actions-edit-localize-status-high', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xml:localize.wasRemovedInOriginal', 1)));
583 }
584
585 // "Info": (All records)
586 if ($enabledControls['info'] && !$isNewItem) {
587 $cells['info'] = '<a href="#" onclick="' . htmlspecialchars('top.launchView(\'' . $foreign_table . '\', \'' . $rec['uid'] . '\'); return false;') . '">' .
588 t3lib_iconWorks::getSpriteIcon('status-dialog-information', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:showInfo', TRUE))) .
589 '</a>';
590 }
591 // If the table is NOT a read-only table, then show these links:
592 if (!$tcaTableCtrl['readOnly'] && !$isVirtualRecord) {
593
594 // "New record after" link (ONLY if the records in the table are sorted by a "sortby"-row or if default values can depend on previous record):
595 if ($enabledControls['new'] && ($enableManualSorting || $tcaTableCtrl['useColumnsForDefaultValues'])) {
596 if (
597 (!$isPagesTable && ($calcPerms & 16)) || // For NON-pages, must have permission to edit content on this parent page
598 ($isPagesTable && ($calcPerms & 8)) // For pages, must have permission to create new pages here.
599 ) {
600 $onClick = "return inline.createNewRecord('" . $nameObjectFt . "','" . $rec['uid'] . "')";
601 $class = ' class="inlineNewButton ' . $this->inlineData['config'][$nameObject]['md5'] . '"';
602 if ($config['inline']['inlineNewButtonStyle']) {
603 $style = ' style="' . $config['inline']['inlineNewButtonStyle'] . '"';
604 }
605 $cells['new'] = '<a href="#" onclick="' . htmlspecialchars($onClick) . '"' . $class . $style . '>' .
606 t3lib_iconWorks::getSpriteIcon('actions-' . ($isPagesTable ? 'page' : 'document') . '-new',
607 array(
608 'title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:new' . ($isPagesTable ? 'Page' : 'Record'), 1)
609 )
610 ) .
611 '</a>';
612 }
613 }
614
615 // Drag&Drop Sorting: Sortable handler for script.aculo.us
616 if ($enabledControls['dragdrop'] && $permsEdit && $enableManualSorting && $config['appearance']['useSortable']) {
617 $cells['dragdrop'] = t3lib_iconWorks::getSpriteIcon('actions-move-move', array('class' => 'sortableHandle', 'title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.move', TRUE)));
618 }
619
620 // "Up/Down" links
621 if ($enabledControls['sort'] && $permsEdit && $enableManualSorting) {
622 $onClick = "return inline.changeSorting('" . $nameObjectFtId . "', '1')"; // Up
623 $style = $config['inline']['first'] == $rec['uid'] ? 'style="visibility: hidden;"' : '';
624 $cells['sort.up'] = '<a href="#" onclick="' . htmlspecialchars($onClick) . '" class="sortingUp" ' . $style . '>' .
625 t3lib_iconWorks::getSpriteIcon('actions-move-up', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:moveUp', TRUE))) .
626 '</a>';
627
628 $onClick = "return inline.changeSorting('" . $nameObjectFtId . "', '-1')"; // Down
629 $style = $config['inline']['last'] == $rec['uid'] ? 'style="visibility: hidden;"' : '';
630 $cells['sort.down'] = '<a href="#" onclick="' . htmlspecialchars($onClick) . '" class="sortingDown" ' . $style . '>' .
631 t3lib_iconWorks::getSpriteIcon('actions-move-down', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:moveDown', TRUE))) .
632 '</a>';
633 }
634
635 // "Hide/Unhide" links:
636 $hiddenField = $tcaTableCtrl['enablecolumns']['disabled'];
637 if ($enabledControls['hide'] && $permsEdit && $hiddenField && $tcaTableCols[$hiddenField] && (!$tcaTableCols[$hiddenField]['exclude'] || $GLOBALS['BE_USER']->check('non_exclude_fields', $foreign_table . ':' . $hiddenField))) {
638 $onClick = "return inline.enableDisableRecord('" . $nameObjectFtId . "')";
639 if ($rec[$hiddenField]) {
640 $cells['hide.unhide'] = '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' .
641 t3lib_iconWorks::getSpriteIcon(
642 'actions-edit-unhide',
643 array(
644 'title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:unHide' . ($isPagesTable ? 'Page' : ''), 1),
645 'id' => $nameObjectFtId . '_disabled'
646 )
647 ) .
648 '</a>';
649 } else {
650 $cells['hide.hide'] = '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' .
651 t3lib_iconWorks::getSpriteIcon(
652 'actions-edit-hide',
653 array(
654 'title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:hide' . ($isPagesTable ? 'Page' : ''), 1),
655 'id' => $nameObjectFtId . '_disabled'
656 )
657 ) .
658 '</a>';
659 }
660 }
661
662 // "Delete" link:
663 if ($enabledControls['delete'] && ($isPagesTable && $localCalcPerms & 4 || !$isPagesTable && $calcPerms & 16)) {
664 $onClick = "inline.deleteRecord('" . $nameObjectFtId . "');";
665 $cells['delete'] = '<a href="#" onclick="' . htmlspecialchars('if (confirm(' . $GLOBALS['LANG']->JScharCode($GLOBALS['LANG']->getLL('deleteWarning')) . ')) { ' . $onClick . ' } return false;') . '">' .
666 t3lib_iconWorks::getSpriteIcon('actions-edit-delete', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:delete', TRUE))) .
667 '</a>';
668 }
669 // If this is a virtual record offer a minimized set of icons for user interaction:
670 } elseif ($isVirtualRecord) {
671 if ($enabledControls['localize'] && isset($rec['__create'])) {
672 $onClick = "inline.synchronizeLocalizeRecords('" . $nameObjectFt . "', " . $rec['uid'] . ");";
673 $cells['localize'] = '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' .
674 t3lib_iconWorks::getSpriteIcon('actions-document-localize', array('title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xml:localize', TRUE))) .
675 '</a>';
676 }
677 }
678
679 // If the record is edit-locked by another user, we will show a little warning sign:
680 if ($lockInfo = t3lib_BEfunc::isRecordLocked($foreign_table, $rec['uid'])) {
681 $cells['locked'] = '<a href="#" onclick="' . htmlspecialchars('alert(' . $GLOBALS['LANG']->JScharCode($lockInfo['msg']) . ');return false;') . '">' .
682 t3lib_iconWorks::getSpriteIcon('status-warning-in-use', array('title' => htmlspecialchars($lockInfo['msg']))) .
683 '</a>';
684 }
685
686 // Hook: Post-processing of single controls for specific child records:
687 foreach ($this->hookObjects as $hookObj) {
688 $hookObj->renderForeignRecordHeaderControl_postProcess($parentUid, $foreign_table, $rec, $config, $isVirtualRecord, $cells);
689 }
690 // Compile items into a DIV-element:
691 return '
692 <!-- CONTROL PANEL: ' . $foreign_table . ':' . $rec['uid'] . ' -->
693 <div class="typo3-DBctrl">' . implode('', $cells) . '</div>';
694 }
695
696
697 /**
698 * Render a table with TCEforms, that occurs on a intermediate table but should be editable directly,
699 * so two tables are combined (the intermediate table with attributes and the sub-embedded table).
700 * -> This is a direct embedding over two levels!
701 *
702 * @param array $rec: The table record of the child/embedded table (normaly post-processed by t3lib_transferData)
703 * @param string $appendFormFieldNames: The [<table>][<uid>] of the parent record (the intermediate table)
704 * @param array $config: content of $PA['fieldConf']['config']
705 * @return string A HTML string with <table> tag around.
706 */
707 function renderCombinationTable(&$rec, $appendFormFieldNames, $config = array()) {
708 $foreign_table = $config['foreign_table'];
709 $foreign_selector = $config['foreign_selector'];
710
711 if ($foreign_selector && $config['appearance']['useCombination']) {
712 $comboConfig = $GLOBALS['TCA'][$foreign_table]['columns'][$foreign_selector]['config'];
713 $comboRecord = array();
714
715 // If record does already exist, load it:
716 if ($rec[$foreign_selector] && t3lib_utility_Math::canBeInterpretedAsInteger($rec[$foreign_selector])) {
717 $comboRecord = $this->getRecord(
718 $this->inlineFirstPid,
719 $comboConfig['foreign_table'],
720 $rec[$foreign_selector]
721 );
722 $isNewRecord = FALSE;
723 // It is a new record, create a new record virtually:
724 } else {
725 $comboRecord = $this->getNewRecord(
726 $this->inlineFirstPid,
727 $comboConfig['foreign_table']
728 );
729 $isNewRecord = TRUE;
730 }
731
732 // get the TCEforms interpretation of the TCA of the child table
733 $out = $this->renderMainFields($comboConfig['foreign_table'], $comboRecord);
734 $out = $this->wrapFormsSection($out, array(), array('class' => 'wrapperAttention'));
735
736 // if this is a new record, add a pid value to store this record and the pointer value for the intermediate table
737 if ($isNewRecord) {
738 $comboFormFieldName = $this->prependFormFieldNames . '[' . $comboConfig['foreign_table'] . '][' . $comboRecord['uid'] . '][pid]';
739 $out .= '<input type="hidden" name="' . $comboFormFieldName . '" value="' . $comboRecord['pid'] . '" />';
740 }
741
742 // if the foreign_selector field is also responsible for uniqueness, tell the browser the uid of the "other" side of the relation
743 if ($isNewRecord || $config['foreign_unique'] == $foreign_selector) {
744 $parentFormFieldName = $this->prependFormFieldNames . $appendFormFieldNames . '[' . $foreign_selector . ']';
745 $out .= '<input type="hidden" name="' . $parentFormFieldName . '" value="' . $comboRecord['uid'] . '" />';
746 }
747 }
748
749 return $out;
750 }
751
752
753 /**
754 * Get a selector as used for the select type, to select from all available
755 * records and to create a relation to the embedding record (e.g. like MM).
756 *
757 * @param array $selItems: Array of all possible records
758 * @param array $conf: TCA configuration of the parent(!) field
759 * @param array $uniqueIds: The uids that have already been used and should be unique
760 * @return string A HTML <select> box with all possible records
761 */
762 function renderPossibleRecordsSelector($selItems, $conf, $uniqueIds = array()) {
763 $foreign_table = $conf['foreign_table'];
764 $foreign_selector = $conf['foreign_selector'];
765
766 $selConfig = $this->getPossibleRecordsSelectorConfig($conf, $foreign_selector);
767 $config = $selConfig['PA']['fieldConf']['config'];
768
769 if ($selConfig['type'] == 'select') {
770 $item = $this->renderPossibleRecordsSelectorTypeSelect($selItems, $conf, $selConfig['PA'], $uniqueIds);
771 } elseif ($selConfig['type'] == 'groupdb') {
772 $item = $this->renderPossibleRecordsSelectorTypeGroupDB($conf, $selConfig['PA']);
773 }
774
775 return $item;
776 }
777
778
779 /**
780 * Get a selector as used for the select type, to select from all available
781 * records and to create a relation to the embedding record (e.g. like MM).
782 *
783 * @param array $selItems: Array of all possible records
784 * @param array $conf: TCA configuration of the parent(!) field
785 * @param array $PA: An array with additional configuration options
786 * @param array $uniqueIds: The uids that have already been used and should be unique
787 * @return string A HTML <select> box with all possible records
788 */
789 function renderPossibleRecordsSelectorTypeSelect($selItems, $conf, &$PA, $uniqueIds = array()) {
790 $foreign_table = $conf['foreign_table'];
791 $foreign_selector = $conf['foreign_selector'];
792
793 $PA = array();
794 $PA['fieldConf'] = $GLOBALS['TCA'][$foreign_table]['columns'][$foreign_selector];
795 $PA['fieldConf']['config']['form_type'] = $PA['fieldConf']['config']['form_type'] ? $PA['fieldConf']['config']['form_type'] : $PA['fieldConf']['config']['type']; // Using "form_type" locally in this script
796 $PA['fieldTSConfig'] = $this->fObj->setTSconfig($foreign_table, array(), $foreign_selector);
797 $config = $PA['fieldConf']['config'];
798
799 //TODO: $disabled is not present - should be read from config?
800 $disabled = FALSE;
801 if (!$disabled) {
802 // Create option tags:
803 $opt = array();
804 $styleAttrValue = '';
805 foreach ($selItems as $p) {
806 if ($config['iconsInOptionTags']) {
807 $styleAttrValue = $this->fObj->optionTagStyle($p[2]);
808 }
809 if (!in_array($p[1], $uniqueIds)) {
810 $opt[] = '<option value="' . htmlspecialchars($p[1]) . '"' .
811 ' style="' . (in_array($p[1], $uniqueIds) ? '' : '') .
812 ($styleAttrValue ? ' style="' . htmlspecialchars($styleAttrValue) : '') . '">' .
813 htmlspecialchars($p[0]) . '</option>';
814 }
815 }
816
817 // Put together the selector box:
818 $selector_itemListStyle = isset($config['itemListStyle']) ? ' style="' . htmlspecialchars($config['itemListStyle']) . '"' : ' style="' . $this->fObj->defaultMultipleSelectorStyle . '"';
819 $size = intval($conf['size']);
820 $size = $conf['autoSizeMax'] ? t3lib_utility_Math::forceIntegerInRange(count($selItems) + 1, t3lib_utility_Math::forceIntegerInRange($size, 1), $conf['autoSizeMax']) : $size;
821 $onChange = "return inline.importNewRecord('" . $this->inlineNames['object'] . self::Structure_Separator . $conf['foreign_table'] . "')";
822 $item = '
823 <select id="' . $this->inlineNames['object'] . self::Structure_Separator . $conf['foreign_table'] . '_selector"' .
824 $this->fObj->insertDefStyle('select') .
825 ($size ? ' size="' . $size . '"' : '') .
826 ' onchange="' . htmlspecialchars($onChange) . '"' .
827 $PA['onFocus'] .
828 $selector_itemListStyle .
829 ($conf['foreign_unique'] ? ' isunique="isunique"' : '') . '>
830 ' . implode('
831 ', $opt) . '
832 </select>';
833
834 // add a "Create new relation" link for adding new relations
835 // this is neccessary, if the size of the selector is "1" or if
836 // there is only one record item in the select-box, that is selected by default
837 // the selector-box creates a new relation on using a onChange event (see some line above)
838 $createNewRelationText = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:cm.createNewRelation', 1);
839 $item .=
840 '<a href="#" onclick="' . htmlspecialchars($onChange) . '" align="abstop">' .
841 t3lib_iconWorks::getSpriteIcon('actions-document-new', array('title' => $createNewRelationText)) . $createNewRelationText .
842 '</a>';
843 // wrap the selector and add a spacer to the bottom
844 $item = '<div style="margin-bottom: 20px;">' . $item . '</div>';
845 }
846
847 return $item;
848 }
849
850
851 /**
852 * Generate a link that opens an element browser in a new window.
853 * For group/db there is no way o use a "selector" like a <select>|</select>-box.
854 *
855 * @param array $conf: TCA configuration of the parent(!) field
856 * @param array $PA: An array with additional configuration options
857 * @return string A HTML link that opens an element browser in a new window
858 */
859 function renderPossibleRecordsSelectorTypeGroupDB($conf, &$PA) {
860 $foreign_table = $conf['foreign_table'];
861
862 $config = $PA['fieldConf']['config'];
863 $allowed = $config['allowed'];
864 $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $foreign_table;
865
866 $createNewRelationText = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:cm.createNewRelation', 1);
867 $onClick = "setFormValueOpenBrowser('db','" . ('|||' . $allowed . '|' . $objectPrefix . '|inline.checkUniqueElement||inline.importElement') . "'); return false;";
868 $item =
869 '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' .
870 t3lib_iconWorks::getSpriteIcon('actions-insert-record', array('title' => $createNewRelationText)) . $createNewRelationText .
871 '</a>';
872
873 return $item;
874 }
875
876
877 /**
878 * Creates the HTML code of a general link to be used on a level of inline children.
879 * The possible keys for the parameter $type are 'newRecord', 'localize' and 'synchronize'.
880 *
881 * @param string $type: The link type, values are 'newRecord', 'localize' and 'synchronize'.
882 * @param string $objectPrefix: The "path" to the child record to create (e.g. 'data-parentPageId-partenTable-parentUid-parentField-childTable]')
883 * @param array $conf: TCA configuration of the parent(!) field
884 * @return string The HTML code of the new link, wrapped in a div
885 */
886 protected function getLevelInteractionLink($type, $objectPrefix, $conf = array()) {
887 $nameObject = $this->inlineNames['object'];
888 $attributes = array();
889 switch ($type) {
890 case 'newRecord':
891 $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:cm.createnew', 1);
892 $icon = 'actions-document-new';
893 $className = 'typo3-newRecordLink';
894 $attributes['class'] = 'inlineNewButton ' . $this->inlineData['config'][$nameObject]['md5'];
895 $attributes['onclick'] = "return inline.createNewRecord('$objectPrefix')";
896 if (isset($conf['inline']['inlineNewButtonStyle']) && $conf['inline']['inlineNewButtonStyle']) {
897 $attributes['style'] = $conf['inline']['inlineNewButtonStyle'];
898 }
899 if (isset($conf['appearance']['newRecordLinkAddTitle']) && $conf['appearance']['newRecordLinkAddTitle']) {
900 $titleAddon = ' ' . $GLOBALS['LANG']->sL($GLOBALS['TCA'][$conf['foreign_table']]['ctrl']['title'], 1);
901 }
902 break;
903 case 'localize':
904 $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xml:localizeAllRecords', 1);
905 $icon = 'actions-document-localize';
906 $className = 'typo3-localizationLink';
907 $attributes['onclick'] = "return inline.synchronizeLocalizeRecords('$objectPrefix', 'localize')";
908 break;
909 case 'synchronize':
910 $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xml:synchronizeWithOriginalLanguage', 1);
911 $icon = 'actions-document-synchronize';
912 $className = 'typo3-synchronizationLink';
913 $attributes['class'] = 'inlineNewButton ' . $this->inlineData['config'][$nameObject]['md5'];
914 $attributes['onclick'] = "return inline.synchronizeLocalizeRecords('$objectPrefix', 'synchronize')";
915 break;
916 }
917 // Create the link:
918 $icon = ($icon ? t3lib_iconWorks::getSpriteIcon($icon, array('title' => htmlspecialchars($title . $titleAddon))) : '');
919 $link = $this->wrapWithAnchor($icon . $title . $titleAddon, '#', $attributes);
920 return '<div' . ($className ? ' class="' . $className . '"' : '') . '>' . $link . '</div>';
921 }
922
923
924 /**
925 * Add Sortable functionality using script.acolo.us "Sortable".
926 *
927 * @param string $objectId: The container id of the object - elements inside will be sortable
928 * @return void
929 */
930 function addJavaScriptSortable($objectId) {
931 $this->fObj->additionalJS_post[] = '
932 inline.createDragAndDropSorting("' . $objectId . '");
933 ';
934 }
935
936
937 /*******************************************************
938 *
939 * Handling of AJAX calls
940 *
941 *******************************************************/
942
943
944 /**
945 * General processor for AJAX requests concerning IRRE.
946 * (called by typo3/ajax.php)
947 *
948 * @param array $params: additional parameters (not used here)
949 * @param TYPO3AJAX $ajaxObj: the TYPO3AJAX object of this request
950 * @return void
951 */
952 public function processAjaxRequest($params, $ajaxObj) {
953
954 $ajaxArguments = t3lib_div::_GP('ajax');
955 $ajaxIdParts = explode('::', $GLOBALS['ajaxID'], 2);
956
957 if (isset($ajaxArguments) && is_array($ajaxArguments) && count($ajaxArguments)) {
958 $ajaxMethod = $ajaxIdParts[1];
959 switch ($ajaxMethod) {
960 case 'createNewRecord':
961 case 'synchronizeLocalizeRecords':
962 case 'getRecordDetails':
963 $this->isAjaxCall = TRUE;
964 // Construct runtime environment for Inline Relational Record Editing:
965 $this->processAjaxRequestConstruct($ajaxArguments);
966 // Parse the DOM identifier (string), add the levels to the structure stack (array) and load the TCA config:
967 $this->parseStructureString($ajaxArguments[0], TRUE);
968 // Render content:
969 $ajaxObj->setContentFormat('jsonbody');
970 $ajaxObj->setContent(
971 call_user_func_array(array(&$this, $ajaxMethod), $ajaxArguments)
972 );
973 break;
974 case 'setExpandedCollapsedState':
975 $ajaxObj->setContentFormat('jsonbody');
976 call_user_func_array(array(&$this, $ajaxMethod), $ajaxArguments);
977 break;
978 }
979 }
980 }
981
982
983 /**
984 * Construct runtime environment for Inline Relational Record Editing.
985 * - creates an anoymous SC_alt_doc in $GLOBALS['SOBE']
986 * - creates a t3lib_TCEforms in $GLOBALS['SOBE']->tceforms
987 * - sets ourself as reference to $GLOBALS['SOBE']->tceforms->inline
988 * - sets $GLOBALS['SOBE']->tceforms->RTEcounter to the current situation on client-side
989 *
990 * @param array &$ajaxArguments: The arguments to be processed by the AJAX request
991 * @return void
992 */
993 protected function processAjaxRequestConstruct(&$ajaxArguments) {
994 require_once(PATH_typo3 . 'template.php');
995
996 $GLOBALS['LANG']->includeLLFile('EXT:lang/locallang_alt_doc.xml');
997
998 // Create a new anonymous object:
999 $GLOBALS['SOBE'] = new stdClass();
1000 $GLOBALS['SOBE']->MOD_MENU = array(
1001 'showPalettes' => '',
1002 'showDescriptions' => '',
1003 'disableRTE' => ''
1004 );
1005 // Setting virtual document name
1006 $GLOBALS['SOBE']->MCONF['name'] = 'xMOD_alt_doc.php';
1007 // CLEANSE SETTINGS
1008 $GLOBALS['SOBE']->MOD_SETTINGS = t3lib_BEfunc::getModuleData(
1009 $GLOBALS['SOBE']->MOD_MENU,
1010 t3lib_div::_GP('SET'),
1011 $GLOBALS['SOBE']->MCONF['name']
1012 );
1013 // Create an instance of the document template object
1014 $GLOBALS['SOBE']->doc = t3lib_div::makeInstance('template');
1015 $GLOBALS['SOBE']->doc->backPath = $GLOBALS['BACK_PATH'];
1016 // Initialize TCEforms (rendering the forms)
1017 $GLOBALS['SOBE']->tceforms = t3lib_div::makeInstance('t3lib_TCEforms');
1018 $GLOBALS['SOBE']->tceforms->inline = $this;
1019 $GLOBALS['SOBE']->tceforms->RTEcounter = intval(array_shift($ajaxArguments));
1020 $GLOBALS['SOBE']->tceforms->initDefaultBEMode();
1021 $GLOBALS['SOBE']->tceforms->palettesCollapsed = !$GLOBALS['SOBE']->MOD_SETTINGS['showPalettes'];
1022 $GLOBALS['SOBE']->tceforms->disableRTE = $GLOBALS['SOBE']->MOD_SETTINGS['disableRTE'];
1023 $GLOBALS['SOBE']->tceforms->enableClickMenu = TRUE;
1024 $GLOBALS['SOBE']->tceforms->enableTabMenu = TRUE;
1025 // Clipboard is initialized:
1026 $GLOBALS['SOBE']->tceforms->clipObj = t3lib_div::makeInstance('t3lib_clipboard'); // Start clipboard
1027 $GLOBALS['SOBE']->tceforms->clipObj->initializeClipboard(); // Initialize - reads the clipboard content from the user session
1028 // Setting external variables:
1029 if ($GLOBALS['BE_USER']->uc['edit_showFieldHelp'] != 'text' && $GLOBALS['SOBE']->MOD_SETTINGS['showDescriptions']) {
1030 $GLOBALS['SOBE']->tceforms->edit_showFieldHelp = 'text';
1031 }
1032 }
1033
1034
1035 /**
1036 * Determines and sets several script calls to a JSON array, that would have been executed if processed in non-AJAX mode.
1037 *
1038 * @param array &$jsonArray: Reference of the array to be used for JSON
1039 * @param array $config: The configuration of the IRRE field of the parent record
1040 * @return void
1041 */
1042 protected function getCommonScriptCalls(&$jsonArray, $config) {
1043 // Add data that would have been added at the top of a regular TCEforms call:
1044 if ($headTags = $this->getHeadTags()) {
1045 $jsonArray['headData'] = $headTags;
1046 }
1047 // Add the JavaScript data that would have been added at the bottom of a regular TCEforms call:
1048 $jsonArray['scriptCall'][] = $this->fObj->JSbottom($this->fObj->formName, TRUE);
1049 // If script.aculo.us Sortable is used, update the Observer to know the record:
1050 if ($config['appearance']['useSortable']) {
1051 $jsonArray['scriptCall'][] = "inline.createDragAndDropSorting('" . $this->inlineNames['object'] . "_records');";
1052 }
1053 // if TCEforms has some JavaScript code to be executed, just do it
1054 if ($this->fObj->extJSCODE) {
1055 $jsonArray['scriptCall'][] = $this->fObj->extJSCODE;
1056 }
1057 }
1058
1059
1060 /**
1061 * Generates an error message that transferred as JSON for AJAX calls
1062 *
1063 * @param string $message: The error message to be shown
1064 * @return array The error message in a JSON array
1065 */
1066 protected function getErrorMessageForAJAX($message) {
1067 $jsonArray = array(
1068 'data' => $message,
1069 'scriptCall' => array(
1070 'alert("' . $message . '");'
1071 )
1072 );
1073 return $jsonArray;
1074 }
1075
1076
1077 /**
1078 * Handle AJAX calls to show a new inline-record of the given table.
1079 * Normally this method is never called from inside TYPO3. Always from outside by AJAX.
1080 *
1081 * @param string $domObjectId: The calling object in hierarchy, that requested a new record.
1082 * @param string $foreignUid: If set, the new record should be inserted after that one.
1083 * @return array An array to be used for JSON
1084 */
1085 function createNewRecord($domObjectId, $foreignUid = 0) {
1086 // the current table - for this table we should add/import records
1087 $current = $this->inlineStructure['unstable'];
1088 // the parent table - this table embeds the current table
1089 $parent = $this->getStructureLevel(-1);
1090 // get TCA 'config' of the parent table
1091 if (!$this->checkConfiguration($parent['config'])) {
1092 return $this->getErrorMessageForAJAX('Wrong configuration in table ' . $parent['table']);
1093 }
1094 $config = $parent['config'];
1095
1096 $collapseAll = (isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll']);
1097 $expandSingle = (isset($config['appearance']['expandSingle']) && $config['appearance']['expandSingle']);
1098
1099 // Put the current level also to the dynNestedStack of TCEforms:
1100 $this->fObj->pushToDynNestedStack('inline', $this->inlineNames['object']);
1101
1102 // dynamically create a new record using t3lib_transferData
1103 if (!$foreignUid || !t3lib_utility_Math::canBeInterpretedAsInteger($foreignUid) || $config['foreign_selector']) {
1104 $record = $this->getNewRecord($this->inlineFirstPid, $current['table']);
1105 // Set language of new child record to the language of the parent record:
1106 if ($config['localizationMode'] == 'select') {
1107 $parentRecord = $this->getRecord(0, $parent['table'], $parent['uid']);
1108 $parentLanguageField = $GLOBALS['TCA'][$parent['table']]['ctrl']['languageField'];
1109 $childLanguageField = $GLOBALS['TCA'][$current['table']]['ctrl']['languageField'];
1110 if ($parentRecord[$parentLanguageField] > 0) {
1111 $record[$childLanguageField] = $parentRecord[$parentLanguageField];
1112 }
1113 }
1114
1115 // dynamically import an existing record (this could be a call from a select box)
1116 } else {
1117 $record = $this->getRecord($this->inlineFirstPid, $current['table'], $foreignUid);
1118 }
1119
1120 // now there is a foreign_selector, so there is a new record on the intermediate table, but
1121 // this intermediate table holds a field, which is responsible for the foreign_selector, so
1122 // we have to set this field to the uid we get - or if none, to a new uid
1123 if ($config['foreign_selector'] && $foreignUid) {
1124 $selConfig = $this->getPossibleRecordsSelectorConfig($config, $config['foreign_selector']);
1125 // For a selector of type group/db, prepend the tablename (<tablename>_<uid>):
1126 $record[$config['foreign_selector']] = $selConfig['type'] != 'groupdb' ? '' : $selConfig['table'] . '_';
1127 $record[$config['foreign_selector']] .= $foreignUid;
1128 }
1129
1130 // the HTML-object-id's prefix of the dynamically created record
1131 $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $current['table'];
1132 $objectId = $objectPrefix . self::Structure_Separator . $record['uid'];
1133
1134 // render the foreign record that should passed back to browser
1135 $item = $this->renderForeignRecord($parent['uid'], $record, $config);
1136 if ($item === FALSE) {
1137 return $this->getErrorMessageForAJAX('Access denied');
1138 }
1139
1140 if (!$current['uid']) {
1141 $jsonArray = array(
1142 'data' => $item,
1143 'scriptCall' => array(
1144 "inline.domAddNewRecord('bottom','" . $this->inlineNames['object'] . "_records','$objectPrefix',json.data);",
1145 "inline.memorizeAddRecord('$objectPrefix','" . $record['uid'] . "',null,'$foreignUid');"
1146 )
1147 );
1148
1149 // append the HTML data after an existing record in the container
1150 } else {
1151 $jsonArray = array(
1152 'data' => $item,
1153 'scriptCall' => array(
1154 "inline.domAddNewRecord('after','" . $domObjectId . '_div' . "','$objectPrefix',json.data);",
1155 "inline.memorizeAddRecord('$objectPrefix','" . $record['uid'] . "','" . $current['uid'] . "','$foreignUid');"
1156 )
1157 );
1158 }
1159 $this->getCommonScriptCalls($jsonArray, $config);
1160 // Collapse all other records if requested:
1161 if (!$collapseAll && $expandSingle) {
1162 $jsonArray['scriptCall'][] = "inline.collapseAllRecords('$objectId', '$objectPrefix', '" . $record['uid'] . "');";
1163 }
1164 // tell the browser to scroll to the newly created record
1165 $jsonArray['scriptCall'][] = "Element.scrollTo('" . $objectId . "_div');";
1166 // fade out and fade in the new record in the browser view to catch the user's eye
1167 $jsonArray['scriptCall'][] = "inline.fadeOutFadeIn('" . $objectId . "_div');";
1168
1169 // Remove the current level also from the dynNestedStack of TCEforms:
1170 $this->fObj->popFromDynNestedStack();
1171
1172 // Return the JSON array:
1173 return $jsonArray;
1174 }
1175
1176
1177 /**
1178 * Handle AJAX calls to localize all records of a parent, localize a single record or to synchronize with the original language parent.
1179 *
1180 * @param string $domObjectId: The calling object in hierarchy, that requested a new record.
1181 * @param mixed $type: Defines the type 'localize' or 'synchronize' (string) or a single uid to be localized (integer)
1182 * @return array An array to be used for JSON
1183 */
1184 protected function synchronizeLocalizeRecords($domObjectId, $type) {
1185 $jsonArray = FALSE;
1186 if (t3lib_div::inList('localize,synchronize', $type) || t3lib_utility_Math::canBeInterpretedAsInteger($type)) {
1187 // The current level:
1188 $current = $this->inlineStructure['unstable'];
1189 // The parent level:
1190 $parent = $this->getStructureLevel(-1);
1191 $parentRecord = $this->getRecord(0, $parent['table'], $parent['uid']);
1192
1193 $cmd = array();
1194 $cmd[$parent['table']][$parent['uid']]['inlineLocalizeSynchronize'] = $parent['field'] . ',' . $type;
1195
1196 /* @var t3lib_TCEmain */
1197 $tce = t3lib_div::makeInstance('t3lib_TCEmain');
1198 $tce->stripslashes_values = FALSE;
1199 $tce->start(array(), $cmd);
1200 $tce->process_cmdmap();
1201 $newItemList = $tce->registerDBList[$parent['table']][$parent['uid']][$parent['field']];
1202 unset($tce);
1203
1204 $jsonArray = $this->getExecuteChangesJsonArray($parentRecord[$parent['field']], $newItemList);
1205 $this->getCommonScriptCalls($jsonArray, $parent['config']);
1206 }
1207 return $jsonArray;
1208 }
1209
1210 /**
1211 * Handle AJAX calls to dynamically load the form fields of a given record.
1212 * (basically a copy of "createNewRecord")
1213 * Normally this method is never called from inside TYPO3. Always from outside by AJAX.
1214 *
1215 * @param string $domObjectId: The calling object in hierarchy, that requested a new record.
1216 * @return array An array to be used for JSON
1217 */
1218 function getRecordDetails($domObjectId) {
1219 // the current table - for this table we should add/import records
1220 $current = $this->inlineStructure['unstable'];
1221 // the parent table - this table embeds the current table
1222 $parent = $this->getStructureLevel(-1);
1223 // get TCA 'config' of the parent table
1224 if (!$this->checkConfiguration($parent['config'])) {
1225 return $this->getErrorMessageForAJAX('Wrong configuration in table ' . $parent['table']);
1226 }
1227 $config = $parent['config'];
1228 // set flag in config so that only the fields are rendered
1229 $config['renderFieldsOnly'] = TRUE;
1230
1231 $collapseAll = (isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll']);
1232 $expandSingle = (isset($config['appearance']['expandSingle']) && $config['appearance']['expandSingle']);
1233
1234 // Put the current level also to the dynNestedStack of TCEforms:
1235 $this->fObj->pushToDynNestedStack('inline', $this->inlineNames['object']);
1236
1237 $record = $this->getRecord($this->inlineFirstPid, $current['table'], $current['uid']);
1238
1239 // the HTML-object-id's prefix of the dynamically created record
1240 $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $current['table'];
1241 $objectId = $objectPrefix . self::Structure_Separator . $record['uid'];
1242
1243 $item = $this->renderForeignRecord($parent['uid'], $record, $config);
1244 if ($item === FALSE) {
1245 return $this->getErrorMessageForAJAX('Access denied');
1246 }
1247
1248 $jsonArray = array(
1249 'data' => $item,
1250 'scriptCall' => array(
1251 'inline.domAddRecordDetails(\'' . $domObjectId . '\',\'' . $objectPrefix . '\',' . ($expandSingle ? '1' : '0') . ',json.data);',
1252 )
1253 );
1254 if ($config['foreign_unique']) {
1255 $jsonArray['scriptCall'][] = 'inline.removeUsed(\'' . $objectPrefix . '\',\'' . $record['uid'] . '\');';
1256 }
1257 $this->getCommonScriptCalls($jsonArray, $config);
1258 // Collapse all other records if requested:
1259 if (!$collapseAll && $expandSingle) {
1260 $jsonArray['scriptCall'][] = 'inline.collapseAllRecords(\'' . $objectId . '\',\'' . $objectPrefix . '\',\'' . $record['uid'] . '\');';
1261 }
1262
1263 // Remove the current level also from the dynNestedStack of TCEforms:
1264 $this->fObj->popFromDynNestedStack();
1265
1266 // Return the JSON array:
1267 return $jsonArray;
1268 }
1269
1270
1271 /**
1272 * Generates a JSON array which executes the changes and thus updates the forms view.
1273 *
1274 * @param string $oldItemList: List of related child reocrds before changes were made (old)
1275 * @param string $newItemList: List of related child records after changes where made (new)
1276 * @return array An array to be used for JSON
1277 */
1278 protected function getExecuteChangesJsonArray($oldItemList, $newItemList) {
1279 $data = '';
1280 $parent = $this->getStructureLevel(-1);
1281 $current = $this->inlineStructure['unstable'];
1282
1283 $jsonArray = array('scriptCall' => array());
1284 $jsonArrayScriptCall =& $jsonArray['scriptCall'];
1285
1286 $nameObject = $this->inlineNames['object'];
1287 $nameObjectForeignTable = $nameObject . self::Structure_Separator . $current['table'];
1288 // Get the name of the field pointing to the original record:
1289 $transOrigPointerField = $GLOBALS['TCA'][$current['table']]['ctrl']['transOrigPointerField'];
1290 // Get the name of the field used as foreign selector (if any):
1291 $foreignSelector = (isset($parent['config']['foreign_selector']) && $parent['config']['foreign_selector'] ? $parent['config']['foreign_selector'] : FALSE);
1292 // Convert lists to array with uids of child records:
1293 $oldItems = $this->getRelatedRecordsUidArray($oldItemList);
1294 $newItems = $this->getRelatedRecordsUidArray($newItemList);
1295 // Determine the items that were localized or localized:
1296 $removedItems = array_diff($oldItems, $newItems);
1297 $localizedItems = array_diff($newItems, $oldItems);
1298 // Set the items that should be removed in the forms view:
1299 foreach ($removedItems as $item) {
1300 $jsonArrayScriptCall[] = "inline.deleteRecord('" . $nameObjectForeignTable . self::Structure_Separator . $item . "', {forceDirectRemoval: true});";
1301 }
1302 // Set the items that should be added in the forms view:
1303 foreach ($localizedItems as $item) {
1304 $row = $this->getRecord($this->inlineFirstPid, $current['table'], $item);
1305 $selectedValue = ($foreignSelector ? "'" . $row[$foreignSelector] . "'" : 'null');
1306 $data .= $this->renderForeignRecord($parent['uid'], $row, $parent['config']);
1307 $jsonArrayScriptCall[] = "inline.memorizeAddRecord('$nameObjectForeignTable', '" . $item . "', null, $selectedValue);";
1308 // Remove possible virtual records in the form which showed that a child records could be localized:
1309 if (isset($row[$transOrigPointerField]) && $row[$transOrigPointerField]) {
1310 $jsonArrayScriptCall[] = "inline.fadeAndRemove('" . $nameObjectForeignTable . self::Structure_Separator . $row[$transOrigPointerField] . '_div' . "');";
1311 }
1312 }
1313 if ($data) {
1314 $jsonArray['data'] = $data;
1315 array_unshift(
1316 $jsonArrayScriptCall,
1317 "inline.domAddNewRecord('bottom', '" . $nameObject . "_records', '$nameObjectForeignTable', json.data);"
1318 );
1319 }
1320
1321 return $jsonArray;
1322 }
1323
1324
1325 /**
1326 * Save the expanded/collapsed state of a child record in the BE_USER->uc.
1327 *
1328 * @param string $domObjectId: The calling object in hierarchy, that requested a new record.
1329 * @param string $expand: Whether this record is expanded.
1330 * @param string $collapse: Whether this record is collapsed.
1331 * @return void
1332 */
1333 function setExpandedCollapsedState($domObjectId, $expand, $collapse) {
1334 // parse the DOM identifier (string), add the levels to the structure stack (array), but don't load TCA config
1335 $this->parseStructureString($domObjectId, FALSE);
1336 // the current table - for this table we should add/import records
1337 $current = $this->inlineStructure['unstable'];
1338 // the top parent table - this table embeds the current table
1339 $top = $this->getStructureLevel(0);
1340
1341 // only do some action if the top record and the current record were saved before
1342 if (t3lib_utility_Math::canBeInterpretedAsInteger($top['uid'])) {
1343 $inlineView = (array) unserialize($GLOBALS['BE_USER']->uc['inlineView']);
1344 $inlineViewCurrent =& $inlineView[$top['table']][$top['uid']];
1345
1346 $expandUids = t3lib_div::trimExplode(',', $expand);
1347 $collapseUids = t3lib_div::trimExplode(',', $collapse);
1348
1349 // set records to be expanded
1350 foreach ($expandUids as $uid) {
1351 $inlineViewCurrent[$current['table']][] = $uid;
1352 }
1353 // set records to be collapsed
1354 foreach ($collapseUids as $uid) {
1355 $inlineViewCurrent[$current['table']] = $this->removeFromArray($uid, $inlineViewCurrent[$current['table']]);
1356 }
1357
1358 // save states back to database
1359 if (is_array($inlineViewCurrent[$current['table']])) {
1360 $inlineViewCurrent[$current['table']] = array_unique($inlineViewCurrent[$current['table']]);
1361 $GLOBALS['BE_USER']->uc['inlineView'] = serialize($inlineView);
1362 $GLOBALS['BE_USER']->writeUC();
1363 }
1364 }
1365 }
1366
1367
1368 /*******************************************************
1369 *
1370 * Get data from database and handle relations
1371 *
1372 *******************************************************/
1373
1374
1375 /**
1376 * Get the related records of the embedding item, this could be 1:n, m:n.
1377 * Returns an associative array with the keys records and count. 'count' contains only real existing records on the current parent record.
1378 *
1379 * @param string $table: The table name of the record
1380 * @param string $field: The field name which this element is supposed to edit
1381 * @param array $row: The record data array where the value(s) for the field can be found
1382 * @param array $PA: An array with additional configuration options.
1383 * @param array $config: (Redundant) content of $PA['fieldConf']['config'] (for convenience)
1384 * @return array The records related to the parent item as associative array.
1385 */
1386 function getRelatedRecords($table, $field, $row, &$PA, $config) {
1387 $records = array();
1388 $pid = $row['pid'];
1389 $elements = $PA['itemFormElValue'];
1390 $foreignTable = $config['foreign_table'];
1391
1392 $localizationMode = t3lib_BEfunc::getInlineLocalizationMode($table, $config);
1393
1394 if ($localizationMode != FALSE) {
1395 $language = intval($row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
1396 $transOrigPointer = intval($row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]);
1397 if ($language > 0 && $transOrigPointer) {
1398 // Localization in mode 'keep', isn't a real localization, but keeps the children of the original parent record:
1399 if ($localizationMode == 'keep') {
1400 $transOrigRec = $this->getRecord(0, $table, $transOrigPointer);
1401 $elements = $transOrigRec[$field];
1402 $pid = $transOrigRec['pid'];
1403 // Localization in modes 'select', 'all' or 'sync' offer a dynamic localization and synchronization with the original language record:
1404 } elseif ($localizationMode == 'select') {
1405 $transOrigRec = $this->getRecord(0, $table, $transOrigPointer);
1406 $pid = $transOrigRec['pid'];
1407 $recordsOriginal = $this->getRelatedRecordsArray($pid, $foreignTable, $transOrigRec[$field]);
1408 }
1409 }
1410 }
1411
1412 $records = $this->getRelatedRecordsArray($pid, $foreignTable, $elements);
1413 $relatedRecords = array('records' => $records, 'count' => count($records));
1414
1415 // Merge original language with current localization and show differences:
1416 if (is_array($recordsOriginal)) {
1417 $options = array(
1418 'showPossible' => (isset($config['appearance']['showPossibleLocalizationRecords']) && $config['appearance']['showPossibleLocalizationRecords']),
1419 'showRemoved' => (isset($config['appearance']['showRemovedLocalizationRecords']) && $config['appearance']['showRemovedLocalizationRecords']),
1420 );
1421 if ($options['showPossible'] || $options['showRemoved']) {
1422 $relatedRecords['records'] = $this->getLocalizationDifferences($foreignTable, $options, $recordsOriginal, $records);
1423 }
1424 }
1425
1426 return $relatedRecords;
1427 }
1428
1429
1430 /**
1431 * Gets the related records of the embedding item, this could be 1:n, m:n.
1432 *
1433 * @param integer $pid: The pid of the parent record
1434 * @param string $table: The table name of the record
1435 * @param string $itemList: The list of related child records
1436 * @return array The records related to the parent item
1437 */
1438 protected function getRelatedRecordsArray($pid, $table, $itemList) {
1439 $records = array();
1440 $itemArray = $this->getRelatedRecordsUidArray($itemList);
1441 // Perform modification of the selected items array:
1442 foreach ($itemArray as $uid) {
1443 // Get the records for this uid using t3lib_transferdata:
1444 if ($record = $this->getRecord($pid, $table, $uid)) {
1445 $records[$uid] = $record;
1446 }
1447 }
1448 return $records;
1449 }
1450
1451
1452 /**
1453 * Gets an array with the uids of related records out of a list of items.
1454 * This list could contain more information than required. This methods just
1455 * extracts the uids.
1456 *
1457 * @param string $itemList: The list of related child records
1458 * @return array An array with uids
1459 */
1460 protected function getRelatedRecordsUidArray($itemList) {
1461 $itemArray = t3lib_div::trimExplode(',', $itemList, 1);
1462 // Perform modification of the selected items array:
1463 foreach ($itemArray as $key => &$value) {
1464 $parts = explode('|', $value, 2);
1465 $value = $parts[0];
1466 }
1467 unset($value);
1468 return $itemArray;
1469 }
1470
1471
1472 /**
1473 * Gets the difference between current localized structure and the original language structure.
1474 * If there are records which once were localized but don't exist in the original version anymore, the record row is marked with '__remove'.
1475 * If there are records which can be localized and exist only in the original version, the record row is marked with '__create' and '__virtual'.
1476 *
1477 * @param string $table: The table name of the parent records
1478 * @param array $options: Options defining what kind of records to display
1479 * @param array $recordsOriginal: The uids of the child records of the original language
1480 * @param array $recordsLocalization: The uids of the child records of the current localization
1481 * @return array Merged array of uids of the child records of both versions
1482 */
1483 protected function getLocalizationDifferences($table, array $options, array $recordsOriginal, array $recordsLocalization) {
1484 $records = array();
1485 $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
1486 // Compare original to localized version of the records:
1487 foreach ($recordsLocalization as $uid => $row) {
1488 // If the record points to a original translation which doesn't exist anymore, it could be removed:
1489 if (isset($row[$transOrigPointerField]) && $row[$transOrigPointerField] > 0) {
1490 $transOrigPointer = $row[$transOrigPointerField];
1491 if (isset($recordsOriginal[$transOrigPointer])) {
1492 unset($recordsOriginal[$transOrigPointer]);
1493 } elseif ($options['showRemoved']) {
1494 $row['__remove'] = TRUE;
1495 }
1496 }
1497 $records[$uid] = $row;
1498 }
1499 // Process the remaining records in the original unlocalized parent:
1500 if ($options['showPossible']) {
1501 foreach ($recordsOriginal as $uid => $row) {
1502 $row['__create'] = TRUE;
1503 $row['__virtual'] = TRUE;
1504 $records[$uid] = $row;
1505 }
1506 }
1507 return $records;
1508 }
1509
1510
1511 /**
1512 * Get possible records.
1513 * Copied from TCEform and modified.
1514 *
1515 * @param string The table name of the record
1516 * @param string The field name which this element is supposed to edit
1517 * @param array The record data array where the value(s) for the field can be found
1518 * @param array An array with additional configuration options.
1519 * @param string $checkForConfField: For which field in the foreign_table the possible records should be fetched
1520 * @return mixed Array of possible record items; FALSE if type is "group/db", then everything could be "possible"
1521 */
1522 function getPossibleRecords($table, $field, $row, $conf, $checkForConfField = 'foreign_selector') {
1523 // ctrl configuration from TCA:
1524 $tcaTableCtrl = $GLOBALS['TCA'][$table]['ctrl'];
1525 // Field configuration from TCA:
1526 $foreign_table = $conf['foreign_table'];
1527 $foreign_check = $conf[$checkForConfField];
1528
1529 $foreignConfig = $this->getPossibleRecordsSelectorConfig($conf, $foreign_check);
1530 $PA = $foreignConfig['PA'];
1531 $config = $PA['fieldConf']['config'];
1532
1533 if ($foreignConfig['type'] == 'select') {
1534 // Getting the selector box items from the system
1535 $selItems = $this->fObj->addSelectOptionsToItemArray(
1536 $this->fObj->initItemArray($PA['fieldConf']),
1537 $PA['fieldConf'],
1538 $this->fObj->setTSconfig($table, $row),
1539 $field
1540 );
1541 // Possibly filter some items:
1542 $keepItemsFunc = create_function('$value', 'return $value[1];');
1543 $selItems = t3lib_div::keepItemsInArray($selItems, $PA['fieldTSConfig']['keepItems'], $keepItemsFunc);
1544 // Possibly add some items:
1545 $selItems = $this->fObj->addItems($selItems, $PA['fieldTSConfig']['addItems.']);
1546 if (isset($config['itemsProcFunc']) && $config['itemsProcFunc']) {
1547 $selItems = $this->fObj->procItems($selItems, $PA['fieldTSConfig']['itemsProcFunc.'], $config, $table, $row, $field);
1548 }
1549
1550 // Possibly remove some items:
1551 $removeItems = t3lib_div::trimExplode(',', $PA['fieldTSConfig']['removeItems'], 1);
1552 foreach ($selItems as $tk => $p) {
1553
1554 // Checking languages and authMode:
1555 $languageDeny = $tcaTableCtrl['languageField'] && !strcmp($tcaTableCtrl['languageField'], $field) && !$GLOBALS['BE_USER']->checkLanguageAccess($p[1]);
1556 $authModeDeny = $config['form_type'] == 'select' && $config['authMode'] && !$GLOBALS['BE_USER']->checkAuthMode($table, $field, $p[1], $config['authMode']);
1557 if (in_array($p[1], $removeItems) || $languageDeny || $authModeDeny) {
1558 unset($selItems[$tk]);
1559 } elseif (isset($PA['fieldTSConfig']['altLabels.'][$p[1]])) {
1560 $selItems[$tk][0] = $this->fObj->sL($PA['fieldTSConfig']['altLabels.'][$p[1]]);
1561 }
1562
1563 // Removing doktypes with no access:
1564 if (($table === 'pages' || $table === 'pages_language_overlay') && $field === 'doktype') {
1565 if (!($GLOBALS['BE_USER']->isAdmin() || t3lib_div::inList($GLOBALS['BE_USER']->groupData['pagetypes_select'], $p[1]))) {
1566 unset($selItems[$tk]);
1567 }
1568 }
1569 }
1570 } else {
1571 $selItems = FALSE;
1572 }
1573
1574 return $selItems;
1575 }
1576
1577 /**
1578 * Gets the uids of a select/selector that should be unique an have already been used.
1579 *
1580 * @param array $records: All inline records on this level
1581 * @param array $conf: The TCA field configuration of the inline field to be rendered
1582 * @param boolean $splitValue: for usage with group/db, values come like "tx_table_123|Title%20abc", but we need "tx_table" and "123"
1583 * @return array The uids, that have been used already and should be used unique
1584 */
1585 function getUniqueIds($records, $conf = array(), $splitValue = FALSE) {
1586 $uniqueIds = array();
1587
1588 if (isset($conf['foreign_unique']) && $conf['foreign_unique'] && count($records)) {
1589 foreach ($records as $rec) {
1590 // Skip virtual records (e.g. shown in localization mode):
1591 if (!isset($rec['__virtual']) || !$rec['__virtual']) {
1592 $value = $rec[$conf['foreign_unique']];
1593 // Split the value and extract the table and uid:
1594 if ($splitValue) {
1595 $valueParts = t3lib_div::trimExplode('|', $value);
1596 $itemParts = explode('_', $valueParts[0]);
1597 $value = array(
1598 'uid' => array_pop($itemParts),
1599 'table' => implode('_', $itemParts)
1600 );
1601 }
1602 $uniqueIds[$rec['uid']] = $value;
1603 }
1604 }
1605 }
1606
1607 return $uniqueIds;
1608 }
1609
1610
1611 /**
1612 * Determines the corrected pid to be used for a new record.
1613 * The pid to be used can be defined by a Page TSconfig.
1614 *
1615 * @param string $table: The table name
1616 * @param integer $parentPid: The pid of the parent record
1617 * @return integer The corrected pid to be used for a new record
1618 */
1619 protected function getNewRecordPid($table, $parentPid = NULL) {
1620 $newRecordPid = $this->inlineFirstPid;
1621 $pageTS = t3lib_beFunc::getPagesTSconfig($parentPid, TRUE);
1622 if (isset($pageTS['TCAdefaults.'][$table . '.']['pid']) && t3lib_utility_Math::canBeInterpretedAsInteger($pageTS['TCAdefaults.'][$table . '.']['pid'])) {
1623 $newRecordPid = $pageTS['TCAdefaults.'][$table . '.']['pid'];
1624 } elseif (isset($parentPid) && t3lib_utility_Math::canBeInterpretedAsInteger($parentPid)) {
1625 $newRecordPid = $parentPid;
1626 }
1627 return $newRecordPid;
1628 }
1629
1630
1631 /**
1632 * Get a single record row for a TCA table from the database.
1633 * t3lib_transferData is used for "upgrading" the values, especially the relations.
1634 *
1635 * @param integer $pid: The pid of the page the record should be stored (only relevant for NEW records)
1636 * @param string $table: The table to fetch data from (= foreign_table)
1637 * @param string $uid: The uid of the record to fetch, or the pid if a new record should be created
1638 * @param string $cmd: The command to perform, empty or 'new'
1639 * @return array A record row from the database post-processed by t3lib_transferData
1640 */
1641 function getRecord($pid, $table, $uid, $cmd = '') {
1642 // Fetch workspace version of a record (if any):
1643 if ($cmd !== 'new' && $GLOBALS['BE_USER']->workspace !== 0) {
1644 $workspaceVersion = t3lib_BEfunc::getWorkspaceVersionOfRecord($GLOBALS['BE_USER']->workspace, $table, $uid, 'uid');
1645 if ($workspaceVersion !== FALSE) {
1646 $uid = $workspaceVersion['uid'];
1647 }
1648 }
1649
1650 $trData = t3lib_div::makeInstance('t3lib_transferData');
1651 $trData->addRawData = TRUE;
1652 $trData->lockRecords = 1;
1653 $trData->disableRTE = $GLOBALS['SOBE']->MOD_SETTINGS['disableRTE'];
1654 // if a new record should be created
1655 $trData->fetchRecord($table, $uid, ($cmd === 'new' ? 'new' : ''));
1656 $rec = reset($trData->regTableItems_data);
1657
1658 return $rec;
1659 }
1660
1661
1662 /**
1663 * Wrapper. Calls getRecord in case of a new record should be created.
1664 *
1665 * @param integer $pid: The pid of the page the record should be stored (only relevant for NEW records)
1666 * @param string $table: The table to fetch data from (= foreign_table)
1667 * @return array A record row from the database post-processed by t3lib_transferData
1668 */
1669 function getNewRecord($pid, $table) {
1670 $rec = $this->getRecord($pid, $table, $pid, 'new');
1671 $rec['uid'] = uniqid('NEW');
1672 $rec['pid'] = $this->getNewRecordPid($table, $pid);
1673 return $rec;
1674 }
1675
1676
1677 /*******************************************************
1678 *
1679 * Structure stack for handling inline objects/levels
1680 *
1681 *******************************************************/
1682
1683
1684 /**
1685 * Add a new level on top of the structure stack. Other functions can access the
1686 * stack and determine, if there's possibly a endless loop.
1687 *
1688 * @param string $table: The table name of the record
1689 * @param string $uid: The uid of the record that embeds the inline data
1690 * @param string $field: The field name which this element is supposed to edit
1691 * @param array $config: The TCA-configuration of the inline field
1692 * @return void
1693 */
1694 function pushStructure($table, $uid, $field = '', $config = array()) {
1695 $this->inlineStructure['stable'][] = array(
1696 'table' => $table,
1697 'uid' => $uid,
1698 'field' => $field,
1699 'config' => $config,
1700 'localizationMode' => t3lib_BEfunc::getInlineLocalizationMode($table, $config),
1701 );
1702 $this->updateStructureNames();
1703 }
1704
1705
1706 /**
1707 * Remove the item on top of the structure stack and return it.
1708 *
1709 * @return array The top item of the structure stack - array(<table>,<uid>,<field>,<config>)
1710 */
1711 function popStructure() {
1712 if (count($this->inlineStructure['stable'])) {
1713 $popItem = array_pop($this->inlineStructure['stable']);
1714 $this->updateStructureNames();
1715 }
1716 return $popItem;
1717 }
1718
1719
1720 /**
1721 * For common use of DOM object-ids and form field names of a several inline-level,
1722 * these names/identifiers are preprocessed and set to $this->inlineNames.
1723 * This function is automatically called if a level is pushed to or removed from the
1724 * inline structure stack.
1725 *
1726 * @return void
1727 */
1728 function updateStructureNames() {
1729 $current = $this->getStructureLevel(-1);
1730 // if there are still more inline levels available
1731 if ($current !== FALSE) {
1732 $this->inlineNames = array(
1733 'form' => $this->prependFormFieldNames . $this->getStructureItemName($current, self::Disposal_AttributeName),
1734 'object' => $this->prependNaming . self::Structure_Separator . $this->inlineFirstPid . self::Structure_Separator . $this->getStructurePath(),
1735 );
1736 // if there are no more inline levels available
1737 } else {
1738 $this->inlineNames = array();
1739 }
1740 }
1741
1742
1743 /**
1744 * Create a name/id for usage in HTML output of a level of the structure stack to be used in form names.
1745 *
1746 * @param array $levelData: Array of a level of the structure stack (containing the keys table, uid and field)
1747 * @param string $disposal: How the structure name is used (e.g. as <div id="..."> or <input name="..." />)
1748 * @return string The name/id of that level, to be used for HTML output
1749 */
1750 function getStructureItemName($levelData, $disposal = self::Disposal_AttributeId) {
1751 if (is_array($levelData)) {
1752 $parts = array($levelData['table'], $levelData['uid']);
1753 if (isset($levelData['field'])) {
1754 $parts[] = $levelData['field'];
1755 }
1756
1757 // Use in name attributes:
1758 if ($disposal === self::Disposal_AttributeName) {
1759 $name = '[' . implode('][', $parts) . ']';
1760 // Use in id attributes:
1761 } else {
1762 $name = implode(self::Structure_Separator, $parts);
1763 }
1764 }
1765 return $name;
1766 }
1767
1768
1769 /**
1770 * Get a level from the stack and return the data.
1771 * If the $level value is negative, this function works top-down,
1772 * if the $level value is positive, this function works bottom-up.
1773 *
1774 * @param integer $level: Which level to return
1775 * @return array The item of the stack at the requested level
1776 */
1777 function getStructureLevel($level) {
1778 $inlineStructureCount = count($this->inlineStructure['stable']);
1779 if ($level < 0) {
1780 $level = $inlineStructureCount + $level;
1781 }
1782 if ($level >= 0 && $level < $inlineStructureCount) {
1783 return $this->inlineStructure['stable'][$level];
1784 }
1785 else
1786 {
1787 return FALSE;
1788 }
1789 }
1790
1791
1792 /**
1793 * Get the identifiers of a given depth of level, from the top of the stack to the bottom.
1794 * An identifier looks like "<table>-<uid>-<field>".
1795 *
1796 * @param integer $structureDepth: How much levels to output, beginning from the top of the stack
1797 * @return string The path of identifiers
1798 */
1799 function getStructurePath($structureDepth = -1) {
1800 $structureLevels = array();
1801 $structureCount = count($this->inlineStructure['stable']);
1802
1803 if ($structureDepth < 0 || $structureDepth > $structureCount) {
1804 $structureDepth = $structureCount;
1805 }
1806
1807 for ($i = 1; $i <= $structureDepth; $i++) {
1808 array_unshift(
1809 $structureLevels,
1810 $this->getStructureItemName(
1811 $this->getStructureLevel(-$i),
1812 self::Disposal_AttributeId
1813 )
1814 );
1815 }
1816
1817 return implode(self::Structure_Separator, $structureLevels);
1818 }
1819
1820
1821 /**
1822 * Convert the DOM object-id of an inline container to an array.
1823 * The object-id could look like 'data-parentPageId-tx_mmftest_company-1-employees'.
1824 * The result is written to $this->inlineStructure.
1825 * There are two keys:
1826 * - 'stable': Containing full qualified identifiers (table, uid and field)
1827 * - 'unstable': Containting partly filled data (e.g. only table and possibly field)
1828 *
1829 * @param string $domObjectId: The DOM object-id
1830 * @param boolean $loadConfig: Load the TCA configuration for that level (default: TRUE)
1831 * @return void
1832 */
1833 function parseStructureString($string, $loadConfig = TRUE) {
1834 $unstable = array();
1835 $vector = array('table', 'uid', 'field');
1836 $pattern = '/^' . $this->prependNaming . self::Structure_Separator . '(.+?)' . self::Structure_Separator . '(.+)$/';
1837 if (preg_match($pattern, $string, $match)) {
1838 $this->inlineFirstPid = $match[1];
1839 $parts = explode(self::Structure_Separator, $match[2]);
1840 $partsCnt = count($parts);
1841 for ($i = 0; $i < $partsCnt; $i++) {
1842 if ($i > 0 && $i % 3 == 0) {
1843 // load the TCA configuration of the table field and store it in the stack
1844 if ($loadConfig) {
1845 t3lib_div::loadTCA($unstable['table']);
1846 $unstable['config'] = $GLOBALS['TCA'][$unstable['table']]['columns'][$unstable['field']]['config'];
1847 // Fetch TSconfig:
1848 $TSconfig = $this->fObj->setTSconfig(
1849 $unstable['table'],
1850 array('uid' => $unstable['uid'], 'pid' => $this->inlineFirstPid),
1851 $unstable['field']
1852 );
1853 // Override TCA field config by TSconfig:
1854 if (!$TSconfig['disabled']) {
1855 $unstable['config'] = $this->fObj->overrideFieldConf($unstable['config'], $TSconfig);
1856 }
1857 $unstable['localizationMode'] = t3lib_BEfunc::getInlineLocalizationMode($unstable['table'], $unstable['config']);
1858 }
1859 $this->inlineStructure['stable'][] = $unstable;
1860 $unstable = array();
1861 }
1862 $unstable[$vector[$i % 3]] = $parts[$i];
1863 }
1864 $this->updateStructureNames();
1865 if (count($unstable)) {
1866 $this->inlineStructure['unstable'] = $unstable;
1867 }
1868 }
1869 }
1870
1871
1872 /*******************************************************
1873 *
1874 * Helper functions
1875 *
1876 *******************************************************/
1877
1878
1879 /**
1880 * Does some checks on the TCA configuration of the inline field to render.
1881 *
1882 * @param array $config: Reference to the TCA field configuration
1883 * @param string $table: The table name of the record
1884 * @param string $field: The field name which this element is supposed to edit
1885 * @param array $row: The record data array of the parent
1886 * @return boolean If critical configuration errors were found, FALSE is returned
1887 */
1888 function checkConfiguration(&$config) {
1889 $foreign_table = $config['foreign_table'];
1890
1891 // An inline field must have a foreign_table, if not, stop all further inline actions for this field:
1892 if (!$foreign_table || !is_array($GLOBALS['TCA'][$foreign_table])) {
1893 return FALSE;
1894 }
1895 // Init appearance if not set:
1896 if (!isset($config['appearance']) || !is_array($config['appearance'])) {
1897 $config['appearance'] = array();
1898 }
1899 // Set the position/appearance of the "Create new record" link:
1900 if (isset($config['foreign_selector']) && $config['foreign_selector'] && (!isset($config['appearance']['useCombination']) || !$config['appearance']['useCombination'])) {
1901 $config['appearance']['levelLinksPosition'] = 'none';
1902 } elseif (!isset($config['appearance']['levelLinksPosition']) || !in_array($config['appearance']['levelLinksPosition'], array('top', 'bottom', 'both', 'none'))) {
1903 $config['appearance']['levelLinksPosition'] = 'top';
1904 }
1905 // Defines which controls should be shown in header of each record:
1906 $enabledControls = array(
1907 'info' => TRUE,
1908 'new' => TRUE,
1909 'dragdrop' => TRUE,
1910 'sort' => TRUE,
1911 'hide' => TRUE,
1912 'delete' => TRUE,
1913 'localize' => TRUE,
1914 );
1915 if (isset($config['appearance']['enabledControls']) && is_array($config['appearance']['enabledControls'])) {
1916 $config['appearance']['enabledControls'] = array_merge($enabledControls, $config['appearance']['enabledControls']);
1917 } else {
1918 $config['appearance']['enabledControls'] = $enabledControls;
1919 }
1920
1921 return TRUE;
1922 }
1923
1924
1925 /**
1926 * Checks the page access rights (Code for access check mostly taken from alt_doc.php)
1927 * as well as the table access rights of the user.
1928 *
1929 * @param string $cmd: The command that sould be performed ('new' or 'edit')
1930 * @param string $table: The table to check access for
1931 * @param string $theUid: The record uid of the table
1932 * @return boolean Returns TRUE is the user has access, or FALSE if not
1933 */
1934 function checkAccess($cmd, $table, $theUid) {
1935 // Checking if the user has permissions? (Only working as a precaution, because the final permission check is always down in TCE. But it's good to notify the user on beforehand...)
1936 // First, resetting flags.
1937 $hasAccess = 0;
1938 $deniedAccessReason = '';
1939
1940 // Admin users always have acces:
1941 if ($GLOBALS['BE_USER']->isAdmin()) {
1942 return TRUE;
1943 }
1944 // If the command is to create a NEW record...:
1945 if ($cmd == 'new') {
1946 // If the pid is numerical, check if it's possible to write to this page:
1947 if (t3lib_utility_Math::canBeInterpretedAsInteger($this->inlineFirstPid)) {
1948 $calcPRec = t3lib_BEfunc::getRecord('pages', $this->inlineFirstPid);
1949 if (!is_array($calcPRec)) {
1950 return FALSE;
1951 }
1952 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec); // Permissions for the parent page
1953 if ($table == 'pages') { // If pages:
1954 $hasAccess = $CALC_PERMS & 8 ? 1 : 0; // Are we allowed to create new subpages?
1955 } else {
1956 $hasAccess = $CALC_PERMS & 16 ? 1 : 0; // Are we allowed to edit content on this page?
1957 }
1958 // If the pid is a NEW... value, the access will be checked on creating the page:
1959 // (if the page with the same NEW... value could be created in TCEmain, this child record can neither)
1960 } else {
1961 $hasAccess = 1;
1962 }
1963 } else { // Edit:
1964 $calcPRec = t3lib_BEfunc::getRecord($table, $theUid);
1965 t3lib_BEfunc::fixVersioningPid($table, $calcPRec);
1966 if (is_array($calcPRec)) {
1967 if ($table == 'pages') { // If pages:
1968 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
1969 $hasAccess = $CALC_PERMS & 2 ? 1 : 0;
1970 } else {
1971 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms(t3lib_BEfunc::getRecord('pages', $calcPRec['pid'])); // Fetching pid-record first.
1972 $hasAccess = $CALC_PERMS & 16 ? 1 : 0;
1973 }
1974
1975 // Check internals regarding access:
1976 if ($hasAccess) {
1977 $hasAccess = $GLOBALS['BE_USER']->recordEditAccessInternals($table, $calcPRec);
1978 }
1979 }
1980 }
1981
1982 if (!$GLOBALS['BE_USER']->check('tables_modify', $table)) {
1983 $hasAccess = 0;
1984 }
1985
1986 if (!$hasAccess) {
1987 $deniedAccessReason = $GLOBALS['BE_USER']->errorMsg;
1988 if ($deniedAccessReason) {
1989 debug($deniedAccessReason);
1990 }
1991 }
1992
1993 return $hasAccess ? TRUE : FALSE;
1994 }
1995
1996
1997 /**
1998 * Check the keys and values in the $compare array against the ['config'] part of the top level of the stack.
1999 * A boolean value is return depending on how the comparison was successful.
2000 *
2001 * @param array $compare: keys and values to compare to the ['config'] part of the top level of the stack
2002 * @return boolean Whether the comparison was successful
2003 * @see arrayCompareComplex
2004 */
2005 function compareStructureConfiguration($compare) {
2006 $level = $this->getStructureLevel(-1);
2007 $result = $this->arrayCompareComplex($level, $compare);
2008
2009 return $result;
2010 }
2011
2012
2013 /**
2014 * Normalize a relation "uid" published by transferData, like "1|Company%201"
2015 *
2016 * @param string $string: A transferData reference string, containing the uid
2017 * @return string The normalized uid
2018 */
2019 function normalizeUid($string) {
2020 $parts = explode('|', $string);
2021 return $parts[0];
2022 }
2023
2024
2025 /**
2026 * Wrap the HTML code of a section with a table tag.
2027 *
2028 * @param string $section: The HTML code to be wrapped
2029 * @param array $styleAttrs: Attributes for the style argument in the table tag
2030 * @param array $tableAttrs: Attributes for the table tag (like width, border, etc.)
2031 * @return string The wrapped HTML code
2032 */
2033 function wrapFormsSection($section, $styleAttrs = array(), $tableAttrs = array()) {
2034 $style = '';
2035 $table = '';
2036 if (!$styleAttrs['margin-right']) {
2037 $styleAttrs['margin-right'] = $this->inlineStyles['margin-right'] . 'px';
2038 }
2039
2040 foreach ($styleAttrs as $key => $value) {
2041 $style .= ($style ? ' ' : '') . $key . ': ' . htmlspecialchars($value) . '; ';
2042 }
2043 if ($style) {
2044 $style = ' style="' . $style . '"';
2045 }
2046
2047 if (!$tableAttrs['background'] && $this->fObj->borderStyle[2]) {
2048 $tableAttrs['background'] = $this->backPath . $this->borderStyle[2];
2049 }
2050 if (!$tableAttrs['cellspacing']) {
2051 $tableAttrs['cellspacing'] = '0';
2052 }
2053 if (!$tableAttrs['cellpadding']) {
2054 $tableAttrs['cellpadding'] = '0';
2055 }
2056 if (!$tableAttrs['border']) {
2057 $tableAttrs['border'] = '0';
2058 }
2059 if (!$tableAttrs['width']) {
2060 $tableAttrs['width'] = '100%';
2061 }
2062 if (!$tableAttrs['class'] && $this->borderStyle[3]) {
2063 $tableAttrs['class'] = $this->borderStyle[3];
2064 }
2065
2066 foreach ($tableAttrs as $key => $value) {
2067 $table .= ($table ? ' ' : '') . $key . '="' . htmlspecialchars($value) . '"';
2068 }
2069
2070 $out = '<table ' . $table . $style . '>' . $section . '</table>';
2071 return $out;
2072 }
2073
2074
2075 /**
2076 * Checks if the $table is the child of a inline type AND the $field is the label field of this table.
2077 * This function is used to dynamically update the label while editing. This has no effect on labels,
2078 * that were processed by a TCEmain-hook on saving.
2079 *
2080 * @param string $table: The table to check
2081 * @param string $field: The field on this table to check
2082 * @return boolean is inline child and field is responsible for the label
2083 */
2084 function isInlineChildAndLabelField($table, $field) {
2085 $level = $this->getStructureLevel(-1);
2086 if ($level['config']['foreign_label']) {
2087 $label = $level['config']['foreign_label'];
2088 }
2089 else
2090 {
2091 $label = $GLOBALS['TCA'][$table]['ctrl']['label'];
2092 }
2093 return $level['config']['foreign_table'] === $table && $label == $field ? TRUE : FALSE;
2094 }
2095
2096
2097 /**
2098 * Get the depth of the stable structure stack.
2099 * (count($this->inlineStructure['stable'])
2100 *
2101 * @return integer The depth of the structure stack
2102 */
2103 function getStructureDepth() {
2104 return count($this->inlineStructure['stable']);
2105 }
2106
2107
2108 /**
2109 * Handles complex comparison requests on an array.
2110 * A request could look like the following:
2111 *
2112 * $searchArray = array(
2113 * '%AND' => array(
2114 * 'key1' => 'value1',
2115 * 'key2' => 'value2',
2116 * '%OR' => array(
2117 * 'subarray' => array(
2118 * 'subkey' => 'subvalue'
2119 * ),
2120 * 'key3' => 'value3',
2121 * 'key4' => 'value4'
2122 * )
2123 * )
2124 * );
2125 *
2126 * It is possible to use the array keys '%AND.1', '%AND.2', etc. to prevent
2127 * overwriting the sub-array. It could be neccessary, if you use complex comparisons.
2128 *
2129 * The example above means, key1 *AND* key2 (and their values) have to match with
2130 * the $subjectArray and additional one *OR* key3 or key4 have to meet the same
2131 * condition.
2132 * It is also possible to compare parts of a sub-array (e.g. "subarray"), so this
2133 * function recurses down one level in that sub-array.
2134 *
2135 * @param array $subjectArray: The array to search in
2136 * @param array $searchArray: The array with keys and values to search for
2137 * @param string $type: Use '%AND' or '%OR' for comparision
2138 * @return boolean The result of the comparison
2139 */
2140 function arrayCompareComplex($subjectArray, $searchArray, $type = '') {
2141 $localMatches = 0;
2142 $localEntries = 0;
2143
2144 if (is_array($searchArray) && count($searchArray)) {
2145 // if no type was passed, try to determine
2146 if (!$type) {
2147 reset($searchArray);
2148 $type = key($searchArray);
2149 $searchArray = current($searchArray);
2150 }
2151
2152 // we use '%AND' and '%OR' in uppercase
2153 $type = strtoupper($type);
2154
2155 // split regular elements from sub elements
2156 foreach ($searchArray as $key => $value) {
2157 $localEntries++;
2158
2159 // process a sub-group of OR-conditions
2160 if ($key == '%OR') {
2161 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%OR') ? 1 : 0;
2162 // process a sub-group of AND-conditions
2163 } elseif ($key == '%AND') {
2164 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%AND') ? 1 : 0;
2165 // a part of an associative array should be compared, so step down in the array hierarchy
2166 } elseif (is_array($value) && $this->isAssociativeArray($searchArray)) {
2167 $localMatches += $this->arrayCompareComplex($subjectArray[$key], $value, $type) ? 1 : 0;
2168 // it is a normal array that is only used for grouping and indexing
2169 } elseif (is_array($value)) {
2170 $localMatches += $this->arrayCompareComplex($subjectArray, $value, $type) ? 1 : 0;
2171 // directly compare a value
2172 } else {
2173 if (isset($subjectArray[$key]) && isset($value)) {
2174 // Boolean match:
2175 if (is_bool($value)) {
2176 $localMatches += (!($subjectArray[$key] xor $value) ? 1 : 0);
2177 // Value match for numbers:
2178 } elseif (is_numeric($subjectArray[$key]) && is_numeric($value)) {
2179 $localMatches += ($subjectArray[$key] == $value ? 1 : 0);
2180 // Value and type match:
2181 } else {
2182 $localMatches += ($subjectArray[$key] === $value ? 1 : 0);
2183 }
2184 }
2185 }
2186
2187 // if one or more matches are required ('OR'), return TRUE after the first successful match
2188 if ($type == '%OR' && $localMatches > 0) {
2189 return TRUE;
2190 }
2191 // if all matches are required ('AND') and we have no result after the first run, return FALSE
2192 if ($type == '%AND' && $localMatches == 0) {
2193 return FALSE;
2194 }
2195 }
2196 }
2197
2198 // return the result for '%AND' (if nothing was checked, TRUE is returned)
2199 return $localEntries == $localMatches ? TRUE : FALSE;
2200 }
2201
2202
2203 /**
2204 * Checks whether an object is an associative array.
2205 *
2206 * @param mixed $object: The object to be checked
2207 * @return boolean Returns TRUE, if the object is an associative array
2208 */
2209 function isAssociativeArray($object) {
2210 return is_array($object) && count($object) && (array_keys($object) !== range(0, sizeof($object) - 1))
2211 ? TRUE
2212 : FALSE;
2213 }
2214
2215
2216 /**
2217 * Remove an element from an array.
2218 *
2219 * @param mixed $needle: The element to be removed.
2220 * @param array $haystack: The array the element should be removed from.
2221 * @param mixed $strict: Search elements strictly.
2222 * @return array The array $haystack without the $needle
2223 */
2224 function removeFromArray($needle, $haystack, $strict = NULL) {
2225 $pos = array_search($needle, $haystack, $strict);
2226 if ($pos !== FALSE) {
2227 unset($haystack[$pos]);
2228 }
2229 return $haystack;
2230 }
2231
2232
2233 /**
2234 * Makes a flat array from the $possibleRecords array.
2235 * The key of the flat array is the value of the record,
2236 * the value of the flat array is the label of the record.
2237 *
2238 * @param array $possibleRecords: The possibleRecords array (for select fields)
2239 * @return mixed A flat array with key=uid, value=label; if $possibleRecords isn't an array, FALSE is returned.
2240 */
2241 function getPossibleRecordsFlat($possibleRecords) {
2242 $flat = FALSE;
2243 if (is_array($possibleRecords)) {
2244 $flat = array();
2245 foreach ($possibleRecords as $record) $flat[$record[1]] = $record[0];
2246 }
2247 return $flat;
2248 }
2249
2250
2251 /**
2252 * Determine the configuration and the type of a record selector.
2253 *
2254 * @param array $conf: TCA configuration of the parent(!) field
2255 * @return array Associative array with the keys 'PA' and 'type', both are FALSE if the selector was not valid.
2256 */
2257 function getPossibleRecordsSelectorConfig($conf, $field = '') {
2258 $foreign_table = $conf['foreign_table'];
2259 $foreign_selector = $conf['foreign_selector'];
2260
2261 $PA = FALSE;
2262 $type = FALSE;
2263 $table = FALSE;
2264 $selector = FALSE;
2265
2266 if ($field) {
2267 $PA = array();
2268 $PA['fieldConf'] = $GLOBALS['TCA'][$foreign_table]['columns'][$field];
2269 $PA['fieldConf']['config']['form_type'] = $PA['fieldConf']['config']['form_type'] ? $PA['fieldConf']['config']['form_type'] : $PA['fieldConf']['config']['type']; // Using "form_type" locally in this script
2270 $PA['fieldTSConfig'] = $this->fObj->setTSconfig($foreign_table, array(), $field);
2271 $config = $PA['fieldConf']['config'];
2272 // Determine type of Selector:
2273 $type = $this->getPossibleRecordsSelectorType($config);
2274 // Return table on this level:
2275 $table = $type == 'select' ? $config['foreign_table'] : $config['allowed'];
2276 // Return type of the selector if foreign_selector is defined and points to the same field as in $field:
2277 if ($foreign_selector && $foreign_selector == $field && $type) {
2278 $selector = $type;
2279 }
2280 }
2281
2282 return array(
2283 'PA' => $PA,
2284 'type' => $type,
2285 'table' => $table,
2286 'selector' => $selector,
2287 );
2288 }
2289
2290
2291 /**
2292 * Determine the type of a record selector, e.g. select or group/db.
2293 *
2294 * @param array $config: TCE configuration of the selector
2295 * @return mixed The type of the selector, 'select' or 'groupdb' - FALSE not valid
2296 */
2297 function getPossibleRecordsSelectorType($config) {
2298 $type = FALSE;
2299 if ($config['type'] == 'select') {
2300 $type = 'select';
2301 } elseif ($config['type'] == 'group' && $config['internal_type'] == 'db') {
2302 $type = 'groupdb';
2303 }
2304 return $type;
2305 }
2306
2307
2308 /**
2309 * Check, if a field should be skipped, that was defined to be handled as foreign_field or foreign_sortby of
2310 * the parent record of the "inline"-type - if so, we have to skip this field - the rendering is done via "inline" as hidden field
2311 *
2312 * @param string $table: The table name
2313 * @param string $field: The field name
2314 * @param array $row: The record row from the database
2315 * @param array $config: TCA configuration of the field
2316 * @return boolean Determines whether the field should be skipped.
2317 */
2318 function skipField($table, $field, $row, $config) {
2319 $skipThisField = FALSE;
2320
2321 if ($this->getStructureDepth()) {
2322 $searchArray = array(
2323 '%OR' => array(
2324 'config' => array(
2325 0 => array(
2326 '%AND' => array(
2327 'foreign_table' => $table,
2328 '%OR' => array(
2329 '%AND' => array(
2330 'appearance' => array('useCombination' => TRUE),
2331 'foreign_selector' => $field,
2332 ),
2333 'MM' => $config['MM']
2334 ),
2335 ),
2336 ),
2337 1 => array(
2338 '%AND' => array(
2339 'foreign_table' => $config['foreign_table'],
2340 'foreign_selector' => $config['foreign_field'],
2341 ),
2342 ),
2343 ),
2344 ),
2345 );
2346
2347 // get the parent record from structure stack
2348 $level = $this->getStructureLevel(-1);
2349
2350 // If we have symmetric fields, check on which side we are and hide fields, that are set automatically:
2351 if (t3lib_loadDBGroup::isOnSymmetricSide($level['uid'], $level['config'], $row)) {
2352 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_field'] = $field;
2353 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_sortby'] = $field;
2354 // Hide fields, that are set automatically:
2355 } else {
2356 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_field'] = $field;
2357 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_sortby'] = $field;
2358 }
2359
2360 $skipThisField = $this->compareStructureConfiguration($searchArray, TRUE);
2361 }
2362
2363 return $skipThisField;
2364 }
2365
2366
2367 /**
2368 * Checks if a uid of a child table is in the inline view settings.
2369 *
2370 * @param string $table: Name of the child table
2371 * @param integer $uid: uid of the the child record
2372 * @return boolean TRUE=expand, FALSE=collapse
2373 */
2374 function getExpandedCollapsedState($table, $uid) {
2375 if (isset($this->inlineView[$table]) && is_array($this->inlineView[$table])) {
2376 if (in_array($uid, $this->inlineView[$table]) !== FALSE) {
2377 return TRUE;
2378 }
2379 }
2380 return FALSE;
2381 }
2382
2383
2384 /**
2385 * Update expanded/collapsed states on new inline records if any.
2386 *
2387 * @param array $uc: The uc array to be processed and saved (by reference)
2388 * @param t3lib_TCEmain $tce: Instance of TCEmain that saved data before
2389 * @return void
2390 */
2391 function updateInlineView(&$uc, $tce) {
2392 if (isset($uc['inlineView']) && is_array($uc['inlineView'])) {
2393 $inlineView = (array) unserialize($GLOBALS['BE_USER']->uc['inlineView']);
2394
2395 foreach ($uc['inlineView'] as $topTable => $topRecords) {
2396 foreach ($topRecords as $topUid => $childElements) {
2397 foreach ($childElements as $childTable => $childRecords) {
2398 $uids = array_keys($tce->substNEWwithIDs_table, $childTable);
2399 if (count($uids)) {
2400 $newExpandedChildren = array();
2401 foreach ($childRecords as $childUid => $state) {
2402 if ($state && in_array($childUid, $uids)) {
2403 $newChildUid = $tce->substNEWwithIDs[$childUid];
2404 $newExpandedChildren[] = $newChildUid;
2405 }
2406 }
2407 // Add new expanded child records to UC (if any):
2408 if (count($newExpandedChildren)) {
2409 $inlineViewCurrent =& $inlineView[$topTable][$topUid][$childTable];
2410 if (is_array($inlineViewCurrent)) {
2411 $inlineViewCurrent = array_unique(array_merge($inlineViewCurrent, $newExpandedChildren));
2412 } else {
2413 $inlineViewCurrent = $newExpandedChildren;
2414 }
2415 }
2416 }
2417 }
2418 }
2419 }
2420
2421 $GLOBALS['BE_USER']->uc['inlineView'] = serialize($inlineView);
2422 $GLOBALS['BE_USER']->writeUC();
2423 }
2424 }
2425
2426
2427 /**
2428 * Returns the the margin in pixels, that is used for each new inline level.
2429 *
2430 * @return integer A pixel value for the margin of each new inline level.
2431 */
2432 function getLevelMargin() {
2433 $margin = ($this->inlineStyles['margin-right'] + 1) * 2;
2434 return $margin;
2435 }
2436
2437 /**
2438 * Parses the HTML tags that would have been inserted to the <head> of a HTML document and returns the found tags as multidimensional array.
2439 *
2440 * @return array The parsed tags with their attributes and innerHTML parts
2441 */
2442 protected function getHeadTags() {
2443 $headTags = array();
2444 $headDataRaw = $this->fObj->JStop() . $this->getJavaScriptAndStyleSheetsOfPageRenderer();
2445
2446 if ($headDataRaw) {
2447 // Create instance of the HTML parser:
2448 $parseObj = t3lib_div::makeInstance('t3lib_parsehtml');
2449 // Removes script wraps:
2450 $headDataRaw = str_replace(array('/*<![CDATA[*/', '/*]]>*/'), '', $headDataRaw);
2451 // Removes leading spaces of a multiline string:
2452 $headDataRaw = trim(preg_replace('/(^|\r|\n)( |\t)+/', '$1', $headDataRaw));
2453 // Get script and link tags:
2454 $tags = array_merge(
2455 $parseObj->getAllParts($parseObj->splitTags('link', $headDataRaw)),
2456 $parseObj->getAllParts($parseObj->splitIntoBlock('script', $headDataRaw))
2457 );
2458
2459 foreach ($tags as $tagData) {
2460 $tagAttributes = $parseObj->get_tag_attributes($parseObj->getFirstTag($tagData), TRUE);
2461 $headTags[] = array(
2462 'name' => $parseObj->getFirstTagName($tagData),
2463 'attributes' => $tagAttributes[0],
2464 'innerHTML' => $parseObj->removeFirstAndLastTag($tagData),
2465 );
2466 }
2467 }
2468
2469 return $headTags;
2470 }
2471
2472 /**
2473 * Gets the JavaScript of the pageRenderer.
2474 * This can be used to extract newly added files which have been added
2475 * during an AJAX request. Due to the spread possibilities of the pageRenderer
2476 * to add JavaScript rendering and extracting seems to be the easiest way.
2477 *
2478 * @return string
2479 */
2480 protected function getJavaScriptAndStyleSheetsOfPageRenderer() {
2481 /** @var $pageRenderer t3lib_PageRenderer */
2482 $pageRenderer = clone $GLOBALS['SOBE']->doc->getPageRenderer();
2483
2484 $pageRenderer->setTemplateFile(TYPO3_mainDir . 'templates/helper_javascript_css.html');
2485 $javaScriptAndStyleSheets = $pageRenderer->render();
2486
2487 return $javaScriptAndStyleSheets;
2488 }
2489
2490
2491 /**
2492 * Wraps a text with an anchor and returns the HTML representation.
2493 *
2494 * @param string $text: The text to be wrapped by an anchor
2495 * @param string $link: The link to be used in the anchor
2496 * @param array $attributes: Array of attributes to be used in the anchor
2497 * @return string The wrapped texted as HTML representation
2498 */
2499 protected function wrapWithAnchor($text, $link, $attributes = array()) {
2500 $link = trim($link);
2501 $result = '<a href="' . ($link ? $link : '#') . '"';
2502 foreach ($attributes as $key => $value) {
2503 $result .= ' ' . $key . '="' . htmlspecialchars(trim($value)) . '"';
2504 }
2505 $result .= '>' . $text . '</a>';
2506 return $result;
2507 }
2508 }
2509
2510
2511 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_tceforms_inline.php'])) {
2512 include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_tceforms_inline.php']);
2513 }
2514
2515 ?>