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