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