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