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