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