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