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