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