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