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