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