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