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