0fc7deea4cf35ddfda60a7169fadb82a6aaf62ac
[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'])) {
542 $originalRecord = \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord($foreign_table, $rec['uid']);
543 if (is_array($originalRecord)) {
544 $fileUid = $originalRecord[$config['appearance']['headerThumbnail']];
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 $imageUrl = $fileObject->process(\TYPO3\CMS\Core\Resource\ProcessedFile::CONTEXT_IMAGEPREVIEW, array('width' => 64, 'height' => 64))->getPublicUrl(TRUE);
550 $thumbnail = '<img src="' . $imageUrl . '" alt="' . htmlspecialchars($recTitle) . '">';
551 } else {
552 $thumbnail = FALSE;
553 }
554 }
555 }
556 }
557 $altText = \TYPO3\CMS\Backend\Utility\BackendUtility::getRecordIconAltText($rec, $foreign_table);
558 $iconImg = \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIconForRecord($foreign_table, $rec, array('title' => htmlspecialchars($altText), 'id' => $objectId . '_icon'));
559 $label = '<span id="' . $objectId . '_label">' . $recTitle . '</span>';
560 $ctrl = $this->renderForeignRecordHeaderControl($parentUid, $foreign_table, $rec, $config, $isVirtualRecord);
561 $header = '<table>' . '<tr>' . (!empty($config['appearance']['headerThumbnail']) && $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>';
562 return $header;
563 }
564
565 /**
566 * Render the control-icons for a record header (create new, sorting, delete, disable/enable).
567 * Most of the parts are copy&paste from class.db_list_extra.inc and modified for the JavaScript calls here
568 *
569 * @param string $parentUid The uid of the parent (embedding) record (uid or NEW...)
570 * @param string $foreign_table The table (foreign_table) we create control-icons for
571 * @param array $rec The current record of that foreign_table
572 * @param array $config (modified) TCA configuration of the field
573 * @return string The HTML code with the control-icons
574 * @todo Define visibility
575 */
576 public function renderForeignRecordHeaderControl($parentUid, $foreign_table, $rec, $config = array(), $isVirtualRecord = FALSE) {
577 // Initialize:
578 $cells = array();
579 $isNewItem = substr($rec['uid'], 0, 3) == 'NEW';
580 $tcaTableCtrl = &$GLOBALS['TCA'][$foreign_table]['ctrl'];
581 $tcaTableCols = &$GLOBALS['TCA'][$foreign_table]['columns'];
582 $isPagesTable = $foreign_table == 'pages' ? TRUE : FALSE;
583 $isOnSymmetricSide = \TYPO3\CMS\Core\Database\RelationHandler::isOnSymmetricSide($parentUid, $config, $rec);
584 $enableManualSorting = $tcaTableCtrl['sortby'] || $config['MM'] || !$isOnSymmetricSide && $config['foreign_sortby'] || $isOnSymmetricSide && $config['symmetric_sortby'] ? TRUE : FALSE;
585 $nameObject = $this->inlineNames['object'];
586 $nameObjectFt = $nameObject . self::Structure_Separator . $foreign_table;
587 $nameObjectFtId = $nameObjectFt . self::Structure_Separator . $rec['uid'];
588 $calcPerms = $GLOBALS['BE_USER']->calcPerms(\TYPO3\CMS\Backend\Utility\BackendUtility::readPageAccess($rec['pid'], $GLOBALS['BE_USER']->getPagePermsClause(1)));
589 // If the listed table is 'pages' we have to request the permission settings for each page:
590 if ($isPagesTable) {
591 $localCalcPerms = $GLOBALS['BE_USER']->calcPerms(\TYPO3\CMS\Backend\Utility\BackendUtility::getRecord('pages', $rec['uid']));
592 }
593 // This expresses the edit permissions for this particular element:
594 $permsEdit = $isPagesTable && $localCalcPerms & 2 || !$isPagesTable && $calcPerms & 16;
595 // Controls: Defines which controls should be shown
596 $enabledControls = $config['appearance']['enabledControls'];
597 // Hook: Can disable/enable single controls for specific child records:
598 foreach ($this->hookObjects as $hookObj) {
599 $hookObj->renderForeignRecordHeaderControl_preProcess($parentUid, $foreign_table, $rec, $config, $isVirtualRecord, $enabledControls);
600 }
601 // Icon to visualize that a required field is nested in this inline level:
602 $cells['required'] = '<img name="' . $nameObjectFtId . '_req" src="clear.gif" width="10" height="10" hspace="4" vspace="3" alt="" />';
603 if (isset($rec['__create'])) {
604 $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)));
605 } elseif (isset($rec['__remove'])) {
606 $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)));
607 }
608 // "Info": (All records)
609 if ($enabledControls['info'] && !$isNewItem) {
610 $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>';
611 }
612 // If the table is NOT a read-only table, then show these links:
613 if (!$tcaTableCtrl['readOnly'] && !$isVirtualRecord) {
614 // "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):
615 if ($enabledControls['new'] && ($enableManualSorting || $tcaTableCtrl['useColumnsForDefaultValues'])) {
616 if (!$isPagesTable && $calcPerms & 16 || $isPagesTable && $calcPerms & 8) {
617 $onClick = 'return inline.createNewRecord(\'' . $nameObjectFt . '\',\'' . $rec['uid'] . '\')';
618 $class = ' class="inlineNewButton ' . $this->inlineData['config'][$nameObject]['md5'] . '"';
619 if ($config['inline']['inlineNewButtonStyle']) {
620 $style = ' style="' . $config['inline']['inlineNewButtonStyle'] . '"';
621 }
622 $cells['new'] = '<a href="#" onclick="' . htmlspecialchars($onClick) . '"' . $class . $style . '>' . \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIcon(('actions-' . ($isPagesTable ? 'page' : 'document') . '-new'), array(
623 'title' => $GLOBALS['LANG']->sL(('LLL:EXT:lang/locallang_mod_web_list.xml:new' . ($isPagesTable ? 'Page' : 'Record')), 1)
624 )) . '</a>';
625 }
626 }
627 // "Up/Down" links
628 if ($enabledControls['sort'] && $permsEdit && $enableManualSorting) {
629 $onClick = 'return inline.changeSorting(\'' . $nameObjectFtId . '\', \'1\')';
630 // Up
631 $style = $config['inline']['first'] == $rec['uid'] ? 'style="visibility: hidden;"' : '';
632 $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>';
633 $onClick = 'return inline.changeSorting(\'' . $nameObjectFtId . '\', \'-1\')';
634 // Down
635 $style = $config['inline']['last'] == $rec['uid'] ? 'style="visibility: hidden;"' : '';
636 $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>';
637 }
638 // "Hide/Unhide" links:
639 $hiddenField = $tcaTableCtrl['enablecolumns']['disabled'];
640 if ($enabledControls['hide'] && $permsEdit && $hiddenField && $tcaTableCols[$hiddenField] && (!$tcaTableCols[$hiddenField]['exclude'] || $GLOBALS['BE_USER']->check('non_exclude_fields', $foreign_table . ':' . $hiddenField))) {
641 $onClick = 'return inline.enableDisableRecord(\'' . $nameObjectFtId . '\')';
642 if ($rec[$hiddenField]) {
643 $cells['hide.unhide'] = '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIcon('actions-edit-unhide', array(
644 'title' => $GLOBALS['LANG']->sL(('LLL:EXT:lang/locallang_mod_web_list.xml:unHide' . ($isPagesTable ? 'Page' : '')), 1),
645 'id' => ($nameObjectFtId . '_disabled')
646 )) . '</a>';
647 } else {
648 $cells['hide.hide'] = '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIcon('actions-edit-hide', array(
649 'title' => $GLOBALS['LANG']->sL(('LLL:EXT:lang/locallang_mod_web_list.xml:hide' . ($isPagesTable ? 'Page' : '')), 1),
650 'id' => ($nameObjectFtId . '_disabled')
651 )) . '</a>';
652 }
653 }
654 // "Delete" link:
655 if ($enabledControls['delete'] && ($isPagesTable && $localCalcPerms & 4 || !$isPagesTable && $calcPerms & 16)) {
656 $onClick = 'inline.deleteRecord(\'' . $nameObjectFtId . '\');';
657 $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>';
658 }
659 // Drag&Drop Sorting: Sortable handler for script.aculo.us
660 if ($enabledControls['dragdrop'] && $permsEdit && $enableManualSorting && $config['appearance']['useSortable']) {
661 $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)));
662 }
663 } elseif ($isVirtualRecord) {
664 if ($enabledControls['localize'] && isset($rec['__create'])) {
665 $onClick = 'inline.synchronizeLocalizeRecords(\'' . $nameObjectFt . '\', ' . $rec['uid'] . ');';
666 $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>';
667 }
668 }
669 // If the record is edit-locked by another user, we will show a little warning sign:
670 if ($lockInfo = \TYPO3\CMS\Backend\Utility\BackendUtility::isRecordLocked($foreign_table, $rec['uid'])) {
671 $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>';
672 }
673 // Hook: Post-processing of single controls for specific child records:
674 foreach ($this->hookObjects as $hookObj) {
675 $hookObj->renderForeignRecordHeaderControl_postProcess($parentUid, $foreign_table, $rec, $config, $isVirtualRecord, $cells);
676 }
677 return '<!-- CONTROL PANEL: ' . $foreign_table . ':' . $rec['uid'] . ' -->' . implode('', $cells);
678 }
679
680 /**
681 * Render a table with TCEforms, that occurs on a intermediate table but should be editable directly,
682 * so two tables are combined (the intermediate table with attributes and the sub-embedded table).
683 * -> This is a direct embedding over two levels!
684 *
685 * @param array $rec The table record of the child/embedded table (normaly post-processed by t3lib_transferData)
686 * @param string $appendFormFieldNames The [<table>][<uid>] of the parent record (the intermediate table)
687 * @param array $config content of $PA['fieldConf']['config']
688 * @return string A HTML string with <table> tag around.
689 * @todo Define visibility
690 */
691 public function renderCombinationTable(&$rec, $appendFormFieldNames, $config = array()) {
692 $foreign_table = $config['foreign_table'];
693 $foreign_selector = $config['foreign_selector'];
694 if ($foreign_selector && $config['appearance']['useCombination']) {
695 $comboConfig = $GLOBALS['TCA'][$foreign_table]['columns'][$foreign_selector]['config'];
696 $comboRecord = array();
697 // If record does already exist, load it:
698 if ($rec[$foreign_selector] && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($rec[$foreign_selector])) {
699 $comboRecord = $this->getRecord($this->inlineFirstPid, $comboConfig['foreign_table'], $rec[$foreign_selector]);
700 $isNewRecord = FALSE;
701 } else {
702 $comboRecord = $this->getNewRecord($this->inlineFirstPid, $comboConfig['foreign_table']);
703 $isNewRecord = TRUE;
704 }
705 // Get the TCEforms interpretation of the TCA of the child table
706 $out = $this->renderMainFields($comboConfig['foreign_table'], $comboRecord);
707 $out = $this->wrapFormsSection($out, array(), array('class' => 'wrapperAttention'));
708 // If this is a new record, add a pid value to store this record and the pointer value for the intermediate table
709 if ($isNewRecord) {
710 $comboFormFieldName = $this->prependFormFieldNames . '[' . $comboConfig['foreign_table'] . '][' . $comboRecord['uid'] . '][pid]';
711 $out .= '<input type="hidden" name="' . $comboFormFieldName . '" value="' . $comboRecord['pid'] . '" />';
712 }
713 // If the foreign_selector field is also responsible for uniqueness, tell the browser the uid of the "other" side of the relation
714 if ($isNewRecord || $config['foreign_unique'] == $foreign_selector) {
715 $parentFormFieldName = $this->prependFormFieldNames . $appendFormFieldNames . '[' . $foreign_selector . ']';
716 $out .= '<input type="hidden" name="' . $parentFormFieldName . '" value="' . $comboRecord['uid'] . '" />';
717 }
718 }
719 return $out;
720 }
721
722 /**
723 * Get a selector as used for the select type, to select from all available
724 * records and to create a relation to the embedding record (e.g. like MM).
725 *
726 * @param array $selItems Array of all possible records
727 * @param array $conf TCA configuration of the parent(!) field
728 * @param array $uniqueIds The uids that have already been used and should be unique
729 * @return string A HTML <select> box with all possible records
730 * @todo Define visibility
731 */
732 public function renderPossibleRecordsSelector($selItems, $conf, $uniqueIds = array()) {
733 $foreign_table = $conf['foreign_table'];
734 $foreign_selector = $conf['foreign_selector'];
735 $selConfig = $this->getPossibleRecordsSelectorConfig($conf, $foreign_selector);
736 $config = $selConfig['PA']['fieldConf']['config'];
737 if ($selConfig['type'] == 'select') {
738 $item = $this->renderPossibleRecordsSelectorTypeSelect($selItems, $conf, $selConfig['PA'], $uniqueIds);
739 } elseif ($selConfig['type'] == 'groupdb') {
740 $item = $this->renderPossibleRecordsSelectorTypeGroupDB($conf, $selConfig['PA']);
741 }
742 return $item;
743 }
744
745 /**
746 * Get a selector as used for the select type, to select from all available
747 * records and to create a relation to the embedding record (e.g. like MM).
748 *
749 * @param array $selItems Array of all possible records
750 * @param array $conf TCA configuration of the parent(!) field
751 * @param array $PA An array with additional configuration options
752 * @param array $uniqueIds The uids that have already been used and should be unique
753 * @return string A HTML <select> box with all possible records
754 * @todo Define visibility
755 */
756 public function renderPossibleRecordsSelectorTypeSelect($selItems, $conf, &$PA, $uniqueIds = array()) {
757 $foreign_table = $conf['foreign_table'];
758 $foreign_selector = $conf['foreign_selector'];
759 $PA = array();
760 $PA['fieldConf'] = $GLOBALS['TCA'][$foreign_table]['columns'][$foreign_selector];
761 $PA['fieldConf']['config']['form_type'] = $PA['fieldConf']['config']['form_type'] ? $PA['fieldConf']['config']['form_type'] : $PA['fieldConf']['config']['type'];
762 // Using "form_type" locally in this script
763 $PA['fieldTSConfig'] = $this->fObj->setTSconfig($foreign_table, array(), $foreign_selector);
764 $config = $PA['fieldConf']['config'];
765 //TODO: $disabled is not present - should be read from config?
766 $disabled = FALSE;
767 if (!$disabled) {
768 // Create option tags:
769 $opt = array();
770 $styleAttrValue = '';
771 foreach ($selItems as $p) {
772 if ($config['iconsInOptionTags']) {
773 $styleAttrValue = $this->fObj->optionTagStyle($p[2]);
774 }
775 if (!in_array($p[1], $uniqueIds)) {
776 $opt[] = '<option value="' . htmlspecialchars($p[1]) . '"' . ' style="' . (in_array($p[1], $uniqueIds) ? '' : '') . ($styleAttrValue ? ' style="' . htmlspecialchars($styleAttrValue) : '') . '">' . htmlspecialchars($p[0]) . '</option>';
777 }
778 }
779 // Put together the selector box:
780 $selector_itemListStyle = isset($config['itemListStyle']) ? ' style="' . htmlspecialchars($config['itemListStyle']) . '"' : ' style="' . $this->fObj->defaultMultipleSelectorStyle . '"';
781 $size = intval($conf['size']);
782 $size = $conf['autoSizeMax'] ? \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange(count($selItems) + 1, \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($size, 1), $conf['autoSizeMax']) : $size;
783 $onChange = 'return inline.importNewRecord(\'' . $this->inlineNames['object'] . self::Structure_Separator . $conf['foreign_table'] . '\')';
784 $item = '
785 <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"' : '') . '>
786 ' . implode('
787 ', $opt) . '
788 </select>';
789 // Add a "Create new relation" link for adding new relations
790 // This is neccessary, if the size of the selector is "1" or if
791 // there is only one record item in the select-box, that is selected by default
792 // The selector-box creates a new relation on using a onChange event (see some line above)
793 if (!empty($conf['appearance']['createNewRelationLinkTitle'])) {
794 $createNewRelationText = $GLOBALS['LANG']->sL($conf['appearance']['createNewRelationLinkTitle'], TRUE);
795 } else {
796 $createNewRelationText = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:cm.createNewRelation', 1);
797 }
798 $item .= '<a href="#" onclick="' . htmlspecialchars($onChange) . '" align="abstop">' . \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIcon('actions-document-new', array('title' => $createNewRelationText)) . $createNewRelationText . '</a>';
799 // Wrap the selector and add a spacer to the bottom
800 $item = '<div style="margin-bottom: 20px;">' . $item . '</div>';
801 }
802 return $item;
803 }
804
805 /**
806 * Generate a link that opens an element browser in a new window.
807 * For group/db there is no way o use a "selector" like a <select>|</select>-box.
808 *
809 * @param array $conf TCA configuration of the parent(!) field
810 * @param array $PA An array with additional configuration options
811 * @return string A HTML link that opens an element browser in a new window
812 * @todo Define visibility
813 */
814 public function renderPossibleRecordsSelectorTypeGroupDB($conf, &$PA) {
815 $foreign_table = $conf['foreign_table'];
816 $config = $PA['fieldConf']['config'];
817 $allowed = $config['allowed'];
818 $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $foreign_table;
819 $mode = 'db';
820 if (!empty($conf['appearance']['createNewRelationLinkTitle'])) {
821 $createNewRelationText = $GLOBALS['LANG']->sL($conf['appearance']['createNewRelationLinkTitle'], TRUE);
822 } else {
823 $createNewRelationText = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:cm.createNewRelation', 1);
824 }
825 if (is_array($config['appearance'])) {
826 if (isset($config['appearance']['elementBrowserType'])) {
827 $mode = $config['appearance']['elementBrowserType'];
828 }
829 if (isset($config['appearance']['elementBrowserAllowed'])) {
830 $allowed = $config['appearance']['elementBrowserAllowed'];
831 }
832 }
833 $browserParams = '|||' . $allowed . '|' . $objectPrefix . '|inline.checkUniqueElement||inline.importElement';
834 $onClick = 'setFormValueOpenBrowser(\'' . $mode . '\', \'' . $browserParams . '\'); return false;';
835 $item = '<a href="#" onclick="' . htmlspecialchars($onClick) . '">' . \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIcon('actions-insert-record', array('title' => $createNewRelationText)) . $createNewRelationText . '</a>';
836 return $item;
837 }
838
839 /**
840 * Creates the HTML code of a general link to be used on a level of inline children.
841 * The possible keys for the parameter $type are 'newRecord', 'localize' and 'synchronize'.
842 *
843 * @param string $type The link type, values are 'newRecord', 'localize' and 'synchronize'.
844 * @param string $objectPrefix The "path" to the child record to create (e.g. 'data-parentPageId-partenTable-parentUid-parentField-childTable]')
845 * @param array $conf TCA configuration of the parent(!) field
846 * @return string The HTML code of the new link, wrapped in a div
847 */
848 protected function getLevelInteractionLink($type, $objectPrefix, $conf = array()) {
849 $nameObject = $this->inlineNames['object'];
850 $attributes = array();
851 switch ($type) {
852 case 'newRecord':
853 $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xml:cm.createnew', 1);
854 $icon = 'actions-document-new';
855 $className = 'typo3-newRecordLink';
856 $attributes['class'] = 'inlineNewButton ' . $this->inlineData['config'][$nameObject]['md5'];
857 $attributes['onclick'] = 'return inline.createNewRecord(\'' . $objectPrefix . '\')';
858 if (isset($conf['inline']['inlineNewButtonStyle']) && $conf['inline']['inlineNewButtonStyle']) {
859 $attributes['style'] = $conf['inline']['inlineNewButtonStyle'];
860 }
861 if (isset($conf['appearance']['newRecordLinkAddTitle']) && $conf['appearance']['newRecordLinkAddTitle']) {
862 $titleAddon = ' ' . $GLOBALS['LANG']->sL($GLOBALS['TCA'][$conf['foreign_table']]['ctrl']['title'], 1);
863 }
864 break;
865 case 'localize':
866 $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xml:localizeAllRecords', 1);
867 $icon = 'actions-document-localize';
868 $className = 'typo3-localizationLink';
869 $attributes['onclick'] = 'return inline.synchronizeLocalizeRecords(\'' . $objectPrefix . '\', \'localize\')';
870 break;
871 case 'synchronize':
872 $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xml:synchronizeWithOriginalLanguage', 1);
873 $icon = 'actions-document-synchronize';
874 $className = 'typo3-synchronizationLink';
875 $attributes['class'] = 'inlineNewButton ' . $this->inlineData['config'][$nameObject]['md5'];
876 $attributes['onclick'] = 'return inline.synchronizeLocalizeRecords(\'' . $objectPrefix . '\', \'synchronize\')';
877 break;
878 }
879 // Create the link:
880 $icon = $icon ? \TYPO3\CMS\Backend\Utility\IconUtility::getSpriteIcon($icon, array('title' => htmlspecialchars($title . $titleAddon))) : '';
881 $link = $this->wrapWithAnchor($icon . $title . $titleAddon, '#', $attributes);
882 return '<div' . ($className ? ' class="' . $className . '"' : '') . '>' . $link . '</div>';
883 }
884
885 /**
886 * Add Sortable functionality using script.acolo.us "Sortable".
887 *
888 * @param string $objectId The container id of the object - elements inside will be sortable
889 * @return void
890 * @todo Define visibility
891 */
892 public function addJavaScriptSortable($objectId) {
893 $this->fObj->additionalJS_post[] = '
894 inline.createDragAndDropSorting("' . $objectId . '");
895 ';
896 }
897
898 /*******************************************************
899 *
900 * Handling of AJAX calls
901 *
902 *******************************************************/
903 /**
904 * General processor for AJAX requests concerning IRRE.
905 * (called by typo3/ajax.php)
906 *
907 * @param array $params Additional parameters (not used here)
908 * @param \TYPO3\CMS\Core\Http\AjaxRequestHandler $ajaxObj The TYPO3AJAX object of this request
909 * @return void
910 */
911 public function processAjaxRequest($params, $ajaxObj) {
912 $ajaxArguments = \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('ajax');
913 $ajaxIdParts = explode('::', $GLOBALS['ajaxID'], 2);
914 if (isset($ajaxArguments) && is_array($ajaxArguments) && count($ajaxArguments)) {
915 $ajaxMethod = $ajaxIdParts[1];
916 switch ($ajaxMethod) {
917 case 'createNewRecord':
918
919 case 'synchronizeLocalizeRecords':
920
921 case 'getRecordDetails':
922 $this->isAjaxCall = TRUE;
923 // Construct runtime environment for Inline Relational Record Editing:
924 $this->processAjaxRequestConstruct($ajaxArguments);
925 // Parse the DOM identifier (string), add the levels to the structure stack (array) and load the TCA config:
926 $this->parseStructureString($ajaxArguments[0], TRUE);
927 $this->injectAjaxConfiguration($ajaxArguments);
928 // Render content:
929 $ajaxObj->setContentFormat('jsonbody');
930 $ajaxObj->setContent(call_user_func_array(array(&$this, $ajaxMethod), $ajaxArguments));
931 break;
932 case 'setExpandedCollapsedState':
933 $ajaxObj->setContentFormat('jsonbody');
934 call_user_func_array(array(&$this, $ajaxMethod), $ajaxArguments);
935 break;
936 }
937 }
938 }
939
940 /**
941 * Injects configuration via AJAX calls.
942 * The configuration is validated using HMAC to avoid hijacking.
943 *
944 * @param array $ajaxArguments
945 * @return void
946 */
947 protected function injectAjaxConfiguration(array $ajaxArguments) {
948 $level = $this->calculateStructureLevel(-1);
949
950 if (empty($ajaxArguments['context']) || $level === FALSE) {
951 return;
952 }
953
954 $current = &$this->inlineStructure['stable'][$level];
955 $context = json_decode($ajaxArguments['context'], TRUE);
956
957 if (\TYPO3\CMS\Core\Utility\GeneralUtility::hmac(serialize($context['config'])) !== $context['hmac']) {
958 return;
959 }
960
961 $current['config'] = $context['config'];
962 $current['localizationMode'] = \TYPO3\CMS\Backend\Utility\BackendUtility::getInlineLocalizationMode(
963 $current['table'],
964 $current['config']
965 );
966 }
967
968 /**
969 * Construct runtime environment for Inline Relational Record Editing.
970 * - creates an anoymous SC_alt_doc in $GLOBALS['SOBE']
971 * - creates a t3lib_TCEforms in $GLOBALS['SOBE']->tceforms
972 * - sets ourself as reference to $GLOBALS['SOBE']->tceforms->inline
973 * - sets $GLOBALS['SOBE']->tceforms->RTEcounter to the current situation on client-side
974 *
975 * @param array &$ajaxArguments The arguments to be processed by the AJAX request
976 * @return void
977 */
978 protected function processAjaxRequestConstruct(&$ajaxArguments) {
979 $GLOBALS['LANG']->includeLLFile('EXT:lang/locallang_alt_doc.xml');
980 // Create a new anonymous object:
981 $GLOBALS['SOBE'] = new \stdClass();
982 $GLOBALS['SOBE']->MOD_MENU = array(
983 'showPalettes' => '',
984 'showDescriptions' => '',
985 'disableRTE' => ''
986 );
987 // Setting virtual document name
988 $GLOBALS['SOBE']->MCONF['name'] = 'xMOD_alt_doc.php';
989 // CLEANSE SETTINGS
990 $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']);
991 // Create an instance of the document template object
992 $GLOBALS['SOBE']->doc = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Template\\DocumentTemplate');
993 $GLOBALS['SOBE']->doc->backPath = $GLOBALS['BACK_PATH'];
994 // Initialize TCEforms (rendering the forms)
995 $GLOBALS['SOBE']->tceforms = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Form\\FormEngine');
996 $GLOBALS['SOBE']->tceforms->inline = $this;
997 $GLOBALS['SOBE']->tceforms->RTEcounter = intval(array_shift($ajaxArguments));
998 $GLOBALS['SOBE']->tceforms->initDefaultBEMode();
999 $GLOBALS['SOBE']->tceforms->palettesCollapsed = !$GLOBALS['SOBE']->MOD_SETTINGS['showPalettes'];
1000 $GLOBALS['SOBE']->tceforms->disableRTE = $GLOBALS['SOBE']->MOD_SETTINGS['disableRTE'];
1001 $GLOBALS['SOBE']->tceforms->enableClickMenu = TRUE;
1002 $GLOBALS['SOBE']->tceforms->enableTabMenu = TRUE;
1003 // Clipboard is initialized:
1004 // Start clipboard
1005 $GLOBALS['SOBE']->tceforms->clipObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Clipboard\\Clipboard');
1006 // Initialize - reads the clipboard content from the user session
1007 $GLOBALS['SOBE']->tceforms->clipObj->initializeClipboard();
1008 }
1009
1010 /**
1011 * Determines and sets several script calls to a JSON array, that would have been executed if processed in non-AJAX mode.
1012 *
1013 * @param array &$jsonArray Reference of the array to be used for JSON
1014 * @param array $config The configuration of the IRRE field of the parent record
1015 * @return void
1016 */
1017 protected function getCommonScriptCalls(&$jsonArray, $config) {
1018 // Add data that would have been added at the top of a regular TCEforms call:
1019 if ($headTags = $this->getHeadTags()) {
1020 $jsonArray['headData'] = $headTags;
1021 }
1022 // Add the JavaScript data that would have been added at the bottom of a regular TCEforms call:
1023 $jsonArray['scriptCall'][] = $this->fObj->JSbottom($this->fObj->formName, TRUE);
1024 // If script.aculo.us Sortable is used, update the Observer to know the record:
1025 if ($config['appearance']['useSortable']) {
1026 $jsonArray['scriptCall'][] = 'inline.createDragAndDropSorting(\'' . $this->inlineNames['object'] . '_records\');';
1027 }
1028 // if TCEforms has some JavaScript code to be executed, just do it
1029 if ($this->fObj->extJSCODE) {
1030 $jsonArray['scriptCall'][] = $this->fObj->extJSCODE;
1031 }
1032 }
1033
1034 /**
1035 * Generates an error message that transferred as JSON for AJAX calls
1036 *
1037 * @param string $message The error message to be shown
1038 * @return array The error message in a JSON array
1039 */
1040 protected function getErrorMessageForAJAX($message) {
1041 $jsonArray = array(
1042 'data' => $message,
1043 'scriptCall' => array(
1044 'alert("' . $message . '");'
1045 )
1046 );
1047 return $jsonArray;
1048 }
1049
1050 /**
1051 * Handle AJAX calls to show a new inline-record of the given table.
1052 * Normally this method is never called from inside TYPO3. Always from outside by AJAX.
1053 *
1054 * @param string $domObjectId The calling object in hierarchy, that requested a new record.
1055 * @param string $foreignUid If set, the new record should be inserted after that one.
1056 * @return array An array to be used for JSON
1057 * @todo Define visibility
1058 */
1059 public function createNewRecord($domObjectId, $foreignUid = 0) {
1060 // The current table - for this table we should add/import records
1061 $current = $this->inlineStructure['unstable'];
1062 // The parent table - this table embeds the current table
1063 $parent = $this->getStructureLevel(-1);
1064 // Get TCA 'config' of the parent table
1065 if (!$this->checkConfiguration($parent['config'])) {
1066 return $this->getErrorMessageForAJAX('Wrong configuration in table ' . $parent['table']);
1067 }
1068 $config = $parent['config'];
1069 $collapseAll = isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll'];
1070 $expandSingle = isset($config['appearance']['expandSingle']) && $config['appearance']['expandSingle'];
1071 // Put the current level also to the dynNestedStack of TCEforms:
1072 $this->fObj->pushToDynNestedStack('inline', $this->inlineNames['object']);
1073 // Dynamically create a new record using t3lib_transferData
1074 if (!$foreignUid || !\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($foreignUid) || $config['foreign_selector']) {
1075 $record = $this->getNewRecord($this->inlineFirstPid, $current['table']);
1076 // Set language of new child record to the language of the parent record:
1077 if ($config['localizationMode'] == 'select') {
1078 $parentRecord = $this->getRecord(0, $parent['table'], $parent['uid']);
1079 $parentLanguageField = $GLOBALS['TCA'][$parent['table']]['ctrl']['languageField'];
1080 $childLanguageField = $GLOBALS['TCA'][$current['table']]['ctrl']['languageField'];
1081 if ($parentRecord[$parentLanguageField] > 0) {
1082 $record[$childLanguageField] = $parentRecord[$parentLanguageField];
1083 }
1084 }
1085 } else {
1086 $record = $this->getRecord($this->inlineFirstPid, $current['table'], $foreignUid);
1087 }
1088 // Now there is a foreign_selector, so there is a new record on the intermediate table, but
1089 // this intermediate table holds a field, which is responsible for the foreign_selector, so
1090 // we have to set this field to the uid we get - or if none, to a new uid
1091 if ($config['foreign_selector'] && $foreignUid) {
1092 $selConfig = $this->getPossibleRecordsSelectorConfig($config, $config['foreign_selector']);
1093 // For a selector of type group/db, prepend the tablename (<tablename>_<uid>):
1094 $record[$config['foreign_selector']] = $selConfig['type'] != 'groupdb' ? '' : $selConfig['table'] . '_';
1095 $record[$config['foreign_selector']] .= $foreignUid;
1096 }
1097 // The HTML-object-id's prefix of the dynamically created record
1098 $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $current['table'];
1099 $objectId = $objectPrefix . self::Structure_Separator . $record['uid'];
1100 // Render the foreign record that should passed back to browser
1101 $item = $this->renderForeignRecord($parent['uid'], $record, $config);
1102 if ($item === FALSE) {
1103 return $this->getErrorMessageForAJAX('Access denied');
1104 }
1105 if (!$current['uid']) {
1106 $jsonArray = array(
1107 'data' => $item,
1108 'scriptCall' => array(
1109 'inline.domAddNewRecord(\'bottom\',\'' . $this->inlineNames['object'] . '_records\',\'' . $objectPrefix . '\',json.data);',
1110 'inline.memorizeAddRecord(\'' . $objectPrefix . '\',\'' . $record['uid'] . '\',null,\'' . $foreignUid . '\');'
1111 )
1112 );
1113 } else {
1114 $jsonArray = array(
1115 'data' => $item,
1116 'scriptCall' => array(
1117 'inline.domAddNewRecord(\'after\',\'' . $domObjectId . '_div' . '\',\'' . $objectPrefix . '\',json.data);',
1118 'inline.memorizeAddRecord(\'' . $objectPrefix . '\',\'' . $record['uid'] . '\',\'' . $current['uid'] . '\',\'' . $foreignUid . '\');'
1119 )
1120 );
1121 }
1122 $this->getCommonScriptCalls($jsonArray, $config);
1123 // Collapse all other records if requested:
1124 if (!$collapseAll && $expandSingle) {
1125 $jsonArray['scriptCall'][] = 'inline.collapseAllRecords(\'' . $objectId . '\', \'' . $objectPrefix . '\', \'' . $record['uid'] . '\');';
1126 }
1127 // Tell the browser to scroll to the newly created record
1128 $jsonArray['scriptCall'][] = 'Element.scrollTo(\'' . $objectId . '_div\');';
1129 // Fade out and fade in the new record in the browser view to catch the user's eye
1130 $jsonArray['scriptCall'][] = 'inline.fadeOutFadeIn(\'' . $objectId . '_div\');';
1131 // Remove the current level also from the dynNestedStack of TCEforms:
1132 $this->fObj->popFromDynNestedStack();
1133 // Return the JSON array:
1134 return $jsonArray;
1135 }
1136
1137 /**
1138 * Handle AJAX calls to localize all records of a parent, localize a single record or to synchronize with the original language parent.
1139 *
1140 * @param string $domObjectId The calling object in hierarchy, that requested a new record.
1141 * @param mixed $type Defines the type 'localize' or 'synchronize' (string) or a single uid to be localized (integer)
1142 * @return array An array to be used for JSON
1143 */
1144 protected function synchronizeLocalizeRecords($domObjectId, $type) {
1145 $jsonArray = FALSE;
1146 if (\TYPO3\CMS\Core\Utility\GeneralUtility::inList('localize,synchronize', $type) || \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($type)) {
1147 // The current level:
1148 $current = $this->inlineStructure['unstable'];
1149 // The parent level:
1150 $parent = $this->getStructureLevel(-1);
1151 $parentRecord = $this->getRecord(0, $parent['table'], $parent['uid']);
1152 $cmd = array();
1153 $cmd[$parent['table']][$parent['uid']]['inlineLocalizeSynchronize'] = $parent['field'] . ',' . $type;
1154 /** @var $tce \TYPO3\CMS\Core\DataHandling\DataHandler */
1155 $tce = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\DataHandling\\DataHandler');
1156 $tce->stripslashes_values = FALSE;
1157 $tce->start(array(), $cmd);
1158 $tce->process_cmdmap();
1159 $newItemList = $tce->registerDBList[$parent['table']][$parent['uid']][$parent['field']];
1160 unset($tce);
1161 $jsonArray = $this->getExecuteChangesJsonArray($parentRecord[$parent['field']], $newItemList);
1162 $this->getCommonScriptCalls($jsonArray, $parent['config']);
1163 }
1164 return $jsonArray;
1165 }
1166
1167 /**
1168 * Handle AJAX calls to dynamically load the form fields of a given record.
1169 * (basically a copy of "createNewRecord")
1170 * Normally this method is never called from inside TYPO3. Always from outside by AJAX.
1171 *
1172 * @param string $domObjectId The calling object in hierarchy, that requested a new record.
1173 * @return array An array to be used for JSON
1174 * @todo Define visibility
1175 */
1176 public function getRecordDetails($domObjectId) {
1177 // The current table - for this table we should add/import records
1178 $current = $this->inlineStructure['unstable'];
1179 // The parent table - this table embeds the current table
1180 $parent = $this->getStructureLevel(-1);
1181 // Get TCA 'config' of the parent table
1182 if (!$this->checkConfiguration($parent['config'])) {
1183 return $this->getErrorMessageForAJAX('Wrong configuration in table ' . $parent['table']);
1184 }
1185 $config = $parent['config'];
1186 // Set flag in config so that only the fields are rendered
1187 $config['renderFieldsOnly'] = TRUE;
1188 $collapseAll = isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll'];
1189 $expandSingle = isset($config['appearance']['expandSingle']) && $config['appearance']['expandSingle'];
1190 // Put the current level also to the dynNestedStack of TCEforms:
1191 $this->fObj->pushToDynNestedStack('inline', $this->inlineNames['object']);
1192 $record = $this->getRecord($this->inlineFirstPid, $current['table'], $current['uid']);
1193 // The HTML-object-id's prefix of the dynamically created record
1194 $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $current['table'];
1195 $objectId = $objectPrefix . self::Structure_Separator . $record['uid'];
1196 $item = $this->renderForeignRecord($parent['uid'], $record, $config);
1197 if ($item === FALSE) {
1198 return $this->getErrorMessageForAJAX('Access denied');
1199 }
1200 $jsonArray = array(
1201 'data' => $item,
1202 'scriptCall' => array(
1203 'inline.domAddRecordDetails(\'' . $domObjectId . '\',\'' . $objectPrefix . '\',' . ($expandSingle ? '1' : '0') . ',json.data);'
1204 )
1205 );
1206 if ($config['foreign_unique']) {
1207 $jsonArray['scriptCall'][] = 'inline.removeUsed(\'' . $objectPrefix . '\',\'' . $record['uid'] . '\');';
1208 }
1209 $this->getCommonScriptCalls($jsonArray, $config);
1210 // Collapse all other records if requested:
1211 if (!$collapseAll && $expandSingle) {
1212 $jsonArray['scriptCall'][] = 'inline.collapseAllRecords(\'' . $objectId . '\',\'' . $objectPrefix . '\',\'' . $record['uid'] . '\');';
1213 }
1214 // Remove the current level also from the dynNestedStack of TCEforms:
1215 $this->fObj->popFromDynNestedStack();
1216 // Return the JSON array:
1217 return $jsonArray;
1218 }
1219
1220 /**
1221 * Generates a JSON array which executes the changes and thus updates the forms view.
1222 *
1223 * @param string $oldItemList List of related child reocrds before changes were made (old)
1224 * @param string $newItemList List of related child records after changes where made (new)
1225 * @return array An array to be used for JSON
1226 */
1227 protected function getExecuteChangesJsonArray($oldItemList, $newItemList) {
1228 $data = '';
1229 $parent = $this->getStructureLevel(-1);
1230 $current = $this->inlineStructure['unstable'];
1231 $jsonArray = array('scriptCall' => array());
1232 $jsonArrayScriptCall = &$jsonArray['scriptCall'];
1233 $nameObject = $this->inlineNames['object'];
1234 $nameObjectForeignTable = $nameObject . self::Structure_Separator . $current['table'];
1235 // Get the name of the field pointing to the original record:
1236 $transOrigPointerField = $GLOBALS['TCA'][$current['table']]['ctrl']['transOrigPointerField'];
1237 // Get the name of the field used as foreign selector (if any):
1238 $foreignSelector = isset($parent['config']['foreign_selector']) && $parent['config']['foreign_selector'] ? $parent['config']['foreign_selector'] : FALSE;
1239 // Convert lists to array with uids of child records:
1240 $oldItems = $this->getRelatedRecordsUidArray($oldItemList);
1241 $newItems = $this->getRelatedRecordsUidArray($newItemList);
1242 // Determine the items that were localized or localized:
1243 $removedItems = array_diff($oldItems, $newItems);
1244 $localizedItems = array_diff($newItems, $oldItems);
1245 // Set the items that should be removed in the forms view:
1246 foreach ($removedItems as $item) {
1247 $jsonArrayScriptCall[] = 'inline.deleteRecord(\'' . $nameObjectForeignTable . self::Structure_Separator . $item . '\', {forceDirectRemoval: true});';
1248 }
1249 // Set the items that should be added in the forms view:
1250 foreach ($localizedItems as $item) {
1251 $row = $this->getRecord($this->inlineFirstPid, $current['table'], $item);
1252 $selectedValue = $foreignSelector ? '\'' . $row[$foreignSelector] . '\'' : 'null';
1253 $data .= $this->renderForeignRecord($parent['uid'], $row, $parent['config']);
1254 $jsonArrayScriptCall[] = 'inline.memorizeAddRecord(\'' . $nameObjectForeignTable . '\', \'' . $item . '\', null, ' . $selectedValue . ');';
1255 // Remove possible virtual records in the form which showed that a child records could be localized:
1256 if (isset($row[$transOrigPointerField]) && $row[$transOrigPointerField]) {
1257 $jsonArrayScriptCall[] = 'inline.fadeAndRemove(\'' . $nameObjectForeignTable . self::Structure_Separator . $row[$transOrigPointerField] . '_div' . '\');';
1258 }
1259 }
1260 if ($data) {
1261 $jsonArray['data'] = $data;
1262 array_unshift($jsonArrayScriptCall, 'inline.domAddNewRecord(\'bottom\', \'' . $nameObject . '_records\', \'' . $nameObjectForeignTable . '\', json.data);');
1263 }
1264 return $jsonArray;
1265 }
1266
1267 /**
1268 * Save the expanded/collapsed state of a child record in the BE_USER->uc.
1269 *
1270 * @param string $domObjectId The calling object in hierarchy, that requested a new record.
1271 * @param string $expand Whether this record is expanded.
1272 * @param string $collapse Whether this record is collapsed.
1273 * @return void
1274 * @todo Define visibility
1275 */
1276 public function setExpandedCollapsedState($domObjectId, $expand, $collapse) {
1277 // Parse the DOM identifier (string), add the levels to the structure stack (array), but don't load TCA config
1278 $this->parseStructureString($domObjectId, FALSE);
1279 // The current table - for this table we should add/import records
1280 $current = $this->inlineStructure['unstable'];
1281 // The top parent table - this table embeds the current table
1282 $top = $this->getStructureLevel(0);
1283 // Only do some action if the top record and the current record were saved before
1284 if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($top['uid'])) {
1285 $inlineView = (array) unserialize($GLOBALS['BE_USER']->uc['inlineView']);
1286 $inlineViewCurrent = &$inlineView[$top['table']][$top['uid']];
1287 $expandUids = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $expand);
1288 $collapseUids = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $collapse);
1289 // Set records to be expanded
1290 foreach ($expandUids as $uid) {
1291 $inlineViewCurrent[$current['table']][] = $uid;
1292 }
1293 // Set records to be collapsed
1294 foreach ($collapseUids as $uid) {
1295 $inlineViewCurrent[$current['table']] = $this->removeFromArray($uid, $inlineViewCurrent[$current['table']]);
1296 }
1297 // Save states back to database
1298 if (is_array($inlineViewCurrent[$current['table']])) {
1299 $inlineViewCurrent[$current['table']] = array_unique($inlineViewCurrent[$current['table']]);
1300 $GLOBALS['BE_USER']->uc['inlineView'] = serialize($inlineView);
1301 $GLOBALS['BE_USER']->writeUC();
1302 }
1303 }
1304 }
1305
1306 /*******************************************************
1307 *
1308 * Get data from database and handle relations
1309 *
1310 *******************************************************/
1311 /**
1312 * Get the related records of the embedding item, this could be 1:n, m:n.
1313 * Returns an associative array with the keys records and count. 'count' contains only real existing records on the current parent record.
1314 *
1315 * @param string $table The table name of the record
1316 * @param string $field The field name which this element is supposed to edit
1317 * @param array $row The record data array where the value(s) for the field can be found
1318 * @param array $PA An array with additional configuration options.
1319 * @param array $config (Redundant) content of $PA['fieldConf']['config'] (for convenience)
1320 * @return array The records related to the parent item as associative array.
1321 * @todo Define visibility
1322 */
1323 public function getRelatedRecords($table, $field, $row, &$PA, $config) {
1324 $pid = $row['pid'];
1325 $elements = $PA['itemFormElValue'];
1326 $foreignTable = $config['foreign_table'];
1327 $localizationMode = \TYPO3\CMS\Backend\Utility\BackendUtility::getInlineLocalizationMode($table, $config);
1328 if ($localizationMode != FALSE) {
1329 $language = intval($row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
1330 $transOrigPointer = intval($row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]);
1331 $transOrigTable = \TYPO3\CMS\Backend\Utility\BackendUtility::getOriginalTranslationTable($table);
1332
1333 if ($language > 0 && $transOrigPointer) {
1334 // Localization in mode 'keep', isn't a real localization, but keeps the children of the original parent record:
1335 if ($localizationMode == 'keep') {
1336 $transOrigRec = $this->getRecord(0, $transOrigTable, $transOrigPointer);
1337 $elements = $transOrigRec[$field];
1338 $pid = $transOrigRec['pid'];
1339 } elseif ($localizationMode == 'select') {
1340 $transOrigRec = $this->getRecord(0, $transOrigTable, $transOrigPointer);
1341 $pid = $transOrigRec['pid'];
1342 $recordsOriginal = $this->getRelatedRecordsArray($pid, $foreignTable, $transOrigRec[$field]);
1343 }
1344 }
1345 }
1346 $records = $this->getRelatedRecordsArray($pid, $foreignTable, $elements);
1347 $relatedRecords = array('records' => $records, 'count' => count($records));
1348 // Merge original language with current localization and show differences:
1349 if (is_array($recordsOriginal)) {
1350 $options = array(
1351 'showPossible' => isset($config['appearance']['showPossibleLocalizationRecords']) && $config['appearance']['showPossibleLocalizationRecords'],
1352 'showRemoved' => isset($config['appearance']['showRemovedLocalizationRecords']) && $config['appearance']['showRemovedLocalizationRecords']
1353 );
1354 if ($options['showPossible'] || $options['showRemoved']) {
1355 $relatedRecords['records'] = $this->getLocalizationDifferences($foreignTable, $options, $recordsOriginal, $records);
1356 }
1357 }
1358 return $relatedRecords;
1359 }
1360
1361 /**
1362 * Gets the related records of the embedding item, this could be 1:n, m:n.
1363 *
1364 * @param integer $pid The pid of the parent record
1365 * @param string $table The table name of the record
1366 * @param string $itemList The list of related child records
1367 * @return array The records related to the parent item
1368 */
1369 protected function getRelatedRecordsArray($pid, $table, $itemList) {
1370 $records = array();
1371 $itemArray = $this->getRelatedRecordsUidArray($itemList);
1372 // Perform modification of the selected items array:
1373 foreach ($itemArray as $uid) {
1374 // Get the records for this uid using t3lib_transferdata:
1375 if ($record = $this->getRecord($pid, $table, $uid)) {
1376 $records[$uid] = $record;
1377 }
1378 }
1379 return $records;
1380 }
1381
1382 /**
1383 * Gets an array with the uids of related records out of a list of items.
1384 * This list could contain more information than required. This methods just
1385 * extracts the uids.
1386 *
1387 * @param string $itemList The list of related child records
1388 * @return array An array with uids
1389 */
1390 protected function getRelatedRecordsUidArray($itemList) {
1391 $itemArray = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $itemList, 1);
1392 // Perform modification of the selected items array:
1393 foreach ($itemArray as $key => &$value) {
1394 $parts = explode('|', $value, 2);
1395 $value = $parts[0];
1396 }
1397 unset($value);
1398 return $itemArray;
1399 }
1400
1401 /**
1402 * Gets the difference between current localized structure and the original language structure.
1403 * If there are records which once were localized but don't exist in the original version anymore, the record row is marked with '__remove'.
1404 * If there are records which can be localized and exist only in the original version, the record row is marked with '__create' and '__virtual'.
1405 *
1406 * @param string $table The table name of the parent records
1407 * @param array $options Options defining what kind of records to display
1408 * @param array $recordsOriginal The uids of the child records of the original language
1409 * @param array $recordsLocalization The uids of the child records of the current localization
1410 * @return array Merged array of uids of the child records of both versions
1411 */
1412 protected function getLocalizationDifferences($table, array $options, array $recordsOriginal, array $recordsLocalization) {
1413 $records = array();
1414 $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
1415 // Compare original to localized version of the records:
1416 foreach ($recordsLocalization as $uid => $row) {
1417 // If the record points to a original translation which doesn't exist anymore, it could be removed:
1418 if (isset($row[$transOrigPointerField]) && $row[$transOrigPointerField] > 0) {
1419 $transOrigPointer = $row[$transOrigPointerField];
1420 if (isset($recordsOriginal[$transOrigPointer])) {
1421 unset($recordsOriginal[$transOrigPointer]);
1422 } elseif ($options['showRemoved']) {
1423 $row['__remove'] = TRUE;
1424 }
1425 }
1426 $records[$uid] = $row;
1427 }
1428 // Process the remaining records in the original unlocalized parent:
1429 if ($options['showPossible']) {
1430 foreach ($recordsOriginal as $uid => $row) {
1431 $row['__create'] = TRUE;
1432 $row['__virtual'] = TRUE;
1433 $records[$uid] = $row;
1434 }
1435 }
1436 return $records;
1437 }
1438
1439 /**
1440 * Get possible records.
1441 * Copied from TCEform and modified.
1442 *
1443 * @param string $table The table name of the record
1444 * @param string $field The field name which this element is supposed to edit
1445 * @param array $row The record data array where the value(s) for the field can be found
1446 * @param array $conf An array with additional configuration options.
1447 * @param string $checkForConfField For which field in the foreign_table the possible records should be fetched
1448 * @return mixed Array of possible record items; FALSE if type is "group/db", then everything could be "possible
1449 * @todo Define visibility
1450 */
1451 public function getPossibleRecords($table, $field, $row, $conf, $checkForConfField = 'foreign_selector') {
1452 // ctrl configuration from TCA:
1453 $tcaTableCtrl = $GLOBALS['TCA'][$table]['ctrl'];
1454 // Field configuration from TCA:
1455 $foreign_table = $conf['foreign_table'];
1456 $foreign_check = $conf[$checkForConfField];
1457 $foreignConfig = $this->getPossibleRecordsSelectorConfig($conf, $foreign_check);
1458 $PA = $foreignConfig['PA'];
1459 $config = $PA['fieldConf']['config'];
1460 if ($foreignConfig['type'] == 'select') {
1461 // Getting the selector box items from the system
1462 $selItems = $this->fObj->addSelectOptionsToItemArray($this->fObj->initItemArray($PA['fieldConf']), $PA['fieldConf'], $this->fObj->setTSconfig($table, $row), $field);
1463 // Possibly filter some items:
1464 $keepItemsFunc = create_function('$value', 'return $value[1];');
1465 $selItems = \TYPO3\CMS\Core\Utility\GeneralUtility::keepItemsInArray($selItems, $PA['fieldTSConfig']['keepItems'], $keepItemsFunc);
1466 // Possibly add some items:
1467 $selItems = $this->fObj->addItems($selItems, $PA['fieldTSConfig']['addItems.']);
1468 if (isset($config['itemsProcFunc']) && $config['itemsProcFunc']) {
1469 $selItems = $this->fObj->procItems($selItems, $PA['fieldTSConfig']['itemsProcFunc.'], $config, $table, $row, $field);
1470 }
1471 // Possibly remove some items:
1472 $removeItems = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $PA['fieldTSConfig']['removeItems'], 1);
1473 foreach ($selItems as $tk => $p) {
1474 // Checking languages and authMode:
1475 $languageDeny = $tcaTableCtrl['languageField'] && !strcmp($tcaTableCtrl['languageField'], $field) && !$GLOBALS['BE_USER']->checkLanguageAccess($p[1]);
1476 $authModeDeny = $config['form_type'] == 'select' && $config['authMode'] && !$GLOBALS['BE_USER']->checkAuthMode($table, $field, $p[1], $config['authMode']);
1477 if (in_array($p[1], $removeItems) || $languageDeny || $authModeDeny) {
1478 unset($selItems[$tk]);
1479 } elseif (isset($PA['fieldTSConfig']['altLabels.'][$p[1]])) {
1480 $selItems[$tk][0] = htmlspecialchars($this->fObj->sL($PA['fieldTSConfig']['altLabels.'][$p[1]]));
1481 }
1482 // Removing doktypes with no access:
1483 if (($table === 'pages' || $table === 'pages_language_overlay') && $field === 'doktype') {
1484 if (!($GLOBALS['BE_USER']->isAdmin() || \TYPO3\CMS\Core\Utility\GeneralUtility::inList($GLOBALS['BE_USER']->groupData['pagetypes_select'], $p[1]))) {
1485 unset($selItems[$tk]);
1486 }
1487 }
1488 }
1489 } else {
1490 $selItems = FALSE;
1491 }
1492 return $selItems;
1493 }
1494
1495 /**
1496 * Gets the uids of a select/selector that should be unique an have already been used.
1497 *
1498 * @param array $records All inline records on this level
1499 * @param array $conf The TCA field configuration of the inline field to be rendered
1500 * @param boolean $splitValue For usage with group/db, values come like "tx_table_123|Title%20abc", but we need "tx_table" and "123
1501 * @return array The uids, that have been used already and should be used unique
1502 * @todo Define visibility
1503 */
1504 public function getUniqueIds($records, $conf = array(), $splitValue = FALSE) {
1505 $uniqueIds = array();
1506 if (isset($conf['foreign_unique']) && $conf['foreign_unique'] && count($records)) {
1507 foreach ($records as $rec) {
1508 // Skip virtual records (e.g. shown in localization mode):
1509 if (!isset($rec['__virtual']) || !$rec['__virtual']) {
1510 $value = $rec[$conf['foreign_unique']];
1511 // Split the value and extract the table and uid:
1512 if ($splitValue) {
1513 $valueParts = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode('|', $value);
1514 $itemParts = explode('_', $valueParts[0]);
1515 $value = array(
1516 'uid' => array_pop($itemParts),
1517 'table' => implode('_', $itemParts)
1518 );
1519 }
1520 $uniqueIds[$rec['uid']] = $value;
1521 }
1522 }
1523 }
1524 return $uniqueIds;
1525 }
1526
1527 /**
1528 * Determines the corrected pid to be used for a new record.
1529 * The pid to be used can be defined by a Page TSconfig.
1530 *
1531 * @param string $table The table name
1532 * @param integer $parentPid The pid of the parent record
1533 * @return integer The corrected pid to be used for a new record
1534 */
1535 protected function getNewRecordPid($table, $parentPid = NULL) {
1536 $newRecordPid = $this->inlineFirstPid;
1537 $pageTS = \t3lib_beFunc::getPagesTSconfig($parentPid, TRUE);
1538 if (isset($pageTS['TCAdefaults.'][$table . '.']['pid']) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($pageTS['TCAdefaults.'][$table . '.']['pid'])) {
1539 $newRecordPid = $pageTS['TCAdefaults.'][$table . '.']['pid'];
1540 } elseif (isset($parentPid) && \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($parentPid)) {
1541 $newRecordPid = $parentPid;
1542 }
1543 return $newRecordPid;
1544 }
1545
1546 /**
1547 * Get a single record row for a TCA table from the database.
1548 * t3lib_transferData is used for "upgrading" the values, especially the relations.
1549 *
1550 * @param integer $pid The pid of the page the record should be stored (only relevant for NEW records)
1551 * @param string $table The table to fetch data from (= foreign_table)
1552 * @param string $uid The uid of the record to fetch, or the pid if a new record should be created
1553 * @param string $cmd The command to perform, empty or 'new'
1554 * @return array A record row from the database post-processed by t3lib_transferData
1555 * @todo Define visibility
1556 */
1557 public function getRecord($pid, $table, $uid, $cmd = '') {
1558 // Fetch workspace version of a record (if any):
1559 if ($cmd !== 'new' && $GLOBALS['BE_USER']->workspace !== 0) {
1560 $workspaceVersion = \TYPO3\CMS\Backend\Utility\BackendUtility::getWorkspaceVersionOfRecord($GLOBALS['BE_USER']->workspace, $table, $uid, 'uid');
1561 if ($workspaceVersion !== FALSE) {
1562 $uid = $workspaceVersion['uid'];
1563 }
1564 }
1565 $trData = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Form\\DataPreprocessor');
1566 $trData->addRawData = TRUE;
1567 $trData->lockRecords = 1;
1568 $trData->disableRTE = $GLOBALS['SOBE']->MOD_SETTINGS['disableRTE'];
1569 // If a new record should be created
1570 $trData->fetchRecord($table, $uid, $cmd === 'new' ? 'new' : '');
1571 $rec = reset($trData->regTableItems_data);
1572 return $rec;
1573 }
1574
1575 /**
1576 * Wrapper. Calls getRecord in case of a new record should be created.
1577 *
1578 * @param integer $pid The pid of the page the record should be stored (only relevant for NEW records)
1579 * @param string $table The table to fetch data from (= foreign_table)
1580 * @return array A record row from the database post-processed by t3lib_transferData
1581 * @todo Define visibility
1582 */
1583 public function getNewRecord($pid, $table) {
1584 $rec = $this->getRecord($pid, $table, $pid, 'new');
1585 $rec['uid'] = uniqid('NEW');
1586 $rec['pid'] = $this->getNewRecordPid($table, $pid);
1587 return $rec;
1588 }
1589
1590 /*******************************************************
1591 *
1592 * Structure stack for handling inline objects/levels
1593 *
1594 *******************************************************/
1595 /**
1596 * Add a new level on top of the structure stack. Other functions can access the
1597 * stack and determine, if there's possibly a endless loop.
1598 *
1599 * @param string $table The table name of the record
1600 * @param string $uid The uid of the record that embeds the inline data
1601 * @param string $field The field name which this element is supposed to edit
1602 * @param array $config The TCA-configuration of the inline field
1603 * @param array $parameters The full parameter array (PA)
1604 * @return void
1605 * @todo Define visibility
1606 */
1607 public function pushStructure($table, $uid, $field = '', $config = array(), array $parameters = array()) {
1608 $structure = array(
1609 'table' => $table,
1610 'uid' => $uid,
1611 'field' => $field,
1612 'config' => $config,
1613 'localizationMode' => \TYPO3\CMS\Backend\Utility\BackendUtility::getInlineLocalizationMode($table, $config),
1614 );
1615
1616 // Extract FlexForm parts (if any) from element name,
1617 // e.g. array('vDEF', 'lDEF', 'FlexField', 'vDEF')
1618 if (!empty($parameters['itemFormElName'])) {
1619 $flexFormParts = $this->extractFlexFormParts($parameters['itemFormElName']);
1620
1621 if ($flexFormParts !== NULL) {
1622 $structure['flexform'] = $flexFormParts;
1623 }
1624 }
1625
1626 $this->inlineStructure['stable'][] = $structure;
1627 $this->updateStructureNames();
1628 }
1629
1630 /**
1631 * Remove the item on top of the structure stack and return it.
1632 *
1633 * @return array The top item of the structure stack - array(<table>,<uid>,<field>,<config>)
1634 * @todo Define visibility
1635 */
1636 public function popStructure() {
1637 $popItem = NULL;
1638
1639 if (count($this->inlineStructure['stable'])) {
1640 $popItem = array_pop($this->inlineStructure['stable']);
1641 $this->updateStructureNames();
1642 }
1643 return $popItem;
1644 }
1645
1646 /**
1647 * For common use of DOM object-ids and form field names of a several inline-level,
1648 * these names/identifiers are preprocessed and set to $this->inlineNames.
1649 * This function is automatically called if a level is pushed to or removed from the
1650 * inline structure stack.
1651 *
1652 * @return void
1653 * @todo Define visibility
1654 */
1655 public function updateStructureNames() {
1656 $current = $this->getStructureLevel(-1);
1657 // If there are still more inline levels available
1658 if ($current !== FALSE) {
1659 $this->inlineNames = array(
1660 'form' => $this->prependFormFieldNames . $this->getStructureItemName($current, self::Disposal_AttributeName),
1661 'object' => $this->prependNaming . self::Structure_Separator . $this->inlineFirstPid . self::Structure_Separator . $this->getStructurePath()
1662 );
1663 } else {
1664 $this->inlineNames = array();
1665 }
1666 }
1667
1668 /**
1669 * Create a name/id for usage in HTML output of a level of the structure stack to be used in form names.
1670 *
1671 * @param array $levelData Array of a level of the structure stack (containing the keys table, uid and field)
1672 * @param string $disposal How the structure name is used (e.g. as <div id="..."> or <input name="..." />)
1673 * @return string The name/id of that level, to be used for HTML output
1674 * @todo Define visibility
1675 */
1676 public function getStructureItemName($levelData, $disposal = self::Disposal_AttributeId) {
1677 $name = NULL;
1678
1679 if (is_array($levelData)) {
1680 $parts = array($levelData['table'], $levelData['uid']);
1681
1682 if (!empty($levelData['field'])) {
1683 $parts[] = $levelData['field'];
1684 }
1685
1686 // Use in name attributes:
1687 if ($disposal === self::Disposal_AttributeName) {
1688 if (!empty($levelData['field']) && !empty($levelData['flexform']) && $this->getStructureLevel(-1) === $levelData) {
1689 $parts[] = implode('][', $levelData['flexform']);
1690 }
1691 $name = '[' . implode('][', $parts) . ']';
1692 // Use in object id attributes:
1693 } else {
1694 $name = implode(self::Structure_Separator, $parts);
1695
1696 if (!empty($levelData['field']) && !empty($levelData['flexform'])) {
1697 array_unshift($levelData['flexform'], $name);
1698 $name = implode(self::FlexForm_Separator, $levelData['flexform']);
1699 }
1700 }
1701 }
1702
1703 return $name;
1704 }
1705
1706 /**
1707 * Get a level from the stack and return the data.
1708 * If the $level value is negative, this function works top-down,
1709 * if the $level value is positive, this function works bottom-up.
1710 *
1711 * @param integer $level Which level to return
1712 * @return array The item of the stack at the requested level
1713 * @todo Define visibility
1714 */
1715 public function getStructureLevel($level) {
1716 $level = $this->calculateStructureLevel($level);
1717
1718 if ($level !== FALSE) {
1719 return $this->inlineStructure['stable'][$level];
1720 } else {
1721 return FALSE;
1722 }
1723 }
1724
1725 /**
1726 * Calculates structure level.
1727 *
1728 * @param integer $level Which level to return
1729 * @return boolean|integer
1730 */
1731 protected function calculateStructureLevel($level) {
1732 $result = FALSE;
1733
1734 $inlineStructureCount = count($this->inlineStructure['stable']);
1735 if ($level < 0) {
1736 $level = $inlineStructureCount + $level;
1737 }
1738 if ($level >= 0 && $level < $inlineStructureCount) {
1739 $result = $level;
1740 }
1741
1742 return $result;
1743 }
1744
1745 /**
1746 * Get the identifiers of a given depth of level, from the top of the stack to the bottom.
1747 * An identifier looks like "<table>-<uid>-<field>".
1748 *
1749 * @param integer $structureDepth How much levels to output, beginning from the top of the stack
1750 * @return string The path of identifiers
1751 * @todo Define visibility
1752 */
1753 public function getStructurePath($structureDepth = -1) {
1754 $structureLevels = array();
1755 $structureCount = count($this->inlineStructure['stable']);
1756 if ($structureDepth < 0 || $structureDepth > $structureCount) {
1757 $structureDepth = $structureCount;
1758 }
1759 for ($i = 1; $i <= $structureDepth; $i++) {
1760 array_unshift($structureLevels, $this->getStructureItemName($this->getStructureLevel(-$i), self::Disposal_AttributeId));
1761 }
1762 return implode(self::Structure_Separator, $structureLevels);
1763 }
1764
1765 /**
1766 * Convert the DOM object-id of an inline container to an array.
1767 * The object-id could look like 'data-parentPageId-tx_mmftest_company-1-employees'.
1768 * The result is written to $this->inlineStructure.
1769 * There are two keys:
1770 * - 'stable': Containing full qualified identifiers (table, uid and field)
1771 * - 'unstable': Containting partly filled data (e.g. only table and possibly field)
1772 *
1773 * @param string $domObjectId The DOM object-id
1774 * @param boolean $loadConfig Load the TCA configuration for that level (default: TRUE)
1775 * @return void
1776 * @todo Define visibility
1777 */
1778 public function parseStructureString($string, $loadConfig = TRUE) {
1779 $unstable = array();
1780 $vector = array('table', 'uid', 'field');
1781
1782 // Substitute FlexForm additon and make parsing a bit easier
1783 $string = str_replace(self::FlexForm_Separator, self::FlexForm_Substitute, $string);
1784 // The starting pattern of an object identifer (e.g. "data-<firstPidValue>-<anything>)
1785 $pattern = '/^' . $this->prependNaming . self::Structure_Separator . '(.+?)' . self::Structure_Separator . '(.+)$/';
1786
1787 if (preg_match($pattern, $string, $match)) {
1788 $this->inlineFirstPid = $match[1];
1789 $parts = explode(self::Structure_Separator, $match[2]);
1790 $partsCnt = count($parts);
1791 for ($i = 0; $i < $partsCnt; $i++) {
1792 if ($i > 0 && $i % 3 == 0) {
1793 // Load the TCA configuration of the table field and store it in the stack
1794 if ($loadConfig) {
1795 \TYPO3\CMS\Core\Utility\GeneralUtility::loadTCA($unstable['table']);
1796 $unstable['config'] = $GLOBALS['TCA'][$unstable['table']]['columns'][$unstable['field']]['config'];
1797 // Fetch TSconfig:
1798 $TSconfig = $this->fObj->setTSconfig($unstable['table'], array('uid' => $unstable['uid'], 'pid' => $this->inlineFirstPid), $unstable['field']);
1799 // Override TCA field config by TSconfig:
1800 if (!$TSconfig['disabled']) {
1801 $unstable['config'] = $this->fObj->overrideFieldConf($unstable['config'], $TSconfig);
1802 }
1803 $unstable['localizationMode'] = \TYPO3\CMS\Backend\Utility\BackendUtility::getInlineLocalizationMode($unstable['table'], $unstable['config']);
1804 }
1805
1806 // Extract FlexForm from field part (if any)
1807 if (strpos($unstable['field'], self::FlexForm_Substitute) !== FALSE) {
1808 $fieldParts = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(self::FlexForm_Substitute, $unstable['field']);
1809 $unstable['field'] = array_shift($fieldParts);
1810 // FlexForm parts start with data:
1811 if (count($fieldParts) > 0 && $fieldParts[0] === 'data') {
1812 $unstable['flexform'] = $fieldParts;
1813 }
1814 }
1815
1816 $this->inlineStructure['stable'][] = $unstable;
1817 $unstable = array();
1818 }
1819 $unstable[$vector[$i % 3]] = $parts[$i];
1820 }
1821 $this->updateStructureNames();
1822 if (count($unstable)) {
1823 $this->inlineStructure['unstable'] = $unstable;
1824 }
1825 }
1826 }
1827
1828 /*******************************************************
1829 *
1830 * Helper functions
1831 *
1832 *******************************************************/
1833 /**
1834 * Does some checks on the TCA configuration of the inline field to render.
1835 *
1836 * @param array $config Reference to the TCA field configuration
1837 * @param string $table The table name of the record
1838 * @param string $field The field name which this element is supposed to edit
1839 * @param array $row The record data array of the parent
1840 * @return boolean If critical configuration errors were found, FALSE is returned
1841 * @todo Define visibility
1842 */
1843 public function checkConfiguration(&$config) {
1844 $foreign_table = $config['foreign_table'];
1845 // An inline field must have a foreign_table, if not, stop all further inline actions for this field:
1846 if (!$foreign_table || !is_array($GLOBALS['TCA'][$foreign_table])) {
1847 return FALSE;
1848 }
1849 // Init appearance if not set:
1850 if (!isset($config['appearance']) || !is_array($config['appearance'])) {
1851 $config['appearance'] = array();
1852 }
1853 // Set the position/appearance of the "Create new record" link:
1854 if (isset($config['foreign_selector']) && $config['foreign_selector'] && (!isset($config['appearance']['useCombination']) || !$config['appearance']['useCombination'])) {
1855 $config['appearance']['levelLinksPosition'] = 'none';
1856 } elseif (!isset($config['appearance']['levelLinksPosition']) || !in_array($config['appearance']['levelLinksPosition'], array('top', 'bottom', 'both', 'none'))) {
1857 $config['appearance']['levelLinksPosition'] = 'top';
1858 }
1859 // Defines which controls should be shown in header of each record:
1860 $enabledControls = array(
1861 'info' => TRUE,
1862 'new' => TRUE,
1863 'dragdrop' => TRUE,
1864 'sort' => TRUE,
1865 'hide' => TRUE,
1866 'delete' => TRUE,
1867 'localize' => TRUE
1868 );
1869 if (isset($config['appearance']['enabledControls']) && is_array($config['appearance']['enabledControls'])) {
1870 $config['appearance']['enabledControls'] = array_merge($enabledControls, $config['appearance']['enabledControls']);
1871 } else {
1872 $config['appearance']['enabledControls'] = $enabledControls;
1873 }
1874 return TRUE;
1875 }
1876
1877 /**
1878 * Checks the page access rights (Code for access check mostly taken from alt_doc.php)
1879 * as well as the table access rights of the user.
1880 *
1881 * @param string $cmd The command that sould be performed ('new' or 'edit')
1882 * @param string $table The table to check access for
1883 * @param string $theUid The record uid of the table
1884 * @return boolean Returns TRUE is the user has access, or FALSE if not
1885 * @todo Define visibility
1886 */
1887 public function checkAccess($cmd, $table, $theUid) {
1888 // 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...)
1889 // First, resetting flags.
1890 $hasAccess = 0;
1891 $deniedAccessReason = '';
1892 // Admin users always have acces:
1893 if ($GLOBALS['BE_USER']->isAdmin()) {
1894 return TRUE;
1895 }
1896 // If the command is to create a NEW record...:
1897 if ($cmd == 'new') {
1898 // If the pid is numerical, check if it's possible to write to this page:
1899 if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->inlineFirstPid)) {
1900 $calcPRec = \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord('pages', $this->inlineFirstPid);
1901 if (!is_array($calcPRec)) {
1902 return FALSE;
1903 }
1904 // Permissions for the parent page
1905 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
1906 // If pages:
1907 if ($table == 'pages') {
1908 // Are we allowed to create new subpages?
1909 $hasAccess = $CALC_PERMS & 8 ? 1 : 0;
1910 } else {
1911 // Are we allowed to edit content on this page?
1912 $hasAccess = $CALC_PERMS & 16 ? 1 : 0;
1913 }
1914 } else {
1915 $hasAccess = 1;
1916 }
1917 } else {
1918 // Edit:
1919 $calcPRec = \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord($table, $theUid);
1920 \TYPO3\CMS\Backend\Utility\BackendUtility::fixVersioningPid($table, $calcPRec);
1921 if (is_array($calcPRec)) {
1922 // If pages:
1923 if ($table == 'pages') {
1924 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
1925 $hasAccess = $CALC_PERMS & 2 ? 1 : 0;
1926 } else {
1927 // Fetching pid-record first.
1928 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms(\TYPO3\CMS\Backend\Utility\BackendUtility::getRecord('pages', $calcPRec['pid']));
1929 $hasAccess = $CALC_PERMS & 16 ? 1 : 0;
1930 }
1931 // Check internals regarding access:
1932 if ($hasAccess) {
1933 $hasAccess = $GLOBALS['BE_USER']->recordEditAccessInternals($table, $calcPRec);
1934 }
1935 }
1936 }
1937 if (!$GLOBALS['BE_USER']->check('tables_modify', $table)) {
1938 $hasAccess = 0;
1939 }
1940 if (!$hasAccess) {
1941 $deniedAccessReason = $GLOBALS['BE_USER']->errorMsg;
1942 if ($deniedAccessReason) {
1943 debug($deniedAccessReason);
1944 }
1945 }
1946 return $hasAccess ? TRUE : FALSE;
1947 }
1948
1949 /**
1950 * Check the keys and values in the $compare array against the ['config'] part of the top level of the stack.
1951 * A boolean value is return depending on how the comparison was successful.
1952 *
1953 * @param array $compare Keys and values to compare to the ['config'] part of the top level of the stack
1954 * @return boolean Whether the comparison was successful
1955 * @see arrayCompareComplex
1956 * @todo Define visibility
1957 */
1958 public function compareStructureConfiguration($compare) {
1959 $level = $this->getStructureLevel(-1);
1960 $result = $this->arrayCompareComplex($level, $compare);
1961 return $result;
1962 }
1963
1964 /**
1965 * Normalize a relation "uid" published by transferData, like "1|Company%201"
1966 *
1967 * @param string $string A transferData reference string, containing the uid
1968 * @return string The normalized uid
1969 * @todo Define visibility
1970 */
1971 public function normalizeUid($string) {
1972 $parts = explode('|', $string);
1973 return $parts[0];
1974 }
1975
1976 /**
1977 * Wrap the HTML code of a section with a table tag.
1978 *
1979 * @param string $section The HTML code to be wrapped
1980 * @param array $styleAttrs Attributes for the style argument in the table tag
1981 * @param array $tableAttrs Attributes for the table tag (like width, border, etc.)
1982 * @return string The wrapped HTML code
1983 * @todo Define visibility
1984 */
1985 public function wrapFormsSection($section, $styleAttrs = array(), $tableAttrs = array()) {
1986 $style = '';
1987 $table = '';
1988 foreach ($styleAttrs as $key => $value) {
1989 $style .= ($style ? ' ' : '') . $key . ': ' . htmlspecialchars($value) . '; ';
1990 }
1991 if ($style) {
1992 $style = ' style="' . $style . '"';
1993 }
1994 if (!$tableAttrs['background'] && $this->fObj->borderStyle[2]) {
1995 $tableAttrs['background'] = $this->backPath . $this->borderStyle[2];
1996 }
1997 if (!$tableAttrs['class'] && $this->borderStyle[3]) {
1998 $tableAttrs['class'] = $this->borderStyle[3];
1999 }
2000 foreach ($tableAttrs as $key => $value) {
2001 $table .= ($table ? ' ' : '') . $key . '="' . htmlspecialchars($value) . '"';
2002 }
2003 $out = '<table ' . $table . $style . '>' . $section . '</table>';
2004 return $out;
2005 }
2006
2007 /**
2008 * Checks if the $table is the child of a inline type AND the $field is the label field of this table.
2009 * This function is used to dynamically update the label while editing. This has no effect on labels,
2010 * that were processed by a TCEmain-hook on saving.
2011 *
2012 * @param string $table The table to check
2013 * @param string $field The field on this table to check
2014 * @return boolean Is inline child and field is responsible for the label
2015 * @todo Define visibility
2016 */
2017 public function isInlineChildAndLabelField($table, $field) {
2018 $level = $this->getStructureLevel(-1);
2019 if ($level['config']['foreign_label']) {
2020 $label = $level['config']['foreign_label'];
2021 } else {
2022 $label = $GLOBALS['TCA'][$table]['ctrl']['label'];
2023 }
2024 return $level['config']['foreign_table'] === $table && $label == $field ? TRUE : FALSE;
2025 }
2026
2027 /**
2028 * Get the depth of the stable structure stack.
2029 * (count($this->inlineStructure['stable'])
2030 *
2031 * @return integer The depth of the structure stack
2032 * @todo Define visibility
2033 */
2034 public function getStructureDepth() {
2035 return count($this->inlineStructure['stable']);
2036 }
2037
2038 /**
2039 * Handles complex comparison requests on an array.
2040 * A request could look like the following:
2041 *
2042 * $searchArray = array(
2043 * '%AND' => array(
2044 * 'key1' => 'value1',
2045 * 'key2' => 'value2',
2046 * '%OR' => array(
2047 * 'subarray' => array(
2048 * 'subkey' => 'subvalue'
2049 * ),
2050 * 'key3' => 'value3',
2051 * 'key4' => 'value4'
2052 * )
2053 * )
2054 * );
2055 *
2056 * It is possible to use the array keys '%AND.1', '%AND.2', etc. to prevent
2057 * overwriting the sub-array. It could be neccessary, if you use complex comparisons.
2058 *
2059 * The example above means, key1 *AND* key2 (and their values) have to match with
2060 * the $subjectArray and additional one *OR* key3 or key4 have to meet the same
2061 * condition.
2062 * It is also possible to compare parts of a sub-array (e.g. "subarray"), so this
2063 * function recurses down one level in that sub-array.
2064 *
2065 * @param array $subjectArray The array to search in
2066 * @param array $searchArray The array with keys and values to search for
2067 * @param string $type Use '%AND' or '%OR' for comparision
2068 * @return boolean The result of the comparison
2069 * @todo Define visibility
2070 */
2071 public function arrayCompareComplex($subjectArray, $searchArray, $type = '') {
2072 $localMatches = 0;
2073 $localEntries = 0;
2074 if (is_array($searchArray) && count($searchArray)) {
2075 // If no type was passed, try to determine
2076 if (!$type) {
2077 reset($searchArray);
2078 $type = key($searchArray);
2079 $searchArray = current($searchArray);
2080 }
2081 // We use '%AND' and '%OR' in uppercase
2082 $type = strtoupper($type);
2083 // Split regular elements from sub elements
2084 foreach ($searchArray as $key => $value) {
2085 $localEntries++;
2086 // Process a sub-group of OR-conditions
2087 if ($key == '%OR') {
2088 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%OR') ? 1 : 0;
2089 } elseif ($key == '%AND') {
2090 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%AND') ? 1 : 0;
2091 } elseif (is_array($value) && $this->isAssociativeArray($searchArray)) {
2092 $localMatches += $this->arrayCompareComplex($subjectArray[$key], $value, $type) ? 1 : 0;
2093 } elseif (is_array($value)) {
2094 $localMatches += $this->arrayCompareComplex($subjectArray, $value, $type) ? 1 : 0;
2095 } else {
2096 if (isset($subjectArray[$key]) && isset($value)) {
2097 // Boolean match:
2098 if (is_bool($value)) {
2099 $localMatches += !($subjectArray[$key] xor $value) ? 1 : 0;
2100 } elseif (is_numeric($subjectArray[$key]) && is_numeric($value)) {
2101 $localMatches += $subjectArray[$key] == $value ? 1 : 0;
2102 } else {
2103 $localMatches += $subjectArray[$key] === $value ? 1 : 0;
2104 }
2105 }
2106 }
2107 // If one or more matches are required ('OR'), return TRUE after the first successful match
2108 if ($type == '%OR' && $localMatches > 0) {
2109 return TRUE;
2110 }
2111 // If all matches are required ('AND') and we have no result after the first run, return FALSE
2112 if ($type == '%AND' && $localMatches == 0) {
2113 return FALSE;
2114 }
2115 }
2116 }
2117 // Return the result for '%AND' (if nothing was checked, TRUE is returned)
2118 return $localEntries == $localMatches ? TRUE : FALSE;
2119 }
2120
2121 /**
2122 * Checks whether an object is an associative array.
2123 *
2124 * @param mixed $object The object to be checked
2125 * @return boolean Returns TRUE, if the object is an associative array
2126 * @todo Define visibility
2127 */
2128 public function isAssociativeArray($object) {
2129 return is_array($object) && count($object) && array_keys($object) !== range(0, sizeof($object) - 1) ? TRUE : FALSE;
2130 }
2131
2132 /**
2133 * Remove an element from an array.
2134 *
2135 * @param mixed $needle The element to be removed.
2136 * @param array $haystack The array the element should be removed from.
2137 * @param mixed $strict Search elements strictly.
2138 * @return array The array $haystack without the $needle
2139 * @todo Define visibility
2140 */
2141 public function removeFromArray($needle, $haystack, $strict = NULL) {
2142 $pos = array_search($needle, $haystack, $strict);
2143 if ($pos !== FALSE) {
2144 unset($haystack[$pos]);
2145 }
2146 return $haystack;
2147 }
2148
2149 /**
2150 * Makes a flat array from the $possibleRecords array.
2151 * The key of the flat array is the value of the record,
2152 * the value of the flat array is the label of the record.
2153 *
2154 * @param array $possibleRecords The possibleRecords array (for select fields)
2155 * @return mixed A flat array with key=uid, value=label; if $possibleRecords isn't an array, FALSE is returned.
2156 * @todo Define visibility
2157 */
2158 public function getPossibleRecordsFlat($possibleRecords) {
2159 $flat = FALSE;
2160 if (is_array($possibleRecords)) {
2161 $flat = array();
2162 foreach ($possibleRecords as $record) {
2163 $flat[$record[1]] = $record[0];
2164 }
2165 }
2166 return $flat;
2167 }
2168
2169 /**
2170 * Determine the configuration and the type of a record selector.
2171 *
2172 * @param array $conf TCA configuration of the parent(!) field
2173 * @return array Associative array with the keys 'PA' and 'type', both are FALSE if the selector was not valid.
2174 * @todo Define visibility
2175 */
2176 public function getPossibleRecordsSelectorConfig($conf, $field = '') {
2177 $foreign_table = $conf['foreign_table'];
2178 $foreign_selector = $conf['foreign_selector'];
2179 $PA = FALSE;
2180 $type = FALSE;
2181 $table = FALSE;
2182 $selector = FALSE;
2183 if ($field) {
2184 $PA = array();
2185 $PA['fieldConf'] = $GLOBALS['TCA'][$foreign_table]['columns'][$field];
2186 if ($PA['fieldConf'] && $conf['foreign_selector_fieldTcaOverride']) {
2187 $PA['fieldConf'] = \TYPO3\CMS\Core\Utility\GeneralUtility::array_merge_recursive_overrule($PA['fieldConf'], $conf['foreign_selector_fieldTcaOverride']);
2188 }
2189 $PA['fieldConf']['config']['form_type'] = $PA['fieldConf']['config']['form_type'] ? $PA['fieldConf']['config']['form_type'] : $PA['fieldConf']['config']['type'];
2190 // Using "form_type" locally in this script
2191 $PA['fieldTSConfig'] = $this->fObj->setTSconfig($foreign_table, array(), $field);
2192 $config = $PA['fieldConf']['config'];
2193 // Determine type of Selector:
2194 $type = $this->getPossibleRecordsSelectorType($config);
2195 // Return table on this level:
2196 $table = $type == 'select' ? $config['foreign_table'] : $config['allowed'];
2197 // Return type of the selector if foreign_selector is defined and points to the same field as in $field:
2198 if ($foreign_selector && $foreign_selector == $field && $type) {
2199 $selector = $type;
2200 }
2201 }
2202 return array(
2203 'PA' => $PA,
2204 'type' => $type,
2205 'table' => $table,
2206 'selector' => $selector
2207 );
2208 }
2209
2210 /**
2211 * Determine the type of a record selector, e.g. select or group/db.
2212 *
2213 * @param array $config TCE configuration of the selector
2214 * @return mixed The type of the selector, 'select' or 'groupdb' - FALSE not valid
2215 * @todo Define visibility
2216 */
2217 public function getPossibleRecordsSelectorType($config) {
2218 $type = FALSE;
2219 if ($config['type'] == 'select') {
2220 $type = 'select';
2221 } elseif ($config['type'] == 'group' && $config['internal_type'] == 'db') {
2222 $type = 'groupdb';
2223 }
2224 return $type;
2225 }
2226
2227 /**
2228 * Check, if a field should be skipped, that was defined to be handled as foreign_field or foreign_sortby of
2229 * the parent record of the "inline"-type - if so, we have to skip this field - the rendering is done via "inline" as hidden field
2230 *
2231 * @param string $table The table name
2232 * @param string $field The field name
2233 * @param array $row The record row from the database
2234 * @param array $config TCA configuration of the field
2235 * @return boolean Determines whether the field should be skipped.
2236 * @todo Define visibility
2237 */
2238 public function skipField($table, $field, $row, $config) {
2239 $skipThisField = FALSE;
2240 if ($this->getStructureDepth()) {
2241 $searchArray = array(
2242 '%OR' => array(
2243 'config' => array(
2244 0 => array(
2245 '%AND' => array(
2246 'foreign_table' => $table,
2247 '%OR' => array(
2248 '%AND' => array(
2249 'appearance' => array('useCombination' => TRUE),
2250 'foreign_selector' => $field
2251 ),
2252 'MM' => $config['MM']
2253 )
2254 )
2255 ),
2256 1 => array(
2257 '%AND' => array(
2258 'foreign_table' => $config['foreign_table'],
2259 'foreign_selector' => $config['foreign_field']
2260 )
2261 )
2262 )
2263 )
2264 );
2265 // Get the parent record from structure stack
2266 $level = $this->getStructureLevel(-1);
2267 // If we have symmetric fields, check on which side we are and hide fields, that are set automatically:
2268 if (\TYPO3\CMS\Core\Database\RelationHandler::isOnSymmetricSide($level['uid'], $level['config'], $row)) {
2269 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_field'] = $field;
2270 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_sortby'] = $field;
2271 } else {
2272 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_field'] = $field;
2273 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_sortby'] = $field;
2274 }
2275 $skipThisField = $this->compareStructureConfiguration($searchArray, TRUE);
2276 }
2277 return $skipThisField;
2278 }
2279
2280 /**
2281 * Checks if a uid of a child table is in the inline view settings.
2282 *
2283 * @param string $table Name of the child table
2284 * @param integer $uid uid of the the child record
2285 * @return boolean TRUE=expand, FALSE=collapse
2286 * @todo Define visibility
2287 */
2288 public function getExpandedCollapsedState($table, $uid) {
2289 if (isset($this->inlineView[$table]) && is_array($this->inlineView[$table])) {
2290 if (in_array($uid, $this->inlineView[$table]) !== FALSE) {
2291 return TRUE;
2292 }
2293 }
2294 return FALSE;
2295 }
2296
2297 /**
2298 * Update expanded/collapsed states on new inline records if any.
2299 *
2300 * @param array $uc The uc array to be processed and saved (by reference)
2301 * @param \TYPO3\CMS\Core\DataHandling\DataHandler $tce Instance of TCEmain that saved data before
2302 * @return void
2303 * @todo Define visibility
2304 */
2305 public function updateInlineView(&$uc, $tce) {
2306 if (isset($uc['inlineView']) && is_array($uc['inlineView'])) {
2307 $inlineView = (array) unserialize($GLOBALS['BE_USER']->uc['inlineView']);
2308 foreach ($uc['inlineView'] as $topTable => $topRecords) {
2309 foreach ($topRecords as $topUid => $childElements) {
2310 foreach ($childElements as $childTable => $childRecords) {
2311 $uids = array_keys($tce->substNEWwithIDs_table, $childTable);
2312 if (count($uids)) {
2313 $newExpandedChildren = array();
2314 foreach ($childRecords as $childUid => $state) {
2315 if ($state && in_array($childUid, $uids)) {
2316 $newChildUid = $tce->substNEWwithIDs[$childUid];
2317 $newExpandedChildren[] = $newChildUid;
2318 }
2319 }
2320 // Add new expanded child records to UC (if any):
2321 if (count($newExpandedChildren)) {
2322 $inlineViewCurrent = &$inlineView[$topTable][$topUid][$childTable];
2323 if (is_array($inlineViewCurrent)) {
2324 $inlineViewCurrent = array_unique(array_merge($inlineViewCurrent, $newExpandedChildren));
2325 } else {
2326 $inlineViewCurrent = $newExpandedChildren;
2327 }
2328 }
2329 }
2330 }
2331 }
2332 }
2333 $GLOBALS['BE_USER']->uc['inlineView'] = serialize($inlineView);
2334 $GLOBALS['BE_USER']->writeUC();
2335 }
2336 }
2337
2338 /**
2339 * Returns the the margin in pixels, that is used for each new inline level.
2340 *
2341 * @return integer A pixel value for the margin of each new inline level.
2342 * @todo Define visibility
2343 */
2344 public function getLevelMargin() {
2345 $margin = ($this->inlineStyles['margin-right'] + 1) * 2;
2346 return $margin;
2347 }
2348
2349 /**
2350 * Parses the HTML tags that would have been inserted to the <head> of a HTML document and returns the found tags as multidimensional array.
2351 *
2352 * @return array The parsed tags with their attributes and innerHTML parts
2353 */
2354 protected function getHeadTags() {
2355 $headTags = array();
2356 $headDataRaw = $this->fObj->JStop() . $this->getJavaScriptAndStyleSheetsOfPageRenderer();
2357 if ($headDataRaw) {
2358 // Create instance of the HTML parser:
2359 $parseObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Html\\HtmlParser');
2360 // Removes script wraps:
2361 $headDataRaw = str_replace(array('/*<![CDATA[*/', '/*]]>*/'), '', $headDataRaw);
2362 // Removes leading spaces of a multiline string:
2363 $headDataRaw = trim(preg_replace('/(^|\\r|\\n)( |\\t)+/', '$1', $headDataRaw));
2364 // Get script and link tags:
2365 $tags = array_merge($parseObj->getAllParts($parseObj->splitTags('link', $headDataRaw)), $parseObj->getAllParts($parseObj->splitIntoBlock('script', $headDataRaw)));
2366 foreach ($tags as $tagData) {
2367 $tagAttributes = $parseObj->get_tag_attributes($parseObj->getFirstTag($tagData), TRUE);
2368 $headTags[] = array(
2369 'name' => $parseObj->getFirstTagName($tagData),
2370 'attributes' => $tagAttributes[0],
2371 'innerHTML' => $parseObj->removeFirstAndLastTag($tagData)
2372 );
2373 }
2374 }
2375 return $headTags;
2376 }
2377
2378 /**
2379 * Gets the JavaScript of the pageRenderer.
2380 * This can be used to extract newly added files which have been added
2381 * during an AJAX request. Due to the spread possibilities of the pageRenderer
2382 * to add JavaScript rendering and extracting seems to be the easiest way.
2383 *
2384 * @return string
2385 */
2386 protected function getJavaScriptAndStyleSheetsOfPageRenderer() {
2387 /** @var $pageRenderer \TYPO3\CMS\Core\Page\PageRenderer */
2388 $pageRenderer = clone $GLOBALS['SOBE']->doc->getPageRenderer();
2389 $pageRenderer->setCharSet($GLOBALS['LANG']->charSet);
2390 $pageRenderer->setTemplateFile(TYPO3_mainDir . 'templates/helper_javascript_css.html');
2391 $javaScriptAndStyleSheets = $pageRenderer->render();
2392 return $javaScriptAndStyleSheets;
2393 }
2394
2395 /**
2396 * Wraps a text with an anchor and returns the HTML representation.
2397 *
2398 * @param string $text The text to be wrapped by an anchor
2399 * @param string $link The link to be used in the anchor
2400 * @param array $attributes Array of attributes to be used in the anchor
2401 * @return string The wrapped texted as HTML representation
2402 */
2403 protected function wrapWithAnchor($text, $link, $attributes = array()) {
2404 $link = trim($link);
2405 $result = '<a href="' . ($link ? $link : '#') . '"';
2406 foreach ($attributes as $key => $value) {
2407 $result .= ' ' . $key . '="' . htmlspecialchars(trim($value)) . '"';
2408 }
2409 $result .= '>' . $text . '</a>';
2410 return $result;
2411 }
2412
2413 /**
2414 * Extracts FlexForm parts of a form element name like
2415 * data[table][uid][field][sDEF][lDEF][FlexForm][vDEF]
2416 *
2417 * @param string $formElementName The form element name
2418 * @return array|NULL
2419 */
2420 protected function extractFlexFormParts($formElementName) {
2421 $flexFormParts = NULL;
2422
2423 $matches = array();
2424 $prefix = preg_quote($this->fObj->prependFormFieldNames, '#');
2425
2426 if (preg_match('#^' . $prefix . '(?:\[[^]]+\]){3}(\[data\](?:\[[^]]+\]){4,})$#', $formElementName, $matches)) {
2427 $flexFormParts = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(
2428 '][',
2429 trim($matches[1], '[]')
2430 );
2431 }
2432
2433 return $flexFormParts;
2434 }
2435
2436 }
2437
2438
2439 ?>