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