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