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