InlineControlContainer.php 33.9 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;

18
use TYPO3\CMS\Backend\Form\InlineStackProcessor;
19
use TYPO3\CMS\Backend\Form\NodeFactory;
Christian Kuhn's avatar
Christian Kuhn committed
20
use TYPO3\CMS\Backend\Utility\BackendUtility;
21
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
22
23
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Imaging\IconFactory;
24
use TYPO3\CMS\Core\Localization\LanguageService;
Christian Kuhn's avatar
Christian Kuhn committed
25
use TYPO3\CMS\Core\Resource\Folder;
26
use TYPO3\CMS\Core\Resource\OnlineMedia\Helpers\OnlineMediaHelperRegistry;
Christian Kuhn's avatar
Christian Kuhn committed
27
use TYPO3\CMS\Core\Utility\GeneralUtility;
28
use TYPO3\CMS\Core\Utility\MathUtility;
29
use TYPO3\CMS\Core\Utility\StringUtility;
Christian Kuhn's avatar
Christian Kuhn committed
30
31
32
33
34
35
36
37
38
39
40
41

/**
 * Inline element entry container.
 *
 * This container is the entry step to rendering an inline element. It is created by SingleFieldContainer.
 *
 * The code creates the main structure for the single inline elements, initializes
 * the inlineData array, that is manipulated and also returned back in its manipulated state.
 * The "control" stuff of inline elements is rendered here, for example the "create new" button.
 *
 * For each existing inline relation an InlineRecordContainer is called for further processing.
 */
42
43
44
45
46
47
48
class InlineControlContainer extends AbstractContainer
{
    /**
     * Inline data array used in JS, returned as JSON object to frontend
     *
     * @var array
     */
49
    protected $inlineData = [];
50
51
52
53
54
55
56
57
58
59
60

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

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

61
62
63
64
65
    /**
     * @var string[]
     */
    protected $requireJsModules = [];

66
67
68
69
70
71
72
73
74
75
76
    /**
     * Default field information enabled for this element.
     *
     * @var array
     */
    protected $defaultFieldInformation = [
        'tcaDescription' => [
            'renderType' => 'tcaDescription',
        ],
    ];

77
78
79
80
81
82
83
84
85
    /**
     * @var array Default wizards
     */
    protected $defaultFieldWizard = [
        'localizationStateSelector' => [
            'renderType' => 'localizationStateSelector',
        ],
    ];

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
    /**
     * Container objects give $nodeFactory down to other containers.
     *
     * @param NodeFactory $nodeFactory
     * @param array $data
     */
    public function __construct(NodeFactory $nodeFactory, array $data)
    {
        parent::__construct($nodeFactory, $data);
        $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
    }

