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