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