InlineRecordContainer.php 36.6 KB
Newer Older
Christian Kuhn's avatar
Christian Kuhn committed
1
<?php
2

Christian Kuhn's avatar
Christian Kuhn committed
3
4
5
6
7
8
9
10
11
12
13
14
15
/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

16
17
namespace TYPO3\CMS\Backend\Form\Container;

Christian Kuhn's avatar
Christian Kuhn committed
18
use TYPO3\CMS\Backend\Form\Element\InlineElementHookInterface;
19
use TYPO3\CMS\Backend\Form\Exception\AccessDeniedContentEditException;
20
use TYPO3\CMS\Backend\Form\InlineStackProcessor;
21
use TYPO3\CMS\Backend\Form\NodeFactory;
22
use TYPO3\CMS\Backend\Routing\UriBuilder;
Christian Kuhn's avatar
Christian Kuhn committed
23
use TYPO3\CMS\Backend\Utility\BackendUtility;
24
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
25
use TYPO3\CMS\Core\Database\ConnectionPool;
26
27
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Imaging\IconFactory;
28
use TYPO3\CMS\Core\Imaging\ImageManipulation\CropVariantCollection;
29
use TYPO3\CMS\Core\Localization\LanguageService;
Christian Kuhn's avatar
Christian Kuhn committed
30
31
use TYPO3\CMS\Core\Resource\ProcessedFile;
use TYPO3\CMS\Core\Resource\ResourceFactory;
32
use TYPO3\CMS\Core\Type\Bitmask\Permission;
Christian Kuhn's avatar
Christian Kuhn committed
33
use TYPO3\CMS\Core\Utility\GeneralUtility;
34
use TYPO3\CMS\Core\Utility\MathUtility;
35
use TYPO3\CMS\Core\Utility\PathUtility;
Christian Kuhn's avatar
Christian Kuhn committed
36
37
38
39
40
41
42
43
44
45
46

/**
 * Render a single inline record relation.
 *
 * This container is called by InlineControlContainer to render single existing records.
 * Furthermore it is called by FormEngine for an incoming ajax request to expand an existing record
 * or to create a new one.
 *
 * This container creates the outer HTML of single inline records - eg. drag and drop and delete buttons.
 * For rendering of the record itself processing is handed over to FullRecordContainer.
 */
47
48
49
50
51
52
53
class InlineRecordContainer extends AbstractContainer
{
    /**
     * Inline data array used for JSON output
     *
     * @var array
     */
54
    protected $inlineData = [];
55
56
57
58
59
60
61
62
63
64
65

    /**
     * @var InlineStackProcessor
     */
    protected $inlineStackProcessor;

    /**
     * Array containing instances of hook classes called once for IRRE objects
     *
     * @var array
     */
66
    protected $hookObjects = [];
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

    /**
     * @var IconFactory
     */
    protected $iconFactory;

    /**
     * Default constructor
     *
     * @param NodeFactory $nodeFactory
     * @param array $data
     */
    public function __construct(NodeFactory $nodeFactory, array $data)
    {
        parent::__construct($nodeFactory, $data);
        $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
83
84
        $this->inlineStackProcessor = GeneralUtility::makeInstance(InlineStackProcessor::class);
        $this->initHookObjects();
85
86
87
88
89
90
91
92
93
94
    }

