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