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