[BUGFIX] Declare statically called method static
[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 $localizationLinks = '';
177 // Count the number of processed inline elements
178 $this->inlineCount++;
179 // Init:
180 $config = $PA['fieldConf']['config'];
181 $foreign_table = $config['foreign_table'];
182 $language = 0;
183 if (BackendUtility::isTableLocalizable($table)) {
184 $language = (int)$row[$GLOBALS['TCA'][$table]['ctrl']['languageField']];
185 }
186 $minitems = MathUtility::forceIntegerInRange($config['minitems'], 0);
187 $maxitems = MathUtility::forceIntegerInRange($config['maxitems'], 0);
188 if (!$maxitems) {
189 $maxitems = 100000;
190 }
191 // Register the required number of elements:
192 $this->fObj->requiredElements[$PA['itemFormElName']] = array($minitems, $maxitems, 'imgName' => $table . '_' . $row['uid'] . '_' . $field);
193 // Remember the page id (pid of record) where inline editing started first
194 // We need that pid for ajax calls, so that they would know where the action takes place on the page structure
195 if (!isset($this->inlineFirstPid)) {
196 // If this record is not new, try to fetch the inlineView states
197 // @TODO: Add checking/cleaning for unused tables, records, etc. to save space in uc-field
198 if (MathUtility::canBeInterpretedAsInteger($row['uid'])) {
199 $inlineView = unserialize($GLOBALS['BE_USER']->uc['inlineView']);
200 $this->inlineView = $inlineView[$table][$row['uid']];
201 }
202 // If the parent is a page, use the uid(!) of the (new?) page as pid for the child records:
203 if ($table == 'pages') {
204 $liveVersionId = BackendUtility::getLiveVersionIdOfRecord('pages', $row['uid']);
205 $this->inlineFirstPid = is_null($liveVersionId) ? $row['uid'] : $liveVersionId;
206 } elseif ($row['pid'] < 0) {
207 $prevRec = BackendUtility::getRecord($table, abs($row['pid']));
208 $this->inlineFirstPid = $prevRec['pid'];
209 } else {
210 $this->inlineFirstPid = $row['pid'];
211 }
212 }
213 // Add the current inline job to the structure stack
214 $this->pushStructure($table, $row['uid'], $field, $config, $PA);
215 // e.g. data[<table>][<uid>][<field>]
216 $nameForm = $this->inlineNames['form'];
217 // e.g. data-<pid>-<table1>-<uid1>-<field1>-<table2>-<uid2>-<field2>
218 $nameObject = $this->inlineNames['object'];
219 // Get the records related to this inline record
220 $relatedRecords = $this->getRelatedRecords($table, $field, $row, $PA, $config);
221 // Set the first and last record to the config array
222 $relatedRecordsUids = array_keys($relatedRecords['records']);
223 $config['inline']['first'] = reset($relatedRecordsUids);
224 $config['inline']['last'] = end($relatedRecordsUids);
225 // Tell the browser what we have (using JSON later):
226 $top = $this->getStructureLevel(0);
227 $this->inlineData['config'][$nameObject] = array(
228 'table' => $foreign_table,
229 'md5' => md5($nameObject)
230 );
231 $this->inlineData['config'][$nameObject . self::Structure_Separator . $foreign_table] = array(
232 'min' => $minitems,
233 'max' => $maxitems,
234 'sortable' => $config['appearance']['useSortable'],
235 'top' => array(
236 'table' => $top['table'],
237 'uid' => $top['uid']
238 ),
239 'context' => array(
240 'config' => $config,
241 'hmac' => GeneralUtility::hmac(serialize($config)),
242 ),
243 );
244 // Set a hint for nested IRRE and tab elements:
245 $this->inlineData['nested'][$nameObject] = $this->fObj->getDynNestedStack(FALSE, $this->isAjaxCall);
246 // If relations are required to be unique, get the uids that have already been used on the foreign side of the relation
247 if ($config['foreign_unique']) {
248 // If uniqueness *and* selector are set, they should point to the same field - so, get the configuration of one:
249 $selConfig = $this->getPossibleRecordsSelectorConfig($config, $config['foreign_unique']);
250 // Get the used unique ids:
251 $uniqueIds = $this->getUniqueIds($relatedRecords['records'], $config, $selConfig['type'] == 'groupdb');
252 $possibleRecords = $this->getPossibleRecords($table, $field, $row, $config, 'foreign_unique');
253 $uniqueMax = $config['appearance']['useCombination'] || $possibleRecords === FALSE ? -1 : count($possibleRecords);
254 $this->inlineData['unique'][$nameObject . self::Structure_Separator . $foreign_table] = array(
255 'max' => $uniqueMax,
256 'used' => $uniqueIds,
257 'type' => $selConfig['type'],
258 'table' => $config['foreign_table'],
259 'elTable' => $selConfig['table'],
260 // element/record table (one step down in hierarchy)
261 'field' => $config['foreign_unique'],
262 'selector' => $selConfig['selector'],
263 'possible' => $this->getPossibleRecordsFlat($possibleRecords)
264 );
265 }
266 // Render the localization links
267 if ($language > 0 && $row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] > 0 && MathUtility::canBeInterpretedAsInteger($row['uid'])) {
268 // Add the "Localize all records" link before all child records:
269 if (isset($config['appearance']['showAllLocalizationLink']) && $config['appearance']['showAllLocalizationLink']) {
270 $localizationLinks .= ' ' . $this->getLevelInteractionLink('localize', $nameObject . self::Structure_Separator . $foreign_table, $config);
271 }
272 // Add the "Synchronize with default language" link before all child records:
273 if (isset($config['appearance']['showSynchronizationLink']) && $config['appearance']['showSynchronizationLink']) {
274 $localizationLinks .= ' ' . $this->getLevelInteractionLink('synchronize', $nameObject . self::Structure_Separator . $foreign_table, $config);
275 }
276 }
277 // If it's required to select from possible child records (reusable children), add a selector box
278 if ($config['foreign_selector'] && $config['appearance']['showPossibleRecordsSelector'] !== FALSE) {
279 // If not already set by the foreign_unique, set the possibleRecords here and the uniqueIds to an empty array
280 if (!$config['foreign_unique']) {
281 $possibleRecords = $this->getPossibleRecords($table, $field, $row, $config);
282 $uniqueIds = array();
283 }
284 $selectorBox = $this->renderPossibleRecordsSelector($possibleRecords, $config, $uniqueIds);
285 $item .= $selectorBox . $localizationLinks;
286 }
287 // Render the level links (create new record):
288 $levelLinks = $this->getLevelInteractionLink('newRecord', $nameObject . self::Structure_Separator . $foreign_table, $config);
289
290 // Wrap all inline fields of a record with a <div> (like a container)
291 $item .= '<div id="' . $nameObject . '">';
292 // Define how to show the "Create new record" link - if there are more than maxitems, hide it
293 if ($relatedRecords['count'] >= $maxitems || $uniqueMax > 0 && $relatedRecords['count'] >= $uniqueMax) {
294 $config['inline']['inlineNewButtonStyle'] = 'display: none;';
295 }
296 // Add the level links before all child records:
297 if (in_array($config['appearance']['levelLinksPosition'], array('both', 'top'))) {
298 $item .= $levelLinks . $localizationLinks;
299 }
300 $item .= '<div id="' . $nameObject . '_records">';
301 $relationList = array();
302 if (count($relatedRecords['records'])) {
303 foreach ($relatedRecords['records'] as $rec) {
304 $item .= $this->renderForeignRecord($row['uid'], $rec, $config);
305 if (!isset($rec['__virtual']) || !$rec['__virtual']) {
306 $relationList[] = $rec['uid'];
307 }
308 }
309 }
310 $item .= '</div>';
311 // Add the level links after all child records:
312 if (in_array($config['appearance']['levelLinksPosition'], array('both', 'bottom'))) {
313 $item .= $levelLinks . $localizationLinks;
314 }
315 if (is_array($config['customControls'])) {
316 $item .= '<div id="' . $nameObject . '_customControls">';
317 foreach ($config['customControls'] as $customControlConfig) {
318 $parameters = array(
319 'table' => $table,
320 'field' => $field,
321 'row' => $row,
322 'nameObject' => $nameObject,
323 'nameForm' => $nameForm,
324 'config' => $config
325 );
326 $item .= GeneralUtility::callUserFunction($customControlConfig, $parameters, $this);
327 }
328 $item .= '</div>';
329 }
330 // Add Drag&Drop functions for sorting to TCEforms::$additionalJS_post
331 if (count($relationList) > 1 && $config['appearance']['useSortable']) {
332 $this->addJavaScriptSortable($nameObject . '_records');
333 }
334 // Publish the uids of the child records in the given order to the browser
335 $item .= '<input type="hidden" name="' . $nameForm . '" value="' . implode(',', $relationList) . '" class="inlineRecord" />';
336 // Close the wrap for all inline fields (container)
337 $item .= '</div>';
338 // On finishing this section, remove the last item from the structure stack
339 $this->popStructure();
340 // If this was the first call to the inline type, restore the values
341 if (!$this->getStructureDepth()) {
342 unset($this->inlineFirstPid);
343 }
344 return $item;
345 }
346
347 /*******************************************************
348 *
349 * Regular rendering of forms, fields, etc.
350 *
351 *******************************************************/
352 /**
353 * Render the form-fields of a related (foreign) record.
354 *
355 * @param string $parentUid The uid of the parent (embedding) record (uid or NEW...)
356 * @param array $rec The table record of the child/embedded table (normaly post-processed by \TYPO3\CMS\Backend\Form\DataPreprocessor)
357 * @param array $config Content of $PA['fieldConf']['config']
358 * @return string The HTML code for this "foreign record
359 * @todo Define visibility
360 */
361 public function renderForeignRecord($parentUid, $rec, $config = array()) {
362 $foreign_table = $config['foreign_table'];
363 $foreign_field = $config['foreign_field'];
364 $foreign_selector = $config['foreign_selector'];
365 // Register default localization content:
366 $parent = $this->getStructureLevel(-1);
367 if (isset($parent['localizationMode']) && $parent['localizationMode'] != FALSE) {
368 $this->fObj->registerDefaultLanguageData($foreign_table, $rec);
369 }
370 // Send a mapping information to the browser via JSON:
371 // e.g. data[<curTable>][<curId>][<curField>] => data-<pid>-<parentTable>-<parentId>-<parentField>-<curTable>-<curId>-<curField>
372 $this->inlineData['map'][$this->inlineNames['form']] = $this->inlineNames['object'];
373 // Set this variable if we handle a brand new unsaved record:
374 $isNewRecord = !MathUtility::canBeInterpretedAsInteger($rec['uid']);
375 // Set this variable if the record is virtual and only show with header and not editable fields:
376 $isVirtualRecord = isset($rec['__virtual']) && $rec['__virtual'];
377 // If there is a selector field, normalize it:
378 if ($foreign_selector) {
379 $rec[$foreign_selector] = $this->normalizeUid($rec[$foreign_selector]);
380 }
381 if (!$this->checkAccess(($isNewRecord ? 'new' : 'edit'), $foreign_table, $rec['uid'])) {
382 return FALSE;
383 }
384 // Get the current naming scheme for DOM name/id attributes:
385 $nameObject = $this->inlineNames['object'];
386 $appendFormFieldNames = '[' . $foreign_table . '][' . $rec['uid'] . ']';
387 $objectId = $nameObject . self::Structure_Separator . $foreign_table . self::Structure_Separator . $rec['uid'];
388 // Put the current level also to the dynNestedStack of TCEforms:
389 $this->fObj->pushToDynNestedStack('inline', $objectId);
390 $class = '';
391 if (!$isVirtualRecord) {
392 // Get configuration:
393 $collapseAll = isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll'];
394 $expandAll = isset($config['appearance']['collapseAll']) && !$config['appearance']['collapseAll'];
395 $ajaxLoad = isset($config['appearance']['ajaxLoad']) && !$config['appearance']['ajaxLoad'] ? FALSE : TRUE;
396 if ($isNewRecord) {
397 // Show this record expanded or collapsed
398 $isExpanded = $expandAll || (!$collapseAll ? 1 : 0);
399 } else {
400 $isExpanded = $config['renderFieldsOnly'] || !$collapseAll && $this->getExpandedCollapsedState($foreign_table, $rec['uid']) || $expandAll;
401 }
402 // 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
403 if ($isNewRecord || $isExpanded || !$ajaxLoad) {
404 $combination = $this->renderCombinationTable($rec, $appendFormFieldNames, $config);
405 $overruleTypesArray = isset($config['foreign_types']) ? $config['foreign_types'] : array();
406 $fields = $this->renderMainFields($foreign_table, $rec, $overruleTypesArray);
407 $fields = $this->wrapFormsSection($fields);
408 // Replace returnUrl in Wizard-Code, if this is an AJAX call
409 $ajaxArguments = GeneralUtility::_GP('ajax');
410 if (isset($ajaxArguments[2]) && trim($ajaxArguments[2]) != '') {
411 $fields = str_replace('P[returnUrl]=%2F' . rawurlencode(TYPO3_mainDir) . 'ajax.php', 'P[returnUrl]=' . rawurlencode($ajaxArguments[2]), $fields);
412 }
413 } else {
414 $combination = '';
415 // This string is the marker for the JS-function to check if the full content has already been loaded
416 $fields = '<!--notloaded-->';
417 }
418 if ($isNewRecord) {
419 // Get the top parent table
420 $top = $this->getStructureLevel(0);
421 $ucFieldName = 'uc[inlineView][' . $top['table'] . '][' . $top['uid'] . ']' . $appendFormFieldNames;
422 // Set additional fields for processing for saving
423 $fields .= '<input type="hidden" name="' . $this->prependFormFieldNames . $appendFormFieldNames . '[pid]" value="' . $rec['pid'] . '"/>';
424 $fields .= '<input type="hidden" name="' . $ucFieldName . '" value="' . $isExpanded . '" />';
425 } else {
426 // Set additional field for processing for saving
427 $fields .= '<input type="hidden" name="' . $this->prependCmdFieldNames . $appendFormFieldNames . '[delete]" value="1" disabled="disabled" />';
428 if (!$isExpanded
429 && !empty($GLOBALS['TCA'][$foreign_table]['ctrl']['enablecolumns']['disabled'])
430 && $ajaxLoad
431 ) {
432 $checked = !empty($rec['hidden']) ? ' checked="checked"' : '';
433 $fields .= '<input type="checkbox" name="' . $this->prependFormFieldNames . $appendFormFieldNames . '[hidden]_0" value="1"' . $checked . ' />';
434 $fields .= '<input type="input" name="' . $this->prependFormFieldNames . $appendFormFieldNames . '[hidden]" value="' . $rec['hidden'] . '" />';
435 }
436 }
437 // If this record should be shown collapsed
438 if (!$isExpanded) {
439 $class = 't3-form-field-container-inline-collapsed';
440 }
441 }
442 if ($config['renderFieldsOnly']) {
443 $out = $fields . $combination;
444 } else {
445 // Set the record container with data for output
446 if ($isVirtualRecord) {
447 $class .= ' t3-form-field-container-inline-placeHolder';
448 }
449 if (isset($rec['hidden']) && (int)$rec['hidden']) {
450 $class .= ' t3-form-field-container-inline-hidden';
451 }
452 $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>';
453 $header = IconUtility::getSpriteIcon('apps-irre-' . ($class != '' ? 'collapsed' : 'expanded'));
454 $header .= $this->renderForeignRecordHeader($parentUid, $foreign_table, $rec, $config, $isVirtualRecord);
455 $out = '<div class="t3-form-field-header-inline" id="' . $objectId . '_header">' . $header . '</div>' . $out;
456 // Wrap the header, fields and combination part of a child record with a div container
457 $classMSIE = $this->fObj->clientInfo['BROWSER'] == 'msie' && $this->fObj->clientInfo['VERSION'] < 8 ? 'MSIE' : '';
458 $class .= ' inlineDiv' . $classMSIE . ($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 $fieldValue = $transOrigRec[$field];
1490
1491 // Checks if it is a flexform field
1492 if ($GLOBALS['TCA'][$table]['columns'][$field]['config']['type'] === 'flex') {
1493 $flexFormParts = $this->extractFlexFormParts($PA['itemFormElName']);
1494 $flexData = GeneralUtility::xml2array($fieldValue);
1495 /** @var $flexFormTools \TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools */
1496 $flexFormTools = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Configuration\\FlexForm\\FlexFormTools');
1497 $flexFormFieldValue = $flexFormTools->getArrayValueByPath($flexFormParts, $flexData);
1498
1499 if ($flexFormFieldValue !== NULL) {
1500 $fieldValue = $flexFormFieldValue;
1501 }
1502 }
1503
1504 $recordsOriginal = $this->getRelatedRecordsArray($pid, $foreignTable, $fieldValue);
1505 }
1506 }
1507 }
1508 $records = $this->getRelatedRecordsArray($pid, $foreignTable, $elements);
1509 $relatedRecords = array('records' => $records, 'count' => count($records));
1510 // Merge original language with current localization and show differences:
1511 if (!empty($recordsOriginal)) {
1512 $options = array(
1513 'showPossible' => isset($config['appearance']['showPossibleLocalizationRecords']) && $config['appearance']['showPossibleLocalizationRecords'],
1514 'showRemoved' => isset($config['appearance']['showRemovedLocalizationRecords']) && $config['appearance']['showRemovedLocalizationRecords']
1515 );
1516 // Either show records that possibly can localized or removed
1517 if ($options['showPossible'] || $options['showRemoved']) {
1518 $relatedRecords['records'] = $this->getLocalizationDifferences($foreignTable, $options, $recordsOriginal, $records);
1519 // Otherwise simulate localizeChildrenAtParentLocalization behaviour when creating a new record
1520 // (which has language and translation pointer values set)
1521 } elseif (!empty($config['behaviour']['localizeChildrenAtParentLocalization']) && !MathUtility::canBeInterpretedAsInteger($row['uid'])) {
1522 if (!empty($GLOBALS['TCA'][$foreignTable]['ctrl']['transOrigPointerField'])) {
1523 $foreignLanguageField = $GLOBALS['TCA'][$foreignTable]['ctrl']['languageField'];
1524 }
1525 if (!empty($GLOBALS['TCA'][$foreignTable]['ctrl']['transOrigPointerField'])) {
1526 $foreignTranslationPointerField = $GLOBALS['TCA'][$foreignTable]['ctrl']['transOrigPointerField'];
1527 }
1528 // Duplicate child records of default language in form
1529 foreach ($recordsOriginal as $record) {
1530 if (!empty($foreignLanguageField)) {
1531 $record[$foreignLanguageField] = $language;
1532 }
1533 if (!empty($foreignTranslationPointerField)) {
1534 $record[$foreignTranslationPointerField] = $record['uid'];
1535 }
1536 $newId = uniqid('NEW');
1537 $record['uid'] = $newId;
1538 $record['pid'] = $this->inlineFirstPid;
1539 $relatedRecords['records'][$newId] = $record;
1540 }
1541 }
1542 }
1543 return $relatedRecords;
1544 }
1545
1546 /**
1547 * Gets the related records of the embedding item, this could be 1:n, m:n.
1548 *
1549 * @param integer $pid The pid of the parent record
1550 * @param string $table The table name of the record
1551 * @param string $itemList The list of related child records
1552 * @return array The records related to the parent item
1553 */
1554 protected function getRelatedRecordsArray($pid, $table, $itemList) {
1555 $records = array();
1556 $itemArray = $this->getRelatedRecordsUidArray($itemList);
1557 // Perform modification of the selected items array:
1558 foreach ($itemArray as $uid) {
1559 // Get the records for this uid using \TYPO3\CMS\Backend\Form\DataPreprocessor
1560 if ($record = $this->getRecord($pid, $table, $uid)) {
1561 $records[$uid] = $record;
1562 }
1563 }
1564 return $records;
1565 }
1566
1567 /**
1568 * Gets an array with the uids of related records out of a list of items.
1569 * This list could contain more information than required. This methods just
1570 * extracts the uids.
1571 *
1572 * @param string $itemList The list of related child records
1573 * @return array An array with uids
1574 */
1575 protected function getRelatedRecordsUidArray($itemList) {
1576 $itemArray = GeneralUtility::trimExplode(',', $itemList, TRUE);
1577 // Perform modification of the selected items array:
1578 foreach ($itemArray as $key => &$value) {
1579 $parts = explode('|', $value, 2);
1580 $value = $parts[0];
1581 }
1582 unset($value);
1583 return $itemArray;
1584 }
1585
1586 /**
1587 * Gets the difference between current localized structure and the original language structure.
1588 * If there are records which once were localized but don't exist in the original version anymore, the record row is marked with '__remove'.
1589 * If there are records which can be localized and exist only in the original version, the record row is marked with '__create' and '__virtual'.
1590 *
1591 * @param string $table The table name of the parent records
1592 * @param array $options Options defining what kind of records to display
1593 * @param array $recordsOriginal The uids of the child records of the original language
1594 * @param array $recordsLocalization The uids of the child records of the current localization
1595 * @return array Merged array of uids of the child records of both versions
1596 */
1597 protected function getLocalizationDifferences($table, array $options, array $recordsOriginal, array $recordsLocalization) {
1598 $records = array();
1599 $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
1600 // Compare original to localized version of the records:
1601 foreach ($recordsLocalization as $uid => $row) {
1602 // If the record points to a original translation which doesn't exist anymore, it could be removed:
1603 if (isset($row[$transOrigPointerField]) && $row[$transOrigPointerField] > 0) {
1604 $transOrigPointer = $row[$transOrigPointerField];
1605 if (isset($recordsOriginal[$transOrigPointer])) {
1606 unset($recordsOriginal[$transOrigPointer]);
1607 } elseif ($options['showRemoved']) {
1608 $row['__remove'] = TRUE;
1609 }
1610 }
1611 $records[$uid] = $row;
1612 }
1613 // Process the remaining records in the original unlocalized parent:
1614 if ($options['showPossible']) {
1615 foreach ($recordsOriginal as $uid => $row) {
1616 $row['__create'] = TRUE;
1617 $row['__virtual'] = TRUE;
1618 $records[$uid] = $row;
1619 }
1620 }
1621 return $records;
1622 }
1623
1624 /**
1625 * Get possible records.
1626 * Copied from TCEform and modified.
1627 *
1628 * @param string $table The table name of the record
1629 * @param string $field The field name which this element is supposed to edit
1630 * @param array $row The record data array where the value(s) for the field can be found
1631 * @param array $conf An array with additional configuration options.
1632 * @param string $checkForConfField For which field in the foreign_table the possible records should be fetched
1633 * @return mixed Array of possible record items; FALSE if type is "group/db", then everything could be "possible
1634 * @todo Define visibility
1635 */
1636 public function getPossibleRecords($table, $field, $row, $conf, $checkForConfField = 'foreign_selector') {
1637 // ctrl configuration from TCA:
1638 $tcaTableCtrl = $GLOBALS['TCA'][$table]['ctrl'];
1639 // Field configuration from TCA:
1640 $foreign_table = $conf['foreign_table'];
1641 $foreign_check = $conf[$checkForConfField];
1642 $foreignConfig = $this->getPossibleRecordsSelectorConfig($conf, $foreign_check);
1643 $PA = $foreignConfig['PA'];
1644 $config = $PA['fieldConf']['config'];
1645 if ($foreignConfig['type'] == 'select') {
1646 // Getting the selector box items from the system
1647 $selItems = $this->fObj->addSelectOptionsToItemArray($this->fObj->initItemArray($PA['fieldConf']), $PA['fieldConf'], $this->fObj->setTSconfig($table, $row), $field);
1648
1649 // Possibly filter some items:
1650 $selItems = GeneralUtility::keepItemsInArray(
1651 $selItems,
1652 $PA['fieldTSConfig']['keepItems'],
1653 function ($value) {
1654 return $value[1];
1655 }
1656 );
1657
1658 // Possibly add some items:
1659 $selItems = $this->fObj->addItems($selItems, $PA['fieldTSConfig']['addItems.']);
1660 if (isset($config['itemsProcFunc']) && $config['itemsProcFunc']) {
1661 $selItems = $this->fObj->procItems($selItems, $PA['fieldTSConfig']['itemsProcFunc.'], $config, $table, $row, $field);
1662 }
1663 // Possibly remove some items:
1664 $removeItems = GeneralUtility::trimExplode(',', $PA['fieldTSConfig']['removeItems'], TRUE);
1665 foreach ($selItems as $tk => $p) {
1666 // Checking languages and authMode:
1667 $languageDeny = $tcaTableCtrl['languageField'] && (string)$tcaTableCtrl['languageField'] === $field && !$GLOBALS['BE_USER']->checkLanguageAccess($p[1]);
1668 $authModeDeny = $config['form_type'] == 'select' && $config['authMode'] && !$GLOBALS['BE_USER']->checkAuthMode($table, $field, $p[1], $config['authMode']);
1669 if (in_array($p[1], $removeItems) || $languageDeny || $authModeDeny) {
1670 unset($selItems[$tk]);
1671 } elseif (isset($PA['fieldTSConfig']['altLabels.'][$p[1]])) {
1672 $selItems[$tk][0] = htmlspecialchars($this->fObj->sL($PA['fieldTSConfig']['altLabels.'][$p[1]]));
1673 }
1674 // Removing doktypes with no access:
1675 if (($table === 'pages' || $table === 'pages_language_overlay') && $field === 'doktype') {
1676 if (!($GLOBALS['BE_USER']->isAdmin() || GeneralUtility::inList($GLOBALS['BE_USER']->groupData['pagetypes_select'], $p[1]))) {
1677 unset($selItems[$tk]);
1678 }
1679 }
1680 }
1681 } else {
1682 $selItems = FALSE;
1683 }
1684 return $selItems;
1685 }
1686
1687 /**
1688 * Gets the uids of a select/selector that should be unique an have already been used.
1689 *
1690 * @param array $records All inline records on this level
1691 * @param array $conf The TCA field configuration of the inline field to be rendered
1692 * @param boolean $splitValue For usage with group/db, values come like "tx_table_123|Title%20abc", but we need "tx_table" and "123
1693 * @return array The uids, that have been used already and should be used unique
1694 * @todo Define visibility
1695 */
1696 public function getUniqueIds($records, $conf = array(), $splitValue = FALSE) {
1697 $uniqueIds = array();
1698 if (isset($conf['foreign_unique']) && $conf['foreign_unique'] && count($records)) {
1699 foreach ($records as $rec) {
1700 // Skip virtual records (e.g. shown in localization mode):
1701 if (!isset($rec['__virtual']) || !$rec['__virtual']) {
1702 $value = $rec[$conf['foreign_unique']];
1703 // Split the value and extract the table and uid:
1704 if ($splitValue) {
1705 $valueParts = GeneralUtility::trimExplode('|', $value);
1706 $itemParts = explode('_', $valueParts[0]);
1707 $value = array(
1708 'uid' => array_pop($itemParts),
1709 'table' => implode('_', $itemParts)
1710 );
1711 }
1712 $uniqueIds[$rec['uid']] = $value;
1713 }
1714 }
1715 }
1716 return $uniqueIds;
1717 }
1718
1719 /**
1720 * Determines the corrected pid to be used for a new record.
1721 * The pid to be used can be defined by a Page TSconfig.
1722 *
1723 * @param string $table The table name
1724 * @param integer $parentPid The pid of the parent record
1725 * @return integer The corrected pid to be used for a new record
1726 */
1727 protected function getNewRecordPid($table, $parentPid = NULL) {
1728 $newRecordPid = $this->inlineFirstPid;
1729 $pageTS = BackendUtility::getPagesTSconfig($parentPid);
1730 if (isset($pageTS['TCAdefaults.'][$table . '.']['pid']) && MathUtility::canBeInterpretedAsInteger($pageTS['TCAdefaults.'][$table . '.']['pid'])) {
1731 $newRecordPid = $pageTS['TCAdefaults.'][$table . '.']['pid'];
1732 } elseif (isset($parentPid) && MathUtility::canBeInterpretedAsInteger($parentPid)) {
1733 $newRecordPid = $parentPid;
1734 }
1735 return $newRecordPid;
1736 }
1737
1738 /**
1739 * Get a single record row for a TCA table from the database.
1740 * \TYPO3\CMS\Backend\Form\DataPreprocessor is used for "upgrading" the
1741 * values, especially the relations.
1742 *
1743 * @param integer $pid The pid of the page the record should be stored (only relevant for NEW records)
1744 * @param string $table The table to fetch data from (= foreign_table)
1745 * @param string $uid The uid of the record to fetch, or the pid if a new record should be created
1746 * @param string $cmd The command to perform, empty or 'new'
1747 * @return array A record row from the database post-processed by \TYPO3\CMS\Backend\Form\DataPreprocessor
1748 * @todo Define visibility
1749 */
1750 public function getRecord($pid, $table, $uid, $cmd = '') {
1751 // Fetch workspace version of a record (if any):
1752 if ($cmd !== 'new' && $GLOBALS['BE_USER']->workspace !== 0 && BackendUtility::isTableWorkspaceEnabled($table)) {
1753 $workspaceVersion = BackendUtility::getWorkspaceVersionOfRecord($GLOBALS['BE_USER']->workspace, $table, $uid, 'uid,t3ver_state');
1754 if ($workspaceVersion !== FALSE) {
1755 $versionState = VersionState::cast($workspaceVersion['t3ver_state']);
1756 if ($versionState->equals(VersionState::DELETE_PLACEHOLDER)) {
1757 return FALSE;
1758 }
1759 $uid = $workspaceVersion['uid'];
1760 }
1761 }
1762 /** @var $trData \TYPO3\CMS\Backend\Form\DataPreprocessor */
1763 $trData = GeneralUtility::makeInstance('TYPO3\\CMS\\Backend\\Form\\DataPreprocessor');
1764 $trData->addRawData = TRUE;
1765 $trData->lockRecords = 1;
1766 $trData->disableRTE = $GLOBALS['SOBE']->MOD_SETTINGS['disableRTE'];
1767 // If a new record should be created
1768 $trData->fetchRecord($table, $uid, $cmd === 'new' ? 'new' : '');
1769 $rec = reset($trData->regTableItems_data);
1770 return $rec;
1771 }
1772
1773 /**
1774 * Wrapper. Calls getRecord in case of a new record should be created.
1775 *
1776 * @param integer $pid The pid of the page the record should be stored (only relevant for NEW records)
1777 * @param string $table The table to fetch data from (= foreign_table)
1778 * @return array A record row from the database post-processed by \TYPO3\CMS\Backend\Form\DataPreprocessor
1779 * @todo Define visibility
1780 */
1781 public function getNewRecord($pid, $table) {
1782 $rec = $this->getRecord($pid, $table, $pid, 'new');
1783 $rec['uid'] = uniqid('NEW');
1784 $rec['pid'] = $this->getNewRecordPid($table, $pid);
1785 return $rec;
1786 }
1787
1788 /*******************************************************
1789 *
1790 * Structure stack for handling inline objects/levels
1791 *
1792 *******************************************************/
1793 /**
1794 * Add a new level on top of the structure stack. Other functions can access the
1795 * stack and determine, if there's possibly a endless loop.
1796 *
1797 * @param string $table The table name of the record
1798 * @param string $uid The uid of the record that embeds the inline data
1799 * @param string $field The field name which this element is supposed to edit
1800 * @param array $config The TCA-configuration of the inline field
1801 * @param array $parameters The full parameter array (PA)
1802 * @return void
1803 * @todo Define visibility
1804 */
1805 public function pushStructure($table, $uid, $field = '', $config = array(), array $parameters = array()) {
1806 $structure = array(
1807 'table' => $table,
1808 'uid' => $uid,
1809 'field' => $field,
1810 'config' => $config,
1811 'localizationMode' => BackendUtility::getInlineLocalizationMode($table, $config),
1812 );
1813
1814 // Extract FlexForm parts (if any) from element name,
1815 // e.g. array('vDEF', 'lDEF', 'FlexField', 'vDEF')
1816 if (!empty($parameters['itemFormElName'])) {
1817 $flexFormParts = $this->extractFlexFormParts($parameters['itemFormElName']);
1818
1819 if ($flexFormParts !== NULL) {
1820 $structure['flexform'] = $flexFormParts;
1821 }
1822 }
1823
1824 $this->inlineStructure['stable'][] = $structure;
1825 $this->updateStructureNames();
1826 }
1827
1828 /**
1829 * Remove the item on top of the structure stack and return it.
1830 *
1831 * @return array The top item of the structure stack - array(<table>,<uid>,<field>,<config>)
1832 * @todo Define visibility
1833 */
1834 public function popStructure() {
1835 $popItem = NULL;
1836
1837 if (count($this->inlineStructure['stable'])) {
1838 $popItem = array_pop($this->inlineStructure['stable']);
1839 $this->updateStructureNames();
1840 }
1841 return $popItem;
1842 }
1843
1844 /**
1845 * For common use of DOM object-ids and form field names of a several inline-level,
1846 * these names/identifiers are preprocessed and set to $this->inlineNames.
1847 * This function is automatically called if a level is pushed to or removed from the
1848 * inline structure stack.
1849 *
1850 * @return void
1851 * @todo Define visibility
1852 */
1853 public function updateStructureNames() {
1854 $current = $this->getStructureLevel(-1);
1855 // If there are still more inline levels available
1856 if ($current !== FALSE) {
1857 $this->inlineNames = array(
1858 'form' => $this->prependFormFieldNames . $this->getStructureItemName($current, self::Disposal_AttributeName),
1859 'object' => $this->prependNaming . self::Structure_Separator . $this->inlineFirstPid . self::Structure_Separator . $this->getStructurePath()
1860 );
1861 } else {
1862 $this->inlineNames = array();
1863 }
1864 }
1865
1866 /**
1867 * Create a name/id for usage in HTML output of a level of the structure stack to be used in form names.
1868 *
1869 * @param array $levelData Array of a level of the structure stack (containing the keys table, uid and field)
1870 * @param string $disposal How the structure name is used (e.g. as <div id="..."> or <input name="..." />)
1871 * @return string The name/id of that level, to be used for HTML output
1872 * @todo Define visibility
1873 */
1874 public function getStructureItemName($levelData, $disposal = self::Disposal_AttributeId) {
1875 $name = NULL;
1876
1877 if (is_array($levelData)) {
1878 $parts = array($levelData['table'], $levelData['uid']);
1879
1880 if (!empty($levelData['field'])) {
1881 $parts[] = $levelData['field'];
1882 }
1883
1884 // Use in name attributes:
1885 if ($disposal === self::Disposal_AttributeName) {
1886 if (!empty($levelData['field']) && !empty($levelData['flexform']) && $this->getStructureLevel(-1) === $levelData) {
1887 $parts[] = implode('][', $levelData['flexform']);
1888 }
1889 $name = '[' . implode('][', $parts) . ']';
1890 // Use in object id attributes:
1891 } else {
1892 $name = implode(self::Structure_Separator, $parts);
1893
1894 if (!empty($levelData['field']) && !empty($levelData['flexform'])) {
1895 array_unshift($levelData['flexform'], $name);
1896 $name = implode(self::FlexForm_Separator, $levelData['flexform']);
1897 }
1898 }
1899 }
1900
1901 return $name;
1902 }
1903
1904 /**
1905 * Get a level from the stack and return the data.
1906 * If the $level value is negative, this function works top-down,
1907 * if the $level value is positive, this function works bottom-up.
1908 *
1909 * @param integer $level Which level to return
1910 * @return array The item of the stack at the requested level
1911 * @todo Define visibility
1912 */
1913 public function getStructureLevel($level) {
1914 $level = $this->calculateStructureLevel($level);
1915
1916 if ($level !== FALSE) {
1917 return $this->inlineStructure['stable'][$level];
1918 } else {
1919 return FALSE;
1920 }
1921 }
1922
1923 /**
1924 * Calculates structure level.
1925 *
1926 * @param integer $level Which level to return
1927 * @return boolean|integer
1928 */
1929 protected function calculateStructureLevel($level) {
1930 $result = FALSE;
1931
1932 $inlineStructureCount = count($this->inlineStructure['stable']);
1933 if ($level < 0) {
1934 $level = $inlineStructureCount + $level;
1935 }
1936 if ($level >= 0 && $level < $inlineStructureCount) {
1937 $result = $level;
1938 }
1939
1940 return $result;
1941 }
1942
1943 /**
1944 * Get the identifiers of a given depth of level, from the top of the stack to the bottom.
1945 * An identifier looks like "<table>-<uid>-<field>".
1946 *
1947 * @param integer $structureDepth How much levels to output, beginning from the top of the stack
1948 * @return string The path of identifiers
1949 * @todo Define visibility
1950 */
1951 public function getStructurePath($structureDepth = -1) {
1952 $structureLevels = array();
1953 $structureCount = count($this->inlineStructure['stable']);
1954 if ($structureDepth < 0 || $structureDepth > $structureCount) {
1955 $structureDepth = $structureCount;
1956 }
1957 for ($i = 1; $i <= $structureDepth; $i++) {
1958 array_unshift($structureLevels, $this->getStructureItemName($this->getStructureLevel(-$i), self::Disposal_AttributeId));
1959 }
1960 return implode(self::Structure_Separator, $structureLevels);
1961 }
1962
1963 /**
1964 * Convert the DOM object-id of an inline container to an array.
1965 * The object-id could look like 'data-parentPageId-tx_mmftest_company-1-employees'.
1966 * The result is written to $this->inlineStructure.
1967 * There are two keys:
1968 * - 'stable': Containing full qualified identifiers (table, uid and field)
1969 * - 'unstable': Containting partly filled data (e.g. only table and possibly field)
1970 *
1971 * @param string $domObjectId The DOM object-id
1972 * @param boolean $loadConfig Load the TCA configuration for that level (default: TRUE)
1973 * @return void
1974 * @todo Define visibility
1975 */
1976 public function parseStructureString($string, $loadConfig = TRUE) {
1977 $unstable = array();
1978 $vector = array('table', 'uid', 'field');
1979
1980 // Substitute FlexForm additon and make parsing a bit easier
1981 $string = str_replace(self::FlexForm_Separator, self::FlexForm_Substitute, $string);
1982 // The starting pattern of an object identifer (e.g. "data-<firstPidValue>-<anything>)
1983 $pattern = '/^' . $this->prependNaming . self::Structure_Separator . '(.+?)' . self::Structure_Separator . '(.+)$/';
1984
1985 if (preg_match($pattern, $string, $match)) {
1986 $this->inlineFirstPid = $match[1];
1987 $parts = explode(self::Structure_Separator, $match[2]);
1988 $partsCnt = count($parts);
1989 for ($i = 0; $i < $partsCnt; $i++) {
1990 if ($i > 0 && $i % 3 == 0) {
1991 // Load the TCA configuration of the table field and store it in the stack
1992 if ($loadConfig) {
1993 $unstable['config'] = $GLOBALS['TCA'][$unstable['table']]['columns'][$unstable['field']]['config'];
1994 // Fetch TSconfig:
1995 $TSconfig = $this->fObj->setTSconfig($unstable['table'], array('uid' => $unstable['uid'], 'pid' => $this->inlineFirstPid), $unstable['field']);
1996 // Override TCA field config by TSconfig:
1997 if (!$TSconfig['disabled']) {
1998 $unstable['config'] = $this->fObj->overrideFieldConf($unstable['config'], $TSconfig);
1999 }
2000 $unstable['localizationMode'] = BackendUtility::getInlineLocalizationMode($unstable['table'], $unstable['config']);
2001 }
2002
2003 // Extract FlexForm from field part (if any)
2004 if (strpos($unstable['field'], self::FlexForm_Substitute) !== FALSE) {
2005 $fieldParts = GeneralUtility::trimExplode(self::FlexForm_Substitute, $unstable['field']);
2006 $unstable['field'] = array_shift($fieldParts);
2007 // FlexForm parts start with data:
2008 if (count($fieldParts) > 0 && $fieldParts[0] === 'data') {
2009 $unstable['flexform'] = $fieldParts;
2010 }
2011 }
2012
2013 $this->inlineStructure['stable'][] = $unstable;
2014 $unstable = array();
2015 }
2016 $unstable[$vector[$i % 3]] = $parts[$i];
2017 }
2018 $this->updateStructureNames();
2019 if (count($unstable)) {
2020 $this->inlineStructure['unstable'] = $unstable;
2021 }
2022 }
2023 }
2024
2025 /*******************************************************
2026 *
2027 * Helper functions
2028 *
2029 *******************************************************/
2030 /**
2031 * Does some checks on the TCA configuration of the inline field to render.
2032 *
2033 * @param array $config Reference to the TCA field configuration
2034 * @param string $table The table name of the record
2035 * @param string $field The field name which this element is supposed to edit
2036 * @param array $row The record data array of the parent
2037 * @return boolean If critical configuration errors were found, FALSE is returned
2038 * @todo Define visibility
2039 */
2040 public function checkConfiguration(&$config) {
2041 $foreign_table = $config['foreign_table'];
2042 // An inline field must have a foreign_table, if not, stop all further inline actions for this field:
2043 if (!$foreign_table || !is_array($GLOBALS['TCA'][$foreign_table])) {
2044 return FALSE;
2045 }
2046 // Init appearance if not set:
2047 if (!isset($config['appearance']) || !is_array($config['appearance'])) {
2048 $config['appearance'] = array();
2049 }
2050 // Set the position/appearance of the "Create new record" link:
2051 if (isset($config['foreign_selector']) && $config['foreign_selector'] && (!isset($config['appearance']['useCombination']) || !$config['appearance']['useCombination'])) {
2052 $config['appearance']['levelLinksPosition'] = 'none';
2053 } elseif (!isset($config['appearance']['levelLinksPosition']) || !in_array($config['appearance']['levelLinksPosition'], array('top', 'bottom', 'both', 'none'))) {
2054 $config['appearance']['levelLinksPosition'] = 'top';
2055 }
2056 // Defines which controls should be shown in header of each record:
2057 $enabledControls = array(
2058 'info' => TRUE,
2059 'new' => TRUE,
2060 'dragdrop' => TRUE,
2061 'sort' => TRUE,
2062 'hide' => TRUE,
2063 'delete' => TRUE,
2064 'localize' => TRUE
2065 );
2066 if (isset($config['appearance']['enabledControls']) && is_array($config['appearance']['enabledControls'])) {
2067 $config['appearance']['enabledControls'] = array_merge($enabledControls, $config['appearance']['enabledControls']);
2068 } else {
2069 $config['appearance']['enabledControls'] = $enabledControls;
2070 }
2071 return TRUE;
2072 }
2073
2074 /**
2075 * Checks the page access rights (Code for access check mostly taken from alt_doc.php)
2076 * as well as the table access rights of the user.
2077 *
2078 * @param string $cmd The command that sould be performed ('new' or 'edit')
2079 * @param string $table The table to check access for
2080 * @param string $theUid The record uid of the table
2081 * @return boolean Returns TRUE is the user has access, or FALSE if not
2082 * @todo Define visibility
2083 */
2084 public function checkAccess($cmd, $table, $theUid) {
2085 // 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...)
2086 // First, resetting flags.
2087 $hasAccess = 0;
2088 $deniedAccessReason = '';
2089 // Admin users always have acces:
2090 if ($GLOBALS['BE_USER']->isAdmin()) {
2091 return TRUE;
2092 }
2093 // If the command is to create a NEW record...:
2094 if ($cmd == 'new') {
2095 // If the pid is numerical, check if it's possible to write to this page:
2096 if (MathUtility::canBeInterpretedAsInteger($this->inlineFirstPid)) {
2097 $calcPRec = BackendUtility::getRecord('pages', $this->inlineFirstPid);
2098 if (!is_array($calcPRec)) {
2099 return FALSE;
2100 }
2101 // Permissions for the parent page
2102 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
2103 // If pages:
2104 if ($table == 'pages') {
2105 // Are we allowed to create new subpages?
2106 $hasAccess = $CALC_PERMS & 8 ? 1 : 0;
2107 } else {
2108 // Are we allowed to edit content on this page?
2109 $hasAccess = $CALC_PERMS & 16 ? 1 : 0;
2110 }
2111 } else {
2112 $hasAccess = 1;
2113 }
2114 } else {
2115 // Edit:
2116 $calcPRec = BackendUtility::getRecord($table, $theUid);
2117 BackendUtility::fixVersioningPid($table, $calcPRec);
2118 if (is_array($calcPRec)) {
2119 // If pages:
2120 if ($table == 'pages') {
2121 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
2122 $hasAccess = $CALC_PERMS & 2 ? 1 : 0;
2123 } else {
2124 // Fetching pid-record first.
2125 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms(BackendUtility::getRecord('pages', $calcPRec['pid']));
2126 $hasAccess = $CALC_PERMS & 16 ? 1 : 0;
2127 }
2128 // Check internals regarding access:
2129 if ($hasAccess) {
2130 $hasAccess = $GLOBALS['BE_USER']->recordEditAccessInternals($table, $calcPRec);
2131 }
2132 }
2133 }
2134 if (!$GLOBALS['BE_USER']->check('tables_modify', $table)) {
2135 $hasAccess = 0;
2136 }
2137 if (!$hasAccess) {
2138 $deniedAccessReason = $GLOBALS['BE_USER']->errorMsg;
2139 if ($deniedAccessReason) {
2140 debug($deniedAccessReason);
2141 }
2142 }
2143 return $hasAccess ? TRUE : FALSE;
2144 }
2145
2146 /**
2147 * Check the keys and values in the $compare array against the ['config'] part of the top level of the stack.
2148 * A boolean value is return depending on how the comparison was successful.
2149 *
2150 * @param array $compare Keys and values to compare to the ['config'] part of the top level of the stack
2151 * @return boolean Whether the comparison was successful
2152 * @see arrayCompareComplex
2153 * @todo Define visibility
2154 */
2155 public function compareStructureConfiguration($compare) {
2156 $level = $this->getStructureLevel(-1);
2157 $result = $this->arrayCompareComplex($level, $compare);
2158 return $result;
2159 }
2160
2161 /**
2162 * Normalize a relation "uid" published by transferData, like "1|Company%201"
2163 *
2164 * @param string $string A transferData reference string, containing the uid
2165 * @return string The normalized uid
2166 * @todo Define visibility
2167 */
2168 public function normalizeUid($string) {
2169 $parts = explode('|', $string);
2170 return $parts[0];
2171 }
2172
2173 /**
2174 * Wrap the HTML code of a section with a table tag.
2175 *
2176 * @param string $section The HTML code to be wrapped
2177 * @param array $styleAttrs Attributes for the style argument in the table tag
2178 * @param array $tableAttrs Attributes for the table tag (like width, border, etc.)
2179 * @return string The wrapped HTML code
2180 * @todo Define visibility
2181 */
2182 public function wrapFormsSection($section, $styleAttrs = array(), $tableAttrs = array()) {
2183 $style = '';
2184 $table = '';
2185 foreach ($styleAttrs as $key => $value) {
2186 $style .= ($style ? ' ' : '') . $key . ': ' . htmlspecialchars($value) . '; ';
2187 }
2188 if ($style) {
2189 $style = ' style="' . $style . '"';
2190 }
2191 if (!$tableAttrs['background'] && $this->fObj->borderStyle[2]) {
2192 $tableAttrs['background'] = $this->backPath . $this->borderStyle[2];
2193 }
2194 if (!$tableAttrs['class'] && $this->borderStyle[3]) {
2195 $tableAttrs['class'] = $this->borderStyle[3];
2196 }
2197 foreach ($tableAttrs as $key => $value) {
2198 $table .= ($table ? ' ' : '') . $key . '="' . htmlspecialchars($value) . '"';
2199 }
2200 $out = '<table ' . $table . $style . '>' . $section . '</table>';
2201 return $out;
2202 }
2203
2204 /**
2205 * Checks if the $table is the child of a inline type AND the $field is the label field of this table.
2206 * This function is used to dynamically update the label while editing. This has no effect on labels,
2207 * that were processed by a TCEmain-hook on saving.
2208 *
2209 * @param string $table The table to check
2210 * @param string $field The field on this table to check
2211 * @return boolean Is inline child and field is responsible for the label
2212 * @todo Define visibility
2213 */
2214 public function isInlineChildAndLabelField($table, $field) {
2215 $level = $this->getStructureLevel(-1);
2216 if ($level['config']['foreign_label']) {
2217 $label = $level['config']['foreign_label'];
2218 } else {
2219 $label = $GLOBALS['TCA'][$table]['ctrl']['label'];
2220 }
2221 return $level['config']['foreign_table'] === $table && $label == $field ? TRUE : FALSE;
2222 }
2223
2224 /**
2225 * Get the depth of the stable structure stack.
2226 * (count($this->inlineStructure['stable'])
2227 *
2228 * @return integer The depth of the structure stack
2229 * @todo Define visibility
2230 */
2231 public function getStructureDepth() {
2232 return count($this->inlineStructure['stable']);
2233 }
2234
2235 /**
2236 * Handles complex comparison requests on an array.
2237 * A request could look like the following:
2238 *
2239 * $searchArray = array(
2240 * '%AND' => array(
2241 * 'key1' => 'value1',
2242 * 'key2' => 'value2',
2243 * '%OR' => array(
2244 * 'subarray' => array(
2245 * 'subkey' => 'subvalue'
2246 * ),
2247 * 'key3' => 'value3',
2248 * 'key4' => 'value4'
2249 * )
2250 * )
2251 * );
2252 *
2253 * It is possible to use the array keys '%AND.1', '%AND.2', etc. to prevent
2254 * overwriting the sub-array. It could be necessary, if you use complex comparisons.
2255 *
2256 * The example above means, key1 *AND* key2 (and their values) have to match with
2257 * the $subjectArray and additional one *OR* key3 or key4 have to meet the same
2258 * condition.
2259 * It is also possible to compare parts of a sub-array (e.g. "subarray"), so this
2260 * function recurses down one level in that sub-array.
2261 *
2262 * @param array $subjectArray The array to search in
2263 * @param array $searchArray The array with keys and values to search for
2264 * @param string $type Use '%AND' or '%OR' for comparison
2265 * @return boolean The result of the comparison
2266 * @todo Define visibility
2267 */
2268 public function arrayCompareComplex($subjectArray, $searchArray, $type = '') {
2269 $localMatches = 0;
2270 $localEntries = 0;
2271 if (is_array($searchArray) && count($searchArray)) {
2272 // If no type was passed, try to determine
2273 if (!$type) {
2274 reset($searchArray);
2275 $type = key($searchArray);
2276 $searchArray = current($searchArray);
2277 }
2278 // We use '%AND' and '%OR' in uppercase
2279 $type = strtoupper($type);
2280 // Split regular elements from sub elements
2281 foreach ($searchArray as $key => $value) {
2282 $localEntries++;
2283 // Process a sub-group of OR-conditions
2284 if ($key == '%OR') {
2285 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%OR') ? 1 : 0;
2286 } elseif ($key == '%AND') {
2287 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%AND') ? 1 : 0;
2288 } elseif (is_array($value) && $this->isAssociativeArray($searchArray)) {
2289 $localMatches += $this->arrayCompareComplex($subjectArray[$key], $value, $type) ? 1 : 0;
2290 } elseif (is_array($value)) {
2291 $localMatches += $this->arrayCompareComplex($subjectArray, $value, $type) ? 1 : 0;
2292 } else {
2293 if (isset($subjectArray[$key]) && isset($value)) {
2294 // Boolean match:
2295 if (is_bool($value)) {
2296 $localMatches += !($subjectArray[$key] xor $value) ? 1 : 0;
2297 } elseif (is_numeric($subjectArray[$key]) && is_numeric($value)) {
2298 $localMatches += $subjectArray[$key] == $value ? 1 : 0;
2299 } else {
2300 $localMatches += $subjectArray[$key] === $value ? 1 : 0;
2301 }
2302 }
2303 }
2304 // If one or more matches are required ('OR'), return TRUE after the first successful match
2305 if ($type == '%OR' && $localMatches > 0) {
2306 return TRUE;
2307 }
2308 // If all matches are required ('AND') and we have no result after the first run, return FALSE
2309 if ($type == '%AND' && $localMatches == 0) {
2310 return FALSE;
2311 }
2312 }
2313 }
2314 // Return the result for '%AND' (if nothing was checked, TRUE is returned)
2315 return $localEntries == $localMatches ? TRUE : FALSE;
2316 }
2317
2318 /**
2319 * Checks whether an object is an associative array.
2320 *
2321 * @param mixed $object The object to be checked
2322 * @return boolean Returns TRUE, if the object is an associative array
2323 * @todo Define visibility
2324 */
2325 public function isAssociativeArray($object) {
2326 return is_array($object) && count($object) && array_keys($object) !== range(0, sizeof($object) - 1) ? TRUE : FALSE;
2327 }
2328
2329 /**
2330 * Remove an element from an array.
2331 *
2332 * @param mixed $needle The element to be removed.
2333 * @param array $haystack The array the element should be removed from.
2334 * @param mixed $strict Search elements strictly.
2335 * @return array The array $haystack without the $needle
2336 * @todo Define visibility
2337 */
2338 public function removeFromArray($needle, $haystack, $strict = NULL) {
2339 $pos = array_search($needle, $haystack, $strict);
2340 if ($pos !== FALSE) {
2341 unset($haystack[$pos]);
2342 }
2343 return $haystack;
2344 }
2345
2346 /**
2347 * Makes a flat array from the $possibleRecords array.
2348 * The key of the flat array is the value of the record,
2349 * the value of the flat array is the label of the record.
2350 *
2351 * @param array $possibleRecords The possibleRecords array (for select fields)
2352 * @return mixed A flat array with key=uid, value=label; if $possibleRecords isn't an array, FALSE is returned.
2353 * @todo Define visibility
2354 */
2355 public function getPossibleRecordsFlat($possibleRecords) {
2356 $flat = FALSE;
2357 if (is_array($possibleRecords)) {
2358 $flat = array();
2359 foreach ($possibleRecords as $record) {
2360 $flat[$record[1]] = $record[0];
2361 }
2362 }
2363 return $flat;
2364 }
2365
2366 /**
2367 * Determine the configuration and the type of a record selector.
2368 *
2369 * @param array $conf TCA configuration of the parent(!) field
2370 * @return array Associative array with the keys 'PA' and 'type', both are FALSE if the selector was not valid.
2371 * @todo Define visibility
2372 */
2373 public function getPossibleRecordsSelectorConfig($conf, $field = '') {
2374 $foreign_table = $conf['foreign_table'];
2375 $foreign_selector = $conf['foreign_selector'];
2376 $PA = FALSE;
2377 $type = FALSE;
2378 $table = FALSE;
2379 $selector = FALSE;
2380 if ($field) {
2381 $PA = array();
2382 $PA['fieldConf'] = $GLOBALS['TCA'][$foreign_table]['columns'][$field];
2383 if ($PA['fieldConf'] && $conf['foreign_selector_fieldTcaOverride']) {
2384 \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($PA['fieldConf'], $conf['foreign_selector_fieldTcaOverride']);
2385 }
2386 $PA['fieldConf']['config']['form_type'] = $PA['fieldConf']['config']['form_type'] ?: $PA['fieldConf']['config']['type'];
2387 // Using "form_type" locally in this script
2388 $PA['fieldTSConfig'] = $this->fObj->setTSconfig($foreign_table, array(), $field);
2389 $config = $PA['fieldConf']['config'];
2390 // Determine type of Selector:
2391 $type = $this->getPossibleRecordsSelectorType($config);
2392 // Return table on this level:
2393 $table = $type == 'select' ? $config['foreign_table'] : $config['allowed'];
2394 // Return type of the selector if foreign_selector is defined and points to the same field as in $field:
2395 if ($foreign_selector && $foreign_selector == $field && $type) {
2396 $selector = $type;
2397 }
2398 }
2399 return array(
2400 'PA' => $PA,
2401 'type' => $type,
2402 'table' => $table,
2403 'selector' => $selector
2404 );
2405 }
2406
2407 /**
2408 * Determine the type of a record selector, e.g. select or group/db.
2409 *
2410 * @param array $config TCE configuration of the selector
2411 * @return mixed The type of the selector, 'select' or 'groupdb' - FALSE not valid
2412 * @todo Define visibility
2413 */
2414 public function getPossibleRecordsSelectorType($config) {
2415 $type = FALSE;
2416 if ($config['type'] == 'select') {
2417 $type = 'select';
2418 } elseif ($config['type'] == 'group' && $config['internal_type'] == 'db') {
2419 $type = 'groupdb';
2420 }
2421 return $type;
2422 }
2423
2424 /**
2425 * Check, if a field should be skipped, that was defined to be handled as foreign_field or foreign_sortby of
2426 * the parent record of the "inline"-type - if so, we have to skip this field - the rendering is done via "inline" as hidden field
2427 *
2428 * @param string $table The table name
2429 * @param string $field The field name
2430 * @param array $row The record row from the database
2431 * @param array $config TCA configuration of the field
2432 * @return boolean Determines whether the field should be skipped.
2433 * @todo Define visibility
2434 */
2435 public function skipField($table, $field, $row, $config) {
2436 $skipThisField = FALSE;
2437 if ($this->getStructureDepth()) {
2438 $searchArray = array(
2439 '%OR' => array(
2440 'config' => array(
2441 0 => array(
2442 '%AND' => array(
2443 'foreign_table' => $table,
2444 '%OR' => array(
2445 '%AND' => array(
2446 'appearance' => array('useCombination' => TRUE),
2447 'foreign_selector' => $field
2448 ),
2449 'MM' => $config['MM']
2450 )
2451 )
2452 ),
2453 1 => array(
2454 '%AND' => array(
2455 'foreign_table' => $config['foreign_table'],
2456 'foreign_selector' => $config['foreign_field']
2457 )
2458 )
2459 )
2460 )
2461 );
2462 // Get the parent record from structure stack
2463 $level = $this->getStructureLevel(-1);
2464 // If we have symmetric fields, check on which side we are and hide fields, that are set automatically:
2465 if (RelationHandler::isOnSymmetricSide($level['uid'], $level['config'], $row)) {
2466 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_field'] = $field;
2467 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_sortby'] = $field;
2468 } else {
2469 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_field'] = $field;
2470 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_sortby'] = $field;
2471 }
2472 $skipThisField = $this->compareStructureConfiguration($searchArray, TRUE);
2473 }
2474 return $skipThisField;
2475 }
2476
2477 /**
2478 * Checks if a uid of a child table is in the inline view settings.
2479 *
2480 * @param string $table Name of the child table
2481 * @param integer $uid uid of the the child record
2482 * @return boolean TRUE=expand, FALSE=collapse
2483 * @todo Define visibility
2484 */
2485 public function getExpandedCollapsedState($table, $uid) {
2486 if (isset($this->inlineView[$table]) && is_array($this->inlineView[$table])) {
2487 if (in_array($uid, $this->inlineView[$table]) !== FALSE) {
2488 return TRUE;
2489 }
2490 }
2491 return FALSE;
2492 }
2493
2494 /**
2495 * Update expanded/collapsed states on new inline records if any.
2496 *
2497 * @param array $uc The uc array to be processed and saved (by reference)
2498 * @param \TYPO3\CMS\Core\DataHandling\DataHandler $tce Instance of TCEmain that saved data before
2499 * @return void
2500 * @todo Define visibility
2501 */
2502 static public function updateInlineView(&$uc, $tce) {
2503 if (isset($uc['inlineView']) && is_array($uc['inlineView'])) {
2504 $inlineView = (array) unserialize($GLOBALS['BE_USER']->uc['inlineView']);
2505 foreach ($uc['inlineView'] as $topTable => $topRecords) {
2506 foreach ($topRecords as $topUid => $childElements) {
2507 foreach ($childElements as $childTable => $childRecords) {
2508 $uids = array_keys($tce->substNEWwithIDs_table, $childTable);
2509 if (count($uids)) {
2510 $newExpandedChildren = array();
2511 foreach ($childRecords as $childUid => $state) {
2512 if ($state && in_array($childUid, $uids)) {
2513 $newChildUid = $tce->substNEWwithIDs[$childUid];
2514 $newExpandedChildren[] = $newChildUid;
2515 }
2516 }
2517 // Add new expanded child records to UC (if any):
2518 if (count($newExpandedChildren)) {
2519 $inlineViewCurrent = &$inlineView[$topTable][$topUid][$childTable];
2520 if (is_array($inlineViewCurrent)) {
2521 $inlineViewCurrent = array_unique(array_merge($inlineViewCurrent, $newExpandedChildren));
2522 } else {
2523 $inlineViewCurrent = $newExpandedChildren;
2524 }
2525 }
2526 }
2527 }
2528 }