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