    /**
     * Entry method
     *
     * @return array As defined in initializeResultArray() of AbstractNode
     * @throws AccessDeniedContentEditException
     */
    public function render()
    {
95
96
        $data = $this->data;
        $this->inlineData = $data['inlineData'];
97

98
99
        $inlineStackProcessor = $this->inlineStackProcessor;
        $inlineStackProcessor->initializeByGivenStructure($data['inlineStructure']);
100

101
102
103
        $record = $data['databaseRow'];
        $inlineConfig = $data['inlineParentConfig'];
        $foreignTable = $inlineConfig['foreign_table'];
104
105
106
107
108
109

        $resultArray = $this->initializeResultArray();

        // Send a mapping information to the browser via JSON:
        // e.g. data[<curTable>][<curId>][<curField>] => data-<pid>-<parentTable>-<parentId>-<parentField>-<curTable>-<curId>-<curField>
        $formPrefix = $inlineStackProcessor->getCurrentStructureFormPrefix();
110
        $domObjectId = $inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($data['inlineFirstPid']);
111
112
113
114
115
        $this->inlineData['map'][$formPrefix] = $domObjectId;

        $resultArray['inlineData'] = $this->inlineData;

        // Get the current naming scheme for DOM name/id attributes:
116
117
        $appendFormFieldNames = '[' . $foreignTable . '][' . $record['uid'] . ']';
        $objectId = $domObjectId . '-' . $foreignTable . '-' . $record['uid'];
118
        $classes = [];
119
120
        $html = '';
        $combinationHtml = '';
121
        $isNewRecord = $data['command'] === 'new';
122
123
124
125
        $hiddenField = '';
        if (isset($data['processedTca']['ctrl']['enablecolumns']['disabled'])) {
            $hiddenField = $data['processedTca']['ctrl']['enablecolumns']['disabled'];
        }
126
        if (!$data['isInlineDefaultLanguageRecordInLocalizedParentContext']) {
127
            if ($isNewRecord || $data['isInlineChildExpanded']) {
128
                // Render full content ONLY IF this is an AJAX request, a new record, or the record is not collapsed
129
                $combinationHtml = '';
130
131
                if (isset($data['combinationChild'])) {
                    $combinationChild = $this->renderCombinationChild($data, $appendFormFieldNames);
132
                    $combinationHtml = $combinationChild['html'];
133
                    $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $combinationChild, false);
134
                }
135
                $childArray = $this->renderChild($data);
136
                $html = $childArray['html'];
137
                $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $childArray, false);
138
            } else {
139
140
                // This class is the marker for the JS-function to check if the full content has already been loaded
                $classes[] = 't3js-not-loaded';
141
142
            }
            if ($isNewRecord) {
143
                // Add pid of record as hidden field
144
145
                $html .= '<input type="hidden" name="data' . htmlspecialchars($appendFormFieldNames)
                    . '[pid]" value="' . htmlspecialchars($record['pid']) . '"/>';
146
147
148
149
150
                // Tell DataHandler this record is expanded
                $ucFieldName = 'uc[inlineView]'
                    . '[' . $data['inlineTopMostParentTableName'] . ']'
                    . '[' . $data['inlineTopMostParentUid'] . ']'
                    . $appendFormFieldNames;
151
152
                $html .= '<input type="hidden" name="' . htmlspecialchars($ucFieldName)
                    . '" value="' . (int)$data['isInlineChildExpanded'] . '" />';
153
154
            } else {
                // Set additional field for processing for saving
155
156
                $html .= '<input type="hidden" name="cmd' . htmlspecialchars($appendFormFieldNames)
                    . '[delete]" value="1" disabled="disabled" />';
157
158
                if (!$data['isInlineChildExpanded'] && !empty($hiddenField)) {
                    $checked = !empty($record[$hiddenField]) ? ' checked="checked"' : '';
159
160
                    $html .= '<input type="checkbox" data-formengine-input-name="data'
                        . htmlspecialchars($appendFormFieldNames)
161
                        . '[' . htmlspecialchars($hiddenField) . ']" value="1"' . $checked . ' />';
162
                    $html .= '<input type="input" name="data' . htmlspecialchars($appendFormFieldNames)
163
                        . '[' . htmlspecialchars($hiddenField) . ']" value="' . htmlspecialchars($record[$hiddenField]) . '" />';
164
165
166
                }
            }
            // If this record should be shown collapsed
167
            $classes[] = $data['isInlineChildExpanded'] ? 'panel-visible' : 'panel-collapsed';
168
        }
169
170
        $hiddenFieldHtml = implode(LF, $resultArray['additionalHiddenFields'] ?? []);