    /**
     * Entry method
     *
     * @return array As defined in initializeResultArray() of AbstractNode
     */
    public function render()
    {
        $languageService = $this->getLanguageService();

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

        /** @var InlineStackProcessor $inlineStackProcessor */
        $inlineStackProcessor = GeneralUtility::makeInstance(InlineStackProcessor::class);
        $this->inlineStackProcessor = $inlineStackProcessor;
        $inlineStackProcessor->initializeByGivenStructure($this->data['inlineStructure']);

        $table = $this->data['tableName'];
        $row = $this->data['databaseRow'];
        $field = $this->data['fieldName'];
        $parameterArray = $this->data['parameterArray'];

        $resultArray = $this->initializeResultArray();

        $config = $parameterArray['fieldConf']['config'];
        $foreign_table = $config['foreign_table'];
123
        $isReadOnly = isset($config['readOnly']) && $config['readOnly'];
124
        $language = 0;
125
        $languageFieldName = $GLOBALS['TCA'][$table]['ctrl']['languageField'];
126
127
        if (BackendUtility::isTableLocalizable($table)) {
            $language = isset($row[$languageFieldName][0]) ? (int)$row[$languageFieldName][0] : (int)$row[$languageFieldName];
128
129
130
        }

        // Add the current inline job to the structure stack
131
        $newStructureItem = [
132
133
134
135
            'table' => $table,
            'uid' => $row['uid'],
            'field' => $field,
            'config' => $config,
136
        ];
137
138
139
140
141
142
143
144
145
        // Extract FlexForm parts (if any) from element name, e.g. array('vDEF', 'lDEF', 'FlexField', 'vDEF')
        if (!empty($parameterArray['itemFormElName'])) {
            $flexFormParts = $this->extractFlexFormParts($parameterArray['itemFormElName']);
            if ($flexFormParts !== null) {
                $newStructureItem['flexform'] = $flexFormParts;
            }
        }
        $inlineStackProcessor->pushStableStructureItem($newStructureItem);

146
        // Transport the flexform DS identifier fields to the FormInlineAjaxController
147
        if (!empty($newStructureItem['flexform'])
148
            && isset($this->data['processedTca']['columns'][$field]['config']['dataStructureIdentifier'])
149
        ) {
150
            $config['dataStructureIdentifier'] = $this->data['processedTca']['columns'][$field]['config']['dataStructureIdentifier'];
151
152
        }

153
154
155
156
157
        // Hand over original returnUrl to FormInlineAjaxController. Needed if opening for instance a
        // nested element in a new view to then go back to the original returnUrl and not the url of
        // the inline ajax controller
        $config['originalReturnUrl'] = $this->data['returnUrl'];

158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
        // e.g. data[<table>][<uid>][<field>]
        $nameForm = $inlineStackProcessor->getCurrentStructureFormPrefix();
        // e.g. data-<pid>-<table1>-<uid1>-<field1>-<table2>-<uid2>-<field2>
        $nameObject = $inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($this->data['inlineFirstPid']);

        $config['inline']['first'] = false;
        $firstChild = reset($this->data['parameterArray']['fieldConf']['children']);
        if (isset($firstChild['databaseRow']['uid'])) {
            $config['inline']['first'] = $firstChild['databaseRow']['uid'];
        }
        $config['inline']['last'] = false;
        $lastChild = end($this->data['parameterArray']['fieldConf']['children']);
        if (isset($lastChild['databaseRow']['uid'])) {
            $config['inline']['last'] = $lastChild['databaseRow']['uid'];
        }

        $top = $inlineStackProcessor->getStructureLevel(0);

176
        $this->inlineData['config'][$nameObject] = [
177
            'table' => $foreign_table,
178
        ];
179
        $configJson = (string)json_encode($config);
180
        $this->inlineData['config'][$nameObject . '-' . $foreign_table] = [
181
182
183
            'min' => $config['minitems'],
            'max' => $config['maxitems'],
            'sortable' => $config['appearance']['useSortable'],
184
            'top' => [
185
186
                'table' => $top['table'],
                'uid' => $top['uid']
187
188
            ],
            'context' => [
189
190
                'config' => $configJson,
                'hmac' => GeneralUtility::hmac($configJson, 'InlineContext'),
191
192
            ],
        ];
193
194
195
196
        $this->inlineData['nested'][$nameObject] = $this->data['tabAndInlineStack'];

        $uniqueMax = 0;
        $uniqueIds = [];
197

198
        if ($config['foreign_unique']) {
199
            // Add inlineData['unique'] with JS unique configuration
200
            // @todo: Improve validation and throw an exception if type is neither select nor group here
201
202
203
            $type = $config['selectorOrUniqueConfiguration']['config']['type'] === 'select' ? 'select' : 'groupdb';
            foreach ($parameterArray['fieldConf']['children'] as $child) {
                // Determine used unique ids, skip not localized records
204
                if (!$child['isInlineDefaultLanguageRecordInLocalizedParentContext']) {
205
206
207
                    $value = $child['databaseRow'][$config['foreign_unique']];
                    // We're assuming there is only one connected value here for both select and group
                    if ($type === 'select') {
208
209
                        // A select field is an array of uids. See TcaSelectItems data provider for details.
                        // Pick first entry, ends up as eg. $value = 42.
210
211
                        $value = $value['0'];
                    } else {
212
213
214
215
216
217
                        // A group field is an array of arrays containing uid + table + title + row.
                        // See TcaGroup data provider for details.
                        // Pick the first one (always on 0), and use uid + table only. Exclude title + row
                        // since the entire inlineData['unique'] array ends up in JavaScript in the end
                        // and we don't need and want the title and the entire row data in the frontend.
                        // Ends up as $value = [ 'uid' => '42', 'table' => 'tx_my_table' ]
218
                        $value = [
219
220
                            'uid' => $value[0]['uid'],
                            'table' => $value[0]['table'],
221
                        ];
222
                    }
223
                    // Note structure of $value is different in select vs. group: It's a uid for select, but an
224
                    // array with uid + table for group.
225
226
227
228
229
230
231
232
233
                    $uniqueIds[$child['databaseRow']['uid']] = $value;
                }
            }
            $possibleRecords = $config['selectorOrUniquePossibleRecords'];
            $possibleRecordsUidToTitle = [];
            foreach ($possibleRecords as $possibleRecord) {
                $possibleRecordsUidToTitle[$possibleRecord[1]] = $possibleRecord[0];
            }
            $uniqueMax = $config['appearance']['useCombination'] || empty($possibleRecords) ? -1 : count($possibleRecords);
234
            $this->inlineData['unique'][$nameObject . '-' . $foreign_table] = [
235
236
                'max' => $uniqueMax,
                'used' => $uniqueIds,
237
238
239
                'type' => $type,
                'table' => $foreign_table,
                'elTable' => $config['selectorOrUniqueConfiguration']['foreignTable'],
240
                'field' => $config['foreign_unique'],
241
242
                'selector' => $config['selectorOrUniqueConfiguration']['isSelector'] ? $type : false,
                'possible' => $possibleRecordsUidToTitle,
243
            ];
244
245
246
247
        }

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

248
        // @todo: It might be a good idea to have something like "isLocalizedRecord" or similar set by a data provider
249
        $uidOfDefaultRecord = $row[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']];
250
        $isLocalizedParent = $language > 0
251
            && ($uidOfDefaultRecord[0] ?? $uidOfDefaultRecord) > 0
252
253
254
255
256
            && MathUtility::canBeInterpretedAsInteger($row['uid']);
        $numberOfFullLocalizedChildren = 0;
        $numberOfNotYetLocalizedChildren = 0;
        foreach ($this->data['parameterArray']['fieldConf']['children'] as $child) {
            if (!$child['isInlineDefaultLanguageRecordInLocalizedParentContext']) {
Christian Kuhn's avatar
Christian Kuhn committed
257
                $numberOfFullLocalizedChildren++;
258
259
            }
            if ($isLocalizedParent && $child['isInlineDefaultLanguageRecordInLocalizedParentContext']) {
Christian Kuhn's avatar
Christian Kuhn committed
260
                $numberOfNotYetLocalizedChildren++;
261
262
263
            }
        }

264
265
        // Render the localization buttons if needed
        $localizationButtons = '';
266
        if ($numberOfNotYetLocalizedChildren) {
267
            // Add the "Localize all records" button before all child records:
268
            if (isset($config['appearance']['showAllLocalizationLink']) && $config['appearance']['showAllLocalizationLink']) {
269
                $localizationButtons = ' ' . $this->getLevelInteractionButton('localize', $config);
270
            }
271
            // Add the "Synchronize with default language" button before all child records:
272
            if (isset($config['appearance']['showSynchronizationLink']) && $config['appearance']['showSynchronizationLink']) {
273
                $localizationButtons .= ' ' . $this->getLevelInteractionButton('synchronize', $config);
274
275
276
            }
        }

277
        // Define how to show the "Create new record" button - if there are more than maxitems, hide it
278
        if ($isReadOnly || $numberOfFullLocalizedChildren >= $config['maxitems'] || ($uniqueMax > 0 && $numberOfFullLocalizedChildren >= $uniqueMax)) {
279
280
            $config['inline']['inlineNewButtonStyle'] = 'display: none;';
            $config['inline']['inlineNewRelationButtonStyle'] = 'display: none;';
281
            $config['inline']['inlineOnlineMediaAddButtonStyle'] = 'display: none;';
282
283
        }

284
285
        // Render the level buttons (create new record):
        $levelButtons = $this->getLevelInteractionButton('newRecord', $config);
286
287
288
289

        $formGroupAttributes = [
            'class' => 'form-group',
            'id' => $nameObject,
290
291
292
293
            'data-uid' => (string)$row['uid'],
            'data-local-table' => (string)$top['table'],
            'data-local-field' => (string)$top['field'],
            'data-foreign-table' => (string)$foreign_table,
294
295
            'data-object-group' => $nameObject . '-' . $foreign_table,
            'data-form-field' => $nameForm,
296
            'data-appearance' => (string)json_encode($config['appearance']),
297
298
        ];

299
        // Wrap all inline fields of a record with a <div> (like a container)
300
        $html = '<div ' . GeneralUtility::implodeAttributes($formGroupAttributes, true) . '>';
301
302
303
304
305

        $fieldInformationResult = $this->renderFieldInformation();
        $html .= $fieldInformationResult['html'];
        $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldInformationResult, false);

306
        // Add the level buttons before all child records:
307
        if ($config['appearance']['levelLinksPosition'] === 'both' || $config['appearance']['levelLinksPosition'] === 'top') {
308
            $html .= '<div class="form-group t3js-formengine-validation-marker">' . $levelButtons . $localizationButtons . '</div>';
309
310
311
        }

        // If it's required to select from possible child records (reusable children), add a selector box
312
        if (!$isReadOnly && $config['foreign_selector'] && $config['appearance']['showPossibleRecordsSelector'] !== false) {
313
314
315
316
            if ($config['selectorOrUniqueConfiguration']['config']['type'] === 'select') {
                $selectorBox = $this->renderPossibleRecordsSelectorTypeSelect($config, $uniqueIds);
            } else {
                $selectorBox = $this->renderPossibleRecordsSelectorTypeGroupDB($config);
317
            }
318
            $html .= $selectorBox . $localizationButtons;
319
320
        }

321
        $title = $languageService->sL(trim($parameterArray['fieldConf']['label']));
322
323
324
325
326
        $html .= '<div class="panel-group panel-hover" data-title="' . htmlspecialchars($title) . '" id="' . $nameObject . '_records">';

        $sortableRecordUids = [];
        foreach ($this->data['parameterArray']['fieldConf']['children'] as $options) {
            $options['inlineParentUid'] = $row['uid'];
327
            $options['inlineFirstPid'] = $this->data['inlineFirstPid'];
328
            // @todo: this can be removed if this container no longer sets additional info to $config
329
330
331
332
333
334
335
            $options['inlineParentConfig'] = $config;
            $options['inlineData'] = $this->inlineData;
            $options['inlineStructure'] = $inlineStackProcessor->getStructure();
            $options['inlineExpandCollapseStateArray'] = $this->data['inlineExpandCollapseStateArray'];
            $options['renderType'] = 'inlineRecordContainer';
            $childResult = $this->nodeFactory->create($options)->render();
            $html .= $childResult['html'];
336
            $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $childResult, false);
337
            if (!$options['isInlineDefaultLanguageRecordInLocalizedParentContext']) {
338
339
340
341
342
343
344
345
                // Don't add record to list of "valid" uids if it is only the default
                // language record of a not yet localized child
                $sortableRecordUids[] = $options['databaseRow']['uid'];
            }
        }

