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