171
        if ($inlineConfig['renderFieldsOnly'] ?? false) {
172
            // Render "body" part only
173
            $html .= $combinationHtml;
174
        } else {
175
176
            // Render header row and content (if expanded)
            if ($data['isInlineDefaultLanguageRecordInLocalizedParentContext']) {
177
                $classes[] = 't3-form-field-container-inline-placeHolder';
178
            }
179
            if (!empty($hiddenField) && isset($record[$hiddenField]) && (int)$record[$hiddenField]) {
180
181
182
183
                $classes[] = 't3-form-field-container-inline-hidden';
            }
            if ($isNewRecord) {
                $classes[] = 'inlineIsNewRecord';
184
            }
185

186
187
188
            $originalUniqueValue = '';
            if (isset($data['inlineData']['unique'][$domObjectId . '-' . $foreignTable]['used'][$record['uid']])) {
                $uniqueValueValues = $data['inlineData']['unique'][$domObjectId . '-' . $foreignTable]['used'][$record['uid']];
189
190
                // in case of site_language we don't have the full form engine options, so fallbacks need to be taken into account
                $originalUniqueValue = ($uniqueValueValues['table'] ?? $foreignTable) . '_' . ($uniqueValueValues['uid'] ?? $uniqueValueValues);
191
            }
192
193
194

            // The hashed object id needs a non-numeric prefix, the value is used as ID selector in JavaScript
            $hashedObjectId = 'hash-' . md5($objectId);
195
196
            $containerAttributes = [
                'id' => $objectId . '_div',
197
                'class' => 'form-irre-object panel panel-default panel-condensed ' . trim(implode(' ', $classes)),
198
199
                'data-object-uid' => $record['uid'],
                'data-object-id' => $objectId,
200
                'data-object-id-hash' => $hashedObjectId,
201
                'data-object-parent-group' => $domObjectId . '-' . $foreignTable,
202
203
204
                'data-field-name' => $appendFormFieldNames,
                'data-topmost-parent-table' => $data['inlineTopMostParentTableName'],
                'data-topmost-parent-uid' => $data['inlineTopMostParentUid'],
205
                'data-table-unique-original-value' => $originalUniqueValue,
206
                'data-placeholder-record' => $data['isInlineDefaultLanguageRecordInLocalizedParentContext'] ? '1' : '0'
207
208
            ];

209
            $ariaExpanded = ($data['isInlineChildExpanded'] ?? false) ? 'true' : 'false';
210
211
            $ariaControls = htmlspecialchars($objectId . '_fields', ENT_QUOTES | ENT_HTML5);
            $ariaAttributesString = 'aria-expanded="' . $ariaExpanded . '" aria-controls="' . $ariaControls . '"';
212
            $html = '
213
				<div ' . GeneralUtility::implodeAttributes($containerAttributes, true) . '>
214
					<div class="panel-heading" data-bs-toggle="formengine-inline" id="' . htmlspecialchars($hashedObjectId, ENT_QUOTES | ENT_HTML5) . '_header" data-expandSingle="' . (($inlineConfig['appearance']['expandSingle'] ?? false) ? 1 : 0) . '">
Christian Kuhn's avatar
Christian Kuhn committed
215
216
217
218
						<div class="form-irre-header">
							<div class="form-irre-header-cell form-irre-header-icon">
								<span class="caret"></span>
							</div>
219
							' . $this->renderForeignRecordHeader($data, $ariaAttributesString) . '
Christian Kuhn's avatar
Christian Kuhn committed
220
221
						</div>
					</div>
222
					<div class="panel-collapse" id="' . $ariaControls . '">' . $html . $hiddenFieldHtml . $combinationHtml . '</div>
Christian Kuhn's avatar
Christian Kuhn committed
223
				</div>';
224
225
226
227
228
229
230
231
232
        }

        $resultArray['html'] = $html;
        return $resultArray;
    }

    /**
     * Render inner child
     *
233
     * @param array $data
234
235
     * @return array Result array
     */
236
    protected function renderChild(array $data)
237
    {
238
239
        $domObjectId = $this->inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($data['inlineFirstPid']);
        $data['tabAndInlineStack'][] = [
240
            'inline',
241
            $domObjectId . '-' . $data['tableName'] . '-' . $data['databaseRow']['uid'],
242
243
        ];
        // @todo: ugly construct ...
244
245
246
        $data['inlineData'] = $this->inlineData;
        $data['renderType'] = 'fullRecordContainer';
        return $this->nodeFactory->create($data)->render();
247
248
249
250
251
252
253
254
255
    }

    /**
     * Render child child
     *
     * Render a table with FormEngine, that occurs on an intermediate table but should be editable directly,
     * so two tables are combined (the intermediate table with attributes and the sub-embedded table).
     * -> This is a direct embedding over two levels!
     *
256
     * @param array $data
257
258
259
     * @param string $appendFormFieldNames The [<table>][<uid>] of the parent record (the intermediate table)
     * @return array Result array
     */
260
    protected function renderCombinationChild(array $data, $appendFormFieldNames)
