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