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