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