InlineRecordContainer.php 37.1 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:
crell's avatar
crell committed
116
117
        $appendFormFieldNames = '[' . $foreignTable . '][' . ($record['uid'] ?? 0) . ']';
        $objectId = $domObjectId . '-' . $foreignTable . '-' . ($record['uid'] ?? 0);
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
            $originalUniqueValue = '';
crell's avatar
crell committed
187
            if (isset($record['uid'], $data['inlineData']['unique'][$domObjectId . '-' . $foreignTable]['used'][$record['uid']])) {
188
                $uniqueValueValues = $data['inlineData']['unique'][$domObjectId . '-' . $foreignTable]['used'][$record['uid']];
189
                // in case of site_language we don't have the full form engine options, so fallbacks need to be taken into account
crell's avatar
crell committed
190
191
192
193
194
195
196
197
                $originalUniqueValue = ($uniqueValueValues['table'] ?? $foreignTable) . '_';
                // @todo In what circumstance would $uniqueValueValues be an array that lacks a 'uid' key? Unclear, but
                // it breaks the string concatenation. This is a hacky workaround for type safety only.
                $uVV = ($uniqueValueValues['uid'] ?? $uniqueValueValues);
                if (is_array($uVV)) {
                    $uVV = implode(',', $uVV);
                }
                $originalUniqueValue .= $uVV;
198
            }
199
200
201

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

216
            $ariaExpanded = ($data['isInlineChildExpanded'] ?? false) ? 'true' : 'false';
217
218
            $ariaControls = htmlspecialchars($objectId . '_fields', ENT_QUOTES | ENT_HTML5);
            $ariaAttributesString = 'aria-expanded="' . $ariaExpanded . '" aria-controls="' . $ariaControls . '"';
219
            $html = '
220
				<div ' . GeneralUtility::implodeAttributes($containerAttributes, true) . '>
221
					<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
222
223
224
225
						<div class="form-irre-header">
							<div class="form-irre-header-cell form-irre-header-icon">
								<span class="caret"></span>
							</div>
226
							' . $this->renderForeignRecordHeader($data, $ariaAttributesString) . '
Christian Kuhn's avatar
Christian Kuhn committed
227
228
						</div>
					</div>
229
					<div class="panel-collapse" id="' . $ariaControls . '">' . $html . $hiddenFieldHtml . $combinationHtml . '</div>
Christian Kuhn's avatar
Christian Kuhn committed
230
				</div>';
231
232
233
234
235
236
237
238
239
        }

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

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

    /**
     * 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!
     *
263
     * @param array $data
264
265
266
     * @param string $appendFormFieldNames The [<table>][<uid>] of the parent record (the intermediate table)
     * @return array Result array
     */
267
    protected function renderCombinationChild(array $data, $appendFormFieldNames)
268
    {
269
270
        $childData = $data['combinationChild'];
        $parentConfig = $data['inlineParentConfig'];
271

272
273
274
275
276
277
278
        // 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;
            }
        }

279
280
281
282
        $resultArray = $this->initializeResultArray();

        // Display Warning FlashMessage if it is not suppressed
        if (!isset($parentConfig['appearance']['suppressCombinationWarning']) || empty($parentConfig['appearance']['suppressCombinationWarning'])) {
283
            $combinationWarningMessage = 'LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:warning.inline_use_combination';
284
285
286
            if (!empty($parentConfig['appearance']['overwriteCombinationWarningMessage'])) {
                $combinationWarningMessage = $parentConfig['appearance']['overwriteCombinationWarningMessage'];
            }
287
288
            $message = $this->getLanguageService()->sL($combinationWarningMessage);
            $markup = [];
289
290
            // @TODO: This is not a FlashMessage! The markup must be changed and special CSS
            // @TODO: should be created, in order to prevent confusion.
291
292
293
294
295
296
297
298
299
            $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">';
300
            $markup[] = '            <div class="alert-message">' . htmlspecialchars($message) . '</div>';
301
302
303
304
            $markup[] = '        </div>';
            $markup[] = '    </div>';
            $markup[] = '</div>';
            $resultArray['html'] = implode(LF, $markup);
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
        }

        $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
329
     * @param string $ariaAttributesString HTML aria attributes for the collapse button
330
331
     * @return string The HTML code of the header
     */
332
    protected function renderForeignRecordHeader(array $data, string $ariaAttributesString)
333
    {
334
335
336
        $languageService = $this->getLanguageService();
        $inlineConfig = $data['inlineParentConfig'];
        $foreignTable = $inlineConfig['foreign_table'];
337
338
        $rec = $data['databaseRow'];
        // Init:
339
        $domObjectId = $this->inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($data['inlineFirstPid']);
crell's avatar
crell committed
340
        $objectId = $domObjectId . '-' . $foreignTable . '-' . ($rec['uid'] ?? 0);
341
342

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

352
        $altText = BackendUtility::getRecordIconAltText($rec, $foreignTable);
353

354
        $iconImg = '<span title="' . $altText . '" id="' . htmlspecialchars($objectId) . '_icon">' . $this->iconFactory->getIconForRecord($foreignTable, $rec, Icon::SIZE_SMALL)->render() . '</span>';
355
356
        $label = '<span id="' . $objectId . '_label">' . $recordTitle . '</span>';
        $ctrl = $this->renderForeignRecordHeaderControl($data);
357
358
359
        $thumbnail = false;

        // Renders a thumbnail for the header
crell's avatar
crell committed
360
        if (($GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails'] ?? false) && !empty($inlineConfig['appearance']['headerThumbnail']['field'])) {
361
            $fieldValue = $rec[$inlineConfig['appearance']['headerThumbnail']['field']];
362
            $fileUid = $fieldValue[0]['uid'];
363
364

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

crell's avatar
crell committed
383
                    if (($GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails'] ?? false) && $fileObject->isImage()) {
384
                        $processedImage = $fileObject->process(ProcessedFile::CONTEXT_IMAGECROPSCALEMASK, $imageSetup);
385
386
                        // Only use a thumbnail if the processing process was successful by checking if image width is set
                        if ($processedImage->getProperty('width')) {
387
                            $imageUrl = $processedImage->getPublicUrl() ?? '';
388
                            $thumbnail = '<img src="' . PathUtility::getAbsoluteWebPath($imageUrl) . '" ' .
389
390
391
392
393
394
395
                                'width="' . $processedImage->getProperty('width') . '" ' .
                                'height="' . $processedImage->getProperty('height') . '" ' .
                                'alt="' . htmlspecialchars($altText) . '" ' .
                                'title="' . htmlspecialchars($altText) . '">';
                        }
                    } else {
                        $thumbnail = '';
396
397
398
399
400
                    }
                }
            }
        }

401
        if (!empty($inlineConfig['appearance']['headerThumbnail']['field']) && $thumbnail) {
402
            $mediaContainer = '<div class="form-irre-header-thumbnail" id="' . $objectId . '_thumbnailcontainer">' . $thumbnail . '</div>';
403
        } else {
404
            $mediaContainer = '<div class="form-irre-header-icon" id="' . $objectId . '_iconcontainer">' . $iconImg . '</div>';
405
        }
406
407
408
409
410
        $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
411

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

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

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

        $out = '';
636
637
638
639
640
641
642
643
644
645
646
647
        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']);
        }
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
        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()
    {
663
        $this->hookObjects = [];
664
665
666
667
        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);
668
            }
669
            $this->hookObjects[] = $processObject;
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
        }
    }

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

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