[TASK] Encapsulate bootstrap base code
[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 $GLOBALS['LANG']->includeLLFile('EXT:lang/locallang_alt_doc.xml');
1051
1052 // Create a new anonymous object:
1053 $GLOBALS['SOBE'] = new stdClass();
1054 $GLOBALS['SOBE']->MOD_MENU = array(
1055 'showPalettes' => '',
1056 'showDescriptions' => '',
1057 'disableRTE' => ''
1058 );
1059 // Setting virtual document name
1060 $GLOBALS['SOBE']->MCONF['name'] = 'xMOD_alt_doc.php';
1061 // CLEANSE SETTINGS
1062 $GLOBALS['SOBE']->MOD_SETTINGS = t3lib_BEfunc::getModuleData(
1063 $GLOBALS['SOBE']->MOD_MENU,
1064 t3lib_div::_GP('SET'),
1065 $GLOBALS['SOBE']->MCONF['name']
1066 );
1067 // Create an instance of the document template object
1068 $GLOBALS['SOBE']->doc = t3lib_div::makeInstance('template');
1069 $GLOBALS['SOBE']->doc->backPath = $GLOBALS['BACK_PATH'];
1070 // Initialize TCEforms (rendering the forms)
1071 $GLOBALS['SOBE']->tceforms = t3lib_div::makeInstance('t3lib_TCEforms');
1072 $GLOBALS['SOBE']->tceforms->inline = $this;
1073 $GLOBALS['SOBE']->tceforms->RTEcounter = intval(array_shift($ajaxArguments));
1074 $GLOBALS['SOBE']->tceforms->initDefaultBEMode();
1075 $GLOBALS['SOBE']->tceforms->palettesCollapsed = !$GLOBALS['SOBE']->MOD_SETTINGS['showPalettes'];
1076 $GLOBALS['SOBE']->tceforms->disableRTE = $GLOBALS['SOBE']->MOD_SETTINGS['disableRTE'];
1077 $GLOBALS['SOBE']->tceforms->enableClickMenu = TRUE;
1078 $GLOBALS['SOBE']->tceforms->enableTabMenu = TRUE;
1079 // Clipboard is initialized:
1080 // Start clipboard
1081 $GLOBALS['SOBE']->tceforms->clipObj = t3lib_div::makeInstance('t3lib_clipboard');
1082 // Initialize - reads the clipboard content from the user session
1083 $GLOBALS['SOBE']->tceforms->clipObj->initializeClipboard();
1084 // Setting external variables:
1085 if ($GLOBALS['BE_USER']->uc['edit_showFieldHelp'] != 'text' && $GLOBALS['SOBE']->MOD_SETTINGS['showDescriptions']) {
1086 $GLOBALS['SOBE']->tceforms->edit_showFieldHelp = 'text';
1087 }
1088 }
1089
1090 /**
1091 * Determines and sets several script calls to a JSON array, that would have been executed if processed in non-AJAX mode.
1092 *
1093 * @param array &$jsonArray Reference of the array to be used for JSON
1094 * @param array $config The configuration of the IRRE field of the parent record
1095 * @return void
1096 */
1097 protected function getCommonScriptCalls(&$jsonArray, $config) {
1098 // Add data that would have been added at the top of a regular TCEforms call:
1099 if ($headTags = $this->getHeadTags()) {
1100 $jsonArray['headData'] = $headTags;
1101 }
1102 // Add the JavaScript data that would have been added at the bottom of a regular TCEforms call:
1103 $jsonArray['scriptCall'][] = $this->fObj->JSbottom($this->fObj->formName, TRUE);
1104 // If script.aculo.us Sortable is used, update the Observer to know the record:
1105 if ($config['appearance']['useSortable']) {
1106 $jsonArray['scriptCall'][] = "inline.createDragAndDropSorting('" . $this->inlineNames['object'] . "_records');";
1107 }
1108 // if TCEforms has some JavaScript code to be executed, just do it
1109 if ($this->fObj->extJSCODE) {
1110 $jsonArray['scriptCall'][] = $this->fObj->extJSCODE;
1111 }
1112 }
1113
1114 /**
1115 * Generates an error message that transferred as JSON for AJAX calls
1116 *
1117 * @param string $message The error message to be shown
1118 * @return array The error message in a JSON array
1119 */
1120 protected function getErrorMessageForAJAX($message) {
1121 $jsonArray = array(
1122 'data' => $message,
1123 'scriptCall' => array(
1124 'alert("' . $message . '");'
1125 )
1126 );
1127 return $jsonArray;
1128 }
1129
1130 /**
1131 * Handle AJAX calls to show a new inline-record of the given table.
1132 * Normally this method is never called from inside TYPO3. Always from outside by AJAX.
1133 *
1134 * @param string $domObjectId The calling object in hierarchy, that requested a new record.
1135 * @param string $foreignUid If set, the new record should be inserted after that one.
1136 * @return array An array to be used for JSON
1137 */
1138 function createNewRecord($domObjectId, $foreignUid = 0) {
1139 // The current table - for this table we should add/import records
1140 $current = $this->inlineStructure['unstable'];
1141 // The parent table - this table embeds the current table
1142 $parent = $this->getStructureLevel(-1);
1143 // Get TCA 'config' of the parent table
1144 if (!$this->checkConfiguration($parent['config'])) {
1145 return $this->getErrorMessageForAJAX('Wrong configuration in table ' . $parent['table']);
1146 }
1147 $config = $parent['config'];
1148
1149 $collapseAll = (isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll']);
1150 $expandSingle = (isset($config['appearance']['expandSingle']) && $config['appearance']['expandSingle']);
1151
1152 // Put the current level also to the dynNestedStack of TCEforms:
1153 $this->fObj->pushToDynNestedStack('inline', $this->inlineNames['object']);
1154
1155 // Dynamically create a new record using t3lib_transferData
1156 if (!$foreignUid || !t3lib_utility_Math::canBeInterpretedAsInteger($foreignUid) || $config['foreign_selector']) {
1157 $record = $this->getNewRecord($this->inlineFirstPid, $current['table']);
1158 // Set language of new child record to the language of the parent record:
1159 if ($config['localizationMode'] == 'select') {
1160 $parentRecord = $this->getRecord(0, $parent['table'], $parent['uid']);
1161 $parentLanguageField = $GLOBALS['TCA'][$parent['table']]['ctrl']['languageField'];
1162 $childLanguageField = $GLOBALS['TCA'][$current['table']]['ctrl']['languageField'];
1163 if ($parentRecord[$parentLanguageField] > 0) {
1164 $record[$childLanguageField] = $parentRecord[$parentLanguageField];
1165 }
1166 }
1167
1168 // Dynamically import an existing record (this could be a call from a select box)
1169 } else {
1170 $record = $this->getRecord($this->inlineFirstPid, $current['table'], $foreignUid);
1171 }
1172
1173 // Now there is a foreign_selector, so there is a new record on the intermediate table, but
1174 // this intermediate table holds a field, which is responsible for the foreign_selector, so
1175 // we have to set this field to the uid we get - or if none, to a new uid
1176 if ($config['foreign_selector'] && $foreignUid) {
1177 $selConfig = $this->getPossibleRecordsSelectorConfig($config, $config['foreign_selector']);
1178 // For a selector of type group/db, prepend the tablename (<tablename>_<uid>):
1179 $record[$config['foreign_selector']] = $selConfig['type'] != 'groupdb' ? '' : $selConfig['table'] . '_';
1180 $record[$config['foreign_selector']] .= $foreignUid;
1181 }
1182
1183 // The HTML-object-id's prefix of the dynamically created record
1184 $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $current['table'];
1185 $objectId = $objectPrefix . self::Structure_Separator . $record['uid'];
1186
1187 // Render the foreign record that should passed back to browser
1188 $item = $this->renderForeignRecord($parent['uid'], $record, $config);
1189 if ($item === FALSE) {
1190 return $this->getErrorMessageForAJAX('Access denied');
1191 }
1192
1193 if (!$current['uid']) {
1194 $jsonArray = array(
1195 'data' => $item,
1196 'scriptCall' => array(
1197 "inline.domAddNewRecord('bottom','" . $this->inlineNames['object'] . "_records','" . $objectPrefix . "',json.data);",
1198 "inline.memorizeAddRecord('" . $objectPrefix . "','" . $record['uid'] . "',null,'" . $foreignUid . "');"
1199 )
1200 );
1201
1202 // Append the HTML data after an existing record in the container
1203 } else {
1204 $jsonArray = array(
1205 'data' => $item,
1206 'scriptCall' => array(
1207 "inline.domAddNewRecord('after','" . $domObjectId . '_div' . "','" . $objectPrefix. "',json.data);",
1208 "inline.memorizeAddRecord('" . $objectPrefix . "','" . $record['uid'] . "','" . $current['uid'] . "','" . $foreignUid . "');"
1209 )
1210 );
1211 }
1212 $this->getCommonScriptCalls($jsonArray, $config);
1213 // Collapse all other records if requested:
1214 if (!$collapseAll && $expandSingle) {
1215 $jsonArray['scriptCall'][] = "inline.collapseAllRecords('" . $objectId . "', '" . $objectPrefix . "', '" . $record['uid'] . "');";
1216 }
1217 // Tell the browser to scroll to the newly created record
1218 $jsonArray['scriptCall'][] = "Element.scrollTo('" . $objectId . "_div');";
1219 // Fade out and fade in the new record in the browser view to catch the user's eye
1220 $jsonArray['scriptCall'][] = "inline.fadeOutFadeIn('" . $objectId . "_div');";
1221
1222 // Remove the current level also from the dynNestedStack of TCEforms:
1223 $this->fObj->popFromDynNestedStack();
1224
1225 // Return the JSON array:
1226 return $jsonArray;
1227 }
1228
1229 /**
1230 * Handle AJAX calls to localize all records of a parent, localize a single record or to synchronize with the original language parent.
1231 *
1232 * @param string $domObjectId The calling object in hierarchy, that requested a new record.
1233 * @param mixed $type Defines the type 'localize' or 'synchronize' (string) or a single uid to be localized (integer)
1234 * @return array An array to be used for JSON
1235 */
1236 protected function synchronizeLocalizeRecords($domObjectId, $type) {
1237 $jsonArray = FALSE;
1238 if (t3lib_div::inList('localize,synchronize', $type) || t3lib_utility_Math::canBeInterpretedAsInteger($type)) {
1239 // The current level:
1240 $current = $this->inlineStructure['unstable'];
1241 // The parent level:
1242 $parent = $this->getStructureLevel(-1);
1243 $parentRecord = $this->getRecord(0, $parent['table'], $parent['uid']);
1244
1245 $cmd = array();
1246 $cmd[$parent['table']][$parent['uid']]['inlineLocalizeSynchronize'] = $parent['field'] . ',' . $type;
1247
1248 /** @var t3lib_TCEmain */
1249 $tce = t3lib_div::makeInstance('t3lib_TCEmain');
1250 $tce->stripslashes_values = FALSE;
1251 $tce->start(array(), $cmd);
1252 $tce->process_cmdmap();
1253 $newItemList = $tce->registerDBList[$parent['table']][$parent['uid']][$parent['field']];
1254 unset($tce);
1255
1256 $jsonArray = $this->getExecuteChangesJsonArray($parentRecord[$parent['field']], $newItemList);
1257 $this->getCommonScriptCalls($jsonArray, $parent['config']);
1258 }
1259 return $jsonArray;
1260 }
1261
1262 /**
1263 * Handle AJAX calls to dynamically load the form fields of a given record.
1264 * (basically a copy of "createNewRecord")
1265 * Normally this method is never called from inside TYPO3. Always from outside by AJAX.
1266 *
1267 * @param string $domObjectId The calling object in hierarchy, that requested a new record.
1268 * @return array An array to be used for JSON
1269 */
1270 function getRecordDetails($domObjectId) {
1271 // The current table - for this table we should add/import records
1272 $current = $this->inlineStructure['unstable'];
1273 // The parent table - this table embeds the current table
1274 $parent = $this->getStructureLevel(-1);
1275 // Get TCA 'config' of the parent table
1276 if (!$this->checkConfiguration($parent['config'])) {
1277 return $this->getErrorMessageForAJAX('Wrong configuration in table ' . $parent['table']);
1278 }
1279 $config = $parent['config'];
1280 // Set flag in config so that only the fields are rendered
1281 $config['renderFieldsOnly'] = TRUE;
1282
1283 $collapseAll = (isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll']);
1284 $expandSingle = (isset($config['appearance']['expandSingle']) && $config['appearance']['expandSingle']);
1285
1286 // Put the current level also to the dynNestedStack of TCEforms:
1287 $this->fObj->pushToDynNestedStack('inline', $this->inlineNames['object']);
1288
1289 $record = $this->getRecord($this->inlineFirstPid, $current['table'], $current['uid']);
1290
1291 // The HTML-object-id's prefix of the dynamically created record
1292 $objectPrefix = $this->inlineNames['object'] . self::Structure_Separator . $current['table'];
1293 $objectId = $objectPrefix . self::Structure_Separator . $record['uid'];
1294
1295 $item = $this->renderForeignRecord($parent['uid'], $record, $config);
1296 if ($item === FALSE) {
1297 return $this->getErrorMessageForAJAX('Access denied');
1298 }
1299
1300 $jsonArray = array(
1301 'data' => $item,
1302 'scriptCall' => array(
1303 'inline.domAddRecordDetails(\'' . $domObjectId . '\',\'' . $objectPrefix . '\',' . ($expandSingle ? '1' : '0') . ',json.data);',
1304 )
1305 );
1306 if ($config['foreign_unique']) {
1307 $jsonArray['scriptCall'][] = 'inline.removeUsed(\'' . $objectPrefix . '\',\'' . $record['uid'] . '\');';
1308 }
1309 $this->getCommonScriptCalls($jsonArray, $config);
1310 // Collapse all other records if requested:
1311 if (!$collapseAll && $expandSingle) {
1312 $jsonArray['scriptCall'][] = 'inline.collapseAllRecords(\'' . $objectId . '\',\'' . $objectPrefix . '\',\'' . $record['uid'] . '\');';
1313 }
1314
1315 // Remove the current level also from the dynNestedStack of TCEforms:
1316 $this->fObj->popFromDynNestedStack();
1317
1318 // Return the JSON array:
1319 return $jsonArray;
1320 }
1321
1322 /**
1323 * Generates a JSON array which executes the changes and thus updates the forms view.
1324 *
1325 * @param string $oldItemList List of related child reocrds before changes were made (old)
1326 * @param string $newItemList List of related child records after changes where made (new)
1327 * @return array An array to be used for JSON
1328 */
1329 protected function getExecuteChangesJsonArray($oldItemList, $newItemList) {
1330 $data = '';
1331 $parent = $this->getStructureLevel(-1);
1332 $current = $this->inlineStructure['unstable'];
1333
1334 $jsonArray = array('scriptCall' => array());
1335 $jsonArrayScriptCall =& $jsonArray['scriptCall'];
1336
1337 $nameObject = $this->inlineNames['object'];
1338 $nameObjectForeignTable = $nameObject . self::Structure_Separator . $current['table'];
1339 // Get the name of the field pointing to the original record:
1340 $transOrigPointerField = $GLOBALS['TCA'][$current['table']]['ctrl']['transOrigPointerField'];
1341 // Get the name of the field used as foreign selector (if any):
1342 $foreignSelector = (isset($parent['config']['foreign_selector']) && $parent['config']['foreign_selector'] ? $parent['config']['foreign_selector'] : FALSE);
1343 // Convert lists to array with uids of child records:
1344 $oldItems = $this->getRelatedRecordsUidArray($oldItemList);
1345 $newItems = $this->getRelatedRecordsUidArray($newItemList);
1346 // Determine the items that were localized or localized:
1347 $removedItems = array_diff($oldItems, $newItems);
1348 $localizedItems = array_diff($newItems, $oldItems);
1349 // Set the items that should be removed in the forms view:
1350 foreach ($removedItems as $item) {
1351 $jsonArrayScriptCall[] = "inline.deleteRecord('" . $nameObjectForeignTable . self::Structure_Separator . $item . "', {forceDirectRemoval: true});";
1352 }
1353 // Set the items that should be added in the forms view:
1354 foreach ($localizedItems as $item) {
1355 $row = $this->getRecord($this->inlineFirstPid, $current['table'], $item);
1356 $selectedValue = ($foreignSelector ? "'" . $row[$foreignSelector] . "'" : 'null');
1357 $data .= $this->renderForeignRecord($parent['uid'], $row, $parent['config']);
1358 $jsonArrayScriptCall[] = "inline.memorizeAddRecord('" . $nameObjectForeignTable . "', '" . $item . "', null, " . $selectedValue . ');';
1359 // Remove possible virtual records in the form which showed that a child records could be localized:
1360 if (isset($row[$transOrigPointerField]) && $row[$transOrigPointerField]) {
1361 $jsonArrayScriptCall[] = "inline.fadeAndRemove('" . $nameObjectForeignTable . self::Structure_Separator . $row[$transOrigPointerField] . '_div' . "');";
1362 }
1363 }
1364 if ($data) {
1365 $jsonArray['data'] = $data;
1366 array_unshift(
1367 $jsonArrayScriptCall,
1368 "inline.domAddNewRecord('bottom', '" . $nameObject . "_records', '" . $nameObjectForeignTable . "', json.data);"
1369 );
1370 }
1371
1372 return $jsonArray;
1373 }
1374
1375 /**
1376 * Save the expanded/collapsed state of a child record in the BE_USER->uc.
1377 *
1378 * @param string $domObjectId The calling object in hierarchy, that requested a new record.
1379 * @param string $expand Whether this record is expanded.
1380 * @param string $collapse Whether this record is collapsed.
1381 * @return void
1382 */
1383 function setExpandedCollapsedState($domObjectId, $expand, $collapse) {
1384 // Parse the DOM identifier (string), add the levels to the structure stack (array), but don't load TCA config
1385 $this->parseStructureString($domObjectId, FALSE);
1386 // The current table - for this table we should add/import records
1387 $current = $this->inlineStructure['unstable'];
1388 // The top parent table - this table embeds the current table
1389 $top = $this->getStructureLevel(0);
1390
1391 // Only do some action if the top record and the current record were saved before
1392 if (t3lib_utility_Math::canBeInterpretedAsInteger($top['uid'])) {
1393 $inlineView = (array) unserialize($GLOBALS['BE_USER']->uc['inlineView']);
1394 $inlineViewCurrent =& $inlineView[$top['table']][$top['uid']];
1395
1396 $expandUids = t3lib_div::trimExplode(',', $expand);
1397 $collapseUids = t3lib_div::trimExplode(',', $collapse);
1398
1399 // Set records to be expanded
1400 foreach ($expandUids as $uid) {
1401 $inlineViewCurrent[$current['table']][] = $uid;
1402 }
1403 // Set records to be collapsed
1404 foreach ($collapseUids as $uid) {
1405 $inlineViewCurrent[$current['table']] = $this->removeFromArray($uid, $inlineViewCurrent[$current['table']]);
1406 }
1407
1408 // Save states back to database
1409 if (is_array($inlineViewCurrent[$current['table']])) {
1410 $inlineViewCurrent[$current['table']] = array_unique($inlineViewCurrent[$current['table']]);
1411 $GLOBALS['BE_USER']->uc['inlineView'] = serialize($inlineView);
1412 $GLOBALS['BE_USER']->writeUC();
1413 }
1414 }
1415 }
1416
1417 /*******************************************************
1418 *
1419 * Get data from database and handle relations
1420 *
1421 *******************************************************/
1422
1423 /**
1424 * Get the related records of the embedding item, this could be 1:n, m:n.
1425 * Returns an associative array with the keys records and count. 'count' contains only real existing records on the current parent record.
1426 *
1427 * @param string $table The table name of the record
1428 * @param string $field The field name which this element is supposed to edit
1429 * @param array $row The record data array where the value(s) for the field can be found
1430 * @param array $PA An array with additional configuration options.
1431 * @param array $config (Redundant) content of $PA['fieldConf']['config'] (for convenience)
1432 * @return array The records related to the parent item as associative array.
1433 */
1434 function getRelatedRecords($table, $field, $row, &$PA, $config) {
1435 $records = array();
1436 $pid = $row['pid'];
1437 $elements = $PA['itemFormElValue'];
1438 $foreignTable = $config['foreign_table'];
1439
1440 $localizationMode = t3lib_BEfunc::getInlineLocalizationMode($table, $config);
1441
1442 if ($localizationMode != FALSE) {
1443 $language = intval($row[$GLOBALS['TCA'][$table]['ctrl']['languageField']]);
1444 $transOrigPointer = intval($row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']]);
1445 if ($language > 0 && $transOrigPointer) {
1446 // Localization in mode 'keep', isn't a real localization, but keeps the children of the original parent record:
1447 if ($localizationMode == 'keep') {
1448 $transOrigRec = $this->getRecord(0, $table, $transOrigPointer);
1449 $elements = $transOrigRec[$field];
1450 $pid = $transOrigRec['pid'];
1451 // Localization in modes 'select', 'all' or 'sync' offer a dynamic localization and synchronization with the original language record:
1452 } elseif ($localizationMode == 'select') {
1453 $transOrigRec = $this->getRecord(0, $table, $transOrigPointer);
1454 $pid = $transOrigRec['pid'];
1455 $recordsOriginal = $this->getRelatedRecordsArray($pid, $foreignTable, $transOrigRec[$field]);
1456 }
1457 }
1458 }
1459
1460 $records = $this->getRelatedRecordsArray($pid, $foreignTable, $elements);
1461 $relatedRecords = array('records' => $records, 'count' => count($records));
1462
1463 // Merge original language with current localization and show differences:
1464 if (is_array($recordsOriginal)) {
1465 $options = array(
1466 'showPossible' => (isset($config['appearance']['showPossibleLocalizationRecords']) && $config['appearance']['showPossibleLocalizationRecords']),
1467 'showRemoved' => (isset($config['appearance']['showRemovedLocalizationRecords']) && $config['appearance']['showRemovedLocalizationRecords']),
1468 );
1469 if ($options['showPossible'] || $options['showRemoved']) {
1470 $relatedRecords['records'] = $this->getLocalizationDifferences($foreignTable, $options, $recordsOriginal, $records);
1471 }
1472 }
1473
1474 return $relatedRecords;
1475 }
1476
1477 /**
1478 * Gets the related records of the embedding item, this could be 1:n, m:n.
1479 *
1480 * @param integer $pid The pid of the parent record
1481 * @param string $table The table name of the record
1482 * @param string $itemList The list of related child records
1483 * @return array The records related to the parent item
1484 */
1485 protected function getRelatedRecordsArray($pid, $table, $itemList) {
1486 $records = array();
1487 $itemArray = $this->getRelatedRecordsUidArray($itemList);
1488 // Perform modification of the selected items array:
1489 foreach ($itemArray as $uid) {
1490 // Get the records for this uid using t3lib_transferdata:
1491 if ($record = $this->getRecord($pid, $table, $uid)) {
1492 $records[$uid] = $record;
1493 }
1494 }
1495 return $records;
1496 }
1497
1498 /**
1499 * Gets an array with the uids of related records out of a list of items.
1500 * This list could contain more information than required. This methods just
1501 * extracts the uids.
1502 *
1503 * @param string $itemList The list of related child records
1504 * @return array An array with uids
1505 */
1506 protected function getRelatedRecordsUidArray($itemList) {
1507 $itemArray = t3lib_div::trimExplode(',', $itemList, 1);
1508 // Perform modification of the selected items array:
1509 foreach ($itemArray as $key => &$value) {
1510 $parts = explode('|', $value, 2);
1511 $value = $parts[0];
1512 }
1513 unset($value);
1514 return $itemArray;
1515 }
1516
1517 /**
1518 * Gets the difference between current localized structure and the original language structure.
1519 * If there are records which once were localized but don't exist in the original version anymore, the record row is marked with '__remove'.
1520 * If there are records which can be localized and exist only in the original version, the record row is marked with '__create' and '__virtual'.
1521 *
1522 * @param string $table The table name of the parent records
1523 * @param array $options Options defining what kind of records to display
1524 * @param array $recordsOriginal The uids of the child records of the original language
1525 * @param array $recordsLocalization The uids of the child records of the current localization
1526 * @return array Merged array of uids of the child records of both versions
1527 */
1528 protected function getLocalizationDifferences($table, array $options, array $recordsOriginal, array $recordsLocalization) {
1529 $records = array();
1530 $transOrigPointerField = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
1531 // Compare original to localized version of the records:
1532 foreach ($recordsLocalization as $uid => $row) {
1533 // If the record points to a original translation which doesn't exist anymore, it could be removed:
1534 if (isset($row[$transOrigPointerField]) && $row[$transOrigPointerField] > 0) {
1535 $transOrigPointer = $row[$transOrigPointerField];
1536 if (isset($recordsOriginal[$transOrigPointer])) {
1537 unset($recordsOriginal[$transOrigPointer]);
1538 } elseif ($options['showRemoved']) {
1539 $row['__remove'] = TRUE;
1540 }
1541 }
1542 $records[$uid] = $row;
1543 }
1544 // Process the remaining records in the original unlocalized parent:
1545 if ($options['showPossible']) {
1546 foreach ($recordsOriginal as $uid => $row) {
1547 $row['__create'] = TRUE;
1548 $row['__virtual'] = TRUE;
1549 $records[$uid] = $row;
1550 }
1551 }
1552 return $records;
1553 }
1554
1555 /**
1556 * Get possible records.
1557 * Copied from TCEform and modified.
1558 *
1559 * @param string $table The table name of the record
1560 * @param string $field The field name which this element is supposed to edit
1561 * @param array $row The record data array where the value(s) for the field can be found
1562 * @param array $conf An array with additional configuration options.
1563 * @param string $checkForConfField For which field in the foreign_table the possible records should be fetched
1564 * @return mixed Array of possible record items; FALSE if type is "group/db", then everything could be "possible"
1565 */
1566 function getPossibleRecords($table, $field, $row, $conf, $checkForConfField = 'foreign_selector') {
1567 // ctrl configuration from TCA:
1568 $tcaTableCtrl = $GLOBALS['TCA'][$table]['ctrl'];
1569 // Field configuration from TCA:
1570 $foreign_table = $conf['foreign_table'];
1571 $foreign_check = $conf[$checkForConfField];
1572
1573 $foreignConfig = $this->getPossibleRecordsSelectorConfig($conf, $foreign_check);
1574 $PA = $foreignConfig['PA'];
1575 $config = $PA['fieldConf']['config'];
1576
1577 if ($foreignConfig['type'] == 'select') {
1578 // Getting the selector box items from the system
1579 $selItems = $this->fObj->addSelectOptionsToItemArray(
1580 $this->fObj->initItemArray($PA['fieldConf']),
1581 $PA['fieldConf'],
1582 $this->fObj->setTSconfig($table, $row),
1583 $field
1584 );
1585 // Possibly filter some items:
1586 $keepItemsFunc = create_function('$value', 'return $value[1];');
1587 $selItems = t3lib_div::keepItemsInArray($selItems, $PA['fieldTSConfig']['keepItems'], $keepItemsFunc);
1588 // Possibly add some items:
1589 $selItems = $this->fObj->addItems($selItems, $PA['fieldTSConfig']['addItems.']);
1590 if (isset($config['itemsProcFunc']) && $config['itemsProcFunc']) {
1591 $selItems = $this->fObj->procItems($selItems, $PA['fieldTSConfig']['itemsProcFunc.'], $config, $table, $row, $field);
1592 }
1593
1594 // Possibly remove some items:
1595 $removeItems = t3lib_div::trimExplode(',', $PA['fieldTSConfig']['removeItems'], 1);
1596 foreach ($selItems as $tk => $p) {
1597
1598 // Checking languages and authMode:
1599 $languageDeny = $tcaTableCtrl['languageField'] && !strcmp($tcaTableCtrl['languageField'], $field) && !$GLOBALS['BE_USER']->checkLanguageAccess($p[1]);
1600 $authModeDeny = $config['form_type'] == 'select' && $config['authMode'] && !$GLOBALS['BE_USER']->checkAuthMode($table, $field, $p[1], $config['authMode']);
1601 if (in_array($p[1], $removeItems) || $languageDeny || $authModeDeny) {
1602 unset($selItems[$tk]);
1603 } elseif (isset($PA['fieldTSConfig']['altLabels.'][$p[1]])) {
1604 $selItems[$tk][0] = $this->fObj->sL($PA['fieldTSConfig']['altLabels.'][$p[1]]);
1605 }
1606
1607 // Removing doktypes with no access:
1608 if (($table === 'pages' || $table === 'pages_language_overlay') && $field === 'doktype') {
1609 if (!($GLOBALS['BE_USER']->isAdmin() || t3lib_div::inList($GLOBALS['BE_USER']->groupData['pagetypes_select'], $p[1]))) {
1610 unset($selItems[$tk]);
1611 }
1612 }
1613 }
1614 } else {
1615 $selItems = FALSE;
1616 }
1617
1618 return $selItems;
1619 }
1620
1621 /**
1622 * Gets the uids of a select/selector that should be unique an have already been used.
1623 *
1624 * @param array $records All inline records on this level
1625 * @param array $conf The TCA field configuration of the inline field to be rendered
1626 * @param boolean $splitValue For usage with group/db, values come like "tx_table_123|Title%20abc", but we need "tx_table" and "123"
1627 * @return array The uids, that have been used already and should be used unique
1628 */
1629 function getUniqueIds($records, $conf = array(), $splitValue = FALSE) {
1630 $uniqueIds = array();
1631
1632 if (isset($conf['foreign_unique']) && $conf['foreign_unique'] && count($records)) {
1633 foreach ($records as $rec) {
1634 // Skip virtual records (e.g. shown in localization mode):
1635 if (!isset($rec['__virtual']) || !$rec['__virtual']) {
1636 $value = $rec[$conf['foreign_unique']];
1637 // Split the value and extract the table and uid:
1638 if ($splitValue) {
1639 $valueParts = t3lib_div::trimExplode('|', $value);
1640 $itemParts = explode('_', $valueParts[0]);
1641 $value = array(
1642 'uid' => array_pop($itemParts),
1643 'table' => implode('_', $itemParts)
1644 );
1645 }
1646 $uniqueIds[$rec['uid']] = $value;
1647 }
1648 }
1649 }
1650
1651 return $uniqueIds;
1652 }
1653
1654 /**
1655 * Determines the corrected pid to be used for a new record.
1656 * The pid to be used can be defined by a Page TSconfig.
1657 *
1658 * @param string $table The table name
1659 * @param integer $parentPid The pid of the parent record
1660 * @return integer The corrected pid to be used for a new record
1661 */
1662 protected function getNewRecordPid($table, $parentPid = NULL) {
1663 $newRecordPid = $this->inlineFirstPid;
1664 $pageTS = t3lib_beFunc::getPagesTSconfig($parentPid, TRUE);
1665 if (isset($pageTS['TCAdefaults.'][$table . '.']['pid']) && t3lib_utility_Math::canBeInterpretedAsInteger($pageTS['TCAdefaults.'][$table . '.']['pid'])) {
1666 $newRecordPid = $pageTS['TCAdefaults.'][$table . '.']['pid'];
1667 } elseif (isset($parentPid) && t3lib_utility_Math::canBeInterpretedAsInteger($parentPid)) {
1668 $newRecordPid = $parentPid;
1669 }
1670 return $newRecordPid;
1671 }
1672
1673 /**
1674 * Get a single record row for a TCA table from the database.
1675 * t3lib_transferData is used for "upgrading" the values, especially the relations.
1676 *
1677 * @param integer $pid The pid of the page the record should be stored (only relevant for NEW records)
1678 * @param string $table The table to fetch data from (= foreign_table)
1679 * @param string $uid The uid of the record to fetch, or the pid if a new record should be created
1680 * @param string $cmd The command to perform, empty or 'new'
1681 * @return array A record row from the database post-processed by t3lib_transferData
1682 */
1683 function getRecord($pid, $table, $uid, $cmd = '') {
1684 // Fetch workspace version of a record (if any):
1685 if ($cmd !== 'new' && $GLOBALS['BE_USER']->workspace !== 0) {
1686 $workspaceVersion = t3lib_BEfunc::getWorkspaceVersionOfRecord($GLOBALS['BE_USER']->workspace, $table, $uid, 'uid');
1687 if ($workspaceVersion !== FALSE) {
1688 $uid = $workspaceVersion['uid'];
1689 }
1690 }
1691
1692 $trData = t3lib_div::makeInstance('t3lib_transferData');
1693 $trData->addRawData = TRUE;
1694 $trData->lockRecords = 1;
1695 $trData->disableRTE = $GLOBALS['SOBE']->MOD_SETTINGS['disableRTE'];
1696 // If a new record should be created
1697 $trData->fetchRecord($table, $uid, ($cmd === 'new' ? 'new' : ''));
1698 $rec = reset($trData->regTableItems_data);
1699
1700 return $rec;
1701 }
1702
1703 /**
1704 * Wrapper. Calls getRecord in case of a new record should be created.
1705 *
1706 * @param integer $pid The pid of the page the record should be stored (only relevant for NEW records)
1707 * @param string $table The table to fetch data from (= foreign_table)
1708 * @return array A record row from the database post-processed by t3lib_transferData
1709 */
1710 function getNewRecord($pid, $table) {
1711 $rec = $this->getRecord($pid, $table, $pid, 'new');
1712 $rec['uid'] = uniqid('NEW');
1713 $rec['pid'] = $this->getNewRecordPid($table, $pid);
1714 return $rec;
1715 }
1716
1717 /*******************************************************
1718 *
1719 * Structure stack for handling inline objects/levels
1720 *
1721 *******************************************************/
1722
1723 /**
1724 * Add a new level on top of the structure stack. Other functions can access the
1725 * stack and determine, if there's possibly a endless loop.
1726 *
1727 * @param string $table The table name of the record
1728 * @param string $uid The uid of the record that embeds the inline data
1729 * @param string $field The field name which this element is supposed to edit
1730 * @param array $config The TCA-configuration of the inline field
1731 * @return void
1732 */
1733 function pushStructure($table, $uid, $field = '', $config = array()) {
1734 $this->inlineStructure['stable'][] = array(
1735 'table' => $table,
1736 'uid' => $uid,
1737 'field' => $field,
1738 'config' => $config,
1739 'localizationMode' => t3lib_BEfunc::getInlineLocalizationMode($table, $config),
1740 );
1741 $this->updateStructureNames();
1742 }
1743
1744 /**
1745 * Remove the item on top of the structure stack and return it.
1746 *
1747 * @return array The top item of the structure stack - array(<table>,<uid>,<field>,<config>)
1748 */
1749 function popStructure() {
1750 if (count($this->inlineStructure['stable'])) {
1751 $popItem = array_pop($this->inlineStructure['stable']);
1752 $this->updateStructureNames();
1753 }
1754 return $popItem;
1755 }
1756
1757 /**
1758 * For common use of DOM object-ids and form field names of a several inline-level,
1759 * these names/identifiers are preprocessed and set to $this->inlineNames.
1760 * This function is automatically called if a level is pushed to or removed from the
1761 * inline structure stack.
1762 *
1763 * @return void
1764 */
1765 function updateStructureNames() {
1766 $current = $this->getStructureLevel(-1);
1767 // If there are still more inline levels available
1768 if ($current !== FALSE) {
1769 $this->inlineNames = array(
1770 'form' => $this->prependFormFieldNames . $this->getStructureItemName($current, self::Disposal_AttributeName),
1771 'object' => $this->prependNaming . self::Structure_Separator . $this->inlineFirstPid . self::Structure_Separator . $this->getStructurePath(),
1772 );
1773 // If there are no more inline levels available
1774 } else {
1775 $this->inlineNames = array();
1776 }
1777 }
1778
1779 /**
1780 * Create a name/id for usage in HTML output of a level of the structure stack to be used in form names.
1781 *
1782 * @param array $levelData Array of a level of the structure stack (containing the keys table, uid and field)
1783 * @param string $disposal How the structure name is used (e.g. as <div id="..."> or <input name="..." />)
1784 * @return string The name/id of that level, to be used for HTML output
1785 */
1786 function getStructureItemName($levelData, $disposal = self::Disposal_AttributeId) {
1787 if (is_array($levelData)) {
1788 $parts = array($levelData['table'], $levelData['uid']);
1789 if (isset($levelData['field'])) {
1790 $parts[] = $levelData['field'];
1791 }
1792
1793 // Use in name attributes:
1794 if ($disposal === self::Disposal_AttributeName) {
1795 $name = '[' . implode('][', $parts) . ']';
1796 // Use in id attributes:
1797 } else {
1798 $name = implode(self::Structure_Separator, $parts);
1799 }
1800 }
1801 return $name;
1802 }
1803
1804 /**
1805 * Get a level from the stack and return the data.
1806 * If the $level value is negative, this function works top-down,
1807 * if the $level value is positive, this function works bottom-up.
1808 *
1809 * @param integer $level Which level to return
1810 * @return array The item of the stack at the requested level
1811 */
1812 function getStructureLevel($level) {
1813 $inlineStructureCount = count($this->inlineStructure['stable']);
1814 if ($level < 0) {
1815 $level = $inlineStructureCount + $level;
1816 }
1817 if ($level >= 0 && $level < $inlineStructureCount) {
1818 return $this->inlineStructure['stable'][$level];
1819 }
1820 else
1821 {
1822 return FALSE;
1823 }
1824 }
1825
1826 /**
1827 * Get the identifiers of a given depth of level, from the top of the stack to the bottom.
1828 * An identifier looks like "<table>-<uid>-<field>".
1829 *
1830 * @param integer $structureDepth How much levels to output, beginning from the top of the stack
1831 * @return string The path of identifiers
1832 */
1833 function getStructurePath($structureDepth = -1) {
1834 $structureLevels = array();
1835 $structureCount = count($this->inlineStructure['stable']);
1836
1837 if ($structureDepth < 0 || $structureDepth > $structureCount) {
1838 $structureDepth = $structureCount;
1839 }
1840
1841 for ($i = 1; $i <= $structureDepth; $i++) {
1842 array_unshift(
1843 $structureLevels,
1844 $this->getStructureItemName(
1845 $this->getStructureLevel(-$i),
1846 self::Disposal_AttributeId
1847 )
1848 );
1849 }
1850
1851 return implode(self::Structure_Separator, $structureLevels);
1852 }
1853
1854 /**
1855 * Convert the DOM object-id of an inline container to an array.
1856 * The object-id could look like 'data-parentPageId-tx_mmftest_company-1-employees'.
1857 * The result is written to $this->inlineStructure.
1858 * There are two keys:
1859 * - 'stable': Containing full qualified identifiers (table, uid and field)
1860 * - 'unstable': Containting partly filled data (e.g. only table and possibly field)
1861 *
1862 * @param string $domObjectId The DOM object-id
1863 * @param boolean $loadConfig Load the TCA configuration for that level (default: TRUE)
1864 * @return void
1865 */
1866 function parseStructureString($string, $loadConfig = TRUE) {
1867 $unstable = array();
1868 $vector = array('table', 'uid', 'field');
1869 $pattern = '/^' . $this->prependNaming . self::Structure_Separator . '(.+?)' . self::Structure_Separator . '(.+)$/';
1870 if (preg_match($pattern, $string, $match)) {
1871 $this->inlineFirstPid = $match[1];
1872 $parts = explode(self::Structure_Separator, $match[2]);
1873 $partsCnt = count($parts);
1874 for ($i = 0; $i < $partsCnt; $i++) {
1875 if ($i > 0 && $i % 3 == 0) {
1876 // Load the TCA configuration of the table field and store it in the stack
1877 if ($loadConfig) {
1878 t3lib_div::loadTCA($unstable['table']);
1879 $unstable['config'] = $GLOBALS['TCA'][$unstable['table']]['columns'][$unstable['field']]['config'];
1880 // Fetch TSconfig:
1881 $TSconfig = $this->fObj->setTSconfig(
1882 $unstable['table'],
1883 array('uid' => $unstable['uid'], 'pid' => $this->inlineFirstPid),
1884 $unstable['field']
1885 );
1886 // Override TCA field config by TSconfig:
1887 if (!$TSconfig['disabled']) {
1888 $unstable['config'] = $this->fObj->overrideFieldConf($unstable['config'], $TSconfig);
1889 }
1890 $unstable['localizationMode'] = t3lib_BEfunc::getInlineLocalizationMode($unstable['table'], $unstable['config']);
1891 }
1892 $this->inlineStructure['stable'][] = $unstable;
1893 $unstable = array();
1894 }
1895 $unstable[$vector[$i % 3]] = $parts[$i];
1896 }
1897 $this->updateStructureNames();
1898 if (count($unstable)) {
1899 $this->inlineStructure['unstable'] = $unstable;
1900 }
1901 }
1902 }
1903
1904 /*******************************************************
1905 *
1906 * Helper functions
1907 *
1908 *******************************************************/
1909
1910 /**
1911 * Does some checks on the TCA configuration of the inline field to render.
1912 *
1913 * @param array $config Reference to the TCA field configuration
1914 * @param string $table The table name of the record
1915 * @param string $field The field name which this element is supposed to edit
1916 * @param array $row The record data array of the parent
1917 * @return boolean If critical configuration errors were found, FALSE is returned
1918 */
1919 function checkConfiguration(&$config) {
1920 $foreign_table = $config['foreign_table'];
1921
1922 // An inline field must have a foreign_table, if not, stop all further inline actions for this field:
1923 if (!$foreign_table || !is_array($GLOBALS['TCA'][$foreign_table])) {
1924 return FALSE;
1925 }
1926 // Init appearance if not set:
1927 if (!isset($config['appearance']) || !is_array($config['appearance'])) {
1928 $config['appearance'] = array();
1929 }
1930 // Set the position/appearance of the "Create new record" link:
1931 if (isset($config['foreign_selector']) && $config['foreign_selector'] && (!isset($config['appearance']['useCombination']) || !$config['appearance']['useCombination'])) {
1932 $config['appearance']['levelLinksPosition'] = 'none';
1933 } elseif (!isset($config['appearance']['levelLinksPosition']) || !in_array($config['appearance']['levelLinksPosition'], array('top', 'bottom', 'both', 'none'))) {
1934 $config['appearance']['levelLinksPosition'] = 'top';
1935 }
1936 // Defines which controls should be shown in header of each record:
1937 $enabledControls = array(
1938 'info' => TRUE,
1939 'new' => TRUE,
1940 'dragdrop' => TRUE,
1941 'sort' => TRUE,
1942 'hide' => TRUE,
1943 'delete' => TRUE,
1944 'localize' => TRUE,
1945 );
1946 if (isset($config['appearance']['enabledControls']) && is_array($config['appearance']['enabledControls'])) {
1947 $config['appearance']['enabledControls'] = array_merge($enabledControls, $config['appearance']['enabledControls']);
1948 } else {
1949 $config['appearance']['enabledControls'] = $enabledControls;
1950 }
1951
1952 return TRUE;
1953 }
1954
1955 /**
1956 * Checks the page access rights (Code for access check mostly taken from alt_doc.php)
1957 * as well as the table access rights of the user.
1958 *
1959 * @param string $cmd The command that sould be performed ('new' or 'edit')
1960 * @param string $table The table to check access for
1961 * @param string $theUid The record uid of the table
1962 * @return boolean Returns TRUE is the user has access, or FALSE if not
1963 */
1964 function checkAccess($cmd, $table, $theUid) {
1965 // 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...)
1966 // First, resetting flags.
1967 $hasAccess = 0;
1968 $deniedAccessReason = '';
1969
1970 // Admin users always have acces:
1971 if ($GLOBALS['BE_USER']->isAdmin()) {
1972 return TRUE;
1973 }
1974 // If the command is to create a NEW record...:
1975 if ($cmd == 'new') {
1976 // If the pid is numerical, check if it's possible to write to this page:
1977 if (t3lib_utility_Math::canBeInterpretedAsInteger($this->inlineFirstPid)) {
1978 $calcPRec = t3lib_BEfunc::getRecord('pages', $this->inlineFirstPid);
1979 if (!is_array($calcPRec)) {
1980 return FALSE;
1981 }
1982 // Permissions for the parent page
1983 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
1984 // If pages:
1985 if ($table == 'pages') {
1986 // Are we allowed to create new subpages?
1987 $hasAccess = $CALC_PERMS & 8 ? 1 : 0;
1988 } else {
1989 // Are we allowed to edit content on this page?
1990 $hasAccess = $CALC_PERMS & 16 ? 1 : 0;
1991 }
1992 // If the pid is a NEW... value, the access will be checked on creating the page:
1993 // (if the page with the same NEW... value could be created in TCEmain, this child record can neither)
1994 } else {
1995 $hasAccess = 1;
1996 }
1997 } else { // Edit:
1998 $calcPRec = t3lib_BEfunc::getRecord($table, $theUid);
1999 t3lib_BEfunc::fixVersioningPid($table, $calcPRec);
2000 if (is_array($calcPRec)) {
2001 // If pages:
2002 if ($table == 'pages') {
2003 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
2004 $hasAccess = $CALC_PERMS & 2 ? 1 : 0;
2005 } else {
2006 // Fetching pid-record first.
2007 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms(t3lib_BEfunc::getRecord('pages', $calcPRec['pid']));
2008 $hasAccess = $CALC_PERMS & 16 ? 1 : 0;
2009 }
2010
2011 // Check internals regarding access:
2012 if ($hasAccess) {
2013 $hasAccess = $GLOBALS['BE_USER']->recordEditAccessInternals($table, $calcPRec);
2014 }
2015 }
2016 }
2017
2018 if (!$GLOBALS['BE_USER']->check('tables_modify', $table)) {
2019 $hasAccess = 0;
2020 }
2021
2022 if (!$hasAccess) {
2023 $deniedAccessReason = $GLOBALS['BE_USER']->errorMsg;
2024 if ($deniedAccessReason) {
2025 debug($deniedAccessReason);
2026 }
2027 }
2028
2029 return $hasAccess ? TRUE : FALSE;
2030 }
2031
2032 /**
2033 * Check the keys and values in the $compare array against the ['config'] part of the top level of the stack.
2034 * A boolean value is return depending on how the comparison was successful.
2035 *
2036 * @param array $compare Keys and values to compare to the ['config'] part of the top level of the stack
2037 * @return boolean Whether the comparison was successful
2038 * @see arrayCompareComplex
2039 */
2040 function compareStructureConfiguration($compare) {
2041 $level = $this->getStructureLevel(-1);
2042 $result = $this->arrayCompareComplex($level, $compare);
2043
2044 return $result;
2045 }
2046
2047 /**
2048 * Normalize a relation "uid" published by transferData, like "1|Company%201"
2049 *
2050 * @param string $string A transferData reference string, containing the uid
2051 * @return string The normalized uid
2052 */
2053 function normalizeUid($string) {
2054 $parts = explode('|', $string);
2055 return $parts[0];
2056 }
2057
2058 /**
2059 * Wrap the HTML code of a section with a table tag.
2060 *
2061 * @param string $section The HTML code to be wrapped
2062 * @param array $styleAttrs Attributes for the style argument in the table tag
2063 * @param array $tableAttrs Attributes for the table tag (like width, border, etc.)
2064 * @return string The wrapped HTML code
2065 */
2066 function wrapFormsSection($section, $styleAttrs = array(), $tableAttrs = array()) {
2067 $style = '';
2068 $table = '';
2069 if (!$styleAttrs['margin-right']) {
2070 $styleAttrs['margin-right'] = $this->inlineStyles['margin-right'] . 'px';
2071 }
2072
2073 foreach ($styleAttrs as $key => $value) {
2074 $style .= ($style ? ' ' : '') . $key . ': ' . htmlspecialchars($value) . '; ';
2075 }
2076 if ($style) {
2077 $style = ' style="' . $style . '"';
2078 }
2079
2080 if (!$tableAttrs['background'] && $this->fObj->borderStyle[2]) {
2081 $tableAttrs['background'] = $this->backPath . $this->borderStyle[2];
2082 }
2083 if (!$tableAttrs['cellspacing']) {
2084 $tableAttrs['cellspacing'] = '0';
2085 }
2086 if (!$tableAttrs['cellpadding']) {
2087 $tableAttrs['cellpadding'] = '0';
2088 }
2089 if (!$tableAttrs['border']) {
2090 $tableAttrs['border'] = '0';
2091 }
2092 if (!$tableAttrs['width']) {
2093 $tableAttrs['width'] = '100%';
2094 }
2095 if (!$tableAttrs['class'] && $this->borderStyle[3]) {
2096 $tableAttrs['class'] = $this->borderStyle[3];
2097 }
2098
2099 foreach ($tableAttrs as $key => $value) {
2100 $table .= ($table ? ' ' : '') . $key . '="' . htmlspecialchars($value) . '"';
2101 }
2102
2103 $out = '<table ' . $table . $style . '>' . $section . '</table>';
2104 return $out;
2105 }
2106
2107 /**
2108 * Checks if the $table is the child of a inline type AND the $field is the label field of this table.
2109 * This function is used to dynamically update the label while editing. This has no effect on labels,
2110 * that were processed by a TCEmain-hook on saving.
2111 *
2112 * @param string $table The table to check
2113 * @param string $field The field on this table to check
2114 * @return boolean Is inline child and field is responsible for the label
2115 */
2116 function isInlineChildAndLabelField($table, $field) {
2117 $level = $this->getStructureLevel(-1);
2118 if ($level['config']['foreign_label']) {
2119 $label = $level['config']['foreign_label'];
2120 }
2121 else
2122 {
2123 $label = $GLOBALS['TCA'][$table]['ctrl']['label'];
2124 }
2125 return $level['config']['foreign_table'] === $table && $label == $field ? TRUE : FALSE;
2126 }
2127
2128 /**
2129 * Get the depth of the stable structure stack.
2130 * (count($this->inlineStructure['stable'])
2131 *
2132 * @return integer The depth of the structure stack
2133 */
2134 function getStructureDepth() {
2135 return count($this->inlineStructure['stable']);
2136 }
2137
2138 /**
2139 * Handles complex comparison requests on an array.
2140 * A request could look like the following:
2141 *
2142 * $searchArray = array(
2143 * '%AND' => array(
2144 * 'key1' => 'value1',
2145 * 'key2' => 'value2',
2146 * '%OR' => array(
2147 * 'subarray' => array(
2148 * 'subkey' => 'subvalue'
2149 * ),
2150 * 'key3' => 'value3',
2151 * 'key4' => 'value4'
2152 * )
2153 * )
2154 * );
2155 *
2156 * It is possible to use the array keys '%AND.1', '%AND.2', etc. to prevent
2157 * overwriting the sub-array. It could be neccessary, if you use complex comparisons.
2158 *
2159 * The example above means, key1 *AND* key2 (and their values) have to match with
2160 * the $subjectArray and additional one *OR* key3 or key4 have to meet the same
2161 * condition.
2162 * It is also possible to compare parts of a sub-array (e.g. "subarray"), so this
2163 * function recurses down one level in that sub-array.
2164 *
2165 * @param array $subjectArray The array to search in
2166 * @param array $searchArray The array with keys and values to search for
2167 * @param string $type Use '%AND' or '%OR' for comparision
2168 * @return boolean The result of the comparison
2169 */
2170 function arrayCompareComplex($subjectArray, $searchArray, $type = '') {
2171 $localMatches = 0;
2172 $localEntries = 0;
2173
2174 if (is_array($searchArray) && count($searchArray)) {
2175 // If no type was passed, try to determine
2176 if (!$type) {
2177 reset($searchArray);
2178 $type = key($searchArray);
2179 $searchArray = current($searchArray);
2180 }
2181
2182 // We use '%AND' and '%OR' in uppercase
2183 $type = strtoupper($type);
2184
2185 // Split regular elements from sub elements
2186 foreach ($searchArray as $key => $value) {
2187 $localEntries++;
2188
2189 // Process a sub-group of OR-conditions
2190 if ($key == '%OR') {
2191 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%OR') ? 1 : 0;
2192 // Process a sub-group of AND-conditions
2193 } elseif ($key == '%AND') {
2194 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%AND') ? 1 : 0;
2195 // A part of an associative array should be compared, so step down in the array hierarchy
2196 } elseif (is_array($value) && $this->isAssociativeArray($searchArray)) {
2197 $localMatches += $this->arrayCompareComplex($subjectArray[$key], $value, $type) ? 1 : 0;
2198 // It is a normal array that is only used for grouping and indexing
2199 } elseif (is_array($value)) {
2200 $localMatches += $this->arrayCompareComplex($subjectArray, $value, $type) ? 1 : 0;
2201 // Directly compare a value
2202 } else {
2203 if (isset($subjectArray[$key]) && isset($value)) {
2204 // Boolean match:
2205 if (is_bool($value)) {
2206 $localMatches += (!($subjectArray[$key] xor $value) ? 1 : 0);
2207 // Value match for numbers:
2208 } elseif (is_numeric($subjectArray[$key]) && is_numeric($value)) {
2209 $localMatches += ($subjectArray[$key] == $value ? 1 : 0);
2210 // Value and type match:
2211 } else {
2212 $localMatches += ($subjectArray[$key] === $value ? 1 : 0);
2213 }
2214 }
2215 }
2216
2217 // If one or more matches are required ('OR'), return TRUE after the first successful match
2218 if ($type == '%OR' && $localMatches > 0) {
2219 return TRUE;
2220 }
2221 // If all matches are required ('AND') and we have no result after the first run, return FALSE
2222 if ($type == '%AND' && $localMatches == 0) {
2223 return FALSE;
2224 }
2225 }
2226 }
2227
2228 // Return the result for '%AND' (if nothing was checked, TRUE is returned)
2229 return $localEntries == $localMatches ? TRUE : FALSE;
2230 }
2231
2232 /**
2233 * Checks whether an object is an associative array.
2234 *
2235 * @param mixed $object The object to be checked
2236 * @return boolean Returns TRUE, if the object is an associative array
2237 */
2238 function isAssociativeArray($object) {
2239 return is_array($object) && count($object) && (array_keys($object) !== range(0, sizeof($object) - 1))
2240 ? TRUE
2241 : FALSE;
2242 }
2243
2244 /**
2245 * Remove an element from an array.
2246 *
2247 * @param mixed $needle The element to be removed.
2248 * @param array $haystack The array the element should be removed from.
2249 * @param mixed $strict Search elements strictly.
2250 * @return array The array $haystack without the $needle
2251 */
2252 function removeFromArray($needle, $haystack, $strict = NULL) {
2253 $pos = array_search($needle, $haystack, $strict);
2254 if ($pos !== FALSE) {
2255 unset($haystack[$pos]);
2256 }
2257 return $haystack;
2258 }
2259
2260 /**
2261 * Makes a flat array from the $possibleRecords array.
2262 * The key of the flat array is the value of the record,
2263 * the value of the flat array is the label of the record.
2264 *
2265 * @param array $possibleRecords The possibleRecords array (for select fields)
2266 * @return mixed A flat array with key=uid, value=label; if $possibleRecords isn't an array, FALSE is returned.
2267 */
2268 function getPossibleRecordsFlat($possibleRecords) {
2269 $flat = FALSE;
2270 if (is_array($possibleRecords)) {
2271 $flat = array();
2272 foreach ($possibleRecords as $record) $flat[$record[1]] = $record[0];
2273 }
2274 return $flat;
2275 }
2276
2277 /**
2278 * Determine the configuration and the type of a record selector.
2279 *
2280 * @param array $conf TCA configuration of the parent(!) field
2281 * @return array Associative array with the keys 'PA' and 'type', both are FALSE if the selector was not valid.
2282 */
2283 function getPossibleRecordsSelectorConfig($conf, $field = '') {
2284 $foreign_table = $conf['foreign_table'];
2285 $foreign_selector = $conf['foreign_selector'];
2286
2287 $PA = FALSE;
2288 $type = FALSE;
2289 $table = FALSE;
2290 $selector = FALSE;
2291
2292 if ($field) {
2293 $PA = array();
2294 $PA['fieldConf'] = $GLOBALS['TCA'][$foreign_table]['columns'][$field];
2295
2296 if ($PA['fieldConf'] && $conf['foreign_selector_fieldTcaOverride']) {
2297 $PA['fieldConf'] = t3lib_div::array_merge_recursive_overrule($PA['fieldConf'], $conf['foreign_selector_fieldTcaOverride']);
2298 }
2299
2300 $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
2301 $PA['fieldTSConfig'] = $this->fObj->setTSconfig($foreign_table, array(), $field);
2302 $config = $PA['fieldConf']['config'];
2303 // Determine type of Selector:
2304 $type = $this->getPossibleRecordsSelectorType($config);
2305 // Return table on this level:
2306 $table = $type == 'select' ? $config['foreign_table'] : $config['allowed'];
2307 // Return type of the selector if foreign_selector is defined and points to the same field as in $field:
2308 if ($foreign_selector && $foreign_selector == $field && $type) {
2309 $selector = $type;
2310 }
2311 }
2312
2313 return array(
2314 'PA' => $PA,
2315 'type' => $type,
2316 'table' => $table,
2317 'selector' => $selector,
2318 );
2319 }
2320
2321
2322 /**
2323 * Determine the type of a record selector, e.g. select or group/db.
2324 *
2325 * @param array $config TCE configuration of the selector
2326 * @return mixed The type of the selector, 'select' or 'groupdb' - FALSE not valid
2327 */
2328 function getPossibleRecordsSelectorType($config) {
2329 $type = FALSE;
2330 if ($config['type'] == 'select') {
2331 $type = 'select';
2332 } elseif ($config['type'] == 'group' && $config['internal_type'] == 'db') {
2333 $type = 'groupdb';
2334 }
2335 return $type;
2336 }
2337
2338 /**
2339 * Check, if a field should be skipped, that was defined to be handled as foreign_field or foreign_sortby of
2340 * the parent record of the "inline"-type - if so, we have to skip this field - the rendering is done via "inline" as hidden field
2341 *
2342 * @param string $table The table name
2343 * @param string $field The field name
2344 * @param array $row The record row from the database
2345 * @param array $config TCA configuration of the field
2346 * @return boolean Determines whether the field should be skipped.
2347 */
2348 function skipField($table, $field, $row, $config) {
2349 $skipThisField = FALSE;
2350
2351 if ($this->getStructureDepth()) {
2352 $searchArray = array(
2353 '%OR' => array(
2354 'config' => array(
2355 0 => array(
2356 '%AND' => array(
2357 'foreign_table' => $table,
2358 '%OR' => array(
2359 '%AND' => array(
2360 'appearance' => array('useCombination' => TRUE),
2361 'foreign_selector' => $field,
2362 ),
2363 'MM' => $config['MM']
2364 ),
2365 ),
2366 ),
2367 1 => array(
2368 '%AND' => array(
2369 'foreign_table' => $config['foreign_table'],
2370 'foreign_selector' => $config['foreign_field'],
2371 ),
2372 ),
2373 ),
2374 ),
2375 );
2376
2377 // Get the parent record from structure stack
2378 $level = $this->getStructureLevel(-1);
2379
2380 // If we have symmetric fields, check on which side we are and hide fields, that are set automatically:
2381 if (t3lib_loadDBGroup::isOnSymmetricSide($level['uid'], $level['config'], $row)) {
2382 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_field'] = $field;
2383 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_sortby'] = $field;
2384 // Hide fields, that are set automatically:
2385 } else {
2386 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_field'] = $field;
2387 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_sortby'] = $field;
2388 }
2389
2390 $skipThisField = $this->compareStructureConfiguration($searchArray, TRUE);
2391 }
2392
2393 return $skipThisField;
2394 }
2395
2396 /**
2397 * Checks if a uid of a child table is in the inline view settings.
2398 *
2399 * @param string $table Name of the child table
2400 * @param integer $uid uid of the the child record
2401 * @return boolean TRUE=expand, FALSE=collapse
2402 */
2403 function getExpandedCollapsedState($table, $uid) {
2404 if (isset($this->inlineView[$table]) && is_array($this->inlineView[$table])) {
2405 if (in_array($uid, $this->inlineView[$table]) !== FALSE) {
2406 return TRUE;
2407 }
2408 }
2409 return FALSE;
2410 }
2411
2412 /**
2413 * Update expanded/collapsed states on new inline records if any.
2414 *
2415 * @param array $uc The uc array to be processed and saved (by reference)
2416 * @param t3lib_TCEmain $tce Instance of TCEmain that saved data before
2417 * @return void
2418 */
2419 function updateInlineView(&$uc, $tce) {
2420 if (isset($uc['inlineView']) && is_array($uc['inlineView'])) {
2421 $inlineView = (array) unserialize($GLOBALS['BE_USER']->uc['inlineView']);
2422
2423 foreach ($uc['inlineView'] as $topTable => $topRecords) {
2424 foreach ($topRecords as $topUid => $childElements) {
2425 foreach ($childElements as $childTable => $childRecords) {
2426 $uids = array_keys($tce->substNEWwithIDs_table, $childTable);
2427 if (count($uids)) {
2428 $newExpandedChildren = array();
2429 foreach ($childRecords as $childUid => $state) {
2430 if ($state && in_array($childUid, $uids)) {
2431 $newChildUid = $tce->substNEWwithIDs[$childUid];
2432 $newExpandedChildren[] = $newChildUid;
2433 }
2434 }
2435 // Add new expanded child records to UC (if any):
2436 if (count($newExpandedChildren)) {
2437 $inlineViewCurrent =& $inlineView[$topTable][$topUid][$childTable];
2438 if (is_array($inlineViewCurrent)) {
2439 $inlineViewCurrent = array_unique(array_merge($inlineViewCurrent, $newExpandedChildren));
2440 } else {
2441 $inlineViewCurrent = $newExpandedChildren;
2442 }
2443 }
2444 }
2445 }
2446 }
2447 }
2448
2449 $GLOBALS['BE_USER']->uc['inlineView'] = serialize($inlineView);
2450 $GLOBALS['BE_USER']->writeUC();
2451 }
2452 }
2453
2454 /**
2455 * Returns the the margin in pixels, that is used for each new inline level.
2456 *
2457 * @return integer A pixel value for the margin of each new inline level.
2458 */
2459 function getLevelMargin() {
2460 $margin = ($this->inlineStyles['margin-right'] + 1) * 2;
2461 return $margin;
2462 }
2463
2464 /**
2465 * Parses the HTML tags that would have been inserted to the <head> of a HTML document and returns the found tags as multidimensional array.
2466 *
2467 * @return array The parsed tags with their attributes and innerHTML parts
2468 */
2469 protected function getHeadTags() {
2470 $headTags = array();
2471 $headDataRaw = $this->fObj->JStop() . $this->getJavaScriptAndStyleSheetsOfPageRenderer();
2472
2473 if ($headDataRaw) {
2474 // Create instance of the HTML parser:
2475 $parseObj = t3lib_div::makeInstance('t3lib_parsehtml');
2476 // Removes script wraps:
2477 $headDataRaw = str_replace(array('/*<![CDATA[*/', '/*]]>*/'), '', $headDataRaw);
2478 // Removes leading spaces of a multiline string:
2479 $headDataRaw = trim(preg_replace('/(^|\r|\n)( |\t)+/', '$1', $headDataRaw));
2480 // Get script and link tags:
2481 $tags = array_merge(
2482 $parseObj->getAllParts($parseObj->splitTags('link', $headDataRaw)),
2483 $parseObj->getAllParts($parseObj->splitIntoBlock('script', $headDataRaw))
2484 );
2485
2486 foreach ($tags as $tagData) {
2487 $tagAttributes = $parseObj->get_tag_attributes($parseObj->getFirstTag($tagData), TRUE);
2488 $headTags[] = array(
2489 'name' => $parseObj->getFirstTagName($tagData),
2490 'attributes' => $tagAttributes[0],
2491 'innerHTML' => $parseObj->removeFirstAndLastTag($tagData),
2492 );
2493 }
2494 }
2495
2496 return $headTags;
2497 }
2498
2499 /**
2500 * Gets the JavaScript of the pageRenderer.
2501 * This can be used to extract newly added files which have been added
2502 * during an AJAX request. Due to the spread possibilities of the pageRenderer
2503 * to add JavaScript rendering and extracting seems to be the easiest way.
2504 *
2505 * @return string
2506 */
2507 protected function getJavaScriptAndStyleSheetsOfPageRenderer() {
2508 /** @var $pageRenderer t3lib_PageRenderer */
2509 $pageRenderer = clone $GLOBALS['SOBE']->doc->getPageRenderer();
2510
2511 $pageRenderer->setTemplateFile(TYPO3_mainDir . 'templates/helper_javascript_css.html');
2512 $javaScriptAndStyleSheets = $pageRenderer->render();
2513
2514 return $javaScriptAndStyleSheets;
2515 }
2516
2517 /**
2518 * Wraps a text with an anchor and returns the HTML representation.
2519 *
2520 * @param string $text The text to be wrapped by an anchor
2521 * @param string $link The link to be used in the anchor
2522 * @param array $attributes Array of attributes to be used in the anchor
2523 * @return string The wrapped texted as HTML representation
2524 */
2525 protected function wrapWithAnchor($text, $link, $attributes = array()) {
2526 $link = trim($link);
2527 $result = '<a href="' . ($link ? $link : '#') . '"';
2528 foreach ($attributes as $key => $value) {
2529 $result .= ' ' . $key . '="' . htmlspecialchars(trim($value)) . '"';
2530 }
2531 $result .= '>' . $text . '</a>';
2532 return $result;
2533 }
2534 }
2535
2536 ?>