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