        $html .= '</div>';

346
        $fieldWizardResult = $this->renderFieldWizard();
347
348
349
350
        $fieldWizardHtml = $fieldWizardResult['html'];
        $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldWizardResult, false);
        $html .= $fieldWizardHtml;

351
        // Add the level buttons after all child records:
352
        if (!$isReadOnly && ($config['appearance']['levelLinksPosition'] === 'both' || $config['appearance']['levelLinksPosition'] === 'bottom')) {
353
            $html .= $levelButtons . $localizationButtons;
354
355
356
357
        }
        if (is_array($config['customControls'])) {
            $html .= '<div id="' . $nameObject . '_customControls">';
            foreach ($config['customControls'] as $customControlConfig) {
358
                if (!isset($customControlConfig['userFunc'])) {
359
                    throw new \RuntimeException('Support for customControl without a userFunc key in TCA type inline is not supported.', 1548052629);
360
                }
361
                $parameters = [
362
363
364
365
366
                    'table' => $table,
                    'field' => $field,
                    'row' => $row,
                    'nameObject' => $nameObject,
                    'nameForm' => $nameForm,
367
368
                    'config' => $config,
                    'customControlConfig' => $customControlConfig,
369
                ];
370
                $html .= GeneralUtility::callUserFunction($customControlConfig['userFunc'], $parameters, $this);
371
372
373
            }
            $html .= '</div>';
        }
