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