Completed
Push — master ( 76a0e0...7a82fc )
by
unknown
17:28
created

InputSlugElement::getPrefix()   A

Complexity

Conditions 6
Paths 12

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 10
nc 12
nop 2
dl 0
loc 15
rs 9.2222
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
namespace TYPO3\CMS\Backend\Form\Element;
4
5
/*
6
 * This file is part of the TYPO3 CMS project.
7
 *
8
 * It is free software; you can redistribute it and/or modify it under
9
 * the terms of the GNU General Public License, either version 2
10
 * of the License, or any later version.
11
 *
12
 * For the full copyright and license information, please read the
13
 * LICENSE.txt file that was distributed with this source code.
14
 *
15
 * The TYPO3 project - inspiring people to share!
16
 */
17
18
use TYPO3\CMS\Backend\Controller\FormSlugAjaxController;
19
use TYPO3\CMS\Core\Imaging\Icon;
20
use TYPO3\CMS\Core\Localization\LanguageService;
21
use TYPO3\CMS\Core\Utility\GeneralUtility;
22
use TYPO3\CMS\Core\Utility\MathUtility;
23
use TYPO3\CMS\Core\Utility\StringUtility;
24
25
/**
26
 * General type=input element for TCA Type=Slug with some additional value.
27
 */
28
class InputSlugElement extends AbstractFormElement
29
{
30
31
    /**
32
     * Default field information enabled for this element.
33
     *
34
     * @var array
35
     */
36
    protected $defaultFieldInformation = [
37
        'tcaDescription' => [
38
            'renderType' => 'tcaDescription',
39
        ],
40
    ];
41
42
    /**
43
     * Default field wizards enabled for this element.
44
     *
45
     * @var array
46
     */
47
    protected $defaultFieldWizard = [
48
        'localizationStateSelector' => [
49
            'renderType' => 'localizationStateSelector',
50
        ],
51
        'otherLanguageContent' => [
52
            'renderType' => 'otherLanguageContent',
53
            'after' => [
54
                'localizationStateSelector'
55
            ],
56
        ],
57
        'defaultLanguageDifferences' => [
58
            'renderType' => 'defaultLanguageDifferences',
59
            'after' => [
60
                'otherLanguageContent',
61
            ],
62
        ],
63
    ];
64
65
    /**
66
     * This will render a single-line input form field, possibly with various control/validation features
67
     *
68
     * @return array As defined in initializeResultArray() of AbstractNode
69
     */
70
    public function render()
71
    {
72
        $table = $this->data['tableName'];
73
        $row = $this->data['databaseRow'];
74
        $parameterArray = $this->data['parameterArray'];
75
        $resultArray = $this->initializeResultArray();
76
77
        $languageId = 0;
78
        if (isset($GLOBALS['TCA'][$table]['ctrl']['languageField']) && !empty($GLOBALS['TCA'][$table]['ctrl']['languageField'])) {
79
            $languageField = $GLOBALS['TCA'][$table]['ctrl']['languageField'];
80
            $languageId = (int)((is_array($row[$languageField]) ? $row[$languageField][0] : $row[$languageField]) ?? 0);
81
        }
82
83
        $itemValue = $parameterArray['itemFormElValue'];
84
        $config = $parameterArray['fieldConf']['config'];
85
        $evalList = GeneralUtility::trimExplode(',', $config['eval'], true);
86
        $size = MathUtility::forceIntegerInRange($config['size'] ?? $this->defaultInputWidth, $this->minimumInputWidth, $this->maxInputWidth);
87
        $width = (int)$this->formMaxWidth($size);
88
        $baseUrl = $this->data['customData'][$this->data['fieldName']]['slugPrefix'] ?? '';
89
90
        // Convert UTF-8 characters back (that is important, see Slug class when sanitizing)
91
        $itemValue = rawurldecode($itemValue);
92
93
        $fieldInformationResult = $this->renderFieldInformation();
94
        $fieldInformationHtml = $fieldInformationResult['html'];
95
        $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldInformationResult, false);
96
97
        $fieldControlResult = $this->renderFieldControl();
98
        $fieldControlHtml = $fieldControlResult['html'];
99
        $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldControlResult, false);
