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