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