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