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