374
        $resultArray['requireJsModules'] = array_merge($resultArray['requireJsModules'], $this->requireJsModules);
375
376
377
378
379
        $resultArray['requireJsModules'][] = ['TYPO3/CMS/Backend/FormEngine/Container/InlineControlContainer' => '
            function(InlineControlContainer) {
                new InlineControlContainer(' . GeneralUtility::quoteJSvalue($nameObject) . ');
            }'
        ];
380

381
382
        // Publish the uids of the child records in the given order to the browser
        $html .= '<input type="hidden" name="' . $nameForm . '" value="' . implode(',', $sortableRecordUids) . '" '
383
            . ' data-formengine-validation-rules="' . htmlspecialchars($this->getValidationDataAsJsonString(['type' => 'inline', 'minitems' => $config['minitems'], 'maxitems' => $config['maxitems']])) . '"'
384
385
386
387
388
389
390
391
392
            . ' class="inlineRecord" />';
        // Close the wrap for all inline fields (container)
        $html .= '</div>';

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

    /**
393
     * Creates the HTML code of a general button to be used on a level of inline children.
394
395
     * The possible keys for the parameter $type are 'newRecord', 'localize' and 'synchronize'.
     *
396
     * @param string $type The button type, values are 'newRecord', 'localize' and 'synchronize'.
397
     * @param array $conf TCA configuration of the parent(!) field
398
     * @return string The HTML code of the new button, wrapped in a div
399
     */
