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