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