400
    protected function getLevelInteractionButton(string $type, array $conf = []): string
401
402
    {
        $languageService = $this->getLanguageService();
403
        $attributes = [];
404
405
        switch ($type) {
            case 'newRecord':
406
                $title = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:cm.createnew'));
407
                $icon = 'actions-add';
408
                $className = 'typo3-newRecordLink t3js-inline-controls';
409
                $attributes['class'] = 'btn btn-default t3js-create-new-button';
410
411
412
413
                if (!empty($conf['inline']['inlineNewButtonStyle'])) {
                    $attributes['style'] = $conf['inline']['inlineNewButtonStyle'];
                }
                if (!empty($conf['appearance']['newRecordLinkAddTitle'])) {
414
                    $title = htmlspecialchars(sprintf(
415
                        $languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:cm.createnew.link'),
416
417
                        $languageService->sL($GLOBALS['TCA'][$conf['foreign_table']]['ctrl']['title'])
                    ));
418
                } elseif (isset($conf['appearance']['newRecordLinkTitle']) && $conf['appearance']['newRecordLinkTitle'] !== '') {
419
                    $title = htmlspecialchars($languageService->sL($conf['appearance']['newRecordLinkTitle']));
420
421
422
                }
                break;
            case 'localize':
423
                $title = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_misc.xlf:localizeAllRecords'));
424
425
                $icon = 'actions-document-localize';
                $className = 'typo3-localizationLink';
426
427
                $attributes['class'] = 'btn btn-default t3js-synchronizelocalize-button';
                $attributes['data-type'] = 'localize';
428
429
                break;
            case 'synchronize':
430
                $title = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_misc.xlf:synchronizeWithOriginalLanguage'));
431
432
                $icon = 'actions-document-synchronize';
                $className = 'typo3-synchronizationLink';
433
434
                $attributes['class'] = 'btn btn-default inlineNewButton t3js-synchronizelocalize-button';
                $attributes['data-type'] = 'synchronize';
435
436
437
438
439
440
                break;
            default:
                $title = '';
                $icon = '';
                $className = '';
        }
441
        // Create the button:
442
        $icon = $icon ? $this->iconFactory->getIcon($icon, Icon::SIZE_SMALL)->render() : '';
443
444
        $button = $this->wrapWithButton($icon . ' ' . $title, $attributes);
        return '<div' . ($className ? ' class="' . $className . '"' : '') . 'title="' . $title . '">' . $button . '</div>';
445
446
447
    }

    /**
448
     * Wraps a text with a button and returns the HTML representation.
449
     *
450
451
     * @param string $text The text to be wrapped by a button
     * @param array<string, string> $attributes Array of attributes to be used in the anchor
452
453
     * @return string The wrapped text as HTML representation
     */
