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