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