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