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