100
101
        $fieldWizardResult = $this->renderFieldWizard();
102
        $fieldWizardHtml = $fieldWizardResult['html'];
103
        $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldWizardResult, false);
104
        $toggleButtonTitle = $this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:buttons.toggleSlugExplanation');
105
        $recreateButtonTitle = $this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:buttons.recreateSlugExplanation');
106
107
        $successMessage = sprintf($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:slugCreation.success.' . ($table === 'pages' ? 'page' : 'record')), $baseUrl);
108
        $errorMessage = sprintf($this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:slugCreation.error'), $baseUrl);
109
110
        $thisSlugId = 't3js-form-field-slug-id' . StringUtility::getUniqueId();
111
        $mainFieldHtml = [];
112
        $mainFieldHtml[] = '<div class="formengine-field-item t3js-formengine-field-item">';
113
        $mainFieldHtml[] =  $fieldInformationHtml;
114
        $mainFieldHtml[] =  '<div class="form-control-wrap" style="max-width: ' . $width . 'px" id="' . htmlspecialchars($thisSlugId) . '">';
115
        $mainFieldHtml[] =      '<div class="form-wizards-wrap">';
116
        $mainFieldHtml[] =          '<div class="form-wizards-element">';
117
        $mainFieldHtml[] =              '<div class="input-group">';
118
        $mainFieldHtml[] =                  ($baseUrl ? '<span class="input-group-addon">' . htmlspecialchars($baseUrl) . '</span>' : '');
119
        // We deal with 3 fields here: a readonly field for current / default values, an input
120
        // field to manipulate the value, and the final hidden field used to send the value
121
        $mainFieldHtml[] =                  '<input';
122
        $mainFieldHtml[] =                      ' class="form-control t3js-form-field-slug-readonly"';
123
        $mainFieldHtml[] =                      ' data-toggle="tooltip"';
124
        $mainFieldHtml[] =                      ' data-title="' . htmlspecialchars($itemValue) . '"';
125
        $mainFieldHtml[] =                      ' value="' . htmlspecialchars($itemValue) . '"';
126
        $mainFieldHtml[] =                      ' readonly';
127
        $mainFieldHtml[] =                  ' />';
128
        $mainFieldHtml[] =                  '<input type="text"';
129
        $mainFieldHtml[] =                      ' id="' . htmlspecialchars(StringUtility::getUniqueId('formengine-input-')) . '"';
130
        $mainFieldHtml[] =                      ' class="form-control t3js-form-field-slug-input hidden"';
131
        $mainFieldHtml[] =                      ' placeholder="' . htmlspecialchars($row['slug'] ?? '/') . '"';
132
        $mainFieldHtml[] =                      ' data-formengine-validation-rules="' . htmlspecialchars($this->getValidationDataAsJsonString($config)) . '"';
133
        $mainFieldHtml[] =                      ' data-formengine-input-params="' . htmlspecialchars(json_encode(['field' => $parameterArray['itemFormElName'], 'evalList' => implode(',', $evalList)])) . '"';
134
        $mainFieldHtml[] =                      ' data-formengine-input-name="' . htmlspecialchars($parameterArray['itemFormElName']) . '"';
135
        $mainFieldHtml[] =                  ' />';
136
        $mainFieldHtml[] =                  '<span class="input-group-btn">';
137
        $mainFieldHtml[] =                      '<button class="btn btn-default t3js-form-field-slug-toggle" type="button" title="' . htmlspecialchars($toggleButtonTitle) . '">';
138
        $mainFieldHtml[] =                          $this->iconFactory->getIcon('actions-version-workspaces-preview-link', Icon::SIZE_SMALL)->render();
139
        $mainFieldHtml[] =                      '</button>';
140
        $mainFieldHtml[] =                      '<button class="btn btn-default t3js-form-field-slug-recreate" type="button" title="' . htmlspecialchars($recreateButtonTitle) . '">';
141
        $mainFieldHtml[] =                          $this->iconFactory->getIcon('actions-refresh', Icon::SIZE_SMALL)->render();
142
        $mainFieldHtml[] =                      '</button>';
143
        $mainFieldHtml[] =                  '</span>';
144
        $mainFieldHtml[] =                  '<input type="hidden"';
145
        $mainFieldHtml[] =                      ' class="t3js-form-field-slug-hidden"';
146
        $mainFieldHtml[] =                      ' name="' . htmlspecialchars($parameterArray['itemFormElName']) . '"';
147
        $mainFieldHtml[] =                      ' value="' . htmlspecialchars($itemValue) . '"';
148
        $mainFieldHtml[] =                  ' />';
149
        $mainFieldHtml[] =              '</div>';
150
        $mainFieldHtml[] =          '</div>';
151
        if (!empty($fieldControlHtml)) {
152
            $mainFieldHtml[] =      '<div class="form-wizards-items-aside">';
153
            $mainFieldHtml[] =          '<div class="btn-group">';
154
            $mainFieldHtml[] =              $fieldControlHtml;
155
            $mainFieldHtml[] =          '</div>';
156
            $mainFieldHtml[] =      '</div>';
157
        }
158
        $mainFieldHtml[] =          '<div class="form-wizards-items-bottom">';
159
        $mainFieldHtml[] =              '<span class="t3js-form-proposal-accepted hidden label label-success">' . htmlspecialchars($successMessage) . '<span>/abc/</span></span>';
160
        $mainFieldHtml[] =              '<span class="t3js-form-proposal-different hidden label label-warning">' . htmlspecialchars($errorMessage) . '<span>/abc/</span></span>';
161
        $mainFieldHtml[] =              $fieldWizardHtml;
162
        $mainFieldHtml[] =          '</div>';
163
        $mainFieldHtml[] =      '</div>';
164
        $mainFieldHtml[] =  '</div>';
165
        $mainFieldHtml[] = '</div>';
166
167
        $resultArray['html'] = implode(LF, $mainFieldHtml);
168
169
        [$commonElementPrefix] = GeneralUtility::revExplode('[', $parameterArray['itemFormElName'], 2);
170
        $validInputNamesToListenTo = [];
171
        $includeUidInValues = false;
172
        foreach ($config['generatorOptions']['fields'] ?? [] as $fieldNameParts) {
173
            if (is_string($fieldNameParts)) {
174
                $fieldNameParts = GeneralUtility::trimExplode(',', $fieldNameParts);
175
            }
176
            foreach ($fieldNameParts as $listenerFieldName) {
177
                if ($listenerFieldName === 'uid') {
178
                    $includeUidInValues = true;
179
                    continue;
180
                }
181
                $validInputNamesToListenTo[$listenerFieldName] = $commonElementPrefix . '[' . htmlspecialchars($listenerFieldName) . ']';
182
            }
183
        }
184
        $parentPageId = $this->data['parentPageRow']['uid'] ?? 0;
185
        $signature = GeneralUtility::hmac(
186
            implode(
187
                '',
188
                [
189
                    $table,
190
                    $this->data['effectivePid'],
191
                    $row['uid'],
192
                    $languageId,
193
                    $this->data['fieldName'],
194
                    $this->data['command'],
195
                    $parentPageId
196
                ]
197
            ),
198
            FormSlugAjaxController::class
199
        );
200
        $optionsForModule = [
201
            'pageId' => $this->data['effectivePid'],
202
            'recordId' => $row['uid'],
203
            'tableName' => $table,
204
            'fieldName' => $this->data['fieldName'],
205
            'config' => $config,
206
            'listenerFieldNames' => $validInputNamesToListenTo,
207
            'language' => $languageId,
208
            'originalValue' => $itemValue,
209
            'signature' => $signature,
210
            'command' => $this->data['command'],
211
            'parentPageId' => $parentPageId,
212
            'includeUidInValues' => $includeUidInValues,
213
        ];
214
        $resultArray['requireJsModules'][] = ['TYPO3/CMS/Backend/FormEngine/Element/SlugElement' => '
215
            function(SlugElement) {
216
                new SlugElement(' . GeneralUtility::quoteJSvalue('#' . $thisSlugId) . ', ' . json_encode($optionsForModule) . ');
217
            }'
218
        ];
219
        return $resultArray;
220
    }
221
222
    /**
223
     * @return LanguageService
224
     */
225
    protected function getLanguageService(): LanguageService
226
    {
227
        return $GLOBALS['LANG'];
228
    }
229
}
230