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