[FEATURE] Add inline AJAX validation for TCA type slug
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Form / Element / InputSlugElement.php
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\Site\Entity\SiteInterface;
22 use TYPO3\CMS\Core\Utility\GeneralUtility;
23 use TYPO3\CMS\Core\Utility\MathUtility;
24 use TYPO3\CMS\Core\Utility\StringUtility;
25
26 /**
27 * General type=input element with some additional value.
28 */
29 class InputSlugElement extends AbstractFormElement
30 {
31 /**
32 * Default field wizards enabled for this element.
33 *
34 * @var array
35 */
36 protected $defaultFieldWizard = [
37 'localizationStateSelector' => [
38 'renderType' => 'localizationStateSelector',
39 ],
40 'otherLanguageContent' => [
41 'renderType' => 'otherLanguageContent',
42 'after' => [
43 'localizationStateSelector'
44 ],
45 ],
46 'defaultLanguageDifferences' => [
47 'renderType' => 'defaultLanguageDifferences',
48 'after' => [
49 'otherLanguageContent',
50 ],
51 ],
52 ];
53
54 /**
55 * This will render a single-line input form field, possibly with various control/validation features
56 *
57 * @return array As defined in initializeResultArray() of AbstractNode
58 */
59 public function render()
60 {
61 $table = $this->data['tableName'];
62 $row = $this->data['databaseRow'];
63 $parameterArray = $this->data['parameterArray'];
64 $resultArray = $this->initializeResultArray();
65
66 $languageField = $GLOBALS['TCA'][$table]['ctrl']['languageField'];
67 $languageId = (int)($row[$languageField][0] ?? 0);
68 $baseUrl = $this->getPrefix($this->data['site'], $languageId);
69
70 $itemValue = $parameterArray['itemFormElValue'];
71 $config = $parameterArray['fieldConf']['config'];
72 $evalList = GeneralUtility::trimExplode(',', $config['eval'], true);
73 $size = MathUtility::forceIntegerInRange($config['size'] ?? $this->defaultInputWidth, $this->minimumInputWidth, $this->maxInputWidth);
74 $width = (int)$this->formMaxWidth($size);
75
76 // Convert UTF-8 characters back (that is important, see Slug class when sanitizing)
77 $itemValue = rawurldecode($itemValue);
78
79 $fieldInformationResult = $this->renderFieldInformation();
80 $fieldInformationHtml = $fieldInformationResult['html'];
81 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldInformationResult, false);
82
83 $fieldControlResult = $this->renderFieldControl();
84 $fieldControlHtml = $fieldControlResult['html'];
85 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldControlResult, false);
86
87 $fieldWizardResult = $this->renderFieldWizard();
88 $fieldWizardHtml = $fieldWizardResult['html'];
89 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldWizardResult, false);
90 $toggleButtonTitle = $this->getLanguageService()->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:buttons.toggleSlugExplanation');
91
92 $thisSlugId = 't3js-form-field-slug-id' . StringUtility::getUniqueId();
93 $mainFieldHtml = [];
94 $mainFieldHtml[] = '<div class="formengine-field-item t3js-formengine-field-item">';
95 $mainFieldHtml[] = $fieldInformationHtml;
96 $mainFieldHtml[] = '<div class="form-control-wrap" style="max-width: ' . $width . 'px" id="' . htmlspecialchars($thisSlugId) . '">';
97 $mainFieldHtml[] = '<div class="form-wizards-wrap">';
98 $mainFieldHtml[] = '<div class="form-wizards-element">';
99 $mainFieldHtml[] = '<div class="input-group">';
100 $mainFieldHtml[] = ($baseUrl ? '<span class="input-group-addon">' . htmlspecialchars($baseUrl) . '</span>' : '');
101 // We deal with 3 fields here: a readonly field for current / default values, an input
102 // field to manipulate the value, and the final hidden field used to send the value
103 $mainFieldHtml[] = '<input';
104 $mainFieldHtml[] = ' class="form-control t3js-form-field-slug-readonly"';
105 $mainFieldHtml[] = ' data-toggle="tooltip"';
106 $mainFieldHtml[] = ' data-title="' . htmlspecialchars($itemValue) . '"';
107 $mainFieldHtml[] = ' value="' . htmlspecialchars($itemValue) . '"';
108 $mainFieldHtml[] = ' readonly';
109 $mainFieldHtml[] = ' />';
110 $mainFieldHtml[] = '<input type="text"';
111 $mainFieldHtml[] = ' id="' . htmlspecialchars(StringUtility::getUniqueId('formengine-input-')) . '"';
112 $mainFieldHtml[] = ' class="form-control t3js-form-field-slug-input hidden"';
113 $mainFieldHtml[] = ' placeholder="' . htmlspecialchars($row['slug'] ?? '/') . '"';
114 $mainFieldHtml[] = ' data-formengine-validation-rules="' . htmlspecialchars($this->getValidationDataAsJsonString($config)) . '"';
115 $mainFieldHtml[] = ' data-formengine-input-params="' . htmlspecialchars(json_encode(['field' => $parameterArray['itemFormElName'], 'evalList' => implode(',', $evalList)])) . '"';
116 $mainFieldHtml[] = ' data-formengine-input-name="' . htmlspecialchars($parameterArray['itemFormElName']) . '"';
117 $mainFieldHtml[] = ' />';
118 $mainFieldHtml[] = '<span class="input-group-btn">';
119 $mainFieldHtml[] = '<button class="btn btn-default t3js-form-field-slug-toggle" type="button" title="' . htmlspecialchars($toggleButtonTitle) . '">';
120 $mainFieldHtml[] = $this->iconFactory->getIcon('actions-version-workspaces-preview-link', Icon::SIZE_SMALL)->render();
121 $mainFieldHtml[] = '</button>';
122 $mainFieldHtml[] = '</span>';
123 $mainFieldHtml[] = '<input type="hidden"';
124 $mainFieldHtml[] = ' class="t3js-form-field-slug-hidden"';
125 $mainFieldHtml[] = ' name="' . htmlspecialchars($parameterArray['itemFormElName']) . '"';
126 $mainFieldHtml[] = ' value="' . htmlspecialchars($itemValue) . '"';
127 $mainFieldHtml[] = ' />';
128 $mainFieldHtml[] = '</div>';
129 $mainFieldHtml[] = '</div>';
130 if (!empty($fieldControlHtml)) {
131 $mainFieldHtml[] = '<div class="form-wizards-items-aside">';
132 $mainFieldHtml[] = '<div class="btn-group">';
133 $mainFieldHtml[] = $fieldControlHtml;
134 $mainFieldHtml[] = '</div>';
135 $mainFieldHtml[] = '</div>';
136 }
137 $mainFieldHtml[] = '<div class="form-wizards-items-bottom">';
138 $mainFieldHtml[] = '<span class="t3js-form-proposal-accepted hidden label label-success">Congrats, this page will look like ' . htmlspecialchars($baseUrl) . '<span>/abc/</span></span>';
139 $mainFieldHtml[] = '<span class="t3js-form-proposal-different hidden label label-warning">Hmm, that is taken, how about ' . htmlspecialchars($baseUrl) . '<span>/abc/</span></span>';
140 $mainFieldHtml[] = $fieldWizardHtml;
141 $mainFieldHtml[] = '</div>';
142 $mainFieldHtml[] = '</div>';
143 $mainFieldHtml[] = '</div>';
144 $mainFieldHtml[] = '</div>';
145
146 $resultArray['html'] = implode(LF, $mainFieldHtml);
147
148 list($commonElementPrefix) = GeneralUtility::revExplode('[', $parameterArray['itemFormElName'], 2);
149 $validInputNamesToListenTo = [];
150 foreach ($config['generatorOptions']['fields'] ?? [] as $listenerFieldName) {
151 $validInputNamesToListenTo[$listenerFieldName] = $commonElementPrefix . '[' . htmlspecialchars($listenerFieldName) . ']';
152 }
153 $signature = GeneralUtility::hmac(
154 implode(
155 '',
156 [
157 $table,
158 $this->data['vanillaUid'] < 0 ? abs($this->data['vanillaUid']) : $this->data['effectivePid'],
159 $row['uid'],
160 $languageId,
161 $this->data['fieldName'],
162 $this->data['command'],
163 ]
164 ),
165 FormSlugAjaxController::class
166 );
167 $optionsForModule = [
168 'pageId' => $this->data['vanillaUid'] < 0 ? abs($this->data['vanillaUid']) : $this->data['effectivePid'],
169 'recordId' => $row['uid'],
170 'tableName' => $table,
171 'fieldName' => $this->data['fieldName'],
172 'config' => $config,
173 'listenerFieldNames' => $validInputNamesToListenTo,
174 'language' => $languageId,
175 'originalValue' => $itemValue,
176 'signature' => $signature,
177 'command' => $this->data['command']
178 ];
179 $resultArray['requireJsModules'][] = ['TYPO3/CMS/Backend/FormEngine/Element/SlugElement' => '
180 function(SlugElement) {
181 SlugElement.initialize(' . GeneralUtility::quoteJSvalue('#' . $thisSlugId) . ', ' . json_encode($optionsForModule) . ');
182 }'
183 ];
184 return $resultArray;
185 }
186
187 /**
188 * Render the prefix for the input field.
189 *
190 * @param SiteInterface $site
191 * @param int $requestLanguageId
192 * @return string
193 */
194 protected function getPrefix(SiteInterface $site, int $requestLanguageId = 0): string
195 {
196 $language = $site->getLanguageById($requestLanguageId);
197 $base = $language->getBase();
198 $baseUrl = (string)$base;
199 $baseUrl = rtrim($baseUrl, '/');
200 if (!empty($baseUrl) && empty($base->getScheme()) && $base->getHost() !== '') {
201 $baseUrl = 'http:' . $baseUrl;
202 }
203 return $baseUrl;
204 }
205
206 /**
207 * @return LanguageService
208 */
209 protected function getLanguageService(): LanguageService
210 {
211 return $GLOBALS['LANG'];
212 }
213 }