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