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