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