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