[BUGFIX] rte_ckeditor triggers has-change on change
[Packages/TYPO3.CMS.git] / typo3 / sysext / rte_ckeditor / Classes / Form / Element / RichTextElement.php
1 <?php
2 declare(strict_types=1);
3 namespace TYPO3\CMS\RteCKEditor\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\Form\Element\AbstractFormElement;
19 use TYPO3\CMS\Backend\Routing\UriBuilder;
20 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
21 use TYPO3\CMS\Core\Localization\Locales;
22 use TYPO3\CMS\Core\Utility\GeneralUtility;
23 use TYPO3\CMS\Core\Utility\PathUtility;
24
25 /**
26 * Render rich text editor in FormEngine
27 */
28 class RichTextElement extends AbstractFormElement
29 {
30 /**
31 * Default field wizards enabled for this element.
32 *
33 * @var array
34 */
35 protected $defaultFieldWizard = [
36 'localizationStateSelector' => [
37 'renderType' => 'localizationStateSelector',
38 ],
39 'otherLanguageContent' => [
40 'renderType' => 'otherLanguageContent',
41 'after' => [
42 'localizationStateSelector'
43 ],
44 ],
45 'defaultLanguageDifferences' => [
46 'renderType' => 'defaultLanguageDifferences',
47 'after' => [
48 'otherLanguageContent',
49 ],
50 ],
51 ];
52
53 /**
54 * This property contains configuration related to the RTE
55 * But only the .editor configuration part
56 *
57 * @var array
58 */
59 protected $rteConfiguration = [];
60
61 /**
62 * Renders the ckeditor element
63 *
64 * @return array
65 * @throws \InvalidArgumentException
66 */
67 public function render() : array
68 {
69 $resultArray = $this->initializeResultArray();
70 $parameterArray = $this->data['parameterArray'];
71 $config = $parameterArray['fieldConf']['config'];
72
73 $fieldId = $this->sanitizeFieldId($parameterArray['itemFormElName']);
74 $itemFormElementName = $this->data['parameterArray']['itemFormElName'];
75
76 $value = $this->data['parameterArray']['itemFormElValue'] ?? '';
77
78 $legacyWizards = $this->renderWizards();
79 $legacyFieldControlHtml = implode(LF, $legacyWizards['fieldControl']);
80 $legacyFieldWizardHtml = implode(LF, $legacyWizards['fieldWizard']);
81
82 $fieldInformationResult = $this->renderFieldInformation();
83 $fieldInformationHtml = $fieldInformationResult['html'];
84 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldInformationResult, false);
85
86 $fieldControlResult = $this->renderFieldControl();
87 $fieldControlHtml = $legacyFieldControlHtml . $fieldControlResult['html'];
88 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldControlResult, false);
89
90 $fieldWizardResult = $this->renderFieldWizard();
91 $fieldWizardHtml = $legacyFieldWizardHtml . $fieldWizardResult['html'];
92 $resultArray = $this->mergeChildReturnIntoExistingResult($resultArray, $fieldWizardResult, false);
93
94 $attributes = [
95 'style' => 'display:none',
96 'data-formengine-validation-rules' => $this->getValidationDataAsJsonString($config),
97 'id' => $fieldId,
98 'name' => htmlspecialchars($itemFormElementName),
99 ];
100
101 $html = [];
102 $html[] = '<div class="formengine-field-item t3js-formengine-field-item">';
103 $html[] = $fieldInformationHtml;
104 $html[] = '<div class="form-control-wrap">';
105 $html[] = '<div class="form-wizards-wrap">';
106 $html[] = '<div class="form-wizards-element">';
107 $html[] = '<textarea ' . GeneralUtility::implodeAttributes($attributes, true) . '>';
108 $html[] = htmlspecialchars($value);
109 $html[] = '</textarea>';
110 $html[] = '</div>';
111 $html[] = '<div class="form-wizards-items-aside">';
112 $html[] = '<div class="btn-group">';
113 $html[] = $fieldControlHtml;
114 $html[] = '</div>';
115 $html[] = '</div>';
116 $html[] = '<div class="form-wizards-items-bottom">';
117 $html[] = $fieldWizardHtml;
118 $html[] = '</div>';
119 $html[] = '</div>';
120 $html[] = '</div>';
121 $html[] = '</div>';
122
123 $resultArray['html'] = implode(LF, $html);
124
125 $this->rteConfiguration = $config['richtextConfiguration']['editor'];
126 $resultArray['requireJsModules'] = [];
127 $resultArray['requireJsModules'][] = [
128 'ckeditor' => $this->getCkEditorRequireJsModuleCode($fieldId)
129 ];
130
131 return $resultArray;
132 }
133
134 /**
135 * Determine the contents language iso code
136 *
137 * @return string
138 */
139 protected function getLanguageIsoCodeOfContent(): string
140 {
141 $currentLanguageUid = $this->data['databaseRow']['sys_language_uid'];
142 if (is_array($currentLanguageUid)) {
143 $currentLanguageUid = $currentLanguageUid[0];
144 }
145 $contentLanguageUid = (int)max($currentLanguageUid, 0);
146 if ($contentLanguageUid) {
147 $contentLanguage = $this->data['systemLanguageRows'][$currentLanguageUid]['iso'];
148 } else {
149 $contentLanguage = $this->rteConfiguration['config']['defaultContentLanguage'] ?? 'en_US';
150 $languageCodeParts = explode('_', $contentLanguage);
151 $contentLanguage = strtolower($languageCodeParts[0]) . ($languageCodeParts[1] ? '_' . strtoupper($languageCodeParts[1]) : '');
152 // Find the configured language in the list of localization locales
153 $locales = GeneralUtility::makeInstance(Locales::class);
154 // If not found, default to 'en'
155 if (!in_array($contentLanguage, $locales->getLocales(), true)) {
156 $contentLanguage = 'en';
157 }
158 }
159 return $contentLanguage;
160 }
161
162 /**
163 * Gets the JavaScript code for CKEditor module
164 * Compiles the configuration, and then adds plugins
165 *
166 * @param string $fieldId
167 * @return string
168 */
169 protected function getCkEditorRequireJsModuleCode(string $fieldId) : string
170 {
171 $configuration = $this->prepareConfigurationForEditor();
172
173 $externalPlugins = '';
174 foreach ($this->getExtraPlugins() as $pluginName => $config) {
175 $configuration[$pluginName] = $config['config'];
176 $configuration['extraPlugins'] .= ',' . $pluginName;
177
178 $externalPlugins .= 'CKEDITOR.plugins.addExternal(';
179 $externalPlugins .= GeneralUtility::quoteJSvalue($pluginName) . ',';
180 $externalPlugins .= GeneralUtility::quoteJSvalue($config['resource']) . ',';
181 $externalPlugins .= '\'\');';
182 }
183
184 return 'function(CKEDITOR) {
185 ' . $externalPlugins . '
186 CKEDITOR.replace("' . $fieldId . '", ' . json_encode($configuration) . ');
187 require([\'jquery\', \'TYPO3/CMS/Backend/FormEngine\'], function($, FormEngine) {
188 CKEDITOR.instances.' . $fieldId . '.on(\'change\', function() {
189 CKEDITOR.instances.' . $fieldId . '.updateElement();
190 FormEngine.Validation.validate();
191 FormEngine.Validation.markFieldAsChanged($(\'#' . $fieldId . '\'));
192 });
193 });
194 }';
195 }
196
197 /**
198 * Get configuration of external/additional plugins
199 *
200 * @return array
201 */
202 protected function getExtraPlugins(): array
203 {
204 $urlParameters = [
205 'P' => [
206 'table' => $this->data['tableName'],
207 'uid' => $this->data['databaseRow']['uid'],
208 'fieldName' => $this->data['fieldName'],
209 'recordType' => $this->data['recordTypeValue'],
210 'pid' => $this->data['effectivePid'],
211 ]
212 ];
213
214 $pluginConfiguration = [];
215 if (isset($this->rteConfiguration['externalPlugins']) && is_array($this->rteConfiguration['externalPlugins'])) {
216 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
217 foreach ($this->rteConfiguration['externalPlugins'] as $pluginName => $configuration) {
218 $pluginConfiguration[$pluginName] = [
219 'resource' => $this->resolveUrlPath($configuration['resource'])
220 ];
221 unset($configuration['resource']);
222
223 if ($configuration['route']) {
224 $configuration['routeUrl'] = (string)$uriBuilder->buildUriFromRoute($configuration['route'], $urlParameters);
225 }
226
227 $pluginConfiguration[$pluginName]['config'] = $configuration;
228 }
229 }
230 return $pluginConfiguration;
231 }
232
233 /**
234 * Add configuration to replace LLL: references with the translated value
235 * @param array $configuration
236 *
237 * @return array
238 */
239 protected function replaceLanguageFileReferences(array $configuration): array
240 {
241 foreach ($configuration as $key => $value) {
242 if (is_array($value)) {
243 $configuration[$key] = $this->replaceLanguageFileReferences($value);
244 } elseif (is_string($value) && stripos($value, 'LLL:') === 0) {
245 $configuration[$key] = $this->getLanguageService()->sL($value);
246 }
247 }
248 return $configuration;
249 }
250
251 /**
252 * Add configuration to replace absolute EXT: paths with relative ones
253 * @param array $configuration
254 *
255 * @return array
256 */
257 protected function replaceAbsolutePathsToRelativeResourcesPath(array $configuration): array
258 {
259 foreach ($configuration as $key => $value) {
260 if (is_array($value)) {
261 $configuration[$key] = $this->replaceAbsolutePathsToRelativeResourcesPath($value);
262 } elseif (is_string($value) && stripos($value, 'EXT:') === 0) {
263 $configuration[$key] = $this->resolveUrlPath($value);
264 }
265 }
266 return $configuration;
267 }
268
269 /**
270 * Resolves an EXT: syntax file to an absolute web URL
271 *
272 * @param string $value
273 * @return string
274 */
275 protected function resolveUrlPath(string $value): string
276 {
277 $value = GeneralUtility::getFileAbsFileName($value);
278 return PathUtility::getAbsoluteWebPath($value);
279 }
280
281 /**
282 * Compiles the configuration set from the outside
283 * to have it easily injected into the CKEditor.
284 *
285 * @return array the configuration
286 */
287 protected function prepareConfigurationForEditor(): array
288 {
289 // Ensure custom config is empty so nothing additional is loaded
290 // Of course this can be overridden by the editor configuration below
291 $configuration = [
292 'customConfig' => '',
293 ];
294
295 if (is_array($this->rteConfiguration['config'])) {
296 $configuration = array_replace_recursive($configuration, $this->rteConfiguration['config']);
297 }
298 // Set the UI language of the editor if not hard-coded by the existing configuration
299 if (empty($configuration['language'])) {
300 $configuration['language'] = $this->getBackendUser()->uc['lang'] ?: ($this->getBackendUser()->user['lang'] ?: 'en');
301 }
302 $configuration['contentsLanguage'] = $this->getLanguageIsoCodeOfContent();
303
304 // Replace all label references
305 $configuration = $this->replaceLanguageFileReferences($configuration);
306 // Replace all paths
307 $configuration = $this->replaceAbsolutePathsToRelativeResourcesPath($configuration);
308
309 // there are some places where we define an array, but it needs to be a list in order to work
310 if (is_array($configuration['extraPlugins'])) {
311 $configuration['extraPlugins'] = implode(',', $configuration['extraPlugins']);
312 }
313 if (is_array($configuration['removePlugins'])) {
314 $configuration['removePlugins'] = implode(',', $configuration['removePlugins']);
315 }
316 if (is_array($configuration['removeButtons'])) {
317 $configuration['removeButtons'] = implode(',', $configuration['removeButtons']);
318 }
319
320 return $configuration;
321 }
322
323 /**
324 * @param string $itemFormElementName
325 * @return string
326 */
327 protected function sanitizeFieldId(string $itemFormElementName): string
328 {
329 $fieldId = preg_replace('/[^a-zA-Z0-9_:.-]/', '_', $itemFormElementName);
330 return htmlspecialchars(preg_replace('/^[^a-zA-Z]/', 'x', $fieldId));
331 }
332
333 /**
334 * @return BackendUserAuthentication
335 */
336 protected function getBackendUser()
337 {
338 return $GLOBALS['BE_USER'];
339 }
340 }