261
    {
262
263
        $childData = $data['combinationChild'];
        $parentConfig = $data['inlineParentConfig'];
264

265
266
267
268
269
270
271
        // If field is set to readOnly, set all fields of the relation to readOnly as well
        if (isset($parentConfig['readOnly']) && $parentConfig['readOnly']) {
            foreach ($childData['processedTca']['columns'] as $columnName => $columnConfiguration) {
                $childData['processedTca']['columns'][$columnName]['config']['readOnly'] = true;
            }
        }

272
273
274
275
        $resultArray = $this->initializeResultArray();

        // Display Warning FlashMessage if it is not suppressed
        if (!isset($parentConfig['appearance']['suppressCombinationWarning']) || empty($parentConfig['appearance']['suppressCombinationWarning'])) {
276
            $combinationWarningMessage = 'LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:warning.inline_use_combination';
277
278
279
            if (!empty($parentConfig['appearance']['overwriteCombinationWarningMessage'])) {
                $combinationWarningMessage = $parentConfig['appearance']['overwriteCombinationWarningMessage'];
            }
280
281
            $message = $this->getLanguageService()->sL($combinationWarningMessage);
            $markup = [];
282
283
            // @TODO: This is not a FlashMessage! The markup must be changed and special CSS
            // @TODO: should be created, in order to prevent confusion.
284
285
286
287
288
289
290
291
292
            $markup[] = '<div class="alert alert-warning">';
            $markup[] = '    <div class="media">';
            $markup[] = '        <div class="media-left">';
            $markup[] = '            <span class="fa-stack fa-lg">';
            $markup[] = '                <i class="fa fa-circle fa-stack-2x"></i>';
            $markup[] = '                <i class="fa fa-exclamation fa-stack-1x"></i>';
            $markup[] = '            </span>';
            $markup[] = '        </div>';
            $markup[] = '        <div class="media-body">';
293
            $markup[] = '            <div class="alert-message">' . htmlspecialchars($message) . '</div>';
294
295
296
297
            $markup[] = '        </div>';
            $markup[] = '    </div>';
            $markup[] = '</div>';
            $resultArray['html'] = implode(LF, $markup);
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
        }

        $childArray = $this->renderChild($childData);
        $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $childArray);

        // If this is a new record, add a pid value to store this record and the pointer value for the intermediate table
        if ($childData['command'] === 'new') {
            $comboFormFieldName = 'data[' . $childData['tableName'] . '][' . $childData['databaseRow']['uid'] . '][pid]';
            $resultArray['html'] .= '<input type="hidden" name="' . htmlspecialchars($comboFormFieldName) . '" value="' . htmlspecialchars($childData['databaseRow']['pid']) . '" />';
        }
        // If the foreign_selector field is also responsible for uniqueness, tell the browser the uid of the "other" side of the relation
        if ($childData['command'] === 'new' || $parentConfig['foreign_unique'] === $parentConfig['foreign_selector']) {
            $parentFormFieldName = 'data' . $appendFormFieldNames . '[' . $parentConfig['foreign_selector'] . ']';
            $resultArray['html'] .= '<input type="hidden" name="' . htmlspecialchars($parentFormFieldName) . '" value="' . htmlspecialchars($childData['databaseRow']['uid']) . '" />';
        }

        return $resultArray;
    }

    /**
     * Renders the HTML header for a foreign record, such as the title, toggle-function, drag'n'drop, etc.
     * Later on the command-icons are inserted here.
     *
     * @param array $data Current data
322
     * @param string $ariaAttributesString HTML aria attributes for the collapse button
323
324
     * @return string The HTML code of the header
     */
325
    protected function renderForeignRecordHeader(array $data, string $ariaAttributesString)
326
    {
327
328
329
        $languageService = $this->getLanguageService();
        $inlineConfig = $data['inlineParentConfig'];
        $foreignTable = $inlineConfig['foreign_table'];
330
331
        $rec = $data['databaseRow'];
        // Init:
332
333
334
335
        $domObjectId = $this->inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($data['inlineFirstPid']);
        $objectId = $domObjectId . '-' . $foreignTable . '-' . $rec['uid'];

        $recordTitle = $data['recordTitle'];
336
        if (!empty($recordTitle)) {
337
338
339
340
            // The user function may return HTML, therefore we can't escape it
            if (empty($data['processedTca']['ctrl']['formattedLabel_userFunc'])) {
                $recordTitle = BackendUtility::getRecordTitlePrep($recordTitle);
            }
341
        } else {
342
            $recordTitle = '<em>[' . htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.no_title')) . ']</em>';
343
344
        }

345
        $altText = BackendUtility::getRecordIconAltText($rec, $foreignTable);
346

347
        $iconImg = '<span title="' . $altText . '" id="' . htmlspecialchars($objectId) . '_icon">' . $this->iconFactory->getIconForRecord($foreignTable, $rec, Icon::SIZE_SMALL)->render() . '</span>';
348
349
        $label = '<span id="' . $objectId . '_label">' . $recordTitle . '</span>';
        $ctrl = $this->renderForeignRecordHeaderControl($data);
350
351
352
        $thumbnail = false;

        // Renders a thumbnail for the header
353
        if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails'] && !empty($inlineConfig['appearance']['headerThumbnail']['field'])) {
354
            $fieldValue = $rec[$inlineConfig['appearance']['headerThumbnail']['field']];
355
            $fileUid = $fieldValue[0]['uid'];
