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