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