454
    protected function wrapWithButton(string $text, array $attributes = []): string
455
    {
456
        return '<button type="button" ' . GeneralUtility::implodeAttributes($attributes, true, true) . '>' . $text . '</button>';
457
458
459
    }

    /**
460
     * Generate a button that opens an element browser in a new window.
461
462
     * For group/db there is no way to use a "selector" like a <select>|</select>-box.
     *
463
     * @param array $inlineConfiguration TCA inline configuration of the parent(!) field
464
     * @return string A HTML button that opens an element browser in a new window
465
     */
466
    protected function renderPossibleRecordsSelectorTypeGroupDB(array $inlineConfiguration)
467
468
469
470
    {
        $backendUser = $this->getBackendUserAuthentication();
        $languageService = $this->getLanguageService();

471
472
473
474
        $groupFieldConfiguration = $inlineConfiguration['selectorOrUniqueConfiguration']['config'];

        $foreign_table = $inlineConfiguration['foreign_table'];
        $allowed = $groupFieldConfiguration['allowed'];
475
476
        $currentStructureDomObjectIdPrefix = $this->inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($this->data['inlineFirstPid']);
        $objectPrefix = $currentStructureDomObjectIdPrefix . '-' . $foreign_table;
477
478
        $mode = 'db';
        $showUpload = false;
479
        $showByUrl = false;
480
        $elementBrowserEnabled = true;
481
        if (!empty($inlineConfiguration['appearance']['createNewRelationLinkTitle'])) {
482
            $createNewRelationText = htmlspecialchars($languageService->sL($inlineConfiguration['appearance']['createNewRelationLinkTitle']));
483
        } else {
484
            $createNewRelationText = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:cm.createNewRelation'));
485
        }
486
487
488
        if (is_array($groupFieldConfiguration['appearance'])) {
            if (isset($groupFieldConfiguration['appearance']['elementBrowserType'])) {
                $mode = $groupFieldConfiguration['appearance']['elementBrowserType'];
489
490
491
            }
            if ($mode === 'file') {
                $showUpload = true;
492
                $showByUrl = true;
493
            }
494
495
            if (isset($inlineConfiguration['appearance']['fileUploadAllowed'])) {
                $showUpload = (bool)$inlineConfiguration['appearance']['fileUploadAllowed'];
496
            }
497
498
499
            if (isset($inlineConfiguration['appearance']['fileByUrlAllowed'])) {
                $showByUrl = (bool)$inlineConfiguration['appearance']['fileByUrlAllowed'];
            }
500
501
            if (isset($groupFieldConfiguration['appearance']['elementBrowserAllowed'])) {
                $allowed = $groupFieldConfiguration['appearance']['elementBrowserAllowed'];
502
            }
503
504
505
            if (isset($inlineConfiguration['appearance']['elementBrowserEnabled'])) {
                $elementBrowserEnabled = (bool)$inlineConfiguration['appearance']['elementBrowserEnabled'];
            }
506
        }
507
508
        // Remove any white-spaces from the allowed extension lists
        $allowed = implode(',', GeneralUtility::trimExplode(',', $allowed, true));
509
        $browserParams = '|||' . $allowed . '|' . $objectPrefix;
510
        $buttonStyle = '';
511
512
        if (isset($inlineConfiguration['inline']['inlineNewRelationButtonStyle'])) {
            $buttonStyle = ' style="' . $inlineConfiguration['inline']['inlineNewRelationButtonStyle'] . '"';
513
        }
514
515
516
        $item = '';
        if ($elementBrowserEnabled) {
            $item .= '
517
			<button type="button" class="btn btn-default t3js-element-browser" data-mode="' . htmlspecialchars($mode) . '" data-params="' . htmlspecialchars($browserParams) . '"
518
				' . $buttonStyle . ' title="' . $createNewRelationText . '">
519
				' . $this->iconFactory->getIcon('actions-insert-record', Icon::SIZE_SMALL)->render() . '
Christian Kuhn's avatar
Christian Kuhn committed
520
				' . $createNewRelationText . '
521
			</button>';
522
523
524
        }

        $isDirectFileUploadEnabled = (bool)$backendUser->uc['edit_docModuleUpload'];
525
526
527
528
529
        $allowedArray = GeneralUtility::trimExplode(',', $allowed, true);
        $onlineMediaAllowed = OnlineMediaHelperRegistry::getInstance()->getSupportedFileExtensions();
        if (!empty($allowedArray)) {
            $onlineMediaAllowed = array_intersect($allowedArray, $onlineMediaAllowed);
        }
530
        if (($showUpload || $showByUrl) && $isDirectFileUploadEnabled) {
531
            $folder = $backendUser->getDefaultUploadFolder(
532
                $this->data['tableName'] === 'pages' ? $this->data['vanillaUid'] : $this->data['parentPageRow']['uid'],
533
534
535
536
537
                $this->data['tableName'],
                $this->data['fieldName']
            );
            if (
                $folder instanceof Folder
538
                && $folder->getStorage()->checkUserActionPermission('add', 'File')
539
            ) {
540
541
                if ($showUpload) {
                    $maxFileSize = GeneralUtility::getMaxUploadFileSize() * 1024;
542
                    $item .= ' <button type="button" class="btn btn-default t3js-drag-uploader inlineNewFileUploadButton"
543
					' . $buttonStyle . '
544
					data-dropzone-target="#' . htmlspecialchars(StringUtility::escapeCssSelector($currentStructureDomObjectIdPrefix)) . '"
Christian Kuhn's avatar
Christian Kuhn committed
545
546
547
548
					data-insert-dropzone-before="1"
					data-file-irre-object="' . htmlspecialchars($objectPrefix) . '"
					data-file-allowed="' . htmlspecialchars($allowed) . '"
					data-target-folder="' . htmlspecialchars($folder->getCombinedIdentifier()) . '"
549
					data-max-file-size="' . htmlspecialchars((string)$maxFileSize) . '"
550
					>';
551
552
                    $item .= $this->iconFactory->getIcon('actions-upload', Icon::SIZE_SMALL)->render() . ' ';
                    $item .= htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:file_upload.select-and-submit'));
553
                    $item .= '</button>';
554

555
556
557
                    $this->requireJsModules[] = ['TYPO3/CMS/Backend/DragUploader' => 'function(dragUploader){dragUploader.initialize()}'];
                }
                if (!empty($onlineMediaAllowed) && $showByUrl) {
558
559
560
561
                    $buttonStyle = '';
                    if (isset($inlineConfiguration['inline']['inlineOnlineMediaAddButtonStyle'])) {
                        $buttonStyle = ' style="' . $inlineConfiguration['inline']['inlineOnlineMediaAddButtonStyle'] . '"';
                    }
562
                    $this->requireJsModules[] = 'TYPO3/CMS/Backend/OnlineMedia';
563
564
565
566
                    $buttonText = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:online_media.new_media.button'));
                    $placeholder = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:online_media.new_media.placeholder'));
                    $buttonSubmit = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:online_media.new_media.submit'));
                    $allowedMediaUrl = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:cm.allowEmbedSources'));
567
                    $item .= '
568
						<button type="button" class="btn btn-default t3js-online-media-add-btn"
569
							' . $buttonStyle . '
570
571
							data-file-irre-object="' . htmlspecialchars($objectPrefix) . '"
							data-online-media-allowed="' . htmlspecialchars(implode(',', $onlineMediaAllowed)) . '"
572
							data-online-media-allowed-help-text="' . $allowedMediaUrl . '"
573
574
575
576
577
							data-target-folder="' . htmlspecialchars($folder->getCombinedIdentifier()) . '"
							title="' . $buttonText . '"
							data-btn-submit="' . $buttonSubmit . '"
							data-placeholder="' . $placeholder . '"
							>
578
							' . $this->iconFactory->getIcon('actions-online-media-add', Icon::SIZE_SMALL)->render() . '
579
							' . $buttonText . '</button>';
580
581
582
583
                }
            }
        }

584
        $item = '<div class="form-control-wrap t3js-inline-controls">' . $item . '</div>';
585
        $allowedList = '';
586
587
        $allowedLabelKey = ($mode === 'file') ? 'allowedFileExtensions' : 'allowedRelations';
        $allowedLabel = htmlspecialchars($languageService->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:cm.' . $allowedLabelKey));
588
589
590
591
592
593
594
595
596
597
598
599
600
601
        foreach ($allowedArray as $allowedItem) {
            $allowedList .= '<span class="label label-success">' . strtoupper($allowedItem) . '</span> ';
        }
        if (!empty($allowedList)) {
            $item .= '<div class="help-block">' . $allowedLabel . '<br>' . $allowedList . '</div>';
        }
        $item = '<div class="form-group t3js-formengine-validation-marker">' . $item . '</div>';
        return $item;
    }

    /**
     * Get a selector as used for the select type, to select from all available
     * records and to create a relation to the embedding record (e.g. like MM).
     *
602
     * @param array $config TCA inline configuration of the parent(!) field
603
604
605
     * @param array $uniqueIds The uids that have already been used and should be unique
     * @return string A HTML <select> box with all possible records
     */
606
    protected function renderPossibleRecordsSelectorTypeSelect(array $config, array $uniqueIds)
607
    {
608
609
610
611
612
613
614
        $possibleRecords = $config['selectorOrUniquePossibleRecords'];
        $nameObject = $this->inlineStackProcessor->getCurrentStructureDomObjectIdPrefix($this->data['inlineFirstPid']);
        // Create option tags:
        $opt = [];
        foreach ($possibleRecords as $p) {
            if (!in_array($p[1], $uniqueIds)) {
                $opt[] = '<option value="' . htmlspecialchars($p[1]) . '">' . htmlspecialchars($p[0]) . '</option>';
615
            }
616
617
618
619
620
        }
        // Put together the selector box:
        $size = (int)$config['size'];
        $size = $config['autoSizeMax'] ? MathUtility::forceIntegerInRange(count($possibleRecords) + 1, MathUtility::forceIntegerInRange($size, 1), $config['autoSizeMax']) : $size;
        $item = '
621
            <select id="' . $nameObject . '-' . $config['foreign_table'] . '_selector" class="form-select t3js-create-new-selector"' . ($size ? ' size="' . $size . '"' : '') . '>
622
623
624
625
                ' . implode('', $opt) . '
            </select>';

        if ($size <= 1) {
626
            // Add a "Create new relation" button for adding new relations
627
628
629
630
            // This is necessary, if the size of the selector is "1" or if
            // there is only one record item in the select-box, that is selected by default
            // The selector-box creates a new relation on using an onChange event (see some line above)
            if (!empty($config['appearance']['createNewRelationLinkTitle'])) {
631
                $createNewRelationText = htmlspecialchars($this->getLanguageService()->sL($config['appearance']['createNewRelationLinkTitle']));
632
            } else {
633
                $createNewRelationText = htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:cm.createNewRelation'));
634
            }
635
636
            $item .= '
            <span class="input-group-btn">
637
                <button type="button" class="btn btn-default t3js-create-new-button" title="' . $createNewRelationText . '">
638
                    ' . $this->iconFactory->getIcon('actions-add', Icon::SIZE_SMALL)->render() . $createNewRelationText . '
639
                </button>
640
641
642
643
            </span>';
        } else {
            $item .= '
            <span class="input-group-btn btn"></span>';
644
        }
645
646

        // Wrap the selector and add a spacer to the bottom
647
        $item = '<div class="input-group form-group t3js-formengine-validation-marker">' . $item . '</div>';
648
649
650
651
652
653
654
655
656
        return $item;
    }

    /**
     * Extracts FlexForm parts of a form element name like
     * data[table][uid][field][sDEF][lDEF][FlexForm][vDEF]
     * Helper method used in inline
     *
     * @param string $formElementName The form element name
657
     * @return array|null
658
659
660
661
     */
    protected function extractFlexFormParts($formElementName)
    {
        $flexFormParts = null;
662
        $matches = [];
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
        if (preg_match('#^data(?:\[[^]]+\]){3}(\[data\](?:\[[^]]+\]){4,})$#', $formElementName, $matches)) {
            $flexFormParts = GeneralUtility::trimExplode(
                '][',
                trim($matches[1], '[]')
            );
        }
        return $flexFormParts;
    }

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

    /**
     * @return LanguageService
     */
    protected function getLanguageService()
    {
        return $GLOBALS['LANG'];
    }
687
}