356
357

            if (!empty($fileUid)) {
358
                try {
359
                    $fileObject = GeneralUtility::makeInstance(ResourceFactory::class)->getFileObject($fileUid);
360
361
362
                } catch (\InvalidArgumentException $e) {
                    $fileObject = null;
                }
363
                if ($fileObject && $fileObject->isMissing()) {
364
                    $thumbnail .= '<span class="label label-danger">'
365
                        . htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:warning.file_missing'))
366
                        . '</span>&nbsp;' . htmlspecialchars($fileObject->getName()) . '<br />';
367
                } elseif ($fileObject) {
368
                    $imageSetup = $inlineConfig['appearance']['headerThumbnail'];
369
                    unset($imageSetup['field']);
370
371
372
                    $cropVariantCollection = CropVariantCollection::create($rec['crop'] ?? '');
                    if (!$cropVariantCollection->getCropArea()->isEmpty()) {
                        $imageSetup['crop'] = $cropVariantCollection->getCropArea()->makeAbsoluteBasedOnFile($fileObject);
373
                    }
374
                    $imageSetup = array_merge(['maxWidth' => '145', 'maxHeight' => '45'], $imageSetup);
375

376
                    if ($GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails'] && $fileObject->isImage()) {
377
                        $processedImage = $fileObject->process(ProcessedFile::CONTEXT_IMAGECROPSCALEMASK, $imageSetup);
378
379
                        // Only use a thumbnail if the processing process was successful by checking if image width is set
                        if ($processedImage->getProperty('width')) {
380
                            $imageUrl = $processedImage->getPublicUrl() ?? '';
381
                            $thumbnail = '<img src="' . PathUtility::getAbsoluteWebPath($imageUrl) . '" ' .
382
383
384
385
386
387
388
                                'width="' . $processedImage->getProperty('width') . '" ' .
                                'height="' . $processedImage->getProperty('height') . '" ' .
                                'alt="' . htmlspecialchars($altText) . '" ' .
                                'title="' . htmlspecialchars($altText) . '">';
                        }
                    } else {
                        $thumbnail = '';
389
390
391
392
393
                    }
                }
            }
        }

394
        if (!empty($inlineConfig['appearance']['headerThumbnail']['field']) && $thumbnail) {
395
            $mediaContainer = '<div class="form-irre-header-thumbnail" id="' . $objectId . '_thumbnailcontainer">' . $thumbnail . '</div>';
396
        } else {
397
            $mediaContainer = '<div class="form-irre-header-icon" id="' . $objectId . '_iconcontainer">' . $iconImg . '</div>';
398
        }
399
400
401
402
403
        $header = '<button class="form-irre-header-cell form-irre-header-button" ' . $ariaAttributesString . '>' .
            $mediaContainer .
            '<div class="form-irre-header-body">' . $label . '</div>' .
            '</button>' .
            '<div class="form-irre-header-cell form-irre-header-control t3js-formengine-irre-control">' . $ctrl . '</div>';
Christian Kuhn's avatar
Christian Kuhn committed
404

405
406
407
408
409
410
411
412
413
414
415
        return $header;
    }

    /**
     * Render the control-icons for a record header (create new, sorting, delete, disable/enable).
     * Most of the parts are copy&paste from TYPO3\CMS\Recordlist\RecordList\DatabaseRecordList and
     * modified for the JavaScript calls here
     *
     * @param array $data Current data
     * @return string The HTML code with the control-icons
     */
416
    protected function renderForeignRecordHeaderControl(array $data)
