e49ce2850ffb7d536d3a354a7d8be8f41a439ae5
[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\Versioning\VersionState;
24
25 /**
26 * The Inline-Relational-Record-Editing (IRRE) functions as part of the TCEforms.
27 *
28 * @author Oliver Hader <oliver@typo3.org>
29 */
30 class InlineElement {
31
32 const Structure_Separator = '-';
33 const FlexForm_Separator = '---';
34 const FlexForm_Substitute = ':';
35 const Disposal_AttributeName = 'Disposal_AttributeName';
36 const Disposal_AttributeId = 'Disposal_AttributeId';
37 /**
38 * Reference to the calling TCEforms instance
39 *
40 * @var \TYPO3\CMS\Backend\Form\FormEngine
41 * @todo Define visibility
42 */
43 public $fObj;
44
45 // Reference to $fObj->backPath
46 /**
47 * @todo Define visibility
48 */
49 public $backPath;
50
51 // Indicates if a field is rendered upon an AJAX call
52 /**
53 * @todo Define visibility
54 */
55 public $isAjaxCall = FALSE;
56
57 // The structure/hierarchy where working in, e.g. cascading inline tables
58 /**
59 * @todo Define visibility
60 */
61 public $inlineStructure = array();
62
63 // The first call of an inline type appeared on this page (pid of record)
64 /**
65 * @todo Define visibility
66 */
67 public $inlineFirstPid;
68
69 // Keys: form, object -> hold the name/id for each of them
70 /**
71 * @todo Define visibility
72 */
73 public $inlineNames = array();
74
75 // Inline data array used for JSON output
76 /**
77 * @todo Define visibility
78 */
79 public $inlineData = array();
80
81 // Expanded/collapsed states for the current BE user
82 /**
83 * @todo Define visibility
84 */
85 public $inlineView = array();
86
87 // Count the number of inline types used
88 /**
89 * @todo Define visibility
90 */
91 public $inlineCount = 0;
92
93 /**
94 * @todo Define visibility
95 */
96 public $inlineStyles = array();
97
98 // How the $this->fObj->prependFormFieldNames should be set ('data' is default)
99 /**
100 * @todo Define visibility
101 */
102 public $prependNaming = 'data';
103
104 // Reference to $this->fObj->prependFormFieldNames
105 /**
106 * @todo Define visibility
107 */
108 public $prependFormFieldNames;
109
110 // Reference to $this->fObj->prependCmdFieldNames
111 /**
112 * @todo Define visibility
113 */
114 public $prependCmdFieldNames;
115
116 // Array containing instances of hook classes called once for IRRE objects
117 protected $hookObjects = array();
118
119 /**
120 * Initialize
121 *
122 * @param \TYPO3\CMS\Backend\Form\FormEngine $tceForms Reference to an TCEforms instance
123 * @return void
124 * @todo Define visibility
125 */
126 public function init(&$tceForms) {
127 $this->fObj = $tceForms;
128 $this->backPath = &$tceForms->backPath;
129 $this->prependFormFieldNames = &$this->fObj->prependFormFieldNames;
130 $this->prependCmdFieldNames = &$this->fObj->prependCmdFieldNames;
131 $this->inlineStyles['margin-right'] = '5';
132 $this->initHookObjects();
133 }
134
135 /**
136 * Initialized the hook objects for this class.
137 * Each hook object has to implement the interface
138 * \TYPO3\CMS\Backend\Form\Element\InlineElementHookInterface
139 *
140 * @return void
141 */
142 protected function initHookObjects() {
143 $this->hookObjects = array();
144 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['tceformsInlineHook'])) {
145 $tceformsInlineHook = &$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['tceformsInlineHook'];
146 if (is_array($tceformsInlineHook)) {
147 foreach ($tceformsInlineHook as $classData) {
148 $processObject = GeneralUtility::getUserObj($classData);
149 if (!$processObject instanceof \TYPO3\CMS\Backend\Form\Element\InlineElementHookInterface) {
150 throw new \UnexpectedValueException('$processObject must implement interface TYPO3\\CMS\\Backend\\Form\\Element\\InlineElementHookInterface', 1202072000);
151 }
152 $processObject->init($this);
153 $this->hookObjects[] = $processObject;
154 }
155 }
156 }
157 }
158
159 /**
160 * Generation of TCEform elements of the type "inline"
161 * This will render inline-relational-record sets. Relations.
162 *
163 * @param string $table The table name of the record
164 * @param string $field The field name which this element is supposed to edit
165 * @param array $row The record data array where the value(s) for the field can be found
166 * @param array $PA An array with additional configuration options.
167 * @return string The HTML code for the TCEform field
168 * @todo Define visibility
169 */
170 public function getSingleField_typeInline($table, $field, $row, &$PA) {
171 // Check the TCA configuration - if FALSE is returned, something was wrong
172 if ($this->checkConfiguration($PA['fieldConf']['config']) === FALSE) {
173 return FALSE;
174 }
175 $item = '';
176 $levelLinks = '';
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 // Render the level links (create new record):
288 } else {
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 $foreign_table = $conf['foreign_table'];
882 $config = $PA['fieldConf']['config'];
883 $allowed = $config['allowed'];
884 $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $foreign_table;
885 $mode = 'db';
886 $showUpload = FALSE;
887 if (!empty($conf['appearance']['createNewRelationLinkTitle'])) {
888 $createNewRelationText = $GLOBALS['LANG']->sL($conf['appearance']['createNewRelationLinkTitle'], TRUE);
889 } else {
890 $createNewRelationText = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:cm.createNewRelation', TRUE);
891 }
892 if (is_array($config['appearance'])) {
893 if (isset($config['appearance']['elementBrowserType'])) {
894 $mode = $config['appearance']['elementBrowserType'];
895 }
896 if ($mode === 'file') {
897 $showUpload = TRUE;
898 }
899 if (isset($config['appearance']['fileUploadAllowed'])) {
900 $showUpload = (bool)$config['appearance']['fileUploadAllowed'];
901 }
902 if (isset($config['appearance']['elementBrowserAllowed'])) {
903 $allowed = $config['appearance']['elementBrowserAllowed'];
904 }
905 }
906 $browserParams = '|||' . $allowed . '|' . $objectPrefix . '|inline.checkUniqueElement||inline.importElement';
907 $onClick = 'setFormValueOpenBrowser(\'' . $mode . '\', \'' . $browserParams . '\'); return false;';
908
909 $item = '<a href="#" class="t3-button" onclick="' . htmlspecialchars($onClick) . '">';
910 $item .= IconUtility::getSpriteIcon('actions-insert-record', array('title' => $createNewRelationText));
911 $item .= $createNewRelationText . '</a>';
912
913 if ($showUpload && $this->fObj->edit_docModuleUpload) {
914 $folder = $GLOBALS['BE_USER']->getDefaultUploadFolder();
915 if (
916 $folder instanceof \TYPO3\CMS\Core\Resource\Folder
917 && $folder->checkActionPermission('add')
918 ) {
919 $maxFileSize = GeneralUtility::getMaxUploadFileSize() * 1024;
920 $item .= ' <a href="#" class="t3-button t3-drag-uploader"
921 style="display:none"
922 data-dropzone-target="#' . htmlspecialchars($this->inlineNames['object']) . '"
923 data-insert-dropzone-before="1"
924 data-file-irre-object="' . htmlspecialchars($objectPrefix) . '"
925 data-file-allowed="' . htmlspecialchars($allowed) . '"
926 data-target-folder="' . htmlspecialchars($folder->getCombinedIdentifier()) . '"
927 data-max-file-size="' . htmlspecialchars($maxFileSize) . '"
928 ><span class="t3-icon t3-icon-actions t3-icon-actions-edit t3-icon-edit-upload">&nbsp;</span>';
929 $item .= $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:file_upload.select-and-submit', TRUE);
930 $item .= '</a>';
931
932 $this->loadDragUploadJs();
933 }
934 }
935 return $item;
936 }
937
938 /**
939 * Load the required javascript for the DragUploader
940 */
941 protected function loadDragUploadJs() {
942
943 /** @var $pageRenderer \TYPO3\CMS\Core\Page\PageRenderer */
944 $pageRenderer = $GLOBALS['SOBE']->doc->getPageRenderer();
945 $pageRenderer->loadRequireJsModule('TYPO3/CMS/Filelist/FileListLocalisation');
946 $pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/DragUploader');
947 $pageRenderer->addInlineLanguagelabelFile(
948 \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('lang') . 'locallang_core.xlf',
949 'file_upload'
950 );
951 }
952
953 /**
954 * Creates the HTML code of a general link to be used on a level of inline children.
955 * The possible keys for the parameter $type are 'newRecord', 'localize' and 'synchronize'.
956 *
957 * @param string $type The link type, values are 'newRecord', 'localize' and 'synchronize'.
958 * @param string $objectPrefix The "path" to the child record to create (e.g. 'data-parentPageId-partenTable-parentUid-parentField-childTable]')
959 * @param array $conf TCA configuration of the parent(!) field
960 * @return string The HTML code of the new link, wrapped in a div
961 */
962 protected function getLevelInteractionLink($type, $objectPrefix, $conf = array()) {
963 $nameObject = $this->inlineNames['object'];
964 $attributes = array();
965 switch ($type) {
966 case 'newRecord':
967 $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:cm.createnew', TRUE);
968 $icon = 'actions-document-new';
969 $className = 'typo3-newRecordLink';
970 $attributes['class'] = 't3-button inlineNewButton ' . $this->inlineData['config'][$nameObject]['md5'];
971 $attributes['onclick'] = 'return inline.createNewRecord(\'' . $objectPrefix . '\')';
972 if (!empty($conf['inline']['inlineNewButtonStyle'])) {
973 $attributes['style'] = $conf['inline']['inlineNewButtonStyle'];
974 }
975 if (!empty($conf['appearance']['newRecordLinkAddTitle'])) {
976 $title = sprintf(
977 $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:cm.createnew.link', TRUE),
978 $GLOBALS['LANG']->sL($GLOBALS['TCA'][$conf['foreign_table']]['ctrl']['title'], TRUE)
979 );
980 } elseif (isset($conf['appearance']['newRecordLinkTitle']) && $conf['appearance']['newRecordLinkTitle'] !== '') {
981 $title = $GLOBALS['LANG']->sL($conf['appearance']['newRecordLinkTitle'], TRUE);
982 }
983 break;
984 case 'localize':
985 $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xlf:localizeAllRecords', 1);
986 $icon = 'actions-document-localize';
987 $className = 'typo3-localizationLink';
988 $attributes['class'] = 't3-button';
989 $attributes['onclick'] = 'return inline.synchronizeLocalizeRecords(\'' . $objectPrefix . '\', \'localize\')';
990 break;
991 case 'synchronize':
992 $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_misc.xlf:synchronizeWithOriginalLanguage', TRUE);
993 $icon = 'actions-document-synchronize';
994 $className = 'typo3-synchronizationLink';
995 $attributes['class'] = 't3-button inlineNewButton ' . $this->inlineData['config'][$nameObject]['md5'];
996 $attributes['onclick'] = 'return inline.synchronizeLocalizeRecords(\'' . $objectPrefix . '\', \'synchronize\')';
997 break;
998 default:
999 $title = '';
1000 $icon = '';
1001 $className = '';
1002 }
1003 // Create the link:
1004 $icon = $icon ? IconUtility::getSpriteIcon($icon, array('title' => htmlspecialchars($title))) : '';
1005 $link = $this->wrapWithAnchor($icon . $title, '#', $attributes);
1006 return '<div' . ($className ? ' class="' . $className . '"' : '') . '>' . $link . '</div>';
1007 }
1008
1009 /**
1010 * Add Sortable functionality using script.acolo.us "Sortable".
1011 *
1012 * @param string $objectId The container id of the object - elements inside will be sortable
1013 * @return void
1014 * @todo Define visibility
1015 */
1016 public function addJavaScriptSortable($objectId) {
1017 $this->fObj->additionalJS_post[] = '
1018 inline.createDragAndDropSorting("' . $objectId . '");
1019 ';
1020 }
1021
1022 /*******************************************************
1023 *
1024 * Handling of AJAX calls
1025 *
1026 *******************************************************/
1027 /**
1028 * General processor for AJAX requests concerning IRRE.
1029 * (called by typo3/ajax.php)
1030 *
1031 * @param array $params Additional parameters (not used here)
1032 * @param \TYPO3\CMS\Core\Http\AjaxRequestHandler $ajaxObj The AjaxRequestHandler object of this request
1033 * @return void
1034 */
1035 public function processAjaxRequest($params, $ajaxObj) {
1036 $ajaxArguments = GeneralUtility::_GP('ajax');
1037 $ajaxIdParts = explode('::', $GLOBALS['ajaxID'], 2);
1038 if (isset($ajaxArguments) && is_array($ajaxArguments) && count($ajaxArguments)) {
1039 $ajaxMethod = $ajaxIdParts[1];
1040 switch ($ajaxMethod) {
1041 case 'createNewRecord':
1042
1043 case 'synchronizeLocalizeRecords':
1044
1045 case 'getRecordDetails':
1046 $this->isAjaxCall = TRUE;
1047 // Construct runtime environment for Inline Relational Record Editing:
1048 $this->processAjaxRequestConstruct($ajaxArguments);
1049 // Parse the DOM identifier (string), add the levels to the structure stack (array) and load the TCA config:
1050 $this->parseStructureString($ajaxArguments[0], TRUE);
1051 $this->injectAjaxConfiguration($ajaxArguments);
1052 // Render content:
1053 $ajaxObj->setContentFormat('jsonbody');
1054 $ajaxObj->setContent(call_user_func_array(array(&$this, $ajaxMethod), $ajaxArguments));
1055 break;
1056 case 'setExpandedCollapsedState':
1057 $ajaxObj->setContentFormat('jsonbody');
1058 call_user_func_array(array(&$this, $ajaxMethod), $ajaxArguments);
1059 break;
1060 }
1061 }
1062 }
1063
1064 /**
1065 * Injects configuration via AJAX calls.
1066 * The configuration is validated using HMAC to avoid hijacking.
1067 *
1068 * @param array $ajaxArguments
1069 * @return void
1070 */
1071 protected function injectAjaxConfiguration(array $ajaxArguments) {
1072 $level = $this->calculateStructureLevel(-1);
1073
1074 if (empty($ajaxArguments['context']) || $level === FALSE) {
1075 return;
1076 }
1077
1078 $current = &$this->inlineStructure['stable'][$level];
1079 $context = json_decode($ajaxArguments['context'], TRUE);
1080
1081 if (GeneralUtility::hmac(serialize($context['config'])) !== $context['hmac']) {
1082 return;
1083 }
1084
1085 $current['config'] = $context['config'];
1086 $current['localizationMode'] = BackendUtility::getInlineLocalizationMode(
1087 $current['table'],
1088 $current['config']
1089 );
1090 }
1091
1092 /**
1093 * Construct runtime environment for Inline Relational Record Editing.
1094 * - creates an anoymous SC_alt_doc in $GLOBALS['SOBE']
1095 * - creates a \TYPO3\CMS\Backend\Form\FormEngine in $GLOBALS['SOBE']->tceforms
1096 * - sets ourself as reference to $GLOBALS['SOBE']->tceforms->inline
1097 * - sets $GLOBALS['SOBE']->tceforms->RTEcounter to the current situation on client-side
1098 *
1099 * @param array &$ajaxArguments The arguments to be processed by the AJAX request
1100 * @return void
1101 */
1102 protected function processAjaxRequestConstruct(&$ajaxArguments) {
1103 $GLOBALS['LANG']->includeLLFile('EXT:lang/locallang_alt_doc.xlf');
1104 // Create a new anonymous object:
1105 $GLOBALS['SOBE'] = new \stdClass();
1106 $GLOBALS['SOBE']->MOD_MENU = array(
1107 'showPalettes' => '',
1108 'showDescriptions' => '',
1109 'disableRTE' => ''
1110 );
1111 // Setting virtual document name
1112 $GLOBALS['SOBE']->MCONF['name'] = 'xMOD_alt_doc.php';
1113 // CLEANSE SETTINGS
1114 $GLOBALS['SOBE']->MOD_SETTINGS = BackendUtility::getModuleData($GLOBALS['SOBE']->MOD_MENU, GeneralUtility::_GP('SET'), $GLOBALS['SOBE']->MCONF['name']);
1115 // Create an instance of the document template object
1116 $GLOBALS['SOBE']->doc = GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Template\\DocumentTemplate');
1117 $GLOBALS['SOBE']->doc->backPath = $GLOBALS['BACK_PATH'];
1118 // Initialize TCEforms (rendering the forms)
1119 $GLOBALS['SOBE']->tceforms = GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Form\\FormEngine');
1120 $GLOBALS['SOBE']->tceforms->inline = $this;
1121 $GLOBALS['SOBE']->tceforms->RTEcounter = (int)array_shift($ajaxArguments);
1122 $GLOBALS['SOBE']->tceforms->initDefaultBEMode();
1123 $GLOBALS['SOBE']->tceforms->palettesCollapsed = !$GLOBALS['SOBE']->MOD_SETTINGS['showPalettes'];
1124 $GLOBALS['SOBE']->tceforms->disableRTE = $GLOBALS['SOBE']->MOD_SETTINGS['disableRTE'];
1125 $GLOBALS['SOBE']->tceforms->enableClickMenu = TRUE;
1126 $GLOBALS['SOBE']->tceforms->enableTabMenu = TRUE;
1127 // Clipboard is initialized:
1128 // Start clipboard
1129 $GLOBALS['SOBE']->tceforms->clipObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Clipboard\\Clipboard');
1130 // Initialize - reads the clipboard content from the user session
1131 $GLOBALS['SOBE']->tceforms->clipObj->initializeClipboard();
1132 }
1133
1134 /**
1135 * Determines and sets several script calls to a JSON array, that would have been executed if processed in non-AJAX mode.
1136 *
1137 * @param array &$jsonArray Reference of the array to be used for JSON
1138 * @param array $config The configuration of the IRRE field of the parent record
1139 * @return void
1140 */
1141 protected function getCommonScriptCalls(&$jsonArray, $config) {
1142 // Add data that would have been added at the top of a regular TCEforms call:
1143 if ($headTags = $this->getHeadTags()) {
1144 $jsonArray['headData'] = $headTags;
1145 }
1146 // Add the JavaScript data that would have been added at the bottom of a regular TCEforms call:
1147 $jsonArray['scriptCall'][] = $this->fObj->JSbottom($this->fObj->formName, TRUE);
1148 // If script.aculo.us Sortable is used, update the Observer to know the record:
1149 if ($config['appearance']['useSortable']) {
1150 $jsonArray['scriptCall'][] = 'inline.createDragAndDropSorting(\'' . $this->inlineNames['object'] . '_records\');';
1151 }
1152 // if TCEforms has some JavaScript code to be executed, just do it
1153 if ($this->fObj->extJSCODE) {
1154 $jsonArray['scriptCall'][] = $this->fObj->extJSCODE;
1155 }
1156 }
1157
1158 /**
1159 * Generates an error message that transferred as JSON for AJAX calls
1160 *
1161 * @param string $message The error message to be shown
1162 * @return array The error message in a JSON array
1163 */
1164 protected function getErrorMessageForAJAX($message) {
1165 $jsonArray = array(
1166 'data' => $message,
1167 'scriptCall' => array(
1168 'alert("' . $message . '");'
1169 )
1170 );
1171 return $jsonArray;
1172 }
1173
1174 /**
1175 * Handle AJAX calls to show a new inline-record of the given table.
1176 * Normally this method is never called from inside TYPO3. Always from outside by AJAX.
1177 *
1178 * @param string $domObjectId The calling object in hierarchy, that requested a new record.
1179 * @param string $foreignUid If set, the new record should be inserted after that one.
1180 * @return array An array to be used for JSON
1181 * @todo Define visibility
1182 */
1183 public function createNewRecord($domObjectId, $foreignUid = 0) {
1184 // The current table - for this table we should add/import records
1185 $current = $this->inlineStructure['unstable'];
1186 // The parent table - this table embeds the current table
1187 $parent = $this->getStructureLevel(-1);
1188 $config = $parent['config'];
1189 // Get TCA 'config' of the parent table
1190 if (!$this->checkConfiguration($config)) {
1191 return $this->getErrorMessageForAJAX('Wrong configuration in table ' . $parent['table']);
1192 }
1193 $collapseAll = isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll'];
1194 $expandSingle = isset($config['appearance']['expandSingle']) && $config['appearance']['expandSingle'];
1195 // Put the current level also to the dynNestedStack of TCEforms:
1196 $this->fObj->pushToDynNestedStack('inline', $this->inlineNames['object']);
1197 // Dynamically create a new record using \TYPO3\CMS\Backend\Form\DataPreprocessor
1198 if (!$foreignUid || !MathUtility::canBeInterpretedAsInteger($foreignUid) || $config['foreign_selector']) {
1199 $record = $this->getNewRecord($this->inlineFirstPid, $current['table']);
1200 // Set default values for new created records
1201 if (isset($config['foreign_record_defaults']) && is_array($config['foreign_record_defaults'])) {
1202 $foreignTableConfig = $GLOBALS['TCA'][$current['table']];
1203 // the following system relevant fields can't be set by foreign_record_defaults
1204 $notSettableFields = array(
1205 'uid', 'pid', 't3ver_oid', 't3ver_id', 't3ver_label', 't3ver_wsid', 't3ver_state', 't3ver_stage',
1206 't3ver_count', 't3ver_tstamp', 't3ver_move_id'
1207 );
1208 $configurationKeysForNotSettableFields = array(
1209 'crdate', 'cruser_id', 'delete', 'origUid', 'transOrigDiffSourceField', 'transOrigPointerField',
1210 'tstamp'
1211 );
1212 foreach ($configurationKeysForNotSettableFields as $configurationKey) {
1213 if (isset($foreignTableConfig['ctrl'][$configurationKey])) {
1214 $notSettableFields[] = $foreignTableConfig['ctrl'][$configurationKey];
1215 }
1216 }
1217 foreach ($config['foreign_record_defaults'] as $fieldName => $defaultValue) {
1218 if (isset($foreignTableConfig['columns'][$fieldName]) && !in_array($fieldName, $notSettableFields)) {
1219 $record[$fieldName] = $defaultValue;
1220 }
1221 }
1222 }
1223 // Set language of new child record to the language of the parent record:
1224 if ($parent['localizationMode'] === 'select') {
1225 $parentRecord = $this->getRecord(0, $parent['table'], $parent['uid']);
1226 $parentLanguageField = $GLOBALS['TCA'][$parent['table']]['ctrl']['languageField'];
1227 $childLanguageField = $GLOBALS['TCA'][$current['table']]['ctrl']['languageField'];
1228 if ($parentRecord[$parentLanguageField] > 0) {
1229 $record[$childLanguageField] = $parentRecord[$parentLanguageField];
1230 }
1231 }
1232 } else {
1233 $record = $this->getRecord($this->inlineFirstPid, $current['table'], $foreignUid);
1234 }
1235 // Now there is a foreign_selector, so there is a new record on the intermediate table, but
1236 // this intermediate table holds a field, which is responsible for the foreign_selector, so
1237 // we have to set this field to the uid we get - or if none, to a new uid
1238 if ($config['foreign_selector'] && $foreignUid) {
1239 $selConfig = $this->getPossibleRecordsSelectorConfig($config, $config['foreign_selector']);
1240 // For a selector of type group/db, prepend the tablename (<tablename>_<uid>):
1241 $record[$config['foreign_selector']] = $selConfig['type'] != 'groupdb' ? '' : $selConfig['table'] . '_';
1242 $record[$config['foreign_selector']] .= $foreignUid;
1243 }
1244 // The HTML-object-id's prefix of the dynamically created record
1245 $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $current['table'];
1246 $objectId = $objectPrefix . self::Structure_Separator . $record['uid'];
1247 // Render the foreign record that should passed back to browser
1248 $item = $this->renderForeignRecord($parent['uid'], $record, $config);
1249 if ($item === FALSE) {
1250 return $this->getErrorMessageForAJAX('Access denied');
1251 }
1252 if (!$current['uid']) {
1253 $jsonArray = array(
1254 'data' => $item,
1255 'scriptCall' => array(
1256 'inline.domAddNewRecord(\'bottom\',\'' . $this->inlineNames['object'] . '_records\',\'' . $objectPrefix . '\',json.data);',
1257 'inline.memorizeAddRecord(\'' . $objectPrefix . '\',\'' . $record['uid'] . '\',null,\'' . $foreignUid . '\');'
1258 )
1259 );
1260 } else {
1261 $jsonArray = array(
1262 'data' => $item,
1263 'scriptCall' => array(
1264 'inline.domAddNewRecord(\'after\',\'' . $domObjectId . '_div' . '\',\'' . $objectPrefix . '\',json.data);',
1265 'inline.memorizeAddRecord(\'' . $objectPrefix . '\',\'' . $record['uid'] . '\',\'' . $current['uid'] . '\',\'' . $foreignUid . '\');'
1266 )
1267 );
1268 }
1269 $this->getCommonScriptCalls($jsonArray, $config);
1270 // Collapse all other records if requested:
1271 if (!$collapseAll && $expandSingle) {
1272 $jsonArray['scriptCall'][] = 'inline.collapseAllRecords(\'' . $objectId . '\', \'' . $objectPrefix . '\', \'' . $record['uid'] . '\');';
1273 }
1274 // Tell the browser to scroll to the newly created record
1275 $jsonArray['scriptCall'][] = 'Element.scrollTo(\'' . $objectId . '_div\');';
1276 // Fade out and fade in the new record in the browser view to catch the user's eye
1277 $jsonArray['scriptCall'][] = 'inline.fadeOutFadeIn(\'' . $objectId . '_div\');';
1278 // Remove the current level also from the dynNestedStack of TCEforms:
1279 $this->fObj->popFromDynNestedStack();
1280 // Return the JSON array:
1281 return $jsonArray;
1282 }
1283
1284 /**
1285 * Handle AJAX calls to localize all records of a parent, localize a single record or to synchronize with the original language parent.
1286 *
1287 * @param string $domObjectId The calling object in hierarchy, that requested a new record.
1288 * @param mixed $type Defines the type 'localize' or 'synchronize' (string) or a single uid to be localized (integer)
1289 * @return array An array to be used for JSON
1290 */
1291 protected function synchronizeLocalizeRecords($domObjectId, $type) {
1292 $jsonArray = FALSE;
1293 if (GeneralUtility::inList('localize,synchronize', $type) || MathUtility::canBeInterpretedAsInteger($type)) {
1294 // The current level:
1295 $current = $this->inlineStructure['unstable'];
1296 // The parent level:
1297 $parent = $this->getStructureLevel(-1);
1298 $parentRecord = $this->getRecord(0, $parent['table'], $parent['uid']);
1299 $cmd = array();
1300 $cmd[$parent['table']][$parent['uid']]['inlineLocalizeSynchronize'] = $parent['field'] . ',' . $type;
1301 /** @var $tce \TYPO3\CMS\Core\DataHandling\DataHandler */
1302 $tce = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\DataHandling\\DataHandler');
1303 $tce->stripslashes_values = FALSE;
1304 $tce->start(array(), $cmd);
1305 $tce->process_cmdmap();
1306 $newItemList = $tce->registerDBList[$parent['table']][$parent['uid']][$parent['field']];
1307 unset($tce);
1308 $jsonArray = $this->getExecuteChangesJsonArray($parentRecord[$parent['field']], $newItemList);
1309 $this->getCommonScriptCalls($jsonArray, $parent['config']);
1310 }
1311 return $jsonArray;
1312 }
1313
1314 /**
1315 * Handle AJAX calls to dynamically load the form fields of a given record.
1316 * (basically a copy of "createNewRecord")
1317 * Normally this method is never called from inside TYPO3. Always from outside by AJAX.
1318 *
1319 * @param string $domObjectId The calling object in hierarchy, that requested a new record.
1320 * @return array An array to be used for JSON
1321 * @todo Define visibility
1322 */
1323 public function getRecordDetails($domObjectId) {
1324 // The current table - for this table we should add/import records
1325 $current = $this->inlineStructure['unstable'];
1326 // The parent table - this table embeds the current table
1327 $parent = $this->getStructureLevel(-1);
1328 // Get TCA 'config' of the parent table
1329 if (!$this->checkConfiguration($parent['config'])) {
1330 return $this->getErrorMessageForAJAX('Wrong configuration in table ' . $parent['table']);
1331 }
1332 $config = $parent['config'];
1333 // Set flag in config so that only the fields are rendered
1334 $config['renderFieldsOnly'] = TRUE;
1335 $collapseAll = isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll'];
1336 $expandSingle = isset($config['appearance']['expandSingle']) && $config['appearance']['expandSingle'];
1337 // Put the current level also to the dynNestedStack of TCEforms:
1338 $this->fObj->pushToDynNestedStack('inline', $this->inlineNames['object']);
1339 $record = $this->getRecord($this->inlineFirstPid, $current['table'], $current['uid']);
1340 // The HTML-object-id's prefix of the dynamically created record
1341 $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $current['table'];
1342 $objectId = $objectPrefix . self::Structure_Separator . $record['uid'];
1343 $item = $this->renderForeignRecord($parent['uid'], $record, $config);
1344 if ($item === FALSE) {
1345 return $this->getErrorMessageForAJAX('Access denied');
1346 }
1347 $jsonArray = array(
1348 'data' => $item,
1349 'scriptCall' => array(
1350 'inline.domAddRecordDetails(\'' . $domObjectId . '\',\'' . $objectPrefix . '\',' . ($expandSingle ? '1' : '0') . ',json.data);'
1351 )
1352 );
1353 if ($config['foreign_unique']) {
1354 $jsonArray['scriptCall'][] = 'inline.removeUsed(\'' . $objectPrefix . '\',\'' . $record['uid'] . '\');';
1355 }
1356 $this->getCommonScriptCalls($jsonArray, $config);
1357 // Collapse all other records if requested:
1358 if (!$collapseAll && $expandSingle) {
1359 $jsonArray['scriptCall'][] = 'inline.collapseAllRecords(\'' . $objectId . '\',\'' . $objectPrefix . '\',\'' . $record['uid'] . '\');';
1360 }
1361 // Remove the current level also from the dynNestedStack of TCEforms:
1362 $this->fObj->popFromDynNestedStack();
1363 // Return the JSON array:
1364 return $jsonArray;
1365 }
1366
1367 /**
1368 * Generates a JSON array which executes the changes and thus updates the forms view.
1369 *
1370 * @param string $oldItemList List of related child reocrds before changes were made (old)
1371 * @param string $newItemList List of related child records after changes where made (new)
1372 * @return array An array to be used for JSON
1373 */
1374 protected function getExecuteChangesJsonArray($oldItemList, $newItemList) {
1375 $data = '';
1376 $parent = $this->getStructureLevel(-1);
1377 $current = $this->inlineStructure['unstable'];
1378 $jsonArray = array('scriptCall' => array());
1379 $jsonArrayScriptCall = &$jsonArray['scriptCall'];
1380 $nameObject = $this->inlineNames['object'];
1381 $nameObjectForeignTable = $nameObject . self::Structure_Separator . $current['table'];
1382 // Get the name of the field pointing to the original record:
1383 $transOrigPointerField = $GLOBALS['TCA'][$current['table']]['ctrl']['transOrigPointerField'];
1384 // Get the name of the field used as foreign selector (if any):
1385 $foreignSelector = isset($parent['config']['foreign_selector']) && $parent['config']['foreign_selector'] ? $parent['config']['foreign_selector'] : FALSE;
1386 // Convert lists to array with uids of child records:
1387 $oldItems = $this->getRelatedRecordsUidArray($oldItemList);
1388 $newItems = $this->getRelatedRecordsUidArray($newItemList);
1389 // Determine the items that were localized or localized:
1390 $removedItems = array_diff($oldItems, $newItems);
1391 $localizedItems = array_diff($newItems, $oldItems);
1392 // Set the items that should be removed in the forms view:
1393 foreach ($removedItems as $item) {
1394 $jsonArrayScriptCall[] = 'inline.deleteRecord(\'' . $nameObjectForeignTable . self::Structure_Separator . $item . '\', {forceDirectRemoval: true});';
1395 }
1396 // Set the items that should be added in the forms view:
1397 foreach ($localizedItems as $item) {
1398 $row = $this->getRecord($this->inlineFirstPid, $current['table'], $item);
1399 $selectedValue = $foreignSelector ? '\'' . $row[$foreignSelector] . '\'' : 'null';
1400 $data .= $this->renderForeignRecord($parent['uid'], $row, $parent['config']);
1401 $jsonArrayScriptCall[] = 'inline.memorizeAddRecord(\'' . $nameObjectForeignTable . '\', \'' . $item . '\', null, ' . $selectedValue . ');';
1402 // Remove possible virtual records in the form which showed that a child records could be localized:
1403 if (isset($row[$transOrigPointerField]) && $row[$transOrigPointerField]) {
1404 $jsonArrayScriptCall[] = 'inline.fadeAndRemove(\'' . $nameObjectForeignTable . self::Structure_Separator . $row[$transOrigPointerField] . '_div' . '\');';
1405 }
1406 }
1407 if ($data) {
1408 $jsonArray['data'] = $data;
1409 array_unshift($jsonArrayScriptCall, 'inline.domAddNewRecord(\'bottom\', \'' . $nameObject . '_records\', \'' . $nameObjectForeignTable . '\', json.data);');
1410 }
1411 return $jsonArray;
1412 }
1413
1414 /**
1415 * Save the expanded/collapsed state of a child record in the BE_USER->uc.
1416 *
1417 * @param string $domObjectId The calling object in hierarchy, that requested a new record.
1418 * @param string $expand Whether this record is expanded.
1419 * @param string $collapse Whether this record is collapsed.
1420 * @return void
1421 * @todo Define visibility
1422 */
1423 public function setExpandedCollapsedState($domObjectId, $expand, $collapse) {
1424 // Parse the DOM identifier (string), add the levels to the structure stack (array), but don't load TCA config
1425 $this->parseStructureString($domObjectId, FALSE);
1426 // The current table - for this table we should add/import records
1427 $current = $this->inlineStructure['unstable'];
1428 // The top parent table - this table embeds the current table
1429 $top = $this->getStructureLevel(0);
1430 // Only do some action if the top record and the current record were saved before
1431 if (MathUtility::canBeInterpretedAsInteger($top['uid'])) {
1432 $inlineView = (array) unserialize($GLOBALS['BE_USER']->uc['inlineView']);
1433 $inlineViewCurrent = &$inlineView[$top['table']][$top['uid']];
1434 $expandUids = GeneralUtility::trimExplode(',', $expand);
1435 $collapseUids = GeneralUtility::trimExplode(',', $collapse);
1436 // Set records to be expanded
1437 foreach ($expandUids as $uid) {
1438 $inlineViewCurrent[$current['table']][] = $uid;
1439 }
1440 // Set records to be collapsed
1441 foreach ($collapseUids as $uid) {
1442 $inlineViewCurrent[$current['table']] = $this->removeFromArray($uid, $inlineViewCurrent[$current['table']]);
1443 }
1444 // Save states back to database
1445 if (is_array($inlineViewCurrent[$current['table']])) {
1446 $inlineViewCurrent[$current['table']] = array_unique($inlineViewCurrent[$current['table']]);
1447 $GLOBALS['BE_USER']->uc['inlineView'] = serialize($inlineView);
1448 $GLOBALS['BE_USER']->writeUC();
1449 }
1450 }
1451 }
1452
1453 /*******************************************************
1454 *
1455 * Get data from database and handle relations
1456 *
1457 *******************************************************/
1458 /**
1459 * Get the related records of the embedding item, this could be 1:n, m:n.
1460 * Returns an associative array with the keys records and count. 'count' contains only real existing records on the current parent record.
1461 *
1462 * @param string $table The table name of the record
1463 * @param string $field The field name which this element is supposed to edit
1464 * @param array $row The record data array where the value(s) for the field can be found
1465 * @param array $PA An array with additional configuration options.
1466 * @param array $config (Redundant) content of $PA['fieldConf']['config'] (for convenience)
1467 * @return array The records related to the parent item as associative array.
1468 * @todo Define visibility
1469 */
1470 public function getRelatedRecords($table, $field, $row, &$PA, $config) {
1471 $language = 0;
1472 $pid = $row['pid'];
1473 $elements = $PA['itemFormElValue'];
1474 $foreignTable = $config['foreign_table'];
1475 $localizationMode = BackendUtility::getInlineLocalizationMode($table, $config);
1476 if ($localizationMode != FALSE) {
1477 $language = (int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']];
1478 $transOrigPointer = (int)$row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']];
1479 $transOrigTable = BackendUtility::getOriginalTranslationTable($table);
1480
1481 if ($language > 0 && $transOrigPointer) {
1482 // Localization in mode 'keep', isn't a real localization, but keeps the children of the original parent record:
1483 if ($localizationMode == 'keep') {
1484 $transOrigRec = $this->getRecord(0, $transOrigTable, $transOrigPointer);
1485 $elements = $transOrigRec[$field];
1486 $pid = $transOrigRec['pid'];
1487 } elseif ($localizationMode == 'select') {
1488 $transOrigRec = $this->getRecord(0, $transOrigTable, $transOrigPointer);
1489 $pid = $transOrigRec['pid'];
1490 $recordsOriginal = $this->getRelatedRecordsArray($pid, $foreignTable, $transOrigRec[$field]);
1491 }
1492 }
1493 }
1494 $records = $this->getRelatedRecordsArray($pid, $foreignTable, $elements);
1495 $relatedRecords = array('records' => $records, 'count' => count($records));
1496 // Merge original language with current localization and show differences:
1497 if (!empty($recordsOriginal)) {
1498 $options = array(
1499 'showPossible' => isset($config['appearance']['showPossibleLocalizationRecords']) && $config['appearance']['showPossibleLocalizationRecords'],
1500 'showRemoved' => isset($config['appearance']['showRemovedLocalizationRecords']) && $config['appearance']['showRemovedLocalizationRecords']
1501 );
1502 // Either show records that possibly can localized or removed
1503 if ($options['showPossible'] || $options['showRemoved']) {
1504 $relatedRecords['records'] = $this->getLocalizationDifferences($foreignTable, $options, $recordsOriginal, $records);
1505 // Otherwise simulate localizeChildrenAtParentLocalization behaviour when creating a new record
1506 // (which has language and translation pointer values set)
1507 } elseif (!empty($config['behaviour']['localizeChildrenAtParentLocalization']) && !MathUtility::canBeInterpretedAsInteger($row['uid'])) {
1508 if (!empty($GLOBALS['TCA'][$foreignTable]['ctrl']['transOrigPointerField'])) {
1509 $foreignLanguageField = $GLOBALS['TCA'][$foreignTable]['ctrl']['languageField'];
1510 }
1511 if (!empty($GLOBALS['TCA'][$foreignTable]['ctrl']['transOrigPointerField'])) {
1512 $foreignTranslationPointerField = $GLOBALS['TCA'][$foreignTable]['ctrl']['transOrigPointerField'];
1513 }
1514 // Duplicate child records of default language in form
1515 foreach ($recordsOriginal as $record) {
1516 if (!empty($foreignLanguageField)) {
1517 $record[$foreignLanguageField] = $language;
1518 }
1519 if (!empty($foreignTranslationPointerField)) {
1520 $record[$foreignTranslationPointerField] = $record['uid'];
1521 }
1522 $newId = uniqid('NEW');
1523 $record['uid'] = $newId;
1524 $record['pid'] = $this->inlineFirstPid;
1525 $relatedRecords['records'][$newId] = $record;
1526 }
1527 }
1528 }
1529 return $relatedRecords;
1530 }
1531
1532 /**
1533 * Gets the related records of the embedding item, this could be 1:n, m:n.
1534 *
1535 * @param integer $pid The pid of the parent record
1536 * @param string $table The table name of the record
1537 * @param string $itemList The list of related child records
1538 * @return array The records related to the parent item
1539 */
1540 protected function getRelatedRecordsArray($pid, $table, $itemList) {
1541 $records = array();
1542 $itemArray = $this->getRelatedRecordsUidArray($itemList);
1543 // Perform modification of the selected items array:
1544 foreach ($itemArray as $uid) {
1545 // Get the records for this uid using \TYPO3\CMS\Backend\Form\DataPreprocessor
1546 if ($record = $this->getRecord($pid, $table, $uid)) {
1547 $records[$uid] = $record;
1548 }
1549 }
1550 return $records;
1551 }
1552
1553 /**
1554 * Gets an array with the uids of related records out of a list of items.
1555 * This list could contain more information than required. This methods just
1556 * extracts the uids.
1557 *
1558 * @param string $itemList The list of related child records
1559 * @return array An array with uids
1560 */
1561 protected function getRelatedRecordsUidArray($itemList) {
1562 $itemArray = GeneralUtility::trimExplode(',', $itemList, TRUE);
1563 // Perform modification of the selected items array:
1564 foreach ($itemArray as $key => &$value) {
1565 $parts = explode('|', $value, 2);
1566 $value = $parts[0];
1567 }
1568 unset($value);
1569 return $itemArray;
1570 }
1571
1572 /**
1573 * Gets the difference between current localized structure and the original language structure.
1574 * If there are records which once were localized but don't exist in the original version anymore, the record row is marked with '__remove'.
1575 * If there are records which can be localized and exist only in the original version, the record row is marked with '__create' and '__virtual'.
1576 *
1577 * @param string $table The table name of the parent records
1578 * @param array $options Options defining what kind of records to display
1579 * @param array $recordsOriginal The uids of the child records of the original language
1580 * @param array $recordsLocalization The uids of the child records of the current localization
1581 * @return array Merged array of uids of the child records of both versions
1582 */
1583 protected function getLocalizationDifferences($table, array $options, array $recordsOriginal, array $recordsLocalization) {
1584 $records = array();
1585 $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
1586 // Compare original to localized version of the records:
1587 foreach ($recordsLocalization as $uid => $row) {
1588 // If the record points to a original translation which doesn't exist anymore, it could be removed:
1589 if (isset($row[$transOrigPointerField]) && $row[$transOrigPointerField] > 0) {
1590 $transOrigPointer = $row[$transOrigPointerField];
1591 if (isset($recordsOriginal[$transOrigPointer])) {
1592 unset($recordsOriginal[$transOrigPointer]);
1593 } elseif ($options['showRemoved']) {
1594 $row['__remove'] = TRUE;
1595 }
1596 }
1597 $records[$uid] = $row;
1598 }
1599 // Process the remaining records in the original unlocalized parent:
1600 if ($options['showPossible']) {
1601 foreach ($recordsOriginal as $uid => $row) {
1602 $row['__create'] = TRUE;
1603 $row['__virtual'] = TRUE;
1604 $records[$uid] = $row;
1605 }
1606 }
1607 return $records;
1608 }
1609
1610 /**
1611 * Get possible records.
1612 * Copied from TCEform and modified.
1613 *
1614 * @param string $table The table name of the record
1615 * @param string $field The field name which this element is supposed to edit
1616 * @param array $row The record data array where the value(s) for the field can be found
1617 * @param array $conf An array with additional configuration options.
1618 * @param string $checkForConfField For which field in the foreign_table the possible records should be fetched
1619 * @return mixed Array of possible record items; FALSE if type is "group/db", then everything could be "possible
1620 * @todo Define visibility
1621 */
1622 public function getPossibleRecords($table, $field, $row, $conf, $checkForConfField = 'foreign_selector') {
1623 // ctrl configuration from TCA:
1624 $tcaTableCtrl = $GLOBALS['TCA'][$table]['ctrl'];
1625 // Field configuration from TCA:
1626 $foreign_table = $conf['foreign_table'];
1627 $foreign_check = $conf[$checkForConfField];
1628 $foreignConfig = $this->getPossibleRecordsSelectorConfig($conf, $foreign_check);
1629 $PA = $foreignConfig['PA'];
1630 $config = $PA['fieldConf']['config'];
1631 if ($foreignConfig['type'] == 'select') {
1632 // Getting the selector box items from the system
1633 $selItems = $this->fObj->addSelectOptionsToItemArray($this->fObj->initItemArray($PA['fieldConf']), $PA['fieldConf'], $this->fObj->setTSconfig($table, $row), $field);
1634
1635 // Possibly filter some items:
1636 $selItems = GeneralUtility::keepItemsInArray(
1637 $selItems,
1638 $PA['fieldTSConfig']['keepItems'],
1639 function ($value) {
1640 return $value[1];
1641 }
1642 );
1643
1644 // Possibly add some items:
1645 $selItems = $this->fObj->addItems($selItems, $PA['fieldTSConfig']['addItems.']);
1646 if (isset($config['itemsProcFunc']) && $config['itemsProcFunc']) {
1647 $selItems = $this->fObj->procItems($selItems, $PA['fieldTSConfig']['itemsProcFunc.'], $config, $table, $row, $field);
1648 }
1649 // Possibly remove some items:
1650 $removeItems = GeneralUtility::trimExplode(',', $PA['fieldTSConfig']['removeItems'], TRUE);
1651 foreach ($selItems as $tk => $p) {
1652 // Checking languages and authMode:
1653 $languageDeny = $tcaTableCtrl['languageField'] && (string)$tcaTableCtrl['languageField'] === $field && !$GLOBALS['BE_USER']->checkLanguageAccess($p[1]);
1654 $authModeDeny = $config['form_type'] == 'select' && $config['authMode'] && !$GLOBALS['BE_USER']->checkAuthMode($table, $field, $p[1], $config['authMode']);
1655 if (in_array($p[1], $removeItems) || $languageDeny || $authModeDeny) {
1656 unset($selItems[$tk]);
1657 } elseif (isset($PA['fieldTSConfig']['altLabels.'][$p[1]])) {
1658 $selItems[$tk][0] = htmlspecialchars($this->fObj->sL($PA['fieldTSConfig']['altLabels.'][$p[1]]));
1659 }
1660 // Removing doktypes with no access:
1661 if (($table === 'pages' || $table === 'pages_language_overlay') && $field === 'doktype') {
1662 if (!($GLOBALS['BE_USER']->isAdmin() || GeneralUtility::inList($GLOBALS['BE_USER']->groupData['pagetypes_select'], $p[1]))) {
1663 unset($selItems[$tk]);
1664 }
1665 }
1666 }
1667 } else {
1668 $selItems = FALSE;
1669 }
1670 return $selItems;
1671 }
1672
1673 /**
1674 * Gets the uids of a select/selector that should be unique an have already been used.
1675 *
1676 * @param array $records All inline records on this level
1677 * @param array $conf The TCA field configuration of the inline field to be rendered
1678 * @param boolean $splitValue For usage with group/db, values come like "tx_table_123|Title%20abc", but we need "tx_table" and "123
1679 * @return array The uids, that have been used already and should be used unique
1680 * @todo Define visibility
1681 */
1682 public function getUniqueIds($records, $conf = array(), $splitValue = FALSE) {
1683 $uniqueIds = array();
1684 if (isset($conf['foreign_unique']) && $conf['foreign_unique'] && count($records)) {
1685 foreach ($records as $rec) {
1686 // Skip virtual records (e.g. shown in localization mode):
1687 if (!isset($rec['__virtual']) || !$rec['__virtual']) {
1688 $value = $rec[$conf['foreign_unique']];
1689 // Split the value and extract the table and uid:
1690 if ($splitValue) {
1691 $valueParts = GeneralUtility::trimExplode('|', $value);
1692 $itemParts = explode('_', $valueParts[0]);
1693 $value = array(
1694 'uid' => array_pop($itemParts),
1695 'table' => implode('_', $itemParts)
1696 );
1697 }
1698 $uniqueIds[$rec['uid']] = $value;
1699 }
1700 }
1701 }
1702 return $uniqueIds;
1703 }
1704
1705 /**
1706 * Determines the corrected pid to be used for a new record.
1707 * The pid to be used can be defined by a Page TSconfig.
1708 *
1709 * @param string $table The table name
1710 * @param integer $parentPid The pid of the parent record
1711 * @return integer The corrected pid to be used for a new record
1712 */
1713 protected function getNewRecordPid($table, $parentPid = NULL) {
1714 $newRecordPid = $this->inlineFirstPid;
1715 $pageTS = BackendUtility::getPagesTSconfig($parentPid);
1716 if (isset($pageTS['TCAdefaults.'][$table . '.']['pid']) && MathUtility::canBeInterpretedAsInteger($pageTS['TCAdefaults.'][$table . '.']['pid'])) {
1717 $newRecordPid = $pageTS['TCAdefaults.'][$table . '.']['pid'];
1718 } elseif (isset($parentPid) && MathUtility::canBeInterpretedAsInteger($parentPid)) {
1719 $newRecordPid = $parentPid;
1720 }
1721 return $newRecordPid;
1722 }
1723
1724 /**
1725 * Get a single record row for a TCA table from the database.
1726 * \TYPO3\CMS\Backend\Form\DataPreprocessor is used for "upgrading" the
1727 * values, especially the relations.
1728 *
1729 * @param integer $pid The pid of the page the record should be stored (only relevant for NEW records)
1730 * @param string $table The table to fetch data from (= foreign_table)
1731 * @param string $uid The uid of the record to fetch, or the pid if a new record should be created
1732 * @param string $cmd The command to perform, empty or 'new'
1733 * @return array A record row from the database post-processed by \TYPO3\CMS\Backend\Form\DataPreprocessor
1734 * @todo Define visibility
1735 */
1736 public function getRecord($pid, $table, $uid, $cmd = '') {
1737 // Fetch workspace version of a record (if any):
1738 if ($cmd !== 'new' && $GLOBALS['BE_USER']->workspace !== 0 && BackendUtility::isTableWorkspaceEnabled($table)) {
1739 $workspaceVersion = BackendUtility::getWorkspaceVersionOfRecord($GLOBALS['BE_USER']->workspace, $table, $uid, 'uid,t3ver_state');
1740 if ($workspaceVersion !== FALSE) {
1741 $versionState = VersionState::cast($workspaceVersion['t3ver_state']);
1742 if ($versionState->equals(VersionState::DELETE_PLACEHOLDER)) {
1743 return FALSE;
1744 }
1745 $uid = $workspaceVersion['uid'];
1746 }
1747 }
1748 /** @var $trData \TYPO3\CMS\Backend\Form\DataPreprocessor */
1749 $trData = GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Form\\DataPreprocessor');
1750 $trData->addRawData = TRUE;
1751 $trData->lockRecords = 1;
1752 $trData->disableRTE = $GLOBALS['SOBE']->MOD_SETTINGS['disableRTE'];
1753 // If a new record should be created
1754 $trData->fetchRecord($table, $uid, $cmd === 'new' ? 'new' : '');
1755 $rec = reset($trData->regTableItems_data);
1756 return $rec;
1757 }
1758
1759 /**
1760 * Wrapper. Calls getRecord in case of a new record should be created.
1761 *
1762 * @param integer $pid The pid of the page the record should be stored (only relevant for NEW records)
1763 * @param string $table The table to fetch data from (= foreign_table)
1764 * @return array A record row from the database post-processed by \TYPO3\CMS\Backend\Form\DataPreprocessor
1765 * @todo Define visibility
1766 */
1767 public function getNewRecord($pid, $table) {
1768 $rec = $this->getRecord($pid, $table, $pid, 'new');
1769 $rec['uid'] = uniqid('NEW');
1770 $rec['pid'] = $this->getNewRecordPid($table, $pid);
1771 return $rec;
1772 }
1773
1774 /*******************************************************
1775 *
1776 * Structure stack for handling inline objects/levels
1777 *
1778 *******************************************************/
1779 /**
1780 * Add a new level on top of the structure stack. Other functions can access the
1781 * stack and determine, if there's possibly a endless loop.
1782 *
1783 * @param string $table The table name of the record
1784 * @param string $uid The uid of the record that embeds the inline data
1785 * @param string $field The field name which this element is supposed to edit
1786 * @param array $config The TCA-configuration of the inline field
1787 * @param array $parameters The full parameter array (PA)
1788 * @return void
1789 * @todo Define visibility
1790 */
1791 public function pushStructure($table, $uid, $field = '', $config = array(), array $parameters = array()) {
1792 $structure = array(
1793 'table' => $table,
1794 'uid' => $uid,
1795 'field' => $field,
1796 'config' => $config,
1797 'localizationMode' => BackendUtility::getInlineLocalizationMode($table, $config),
1798 );
1799
1800 // Extract FlexForm parts (if any) from element name,
1801 // e.g. array('vDEF', 'lDEF', 'FlexField', 'vDEF')
1802 if (!empty($parameters['itemFormElName'])) {
1803 $flexFormParts = $this->extractFlexFormParts($parameters['itemFormElName']);
1804
1805 if ($flexFormParts !== NULL) {
1806 $structure['flexform'] = $flexFormParts;
1807 }
1808 }
1809
1810 $this->inlineStructure['stable'][] = $structure;
1811 $this->updateStructureNames();
1812 }
1813
1814 /**
1815 * Remove the item on top of the structure stack and return it.
1816 *
1817 * @return array The top item of the structure stack - array(<table>,<uid>,<field>,<config>)
1818 * @todo Define visibility
1819 */
1820 public function popStructure() {
1821 $popItem = NULL;
1822
1823 if (count($this->inlineStructure['stable'])) {
1824 $popItem = array_pop($this->inlineStructure['stable']);
1825 $this->updateStructureNames();
1826 }
1827 return $popItem;
1828 }
1829
1830 /**
1831 * For common use of DOM object-ids and form field names of a several inline-level,
1832 * these names/identifiers are preprocessed and set to $this->inlineNames.
1833 * This function is automatically called if a level is pushed to or removed from the
1834 * inline structure stack.
1835 *
1836 * @return void
1837 * @todo Define visibility
1838 */
1839 public function updateStructureNames() {
1840 $current = $this->getStructureLevel(-1);
1841 // If there are still more inline levels available
1842 if ($current !== FALSE) {
1843 $this->inlineNames = array(
1844 'form' => $this->prependFormFieldNames . $this->getStructureItemName($current, self::Disposal_AttributeName),
1845 'object' => $this->prependNaming . self::Structure_Separator . $this->inlineFirstPid . self::Structure_Separator . $this->getStructurePath()
1846 );
1847 } else {
1848 $this->inlineNames = array();
1849 }
1850 }
1851
1852 /**
1853 * Create a name/id for usage in HTML output of a level of the structure stack to be used in form names.
1854 *
1855 * @param array $levelData Array of a level of the structure stack (containing the keys table, uid and field)
1856 * @param string $disposal How the structure name is used (e.g. as <div id="..."> or <input name="..." />)
1857 * @return string The name/id of that level, to be used for HTML output
1858 * @todo Define visibility
1859 */
1860 public function getStructureItemName($levelData, $disposal = self::Disposal_AttributeId) {
1861 $name = NULL;
1862
1863 if (is_array($levelData)) {
1864 $parts = array($levelData['table'], $levelData['uid']);
1865
1866 if (!empty($levelData['field'])) {
1867 $parts[] = $levelData['field'];
1868 }
1869
1870 // Use in name attributes:
1871 if ($disposal === self::Disposal_AttributeName) {
1872 if (!empty($levelData['field']) && !empty($levelData['flexform']) && $this->getStructureLevel(-1) === $levelData) {
1873 $parts[] = implode('][', $levelData['flexform']);
1874 }
1875 $name = '[' . implode('][', $parts) . ']';
1876 // Use in object id attributes:
1877 } else {
1878 $name = implode(self::Structure_Separator, $parts);
1879
1880 if (!empty($levelData['field']) && !empty($levelData['flexform'])) {
1881 array_unshift($levelData['flexform'], $name);
1882 $name = implode(self::FlexForm_Separator, $levelData['flexform']);
1883 }
1884 }
1885 }
1886
1887 return $name;
1888 }
1889
1890 /**
1891 * Get a level from the stack and return the data.
1892 * If the $level value is negative, this function works top-down,
1893 * if the $level value is positive, this function works bottom-up.
1894 *
1895 * @param integer $level Which level to return
1896 * @return array The item of the stack at the requested level
1897 * @todo Define visibility
1898 */
1899 public function getStructureLevel($level) {
1900 $level = $this->calculateStructureLevel($level);
1901
1902 if ($level !== FALSE) {
1903 return $this->inlineStructure['stable'][$level];
1904 } else {
1905 return FALSE;
1906 }
1907 }
1908
1909 /**
1910 * Calculates structure level.
1911 *
1912 * @param integer $level Which level to return
1913 * @return boolean|integer
1914 */
1915 protected function calculateStructureLevel($level) {
1916 $result = FALSE;
1917
1918 $inlineStructureCount = count($this->inlineStructure['stable']);
1919 if ($level < 0) {
1920 $level = $inlineStructureCount + $level;
1921 }
1922 if ($level >= 0 && $level < $inlineStructureCount) {
1923 $result = $level;
1924 }
1925
1926 return $result;
1927 }
1928
1929 /**
1930 * Get the identifiers of a given depth of level, from the top of the stack to the bottom.
1931 * An identifier looks like "<table>-<uid>-<field>".
1932 *
1933 * @param integer $structureDepth How much levels to output, beginning from the top of the stack
1934 * @return string The path of identifiers
1935 * @todo Define visibility
1936 */
1937 public function getStructurePath($structureDepth = -1) {
1938 $structureLevels = array();
1939 $structureCount = count($this->inlineStructure['stable']);
1940 if ($structureDepth < 0 || $structureDepth > $structureCount) {
1941 $structureDepth = $structureCount;
1942 }
1943 for ($i = 1; $i <= $structureDepth; $i++) {
1944 array_unshift($structureLevels, $this->getStructureItemName($this->getStructureLevel(-$i), self::Disposal_AttributeId));
1945 }
1946 return implode(self::Structure_Separator, $structureLevels);
1947 }
1948
1949 /**
1950 * Convert the DOM object-id of an inline container to an array.
1951 * The object-id could look like 'data-parentPageId-tx_mmftest_company-1-employees'.
1952 * The result is written to $this->inlineStructure.
1953 * There are two keys:
1954 * - 'stable': Containing full qualified identifiers (table, uid and field)
1955 * - 'unstable': Containting partly filled data (e.g. only table and possibly field)
1956 *
1957 * @param string $domObjectId The DOM object-id
1958 * @param boolean $loadConfig Load the TCA configuration for that level (default: TRUE)
1959 * @return void
1960 * @todo Define visibility
1961 */
1962 public function parseStructureString($string, $loadConfig = TRUE) {
1963 $unstable = array();
1964 $vector = array('table', 'uid', 'field');
1965
1966 // Substitute FlexForm additon and make parsing a bit easier
1967 $string = str_replace(self::FlexForm_Separator, self::FlexForm_Substitute, $string);
1968 // The starting pattern of an object identifer (e.g. "data-<firstPidValue>-<anything>)
1969 $pattern = '/^' . $this->prependNaming . self::Structure_Separator . '(.+?)' . self::Structure_Separator . '(.+)$/';
1970
1971 if (preg_match($pattern, $string, $match)) {
1972 $this->inlineFirstPid = $match[1];
1973 $parts = explode(self::Structure_Separator, $match[2]);
1974 $partsCnt = count($parts);
1975 for ($i = 0; $i < $partsCnt; $i++) {
1976 if ($i > 0 && $i % 3 == 0) {
1977 // Load the TCA configuration of the table field and store it in the stack
1978 if ($loadConfig) {
1979 $unstable['config'] = $GLOBALS['TCA'][$unstable['table']]['columns'][$unstable['field']]['config'];
1980 // Fetch TSconfig:
1981 $TSconfig = $this->fObj->setTSconfig($unstable['table'], array('uid' => $unstable['uid'], 'pid' => $this->inlineFirstPid), $unstable['field']);
1982 // Override TCA field config by TSconfig:
1983 if (!$TSconfig['disabled']) {
1984 $unstable['config'] = $this->fObj->overrideFieldConf($unstable['config'], $TSconfig);
1985 }
1986 $unstable['localizationMode'] = BackendUtility::getInlineLocalizationMode($unstable['table'], $unstable['config']);
1987 }
1988
1989 // Extract FlexForm from field part (if any)
1990 if (strpos($unstable['field'], self::FlexForm_Substitute) !== FALSE) {
1991 $fieldParts = GeneralUtility::trimExplode(self::FlexForm_Substitute, $unstable['field']);
1992 $unstable['field'] = array_shift($fieldParts);
1993 // FlexForm parts start with data:
1994 if (count($fieldParts) > 0 && $fieldParts[0] === 'data') {
1995 $unstable['flexform'] = $fieldParts;
1996 }
1997 }
1998
1999 $this->inlineStructure['stable'][] = $unstable;
2000 $unstable = array();
2001 }
2002 $unstable[$vector[$i % 3]] = $parts[$i];
2003 }
2004 $this->updateStructureNames();
2005 if (count($unstable)) {
2006 $this->inlineStructure['unstable'] = $unstable;
2007 }
2008 }
2009 }
2010
2011 /*******************************************************
2012 *
2013 * Helper functions
2014 *
2015 *******************************************************/
2016 /**
2017 * Does some checks on the TCA configuration of the inline field to render.
2018 *
2019 * @param array $config Reference to the TCA field configuration
2020 * @param string $table The table name of the record
2021 * @param string $field The field name which this element is supposed to edit
2022 * @param array $row The record data array of the parent
2023 * @return boolean If critical configuration errors were found, FALSE is returned
2024 * @todo Define visibility
2025 */
2026 public function checkConfiguration(&$config) {
2027 $foreign_table = $config['foreign_table'];
2028 // An inline field must have a foreign_table, if not, stop all further inline actions for this field:
2029 if (!$foreign_table || !is_array($GLOBALS['TCA'][$foreign_table])) {
2030 return FALSE;
2031 }
2032 // Init appearance if not set:
2033 if (!isset($config['appearance']) || !is_array($config['appearance'])) {
2034 $config['appearance'] = array();
2035 }
2036 // Set the position/appearance of the "Create new record" link:
2037 if (isset($config['foreign_selector']) && $config['foreign_selector'] && (!isset($config['appearance']['useCombination']) || !$config['appearance']['useCombination'])) {
2038 $config['appearance']['levelLinksPosition'] = 'none';
2039 } elseif (!isset($config['appearance']['levelLinksPosition']) || !in_array($config['appearance']['levelLinksPosition'], array('top', 'bottom', 'both', 'none'))) {
2040 $config['appearance']['levelLinksPosition'] = 'top';
2041 }
2042 // Defines which controls should be shown in header of each record:
2043 $enabledControls = array(
2044 'info' => TRUE,
2045 'new' => TRUE,
2046 'dragdrop' => TRUE,
2047 'sort' => TRUE,
2048 'hide' => TRUE,
2049 'delete' => TRUE,
2050 'localize' => TRUE
2051 );
2052 if (isset($config['appearance']['enabledControls']) && is_array($config['appearance']['enabledControls'])) {
2053 $config['appearance']['enabledControls'] = array_merge($enabledControls, $config['appearance']['enabledControls']);
2054 } else {
2055 $config['appearance']['enabledControls'] = $enabledControls;
2056 }
2057 return TRUE;
2058 }
2059
2060 /**
2061 * Checks the page access rights (Code for access check mostly taken from alt_doc.php)
2062 * as well as the table access rights of the user.
2063 *
2064 * @param string $cmd The command that sould be performed ('new' or 'edit')
2065 * @param string $table The table to check access for
2066 * @param string $theUid The record uid of the table
2067 * @return boolean Returns TRUE is the user has access, or FALSE if not
2068 * @todo Define visibility
2069 */
2070 public function checkAccess($cmd, $table, $theUid) {
2071 // 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...)
2072 // First, resetting flags.
2073 $hasAccess = 0;
2074 $deniedAccessReason = '';
2075 // Admin users always have acces:
2076 if ($GLOBALS['BE_USER']->isAdmin()) {
2077 return TRUE;
2078 }
2079 // If the command is to create a NEW record...:
2080 if ($cmd == 'new') {
2081 // If the pid is numerical, check if it's possible to write to this page:
2082 if (MathUtility::canBeInterpretedAsInteger($this->inlineFirstPid)) {
2083 $calcPRec = BackendUtility::getRecord('pages', $this->inlineFirstPid);
2084 if (!is_array($calcPRec)) {
2085 return FALSE;
2086 }
2087 // Permissions for the parent page
2088 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
2089 // If pages:
2090 if ($table == 'pages') {
2091 // Are we allowed to create new subpages?
2092 $hasAccess = $CALC_PERMS & 8 ? 1 : 0;
2093 } else {
2094 // Are we allowed to edit content on this page?
2095 $hasAccess = $CALC_PERMS & 16 ? 1 : 0;
2096 }
2097 } else {
2098 $hasAccess = 1;
2099 }
2100 } else {
2101 // Edit:
2102 $calcPRec = BackendUtility::getRecord($table, $theUid);
2103 BackendUtility::fixVersioningPid($table, $calcPRec);
2104 if (is_array($calcPRec)) {
2105 // If pages:
2106 if ($table == 'pages') {
2107 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
2108 $hasAccess = $CALC_PERMS & 2 ? 1 : 0;
2109 } else {
2110 // Fetching pid-record first.
2111 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms(BackendUtility::getRecord('pages', $calcPRec['pid']));
2112 $hasAccess = $CALC_PERMS & 16 ? 1 : 0;
2113 }
2114 // Check internals regarding access:
2115 if ($hasAccess) {
2116 $hasAccess = $GLOBALS['BE_USER']->recordEditAccessInternals($table, $calcPRec);
2117 }
2118 }
2119 }
2120 if (!$GLOBALS['BE_USER']->check('tables_modify', $table)) {
2121 $hasAccess = 0;
2122 }
2123 if (!$hasAccess) {
2124 $deniedAccessReason = $GLOBALS['BE_USER']->errorMsg;
2125 if ($deniedAccessReason) {
2126 debug($deniedAccessReason);
2127 }
2128 }
2129 return $hasAccess ? TRUE : FALSE;
2130 }
2131
2132 /**
2133 * Check the keys and values in the $compare array against the ['config'] part of the top level of the stack.
2134 * A boolean value is return depending on how the comparison was successful.
2135 *
2136 * @param array $compare Keys and values to compare to the ['config'] part of the top level of the stack
2137 * @return boolean Whether the comparison was successful
2138 * @see arrayCompareComplex
2139 * @todo Define visibility
2140 */
2141 public function compareStructureConfiguration($compare) {
2142 $level = $this->getStructureLevel(-1);
2143 $result = $this->arrayCompareComplex($level, $compare);
2144 return $result;
2145 }
2146
2147 /**
2148 * Normalize a relation "uid" published by transferData, like "1|Company%201"
2149 *
2150 * @param string $string A transferData reference string, containing the uid
2151 * @return string The normalized uid
2152 * @todo Define visibility
2153 */
2154 public function normalizeUid($string) {
2155 $parts = explode('|', $string);
2156 return $parts[0];
2157 }
2158
2159 /**
2160 * Wrap the HTML code of a section with a table tag.
2161 *
2162 * @param string $section The HTML code to be wrapped
2163 * @param array $styleAttrs Attributes for the style argument in the table tag
2164 * @param array $tableAttrs Attributes for the table tag (like width, border, etc.)
2165 * @return string The wrapped HTML code
2166 * @todo Define visibility
2167 */
2168 public function wrapFormsSection($section, $styleAttrs = array(), $tableAttrs = array()) {
2169 $style = '';
2170 $table = '';
2171 foreach ($styleAttrs as $key => $value) {
2172 $style .= ($style ? ' ' : '') . $key . ': ' . htmlspecialchars($value) . '; ';
2173 }
2174 if ($style) {
2175 $style = ' style="' . $style . '"';
2176 }
2177 if (!$tableAttrs['background'] && $this->fObj->borderStyle[2]) {
2178 $tableAttrs['background'] = $this->backPath . $this->borderStyle[2];
2179 }
2180 if (!$tableAttrs['class'] && $this->borderStyle[3]) {
2181 $tableAttrs['class'] = $this->borderStyle[3];
2182 }
2183 foreach ($tableAttrs as $key => $value) {
2184 $table .= ($table ? ' ' : '') . $key . '="' . htmlspecialchars($value) . '"';
2185 }
2186 $out = '<table ' . $table . $style . '>' . $section . '</table>';
2187 return $out;
2188 }
2189
2190 /**
2191 * Checks if the $table is the child of a inline type AND the $field is the label field of this table.
2192 * This function is used to dynamically update the label while editing. This has no effect on labels,
2193 * that were processed by a TCEmain-hook on saving.
2194 *
2195 * @param string $table The table to check
2196 * @param string $field The field on this table to check
2197 * @return boolean Is inline child and field is responsible for the label
2198 * @todo Define visibility
2199 */
2200 public function isInlineChildAndLabelField($table, $field) {
2201 $level = $this->getStructureLevel(-1);
2202 if ($level['config']['foreign_label']) {
2203 $label = $level['config']['foreign_label'];
2204 } else {
2205 $label = $GLOBALS['TCA'][$table]['ctrl']['label'];
2206 }
2207 return $level['config']['foreign_table'] === $table && $label == $field ? TRUE : FALSE;
2208 }
2209
2210 /**
2211 * Get the depth of the stable structure stack.
2212 * (count($this->inlineStructure['stable'])
2213 *
2214 * @return integer The depth of the structure stack
2215 * @todo Define visibility
2216 */
2217 public function getStructureDepth() {
2218 return count($this->inlineStructure['stable']);
2219 }
2220
2221 /**
2222 * Handles complex comparison requests on an array.
2223 * A request could look like the following:
2224 *
2225 * $searchArray = array(
2226 * '%AND' => array(
2227 * 'key1' => 'value1',
2228 * 'key2' => 'value2',
2229 * '%OR' => array(
2230 * 'subarray' => array(
2231 * 'subkey' => 'subvalue'
2232 * ),
2233 * 'key3' => 'value3',
2234 * 'key4' => 'value4'
2235 * )
2236 * )
2237 * );
2238 *
2239 * It is possible to use the array keys '%AND.1', '%AND.2', etc. to prevent
2240 * overwriting the sub-array. It could be necessary, if you use complex comparisons.
2241 *
2242 * The example above means, key1 *AND* key2 (and their values) have to match with
2243 * the $subjectArray and additional one *OR* key3 or key4 have to meet the same
2244 * condition.
2245 * It is also possible to compare parts of a sub-array (e.g. "subarray"), so this
2246 * function recurses down one level in that sub-array.
2247 *
2248 * @param array $subjectArray The array to search in
2249 * @param array $searchArray The array with keys and values to search for
2250 * @param string $type Use '%AND' or '%OR' for comparison
2251 * @return boolean The result of the comparison
2252 * @todo Define visibility
2253 */
2254 public function arrayCompareComplex($subjectArray, $searchArray, $type = '') {
2255 $localMatches = 0;
2256 $localEntries = 0;
2257 if (is_array($searchArray) && count($searchArray)) {
2258 // If no type was passed, try to determine
2259 if (!$type) {
2260 reset($searchArray);
2261 $type = key($searchArray);
2262 $searchArray = current($searchArray);
2263 }
2264 // We use '%AND' and '%OR' in uppercase
2265 $type = strtoupper($type);
2266 // Split regular elements from sub elements
2267 foreach ($searchArray as $key => $value) {
2268 $localEntries++;
2269 // Process a sub-group of OR-conditions
2270 if ($key == '%OR') {
2271 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%OR') ? 1 : 0;
2272 } elseif ($key == '%AND') {
2273 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%AND') ? 1 : 0;
2274 } elseif (is_array($value) && $this->isAssociativeArray($searchArray)) {
2275 $localMatches += $this->arrayCompareComplex($subjectArray[$key], $value, $type) ? 1 : 0;
2276 } elseif (is_array($value)) {
2277 $localMatches += $this->arrayCompareComplex($subjectArray, $value, $type) ? 1 : 0;
2278 } else {
2279 if (isset($subjectArray[$key]) && isset($value)) {
2280 // Boolean match:
2281 if (is_bool($value)) {
2282 $localMatches += !($subjectArray[$key] xor $value) ? 1 : 0;
2283 } elseif (is_numeric($subjectArray[$key]) && is_numeric($value)) {
2284 $localMatches += $subjectArray[$key] == $value ? 1 : 0;
2285 } else {
2286 $localMatches += $subjectArray[$key] === $value ? 1 : 0;
2287 }
2288 }
2289 }
2290 // If one or more matches are required ('OR'), return TRUE after the first successful match
2291 if ($type == '%OR' && $localMatches > 0) {
2292 return TRUE;
2293 }
2294 // If all matches are required ('AND') and we have no result after the first run, return FALSE
2295 if ($type == '%AND' && $localMatches == 0) {
2296 return FALSE;
2297 }
2298 }
2299 }
2300 // Return the result for '%AND' (if nothing was checked, TRUE is returned)
2301 return $localEntries == $localMatches ? TRUE : FALSE;
2302 }
2303
2304 /**
2305 * Checks whether an object is an associative array.
2306 *
2307 * @param mixed $object The object to be checked
2308 * @return boolean Returns TRUE, if the object is an associative array
2309 * @todo Define visibility
2310 */
2311 public function isAssociativeArray($object) {
2312 return is_array($object) && count($object) && array_keys($object) !== range(0, sizeof($object) - 1) ? TRUE : FALSE;
2313 }
2314
2315 /**
2316 * Remove an element from an array.
2317 *
2318 * @param mixed $needle The element to be removed.
2319 * @param array $haystack The array the element should be removed from.
2320 * @param mixed $strict Search elements strictly.
2321 * @return array The array $haystack without the $needle
2322 * @todo Define visibility
2323 */
2324 public function removeFromArray($needle, $haystack, $strict = NULL) {
2325 $pos = array_search($needle, $haystack, $strict);
2326 if ($pos !== FALSE) {
2327 unset($haystack[$pos]);
2328 }
2329 return $haystack;
2330 }
2331
2332 /**
2333 * Makes a flat array from the $possibleRecords array.
2334 * The key of the flat array is the value of the record,
2335 * the value of the flat array is the label of the record.
2336 *
2337 * @param array $possibleRecords The possibleRecords array (for select fields)
2338 * @return mixed A flat array with key=uid, value=label; if $possibleRecords isn't an array, FALSE is returned.
2339 * @todo Define visibility
2340 */
2341 public function getPossibleRecordsFlat($possibleRecords) {
2342 $flat = FALSE;
2343 if (is_array($possibleRecords)) {
2344 $flat = array();
2345 foreach ($possibleRecords as $record) {
2346 $flat[$record[1]] = $record[0];
2347 }
2348 }
2349 return $flat;
2350 }
2351
2352 /**
2353 * Determine the configuration and the type of a record selector.
2354 *
2355 * @param array $conf TCA configuration of the parent(!) field
2356 * @return array Associative array with the keys 'PA' and 'type', both are FALSE if the selector was not valid.
2357 * @todo Define visibility
2358 */
2359 public function getPossibleRecordsSelectorConfig($conf, $field = '') {
2360 $foreign_table = $conf['foreign_table'];
2361 $foreign_selector = $conf['foreign_selector'];
2362 $PA = FALSE;
2363 $type = FALSE;
2364 $table = FALSE;
2365 $selector = FALSE;
2366 if ($field) {
2367 $PA = array();
2368 $PA['fieldConf'] = $GLOBALS['TCA'][$foreign_table]['columns'][$field];
2369 if ($PA['fieldConf'] && $conf['foreign_selector_fieldTcaOverride']) {
2370 \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($PA['fieldConf'], $conf['foreign_selector_fieldTcaOverride']);
2371 }
2372 $PA['fieldConf']['config']['form_type'] = $PA['fieldConf']['config']['form_type'] ?: $PA['fieldConf']['config']['type'];
2373 // Using "form_type" locally in this script
2374 $PA['fieldTSConfig'] = $this->fObj->setTSconfig($foreign_table, array(), $field);
2375 $config = $PA['fieldConf']['config'];
2376 // Determine type of Selector:
2377 $type = $this->getPossibleRecordsSelectorType($config);
2378 // Return table on this level:
2379 $table = $type == 'select' ? $config['foreign_table'] : $config['allowed'];
2380 // Return type of the selector if foreign_selector is defined and points to the same field as in $field:
2381 if ($foreign_selector && $foreign_selector == $field && $type) {
2382 $selector = $type;
2383 }
2384 }
2385 return array(
2386 'PA' => $PA,
2387 'type' => $type,
2388 'table' => $table,
2389 'selector' => $selector
2390 );
2391 }
2392
2393 /**
2394 * Determine the type of a record selector, e.g. select or group/db.
2395 *
2396 * @param array $config TCE configuration of the selector
2397 * @return mixed The type of the selector, 'select' or 'groupdb' - FALSE not valid
2398 * @todo Define visibility
2399 */
2400 public function getPossibleRecordsSelectorType($config) {
2401 $type = FALSE;
2402 if ($config['type'] == 'select') {
2403 $type = 'select';
2404 } elseif ($config['type'] == 'group' && $config['internal_type'] == 'db') {
2405 $type = 'groupdb';
2406 }
2407 return $type;
2408 }
2409
2410 /**
2411 * Check, if a field should be skipped, that was defined to be handled as foreign_field or foreign_sortby of
2412 * the parent record of the "inline"-type - if so, we have to skip this field - the rendering is done via "inline" as hidden field
2413 *
2414 * @param string $table The table name
2415 * @param string $field The field name
2416 * @param array $row The record row from the database
2417 * @param array $config TCA configuration of the field
2418 * @return boolean Determines whether the field should be skipped.
2419 * @todo Define visibility
2420 */
2421 public function skipField($table, $field, $row, $config) {
2422 $skipThisField = FALSE;
2423 if ($this->getStructureDepth()) {
2424 $searchArray = array(
2425 '%OR' => array(
2426 'config' => array(
2427 0 => array(
2428 '%AND' => array(
2429 'foreign_table' => $table,
2430 '%OR' => array(
2431 '%AND' => array(
2432 'appearance' => array('useCombination' => TRUE),
2433 'foreign_selector' => $field
2434 ),
2435 'MM' => $config['MM']
2436 )
2437 )
2438 ),
2439 1 => array(
2440 '%AND' => array(
2441 'foreign_table' => $config['foreign_table'],
2442 'foreign_selector' => $config['foreign_field']
2443 )
2444 )
2445 )
2446 )
2447 );
2448 // Get the parent record from structure stack
2449 $level = $this->getStructureLevel(-1);
2450 // If we have symmetric fields, check on which side we are and hide fields, that are set automatically:
2451 if (RelationHandler::isOnSymmetricSide($level['uid'], $level['config'], $row)) {
2452 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_field'] = $field;
2453 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_sortby'] = $field;
2454 } else {
2455 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_field'] = $field;
2456 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_sortby'] = $field;
2457 }
2458 $skipThisField = $this->compareStructureConfiguration($searchArray, TRUE);
2459 }
2460 return $skipThisField;
2461 }
2462
2463 /**
2464 * Checks if a uid of a child table is in the inline view settings.
2465 *
2466 * @param string $table Name of the child table
2467 * @param integer $uid uid of the the child record
2468 * @return boolean TRUE=expand, FALSE=collapse
2469 * @todo Define visibility
2470 */
2471 public function getExpandedCollapsedState($table, $uid) {
2472 if (isset($this->inlineView[$table]) && is_array($this->inlineView[$table])) {
2473 if (in_array($uid, $this->inlineView[$table]) !== FALSE) {
2474 return TRUE;
2475 }
2476 }
2477 return FALSE;
2478 }
2479
2480 /**
2481 * Update expanded/collapsed states on new inline records if any.
2482 *
2483 * @param array $uc The uc array to be processed and saved (by reference)
2484 * @param \TYPO3\CMS\Core\DataHandling\DataHandler $tce Instance of TCEmain that saved data before
2485 * @return void
2486 * @todo Define visibility
2487 */
2488 public function updateInlineView(&$uc, $tce) {
2489 if (isset($uc['inlineView']) && is_array($uc['inlineView'])) {
2490 $inlineView = (array) unserialize($GLOBALS['BE_USER']->uc['inlineView']);
2491 foreach ($uc['inlineView'] as $topTable => $topRecords) {
2492 foreach ($topRecords as $topUid => $childElements) {
2493 foreach ($childElements as $childTable => $childRecords) {
2494 $uids = array_keys($tce->substNEWwithIDs_table, $childTable);
2495 if (count($uids)) {
2496 $newExpandedChildren = array();
2497 foreach ($childRecords as $childUid => $state) {
2498 if ($state && in_array($childUid, $uids)) {
2499 $newChildUid = $tce->substNEWwithIDs[$childUid];
2500 $newExpandedChildren[] = $newChildUid;
2501 }
2502 }
2503 // Add new expanded child records to UC (if any):
2504 if (count($newExpandedChildren)) {
2505 $inlineViewCurrent = &$inlineView[$topTable][$topUid][$childTable];
2506 if (is_array($inlineViewCurrent)) {
2507 $inlineViewCurrent = array_unique(array_merge($inlineViewCurrent, $newExpandedChildren));
2508 } else {
2509 $inlineViewCurrent = $newExpandedChildren;
2510 }
2511 }
2512 }
2513 }
2514 }
2515 }
2516 $GLOBALS['BE_USER']->uc['inlineView'] = serialize($inlineView);
2517 $GLOBALS['BE_USER']->writeUC();
2518 }
2519 }
2520
2521 /**
2522 * Returns the the margin in pixels, that is used for each new inline level.
2523 *
2524 * @return integer A pixel value for the margin of each new inline level.
2525 * @todo Define visibility
2526 */
2527 public function getLevelMargin() {
2528 $margin = ($this->inlineStyles['margin-right'] + 1) * 2;
2529 return $margin;