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