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