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