417
418
    {
        $rec = $data['databaseRow'];
419
420
421
422
423
        $rec += [
            'uid' => 0,
            'table_local' => '',
            'sys_language_uid' => '',
        ];
424
425
        $inlineConfig = $data['inlineParentConfig'];
        $foreignTable = $inlineConfig['foreign_table'];
426
427
428
        $languageService = $this->getLanguageService();
        $backendUser = $this->getBackendUserAuthentication();
        // Initialize:
429
430
431
432
433
434
435
436
437
438
439
440
        $cells = [
            'edit' => '',
            'hide' => '',
            'delete' => '',
            'info' => '',
            'new' => '',
            'sort.up' => '',
            'sort.down' => '',
            'dragdrop' => '',
            'localize' => '',
            'locked' => '',
        ];
441
        $isNewItem = strpos($rec['uid'], 'NEW') === 0;
442
        $isParentReadOnly = isset($inlineConfig['readOnly']) && $inlineConfig['readOnly'];
443
        $isParentExisting = MathUtility::canBeInterpretedAsInteger($data['inlineParentUid']);
444
445
        $tcaTableCtrl = $GLOBALS['TCA'][$foreignTable]['ctrl'];
        $tcaTableCols = $GLOBALS['TCA'][$foreignTable]['columns'];
446
447
        $isPagesTable = $foreignTable === 'pages';
        $isSysFileReferenceTable = $foreignTable === 'sys_file_reference';
448
449
450
451
        $enableManualSorting = ($tcaTableCtrl['sortby'] ?? false)
            || ($inlineConfig['MM'] ?? false)
            || (!($data['isOnSymmetricSide'] ?? false) && ($inlineConfig['foreign_sortby'] ?? false))
            || (($data['isOnSymmetricSide'] ?? false) && ($inlineConfig['symmetric_sortby'] ?? false));
452
        $calcPerms = new Permission($backendUser->calcPerms(BackendUtility::readPageAccess((int)($data['parentPageRow']['uid'] ?? 0), $backendUser->getPagePermsClause(Permission::PAGE_SHOW))));
453
        // If the listed table is 'pages' we have to request the permission settings for each page:
454
        $localCalcPerms = new Permission(Permission::NOTHING);
455
        if ($isPagesTable) {
456
            $localCalcPerms = new Permission($backendUser->calcPerms(BackendUtility::getRecord('pages', $rec['uid'])));
457
458
        }
        // This expresses the edit permissions for this particular element:
459
        $permsEdit = ($isPagesTable && $localCalcPerms->editPagePermissionIsGranted()) || (!$isPagesTable && $calcPerms->editContentPermissionIsGranted());
460
        // Controls: Defines which controls should be shown
461
        $enabledControls = $inlineConfig['appearance']['enabledControls'];
462
463
464
        // Hook: Can disable/enable single controls for specific child records:
        foreach ($this->hookObjects as $hookObj) {
            /** @var InlineElementHookInterface $hookObj */
465
            $hookObj->renderForeignRecordHeaderControl_preProcess($data['inlineParentUid'], $foreignTable, $rec, $inlineConfig, $data['isInlineDefaultLanguageRecordInLocalizedParentContext'], $enabledControls);
466
        }
467
        if ($data['isInlineDefaultLanguageRecordInLocalizedParentContext']) {
468
            $cells['localize'] = '<span title="' . htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_misc.xlf:localize.isLocalizable')) . '">
469
470
                    ' . $this->iconFactory->getIcon('actions-edit-localize-status-low', Icon::SIZE_SMALL)->render() . '
                </span>';
471
472
        }
        // "Info": (All records)
473
474
475
476
477
478
479
480
        // @todo: hardcoded sys_file!
        if ($rec['table_local'] === 'sys_file') {
            $uid = $rec['uid_local'][0]['uid'];
            $table = '_FILE';
        } else {
            $uid = $rec['uid'];
            $table = $foreignTable;
        }
481
482
483
484
485
        if ($enabledControls['info']) {
            if ($isNewItem) {
                $cells['info'] = '<span class="btn btn-default disabled">' . $this->iconFactory->getIcon('empty-empty', Icon::SIZE_SMALL)->render() . '</span>';
            } else {
                $cells['info'] = '
486
				<button type="button" class="btn btn-default" data-action="infowindow" data-info-table="' . htmlspecialchars($table) . '" data-info-uid="' . htmlspecialchars($uid) . '" title="' . htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_mod_web_list.xlf:showInfo')) . '">
487
					' . $this->iconFactory->getIcon('actions-document-info', Icon::SIZE_SMALL)->render() . '
488
				</button>';
489
            }
490
491
        }
        // If the table is NOT a read-only table, then show these links:
492
        if (!$isParentReadOnly && !($tcaTableCtrl['readOnly'] ?? false) && !($data['isInlineDefaultLanguageRecordInLocalizedParentContext'] ?? false)) {
493
494
            // "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):
            if ($enabledControls['new'] && ($enableManualSorting || $tcaTableCtrl['useColumnsForDefaultValues'])) {
495
                if ((!$isPagesTable && $calcPerms->editContentPermissionIsGranted()) || ($isPagesTable && $calcPerms->createPagePermissionIsGranted())) {
496
                    $style = '';
497
                    if ($inlineConfig['inline']['inlineNewButtonStyle'] ?? false) {
498
                        $style = ' style="' . $inlineConfig['inline']['inlineNewButtonStyle'] . '"';
499
500
                    }
                    $cells['new'] = '
501
                        <button type="button" class="btn btn-default t3js-create-new-button" data-record-uid="' . htmlspecialchars($rec['uid']) . '" title="' . htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_mod_web_list.xlf:new' . ($isPagesTable ? 'Page' : 'Record'))) . '" ' . $style . '>
502
                            ' . $this->iconFactory->getIcon('actions-' . ($isPagesTable ? 'page-new' : 'add'), Icon::SIZE_SMALL)->render() . '
503
                        </button>';
504
505
506
507
508
                }
            }
            // "Up/Down" links
            if ($enabledControls['sort'] && $permsEdit && $enableManualSorting) {
                // Up
509
510
511
512
513
514
                $icon = 'actions-move-up';
                $class = '';
                if ($inlineConfig['inline']['first'] == $rec['uid']) {
                    $class = ' disabled';
                    $icon = 'empty-empty';
                }
515
                $cells['sort.up'] = '
516
                    <button type="button" class="btn btn-default' . $class . '" data-action="sort" data-direction="up" title="' . htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_mod_web_list.xlf:moveUp')) . '">
517
                        ' . $this->iconFactory->getIcon($icon, Icon::SIZE_SMALL)->render() . '
518
                    </button>';
519
                // Down
520
521
522
523
524
525
526
                $icon = 'actions-move-down';
                $class = '';
                if ($inlineConfig['inline']['last'] == $rec['uid']) {
                    $class = ' disabled';
                    $icon = 'empty-empty';
                }

527
                $cells['sort.down'] = '
528
                    <button type="button" class="btn btn-default' . $class . '" data-action="sort" data-direction="down" title="' . htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_mod_web_list.xlf:moveDown')) . '">
529
                        ' . $this->iconFactory->getIcon($icon, Icon::SIZE_SMALL)->render() . '
530
                    </button>';
531
532
            }
            // "Edit" link:
533
            if (($rec['table_local'] === 'sys_file') && !$isNewItem && $backendUser->check('tables_modify', 'sys_file_metadata')) {
534
535
536
537
                $sys_language_uid = 0;
                if (!empty($rec['sys_language_uid'])) {
                    $sys_language_uid = $rec['sys_language_uid'][0];
                }
538
539
540
541
542
543
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
                    ->getQueryBuilderForTable('sys_file_metadata');
                $recordInDatabase = $queryBuilder
                    ->select('uid')
                    ->from('sys_file_metadata')
                    ->where(
544
545
                        $queryBuilder->expr()->eq(
                            'file',
546
                            $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)
547
548
549
550
551
                        ),
                        $queryBuilder->expr()->eq(
                            'sys_language_uid',
                            $queryBuilder->createNamedParameter($sys_language_uid, \PDO::PARAM_INT)
                        )
552
553
554
555
                    )
                    ->setMaxResults(1)
                    ->execute()
                    ->fetch();
556
                if (!empty($recordInDatabase)) {
557
                    $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
558
                    $url = (string)$uriBuilder->buildUriFromRoute('record_edit', [
559
                        'edit[sys_file_metadata][' . (int)$recordInDatabase['uid'] . ']' => 'edit',
560
                        'returnUrl' => $this->data['returnUrl']
561
                    ]);
562
                    $title = $languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:cm.editMetadata');
563
564
565
566
                    $cells['edit'] = '
                        <a class="btn btn-default" href="' . htmlspecialchars($url) . '" title="' . htmlspecialchars($title) . '">
                            ' . $this->iconFactory->getIcon('actions-open', Icon::SIZE_SMALL)->render() . '
                        </a>';
567
568
569
                }
            }
            // "Delete" link:
570
571
572
            if ($enabledControls['delete'] && (($isPagesTable && $localCalcPerms->deletePagePermissionIsGranted())
                    || (!$isPagesTable && $calcPerms->editContentPermissionIsGranted())
                    || ($isSysFileReferenceTable && $calcPerms->editPagePermissionIsGranted()))
573
            ) {
574
                $title = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_mod_web_list.xlf:delete'));
575
                $icon = $this->iconFactory->getIcon('actions-edit-delete', Icon::SIZE_SMALL)->render();
576
                $cells['delete'] = '<button type="button" class="btn btn-default t3js-editform-delete-inline-record" title="' . $title . '">' . $icon . '</button>';
577
578
579
            }

            // "Hide/Unhide" links:
580
581
582
583
584
585
586
            $hiddenField = $tcaTableCtrl['enablecolumns']['disabled'] ?? '';
            if (($enabledControls['hide'] ?? false)
                && $permsEdit
                && $hiddenField
                && $tcaTableCols[$hiddenField]
                && (!($tcaTableCols[$hiddenField]['exclude'] ?? false) || $backendUser->check('non_exclude_fields', $foreignTable . ':' . $hiddenField))
            ) {
587
                if ($rec[$hiddenField]) {
588
                    $title = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_mod_web_list.xlf:unHide' . ($isPagesTable ? 'Page' : '')));
589
                    $cells['hide'] = '
590
                        <button type="button" class="btn btn-default t3js-toggle-visibility-button" data-hidden-field="' . htmlspecialchars($hiddenField) . '" title="' . $title . '">
591
                            ' . $this->iconFactory->getIcon('actions-edit-unhide', Icon::SIZE_SMALL)->render() . '
592
                        </button>';
593
                } else {
594
                    $title = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_mod_web_list.xlf:hide' . ($isPagesTable ? 'Page' : '')));
595
                    $cells['hide'] = '
596
                        <button type="button" class="btn btn-default t3js-toggle-visibility-button" data-hidden-field="' . htmlspecialchars($hiddenField) . '" title="' . $title . '">
597
                            ' . $this->iconFactory->getIcon('actions-edit-hide', Icon::SIZE_SMALL)->render() . '
598
                        </button>';
599
600
601
                }
            }
            // Drag&Drop Sorting: Sortable handler for script.aculo.us
602
            if (($enabledControls['dragdrop'] ?? false) && $permsEdit && $enableManualSorting && ($inlineConfig['appearance']['useSortable'] ?? false)) {
603
                $cells['dragdrop'] = '
604
                    <span class="btn btn-default sortableHandle" data-id="' . htmlspecialchars($rec['uid']) . '" title="' . htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.move')) . '">
605
606
                        ' . $this->iconFactory->getIcon('actions-move-move', Icon::SIZE_SMALL)->render() . '
                    </span>';
607
            }
608
609
        } elseif (($data['isInlineDefaultLanguageRecordInLocalizedParentContext'] ?? false) && $isParentExisting) {
            if (($enabledControls['localize'] ?? false) && ($data['isInlineDefaultLanguageRecordInLocalizedParentContext'] ?? false)) {
610
                $cells['localize'] = '
611
                    <button type="button" class="btn btn-default t3js-synchronizelocalize-button" data-type="' . htmlspecialchars($rec['uid']) . '" title="' . htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_misc.xlf:localize')) . '">
612
                        ' . $this->iconFactory->getIcon('actions-document-localize', Icon::SIZE_SMALL)->render() . '
613
                    </button>';
614
615
616
            }
        }
        // If the record is edit-locked by another user, we will show a little warning sign:
617
        if ($lockInfo = BackendUtility::isRecordLocked($foreignTable, $rec['uid'])) {
618
            $cells['locked'] = '
619
620
				<button type="button" class="btn btn-default" data-bs-toggle="tooltip" title="' . htmlspecialchars($lockInfo['msg']) . '">
					' . $this->iconFactory->getIcon('warning-in-use', Icon::SIZE_SMALL)->render() . '
621
				</button>';
622
623
624
        }
        // Hook: Post-processing of single controls for specific child records:
        foreach ($this->hookObjects as $hookObj) {
625
            $hookObj->renderForeignRecordHeaderControl_postProcess($data['inlineParentUid'], $foreignTable, $rec, $inlineConfig, $data['isInlineDefaultLanguageRecordInLocalizedParentContext'], $cells);
626
627
628
        }

        $out = '';
629
630
631
632
633
634
635
636
637
638
639
640
        if (!empty($cells['edit']) || !empty($cells['hide']) || !empty($cells['delete'])) {
            $out .= '<div class="btn-group btn-group-sm" role="group">' . $cells['edit'] . $cells['hide'] . $cells['delete'] . '</div>';
            unset($cells['edit'], $cells['hide'], $cells['delete']);
        }
        if (!empty($cells['info']) || !empty($cells['new']) || !empty($cells['sort.up']) || !empty($cells['sort.down']) || !empty($cells['dragdrop'])) {
            $out .= '<div class="btn-group btn-group-sm" role="group">' . $cells['info'] . $cells['new'] . $cells['sort.up'] . $cells['sort.down'] . $cells['dragdrop'] . '</div>';
            unset($cells['info'], $cells['new'], $cells['sort.up'], $cells['sort.down'], $cells['dragdrop']);
        }
        if (!empty($cells['localize'])) {
            $out .= '<div class="btn-group btn-group-sm" role="group">' . $cells['localize'] . '</div>';
            unset($cells['localize']);
        }
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
        if (!empty($cells)) {
            $out .= ' <div class="btn-group btn-group-sm" role="group">' . implode('', $cells) . '</div>';
        }
        return $out;
    }

    /**
     * Initialized the hook objects for this class.
     * Each hook object has to implement the interface
     * \TYPO3\CMS\Backend\Form\Element\InlineElementHookInterface
     *
     * @throws \UnexpectedValueException
     */
    protected function initHookObjects()
    {
656
        $this->hookObjects = [];
657
658
659
660
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tceforms_inline.php']['tceformsInlineHook'] ?? [] as $className) {
            $processObject = GeneralUtility::makeInstance($className);
            if (!$processObject instanceof InlineElementHookInterface) {
                throw new \UnexpectedValueException($className . ' must implement interface ' . InlineElementHookInterface::class, 1202072000);
661
            }
662
            $this->hookObjects[] = $processObject;
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
        }
    }

    /**
     * @return BackendUserAuthentication
     */
    protected function getBackendUserAuthentication()
    {
        return $GLOBALS['BE_USER'];
    }

    /**
     * @return LanguageService
     */
    protected function getLanguageService()
    {
        return $GLOBALS['LANG'];
    }
Christian Kuhn's avatar
Christian Kuhn committed
681
}