[TASK] Call explicit render() on icon objects
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Form / Container / InlineRecordContainer.php
1 <?php
2 namespace TYPO3\CMS\Backend\Form\Container;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\Form\Element\InlineElementHookInterface;
18 use TYPO3\CMS\Backend\Form\Exception\AccessDeniedContentEditException;
19 use TYPO3\CMS\Backend\Form\FormDataCompiler;
20 use TYPO3\CMS\Backend\Form\FormDataGroup\TcaDatabaseRecord;
21 use TYPO3\CMS\Backend\Form\InlineRelatedRecordResolver;
22 use TYPO3\CMS\Backend\Form\InlineStackProcessor;
23 use TYPO3\CMS\Backend\Form\NodeFactory;
24 use TYPO3\CMS\Backend\Form\Utility\FormEngineUtility;
25 use TYPO3\CMS\Backend\Utility\BackendUtility;
26 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
27 use TYPO3\CMS\Core\Database\DatabaseConnection;
28 use TYPO3\CMS\Core\Database\RelationHandler;
29 use TYPO3\CMS\Core\Imaging\Icon;
30 use TYPO3\CMS\Core\Imaging\IconFactory;
31 use TYPO3\CMS\Core\Messaging\FlashMessage;
32 use TYPO3\CMS\Core\Resource\ProcessedFile;
33 use TYPO3\CMS\Core\Resource\ResourceFactory;
34 use TYPO3\CMS\Core\Type\Bitmask\Permission;
35 use TYPO3\CMS\Core\Utility\GeneralUtility;
36 use TYPO3\CMS\Core\Utility\MathUtility;
37 use TYPO3\CMS\Core\Utility\StringUtility;
38 use TYPO3\CMS\Lang\LanguageService;
39
40 /**
41 * Render a single inline record relation.
42 *
43 * This container is called by InlineControlContainer to render single existing records.
44 * Furthermore it is called by FormEngine for an incoming ajax request to expand an existing record
45 * or to create a new one.
46 *
47 * This container creates the outer HTML of single inline records - eg. drag and drop and delete buttons.
48 * For rendering of the record itself processing is handed over to FullRecordContainer.
49 */
50 class InlineRecordContainer extends AbstractContainer {
51
52 /**
53 * Inline data array used for JSON output
54 *
55 * @var array
56 */
57 protected $inlineData = array();
58
59 /**
60 * @var InlineStackProcessor
61 */
62 protected $inlineStackProcessor;
63
64 /**
65 * Array containing instances of hook classes called once for IRRE objects
66 *
67 * @var array
68 */
69 protected $hookObjects = array();
70
71 /**
72 * @var IconFactory
73 */
74 protected $iconFactory;
75
76 /**
77 * Default constructor
78 *
79 * @param NodeFactory $nodeFactory
80 * @param array $data
81 */
82 public function __construct(NodeFactory $nodeFactory, array $data) {
83 parent::__construct($nodeFactory, $data);
84 $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
85 }
86
87 /**
88 * Entry method
89 *
90 * @return array As defined in initializeResultArray() of AbstractNode
91 * @throws AccessDeniedContentEditException
92 */
93 public function render() {
94 $this->inlineData = $this->data['inlineData'];
95
96 /** @var InlineStackProcessor $inlineStackProcessor */
97 $inlineStackProcessor = GeneralUtility::makeInstance(InlineStackProcessor::class);
98 $this->inlineStackProcessor = $inlineStackProcessor;
99 $inlineStackProcessor->initializeByGivenStructure($this->data['inlineStructure']);
100
101 $this->initHookObjects();
102
103 $row = $this->data['databaseRow'];
104 $parentUid = $row['uid'];
105 $record = $this->data['inlineRelatedRecordToRender'];
106 $config = $this->data['inlineRelatedRecordConfig'];
107
108 $foreign_table = $config['foreign_table'];
109 $foreign_selector = $config['foreign_selector'];
110 $resultArray = $this->initializeResultArray();
111
112 // Send a mapping information to the browser via JSON:
113 // e.g. data[<curTable>][<curId>][<curField>] => data-<pid>-<parentTable>-<parentId>-<parentField>-<curTable>-<curId>-<curField>
114 $formPrefix = $inlineStackProcessor->getCurrentStructureFormPrefix();
115 $domObjectId = $inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($this->data['inlineFirstPid']);
116 $this->inlineData['map'][$formPrefix] = $domObjectId;
117
118 $resultArray['inlineData'] = $this->inlineData;
119
120 // Set this variable if we handle a brand new unsaved record:
121 $isNewRecord = !MathUtility::canBeInterpretedAsInteger($record['uid']);
122 // Set this variable if the record is virtual and only show with header and not editable fields:
123 $isVirtualRecord = isset($record['__virtual']) && $record['__virtual'];
124 // If there is a selector field, normalize it:
125 if ($foreign_selector) {
126 $valueToNormalize = $record[$foreign_selector];
127 if (is_array($record[$foreign_selector])) {
128 // @todo: this can be kicked again if always prepared rows are handled here
129 $valueToNormalize = implode(',', $record[$foreign_selector]);
130 }
131 $record[$foreign_selector] = $this->normalizeUid($valueToNormalize);
132 }
133 if (!$this->checkAccess(($isNewRecord ? 'new' : 'edit'), $foreign_table, $record['uid'])) {
134 // This is caught by InlineControlContainer or FormEngine, they need to handle this case differently
135 // @todo: This is actually not the correct exception, but this code will vanish if inline data stuff is within provider
136 throw new AccessDeniedContentEditException('Access denied', 1437081986);
137 }
138 // Get the current naming scheme for DOM name/id attributes:
139 $appendFormFieldNames = '[' . $foreign_table . '][' . $record['uid'] . ']';
140 $objectId = $domObjectId . '-' . $foreign_table . '-' . $record['uid'];
141 $class = '';
142 $html = '';
143 $combinationHtml = '';
144 if (!$isVirtualRecord) {
145 // Get configuration:
146 $collapseAll = isset($config['appearance']['collapseAll']) && $config['appearance']['collapseAll'];
147 $expandAll = isset($config['appearance']['collapseAll']) && !$config['appearance']['collapseAll'];
148 $ajaxLoad = !isset($config['appearance']['ajaxLoad']) || $config['appearance']['ajaxLoad'];
149 if ($isNewRecord) {
150 // Show this record expanded or collapsed
151 $isExpanded = $expandAll || (!$collapseAll ? 1 : 0);
152 } else {
153 $isExpanded = $config['renderFieldsOnly'] || !$collapseAll && $this->getExpandedCollapsedState($foreign_table, $record['uid']) || $expandAll;
154 }
155 // Render full content ONLY IF this is an AJAX request, a new record, the record is not collapsed or AJAX loading is explicitly turned off
156 if ($isNewRecord || $isExpanded || !$ajaxLoad) {
157 $combinationChildArray = $this->renderCombinationTable($record, $appendFormFieldNames, $config);
158 $combinationHtml = $combinationChildArray['html'];
159 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $combinationChildArray);
160
161 $overruleTypesArray = isset($config['foreign_types']) ? $config['foreign_types'] : array();
162 $childArray = $this->renderRecord($foreign_table, $record, $overruleTypesArray);
163 $html = $childArray['html'];
164 $childArray['html'] = '';
165 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $childArray);
166
167 // Replace returnUrl in Wizard-Code, if this is an AJAX call
168 $ajaxArguments = GeneralUtility::_GP('ajax');
169 if (isset($ajaxArguments[2]) && trim($ajaxArguments[2]) != '') {
170 $html = str_replace('P[returnUrl]=%2F' . rawurlencode(TYPO3_mainDir) . 'ajax.php', 'P[returnUrl]=' . rawurlencode($ajaxArguments[2]), $html);
171 }
172 } else {
173 // This string is the marker for the JS-function to check if the full content has already been loaded
174 $html = '<!--notloaded-->';
175 }
176 if ($isNewRecord) {
177 // Get the top parent table
178 $top = $this->inlineStackProcessor->getStructureLevel(0);
179 $ucFieldName = 'uc[inlineView][' . $top['table'] . '][' . $top['uid'] . ']' . $appendFormFieldNames;
180 // Set additional fields for processing for saving
181 $html .= '<input type="hidden" name="data' . $appendFormFieldNames . '[pid]" value="' . $record['pid'] . '"/>';
182 $html .= '<input type="hidden" name="' . $ucFieldName . '" value="' . $isExpanded . '" />';
183 } else {
184 // Set additional field for processing for saving
185 $html .= '<input type="hidden" name="cmd' . $appendFormFieldNames . '[delete]" value="1" disabled="disabled" />';
186 if (!$isExpanded
187 && !empty($GLOBALS['TCA'][$foreign_table]['ctrl']['enablecolumns']['disabled'])
188 && $ajaxLoad
189 ) {
190 $checked = !empty($record['hidden']) ? ' checked="checked"' : '';
191 $html .= '<input type="checkbox" name="data' . $appendFormFieldNames . '[hidden]_0" value="1"' . $checked . ' />';
192 $html .= '<input type="input" name="data' . $appendFormFieldNames . '[hidden]" value="' . $record['hidden'] . '" />';
193 }
194 }
195 // If this record should be shown collapsed
196 $class = $isExpanded ? 'panel-visible' : 'panel-collapsed';
197 }
198 if ($config['renderFieldsOnly']) {
199 $html = $html . $combinationHtml;
200 } else {
201 // Set the record container with data for output
202 if ($isVirtualRecord) {
203 $class .= ' t3-form-field-container-inline-placeHolder';
204 }
205 if (isset($record['hidden']) && (int)$record['hidden']) {
206 $class .= ' t3-form-field-container-inline-hidden';
207 }
208 $class .= ($isNewRecord ? ' inlineIsNewRecord' : '');
209 $html = '
210 <div class="panel panel-default panel-condensed ' . trim($class) . '" id="' . $objectId . '_div">
211 <div class="panel-heading" data-toggle="formengine-inline" id="' . $objectId . '_header" data-expandSingle="' . ($config['appearance']['expandSingle'] ? 1 : 0) . '">
212 <div class="form-irre-header">
213 <div class="form-irre-header-cell form-irre-header-icon">
214 <span class="caret"></span>
215 </div>
216 ' . $this->renderForeignRecordHeader($parentUid, $foreign_table, $record, $config, $isVirtualRecord) . '
217 </div>
218 </div>
219 <div class="panel-collapse" id="' . $objectId . '_fields" data-expandSingle="' . ($config['appearance']['expandSingle'] ? 1 : 0) . '" data-returnURL="' . htmlspecialchars(GeneralUtility::getIndpEnv('REQUEST_URI')) . '">' . $html . $combinationHtml . '</div>
220 </div>';
221 }
222
223 $resultArray['html'] = $html;
224 return $resultArray;
225 }
226
227 /**
228 * Creates main container for foreign record and renders it
229 *
230 * @param string $table The table name
231 * @param array $row The record to be rendered
232 * @param array $overruleTypesArray Overrule TCA [types] array, e.g to override [showitem] configuration of a particular type
233 * @return string The rendered form
234 */
235 protected function renderRecord($table, array $row, array $overruleTypesArray = array()) {
236 $domObjectId = $this->inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($this->data['inlineFirstPid']);
237
238 $options = $this->data['tabAndInlineStack'];
239 $options['tabAndInlineStack'][] = array(
240 'inline',
241 $domObjectId . '-' . $table . '-' . $row['uid'],
242 );
243
244 $command = 'edit';
245 $vanillaUid = (int)$row['uid'];
246
247 // If dealing with a new record, take pid as vanillaUid and set command to new
248 if (!MathUtility::canBeInterpretedAsInteger($row['uid'])) {
249 $command = 'new';
250 $vanillaUid = (int)$row['pid'];
251 }
252
253 /** @var TcaDatabaseRecord $formDataGroup */
254 $formDataGroup = GeneralUtility::makeInstance(TcaDatabaseRecord::class);
255 /** @var FormDataCompiler $formDataCompiler */
256 $formDataCompiler = GeneralUtility::makeInstance(FormDataCompiler::class, $formDataGroup);
257 $formDataCompilerInput = [
258 'command' => $command,
259 'vanillaUid' => $vanillaUid,
260 'tableName' => $table,
261 'inlineData' => $this->inlineData,
262 'tabAndInlineStack' => $options['tabAndInlineStack'],
263 'overruleTypesArray' => $overruleTypesArray,
264 'inlineStructure' => $this->data['inlineStructure'],
265 ];
266 $options = $formDataCompiler->compile($formDataCompilerInput);
267 $options['renderType'] = 'fullRecordContainer';
268
269 // @todo: This hack merges data from already prepared row over fresh row again.
270 // @todo: This really must fall ...
271 foreach ($row as $field => $value) {
272 if ($command === 'new' && is_string($value) && $value !== '' && array_key_exists($field, $options['databaseRow'])) {
273 $options['databaseRow'][$field] = $value;
274 }
275 }
276
277 return $this->nodeFactory->create($options)->render();
278 }
279
280 /**
281 * Render a table with FormEngine, that occurs on an intermediate table but should be editable directly,
282 * so two tables are combined (the intermediate table with attributes and the sub-embedded table).
283 * -> This is a direct embedding over two levels!
284 *
285 * @param array $record The table record of the child/embedded table
286 * @param string $appendFormFieldNames The [<table>][<uid>] of the parent record (the intermediate table)
287 * @param array $config content of $PA['fieldConf']['config']
288 * @return array As defined in initializeResultArray() of AbstractNode
289 * @todo: Maybe create another container from this?
290 */
291 protected function renderCombinationTable($record, $appendFormFieldNames, $config = array()) {
292 $resultArray = $this->initializeResultArray();
293
294 $foreign_table = $config['foreign_table'];
295 $foreign_selector = $config['foreign_selector'];
296
297 if ($foreign_selector && $config['appearance']['useCombination']) {
298 $comboConfig = $GLOBALS['TCA'][$foreign_table]['columns'][$foreign_selector]['config'];
299 // If record does already exist, load it:
300 /** @var InlineRelatedRecordResolver $inlineRelatedRecordResolver */
301 $inlineRelatedRecordResolver = GeneralUtility::makeInstance(InlineRelatedRecordResolver::class);
302 if ($record[$foreign_selector] && MathUtility::canBeInterpretedAsInteger($record[$foreign_selector])) {
303 $comboRecord = $inlineRelatedRecordResolver->getRecord($comboConfig['foreign_table'], $record[$foreign_selector]);
304 $isNewRecord = FALSE;
305 } else {
306 $comboRecord = $inlineRelatedRecordResolver->getNewRecord($this->data['inlineFirstPid'], $comboConfig['foreign_table']);
307 $isNewRecord = TRUE;
308 }
309
310 // Display Warning FlashMessage if it is not suppressed
311 if (!isset($config['appearance']['suppressCombinationWarning']) || empty($config['appearance']['suppressCombinationWarning'])) {
312 $combinationWarningMessage = 'LLL:EXT:lang/locallang_core.xlf:warning.inline_use_combination';
313 if (!empty($config['appearance']['overwriteCombinationWarningMessage'])) {
314 $combinationWarningMessage = $config['appearance']['overwriteCombinationWarningMessage'];
315 }
316 $flashMessage = GeneralUtility::makeInstance(
317 FlashMessage::class,
318 $this->getLanguageService()->sL($combinationWarningMessage),
319 '',
320 FlashMessage::WARNING
321 );
322 $resultArray['html'] = $flashMessage->render();
323 }
324
325 // Get the FormEngine interpretation of the TCA of the child table
326 $childArray = $this->renderRecord($comboConfig['foreign_table'], $comboRecord);
327 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $childArray);
328
329 // If this is a new record, add a pid value to store this record and the pointer value for the intermediate table
330 if ($isNewRecord) {
331 $comboFormFieldName = 'data[' . $comboConfig['foreign_table'] . '][' . $comboRecord['uid'] . '][pid]';
332 $resultArray['html'] .= '<input type="hidden" name="' . $comboFormFieldName . '" value="' . $comboRecord['pid'] . '" />';
333 }
334 // If the foreign_selector field is also responsible for uniqueness, tell the browser the uid of the "other" side of the relation
335 if ($isNewRecord || $config['foreign_unique'] === $foreign_selector) {
336 $parentFormFieldName = 'data' . $appendFormFieldNames . '[' . $foreign_selector . ']';
337 $resultArray['html'] .= '<input type="hidden" name="' . $parentFormFieldName . '" value="' . $comboRecord['uid'] . '" />';
338 }
339 }
340 return $resultArray;
341 }
342
343 /**
344 * Renders the HTML header for a foreign record, such as the title, toggle-function, drag'n'drop, etc.
345 * Later on the command-icons are inserted here.
346 *
347 * @param string $parentUid The uid of the parent (embedding) record (uid or NEW...)
348 * @param string $foreign_table The foreign_table we create a header for
349 * @param array $rec The current record of that foreign_table
350 * @param array $config content of $PA['fieldConf']['config']
351 * @param bool $isVirtualRecord
352 * @return string The HTML code of the header
353 */
354 protected function renderForeignRecordHeader($parentUid, $foreign_table, $rec, $config, $isVirtualRecord = FALSE) {
355 // Init:
356 $domObjectId = $this->inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($this->data['inlineFirstPid']);
357 $objectId = $domObjectId . '-' . $foreign_table . '-' . $rec['uid'];
358 // 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)
359 // Pre-Processing:
360 $isOnSymmetricSide = RelationHandler::isOnSymmetricSide($parentUid, $config, $rec);
361 $hasForeignLabel = (bool)(!$isOnSymmetricSide && $config['foreign_label']);
362 $hasSymmetricLabel = (bool)$isOnSymmetricSide && $config['symmetric_label'];
363
364 // Get the record title/label for a record:
365 // Try using a self-defined user function only for formatted labels
366 if (isset($GLOBALS['TCA'][$foreign_table]['ctrl']['formattedLabel_userFunc'])) {
367 $params = array(
368 'table' => $foreign_table,
369 'row' => $rec,
370 'title' => '',
371 'isOnSymmetricSide' => $isOnSymmetricSide,
372 'options' => isset($GLOBALS['TCA'][$foreign_table]['ctrl']['formattedLabel_userFunc_options'])
373 ? $GLOBALS['TCA'][$foreign_table]['ctrl']['formattedLabel_userFunc_options']
374 : array(),
375 'parent' => array(
376 'uid' => $parentUid,
377 'config' => $config
378 )
379 );
380 // callUserFunction requires a third parameter, but we don't want to give $this as reference!
381 $null = NULL;
382 GeneralUtility::callUserFunction($GLOBALS['TCA'][$foreign_table]['ctrl']['formattedLabel_userFunc'], $params, $null);
383 $recTitle = $params['title'];
384
385 // Try using a normal self-defined user function
386 } elseif (isset($GLOBALS['TCA'][$foreign_table]['ctrl']['label_userFunc'])) {
387 $params = array(
388 'table' => $foreign_table,
389 'row' => $rec,
390 'title' => '',
391 'isOnSymmetricSide' => $isOnSymmetricSide,
392 'parent' => array(
393 'uid' => $parentUid,
394 'config' => $config
395 )
396 );
397 // callUserFunction requires a third parameter, but we don't want to give $this as reference!
398 $null = NULL;
399 GeneralUtility::callUserFunction($GLOBALS['TCA'][$foreign_table]['ctrl']['label_userFunc'], $params, $null);
400 $recTitle = $params['title'];
401 } elseif ($hasForeignLabel || $hasSymmetricLabel) {
402 $titleCol = $hasForeignLabel ? $config['foreign_label'] : $config['symmetric_label'];
403 $foreignConfig = FormEngineUtility::getInlinePossibleRecordsSelectorConfig($config, $titleCol);
404 // Render title for everything else than group/db:
405 if ($foreignConfig['type'] !== 'groupdb') {
406 $recTitle = BackendUtility::getProcessedValueExtra($foreign_table, $titleCol, $rec[$titleCol], 0, 0, FALSE);
407 } else {
408 // $recTitle could be something like: "tx_table_123|...",
409 $valueParts = GeneralUtility::trimExplode('|', $rec[$titleCol]);
410 $itemParts = GeneralUtility::revExplode('_', $valueParts[0], 2);
411 $recTemp = BackendUtility::getRecordWSOL($itemParts[0], $itemParts[1]);
412 $recTitle = BackendUtility::getRecordTitle($itemParts[0], $recTemp, FALSE);
413 }
414 $recTitle = BackendUtility::getRecordTitlePrep($recTitle);
415 if (trim($recTitle) === '') {
416 $recTitle = BackendUtility::getNoRecordTitle(TRUE);
417 }
418 } else {
419 $recTitle = BackendUtility::getRecordTitle($foreign_table, FormEngineUtility::databaseRowCompatibility($rec), TRUE);
420 }
421
422 $altText = BackendUtility::getRecordIconAltText($rec, $foreign_table);
423
424 $iconImg = '<span title="' . $altText . '" id="' . htmlspecialchars($objectId) . '_icon' . '">' . $this->iconFactory->getIconForRecord($foreign_table, $rec, Icon::SIZE_SMALL)->render() . '</span>';
425 $label = '<span id="' . $objectId . '_label">' . $recTitle . '</span>';
426 $ctrl = $this->renderForeignRecordHeaderControl($parentUid, $foreign_table, $rec, $config, $isVirtualRecord);
427 $thumbnail = FALSE;
428
429 // Renders a thumbnail for the header
430 if (!empty($config['appearance']['headerThumbnail']['field'])) {
431 $fieldValue = $rec[$config['appearance']['headerThumbnail']['field']];
432 $firstElement = array_shift(GeneralUtility::trimExplode(',', $fieldValue));
433 $fileUid = array_pop(BackendUtility::splitTable_Uid($firstElement));
434
435 if (!empty($fileUid)) {
436 $fileObject = ResourceFactory::getInstance()->getFileObject($fileUid);
437 if ($fileObject && $fileObject->isMissing()) {
438 $flashMessage = \TYPO3\CMS\Core\Resource\Utility\BackendUtility::getFlashMessageForMissingFile($fileObject);
439 $thumbnail = $flashMessage->render();
440 } elseif ($fileObject) {
441 $imageSetup = $config['appearance']['headerThumbnail'];
442 unset($imageSetup['field']);
443 if (!empty($rec['crop'])) {
444 $imageSetup['crop'] = $rec['crop'];
445 }
446 $imageSetup = array_merge(array('width' => '45', 'height' => '45c'), $imageSetup);
447 $processedImage = $fileObject->process(ProcessedFile::CONTEXT_IMAGECROPSCALEMASK, $imageSetup);
448 // Only use a thumbnail if the processing process was successful by checking if image width is set
449 if ($processedImage->getProperty('width')) {
450 $imageUrl = $processedImage->getPublicUrl(TRUE);
451 $thumbnail = '<img src="' . $imageUrl . '" ' .
452 'width="' . $processedImage->getProperty('width') . '" ' .
453 'height="' . $processedImage->getProperty('height') . '" ' .
454 'alt="' . htmlspecialchars($altText) . '" ' .
455 'title="' . htmlspecialchars($altText) . '">';
456 }
457 }
458 }
459 }
460
461 if (!empty($config['appearance']['headerThumbnail']['field']) && $thumbnail) {
462 $mediaContainer = '<div class="form-irre-header-cell form-irre-header-thumbnail" id="' . $objectId . '_thumbnailcontainer">' . $thumbnail . '</div>';
463 } else {
464 $mediaContainer = '<div class="form-irre-header-cell form-irre-header-icon" id="' . $objectId . '_iconcontainer">' . $iconImg . '</div>';
465 }
466 $header = $mediaContainer . '
467 <div class="form-irre-header-cell form-irre-header-body">' . $label . '</div>
468 <div class="form-irre-header-cell form-irre-header-control t3js-formengine-irre-control">' . $ctrl . '</div>';
469
470 return $header;
471 }
472
473 /**
474 * Render the control-icons for a record header (create new, sorting, delete, disable/enable).
475 * Most of the parts are copy&paste from TYPO3\CMS\Recordlist\RecordList\DatabaseRecordList and
476 * modified for the JavaScript calls here
477 *
478 * @param string $parentUid The uid of the parent (embedding) record (uid or NEW...)
479 * @param string $foreign_table The table (foreign_table) we create control-icons for
480 * @param array $rec The current record of that foreign_table
481 * @param array $config (modified) TCA configuration of the field
482 * @param bool $isVirtualRecord TRUE if the current record is virtual, FALSE otherwise
483 * @return string The HTML code with the control-icons
484 */
485 protected function renderForeignRecordHeaderControl($parentUid, $foreign_table, $rec, $config = array(), $isVirtualRecord = FALSE) {
486 $languageService = $this->getLanguageService();
487 $backendUser = $this->getBackendUserAuthentication();
488 // Initialize:
489 $cells = array();
490 $additionalCells = array();
491 $isNewItem = substr($rec['uid'], 0, 3) == 'NEW';
492 $isParentExisting = MathUtility::canBeInterpretedAsInteger($parentUid);
493 $tcaTableCtrl = &$GLOBALS['TCA'][$foreign_table]['ctrl'];
494 $tcaTableCols = &$GLOBALS['TCA'][$foreign_table]['columns'];
495 $isPagesTable = $foreign_table === 'pages';
496 $isSysFileReferenceTable = $foreign_table === 'sys_file_reference';
497 $isOnSymmetricSide = RelationHandler::isOnSymmetricSide($parentUid, $config, $rec);
498 $enableManualSorting = $tcaTableCtrl['sortby'] || $config['MM'] || !$isOnSymmetricSide && $config['foreign_sortby'] || $isOnSymmetricSide && $config['symmetric_sortby'];
499 $nameObject = $this->inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($this->data['inlineFirstPid']);
500 $nameObjectFt = $nameObject . '-' . $foreign_table;
501 $nameObjectFtId = $nameObjectFt . '-' . $rec['uid'];
502 $calcPerms = $backendUser->calcPerms(BackendUtility::readPageAccess($rec['pid'], $backendUser->getPagePermsClause(1)));
503 // If the listed table is 'pages' we have to request the permission settings for each page:
504 $localCalcPerms = FALSE;
505 if ($isPagesTable) {
506 $localCalcPerms = $backendUser->calcPerms(BackendUtility::getRecord('pages', $rec['uid']));
507 }
508 // This expresses the edit permissions for this particular element:
509 $permsEdit = $isPagesTable && $localCalcPerms & Permission::PAGE_EDIT || !$isPagesTable && $calcPerms & Permission::CONTENT_EDIT;
510 // Controls: Defines which controls should be shown
511 $enabledControls = $config['appearance']['enabledControls'];
512 // Hook: Can disable/enable single controls for specific child records:
513 foreach ($this->hookObjects as $hookObj) {
514 /** @var InlineElementHookInterface $hookObj */
515 $hookObj->renderForeignRecordHeaderControl_preProcess($parentUid, $foreign_table, $rec, $config, $isVirtualRecord, $enabledControls);
516 }
517 if (isset($rec['__create'])) {
518 $cells['localize.isLocalizable'] = '<span title="' . $languageService->sL('LLL:EXT:lang/locallang_misc.xlf:localize.isLocalizable', TRUE) . '">'
519 . $this->iconFactory->getIcon('actions-edit-localize-status-low', Icon::SIZE_SMALL)->render()
520 . '</span>';
521 } elseif (isset($rec['__remove'])) {
522 $cells['localize.wasRemovedInOriginal'] = '<span title="' . $languageService->sL('LLL:EXT:lang/locallang_misc.xlf:localize.wasRemovedInOriginal', TRUE) . '">'
523 . $this->iconFactory->getIcon('actions-edit-localize-status-high', Icon::SIZE_SMALL)->render()
524 . '</span>';
525 }
526 // "Info": (All records)
527 if ($enabledControls['info'] && !$isNewItem) {
528 if ($rec['table_local'] === 'sys_file') {
529 $uid = (int)substr($rec['uid_local'], 9);
530 $table = '_FILE';
531 } else {
532 $uid = $rec['uid'];
533 $table = $foreign_table;
534 }
535 $cells['info'] = '
536 <a class="btn btn-default" href="#" onclick="' . htmlspecialchars(('top.launchView(' . GeneralUtility::quoteJSvalue($table) . ', ' . GeneralUtility::quoteJSvalue($uid) . '); return false;')) . '" title="' . $languageService->sL('LLL:EXT:lang/locallang_mod_web_list.xlf:showInfo', TRUE) . '">
537 ' . $this->iconFactory->getIcon('actions-document-info', Icon::SIZE_SMALL)->render() . '
538 </a>';
539 }
540 // If the table is NOT a read-only table, then show these links:
541 if (!$tcaTableCtrl['readOnly'] && !$isVirtualRecord) {
542 // "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):
543 if ($enabledControls['new'] && ($enableManualSorting || $tcaTableCtrl['useColumnsForDefaultValues'])) {
544 if (!$isPagesTable && $calcPerms & Permission::CONTENT_EDIT || $isPagesTable && $calcPerms & Permission::PAGE_NEW) {
545 $onClick = 'return inline.createNewRecord(' . GeneralUtility::quoteJSvalue($nameObjectFt) . ',' . GeneralUtility::quoteJSvalue($rec['uid']) . ')';
546 $style = '';
547 if ($config['inline']['inlineNewButtonStyle']) {
548 $style = ' style="' . $config['inline']['inlineNewButtonStyle'] . '"';
549 }
550 $cells['new'] = '
551 <a class="btn btn-default inlineNewButton ' . $this->inlineData['config'][$nameObject]['md5'] . '" href="#" onclick="' . htmlspecialchars($onClick) . '" title="' . $languageService->sL(('LLL:EXT:lang/locallang_mod_web_list.xlf:new' . ($isPagesTable ? 'Page' : 'Record')), TRUE) . '" ' . $style . '>
552 ' . $this->iconFactory->getIcon('actions-' . ($isPagesTable ? 'page' : 'document') . '-new', Icon::SIZE_SMALL)->render() . '
553 </a>';
554 }
555 }
556 // "Up/Down" links
557 if ($enabledControls['sort'] && $permsEdit && $enableManualSorting) {
558 // Up
559 $onClick = 'return inline.changeSorting(' . GeneralUtility::quoteJSvalue($nameObjectFtId) . ', \'1\')';
560 $style = $config['inline']['first'] == $rec['uid'] ? 'style="visibility: hidden;"' : '';
561 $cells['sort.up'] = '
562 <a class="btn btn-default sortingUp" href="#" onclick="' . htmlspecialchars($onClick) . '" ' . $style . ' title="' . $languageService->sL('LLL:EXT:lang/locallang_mod_web_list.xlf:moveUp', TRUE) . '">
563 ' . $this->iconFactory->getIcon('actions-move-up', Icon::SIZE_SMALL)->render() . '
564 </a>';
565 // Down
566 $onClick = 'return inline.changeSorting(' . GeneralUtility::quoteJSvalue($nameObjectFtId) . ', \'-1\')';
567 $style = $config['inline']['last'] == $rec['uid'] ? 'style="visibility: hidden;"' : '';
568 $cells['sort.down'] = '
569 <a class="btn btn-default sortingDown" href="#" onclick="' . htmlspecialchars($onClick) . '" ' . $style . ' title="' . $languageService->sL('LLL:EXT:lang/locallang_mod_web_list.xlf:moveDown', TRUE) . '">
570 ' . $this->iconFactory->getIcon('actions-move-down', Icon::SIZE_SMALL)->render() . '
571 </a>';
572 }
573 // "Edit" link:
574 if (($rec['table_local'] === 'sys_file') && !$isNewItem) {
575 $sys_language_uid = 0;
576 if (!empty($rec['sys_language_uid'])) {
577 $sys_language_uid = $rec['sys_language_uid'][0];
578 }
579 $recordInDatabase = $this->getDatabaseConnection()->exec_SELECTgetSingleRow(
580 'uid',
581 'sys_file_metadata',
582 'file = ' . (int)substr($rec['uid_local'], 9) . ' AND sys_language_uid = ' . $sys_language_uid
583 );
584 if ($backendUser->check('tables_modify', 'sys_file_metadata')) {
585 $url = BackendUtility::getModuleUrl('record_edit', array(
586 'edit[sys_file_metadata][' . (int)$recordInDatabase['uid'] . ']' => 'edit'
587 ));
588 $editOnClick = 'if (top.content.list_frame) {' .
589 'top.content.list_frame.location.href=' .
590 GeneralUtility::quoteJSvalue($url . '&returnUrl=') .
591 '+top.rawurlencode(top.content.list_frame.document.location.pathname+top.content.list_frame.document.location.search)' .
592 ';' .
593 '}';
594 $title = $languageService->sL('LLL:EXT:lang/locallang_core.xlf:cm.editMetadata');
595 $cells['editmetadata'] = '
596 <a class="btn btn-default" href="#" class="btn" onclick="' . htmlspecialchars($editOnClick) . '" title="' . htmlspecialchars($title) . '">
597 ' . $this->iconFactory->getIcon('actions-document-open', Icon::SIZE_SMALL)->render() . '
598 </a>';
599 }
600 }
601 // "Delete" link:
602 if ($enabledControls['delete'] && ($isPagesTable && $localCalcPerms & Permission::PAGE_DELETE
603 || !$isPagesTable && $calcPerms & Permission::CONTENT_EDIT
604 || $isSysFileReferenceTable && $calcPerms & Permission::PAGE_EDIT)
605 ) {
606 $title = $languageService->sL('LLL:EXT:lang/locallang_mod_web_list.xlf:delete', TRUE);
607 $icon = $this->iconFactory->getIcon('actions-edit-delete', Icon::SIZE_SMALL)->render();
608 $cells['delete'] = '<a href="#" class="btn btn-default t3js-editform-delete-inline-record" data-objectid="' . htmlspecialchars($nameObjectFtId) . '" title="' . $title . '">' . $icon . '</a>';
609 }
610
611 // "Hide/Unhide" links:
612 $hiddenField = $tcaTableCtrl['enablecolumns']['disabled'];
613 if ($enabledControls['hide'] && $permsEdit && $hiddenField && $tcaTableCols[$hiddenField] && (!$tcaTableCols[$hiddenField]['exclude'] || $backendUser->check('non_exclude_fields', $foreign_table . ':' . $hiddenField))) {
614 $onClick = 'return inline.enableDisableRecord(' . GeneralUtility::quoteJSvalue($nameObjectFtId) . ')';
615 $className = 't3js-' . $nameObjectFtId . '_disabled';
616 if ($rec[$hiddenField]) {
617 $title = $languageService->sL(('LLL:EXT:lang/locallang_mod_web_list.xlf:unHide' . ($isPagesTable ? 'Page' : '')), TRUE);
618 $cells['hide.unhide'] = '
619 <a class="btn btn-default hiddenHandle ' . $className . '" href="#" onclick="'
620 . htmlspecialchars($onClick) . '"' . 'title="' . $title . '">' .
621 $this->iconFactory->getIcon('actions-edit-unhide', Icon::SIZE_SMALL)->render() . '
622 </a>';
623 } else {
624 $title = $languageService->sL(('LLL:EXT:lang/locallang_mod_web_list.xlf:hide' . ($isPagesTable ? 'Page' : '')), TRUE);
625 $cells['hide.hide'] = '
626 <a class="btn btn-default hiddenHandle ' . $className . '" href="#" onclick="'
627 . htmlspecialchars($onClick) . '"' . 'title="' . $title . '">' .
628 $this->iconFactory->getIcon('actions-edit-hide', Icon::SIZE_SMALL)->render() . '
629 </a>';
630 }
631 }
632 // Drag&Drop Sorting: Sortable handler for script.aculo.us
633 if ($enabledControls['dragdrop'] && $permsEdit && $enableManualSorting && $config['appearance']['useSortable']) {
634 $additionalCells['dragdrop'] = '
635 <span class="btn btn-default sortableHandle" data-id="' . htmlspecialchars($rec['uid']) . '" title="' . $languageService->sL('LLL:EXT:lang/locallang_core.xlf:labels.move', TRUE) . '">
636 ' . $this->iconFactory->getIcon('actions-move-move', Icon::SIZE_SMALL)->render() . '
637 </span>';
638 }
639 } elseif ($isVirtualRecord && $isParentExisting) {
640 if ($enabledControls['localize'] && isset($rec['__create'])) {
641 $onClick = 'inline.synchronizeLocalizeRecords(' . GeneralUtility::quoteJSvalue($nameObjectFt) . ', ' . GeneralUtility::quoteJSvalue($rec['uid']) . ');';
642 $cells['localize'] = '
643 <a class="btn btn-default" href="#" onclick="' . htmlspecialchars($onClick) . 'title="' . $languageService->sL('LLL:EXT:lang/locallang_misc.xlf:localize', TRUE) . '">
644 ' . $this->iconFactory->getIcon('actions-document-localize', Icon::SIZE_SMALL)->render() . '
645 </a>';
646 }
647 }
648 // If the record is edit-locked by another user, we will show a little warning sign:
649 if ($lockInfo = BackendUtility::isRecordLocked($foreign_table, $rec['uid'])) {
650 $cells['locked'] = '
651 <a class="btn btn-default" href="#" onclick="alert(' . GeneralUtility::quoteJSvalue($lockInfo['msg']) . ');return false;">
652 ' . '<span title="' . htmlspecialchars($lockInfo['msg']) . '">' . $this->iconFactory->getIcon('status-warning-in-use', Icon::SIZE_SMALL)->render() . '</span>' . '
653 </a>';
654 }
655 // Hook: Post-processing of single controls for specific child records:
656 foreach ($this->hookObjects as $hookObj) {
657 $hookObj->renderForeignRecordHeaderControl_postProcess($parentUid, $foreign_table, $rec, $config, $isVirtualRecord, $cells);
658 }
659
660 $out = '';
661 if (!empty($cells)) {
662 $out .= ' <div class="btn-group btn-group-sm" role="group">' . implode('', $cells) . '</div>';
663 }
664 if (!empty($additionalCells)) {
665 $out .= ' <div class="btn-group btn-group-sm" role="group">' . implode('', $additionalCells) . '</div>';
666 }
667 return $out;
668 }
669
670 /**
671 * Checks the page access rights (Code for access check mostly taken from alt_doc.php)
672 * as well as the table access rights of the user.
673 *
674 * @param string $cmd The command that should be performed ('new' or 'edit')
675 * @param string $table The table to check access for
676 * @param string $theUid The record uid of the table
677 * @return bool Returns TRUE is the user has access, or FALSE if not
678 */
679 protected function checkAccess($cmd, $table, $theUid) {
680 // @todo This should be within data provider
681 $backendUser = $this->getBackendUserAuthentication();
682 // 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...)
683 // First, resetting flags.
684 $hasAccess = FALSE;
685 // Admin users always have access:
686 if ($backendUser->isAdmin()) {
687 return TRUE;
688 }
689 // If the command is to create a NEW record...:
690 if ($cmd === 'new') {
691 // If the pid is numerical, check if it's possible to write to this page:
692 if (MathUtility::canBeInterpretedAsInteger($this->data['inlineFirstPid'])) {
693 $calcPRec = BackendUtility::getRecord('pages', $this->data['inlineFirstPid']);
694 if (!is_array($calcPRec)) {
695 return FALSE;
696 }
697 // Permissions for the parent page
698 $CALC_PERMS = $backendUser->calcPerms($calcPRec);
699 // If pages:
700 if ($table === 'pages') {
701 // Are we allowed to create new subpages?
702 $hasAccess = (bool)($CALC_PERMS & Permission::PAGE_NEW);
703 } else {
704 // Are we allowed to edit the page?
705 if ($table === 'sys_file_reference' && $this->isMediaOnPages($theUid)) {
706 $hasAccess = (bool)($CALC_PERMS & Permission::PAGE_EDIT);
707 }
708 if (!$hasAccess) {
709 // Are we allowed to edit content on this page?
710 $hasAccess = (bool)($CALC_PERMS & Permission::CONTENT_EDIT);
711 }
712 }
713 } else {
714 $hasAccess = TRUE;
715 }
716 } else {
717 // Edit:
718 $calcPRec = BackendUtility::getRecord($table, $theUid);
719 BackendUtility::fixVersioningPid($table, $calcPRec);
720 if (is_array($calcPRec)) {
721 // If pages:
722 if ($table === 'pages') {
723 $CALC_PERMS = $backendUser->calcPerms($calcPRec);
724 $hasAccess = (bool)($CALC_PERMS & Permission::PAGE_EDIT);
725 } else {
726 // Fetching pid-record first.
727 $CALC_PERMS = $backendUser->calcPerms(BackendUtility::getRecord('pages', $calcPRec['pid']));
728 if ($table === 'sys_file_reference' && $this->isMediaOnPages($theUid)) {
729 $hasAccess = (bool)($CALC_PERMS & Permission::PAGE_EDIT);
730 }
731 if (!$hasAccess) {
732 $hasAccess = (bool)($CALC_PERMS & Permission::CONTENT_EDIT);
733 }
734 }
735 // Check internals regarding access
736 $isRootLevelRestrictionIgnored = BackendUtility::isRootLevelRestrictionIgnored($table);
737 if ($hasAccess || (int)$calcPRec['pid'] === 0 && $isRootLevelRestrictionIgnored) {
738 $hasAccess = (bool)$backendUser->recordEditAccessInternals($table, $calcPRec);
739 }
740 }
741 }
742 if (!$backendUser->check('tables_modify', $table)) {
743 $hasAccess = FALSE;
744 }
745 if (
746 !empty($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['checkAccess'])
747 && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['checkAccess'])
748 ) {
749 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['checkAccess'] as $_funcRef) {
750 $_params = array(
751 'table' => $table,
752 'uid' => $theUid,
753 'cmd' => $cmd,
754 'hasAccess' => $hasAccess
755 );
756 $hasAccess = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
757 }
758 }
759 if (!$hasAccess) {
760 $deniedAccessReason = $backendUser->errorMsg;
761 if ($deniedAccessReason) {
762 debug($deniedAccessReason);
763 }
764 }
765 return $hasAccess;
766 }
767
768 /**
769 * Checks if a uid of a child table is in the inline view settings.
770 *
771 * @param string $table Name of the child table
772 * @param int $uid uid of the the child record
773 * @return bool TRUE=expand, FALSE=collapse
774 */
775 protected function getExpandedCollapsedState($table, $uid) {
776 $inlineView = $this->data['inlineExpandCollapseStateArray'];
777 // @todo Add checking/cleaning for unused tables, records, etc. to save space in uc-field
778 if (isset($inlineView[$table]) && is_array($inlineView[$table])) {
779 if (in_array($uid, $inlineView[$table]) !== FALSE) {
780 return TRUE;
781 }
782 }
783 return FALSE;
784 }
785
786 /**
787 * Normalize a relation "uid" published by transferData, like "1|Company%201"
788 *
789 * @param string $string A transferData reference string, containing the uid
790 * @return string The normalized uid
791 */
792 protected function normalizeUid($string) {
793 $parts = explode('|', $string);
794 return $parts[0];
795 }
796
797 /**
798 * Initialized the hook objects for this class.
799 * Each hook object has to implement the interface
800 * \TYPO3\CMS\Backend\Form\Element\InlineElementHookInterface
801 *
802 * @throws \UnexpectedValueException
803 * @return void
804 */
805 protected function initHookObjects() {
806 $this->hookObjects = array();
807 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['tceformsInlineHook'])) {
808 $tceformsInlineHook = &$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['tceformsInlineHook'];
809 if (is_array($tceformsInlineHook)) {
810 foreach ($tceformsInlineHook as $classData) {
811 $processObject = GeneralUtility::getUserObj($classData);
812 if (!$processObject instanceof InlineElementHookInterface) {
813 throw new \UnexpectedValueException('$processObject must implement interface ' . InlineElementHookInterface::class, 1202072000);
814 }
815 $this->hookObjects[] = $processObject;
816 }
817 }
818 }
819 }
820
821 /**
822 * Check if the record is a media element on a page.
823 *
824 * @param string $theUid Uid of the sys_file_reference record to be checked
825 * @return bool TRUE if the record has media in the column 'fieldname' and pages in the column 'tablenames'
826 */
827 protected function isMediaOnPages($theUid) {
828 if (StringUtility::beginsWith($theUid, 'NEW')) {
829 return TRUE;
830 }
831 $row = BackendUtility::getRecord('sys_file_reference', $theUid);
832 return ($row['fieldname'] === 'media') && ($row['tablenames'] === 'pages');
833 }
834
835 /**
836 * @return BackendUserAuthentication
837 */
838 protected function getBackendUserAuthentication() {
839 return $GLOBALS['BE_USER'];
840 }
841
842 /**
843 * @return DatabaseConnection
844 */
845 protected function getDatabaseConnection() {
846 return $GLOBALS['TYPO3_DB'];
847 }
848
849 /**
850 * @return LanguageService
851 */
852 protected function getLanguageService() {
853 return $GLOBALS['LANG'];
854 }
855
856 }