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