Fixed bug #5913: RTEhtmlarea not correctly displayed in IRRE child form-fields and...
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_tceforms_inline.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2006 Oliver Hader <oh@inpublica.de>
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * The Inline-Relational-Record-Editing (IRRE) functions as part of the TCEforms.
29 *
30 * $Id$
31 *
32 * @author Oliver Hader <oh@inpublica.de>
33 */
34 /**
35 * [CLASS/FUNCTION INDEX of SCRIPT]
36 *
37 *
38 *
39 * 88: class t3lib_TCEforms_inline
40 * 109: function init(&$tceForms)
41 * 127: function getSingleField_typeInline($table,$field,$row,&$PA)
42 *
43 * SECTION: Regular rendering of forms, fields, etc.
44 * 263: function renderForeignRecord($parentUid, $rec, $config = array())
45 * 319: function renderForeignRecordHeader($parentUid, $foreign_table,$rec,$config = array())
46 * 375: function renderForeignRecordHeaderControl($table,$row,$config = array())
47 * 506: function renderCombinationTable(&$rec, $appendFormFieldNames, $config = array())
48 * 560: function renderPossibleRecordsSelector($selItems, $conf, $uniqueIds=array())
49 * 627: function addJavaScript()
50 * 643: function addJavaScriptSortable($objectId)
51 *
52 * SECTION: Handling of AJAX calls
53 * 665: function createNewRecord($domObjectId, $foreignUid = 0)
54 * 755: function getJSON($jsonArray)
55 * 770: function getNewRecordLink($objectPrefix, $conf = array())
56 *
57 * SECTION: Get data from database and handle relations
58 * 807: function getRelatedRecords($table,$field,$row,&$PA,$config)
59 * 839: function getPossibleRecords($table,$field,$row,$conf,$checkForConfField='foreign_selector')
60 * 885: function getUniqueIds($records, $conf=array())
61 * 905: function getRecord($pid, $table, $uid, $cmd='')
62 * 929: function getNewRecord($pid, $table)
63 *
64 * SECTION: Structure stack for handling inline objects/levels
65 * 951: function pushStructure($table, $uid, $field = '', $config = array())
66 * 967: function popStructure()
67 * 984: function updateStructureNames()
68 * 1000: function getStructureItemName($levelData)
69 * 1015: function getStructureLevel($level)
70 * 1032: function getStructurePath($structureDepth = -1)
71 * 1057: function parseStructureString($string, $loadConfig = false)
72 *
73 * SECTION: Helper functions
74 * 1098: function checkConfiguration(&$config)
75 * 1123: function checkAccess($cmd, $table, $theUid)
76 * 1185: function compareStructureConfiguration($compare)
77 * 1199: function normalizeUid($string)
78 * 1213: function wrapFormsSection($section, $styleAttrs = array(), $tableAttrs = array())
79 * 1242: function isInlineChildAndLabelField($table, $field)
80 * 1258: function getStructureDepth()
81 * 1295: function arrayCompareComplex($subjectArray, $searchArray, $type = '')
82 * 1349: function isAssociativeArray($object)
83 * 1364: function getPossibleRecordsFlat($possibleRecords)
84 * 1383: function skipField($table, $field, $row, $config)
85 *
86 * TOTAL FUNCTIONS: 35
87 * (This index is automatically created/updated by the extension "extdeveval")
88 *
89 */
90 class t3lib_TCEforms_inline {
91 var $fObj; // Reference to the calling TCEforms instance
92 var $backPath; // Reference to $fObj->backPath
93
94 var $isAjaxCall = false; // Indicates if a field is rendered upon an AJAX call
95 var $inlineStructure = array(); // the structure/hierarchy where working in, e.g. cascading inline tables
96 var $inlineFirstPid; // the first call of an inline type appeared on this page (pid of record)
97 var $inlineNames = array(); // keys: form, object -> hold the name/id for each of them
98 var $inlineData = array(); // inline data array used for JSON output
99 var $inlineView = array(); // expanded/collapsed states for the current BE user
100 var $inlineCount = 0; // count the number of inline types used
101 var $inlineStyles = array();
102
103 var $prependNaming = 'data'; // how the $this->fObj->prependFormFieldNames should be set ('data' is default)
104 var $prependFormFieldNames; // reference to $this->fObj->prependFormFieldNames
105 var $prependCmdFieldNames; // reference to $this->fObj->prependCmdFieldNames
106
107
108 /**
109 * Intialize an instance of t3lib_TCEforms_inline
110 *
111 * @param object $tceForms: Reference to an TCEforms instance
112 * @return void
113 */
114 function init(&$tceForms) {
115 $this->fObj =& $tceForms;
116 $this->backPath =& $tceForms->backPath;
117 $this->prependFormFieldNames =& $this->fObj->prependFormFieldNames;
118 $this->prependCmdFieldNames =& $this->fObj->prependCmdFieldNames;
119 $this->inlineStyles['margin-right'] = '5';
120 }
121
122
123 /**
124 * Generation of TCEform elements of the type "inline"
125 * This will render inline-relational-record sets. Relations.
126 *
127 * @param string $table: The table name of the record
128 * @param string $field: The field name which this element is supposed to edit
129 * @param array $row: The record data array where the value(s) for the field can be found
130 * @param array $PA: An array with additional configuration options.
131 * @return string The HTML code for the TCEform field
132 */
133 function getSingleField_typeInline($table,$field,$row,&$PA) {
134 // check the TCA configuration - if false is returned, something was wrong
135 if ($this->checkConfiguration($PA['fieldConf']['config']) === false) return false;
136
137 // count the number of processed inline elements
138 $this->inlineCount++;
139
140 // Init:
141 $config = $PA['fieldConf']['config'];
142 $foreign_table = $config['foreign_table'];
143 t3lib_div::loadTCA($foreign_table);
144
145 $minitems = t3lib_div::intInRange($config['minitems'],0);
146 $maxitems = t3lib_div::intInRange($config['maxitems'],0);
147 if (!$maxitems) $maxitems=100000;
148
149 // Register the required number of elements:
150 $this->fObj->requiredElements[$PA['itemFormElName']] = array($minitems,$maxitems,'imgName'=>$table.'_'.$row['uid'].'_'.$field);
151
152 // remember the page id (pid of record) where inline editing started first
153 // we need that pid for ajax calls, so that they would know where the action takes place on the page structure
154 if (!isset($this->inlineFirstPid)) {
155 // if this record is not new, try to fetch the inlineView states
156 // @TODO: Add checking/cleaning for unused tables, records, etc. to save space in uc-field
157 if (t3lib_div::testInt($row['uid'])) {
158 $inlineView = unserialize($GLOBALS['BE_USER']->uc['inlineView']);
159 $this->inlineView = $inlineView[$table][$row['uid']];
160 }
161 // if pid is negative, fetch the previous record and take its pid
162 if ($row['pid'] < 0) {
163 $prevRec = t3lib_BEfunc::getRecord($table, abs($row['pid']));
164 $this->inlineFirstPid = $prevRec['pid'];
165 // take the pid as it is
166 } else {
167 $this->inlineFirstPid = $row['pid'];
168 }
169 }
170 // add the current inline job to the structure stack
171 $this->pushStructure($table, $row['uid'], $field, $config);
172 // e.g. inline[<table>][<uid>][<field>]
173 $nameForm = $this->inlineNames['form'];
174 // e.g. inline[<pid>][<table1>][<uid1>][<field1>][<table2>][<uid2>][<field2>]
175 $nameObject = $this->inlineNames['object'];
176 // get the records related to this inline record
177 $recordList = $this->getRelatedRecords($table,$field,$row,$PA,$config);
178 // set the first and last record to the config array
179 $config['inline']['first'] = $recordList[0]['uid'];
180 $config['inline']['last'] = $recordList[count($recordList)-1]['uid'];
181
182 // Tell the browser what we have (using JSON later):
183 $top = $this->getStructureLevel(0);
184 $this->inlineData['config'][$nameObject] = array('table' => $foreign_table);
185 $this->inlineData['config'][$nameObject.'['.$foreign_table.']'] = array(
186 'min' => $minitems,
187 'max' => $maxitems,
188 'sortable' => $config['appearance']['useSortable'],
189 'top' => array(
190 'table' => $top['table'],
191 'uid' => $top['uid'],
192 ),
193 );
194 // Set a hint for nested IRRE and tab elements:
195 $this->inlineData['nested'][$nameObject] = $this->fObj->getDynNestedStack(false, $this->isAjaxCall);
196
197 // if relations are required to be unique, get the uids that have already been used on the foreign side of the relation
198 if ($config['foreign_unique']) {
199 // If uniqueness *and* selector are set, they should point to the same field - so, get the configuration of one:
200 $selConfig = $this->getPossibleRecordsSelectorConfig($config, $config['foreign_unique']);
201 // Get the used unique ids:
202 $uniqueIds = $this->getUniqueIds($recordList, $config, $selConfig['type']=='groupdb');
203 $possibleRecords = $this->getPossibleRecords($table,$field,$row,$config,'foreign_unique');
204 $uniqueMax = $config['appearance']['useCombination'] || $possibleRecords === false ? -1 : count($possibleRecords);
205 $this->inlineData['unique'][$nameObject.'['.$foreign_table.']'] = array(
206 'max' => $uniqueMax,
207 'used' => $uniqueIds,
208 'type' => $selConfig['type'],
209 'table' => $config['foreign_table'],
210 'elTable' => $selConfig['table'], // element/record table (one step down in hierarchy)
211 'field' => $config['foreign_unique'],
212 'selector' => $selConfig['selector'],
213 'possible' => $this->getPossibleRecordsFlat($possibleRecords),
214 );
215 }
216
217 // if it's required to select from possible child records (reusable children), add a selector box
218 if ($config['foreign_selector']) {
219 // if not already set by the foreign_unique, set the possibleRecords here and the uniqueIds to an empty array
220 if (!$config['foreign_unique']) {
221 $possibleRecords = $this->getPossibleRecords($table,$field,$row,$config);
222 $uniqueIds = array();
223 }
224 $selectorBox = $this->renderPossibleRecordsSelector($possibleRecords,$config,$uniqueIds);
225 $item .= $selectorBox;
226 }
227
228 // wrap all inline fields of a record with a <div> (like a container)
229 $item .= '<div id="'.$nameObject.'">';
230
231 // define how to show the "Create new record" link - if there are more than maxitems, hide it
232 if (count($recordList) >= $maxitems || ($uniqueMax > 0 && count($recordList) >= $uniqueMax)) {
233 $config['inline']['inlineNewButtonStyle'] = 'display: none;';
234 }
235 // add the "Create new record" link before all child records
236 if (in_array($config['appearance']['newRecordLinkPosition'], array('both', 'top'))) {
237 $item .= $this->getNewRecordLink($nameObject.'['.$foreign_table.']', $config);
238 }
239
240 $item .= '<div id="'.$nameObject.'_records">';
241 $relationList = array();
242 if (count($recordList)) {
243 foreach ($recordList as $rec) {
244 $item .= $this->renderForeignRecord($row['uid'],$rec,$config);
245 $relationList[] = $rec['uid'];
246 }
247 }
248 $item .= '</div>';
249
250 // add the "Create new record" link after all child records
251 if (in_array($config['appearance']['newRecordLinkPosition'], array('both', 'bottom'))) {
252 $item .= $this->getNewRecordLink($nameObject.'['.$foreign_table.']', $config);
253 }
254
255 // add Drag&Drop functions for sorting to TCEforms::$additionalJS_post
256 if (count($relationList) > 1 && $config['appearance']['useSortable'])
257 $this->addJavaScriptSortable($nameObject.'_records');
258 // publish the uids of the child records in the given order to the browser
259 $item .= '<input type="hidden" name="'.$nameForm.'" value="'.implode(',', $relationList).'" class="inlineRecord" />';
260 // close the wrap for all inline fields (container)
261 $item .= '</div>';
262
263 // on finishing this section, remove the last item from the structure stack
264 $this->popStructure();
265
266 // if this was the first call to the inline type, restore the values
267 if (!$this->getStructureDepth()) {
268 unset($this->inlineFirstPid);
269 }
270
271 return $item;
272 }
273
274
275 /*******************************************************
276 *
277 * Regular rendering of forms, fields, etc.
278 *
279 *******************************************************/
280
281
282 /**
283 * Render the form-fields of a related (foreign) record.
284 *
285 * @param string $parentUid: The uid of the parent (embedding) record (uid or NEW...)
286 * @param array $rec: The table record of the child/embedded table (normaly post-processed by t3lib_transferData)
287 * @param array $config: content of $PA['fieldConf']['config']
288 * @return string The HTML code for this "foreign record"
289 */
290 function renderForeignRecord($parentUid, $rec, $config = array()) {
291 $foreign_table = $config['foreign_table'];
292 $foreign_field = $config['foreign_field'];
293 $foreign_selector = $config['foreign_selector'];
294
295 // Send a mapping information to the browser via JSON:
296 // e.g. data[<curTable>][<curId>][<curField>] => data[<pid>][<parentTable>][<parentId>][<parentField>][<curTable>][<curId>][<curField>]
297 $this->inlineData['map'][$this->inlineNames['form']] = $this->inlineNames['object'];
298
299 // Set this variable if we handle a brand new unsaved record:
300 $isNewRecord = t3lib_div::testInt($rec['uid']) ? false : true;
301 // If there is a selector field, normalize it:
302 if ($foreign_selector) {
303 $rec[$foreign_selector] = $this->normalizeUid($rec[$foreign_selector]);
304 }
305
306 $hasAccess = $this->checkAccess($isNewRecord?'new':'edit', $foreign_table, $rec['uid']);
307
308 if(!$hasAccess) return false;
309
310 // Get the current naming scheme for DOM name/id attributes:
311 $nameObject = $this->inlineNames['object'];
312 $appendFormFieldNames = '['.$foreign_table.']['.$rec['uid'].']';
313 $formFieldNames = $nameObject.$appendFormFieldNames;
314 // Put the current level also to the dynNestedStack of TCEforms:
315 $this->fObj->pushToDynNestedStack('inline', $this->inlineNames['object'].$appendFormFieldNames);
316
317 $header = $this->renderForeignRecordHeader($parentUid, $foreign_table, $rec, $config);
318 $combination = $this->renderCombinationTable($rec, $appendFormFieldNames, $config);
319 $fields = $this->fObj->getMainFields($foreign_table,$rec);
320 $fields = $this->wrapFormsSection($fields);
321
322 if ($isNewRecord) {
323 // show this record expanded or collapsed
324 $isExpanded = is_array($config['appearance']) && $config['appearance']['collapseAll'] ? 1 : 0;
325 // get the top parent table
326 $top = $this->getStructureLevel(0);
327 $ucFieldName = 'uc['.$top['table'].']['.$top['uid'].']'.$appendFormFieldNames;
328 // set additional fields for processing for saving
329 $fields .= '<input type="hidden" name="'.$this->prependFormFieldNames.$appendFormFieldNames.'[pid]" value="'.$rec['pid'].'"/>';
330 $fields .= '<input type="hidden" name="'.$ucFieldName.'" value="'.$isExpanded.'" />';
331
332 } else {
333 // show this record expanded or collapsed
334 $isExpanded = $this->getExpandedCollapsedState($foreign_table, $rec['uid']);
335 // set additional field for processing for saving
336 $fields .= '<input type="hidden" name="'.$this->prependCmdFieldNames.$appendFormFieldNames.'[delete]" value="1" disabled="disabled" />';
337 }
338
339 // if this record should be shown collapsed
340 if (!$isExpanded) $appearanceStyleFields = ' style="display: none;"';
341
342 // set the record container with data for output
343 $out = '<div id="'.$formFieldNames.'_header">'.$header.'</div>';
344 $out .= '<div id="'.$formFieldNames.'_fields"'.$appearanceStyleFields.'>'.$fields.$combination.'</div>';
345 // wrap the header, fields and combination part of a child record with a div container
346 $out = '<div id="'.$formFieldNames.'_div"'.($isNewRecord ? ' class="inlineIsNewRecord"' : '').'>' . $out . '</div>';
347
348 // Remove the current level also from the dynNestedStack of TCEforms:
349 $this->fObj->popFromDynNestedStack();
350
351 return $out;
352 }
353
354
355 /**
356 * Renders the HTML header for a foreign record, such as the title, toggle-function, drag'n'drop, etc.
357 * Later on the command-icons are inserted here.
358 *
359 * @param string $parentUid: The uid of the parent (embedding) record (uid or NEW...)
360 * @param string $foreign_table: The foreign_table we create a header for
361 * @param array $rec: The current record of that foreign_table
362 * @param array $config: content of $PA['fieldConf']['config']
363 * @return string The HTML code of the header
364 */
365 function renderForeignRecordHeader($parentUid, $foreign_table, $rec, $config = array()) {
366 // Init:
367 $formFieldNames = $this->inlineNames['object'].'['.$foreign_table.']['.$rec['uid'].']';
368 $expandSingle = $config['appearance']['expandSingle'] ? 1 : 0;
369 $onClick = "return inline.expandCollapseRecord('".htmlspecialchars($formFieldNames)."', $expandSingle)";
370
371 // Pre-Processing:
372 $isOnSymmetricSide = t3lib_loadDBGroup::isOnSymmetricSide($parentUid, $config, $rec);
373 $hasForeignLabel = !$isOnSymmetricSide && $config['foreign_label'] ? true : false;
374 $hasSymmetricLabel = $isOnSymmetricSide && $config['symmetric_label'] ? true : false;
375 // Get the record title/label for a record:
376 // render using a self-defined user function
377 if ($GLOBALS['TCA'][$foreign_table]['ctrl']['label_userFunc']) {
378 $params = array(
379 'table' => $foreign_table,
380 'row' => $rec,
381 'title' => '',
382 'isOnSymmetricSide' => $isOnSymmetricSide
383 );
384 $null = null; // callUserFunction requires a third parameter, but we don't want to give $this as reference!
385 t3lib_div::callUserFunction($GLOBALS['TCA'][$foreign_table]['ctrl']['label_userFunc'], $params, $null);
386 $recTitle = $params['title'];
387 // render the special alternative title
388 } elseif ($hasForeignLabel || $hasSymmetricLabel) {
389 $titleCol = $hasForeignLabel ? $config['foreign_label'] : $config['symmetric_label'];
390 $foreignConfig = $this->getPossibleRecordsSelectorConfig($config, $titleCol);
391 // Render title for everything else than group/db:
392 if ($foreignConfig['type'] != 'groupdb') {
393 $recTitle = t3lib_BEfunc::getProcessedValueExtra($foreign_table, $titleCol, $rec[$titleCol], 0, 0, false);
394 // Render title for group/db:
395 } else {
396 // $recTitle could be something like: "tx_table_123|...",
397 $valueParts = t3lib_div::trimExplode('|', $rec[$titleCol]);
398 $itemParts = t3lib_div::revExplode('_', $valueParts[0], 2);
399 $recTemp = t3lib_befunc::getRecordWSOL($itemParts[0], $itemParts[1]);
400 $recTitle = t3lib_BEfunc::getRecordTitle($itemParts[0], $recTemp, true);
401 }
402 $recTitle = t3lib_BEfunc::getRecordTitlePrep($recTitle);
403 if (!strcmp(trim($recTitle),'')) {
404 $recTitle = t3lib_BEfunc::getNoRecordTitle(true);
405 }
406 // render the standard
407 } else {
408 $recTitle = t3lib_BEfunc::getRecordTitle($foreign_table, $rec, true);
409 }
410
411 $altText = t3lib_BEfunc::getRecordIconAltText($rec, $foreign_table);
412 $iconImg =
413 '<a href="#" onclick="'.htmlspecialchars($onClick).'">'.t3lib_iconWorks::getIconImage(
414 $foreign_table, $rec, $this->backPath,
415 'title="'.htmlspecialchars($altText).'" class="absmiddle"'
416 ).'</a>';
417
418 $label =
419 '<a href="#" onclick="'.htmlspecialchars($onClick).'" style="display: block;">'.
420 '<span id="'.$formFieldNames.'_label">'.$recTitle.'</span>'.
421 '</a>';
422
423 $ctrl = $this->renderForeignRecordHeaderControl($parentUid, $foreign_table, $rec, $config);
424
425 // @TODO: Check the table wrapping and the CSS definitions
426 $header =
427 '<table cellspacing="0" cellpadding="0" border="0" width="100%" style="margin-right: '.$this->inlineStyles['margin-right'].'px;"'.
428 ($this->fObj->borderStyle[2] ? ' background="'.htmlspecialchars($this->backPath.$this->fObj->borderStyle[2]).'"':'').
429 ($this->fObj->borderStyle[3] ? ' class="'.htmlspecialchars($this->fObj->borderStyle[3]).'"':'').'>' .
430 '<tr class="class-main12"><td width="18">'.$iconImg.'</td><td align="left"><b>'.$label.'</b></td><td align="right">'.$ctrl.'</td></tr></table>';
431
432 return $header;
433 }
434
435
436 /**
437 * Render the control-icons for a record header (create new, sorting, delete, disable/enable).
438 * Most of the parts are copy&paste from class.db_list_extra.inc and modified for the JavaScript calls here
439 *
440 * @param string $parentUid: The uid of the parent (embedding) record (uid or NEW...)
441 * @param string $foreign_table: The table (foreign_table) we create control-icons for
442 * @param array $rec: The current record of that foreign_table
443 * @param array $config: (modified) TCA configuration of the field
444 * @return string The HTML code with the control-icons
445 */
446 function renderForeignRecordHeaderControl($parentUid, $foreign_table, $rec, $config = array()) {
447 // Initialize:
448 $cells=array();
449 $isNewItem = substr($rec['uid'], 0, 3) == 'NEW';
450
451 $tcaTableCtrl =& $GLOBALS['TCA'][$foreign_table]['ctrl'];
452 $tcaTableCols =& $GLOBALS['TCA'][$foreign_table]['columns'];
453
454 $isPagesTable = $foreign_table == 'pages' ? true : false;
455 $isOnSymmetricSide = t3lib_loadDBGroup::isOnSymmetricSide($parentUid, $config, $rec);
456 $enableManualSorting = $tcaTableCtrl['sortby'] || $config['MM'] || (!$isOnSymmetricSide && $config['foreign_sortby']) || ($isOnSymmetricSide && $config['symmetric_sortby']) ? true : false;
457
458 $nameObjectFt = $this->inlineNames['object'].'['.$foreign_table.']';
459 $nameObjectFtId = $nameObjectFt.'['.$rec['uid'].']';
460
461 $calcPerms = $GLOBALS['BE_USER']->calcPerms(
462 t3lib_BEfunc::readPageAccess($rec['pid'], $GLOBALS['BE_USER']->getPagePermsClause(1))
463 );
464
465 // If the listed table is 'pages' we have to request the permission settings for each page:
466 if ($isPagesTable) {
467 $localCalcPerms = $GLOBALS['BE_USER']->calcPerms(t3lib_BEfunc::getRecord('pages',$rec['uid']));
468 }
469
470 // This expresses the edit permissions for this particular element:
471 $permsEdit = ($isPagesTable && ($localCalcPerms&2)) || (!$isPagesTable && ($calcPerms&16));
472
473 // "Info": (All records)
474 if (!$isNewItem)
475 $cells[]='<a href="#" onclick="'.htmlspecialchars('top.launchView(\''.$foreign_table.'\', \''.$rec['uid'].'\'); return false;').'">'.
476 '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/zoom2.gif','width="12" height="12"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:showInfo',1).'" alt="" />'.
477 '</a>';
478
479 // If the table is NOT a read-only table, then show these links:
480 if (!$tcaTableCtrl['readOnly']) {
481
482 // "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):
483 if ($enableManualSorting || $tcaTableCtrl['useColumnsForDefaultValues']) {
484 if (
485 (!$isPagesTable && ($calcPerms&16)) || // For NON-pages, must have permission to edit content on this parent page
486 ($isPagesTable && ($calcPerms&8)) // For pages, must have permission to create new pages here.
487 ) {
488 $onClick = "return inline.createNewRecord('".$nameObjectFt."','".$rec['uid']."')";
489 if ($config['inline']['inlineNewButtonStyle']) {
490 $style = ' style="'.$config['inline']['inlineNewButtonStyle'].'"';
491 }
492 $cells[]='<a href="#" onclick="'.htmlspecialchars($onClick).'" class="inlineNewButton"'.$style.'>'.
493 '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/new_'.($isPagesTable?'page':'el').'.gif','width="'.($isPagesTable?13:11).'" height="12"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:new'.($isPagesTable?'Page':'Record'),1).'" alt="" />'.
494 '</a>';
495 }
496 }
497
498 // Drag&Drop Sorting: Sortable handler for script.aculo.us
499 if ($permsEdit && $enableManualSorting && $config['appearance']['useSortable']) {
500 $cells[] = '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/move.gif','width="16" height="16" hspace="2"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.move',1).'" alt="" style="cursor: move;" class="sortableHandle" />';
501 }
502
503 // "Up/Down" links
504 if ($permsEdit && $enableManualSorting) {
505 $onClick = "return inline.changeSorting('".$nameObjectFtId."', '1')"; // Up
506 $style = $config['inline']['first'] == $rec['uid'] ? 'style="visibility: hidden;"' : '';
507 $cells[]='<a href="#" onclick="'.htmlspecialchars($onClick).'" class="sortingUp" '.$style.'>'.
508 '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/button_up.gif','width="11" height="10"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:moveUp',1).'" alt="" />'.
509 '</a>';
510
511 $onClick = "return inline.changeSorting('".$nameObjectFtId."', '-1')"; // Down
512 $style = $config['inline']['last'] == $rec['uid'] ? 'style="visibility: hidden;"' : '';
513 $cells[]='<a href="#" onclick="'.htmlspecialchars($onClick).'" class="sortingDown" '.$style.'>'.
514 '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/button_down.gif','width="11" height="10"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:moveDown',1).'" alt="" />'.
515 '</a>';
516 }
517
518 // "Hide/Unhide" links:
519 $hiddenField = $tcaTableCtrl['enablecolumns']['disabled'];
520 if ($permsEdit && $hiddenField && $tcaTableCols[$hiddenField] && (!$tcaTableCols[$hiddenField]['exclude'] || $GLOBALS['BE_USER']->check('non_exclude_fields',$foreign_table.':'.$hiddenField))) {
521 $onClick = "return inline.enableDisableRecord('".$nameObjectFtId."')";
522 if ($rec[$hiddenField]) {
523 $cells[]='<a href="#" onclick="'.htmlspecialchars($onClick).'">'.
524 '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/button_unhide.gif','width="11" height="10"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:unHide'.($isPagesTable?'Page':''),1).'" alt="" id="'.$nameObjectFtId.'_disabled" />'.
525 '</a>';
526 } else {
527 $cells[]='<a href="#" onclick="'.htmlspecialchars($onClick).'">'.
528 '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/button_hide.gif','width="11" height="10"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:hide'.($isPagesTable?'Page':''),1).'" alt="" id="'.$nameObjectFtId.'_disabled" />'.
529 '</a>';
530 }
531 }
532
533 // "Delete" link:
534 if (
535 ($isPagesTable && ($localCalcPerms&4)) || (!$isPagesTable && ($calcPerms&16))
536 ) {
537 $onClick = "inline.deleteRecord('".$nameObjectFtId."');";
538 $cells[]='<a href="#" onclick="'.htmlspecialchars('if (confirm('.$GLOBALS['LANG']->JScharCode($GLOBALS['LANG']->getLL('deleteWarning')).')) { '.$onClick.' } return false;').'">'.
539 '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/garbage.gif','width="11" height="12"').' title="'.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_mod_web_list.xml:delete',1).'" alt="" />'.
540 '</a>';
541 }
542 }
543
544 // If the record is edit-locked by another user, we will show a little warning sign:
545 if ($lockInfo=t3lib_BEfunc::isRecordLocked($foreign_table,$rec['uid'])) {
546 $cells[]='<a href="#" onclick="'.htmlspecialchars('alert('.$GLOBALS['LANG']->JScharCode($lockInfo['msg']).');return false;').'">'.
547 '<img'.t3lib_iconWorks::skinImg('','gfx/recordlock_warning3.gif','width="17" height="12"').' title="'.htmlspecialchars($lockInfo['msg']).'" alt="" />'.
548 '</a>';
549 }
550
551 // Compile items into a DIV-element:
552 return '
553 <!-- CONTROL PANEL: '.$foreign_table.':'.$rec['uid'].' -->
554 <div class="typo3-DBctrl">'.implode('',$cells).'</div>';
555 }
556
557
558 /**
559 * Render a table with TCEforms, that occurs on a intermediate table but should be editable directly,
560 * so two tables are combined (the intermediate table with attributes and the sub-embedded table).
561 * -> This is a direct embedding over two levels!
562 *
563 * @param array $rec: The table record of the child/embedded table (normaly post-processed by t3lib_transferData)
564 * @param string $appendFormFieldNames: The [<table>][<uid>] of the parent record (the intermediate table)
565 * @param array $config: content of $PA['fieldConf']['config']
566 * @return string A HTML string with <table> tag around.
567 */
568 function renderCombinationTable(&$rec, $appendFormFieldNames, $config = array()) {
569 $foreign_table = $config['foreign_table'];
570 $foreign_selector = $config['foreign_selector'];
571
572 if ($foreign_selector && $config['appearance']['useCombination']) {
573 $comboConfig = $GLOBALS['TCA'][$foreign_table]['columns'][$foreign_selector]['config'];
574 $comboRecord = array();
575
576 // record does already exist, so load it
577 if (t3lib_div::testInt($rec[$foreign_selector])) {
578 $comboRecord = $this->getRecord(
579 $this->inlineFirstPid,
580 $comboConfig['foreign_table'],
581 $rec[$foreign_selector]
582 );
583 $isNewRecord = false;
584 // it's a new record, so get some default data
585 } else {
586 $comboRecord = $this->getNewRecord(
587 $this->inlineFirstPid,
588 $comboConfig['foreign_table']
589 );
590 $isNewRecord = true;
591 }
592
593 // get the TCEforms interpretation of the TCA of the child table
594 $out = $this->fObj->getMainFields($comboConfig['foreign_table'], $comboRecord);
595 $out = $this->wrapFormsSection($out, array(), array('class' => 'wrapperAttention'));
596
597 // if this is a new record, add a pid value to store this record and the pointer value for the intermediate table
598 if ($isNewRecord) {
599 $comboFormFieldName = $this->prependFormFieldNames.'['.$comboConfig['foreign_table'].']['.$comboRecord['uid'].'][pid]';
600 $out .= '<input type="hidden" name="'.$comboFormFieldName.'" value="'.$this->inlineFirstPid.'"/>';
601 }
602
603 // if the foreign_selector field is also responsible for uniqueness, tell the browser the uid of the "other" side of the relation
604 if ($isNewRecord || $config['foreign_unique'] == $foreign_selector) {
605 $parentFormFieldName = $this->prependFormFieldNames.$appendFormFieldNames.'['.$foreign_selector.']';
606 $out .= '<input type="hidden" name="'.$parentFormFieldName.'" value="'.$comboRecord['uid'].'" />';
607 }
608 }
609
610 return $out;
611 }
612
613
614 /**
615 * Get a selector as used for the select type, to select from all available
616 * records and to create a relation to the embedding record (e.g. like MM).
617 *
618 * @param array $selItems: Array of all possible records
619 * @param array $conf: TCA configuration of the parent(!) field
620 * @param array $uniqueIds: The uids that have already been used and should be unique
621 * @return string A HTML <select> box with all possible records
622 */
623 function renderPossibleRecordsSelector($selItems, $conf, $uniqueIds=array()) {
624 $foreign_table = $conf['foreign_table'];
625 $foreign_selector = $conf['foreign_selector'];
626
627 $selConfig = $this->getPossibleRecordsSelectorConfig($conf, $foreign_selector);
628 $config = $selConfig['PA']['fieldConf']['config'];
629
630 if ($selConfig['type'] == 'select') {
631 $item = $this->renderPossibleRecordsSelectorTypeSelect($selItems, $conf, $selConfig['PA'], $uniqueIds);
632 } elseif ($selConfig['type'] == 'groupdb') {
633 $item = $this->renderPossibleRecordsSelectorTypeGroupDB($conf, $selConfig['PA']);
634 }
635
636 return $item;
637 }
638
639
640 /**
641 * Get a selector as used for the select type, to select from all available
642 * records and to create a relation to the embedding record (e.g. like MM).
643 *
644 * @param array $selItems: Array of all possible records
645 * @param array $conf: TCA configuration of the parent(!) field
646 * @param array $PA: An array with additional configuration options
647 * @param array $uniqueIds: The uids that have already been used and should be unique
648 * @return string A HTML <select> box with all possible records
649 */
650 function renderPossibleRecordsSelectorTypeSelect($selItems, $conf, &$PA, $uniqueIds=array()) {
651 $foreign_table = $conf['foreign_table'];
652 $foreign_selector = $conf['foreign_selector'];
653
654 $PA = array();
655 $PA['fieldConf'] = $GLOBALS['TCA'][$foreign_table]['columns'][$foreign_selector];
656 $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
657 $PA['fieldTSConfig'] = $this->fObj->setTSconfig($foreign_table,array(),$foreign_selector);
658 $config = $PA['fieldConf']['config'];
659
660 if(!$disabled) {
661 // Create option tags:
662 $opt = array();
663 $styleAttrValue = '';
664 foreach($selItems as $p) {
665 if ($config['iconsInOptionTags']) {
666 $styleAttrValue = $this->fObj->optionTagStyle($p[2]);
667 }
668 if (!in_array($p[1], $uniqueIds)) {
669 $opt[]= '<option value="'.htmlspecialchars($p[1]).'"'.
670 ' style="'.(in_array($p[1], $uniqueIds) ? '' : '').
671 ($styleAttrValue ? ' style="'.htmlspecialchars($styleAttrValue) : '').'">'.
672 htmlspecialchars($p[0]).'</option>';
673 }
674 }
675
676 // Put together the selector box:
677 $selector_itemListStyle = isset($config['itemListStyle']) ? ' style="'.htmlspecialchars($config['itemListStyle']).'"' : ' style="'.$this->fObj->defaultMultipleSelectorStyle.'"';
678 $size = intval($conf['size']);
679 $size = $conf['autoSizeMax'] ? t3lib_div::intInRange(count($itemArray)+1,t3lib_div::intInRange($size,1),$conf['autoSizeMax']) : $size;
680 $onChange = "return inline.importNewRecord('".$this->inlineNames['object']."[".$conf['foreign_table']."]')";
681 $item = '
682 <select id="'.$this->inlineNames['object'].'['.$conf['foreign_table'].']_selector"'.
683 $this->fObj->insertDefStyle('select').
684 ($size ? ' size="'.$size.'"' : '').
685 ' onchange="'.htmlspecialchars($onChange).'"'.
686 $PA['onFocus'].
687 $selector_itemListStyle.
688 ($conf['foreign_unique'] ? ' isunique="isunique"' : '').'>
689 '.implode('
690 ',$opt).'
691 </select>';
692
693 // add a "Create new relation" link for adding new relations
694 // this is neccessary, if the size of the selector is "1" or if
695 // there is only one record item in the select-box, that is selected by default
696 // the selector-box creates a new relation on using a onChange event (see some line above)
697 $createNewRelationText = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:cm.createNewRelation',1);
698 $item .=
699 '<a href="#" onclick="'.htmlspecialchars($onChange).'" align="abstop">'.
700 '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/edit2.gif','width="11" height="12"').' align="absmiddle" '.t3lib_BEfunc::titleAltAttrib($createNewRelationText).' /> '.$createNewRelationText.
701 '</a>';
702 // wrap the selector and add a spacer to the bottom
703 $item = '<div style="margin-bottom: 20px;">'.$item.'</div>';
704 }
705
706 return $item;
707 }
708
709
710 /**
711 * Generate a link that opens an element browser in a new window.
712 * For group/db there is no way o use a "selector" like a <select>|</select>-box.
713 *
714 * @param array $conf: TCA configuration of the parent(!) field
715 * @param array $PA: An array with additional configuration options
716 * @return string A HTML link that opens an element browser in a new window
717 */
718 function renderPossibleRecordsSelectorTypeGroupDB($conf, &$PA) {
719 $foreign_table = $conf['foreign_table'];
720
721 $config = $PA['fieldConf']['config'];
722 $allowed = $config['allowed'];
723 $objectPrefix = $this->inlineNames['object'].'['.$foreign_table.']';
724
725 $createNewRelationText = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:cm.createNewRelation',1);
726 $onClick = "setFormValueOpenBrowser('db','".('|||'.$allowed.'|'.$objectPrefix.'|inline.checkUniqueElement||inline.importElement')."'); return false;";
727 $item =
728 '<a href="#" onclick="'.htmlspecialchars($onClick).'">'.
729 '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/insert3.gif','width="14" height="14"').' align="absmiddle" '.t3lib_BEfunc::titleAltAttrib($createNewRelationText).' /> '.$createNewRelationText.
730 '</a>';
731
732 return $item;
733 }
734
735
736 /**
737 * Creates a link/button to create new records
738 *
739 * @param string $objectPrefix: The "path" to the child record to create (e.g. '[parten_table][parent_uid][parent_field][child_table]')
740 * @param array $conf: TCA configuration of the parent(!) field
741 * @return string The HTML code for the new record link
742 */
743 function getNewRecordLink($objectPrefix, $conf = array()) {
744 if ($conf['inline']['inlineNewButtonStyle']) $style = ' style="'.$conf['inline']['inlineNewButtonStyle'].'"';
745
746 $onClick = "return inline.createNewRecord('$objectPrefix')";
747 $title = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:cm.createnew',1);
748
749 if ($conf['appearance']['newRecordLinkAddTitle'])
750 $tableTitle .= ' '.$GLOBALS['LANG']->sL($GLOBALS['TCA'][$conf['foreign_table']]['ctrl']['title'],1);
751
752 $out = '
753 <div class="typo3-newRecordLink">
754 <a href="#" onClick="'.$onClick.'" class="inlineNewButton"'.$style.' title="'.$title.$tableTitle.'">'.
755 '<img'.t3lib_iconWorks::skinImg($this->backPath,'gfx/new_el.gif','width="11" height="12"').' alt="'.$title.$tableTitle.'" />'.
756 $title.t3lib_div::fixed_lgd_cs($tableTitle, $this->fObj->titleLen).
757 '</a>
758 </div>';
759 return $out;
760 }
761
762
763 /**
764 * Add Sortable functionality using script.acolo.us "Sortable".
765 *
766 * @param string $objectId: The container id of the object - elements inside will be sortable
767 * @return void
768 */
769 function addJavaScriptSortable($objectId) {
770 $this->fObj->additionalJS_post[] = '
771 inline.createDragAndDropSorting("'.$objectId.'");
772 ';
773 }
774
775
776 /*******************************************************
777 *
778 * Handling of AJAX calls
779 *
780 *******************************************************/
781
782
783 /**
784 * Handle AJAX calls to show a new inline-record of the given table.
785 * Normally this method is never called from inside TYPO3. Always from outside by AJAX.
786 *
787 * @param string $domObjectId: The calling object in hierarchy, that requested a new record.
788 * @param string $foreignUid: If set, the new record should be inserted after that one.
789 * @return string A JSON string
790 */
791 function createNewRecord($domObjectId, $foreignUid = 0) {
792 $this->isAjaxCall = true;
793 // parse the DOM identifier (string), add the levels to the structure stack (array) and load the TCA config
794 $this->parseStructureString($domObjectId, true);
795 // the current table - for this table we should add/import records
796 $current = $this->inlineStructure['unstable'];
797 // the parent table - this table embeds the current table
798 $parent = $this->getStructureLevel(-1);
799 // get TCA 'config' of the parent table
800 $config = $parent['config'];
801
802 // Put the current level also to the dynNestedStack of TCEforms:
803 $this->fObj->pushToDynNestedStack('inline', $this->inlineNames['object']);
804
805 // dynamically create a new record using t3lib_transferData
806 if (!$foreignUid || !t3lib_div::testInt($foreignUid) || $config['foreign_selector']) {
807 $record = $this->getNewRecord($this->inlineFirstPid, $current['table']);
808
809 // dynamically import an existing record (this could be a call from a select box)
810 } else {
811 $record = $this->getRecord($this->inlineFirstPid, $current['table'], $foreignUid);
812 }
813
814 // now there is a foreign_selector, so there is a new record on the intermediate table, but
815 // this intermediate table holds a field, which is responsible for the foreign_selector, so
816 // we have to set this field to the uid we get - or if none, to a new uid
817 if ($config['foreign_selector'] && $foreignUid) {
818 $selConfig = $this->getPossibleRecordsSelectorConfig($config, $config['foreign_selector']);
819 // For a selector of type group/db, prepend the tablename (<tablename>_<uid>):
820 $record[$config['foreign_selector']] = $selConfig['type'] != 'groupdb' ? '' : $selConfig['table'].'_';
821 $record[$config['foreign_selector']] .= $foreignUid;
822 }
823
824 // the HTML-object-id's prefix of the dynamically created record
825 $objectPrefix = $this->inlineNames['object'].'['.$current['table'].']';
826 $objectId = $objectPrefix.'['.$record['uid'].']';
827
828 // render the foreign record that should passed back to browser
829 $item = $this->renderForeignRecord($parent['uid'], $record, $config);
830 if($item === false) {
831 $jsonArray = array(
832 'data' => 'Access denied',
833 'scriptCall' => array(
834 "alert('Access denied');",
835 )
836 );
837 return $this->getJSON($jsonArray);
838 }
839
840 // Encode TCEforms AJAX response with utf-8:
841 $item = $GLOBALS['LANG']->csConvObj->utf8_encode($item, $GLOBALS['LANG']->charSet);
842
843 if (!$current['uid']) {
844 $jsonArray = array(
845 'data' => $item,
846 'scriptCall' => array(
847 "inline.domAddNewRecord('bottom','".$this->inlineNames['object']."_records','$objectPrefix',json.data);",
848 "inline.memorizeAddRecord('$objectPrefix','".$record['uid']."',null,'$foreignUid');"
849 )
850 );
851
852 // append the HTML data after an existing record in the container
853 } else {
854 $jsonArray = array(
855 'data' => $item,
856 'scriptCall' => array(
857 "inline.domAddNewRecord('after','".$domObjectId.'_div'."','$objectPrefix',json.data);",
858 "inline.memorizeAddRecord('$objectPrefix','".$record['uid']."','".$current['uid']."','$foreignUid');"
859 )
860 );
861 }
862
863 // add the JavaScript data that would have been added at the bottom of a regular TCEforms calls
864 $jsonArray['scriptCall'][] = $this->fObj->JSbottom($this->fObj->formName, true);
865 // if script.aculo.us Sortable is used, update the Observer to know the the record
866 if ($config['appearance']['useSortable'])
867 $jsonArray['scriptCall'][] = "inline.createDragAndDropSorting('".$this->inlineNames['object']."_records');";
868 // if TCEforms has some JavaScript code to be executed, just do it
869 if ($this->fObj->extJSCODE)
870 $jsonArray['scriptCall'][] = $this->fObj->extJSCODE;
871 // tell the browser to scroll to the newly created record
872 $jsonArray['scriptCall'][] = "Element.scrollTo('".$objectId."_div');";
873 // fade out and fade in the new record in the browser view to catch the user's eye
874 $jsonArray['scriptCall'][] = "inline.fadeOutFadeIn('".$objectId."_div');";
875
876 // Remove the current level also from the dynNestedStack of TCEforms:
877 $this->fObj->popFromDynNestedStack();
878
879 // return the JSON string
880 return $this->getJSON($jsonArray);
881 }
882
883
884 /**
885 * Save the expanded/collapsed state of a child record in the BE_USER->uc.
886 *
887 * @param string $domObjectId: The calling object in hierarchy, that requested a new record.
888 * @param string $expand: Whether this record is expanded.
889 * @param string $collapse: Whether this record is collapsed.
890 * @return void
891 */
892 function setExpandedCollapsedState($domObjectId, $expand, $collapse) {
893 // parse the DOM identifier (string), add the levels to the structure stack (array), but don't load TCA config
894 $this->parseStructureString($domObjectId, false);
895 // the current table - for this table we should add/import records
896 $current = $this->inlineStructure['unstable'];
897 // the top parent table - this table embeds the current table
898 $top = $this->getStructureLevel(0);
899
900 // only do some action if the top record and the current record were saved before
901 if (t3lib_div::testInt($top['uid'])) {
902 $inlineView = unserialize($GLOBALS['BE_USER']->uc['inlineView']);
903 $inlineViewCurrent =& $inlineView[$top['table']][$top['uid']];
904
905 $expandUids = t3lib_div::trimExplode(',', $expand);
906 $collapseUids = t3lib_div::trimExplode(',', $collapse);
907
908 // set records to be expanded
909 foreach ($expandUids as $uid) {
910 $inlineViewCurrent[$current['table']][] = $uid;
911 }
912 // set records to be collapsed
913 foreach ($collapseUids as $uid) {
914 $inlineViewCurrent[$current['table']] = $this->removeFromArray($uid, $inlineViewCurrent[$current['table']]);
915 }
916
917 // save states back to database
918 if (is_array($inlineViewCurrent[$current['table']])) {
919 $GLOBALS['BE_USER']->uc['inlineView'] = serialize($inlineView);
920 $GLOBALS['BE_USER']->writeUC();
921 }
922 }
923 }
924
925
926 /*******************************************************
927 *
928 * Get data from database and handle relations
929 *
930 *******************************************************/
931
932
933 /**
934 * Get the related records of the embedding item, this could be 1:n, m:n.
935 *
936 * @param string $table: The table name of the record
937 * @param string $field: The field name which this element is supposed to edit
938 * @param array $row: The record data array where the value(s) for the field can be found
939 * @param array $PA: An array with additional configuration options.
940 * @param array $config: (Redundant) content of $PA['fieldConf']['config'] (for convenience)
941 * @return array The records related to the parent item
942 */
943 function getRelatedRecords($table,$field,$row,&$PA,$config) {
944 $records = array();
945
946 // Creating the label for the "No Matching Value" entry.
947 $nMV_label = isset($PA['fieldTSConfig']['noMatchingValue_label']) ? $this->fObj->sL($PA['fieldTSConfig']['noMatchingValue_label']) : '[ '.$this->fObj->getLL('l_noMatchingValue').' ]';
948
949 // Register the required number of elements:
950 # $this->fObj->requiredElements[$PA['itemFormElName']] = array($minitems,$maxitems,'imgName'=>$table.'_'.$row['uid'].'_'.$field);
951
952 // Perform modification of the selected items array:
953 $itemArray = t3lib_div::trimExplode(',',$PA['itemFormElValue'],1);
954 foreach($itemArray as $tk => $tv) {
955 $tvP = explode('|',$tv,2);
956 // get the records for this uid using t3lib_transferdata
957 $records[] = $this->getRecord($row['pid'], $config['foreign_table'], $tvP[0]);
958 }
959
960 return $records;
961 }
962
963
964 /**
965 * Get possible records.
966 * Copied from TCEform and modified.
967 *
968 * @param string The table name of the record
969 * @param string The field name which this element is supposed to edit
970 * @param array The record data array where the value(s) for the field can be found
971 * @param array An array with additional configuration options.
972 * @param string $checkForConfField: For which field in the foreign_table the possible records should be fetched
973 * @return mixed Array of possible record items; false if type is "group/db", then everything could be "possible"
974 */
975 function getPossibleRecords($table,$field,$row,$conf,$checkForConfField='foreign_selector') {
976 // ctrl configuration from TCA:
977 $tcaTableCtrl = $GLOBALS['TCA'][$table]['ctrl'];
978 // Field configuration from TCA:
979 $foreign_table = $conf['foreign_table'];
980 $foreign_check = $conf[$checkForConfField];
981
982 $foreignConfig = $this->getPossibleRecordsSelectorConfig($conf, $foreign_check);
983 $PA = $foreignConfig['PA'];
984 $config = $PA['fieldConf']['config'];
985
986 if ($foreignConfig['type'] == 'select') {
987 // Getting the selector box items from the system
988 $selItems = $this->fObj->addSelectOptionsToItemArray($this->fObj->initItemArray($PA['fieldConf']),$PA['fieldConf'],$this->fObj->setTSconfig($table,$row),$field);
989 if ($config['itemsProcFunc']) $selItems = $this->fObj->procItems($selItems,$PA['fieldTSConfig']['itemsProcFunc.'],$config,$table,$row,$field);
990
991 // Possibly remove some items:
992 $removeItems = t3lib_div::trimExplode(',',$PA['fieldTSConfig']['removeItems'],1);
993 foreach($selItems as $tk => $p) {
994
995 // Checking languages and authMode:
996 $languageDeny = $tcaTableCtrl['languageField'] && !strcmp($tcaTableCtrl['languageField'], $field) && !$GLOBALS['BE_USER']->checkLanguageAccess($p[1]);
997 $authModeDeny = $config['form_type']=='select' && $config['authMode'] && !$GLOBALS['BE_USER']->checkAuthMode($table,$field,$p[1],$config['authMode']);
998 if (in_array($p[1],$removeItems) || $languageDeny || $authModeDeny) {
999 unset($selItems[$tk]);
1000 } elseif (isset($PA['fieldTSConfig']['altLabels.'][$p[1]])) {
1001 $selItems[$tk][0]=$this->fObj->sL($PA['fieldTSConfig']['altLabels.'][$p[1]]);
1002 }
1003
1004 // Removing doktypes with no access:
1005 if ($table.'.'.$field == 'pages.doktype') {
1006 if (!($GLOBALS['BE_USER']->isAdmin() || t3lib_div::inList($GLOBALS['BE_USER']->groupData['pagetypes_select'],$p[1]))) {
1007 unset($selItems[$tk]);
1008 }
1009 }
1010 }
1011 } else {
1012 $selItems = false;
1013 }
1014
1015 return $selItems;
1016 }
1017
1018 /**
1019 * Gets the uids of a select/selector that should be unique an have already been used.
1020 *
1021 * @param array $records: All inline records on this level
1022 * @param array $conf: The TCA field configuration of the inline field to be rendered
1023 * @param boolean $splitValue: for usage with group/db, values come like "tx_table_123|Title%20abc", but we need "tx_table" and "123"
1024 * @return array The uids, that have been used already and should be used unique
1025 */
1026 function getUniqueIds($records, $conf=array(), $splitValue=false) {
1027 $uniqueIds = array();
1028
1029 if ($conf['foreign_unique'] && count($records)) {
1030 foreach ($records as $rec) {
1031 $value = $rec[$conf['foreign_unique']];
1032 // Split the value and extract the table and uid:
1033 if ($splitValue) {
1034 $valueParts = t3lib_div::trimExplode('|', $value);
1035 $itemParts = explode('_', $valueParts[0]);
1036 $value = array(
1037 'uid' => array_pop($itemParts),
1038 'table' => implode('_', $itemParts)
1039 );
1040 }
1041 $uniqueIds[$rec['uid']] = $value;
1042 }
1043 }
1044
1045 return $uniqueIds;
1046 }
1047
1048
1049 /**
1050 * Get a single record row for a TCA table from the database.
1051 * t3lib_transferData is used for "upgrading" the values, especially the relations.
1052 *
1053 * @param integer $pid: The pid of the page the record should be stored (only relevant for NEW records)
1054 * @param string $table: The table to fetch data from (= foreign_table)
1055 * @param string $uid: The uid of the record to fetch, or empty if a new one should be created
1056 * @param string $cmd: The command to perform, empty or 'new'
1057 * @return array A record row from the database post-processed by t3lib_transferData
1058 */
1059 function getRecord($pid, $table, $uid, $cmd='') {
1060 $trData = t3lib_div::makeInstance('t3lib_transferData');
1061 $trData->addRawData = TRUE;
1062 # $trData->defVals = $this->defVals;
1063 $trData->lockRecords=1;
1064 $trData->disableRTE = $GLOBALS['SOBE']->MOD_SETTINGS['disableRTE'];
1065 // if a new record should be created
1066 $trData->fetchRecord($table, $uid, ($cmd === 'new' ? 'new' : ''));
1067 reset($trData->regTableItems_data);
1068 $rec = current($trData->regTableItems_data);
1069 $rec['uid'] = $cmd == 'new' ? uniqid('NEW') : $uid;
1070 if ($cmd=='new') $rec['pid'] = $pid;
1071
1072 return $rec;
1073 }
1074
1075
1076 /**
1077 * Wrapper. Calls getRecord in case of a new record should be created.
1078 *
1079 * @param integer $pid: The pid of the page the record should be stored (only relevant for NEW records)
1080 * @param string $table: The table to fetch data from (= foreign_table)
1081 * @return array A record row from the database post-processed by t3lib_transferData
1082 */
1083 function getNewRecord($pid, $table) {
1084 return $this->getRecord($pid, $table, '', 'new');
1085 }
1086
1087
1088 /*******************************************************
1089 *
1090 * Structure stack for handling inline objects/levels
1091 *
1092 *******************************************************/
1093
1094
1095 /**
1096 * Add a new level on top of the structure stack. Other functions can access the
1097 * stack and determine, if there's possibly a endless loop.
1098 *
1099 * @param string $table: The table name of the record
1100 * @param string $uid: The uid of the record that embeds the inline data
1101 * @param string $field: The field name which this element is supposed to edit
1102 * @param array $config: The TCA-configuration of the inline field
1103 * @return void
1104 */
1105 function pushStructure($table, $uid, $field = '', $config = array()) {
1106 $this->inlineStructure['stable'][] = array(
1107 'table' => $table,
1108 'uid' => $uid,
1109 'field' => $field,
1110 'config' => $config,
1111 );
1112 $this->updateStructureNames();
1113 }
1114
1115
1116 /**
1117 * Remove the item on top of the structure stack and return it.
1118 *
1119 * @return array The top item of the structure stack - array(<table>,<uid>,<field>,<config>)
1120 */
1121 function popStructure() {
1122 if (count($this->inlineStructure['stable'])) {
1123 $popItem = array_pop($this->inlineStructure['stable']);
1124 $this->updateStructureNames();
1125 }
1126 return $popItem;
1127 }
1128
1129
1130 /**
1131 * For common use of DOM object-ids and form field names of a several inline-level,
1132 * these names/identifiers are preprocessed and set to $this->inlineNames.
1133 * This function is automatically called if a level is pushed to or removed from the
1134 * inline structure stack.
1135 *
1136 * @return void
1137 */
1138 function updateStructureNames() {
1139 $current = $this->getStructureLevel(-1);
1140 // if there are still more inline levels available
1141 if ($current !== false) {
1142 $lastItemName = $this->getStructureItemName($current);
1143 $this->inlineNames = array(
1144 'form' => $this->prependFormFieldNames.$lastItemName,
1145 'object' => $this->prependNaming.'['.$this->inlineFirstPid.']'.$this->getStructurePath(),
1146 );
1147 // if there are no more inline levels available
1148 } else {
1149 $this->inlineNames = array();
1150 }
1151 }
1152
1153
1154 /**
1155 * Create a name/id for usage in HTML output of a level of the structure stack.
1156 *
1157 * @param array $levelData: Array of a level of the structure stack (containing the keys table, uid and field)
1158 * @return string The name/id of that level, to be used for HTML output
1159 */
1160 function getStructureItemName($levelData) {
1161 if (is_array($levelData)) {
1162 $name = '['.$levelData['table'].']' .
1163 '['.$levelData['uid'].']' .
1164 (isset($levelData['field']) ? '['.$levelData['field'].']' : '');
1165 }
1166 return $name;
1167 }
1168
1169
1170 /**
1171 * Get a level from the stack and return the data.
1172 * If the $level value is negative, this function works top-down,
1173 * if the $level value is positive, this function works bottom-up.
1174 *
1175 * @param integer $level: Which level to return
1176 * @return array The item of the stack at the requested level
1177 */
1178 function getStructureLevel($level) {
1179 $inlineStructureCount = count($this->inlineStructure['stable']);
1180 if ($level < 0) $level = $inlineStructureCount+$level;
1181 if ($level >= 0 && $level < $inlineStructureCount)
1182 return $this->inlineStructure['stable'][$level];
1183 else
1184 return false;
1185 }
1186
1187
1188 /**
1189 * Get the identifiers of a given depth of level, from the top of the stack to the bottom.
1190 * An identifier consists looks like [<table>][<uid>][<field>].
1191 *
1192 * @param integer $structureDepth: How much levels to output, beginning from the top of the stack
1193 * @return string The path of identifiers
1194 */
1195 function getStructurePath($structureDepth = -1) {
1196 $structureCount = count($this->inlineStructure['stable']);
1197 if ($structureDepth < 0 || $structureDepth > $structureCount) $structureDepth = $structureCount;
1198
1199 for ($i = 1; $i <= $structureDepth; $i++) {
1200 $current = $this->getStructureLevel(-$i);
1201 $string = $this->getStructureItemName($current).$string;
1202 }
1203
1204 return $string;
1205 }
1206
1207
1208 /**
1209 * Convert the DOM object-id of an inline container to an array.
1210 * The object-id could look like 'data[inline][tx_mmftest_company][1][employees]'.
1211 * The result is written to $this->inlineStructure.
1212 * There are two keys:
1213 * - 'stable': Containing full qualified identifiers (table, uid and field)
1214 * - 'unstable': Containting partly filled data (e.g. only table and possibly field)
1215 *
1216 * @param string $domObjectId: The DOM object-id
1217 * @param boolean $loadConfig: Load the TCA configuration for that level
1218 * @return void
1219 */
1220 function parseStructureString($string, $loadConfig = false) {
1221 $unstable = array();
1222 $vector = array('table', 'uid', 'field');
1223 $pattern = '/^'.$this->prependNaming.'\[(.+?)\]\[(.+)\]$/';
1224 if (preg_match($pattern, $string, $match)) {
1225 $this->inlineFirstPid = $match[1];
1226 $parts = explode('][', $match[2]);
1227 $partsCnt = count($parts);
1228 for ($i = 0; $i < $partsCnt; $i++) {
1229 if ($i > 0 && $i % 3 == 0) {
1230 // load the TCA configuration of the table field and store it in the stack
1231 if ($loadConfig) {
1232 t3lib_div::loadTCA($unstable['table']);
1233 $unstable['config'] = $GLOBALS['TCA'][$unstable['table']]['columns'][$unstable['field']]['config'];
1234 // Fetch TSconfig:
1235 $TSconfig = $this->fObj->setTSconfig(
1236 $unstable['table'],
1237 array('uid' => $unstable['uid'], 'pid' => $this->inlineFirstPid),
1238 $unstable['field']
1239 );
1240 // Override TCA field config by TSconfig:
1241 if (!$TSconfig['disabled']) {
1242 $unstable['config'] = $this->fObj->overrideFieldConf($unstable['config'], $TSconfig);
1243 }
1244 }
1245 $this->inlineStructure['stable'][] = $unstable;
1246 $unstable = array();
1247 }
1248 $unstable[$vector[$i % 3]] = $parts[$i];
1249 }
1250 $this->updateStructureNames();
1251 if (count($unstable)) $this->inlineStructure['unstable'] = $unstable;
1252 }
1253 }
1254
1255
1256 /*******************************************************
1257 *
1258 * Helper functions
1259 *
1260 *******************************************************/
1261
1262
1263 /**
1264 * Does some checks on the TCA configuration of the inline field to render.
1265 *
1266 * @param array $config: Reference to the TCA field configuration
1267 * @return boolean If critical configuration errors were found, false is returned
1268 */
1269 function checkConfiguration(&$config) {
1270 $foreign_table = $config['foreign_table'];
1271
1272 // An inline field must have a foreign_table, if not, stop all further inline actions for this field:
1273 if (!$foreign_table || !is_array($GLOBALS['TCA'][$foreign_table])) {
1274 return false;
1275 }
1276 // Init appearance if not set:
1277 if (!is_array($config['appearance'])) {
1278 $config['appearance'] = array();
1279 }
1280 // Set the position/appearance of the "Create new record" link:
1281 if ($config['foreign_selector'] && !$config['appearance']['useCombination']) {
1282 $config['appearance']['newRecordLinkPosition'] = 'none';
1283 } elseif (!in_array($config['appearance']['newRecordLinkPosition'], array('top', 'bottom', 'both', 'none'))) {
1284 $config['appearance']['newRecordLinkPosition'] = 'top';
1285 }
1286
1287 return true;
1288 }
1289
1290
1291 /**
1292 * Checks the page access rights (Code for access check mostly taken from alt_doc.php)
1293 * as well as the table access rights of the user.
1294 *
1295 * @param string $cmd: The command that sould be performed ('new' or 'edit')
1296 * @param string $table: The table to check access for
1297 * @param string $theUid: The record uid of the table
1298 * @return boolean Returns true is the user has access, or false if not
1299 */
1300 function checkAccess($cmd, $table, $theUid) {
1301 // 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...)
1302 // First, resetting flags.
1303 $hasAccess = 0;
1304 $deniedAccessReason = '';
1305
1306 // If the command is to create a NEW record...:
1307 if ($cmd=='new') {
1308 $calcPRec = t3lib_BEfunc::getRecord('pages',$this->inlineFirstPid);
1309 if(!is_array($calcPRec)) {
1310 return false;
1311 }
1312 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec); // Permissions for the parent page
1313 if ($table=='pages') { // If pages:
1314 $hasAccess = $CALC_PERMS&8 ? 1 : 0; // Are we allowed to create new subpages?
1315 } else {
1316 $hasAccess = $CALC_PERMS&16 ? 1 : 0; // Are we allowed to edit content on this page?
1317 }
1318 } else { // Edit:
1319 $calcPRec = t3lib_BEfunc::getRecord($table,$theUid);
1320 t3lib_BEfunc::fixVersioningPid($table,$calcPRec);
1321 if (is_array($calcPRec)) {
1322 if ($table=='pages') { // If pages:
1323 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms($calcPRec);
1324 $hasAccess = $CALC_PERMS&2 ? 1 : 0;
1325 } else {
1326 $CALC_PERMS = $GLOBALS['BE_USER']->calcPerms(t3lib_BEfunc::getRecord('pages',$calcPRec['pid'])); // Fetching pid-record first.
1327 $hasAccess = $CALC_PERMS&16 ? 1 : 0;
1328 }
1329
1330 // Check internals regarding access:
1331 if ($hasAccess) {
1332 $hasAccess = $GLOBALS['BE_USER']->recordEditAccessInternals($table, $calcPRec);
1333 }
1334 }
1335 }
1336
1337 if(!$GLOBALS['BE_USER']->check('tables_modify', $table)) {
1338 $hasAccess = 0;
1339 }
1340
1341 if(!$hasAccess) {
1342 $deniedAccessReason = $GLOBALS['BE_USER']->errorMsg;
1343 if($deniedAccessReason) {
1344 debug($deniedAccessReason);
1345 }
1346 }
1347
1348 return $hasAccess ? true : false;
1349 }
1350
1351
1352 /**
1353 * Check the keys and values in the $compare array against the ['config'] part of the top level of the stack.
1354 * A boolean value is return depending on how the comparison was successful.
1355 *
1356 * @param array $compare: keys and values to compare to the ['config'] part of the top level of the stack
1357 * @return boolean Whether the comparison was successful
1358 * @see arrayCompareComplex
1359 */
1360 function compareStructureConfiguration($compare) {
1361 $level = $this->getStructureLevel(-1);
1362 $result = $this->arrayCompareComplex($level, $compare);
1363
1364 return $result;
1365 }
1366
1367
1368 /**
1369 * Normalize a relation "uid" published by transferData, like "1|Company%201"
1370 *
1371 * @param string $string: A transferData reference string, containing the uid
1372 * @return string The normalized uid
1373 */
1374 function normalizeUid($string) {
1375 $parts = explode('|', $string);
1376 return $parts[0];
1377 }
1378
1379
1380 /**
1381 * Wrap the HTML code of a section with a table tag.
1382 *
1383 * @param string $section: The HTML code to be wrapped
1384 * @param array $styleAttrs: Attributes for the style argument in the table tag
1385 * @param array $tableAttrs: Attributes for the table tag (like width, border, etc.)
1386 * @return string The wrapped HTML code
1387 */
1388 function wrapFormsSection($section, $styleAttrs = array(), $tableAttrs = array()) {
1389 if (!$styleAttrs['margin-right']) $styleAttrs['margin-right'] = $this->inlineStyles['margin-right'].'px';
1390
1391 foreach ($styleAttrs as $key => $value) $style .= ($style?' ':'').$key.': '.htmlspecialchars($value).'; ';
1392 if ($style) $style = ' style="'.$style.'"';
1393
1394 if (!$tableAttrs['background'] && $this->fObj->borderStyle[2]) $tableAttrs['background'] = $this->backPath.$this->borderStyle[2];
1395 if (!$tableAttrs['cellspacing']) $tableAttrs['cellspacing'] = '0';
1396 if (!$tableAttrs['cellpadding']) $tableAttrs['cellpadding'] = '0';
1397 if (!$tableAttrs['border']) $tableAttrs['border'] = '0';
1398 if (!$tableAttrs['width']) $tableAttrs['width'] = '100%';
1399 if (!$tableAttrs['class'] && $this->borderStyle[3]) $tableAttrs['class'] = $this->borderStyle[3];
1400
1401 foreach ($tableAttrs as $key => $value) $table .= ($table?' ':'').$key.'="'.htmlspecialchars($value).'"';
1402
1403 $out = '<table '.$table.$style.'>'.$section.'</table>';
1404 return $out;
1405 }
1406
1407
1408 /**
1409 * Checks if the $table is the child of a inline type AND the $field is the label field of this table.
1410 * This function is used to dynamically update the label while editing. This has no effect on labels,
1411 * that were processed by a TCEmain-hook on saving.
1412 *
1413 * @param string $table: The table to check
1414 * @param string $field: The field on this table to check
1415 * @return boolean is inline child and field is responsible for the label
1416 */
1417 function isInlineChildAndLabelField($table, $field) {
1418 $level = $this->getStructureLevel(-1);
1419 if ($level['config']['foreign_label'])
1420 $label = $level['config']['foreign_label'];
1421 else
1422 $label = $GLOBALS['TCA'][$table]['ctrl']['label'];
1423 return $level['config']['foreign_table'] === $table && $label == $field ? true : false;
1424 }
1425
1426
1427 /**
1428 * Get the depth of the stable structure stack.
1429 * (count($this->inlineStructure['stable'])
1430 *
1431 * @return integer The depth of the structure stack
1432 */
1433 function getStructureDepth() {
1434 return count($this->inlineStructure['stable']);
1435 }
1436
1437
1438 /**
1439 * Handles complex comparison requests on an array.
1440 * A request could look like the following:
1441 *
1442 * $searchArray = array(
1443 * '%AND' => array(
1444 * 'key1' => 'value1',
1445 * 'key2' => 'value2',
1446 * '%OR' => array(
1447 * 'subarray' => array(
1448 * 'subkey' => 'subvalue'
1449 * ),
1450 * 'key3' => 'value3',
1451 * 'key4' => 'value4'
1452 * )
1453 * )
1454 * );
1455 *
1456 * It is possible to use the array keys '%AND.1', '%AND.2', etc. to prevent
1457 * overwriting the sub-array. It could be neccessary, if you use complex comparisons.
1458 *
1459 * The example above means, key1 *AND* key2 (and their values) have to match with
1460 * the $subjectArray and additional one *OR* key3 or key4 have to meet the same
1461 * condition.
1462 * It is also possible to compare parts of a sub-array (e.g. "subarray"), so this
1463 * function recurses down one level in that sub-array.
1464 *
1465 * @param array $subjectArray: The array to search in
1466 * @param array $searchArray: The array with keys and values to search for
1467 * @param string $type: Use '%AND' or '%OR' for comparision
1468 * @return boolean The result of the comparison
1469 */
1470 function arrayCompareComplex($subjectArray, $searchArray, $type = '') {
1471 $localMatches = 0;
1472 $localEntries = 0;
1473
1474 if (is_array($searchArray) && count($searchArray)) {
1475 // if no type was passed, try to determine
1476 if (!$type) {
1477 reset($searchArray);
1478 $type = key($searchArray);
1479 $searchArray = current($searchArray);
1480 }
1481
1482 // we use '%AND' and '%OR' in uppercase
1483 $type = strtoupper($type);
1484
1485 // split regular elements from sub elements
1486 foreach ($searchArray as $key => $value) {
1487 $localEntries++;
1488
1489 // process a sub-group of OR-conditions
1490 if ($key == '%OR') {
1491 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%OR') ? 1 : 0;
1492 // process a sub-group of AND-conditions
1493 } elseif ($key == '%AND') {
1494 $localMatches += $this->arrayCompareComplex($subjectArray, $value, '%AND') ? 1 : 0;
1495 // a part of an associative array should be compared, so step down in the array hierarchy
1496 } elseif (is_array($value) && $this->isAssociativeArray($searchArray)) {
1497 $localMatches += $this->arrayCompareComplex($subjectArray[$key], $value, $type) ? 1 : 0;
1498 // it is a normal array that is only used for grouping and indexing
1499 } elseif (is_array($value)) {
1500 $localMatches += $this->arrayCompareComplex($subjectArray, $value, $type) ? 1 : 0;
1501 // directly compare a value
1502 } else {
1503 $localMatches += isset($subjectArray[$key]) && isset($value) && $subjectArray[$key] === $value ? 1 : 0;
1504 }
1505
1506 // if one or more matches are required ('OR'), return true after the first successful match
1507 if ($type == '%OR' && $localMatches > 0) return true;
1508 // if all matches are required ('AND') and we have no result after the first run, return false
1509 if ($type == '%AND' && $localMatches == 0) return false;
1510 }
1511 }
1512
1513 // return the result for '%AND' (if nothing was checked, true is returned)
1514 return $localEntries == $localMatches ? true : false;
1515 }
1516
1517
1518 /**
1519 * Checks whether an object is an associative array.
1520 *
1521 * @param mixed $object: The object to be checked
1522 * @return boolean Returns true, if the object is an associative array
1523 */
1524 function isAssociativeArray($object) {
1525 return is_array($object) && count($object) && (array_keys($object) !== range(0, sizeof($object) - 1))
1526 ? true
1527 : false;
1528 }
1529
1530
1531 /**
1532 * Remove an element from an array.
1533 *
1534 * @param mixed $needle: The element to be removed.
1535 * @param array $haystack: The array the element should be removed from.
1536 * @param mixed $strict: Search elements strictly.
1537 * @return array The array $haystack without the $needle
1538 */
1539 function removeFromArray($needle, $haystack, $strict=null) {
1540 $pos = array_search($needle, $haystack, $strict);
1541 if ($pos !== false) unset($haystack[$pos]);
1542 return $haystack;
1543 }
1544
1545
1546 /**
1547 * Makes a flat array from the $possibleRecords array.
1548 * The key of the flat array is the value of the record,
1549 * the value of the flat array is the label of the record.
1550 *
1551 * @param array $possibleRecords: The possibleRecords array (for select fields)
1552 * @return mixed A flat array with key=uid, value=label; if $possibleRecords isn't an array, false is returned.
1553 */
1554 function getPossibleRecordsFlat($possibleRecords) {
1555 $flat = false;
1556 if (is_array($possibleRecords)) {
1557 $flat = array();
1558 foreach ($possibleRecords as $record) $flat[$record[1]] = $record[0];
1559 }
1560 return $flat;
1561 }
1562
1563
1564 /**
1565 * Determine the configuration and the type of a record selector.
1566 *
1567 * @param array $conf: TCA configuration of the parent(!) field
1568 * @return array Associative array with the keys 'PA' and 'type', both are false if the selector was not valid.
1569 */
1570 function getPossibleRecordsSelectorConfig($conf, $field = '') {
1571 $foreign_table = $conf['foreign_table'];
1572 $foreign_selector = $conf['foreign_selector'];
1573
1574 $PA = false;
1575 $type = false;
1576 $table = false;
1577 $selector = false;
1578
1579 if ($field) {
1580 $PA = array();
1581 $PA['fieldConf'] = $GLOBALS['TCA'][$foreign_table]['columns'][$field];
1582 $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
1583 $PA['fieldTSConfig'] = $this->fObj->setTSconfig($foreign_table,array(),$field);
1584 $config = $PA['fieldConf']['config'];
1585 // Determine type of Selector:
1586 $type = $this->getPossibleRecordsSelectorType($config);
1587 // Return table on this level:
1588 $table = $type == 'select' ? $config['foreign_table'] : $config['allowed'];
1589 // Return type of the selector if foreign_selector is defined and points to the same field as in $field:
1590 if ($foreign_selector && $foreign_selector == $field && $type) {
1591 $selector = $type;
1592 }
1593 }
1594
1595 return array(
1596 'PA' => $PA,
1597 'type' => $type,
1598 'table' => $table,
1599 'selector' => $selector,
1600 );
1601 }
1602
1603
1604 /**
1605 * Determine the type of a record selector, e.g. select or group/db.
1606 *
1607 * @param array $config: TCE configuration of the selector
1608 * @return mixed The type of the selector, 'select' or 'groupdb' - false not valid
1609 */
1610 function getPossibleRecordsSelectorType($config) {
1611 $type = false;
1612 if ($config['type'] == 'select') {
1613 $type = 'select';
1614 } elseif ($config['type'] == 'group' && $config['internal_type'] == 'db') {
1615 $type = 'groupdb';
1616 }
1617 return $type;
1618 }
1619
1620
1621 /**
1622 * Check, if a field should be skipped, that was defined to be handled as foreign_field or foreign_sortby of
1623 * the parent record of the "inline"-type - if so, we have to skip this field - the rendering is done via "inline" as hidden field
1624 *
1625 * @param string $table: The table name
1626 * @param string $field: The field name
1627 * @param array $row: The record row from the database
1628 * @param array $config: TCA configuration of the field
1629 * @return boolean Determines whether the field should be skipped.
1630 */
1631 function skipField($table, $field, $row, $config) {
1632 $skipThisField = false;
1633
1634 if ($this->getStructureDepth()) {
1635 $searchArray = array(
1636 '%OR' => array(
1637 'config' => array(
1638 0 => array(
1639 '%AND' => array(
1640 'foreign_table' => $table,
1641 '%OR' => array(
1642 '%AND' => array(
1643 'appearance' => array('useCombination' => 1),
1644 'foreign_selector' => $field,
1645 ),
1646 'MM' => $config['MM']
1647 ),
1648 ),
1649 ),
1650 1 => array(
1651 '%AND' => array(
1652 'foreign_table' => $config['foreign_table'],
1653 'foreign_selector' => $config['foreign_field'],
1654 ),
1655 ),
1656 ),
1657 ),
1658 );
1659
1660 // get the parent record from structure stack
1661 $level = $this->getStructureLevel(-1);
1662
1663 // If we have symmetric fields, check on which side we are and hide fields, that are set automatically:
1664 if (t3lib_loadDBGroup::isOnSymmetricSide($level['uid'], $level['config'], $row)) {
1665 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_field'] = $field;
1666 $searchArray['%OR']['config'][0]['%AND']['%OR']['symmetric_sortby'] = $field;
1667 // Hide fields, that are set automatically:
1668 } else {
1669 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_field'] = $field;
1670 $searchArray['%OR']['config'][0]['%AND']['%OR']['foreign_sortby'] = $field;
1671 }
1672
1673 $skipThisField = $this->compareStructureConfiguration($searchArray, true);
1674 }
1675
1676 return $skipThisField;
1677 }
1678
1679
1680 /**
1681 * Creates recursively a JSON literal from a mulidimensional associative array.
1682 * Uses Services_JSON (http://mike.teczno.com/JSON/doc/)
1683 *
1684 * @param array $jsonArray: The array (or part of) to be transformed to JSON
1685 * @return string If $level>0: part of JSON literal; if $level==0: whole JSON literal wrapped with <script> tags
1686 */
1687 function getJSON($jsonArray) {
1688 if (!$GLOBALS['JSON']) {
1689 require_once(PATH_typo3.'contrib/json.php');
1690 $GLOBALS['JSON'] = t3lib_div::makeInstance('Services_JSON');
1691 }
1692 return $GLOBALS['JSON']->encode($jsonArray);
1693 }
1694
1695
1696 /**
1697 * Checks if a uid of a child table is in the inline view settings.
1698 *
1699 * @param string $table: Name of the child table
1700 * @param integer $uid: uid of the the child record
1701 * @return boolean true=expand, false=collapse
1702 */
1703 function getExpandedCollapsedState($table, $uid) {
1704 if (is_array($this->inlineView) && is_array($this->inlineView[$table])) {
1705 if (in_array($uid, $this->inlineView[$table]) !== false) return true;
1706 }
1707 return false;
1708 }
1709
1710
1711 /**
1712 * Update expanded/collapsed states on new inline records if any.
1713 *
1714 * @param array $uc: The uc array to be processed and saved (by reference)
1715 * @param object $tce: Instance of TCEmain that saved data before (by reference)
1716 * @return void
1717 */
1718 function updateInlineView(&$uc, &$tce) {
1719 if (is_array($uc) && $uc['inlineView']) {
1720 $inlineView = unserialize($GLOBALS['BE_USER']->uc['inlineView']);
1721
1722 foreach ($uc['inlineView'] as $topTable => $topRecords) {
1723 foreach ($topRecords as $topUid => $childElements) {
1724 foreach ($childElements as $childTable => $childRecords) {
1725 $uids = array_keys($tce->substNEWwithIDs_table, $childTable);
1726 if (count($uids)) {
1727 foreach ($childRecords as $childUid => $state) {
1728 if ($state && in_array($childUid, $uids)) {
1729 $newChildUid = $tce->substNEWwithIDs[$childUid];
1730 $inlineView[$topTable][$topUid][$childTable][$newChildUid] = 1;
1731 }
1732 }
1733 }
1734 }
1735 }
1736 }
1737
1738 $GLOBALS['BE_USER']->uc['inlineView'] = serialize($inlineView);
1739 $GLOBALS['BE_USER']->writeUC();
1740 }
1741 }
1742
1743
1744 /**
1745 * Returns the the margin in pixels, that is used for each new inline level.
1746 *
1747 * @return integer A pixel value for the margin of each new inline level.
1748 */
1749 function getLevelMargin() {
1750 $margin = ($this->inlineStyles['margin-right']+1)*2;
1751 return $margin;
1752 }
1753 }
1754
1755
1756 if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_tceforms_inline.php']) {
1757 include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_tceforms_inline.php']);
1758 }
1759 ?>