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