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