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