6f92942f5848ffb84b22784c2553c771e2845d9a
[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([\'TYPO3/CMS/Backend/FormEngine\'], function(FormEngine) {
188 CKEDITOR.instances.' . $fieldId . '.on(\'change\', function() {
189 CKEDITOR.instances.' . $fieldId . '.updateElement();
190 FormEngine.Validation.validate();
191 });
192 });
193 }';
194 }
195
196 /**
197 * Get configuration of external/additional plugins
198 *
199 * @return array
200 */
201 protected function getExtraPlugins(): array
202 {
203 $urlParameters = [
204 'P' => [
205 'table' => $this->data['tableName'],
206 'uid' => $this->data['databaseRow']['uid'],
207 'fieldName' => $this->data['fieldName'],
208 'recordType' => $this->data['recordTypeValue'],
209 'pid' => $this->data['effectivePid'],
210 ]
211 ];
212
213 $pluginConfiguration = [];
214 if (isset($this->rteConfiguration['externalPlugins']) && is_array($this->rteConfiguration['externalPlugins'])) {
215 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
216 foreach ($this->rteConfiguration['externalPlugins'] as $pluginName => $configuration) {
217 $pluginConfiguration[$pluginName] = [
218 'resource' => $this->resolveUrlPath($configuration['resource'])
219 ];
220 unset($configuration['resource']);
221
222 if ($configuration['route']) {
223 $configuration['routeUrl'] = (string)$uriBuilder->buildUriFromRoute($configuration['route'], $urlParameters);
224 }
225
226 $pluginConfiguration[$pluginName]['config'] = $configuration;
227 }
228 }
229 return $pluginConfiguration;
230 }
231
232 /**
233 * Add configuration to replace LLL: references with the translated value
234 * @param array $configuration
235 *
236 * @return array
237 */
238 protected function replaceLanguageFileReferences(array $configuration): array
239 {
240 foreach ($configuration as $key => $value) {
241 if (is_array($value)) {
242 $configuration[$key] = $this->replaceLanguageFileReferences($value);
243 } elseif (is_string($value) && stripos($value, 'LLL:') === 0) {
244 $configuration[$key] = $this->getLanguageService()->sL($value);
245 }
246 }
247 return $configuration;
248 }
249
250 /**
251 * Add configuration to replace absolute EXT: paths with relative ones
252 * @param array $configuration
253 *
254 * @return array
255 */
256 protected function replaceAbsolutePathsToRelativeResourcesPath(array $configuration): array
257 {
258 foreach ($configuration as $key => $value) {
259 if (is_array($value)) {
260 $configuration[$key] = $this->replaceAbsolutePathsToRelativeResourcesPath($value);
261 } elseif (is_string($value) && stripos($value, 'EXT:') === 0) {
262 $configuration[$key] = $this->resolveUrlPath($value);
263 }
264 }
265 return $configuration;
266 }
267
268 /**
269 * Resolves an EXT: syntax file to an absolute web URL
270 *
271 * @param string $value
272 * @return string
273 */
274 protected function resolveUrlPath(string $value): string
275 {
276 $value = GeneralUtility::getFileAbsFileName($value);
277 return PathUtility::getAbsoluteWebPath($value);
278 }
279
280 /**
281 * Compiles the configuration set from the outside
282 * to have it easily injected into the CKEditor.
283 *
284 * @return array the configuration
285 */
286 protected function prepareConfigurationForEditor(): array
287 {
288 // Ensure custom config is empty so nothing additional is loaded
289 // Of course this can be overridden by the editor configuration below
290 $configuration = [
291 'customConfig' => '',
292 ];
293
294 if (is_array($this->rteConfiguration['config'])) {
295 $configuration = array_replace_recursive($configuration, $this->rteConfiguration['config']);
296 }
297 // Set the UI language of the editor if not hard-coded by the existing configuration
298 if (empty($configuration['language'])) {
299 $configuration['language'] = $this->getBackendUser()->uc['lang'] ?: ($this->getBackendUser()->user['lang'] ?: 'en');
300 }
301 $configuration['contentsLanguage'] = $this->getLanguageIsoCodeOfContent();
302
303 // Replace all label references
304 $configuration = $this->replaceLanguageFileReferences($configuration);
305 // Replace all paths
306 $configuration = $this->replaceAbsolutePathsToRelativeResourcesPath($configuration);
307
308 // there are some places where we define an array, but it needs to be a list in order to work
309 if (is_array($configuration['extraPlugins'])) {
310 $configuration['extraPlugins'] = implode(',', $configuration['extraPlugins']);
311 }
312 if (is_array($configuration['removePlugins'])) {
313 $configuration['removePlugins'] = implode(',', $configuration['removePlugins']);
314 }
315 if (is_array($configuration['removeButtons'])) {
316 $configuration['removeButtons'] = implode(',', $configuration['removeButtons']);
317 }
318
319 return $configuration;
320 }
321
322 /**
323 * @param string $itemFormElementName
324 * @return string
325 */
326 protected function sanitizeFieldId(string $itemFormElementName): string
327 {
328 $fieldId = preg_replace('/[^a-zA-Z0-9_:.-]/', '_', $itemFormElementName);
329 return htmlspecialchars(preg_replace('/^[^a-zA-Z]/', 'x', $fieldId));
330 }
331
332 /**
333 * @return BackendUserAuthentication
334 */
335 protected function getBackendUser()
336 {
337 return $GLOBALS['BE_USER'];
338 }
339 }