0c1c7add6cb4e8b4d9c14f3cfdf949cda21cf56f
[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 $fileRecord = $this->getRecord(0, $selConfig['table'], $foreignUid);
1267
1268 if (!$this->checkFileTypeAccessForField($selConfig, $fileRecord)) {
1269 return $this->getErrorMessageForAJAX('File extension ' . $fileRecord['extension'] . ' is not allowed here!');
1270 }
1271 }
1272 // The HTML-object-id's prefix of the dynamically created record
1273 $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $current['table'];
1274 $objectId = $objectPrefix . self::Structure_Separator . $record['uid'];
1275 // Render the foreign record that should passed back to browser
1276 $item = $this->renderForeignRecord($parent['uid'], $record, $config);
1277 if ($item === FALSE) {
1278 return $this->getErrorMessageForAJAX('Access denied');
1279 }
1280 if (!$current['uid']) {
1281 $jsonArray = array(
1282 'data' => $item,
1283 'scriptCall' => array(
1284 'inline.domAddNewRecord(\'bottom\',\'' . $this->inlineNames['object'] . '_records\',\'' . $objectPrefix . '\',json.data);',
1285 'inline.memorizeAddRecord(\'' . $objectPrefix . '\',\'' . $record['uid'] . '\',null,\'' . $foreignUid . '\');'
1286 )
1287 );
1288 } else {
1289 $jsonArray = array(
1290 'data' => $item,
1291 'scriptCall' => array(
1292 'inline.domAddNewRecord(\'after\',\'' . $domObjectId . '_div' . '\',\'' . $objectPrefix . '\',json.data);',
1293 'inline.memorizeAddRecord(\'' . $objectPrefix . '\',\'' . $record['uid'] . '\',\'' . $current['uid'] . '\',\'' . $foreignUid . '\');'
1294 )
1295 );
1296 }
1297 $this->getCommonScriptCalls($jsonArray, $config);
1298 // Collapse all other records if requested:
1299 if (!$collapseAll && $expandSingle) {
1300 $jsonArray['scriptCall'][] = 'inline.collapseAllRecords(\'' . $objectId . '\', \'' . $objectPrefix . '\', \'' . $record['uid'] . '\');';
1301 }
1302 // Tell the browser to scroll to the newly created record
1303 $jsonArray['scriptCall'][] = 'Element.scrollTo(\'' . $objectId . '_div\');';
1304 // Fade out and fade in the new record in the browser view to catch the user's eye
1305 $jsonArray['scriptCall'][] = 'inline.fadeOutFadeIn(\'' . $objectId . '_div\');';
1306 // Remove the current level also from the dynNestedStack of TCEforms:
1307 $this->fObj->popFromDynNestedStack();
1308 // Return the JSON array:
1309 return $jsonArray;
1310 }
1311
1312 /**
1313 * Checks if a record selector may select a certain file type
1314 *
1315 * @param array $selectorConfiguration
1316 * @param array $fileRecord
1317 * @return bool
1318 */
1319 protected function checkFileTypeAccessForField(array $selectorConfiguration, array $fileRecord) {
1320 if (isset($selectorConfiguration['PA']['fieldConf']['config']['appearance']['elementBrowserAllowed'])) {
1321 $allowedFileExtensions = GeneralUtility::trimExplode(
1322 ',',
1323 $selectorConfiguration['PA']['fieldConf']['config']['appearance']['elementBrowserAllowed'],
1324 TRUE
1325 );
1326 if (!in_array($fileRecord['extension'], $allowedFileExtensions, TRUE)) {
1327 return FALSE;
1328 }
1329 }
1330 return TRUE;
1331 }
1332
1333 /**
1334 * Handle AJAX calls to localize all records of a parent, localize a single record or to synchronize with the original language parent.
1335 *
1336 * @param string $domObjectId The calling object in hierarchy, that requested a new record.
1337 * @param mixed $type Defines the type 'localize' or 'synchronize' (string) or a single uid to be localized (int)
1338 * @return array An array to be used for JSON
1339 */
1340 protected function synchronizeLocalizeRecords($domObjectId, $type) {
1341 $jsonArray = FALSE;
1342 if (GeneralUtility::inList('localize,synchronize', $type) || MathUtility::canBeInterpretedAsInteger($type)) {
1343 // The current level:
1344 $current = $this->inlineStructure['unstable'];
1345 // The parent level:
1346 $parent = $this->getStructureLevel(-1);
1347 $parentRecord = $this->getRecord(0, $parent['table'], $parent['uid']);
1348 $cmd = array();
1349 $cmd[$parent['table']][$parent['uid']]['inlineLocalizeSynchronize'] = $parent['field'] . ',' . $type;
1350 /** @var $tce \TYPO3\CMS\Core\DataHandling\DataHandler */
1351 $tce = GeneralUtility::makeInstance(\TYPO3\CMS\Core\DataHandling\DataHandler::class);
1352 $tce->stripslashes_values = FALSE;
1353 $tce->start(array(), $cmd);
1354 $tce->process_cmdmap();
1355 $newItemList = $tce->registerDBList[$parent['table']][$parent['uid']][$parent['field']];
1356 unset($tce);
1357 $jsonArray = $this->getExecuteChangesJsonArray($parentRecord[$parent['field']], $newItemList);
1358 $this->getCommonScriptCalls($jsonArray, $parent['config']);
1359 }
1360 return $jsonArray;
1361 }
1362
1363 /**
1364 * Handle AJAX calls to dynamically load the form fields of a given record.
1365 * (basically a copy of "createNewRecord")
1366 * Normally this method is never called from inside TYPO3. Always from outside by AJAX.
1367 *
1368 * @param string $domObjectId The calling object in hierarchy, that requested a new record.
1369 * @return array An array to be used for JSON
1370 */
1371 public function getRecordDetails($domObjectId) {
1372 // The current table - for this table we should add/import records
1373 $current = $this->inlineStructure['unstable'];
1374 // The parent table - this table embeds the current table
1375 $parent = $this->getStructureLevel(-1);
1376 // Get TCA 'config' of the parent table
1377 if (!$this->checkConfiguration($parent['config'])) {
1378 return $this->getErrorMessageForAJAX('Wrong configuration in table ' . $parent['table']);
1379 }
1380 $config = $parent['config'];
1381 // Set flag in config so that only the fields are rendered
1382 $config['renderFieldsOnly'] = TRUE;
1383 $collapseAll = isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll'];
1384 $expandSingle = isset($config['appearance']['expandSingle']) && $config['appearance']['expandSingle'];
1385 // Put the current level also to the dynNestedStack of TCEforms:
1386 $this->fObj->pushToDynNestedStack('inline', $this->inlineNames['object']);
1387 $record = $this->getRecord($this->inlineFirstPid, $current['table'], $current['uid']);
1388 // The HTML-object-id's prefix of the dynamically created record
1389 $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $current['table'];
1390 $objectId = $objectPrefix . self::Structure_Separator . $record['uid'];
1391 $item = $this->renderForeignRecord($parent['uid'], $record, $config);
1392 if ($item === FALSE) {
1393 return $this->getErrorMessageForAJAX('Access denied');
1394 }
1395 $jsonArray = array(
1396 'data' => $item,
1397 'scriptCall' => array(
1398 'inline.domAddRecordDetails(\'' . $domObjectId . '\',\'' . $objectPrefix . '\',' . ($expandSingle ? '1' : '0') . ',json.data);'
1399 )
1400 );
1401 if ($config['foreign_unique']) {
1402 $jsonArray['scriptCall'][] = 'inline.removeUsed(\'' . $objectPrefix . '\',\'' . $record['uid'] . '\');';
1403 }
1404 $this->getCommonScriptCalls($jsonArray, $config);
1405 // Collapse all other records if requested:
1406 if (!$collapseAll && $expandSingle) {
1407 $jsonArray['scriptCall'][] = 'inline.collapseAllRecords(\'' . $objectId . '\',\'' . $objectPrefix . '\',\'' . $record['uid'] . '\');';
1408 }
1409 // Remove the current level also from the dynNestedStack of TCEforms:
1410 $this->fObj->popFromDynNestedStack();
1411 // Return the JSON array:
1412 return $jsonArray;
1413 }
1414
1415 /**
1416 * Generates a JSON array which executes the changes and thus updates the forms view.
1417 *
1418 * @param string $oldItemList List of related child reocrds before changes were made (old)
1419 * @param string $newItemList List of related child records after changes where made (new)
1420 * @return array An array to be used for JSON
1421 */
1422 protected function getExecuteChangesJsonArray($oldItemList, $newItemList) {
1423 $data = '';
1424 $parent = $this->getStructureLevel(-1);
1425 $current = $this->inlineStructure['unstable'];
1426 $jsonArray = array('scriptCall' => array());
1427 $jsonArrayScriptCall = &$jsonArray['scriptCall'];
1428 $nameObject = $this->inlineNames['object'];
1429 $nameObjectForeignTable = $nameObject . self::Structure_Separator . $current['table'];
1430 // Get the name of the field pointing to the original record:
1431 $transOrigPointerField = $GLOBALS['TCA'][$current['table']]['ctrl']['transOrigPointerField'];
1432 // Get the name of the field used as foreign selector (if any):
1433 $foreignSelector = isset($parent['config']['foreign_selector']) && $parent['config']['foreign_selector'] ? $parent['config']['foreign_selector'] : FALSE;
1434 // Convert lists to array with uids of child records:
1435 $oldItems = $this->getRelatedRecordsUidArray($oldItemList);
1436 $newItems = $this->getRelatedRecordsUidArray($newItemList);
1437 // Determine the items that were localized or localized:
1438 $removedItems = array_diff($oldItems, $newItems);
1439 $localizedItems = array_diff($newItems, $oldItems);
1440 // Set the items that should be removed in the forms view:
1441 foreach ($removedItems as $item) {
1442 $jsonArrayScriptCall[] = 'inline.deleteRecord(\'' . $nameObjectForeignTable . self::Structure_Separator . $item . '\', {forceDirectRemoval: true});';
1443 }
1444 // Set the items that should be added in the forms view:
1445 foreach ($localizedItems as $item) {
1446 $row = $this->getRecord($this->inlineFirstPid, $current['table'], $item);
1447 $selectedValue = $foreignSelector ? '\'' . $row[$foreignSelector] . '\'' : 'null';
1448 $data .= $this->renderForeignRecord($parent['uid'], $row, $parent['config']);
1449 $jsonArrayScriptCall[] = 'inline.memorizeAddRecord(\'' . $nameObjectForeignTable . '\', \'' . $item . '\', null, ' . $selectedValue . ');';
1450 // Remove possible virtual records in the form which showed that a child records could be localized:
1451 if (isset($row[$transOrigPointerField]) && $row[$transOrigPointerField]) {
1452 $jsonArrayScriptCall[] = 'inline.fadeAndRemove(\'' . $nameObjectForeignTable . self::Structure_Separator . $row[$transOrigPointerField] . '_div' . '\');';
1453 }
1454 }
1455 if ($data) {
1456 $jsonArray['data'] = $data;
1457 array_unshift($jsonArrayScriptCall, 'inline.domAddNewRecord(\'bottom\', \'' . $nameObject . '_records\', \'' . $nameObjectForeignTable . '\', json.data);');
1458 }
1459 return $jsonArray;
1460 }
1461
1462 /**
1463 * Save the expanded/collapsed state of a child record in the BE_USER->uc.
1464 *
1465 * @param string $domObjectId The calling object in hierarchy, that requested a new record.
1466 * @param string $expand Whether this record is expanded.
1467 * @param string $collapse Whether this record is collapsed.
1468 * @return void
1469 */
1470 public function setExpandedCollapsedState($domObjectId, $expand, $collapse) {
1471 // Parse the DOM identifier (string), add the levels to the structure stack (array), but don't load TCA config
1472 $this->parseStructureString($domObjectId, FALSE);
1473 // The current table - for this table we should add/import records
1474 $current = $this->inlineStructure['unstable'];
1475 // The top parent table - this table embeds the current table
1476 $top = $this->getStructureLevel(0);
1477 // Only do some action if the top record and the current record were saved before
1478 if (MathUtility::canBeInterpretedAsInteger($top['uid'])) {
1479 $inlineView = (array)unserialize($GLOBALS['BE_USER']->uc['inlineView']);
1480 $inlineViewCurrent = &$inlineView[$top['table']][$top['uid']];
1481 $expandUids = GeneralUtility::trimExplode(',', $expand);
1482 $collapseUids = GeneralUtility::trimExplode(',', $collapse);
1483 // Set records to be expanded
1484 foreach ($expandUids as $uid) {
1485 $inlineViewCurrent[$current['table']][] = $uid;
1486 }
1487 // Set records to be collapsed
1488 foreach ($collapseUids as $uid) {
1489 $inlineViewCurrent[$current['table']] = $this->removeFromArray($uid, $inlineViewCurrent[$current['table']]);
1490 }
1491 // Save states back to database
1492 if (is_array($inlineViewCurrent[$current['table']])) {
1493 $inlineViewCurrent[$current['table']] = array_unique($inlineViewCurrent[$current['table']]);
1494 $GLOBALS['BE_USER']->uc['inlineView'] = serialize($inlineView);
1495 $GLOBALS['BE_USER']->writeUC();
1496 }
1497 }
1498 }
1499
1500 /*******************************************************
1501 *
1502 * Get data from database and handle relations
1503 *
1504 *******************************************************/
1505 /**
1506 * Get the related records of the embedding item, this could be 1:n, m:n.
1507 * Returns an associative array with the keys records and count. 'count' contains only real existing records on the current parent record.
1508 *
1509 * @param string $table The table name of the record
1510 * @param string $field The field name which this element is supposed to edit
1511 * @param array $row The record data array where the value(s) for the field can be found
1512 * @param array $PA An array with additional configuration options.
1513 * @param array $config (Redundant) content of $PA['fieldConf']['config'] (for convenience)
1514 * @return array The records related to the parent item as associative array.
1515 */
1516 public function getRelatedRecords($table, $field, $row, &$PA, $config) {
1517 $language = 0;
1518 $pid = $row['pid'];
1519 $elements = $PA['itemFormElValue'];
1520 $foreignTable = $config['foreign_table'];
1521 $localizationMode = BackendUtility::getInlineLocalizationMode($table, $config);
1522 if ($localizationMode != FALSE) {
1523 $language = (int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']];
1524 $transOrigPointer = (int)$row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']];
1525 $transOrigTable = BackendUtility::getOriginalTranslationTable($table);
1526
1527 if ($language > 0 && $transOrigPointer) {
1528 // Localization in mode 'keep', isn't a real localization, but keeps the children of the original parent record:
1529 if ($localizationMode == 'keep') {
1530 $transOrigRec = $this->getRecord(0, $transOrigTable, $transOrigPointer);
1531 $elements = $transOrigRec[$field];
1532 $pid = $transOrigRec['pid'];
1533 } elseif ($localizationMode == 'select') {
1534 $transOrigRec = $this->getRecord(0, $transOrigTable, $transOrigPointer);
1535 $pid = $transOrigRec['pid'];
1536 $fieldValue = $transOrigRec[$field];
1537
1538 // Checks if it is a flexform field
1539 if ($GLOBALS['TCA'][$table]['columns'][$field]['config']['type'] === 'flex') {
1540 $flexFormParts = $this->extractFlexFormParts($PA['itemFormElName']);
1541 $flexData = GeneralUtility::xml2array($fieldValue);
1542 /** @var $flexFormTools \TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools */
1543 $flexFormTools = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools::class);
1544 $flexFormFieldValue = $flexFormTools->getArrayValueByPath($flexFormParts, $flexData);
1545
1546 if ($flexFormFieldValue !== NULL) {
1547 $fieldValue = $flexFormFieldValue;
1548 }
1549 }
1550
1551 $recordsOriginal = $this->getRelatedRecordsArray($pid, $foreignTable, $fieldValue);
1552 }
1553 }
1554 }
1555 $records = $this->getRelatedRecordsArray($pid, $foreignTable, $elements);
1556 $relatedRecords = array('records' => $records, 'count' => count($records));
1557 // Merge original language with current localization and show differences:
1558 if (!empty($recordsOriginal)) {
1559 $options = array(
1560 'showPossible' => isset($config['appearance']['showPossibleLocalizationRecords']) && $config['appearance']['showPossibleLocalizationRecords'],
1561 'showRemoved' => isset($config['appearance']['showRemovedLocalizationRecords']) && $config['appearance']['showRemovedLocalizationRecords']
1562 );
1563 // Either show records that possibly can localized or removed
1564 if ($options['showPossible'] || $options['showRemoved']) {
1565 $relatedRecords['records'] = $this->getLocalizationDifferences($foreignTable, $options, $recordsOriginal, $records);
1566 // Otherwise simulate localizeChildrenAtParentLocalization behaviour when creating a new record
1567 // (which has language and translation pointer values set)
1568 } elseif (!empty($config['behaviour']['localizeChildrenAtParentLocalization']) && !MathUtility::canBeInterpretedAsInteger($row['uid'])) {
1569 if (!empty($GLOBALS['TCA'][$foreignTable]['ctrl']['transOrigPointerField'])) {
1570 $foreignLanguageField = $GLOBALS['TCA'][$foreignTable]['ctrl']['languageField'];
1571 }
1572 if (!empty($GLOBALS['TCA'][$foreignTable]['ctrl']['transOrigPointerField'])) {
1573 $foreignTranslationPointerField = $GLOBALS['TCA'][$foreignTable]['ctrl']['transOrigPointerField'];
1574 }
1575 // Duplicate child records of default language in form
1576 foreach ($recordsOriginal as $record) {
1577 if (!empty($foreignLanguageField)) {
1578 $record[$foreignLanguageField] = $language;
1579 }
1580 if (!empty($foreignTranslationPointerField)) {
1581 $record[$foreignTranslationPointerField] = $record['uid'];
1582 }
1583 $newId = uniqid('NEW', TRUE);
1584 $record['uid'] = $newId;
1585 $record['pid'] = $this->inlineFirstPid;
1586 $relatedRecords['records'][$newId] = $record;
1587 }
1588 }
1589 }
1590 return $relatedRecords;
1591 }
1592
1593 /**
1594 * Gets the related records of the embedding item, this could be 1:n, m:n.
1595 *
1596 * @param int $pid The pid of the parent record
1597 * @param string $table The table name of the record
1598 * @param string $itemList The list of related child records
1599 * @return array The records related to the parent item
1600 */
1601 protected function getRelatedRecordsArray($pid, $table, $itemList) {
1602 $records = array();
1603 $itemArray = $this->getRelatedRecordsUidArray($itemList);
1604 // Perform modification of the selected items array:
1605 foreach ($itemArray as $uid) {
1606 // Get the records for this uid using \TYPO3\CMS\Backend\Form\DataPreprocessor
1607 if ($record = $this->getRecord($pid, $table, $uid)) {
1608 $records[$uid] = $record;
1609 }
1610 }
1611 return $records;
1612 }
1613
1614 /**
1615 * Gets an array with the uids of related records out of a list of items.
1616 * This list could contain more information than required. This methods just
1617 * extracts the uids.
1618 *
1619 * @param string $itemList The list of related child records
1620 * @return array An array with uids
1621 */
1622 protected function getRelatedRecordsUidArray($itemList) {
1623 $itemArray = GeneralUtility::trimExplode(',', $itemList, TRUE);
1624 // Perform modification of the selected items array:
1625 foreach ($itemArray as $key => &$value) {
1626 $parts = explode('|', $value, 2);
1627 $value = $parts[0];
1628 }
1629 unset($value);
1630 return $itemArray;
1631 }
1632
1633 /**
1634 * Gets the difference between current localized structure and the original language structure.
1635 * If there are records which once were localized but don't exist in the original version anymore, the record row is marked with '__remove'.
1636 * If there are records which can be localized and exist only in the original version, the record row is marked with '__create' and '__virtual'.
1637 *
1638 * @param string $table The table name of the parent records
1639 * @param array $options Options defining what kind of records to display
1640 * @param array $recordsOriginal The uids of the child records of the original language
1641 * @param array $recordsLocalization The uids of the child records of the current localization
1642 * @return array Merged array of uids of the child records of both versions
1643 */
1644 protected function getLocalizationDifferences($table, array $options, array $recordsOriginal, array $recordsLocalization) {
1645 $records = array();
1646 $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
1647 // Compare original to localized version of the records:
1648 foreach ($recordsLocalization as $uid => $row) {
1649 // If the record points to a original translation which doesn't exist anymore, it could be removed:
1650 if (isset($row[$transOrigPointerField]) && $row[$transOrigPointerField] > 0) {
1651 $transOrigPointer = $row[$transOrigPointerField];
1652 if (isset($recordsOriginal[$transOrigPointer])) {
1653 unset($recordsOriginal[$transOrigPointer]);
1654 } elseif ($options['showRemoved']) {
1655 $row['__remove'] = TRUE;
1656 }
1657 }
1658 $records[$uid] = $row;
1659 }
1660 // Process the remaining records in the original unlocalized parent:
1661 if ($options['showPossible']) {
1662 foreach ($recordsOriginal as $uid => $row) {
1663 $row['__create'] = TRUE;
1664 $row['__virtual'] = TRUE;
1665 $records[$uid] = $row;
1666 }
1667 }
1668 return $records;
1669 }
1670
1671 /**
1672 * Get possible records.
1673 * Copied from TCEform and modified.
1674 *
1675 * @param string $table The table name of the record
1676 * @param string $field The field name which this element is supposed to edit
1677 * @param array $row The record data array where the value(s) for the field can be found
1678 * @param array $conf An array with additional configuration options.
1679 * @param string $checkForConfField For which field in the foreign_table the possible records should be fetched
1680 * @return mixed Array of possible record items; FALSE if type is "group/db", then everything could be "possible
1681 */
1682 public function getPossibleRecords($table, $field, $row, $conf, $checkForConfField = 'foreign_selector') {
1683 // ctrl configuration from TCA:
1684 $tcaTableCtrl = $GLOBALS['TCA'][$table]['ctrl'];
1685 // Field configuration from TCA:
1686 $foreign_table = $conf['foreign_table'];
1687 $foreign_check = $conf[$checkForConfField];
1688 $foreignConfig = $this->getPossibleRecordsSelectorConfig($conf, $foreign_check);
1689 $PA = $foreignConfig['PA'];
1690 $config = $PA['fieldConf']['config'];
1691 if ($foreignConfig['type'] == 'select') {
1692 // Getting the selector box items from the system
1693 $selItems = $this->fObj->addSelectOptionsToItemArray($this->fObj->initItemArray($PA['fieldConf']), $PA['fieldConf'], $this->fObj->setTSconfig($table, $row), $field);
1694
1695 // Possibly filter some items:
1696 $selItems = ArrayUtility::keepItemsInArray(
1697 $selItems,
1698 $PA['fieldTSConfig']['keepItems'],
1699 function ($value) {
1700 return $value[1];
1701 }
1702 );
1703
1704 // Possibly add some items:
1705 $selItems = $this->fObj->addItems($selItems, $PA['fieldTSConfig']['addItems.']);
1706 if (isset($config['itemsProcFunc']) && $config['itemsProcFunc']) {
1707 $selItems = $this->fObj->procItems($selItems, $PA['fieldTSConfig']['itemsProcFunc.'], $config, $table, $row, $field);
1708 }
1709 // Possibly remove some items:
1710 $removeItems = GeneralUtility::trimExplode(',', $PA['fieldTSConfig']['removeItems'], TRUE);
1711 foreach ($selItems as $tk => $p) {
1712 // Checking languages and authMode:
1713 $languageDeny = $tcaTableCtrl['languageField'] && (string)$tcaTableCtrl['languageField'] === $field && !$GLOBALS['BE_USER']->checkLanguageAccess($p[1]);
1714 $authModeDeny = $config['form_type'] == 'select' && $config['authMode'] && !$GLOBALS['BE_USER']->checkAuthMode($table, $field, $p[1], $config['authMode']);
1715 if (in_array($p[1], $removeItems) || $languageDeny || $authModeDeny) {
1716 unset($selItems[$tk]);
1717 } else {
1718 if (isset($PA['fieldTSConfig']['altLabels.'][$p[1]])) {
1719 $selItems[$tk][0] = htmlspecialchars($this->getLanguageService()->sL($PA['fieldTSConfig']['altLabels.'][$p[1]]));
1720 }
1721 if (isset($PA['fieldTSConfig']['altIcons.'][$p[1]])) {
1722 $selItems[$tk][2] = $PA['fieldTSConfig']['altIcons.'][$p[1]];
1723 }
1724 }
1725 // Removing doktypes with no access:
1726 if (($table === 'pages' || $table === 'pages_language_overlay') && $field === 'doktype') {
1727 if (!($GLOBALS['BE_USER']->isAdmin() || GeneralUtility::inList($GLOBALS['BE_USER']->groupData['pagetypes_select'], $p[1]))) {
1728 unset($selItems[$tk]);
1729 }
1730 }
1731 }
1732 } else {
1733 $selItems = FALSE;
1734 }
1735 return $selItems;
1736 }
1737
1738 /**
1739 * Gets the uids of a select/selector that should be unique an have already been used.
1740 *
1741 * @param array $records All inline records on this level
1742 * @param array $conf The TCA field configuration of the inline field to be rendered
1743 * @param bool $splitValue For usage with group/db, values come like "tx_table_123|Title%20abc", but we need "tx_table" and "123
1744 * @return array The uids, that have been used already and should be used unique
1745 */
1746 public function getUniqueIds($records, $conf = array(), $splitValue = FALSE) {
1747 $uniqueIds = array();
1748 if (isset($conf['foreign_unique']) && $conf['foreign_unique'] && count($records)) {
1749 foreach ($records as $rec) {
1750 // Skip virtual records (e.g. shown in localization mode):
1751 if (!isset($rec['__virtual']) || !$rec['__virtual']) {
1752 $value = $rec[$conf['foreign_unique']];
1753 // Split the value and extract the table and uid:
1754 if ($splitValue) {
1755 $valueParts = GeneralUtility::trimExplode('|', $value);
1756 $itemParts = explode('_', $valueParts[0]);
1757 $value = array(
1758 'uid' => array_pop($itemParts),
1759 'table' => implode('_', $itemParts)
1760 );
1761 }
1762 $uniqueIds[$rec['uid']] = $value;
1763 }
1764 }
1765 }
1766 return $uniqueIds;
1767 }
1768
1769 /**
1770 * Determines the corrected pid to be used for a new record.
1771 * The pid to be used can be defined by a Page TSconfig.
1772 *
1773 * @param string $table The table name
1774 * @param int $parentPid The pid of the parent record
1775 * @return int The corrected pid to be used for a new record
1776 */
1777 protected function getNewRecordPid($table, $parentPid = NULL) {
1778 $newRecordPid = $this->inlineFirstPid;
1779 $pageTS = BackendUtility::getPagesTSconfig($parentPid);
1780 if (isset($pageTS['TCAdefaults.'][$table . '.']['pid']) && MathUtility::canBeInterpretedAsInteger($pageTS['TCAdefaults.'][$table . '.']['pid'])) {
1781 $newRecordPid = $pageTS['TCAdefaults.'][$table . '.']['pid'];
1782 } elseif (isset($parentPid) && MathUtility::canBeInterpretedAsInteger($parentPid)) {
1783 $newRecordPid = $parentPid;
1784 }
1785 return $newRecordPid;
1786 }
1787
1788 /**
1789 * Get a single record row for a TCA table from the database.
1790 * \TYPO3\CMS\Backend\Form\DataPreprocessor is used for "upgrading" the
1791 * values, especially the relations.
1792 *
1793 * @param int $pid The pid of the page the record should be stored (only relevant for NEW records)
1794 * @param string $table The table to fetch data from (= foreign_table)
1795 * @param string $uid The uid of the record to fetch, or the pid if a new record should be created
1796 * @param string $cmd The command to perform, empty or 'new'
1797 * @return array A record row from the database post-processed by \TYPO3\CMS\Backend\Form\DataPreprocessor
1798 */
1799 public function getRecord($pid, $table, $uid, $cmd = '') {
1800 // Fetch workspace version of a record (if any):
1801 if ($cmd !== 'new' && $GLOBALS['BE_USER']->workspace !== 0 && BackendUtility::isTableWorkspaceEnabled($table)) {
1802 $workspaceVersion = BackendUtility::getWorkspaceVersionOfRecord($GLOBALS['BE_USER']->workspace, $table, $uid, 'uid,t3ver_state');
1803 if ($workspaceVersion !== FALSE) {
1804 $versionState = VersionState::cast($workspaceVersion['t3ver_state']);
1805 if ($versionState->equals(VersionState::DELETE_PLACEHOLDER)) {
1806 return FALSE;
1807 }
1808 $uid = $workspaceVersion['uid'];
1809 }
1810 }
1811 /** @var $trData \TYPO3\CMS\Backend\Form\DataPreprocessor */
1812 $trData = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Form\DataPreprocessor::class);
1813 $trData->addRawData = TRUE;
1814 $trData->lockRecords = 1;
1815 $trData->disableRTE = $GLOBALS['SOBE']->MOD_SETTINGS['disableRTE'];
1816 // If a new record should be created
1817 $trData->fetchRecord($table, $uid, $cmd === 'new' ? 'new' : '');
1818 $rec = reset($trData->regTableItems_data);
1819 return $rec;
1820 }
1821
1822 /**
1823 * Wrapper. Calls getRecord in case of a new record should be created.
1824 *
1825 * @param int $pid The pid of the page the record should be stored (only relevant for NEW records)
1826 * @param string $table The table to fetch data from (= foreign_table)
1827 * @return array A record row from the database post-processed by \TYPO3\CMS\Backend\Form\DataPreprocessor
1828 */
1829 public function getNewRecord($pid, $table) {
1830 $rec = $this->getRecord($pid, $table, $pid, 'new');
1831 $rec['uid'] = uniqid('NEW', TRUE);
1832 $rec['pid'] = $this->getNewRecordPid($table, $pid);
1833 return $rec;
1834 }
1835
1836 /*******************************************************
1837 *
1838 * Structure stack for handling inline objects/levels
1839 *
1840 *******************************************************/
1841 /**
1842 * Add a new level on top of the structure stack. Other functions can access the
1843 * stack and determine, if there's possibly a endless loop.
1844 *
1845 * @param string $table The table name of the record
1846 * @param string $uid The uid of the record that embeds the inline data
1847 * @param string $field The field name which this element is supposed to edit
1848 * @param array $config The TCA-configuration of the inline field
1849 * @param array $parameters The full parameter array (PA)
1850 * @return void
1851 */
1852 public function pushStructure($table, $uid, $field = '', $config = array(), array $parameters = array()) {
1853 $structure = array(
1854 'table' => $table,
1855 'uid' => $uid,
1856 'field' => $field,
1857 'config' => $config,
1858 'localizationMode' => BackendUtility::getInlineLocalizationMode($table, $config),
1859 );
1860
1861 // Extract FlexForm parts (if any) from element name,
1862 // e.g. array('vDEF', 'lDEF', 'FlexField', 'vDEF')
1863 if (!empty($parameters['itemFormElName'])) {
1864 $flexFormParts = $this->extractFlexFormParts($parameters['itemFormElName']);
1865
1866 if ($flexFormParts !== NULL) {
1867 $structure['flexform'] = $flexFormParts;
1868 }
1869 }
1870
1871 $this->inlineStructure['stable'][] = $structure;
1872 $this->updateStructureNames();
1873 }
1874
1875 /**
1876 * Remove the item on top of the structure stack and return it.
1877 *
1878 * @return array The top item of the structure stack - array(<table>,<uid>,<field>,<config>)
1879 */
1880 public function popStructure() {
1881 $popItem = NULL;
1882
1883 if (count($this->inlineStructure['stable'])) {
1884 $popItem = array_pop($this->inlineStructure['stable']);
1885 $this->updateStructureNames();
1886 }
1887 return $popItem;
1888 }
1889
1890 /**
1891 * For common use of DOM object-ids and form field names of a several inline-level,
1892 * these names/identifiers are preprocessed and set to $this->inlineNames.
1893 * This function is automatically called if a level is pushed to or removed from the
1894 * inline structure stack.
1895 *
1896 * @return void
1897 */
1898 public function updateStructureNames() {
1899 $current = $this->getStructureLevel(-1);
1900 // If there are still more inline levels available
1901 if ($current !== FALSE) {
1902 $this->inlineNames = array(
1903 'form' => $this->prependFormFieldNames . $this->getStructureItemName($current, self::Disposal_AttributeName),
1904 'object' => $this->prependNaming . self::Structure_Separator . $this->inlineFirstPid . self::Structure_Separator . $this->getStructurePath()
1905 );
1906 } else {
1907 $this->inlineNames = array();
1908 }
1909 }
1910
1911 /**
1912 * Create a name/id for usage in HTML output of a level of the structure stack to be used in form names.
1913 *
1914 * @param array $levelData Array of a level of the structure stack (containing the keys table, uid and field)
1915 * @param string $disposal How the structure name is used (e.g. as <div id="..."> or <input name="..." />)
1916 * @return string The name/id of that level, to be used for HTML output
1917 */
1918 public function getStructureItemName($levelData, $disposal = self::Disposal_AttributeId) {
1919 $name = NULL;
1920
1921 if (is_array($levelData)) {
1922 $parts = array($levelData['table'], $levelData['uid']);
1923
1924 if (!empty($levelData['field'])) {
1925 $parts[] = $levelData['field'];
1926 }
1927
1928 // Use in name attributes:
1929 if ($disposal === self::Disposal_AttributeName) {
1930 if (!empty($levelData['field']) && !empty($levelData['flexform']) && $this->getStructureLevel(-1) === $levelData) {
1931 $parts[] = implode('][', $levelData['flexform']);
1932 }
1933 $name = '[' . implode('][', $parts) . ']';
1934 // Use in object id attributes:
1935 } else {
1936 $name = implode(self::Structure_Separator, $parts);
1937
1938 if (!empty($levelData['field']) && !empty($levelData['flexform'])) {
1939 array_unshift($levelData['flexform'], $name);
1940 $name = implode(self::FlexForm_Separator, $levelData['flexform']);
1941 }
1942 }
1943 }
1944
1945 return $name;
1946 }
1947
1948 /**
1949 * Get a level from the stack and return the data.
1950 * If the $level value is negative, this function works top-down,
1951 * if the $level value is positive, this function works bottom-up.
1952 *
1953 * @param int $level Which level to return
1954 * @return array The item of the stack at the requested level
1955 */
1956 public function getStructureLevel($level) {
1957 $level = $this->calculateStructureLevel($level);
1958
1959 if ($level !== FALSE) {
1960 return $this->inlineStructure['stable'][$level];
1961 } else {
1962 return FALSE;
1963 }
1964 }
1965
1966 /**
1967 * Calculates structure level.
1968 *
1969 * @param int $level Which level to return
1970 * @return bool|int
1971 */
1972 protected function calculateStructureLevel($level) {
1973 $result = FALSE;
1974
1975 $inlineStructureCount = count($this->inlineStructure['stable']);
1976 if ($level < 0) {
1977 $level = $inlineStructureCount + $level;
1978 }
1979 if ($level >= 0 && $level < $inlineStructureCount) {
1980 $result = $level;
1981 }
1982
1983 return $result;
1984 }
1985
1986 /**
1987 * Get the identifiers of a given depth of level, from the top of the stack to the bottom.
1988 * An identifier looks like "<table>-<uid>-<field>".
1989 *
1990 * @param int $structureDepth How much levels to output, beginning from the top of the stack
1991 * @return string The path of identifiers
1992 */
1993 public function getStructurePath($structureDepth = -1) {
1994 $structureLevels = array();
1995 $structureCount = count($this->inlineStructure['stable']);
1996 if ($structureDepth < 0 || $structureDepth > $structureCount) {
1997 $structureDepth = $structureCount;
1998 }
1999 for ($i = 1; $i <= $structureDepth; $i++) {
2000 array_unshift($structureLevels, $this->getStructureItemName($this->getStructureLevel(-$i), self::Disposal_AttributeId));
2001 }
2002 return implode(self::Structure_Separator, $structureLevels);
2003 }
2004
2005 /**
2006 * Convert the DOM object-id of an inline container to an array.
2007 * The object-id could look like 'data-parentPageId-tx_mmftest_company-1-employees'.
2008 * The result is written to $this->inlineStructure.
2009 * There are two keys:
2010 * - 'stable': Containing full qualified identifiers (table, uid and field)
2011 * - 'unstable': Containting partly filled data (e.g. only table and possibly field)
2012 *
2013 * @param string $domObjectId The DOM object-id
2014 * @param bool $loadConfig Load the TCA configuration for that level (default: TRUE)
2015 * @return void
2016 */
2017 public function parseStructureString($string, $loadConfig = TRUE) {
2018 $unstable = array();
2019 $vector = array('table', 'uid', 'field');
2020
2021 // Substitute FlexForm additon and make parsing a bit easier
2022 $string = str_replace(self::FlexForm_Separator, self::FlexForm_Substitute, $string);
2023 // The starting pattern of an object identifer (e.g. "data-<firstPidValue>-<anything>)
2024 $pattern = '/^' . $this->prependNaming . self::Structure_Separator . '(.+?)' . self::Structure_Separator . '(.+)$/';
2025
2026 if (preg_match($pattern, $string, $match)) {
2027 $this->inlineFirstPid = $match[1];
2028 $parts = explode(self::Structure_Separator, $match[2]);
2029 $partsCnt = count($parts);
2030 for ($i = 0; $i < $partsCnt; $i++) {
2031 if ($i > 0 && $i % 3 == 0) {
2032 // Load the TCA configuration of the table field and store it in the stack
2033 if ($loadConfig) {
2034 $unstable['config'] = $GLOBALS['TCA'][$unstable['table']]['columns'][$unstable['field']]['config'];
2035 // Fetch TSconfig:
2036 $TSconfig = $this->fObj->setTSconfig($unstable['table'], array('uid' => $unstable['uid'], 'pid' => $this->inlineFirstPid), $unstable['field']);
2037 // Override TCA field config by TSconfig:
2038 if (!$TSconfig['disabled']) {
2039 $unstable['config'] = $this->fObj->overrideFieldConf($unstable['config'], $TSconfig);
2040 }
2041 $unstable['localizationMode'] = BackendUtility::getInlineLocalizationMode($unstable['table'], $unstable['config']);
2042 }
2043
2044 // Extract FlexForm from field part (if any)
2045 if (strpos($unstable['field'], self::FlexForm_Substitute) !== FALSE) {
2046 $fieldParts = GeneralUtility::trimExplode(self::FlexForm_Substitute, $unstable['field']);
2047 $unstable['field'] = array_shift($fieldParts);
2048 // FlexForm parts start with data:
2049 if (count($fieldParts) > 0 && $fieldParts[0] === 'data') {
2050 $unstable['flexform'] = $fieldParts;
2051 }
2052 }
2053
2054 $this->inlineStructure['stable'][] = $unstable;
2055 $unstable = array();
2056 }
2057 $unstable[$vector[$i % 3]] = $parts[$i];
2058 }
2059 $this->updateStructureNames();
2060 if (count($unstable)) {
2061 $this->inlineStructure['unstable'] = $unstable;
2062 }
2063 }
2064 }
2065
2066 /*******************************************************
2067 *
2068 * Helper functions
2069 *
2070 *******************************************************/
2071 /**
2072 * Does some checks on the TCA configuration of the inline field to render.
2073 *
2074 * @param array $config Reference to the TCA field configuration
2075 * @param string $table The table name of the record
2076 * @param string $field The field name which this element is supposed to edit
2077 * @param array $row The record data array of the parent
2078 * @return bool If critical configuration errors were found, FALSE is returned
2079 */
2080 public function checkConfiguration(&$config) {
2081 $foreign_table = $config['foreign_table'];
2082 // An inline field must have a foreign_table, if not, stop all further inline actions for this field:
2083 if (!$foreign_table || !is_array($GLOBALS['TCA'][$foreign_table])) {
2084 return FALSE;
2085 }
2086 // Init appearance if not set:
2087 if (!isset($config['appearance']) || !is_array($config['appearance'])) {
2088 $config['appearance'] = array();
2089 }
2090 // Set the position/appearance of the "Create new record" link:
2091 if (isset($config['foreign_selector']) && $config['foreign_selector'] && (!isset($config['appearance']['useCombination']) || !$config['appearance']['useCombination'])) {
2092 $config['appearance']['levelLinksPosition'] = 'none';
2093 } elseif (!isset($config['appearance']['levelLinksPosition']) || !in_array($config['appearance']['levelLinksPosition'], array('top', 'bottom', 'both', 'none'))) {
2094 $config['appearance']['levelLinksPosition'] = 'top';
2095 }
2096 // Defines which controls should be shown in header of each record:
2097 $enabledControls = array(
2098 'info' => TRUE,
2099 'new' => TRUE,
2100 'dragdrop' => TRUE,
2101 'sort' => TRUE,
2102 'hide' => TRUE,
2103 'delete' => TRUE,
2104 'localize' => TRUE
2105 );
2106 if (isset($config['appearance']['enabledControls']) && is_array($config['appearance']['enabledControls'])) {
2107 $config['appearance']['enabledControls'] = array_merge($enabledControls, $config['appearance']['enabledControls']);
2108 } else {
2109 $config['appearance']['enabledControls'] = $enabledControls;
2110 }
2111 return TRUE;
2112 }
2113
2114 /**
2115 * Checks the page access rights (Code for access check mostly taken from alt_doc.php)
2116 * as well as the table access rights of the user.
2117 *
2118 * @param string $cmd The command that sould be performed ('new' or 'edit')
2119 * @param string $table The table to check access for
2120 * @param string $theUid The record uid of the table
2121 * @return bool Returns TRUE is the user has access, or FALSE if not
2122 */
2123 public function checkAccess($cmd, $table, $theUid) {
2124 // 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...)
2125 // First, resetting flags.
2126 $hasAccess = 0;
2127 $deniedAccessReason = '';
2128 // Admin users always have acces:
2129 if ($GLOBALS['BE_USER']->isAdmin()) {
2130 return TRUE;
2131 }
2132 // If the command is to create a NEW record...:
2133 if ($cmd == 'new') {
2134 // If the pid is numerical, check if it's possible to write to this page:
2135 if (MathUtility::canBeInterpretedAsInteger($this->inlineFirstPid)) {
2136 $calcPRec = BackendUtility::getRecord('pages', $this->inlineFirstPid);
2137 if (!is_array($calcPRec)) {
2138 return FALSE;
2139 }
2140 // Permissions for the parent page
2141 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
2142 // If pages:
2143 if ($table == 'pages') {
2144 // Are we allowed to create new subpages?
2145 $hasAccess = $CALC_PERMS & 8 ? 1 : 0;
2146 } else {
2147 // Are we allowed to edit content on this page?
2148 $hasAccess = $CALC_PERMS & 16 ? 1 : 0;
2149 }
2150 } else {
2151 $hasAccess = 1;
2152 }
2153 } else {
2154 // Edit:
2155 $calcPRec = BackendUtility::getRecord($table, $theUid);
2156 BackendUtility::fixVersioningPid($table, $calcPRec);
2157 if (is_array($calcPRec)) {
2158 // If pages:
2159 if ($table == 'pages') {
2160 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
2161 $hasAccess = $CALC_PERMS & 2 ? 1 : 0;
2162 } else {
2163 // Fetching pid-record first.
2164 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms(BackendUtility::getRecord('pages', $calcPRec['pid']));
2165 $hasAccess = $CALC_PERMS & 16 ? 1 : 0;
2166 }
2167 // Check internals regarding access:
2168 if ($hasAccess) {
2169 $hasAccess = $GLOBALS['BE_USER']->recordEditAccessInternals($table, $calcPRec);
2170 }
2171 }
2172 }
2173 if (!$GLOBALS['BE_USER']->check('tables_modify', $table)) {
2174 $hasAccess = 0;
2175 }
2176 if (!$hasAccess) {
2177 $deniedAccessReason = $GLOBALS['BE_USER']->errorMsg;
2178 if ($deniedAccessReason) {
2179 debug($deniedAccessReason);
2180 }
2181 }
2182 return $hasAccess ? TRUE : FALSE;
2183 }
2184
2185 /**
2186 * Check the keys and values in the $compare array against the ['config'] part of the top level of the stack.
2187 * A boolean value is return depending on how the comparison was successful.
2188 *
2189 * @param array $compare Keys and values to compare to the ['config'] part of the top level of the stack
2190 * @return bool Whether the comparison was successful
2191 * @see arrayCompareComplex
2192 */
2193 public function compareStructureConfiguration($compare) {
2194 $level = $this->getStructureLevel(-1);
2195 $result = $this->arrayCompareComplex($level, $compare);
2196 return $result;
2197 }
2198
2199 /**
2200 * Normalize a relation "uid" published by transferData, like "1|Company%201"
2201 *
2202 * @param string $string A transferData reference string, containing the uid
2203 * @return string The normalized uid
2204 */
2205 public function normalizeUid($string) {
2206 $parts = explode('|', $string);
2207 return $parts[0];
2208 }
2209
2210 /**
2211 * Wrap the HTML code of a section with a table tag.
2212 *
2213 * @param string $section The HTML code to be wrapped
2214 * @param array $styleAttrs Attributes for the style argument in the table tag
2215 * @param array $tableAttrs Attributes for the table tag (like width, border, etc.)
2216 * @return string The wrapped HTML code
2217 */
2218 public function wrapFormsSection($section, $styleAttrs = array(), $tableAttrs = array()) {
2219 $style = '';
2220 $table = '';
2221 foreach ($styleAttrs as $key => $value) {
2222 $style .= ($style ? ' ' : '') . $key . ': ' . htmlspecialchars($value) . '; ';
2223 }
2224 if ($style) {
2225 $style = ' style="' . $style . '"';
2226 }
2227 if (!$tableAttrs['background'] && $this->fObj->borderStyle[2]) {
2228 $tableAttrs['background'] = $this->backPath . $this->borderStyle[2];
2229 }
2230 if (!$tableAttrs['class'] && $this->borderStyle[3]) {
2231 $tableAttrs['class'] = $this->borderStyle[3];
2232 }
2233 foreach ($tableAttrs as $key => $value) {
2234 $table .= ($table ? ' ' : '') . $key . '="' . htmlspecialchars($value) . '"';
2235 }
2236 $out = '<table ' . $table . $style . '>' . $section . '</table>';
2237 return $out;
2238 }
2239
2240 /**
2241 * Checks if the $table is the child of a inline type AND the $field is the label field of this table.
2242 * This function is used to dynamically update the label while editing. This has no effect on labels,
2243 * that were processed by a TCEmain-hook on saving.
2244 *
2245 * @param string $table The table to check
2246 * @param string $field The field on this table to check
2247 * @return bool Is inline child and field is responsible for the label
2248 */
2249 public function isInlineChildAndLabelField($table, $field) {
2250 $level = $this->getStructureLevel(-1);
2251 if ($level['config']['foreign_label']) {
2252 $label = $level['config']['foreign_label'];
2253 } else {
2254 $label = $GLOBALS['TCA'][$table]['ctrl']['label'];
2255 }
2256 return $level['config']['foreign_table'] === $table && $label == $field ? TRUE : FALSE;
2257 }
2258
2259 /**
2260 * Get the depth of the stable structure stack.
2261 * (count($this->inlineStructure['stable'])
2262 *
2263 * @return int The depth of the structure stack
2264 */
2265 public function getStructureDepth() {
2266 return count($this->inlineStructure['stable']);
2267 }
2268
2269 /**
2270 * Handles complex comparison requests on an array.
2271 * A request could look like the following:
2272 *
2273 * $searchArray = array(
2274 * '%AND' => array(
2275 * 'key1' => 'value1',
2276 * 'key2' => 'value2',
2277 * '%OR' => array(
2278 * 'subarray' => array(
2279 * 'subkey' => 'subvalue'
2280 * ),
2281 * 'key3' => 'value3',
2282 * 'key4' => 'value4'
2283 * )
2284 * )
2285 * );
2286 *
2287 * It is possible to use the array keys '%AND.1', '%AND.2', etc. to prevent
2288 * overwriting the sub-array. It could be necessary, if you use complex comparisons.
2289 *
2290 * The example above means, key1 *AND* key2 (and their values) have to match with
2291 * the $subjectArray and additional one *OR* key3 or key4 have to meet the same
2292 * condition.
2293 * It is also possible to compare parts of a sub-array (e.g. "subarray"), so this
2294 * function recurses down one level in that sub-array.
2295 *
2296 * @param array $subjectArray The array to search in
2297 * @param array $searchArray The array with keys and values to search for
2298 * @param string $type Use '%AND' or '%OR' for comparison
2299 * @return bool The result of the comparison
2300 */
2301 public function arrayCompareComplex($subjectArray, $searchArray, $type = '') {
2302 $localMatches = 0;
2303 $localEntries = 0;
2304 if (is_array($searchArray) && count($searchArray)) {
2305 // If no type was passed, try to determine
2306 if (!$type) {
2307 reset($searchArray);
2308 $type = key($searchArray);
2309 $searchArray = current($searchArray);
2310 }
2311 // We use '%AND' and '%OR' in uppercase
2312 $type = strtoupper($type);
2313 // Split regular elements from sub elements
2314 foreach ($searchArray as $key => $value) {
2315 $localEntries++;
2316 // Process a sub-group of OR-conditions
2317 if ($key == '%OR') {
2318 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%OR') ? 1 : 0;
2319 } elseif ($key == '%AND') {
2320 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%AND') ? 1 : 0;
2321 } elseif (is_array($value) && $this->isAssociativeArray($searchArray)) {
2322 $localMatches += $this->arrayCompareComplex($subjectArray[$key], $value, $type) ? 1 : 0;
2323 } elseif (is_array($value)) {
2324 $localMatches += $this->arrayCompareComplex($subjectArray, $value, $type) ? 1 : 0;
2325 } else {
2326 if (isset($subjectArray[$key]) && isset($value)) {
2327 // Boolean match:
2328 if (is_bool($value)) {
2329 $localMatches += !($subjectArray[$key] xor $value) ? 1 : 0;
2330 } elseif (is_numeric($subjectArray[$key]) && is_numeric($value)) {
2331 $localMatches += $subjectArray[$key] == $value ? 1 : 0;
2332 } else {
2333 $localMatches += $subjectArray[$key] === $value ? 1 : 0;
2334 }
2335 }
2336 }
2337 // If one or more matches are required ('OR'), return TRUE after the first successful match
2338 if ($type == '%OR' && $localMatches > 0) {
2339 return TRUE;
2340 }
2341 // If all matches are required ('AND') and we have no result after the first run, return FALSE
2342 if ($type == '%AND' && $localMatches == 0) {
2343 return FALSE;
2344 }
2345 }
2346 }
2347 // Return the result for '%AND' (if nothing was checked, TRUE is returned)
2348 return $localEntries == $localMatches ? TRUE : FALSE;
2349 }
2350
2351 /**
2352 * Checks whether an object is an associative array.
2353 *
2354 * @param mixed $object The object to be checked
2355 * @return bool Returns TRUE, if the object is an associative array
2356 */
2357 public function isAssociativeArray($object) {
2358 return is_array($object) && count($object) && array_keys($object) !== range(0, sizeof($object) - 1) ? TRUE : FALSE;
2359 }
2360
2361 /**
2362 * Remove an element from an array.
2363 *
2364 * @param mixed $needle The element to be removed.
2365 * @param array $haystack The array the element should be removed from.
2366 * @param mixed $strict Search elements strictly.
2367 * @return array The array $haystack without the $needle
2368 */
2369 public function removeFromArray($needle, $haystack, $strict = NULL) {
2370 $pos = array_search($needle, $haystack, $strict);
2371 if ($pos !== FALSE) {
2372 unset($haystack[$pos]);
2373 }
2374 return $haystack;
2375 }
2376
2377 /**
2378 * Makes a flat array from the $possibleRecords array.
2379 * The key of the flat array is the value of the record,
2380 * the value of the flat array is the label of the record.
2381 *
2382 * @param array $possibleRecords The possibleRecords array (for select fields)
2383 * @return mixed A flat array with key=uid, value=label; if $possibleRecords isn't an array, FALSE is returned.
2384 */
2385 public function getPossibleRecordsFlat($possibleRecords) {
2386 $flat = FALSE;
2387 if (is_array($possibleRecords)) {
2388 $flat = array();
2389 foreach ($possibleRecords as $record) {
2390 $flat[$record[1]] = $record[0];
2391 }
2392 }
2393 return $flat;
2394 }
2395
2396 /**
2397 * Determine the configuration and the type of a record selector.
2398 *
2399 * @param array $conf TCA configuration of the parent(!) field
2400 * @return array Associative array with the keys 'PA' and 'type', both are FALSE if the selector was not valid.
2401 */
2402 public function getPossibleRecordsSelectorConfig($conf, $field = '') {
2403 $foreign_table = $conf['foreign_table'];
2404 $foreign_selector = $conf['foreign_selector'];
2405 $PA = FALSE;
2406 $type = FALSE;
2407 $table = FALSE;
2408 $selector = FALSE;
2409 if ($field) {
2410 $PA = array();
2411 $PA['fieldConf'] = $GLOBALS['TCA'][$foreign_table]['columns'][$field];
2412 if ($PA['fieldConf'] && $conf['foreign_selector_fieldTcaOverride']) {
2413 \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($PA['fieldConf'], $conf['foreign_selector_fieldTcaOverride']);
2414 }
2415 $PA['fieldConf']['config']['form_type'] = $PA['fieldConf']['config']['form_type'] ?: $PA['fieldConf']['config']['type'];
2416 // Using "form_type" locally in this script
2417 $PA['fieldTSConfig'] = $this->fObj->setTSconfig($foreign_table, array(), $field);
2418 $config = $PA['fieldConf']['config'];
2419 // Determine type of Selector:
2420 $type = $this->getPossibleRecordsSelectorType($config);
2421 // Return table on this level:
2422 $table = $type == 'select' ? $config['foreign_table'] : $config['allowed'];
2423 // Return type of the selector if foreign_selector is defined and points to the same field as in $field:
2424 if ($foreign_selector && $foreign_selector == $field && $type) {
2425 $selector = $type;
2426 }
2427 }
2428 return array(
2429 'PA' => $PA,
2430 'type' => $type,
2431 'table' => $table,
2432 'selector' => $selector
2433 );
2434 }
2435
2436 /**
2437 * Determine the type of a record selector, e.g. select or group/db.
2438 *
2439 * @param array $config TCE configuration of the selector
2440 * @return mixed The type of the selector, 'select' or 'groupdb' - FALSE not valid
2441 */
2442 public function getPossibleRecordsSelectorType($config) {
2443 $type = FALSE;
2444 if ($config['type'] == 'select') {
2445 $type = 'select';
2446 } elseif ($config['type'] == 'group' && $config['internal_type'] == 'db') {
2447 $type = 'groupdb';
2448 }
2449 return $type;
2450 }
2451
2452 /**
2453 * Check, if a field should be skipped, that was defined to be handled as foreign_field or foreign_sortby of
2454 * the parent record of the "inline"-type - if so, we have to skip this field - the rendering is done via "inline" as hidden field
2455 *
2456 * @param string $table The table name
2457 * @param string $field The field name
2458 * @param array $row The record row from the database
2459 * @param array $config TCA configuration of the field
2460 * @return bool Determines whether the field should be skipped.
2461 */
2462 public function skipField($table, $field, $row, $config) {
2463 $skipThisField = FALSE;
2464 if ($this->getStructureDepth()) {
2465 $searchArray = array(
2466 '%OR' => array(
2467 'config' => array(
2468 0 => array(
2469 '%AND' => array(
2470 'foreign_table' => $table,
2471 '%OR' => array(
2472 '%AND' => array(
2473 'appearance' => array('useCombination' => TRUE),
2474 'foreign_selector' => $field
2475 ),
2476 'MM' => $config['MM']
2477 )
2478 )
2479 ),
2480 1 => array(
2481 '%AND' => array(
2482 'foreign_table' => $config['foreign_table'],
2483 'foreign_selector' => $config['foreign_field']
2484 )
2485 )
2486 )
2487 )
2488 );
2489 // Get the parent record from structure stack
2490 $level = $this->getStructureLevel(-1);
2491 // If we have symmetric fields, check on which side we are and hide fields, that are set automatically:
2492 if (RelationHandler::isOnSymmetricSide($level['uid'], $level['config'], $row)) {
2493 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_field'] = $field;
2494 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_sortby'] = $field;
2495 } else {
2496 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_field'] = $field;
2497 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_sortby'] = $field;
2498 }
2499 $skipThisField = $this->compareStructureConfiguration($searchArray, TRUE);
2500 }
2501 return $skipThisField;
2502 }
2503
2504 /**
2505 * Checks if a uid of a child table is in the inline view settings.
2506 *
2507 * @param string $table Name of the child table
2508 * @param int $uid uid of the the child record
2509 * @return bool TRUE=expand, FALSE=collapse
2510 */
2511 public function getExpandedCollapsedState($table, $uid) {
2512 if (isset($this->inlineView[$table]) && is_array($this->inlineView[$table])) {
2513 if (in_array($uid, $this->inlineView[$table]) !== FALSE) {
2514 return TRUE;
2515 }
2516 }
2517 return FALSE;
2518 }
2519
2520 /**
2521 * Update expanded/collapsed states on new inline records if any.
2522 *
2523 * @param array $uc The uc array to be processed and saved (by reference)
2524 * @param \TYPO3\CMS\Core\DataHandling\DataHandler $tce Instance of TCEmain that saved data before
2525 * @return void
2526 */
2527 static public function updateInlineView(&$uc, $tce) {
2528 if (isset($uc['inlineView']) && is_array($uc['inlineView'])) {
2529 $inlineView = (array)unserialize($GLOBALS['BE_USER']->uc['inlineView']);
2530 foreach ($uc['inlineView'] as $topTable => $topRecords) {
2531 foreach ($topRecords as $topUid => $childElements) {
2532 foreach ($childElements as $childTable => $childRecords) {
2533 $uids = array_keys($tce->substNEWwithIDs_table, $childTable);
2534 if (count($uids)) {
2535 $newExpandedChildren = array();
2536 foreach ($childRecords as $childUid => $state) {
2537 if ($state && in_array($childUid, $uids)) {
2538 $newChildUid = $tce->substNEWwithIDs[$childUid];
2539 $newExpandedChildren[] = $newChildUid;
2540 }
2541 }
2542 // Add new expanded child records to UC (if any):
2543 if (count($newExpandedChildren)) {
2544 $inlineViewCurrent = &$inlineView[$topTable][$topUid][$childTable];
2545 if (is_array($inlineViewCurrent)) {
2546 $inlineViewCurrent = array_unique(array_merge($inlineViewCurrent, $newExpandedChildren));
2547 } else {
2548 $inlineViewCurrent = $newExpandedChildren;
2549 }
2550 }
2551 }
2552 }
2553 }
2554 }
2555 $GLOBALS['BE_USER']->uc['inlineView'] = serialize($inlineView);
2556 $GLOBALS['BE_USER']->writeUC();
2557 }
2558 }
2559
2560 /**
2561 * Returns the the margin in pixels, that is used for each new inline level.
2562 *
2563 * @return int A pixel value for the margin of each new inline level.
2564 */
2565 public function getLevelMargin() {
2566 $margin = ($this->inlineStyles['margin-right'] + 1) * 2;
2567