[TASK] Use null coalescing operator where possible
[Packages/TYPO3.CMS.git] / typo3 / sysext / rte_ckeditor / Classes / Controller / BrowseLinksController.php
1 <?php
2 declare(strict_types=1);
3 namespace TYPO3\CMS\RteCKEditor\Controller;
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 Psr\Http\Message\ServerRequestInterface;
19 use TYPO3\CMS\Core\Configuration\Richtext;
20 use TYPO3\CMS\Core\LinkHandling\LinkService;
21 use TYPO3\CMS\Core\Localization\LanguageService;
22 use TYPO3\CMS\Core\Page\PageRenderer;
23 use TYPO3\CMS\Core\Utility\GeneralUtility;
24 use TYPO3\CMS\Recordlist\Controller\AbstractLinkBrowserController;
25
26 /**
27 * Extended controller for link browser
28 */
29 class BrowseLinksController extends AbstractLinkBrowserController
30 {
31 /**
32 * @var string
33 */
34 protected $editorId;
35
36 /**
37 * TYPO3 language code of the content language
38 *
39 * @var int
40 */
41 protected $contentsLanguage;
42
43 /**
44 * Language service object for localization to the content language
45 *
46 * @var LanguageService
47 */
48 protected $contentLanguageService;
49
50 /**
51 * @var array
52 */
53 protected $buttonConfig = [];
54
55 /**
56 * @var array
57 */
58 protected $thisConfig = [];
59
60 /**
61 * @var array
62 */
63 protected $classesAnchorDefault = [];
64
65 /**
66 * @var array
67 */
68 protected $classesAnchorDefaultTitle = [];
69
70 /**
71 * @var array
72 */
73 protected $classesAnchorClassTitle = [];
74
75 /**
76 * @var array
77 */
78 protected $classesAnchorDefaultTarget = [];
79
80 /**
81 * @var array
82 */
83 protected $classesAnchorJSOptions = [];
84
85 /**
86 * @var string
87 */
88 protected $defaultLinkTarget = '';
89
90 /**
91 * @var array
92 */
93 protected $additionalAttributes = [];
94
95 /**
96 * @var string
97 */
98 protected $siteUrl = '';
99
100 /**
101 * Initialize controller
102 */
103 protected function init()
104 {
105 parent::init();
106
107 $this->contentLanguageService = GeneralUtility::makeInstance(LanguageService::class);
108 }
109
110 /**
111 * @param ServerRequestInterface $request
112 */
113 protected function initVariables(ServerRequestInterface $request)
114 {
115 parent::initVariables($request);
116
117 $queryParameters = $request->getQueryParams();
118
119 $this->siteUrl = GeneralUtility::getIndpEnv('TYPO3_SITE_URL');
120
121 $this->currentLinkParts = $queryParameters['curUrl'] ?? [];
122 $this->editorId = $queryParameters['editorId'];
123 $this->contentsLanguage = $queryParameters['contentsLanguage'];
124 $this->RTEtsConfigParams = $queryParameters['RTEtsConfigParams'] ?? null;
125
126 $this->contentLanguageService->init($this->contentsLanguage);
127
128 /** @var Richtext $richtextConfigurationProvider */
129 $richtextConfigurationProvider = GeneralUtility::makeInstance(Richtext::class);
130 $this->thisConfig = $richtextConfigurationProvider->getConfiguration(
131 $this->parameters['table'],
132 $this->parameters['fieldName'],
133 (int)$this->parameters['pid'],
134 $this->parameters['recordType'],
135 ['richtext' => true]
136 );
137 $this->buttonConfig = $this->thisConfig['buttons']['link'] ?? [];
138 }
139
140 /**
141 * Initialize document template object
142 */
143 protected function initDocumentTemplate()
144 {
145 parent::initDocumentTemplate();
146
147 $pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
148 $pageRenderer->loadRequireJsModule(
149 'TYPO3/CMS/RteCkeditor/RteLinkBrowser',
150 'function(RteLinkBrowser) {
151 RteLinkBrowser.initialize(' . GeneralUtility::quoteJSvalue($this->editorId) . ');
152 }'
153 );
154 }
155
156 /**
157 * Initialize $this->currentLink and $this->currentLinkHandler
158 */
159 protected function initCurrentUrl()
160 {
161 if (empty($this->currentLinkParts)) {
162 return;
163 }
164
165 if (!empty($this->currentLinkParts['url'])) {
166 $linkService = GeneralUtility::makeInstance(LinkService::class);
167 $data = $linkService->resolve($this->currentLinkParts['url']);
168 $this->currentLinkParts['type'] = $data['type'];
169 unset($data['type']);
170 $this->currentLinkParts['url'] = $data;
171 }
172
173 if (!empty($this->currentLinkParts['class'])) {
174 // Only keep last class value (others are automatically added again by required option)
175 // https://review.typo3.org/#/c/29643
176 $currentClasses = GeneralUtility::trimExplode(' ', $this->currentLinkParts['class'], true);
177 if (count($currentClasses) > 1) {
178 $this->currentLinkParts['class'] = end($currentClasses);
179 }
180 }
181 parent::initCurrentUrl();
182 }
183
184 /**
185 * Renders the link attributes for the selected link handler
186 *
187 * @return string
188 */
189 public function renderLinkAttributeFields()
190 {
191 // Processing the classes configuration
192 if (!empty($this->buttonConfig['properties']['class']['allowedClasses'])) {
193 $classesAnchorArray = is_array($this->buttonConfig['properties']['class']['allowedClasses']) ? $this->buttonConfig['properties']['class']['allowedClasses'] : GeneralUtility::trimExplode(',', $this->buttonConfig['properties']['class']['allowedClasses'], true);
194 // Collecting allowed classes and configured default values
195 $classesAnchor = [
196 'all' => []
197 ];
198
199 if (is_array($this->thisConfig['classesAnchor'])) {
200 foreach ($this->thisConfig['classesAnchor'] as $label => $conf) {
201 if (in_array($conf['class'], $classesAnchorArray, true)) {
202 $classesAnchor['all'][] = $conf['class'];
203 if ($conf['type'] === $this->displayedLinkHandlerId) {
204 $classesAnchor[$conf['type']][] = $conf['class'];
205 if ($this->buttonConfig[$conf['type']]['properties']['class']['default'] == $conf['class']) {
206 $this->classesAnchorDefault[$conf['type']] = $conf['class'];
207 if ($conf['titleText']) {
208 $this->classesAnchorDefaultTitle[$conf['type']] = $this->contentLanguageService->sL(trim($conf['titleText']));
209 }
210 if (isset($conf['target'])) {
211 $this->classesAnchorDefaultTarget[$conf['type']] = trim($conf['target']);
212 }
213 }
214 }
215 if ($conf['titleText']) {
216 $this->classesAnchorClassTitle[$conf['class']] = ($this->classesAnchorDefaultTitle[$conf['type']] = $this->contentLanguageService->sL(trim($conf['titleText'])));
217 }
218 }
219 }
220 }
221 if (isset($this->linkAttributeValues['class'])
222 && isset($classesAnchor[$this->displayedLinkHandlerId])
223 && !in_array($this->linkAttributeValues['class'], $classesAnchor[$this->displayedLinkHandlerId], true)
224 ) {
225 unset($this->linkAttributeValues['class']);
226 }
227 // Constructing the class selector options
228 foreach ($classesAnchorArray as $class) {
229 if (!in_array($class, $classesAnchor['all']) || in_array($class, $classesAnchor['all']) && is_array($classesAnchor[$this->displayedLinkHandlerId]) && in_array($class, $classesAnchor[$this->displayedLinkHandlerId])) {
230 $selected = '';
231 if ($this->linkAttributeValues['class'] === $class || !$this->linkAttributeValues['class'] && $this->classesAnchorDefault[$this->displayedLinkHandlerId] == $class) {
232 $selected = 'selected="selected"';
233 }
234 $classLabel = !empty($this->thisConfig['classes'][$class]['name'])
235 ? $this->getPageConfigLabel($this->thisConfig['classes'][$class]['name'], 0)
236 : $class;
237 $classStyle = !empty($this->thisConfig['classes'][$class]['value'])
238 ? $this->thisConfig['classes'][$class]['value']
239 : '';
240 $title = $this->classesAnchorClassTitle[$class] ?? $this->classesAnchorDefaultTitle[$class] ?? '';
241 $this->classesAnchorJSOptions[$this->displayedLinkHandlerId] .= '<option ' . $selected . ' value="' . htmlspecialchars($class) . '"'
242 . ($classStyle ? ' style="' . htmlspecialchars($classStyle) . '"' : '')
243 . 'data-link-title="' . htmlspecialchars($title) . '"'
244 . '>' . htmlspecialchars($classLabel)
245 . '</option>';
246 }
247 }
248 if ($this->classesAnchorJSOptions[$this->displayedLinkHandlerId] && !($this->buttonConfig['properties']['class']['required'] || $this->buttonConfig[$this->displayedLinkHandlerId]['properties']['class']['required'])) {
249 $selected = '';
250 if (!$this->linkAttributeValues['class'] && !$this->classesAnchorDefault[$this->displayedLinkHandlerId]) {
251 $selected = 'selected="selected"';
252 }
253 $this->classesAnchorJSOptions[$this->displayedLinkHandlerId] = '<option ' . $selected . ' value=""></option>' . $this->classesAnchorJSOptions[$this->displayedLinkHandlerId];
254 }
255 }
256 // Default target
257 $this->defaultLinkTarget = $this->classesAnchorDefault[$this->displayedLinkHandlerId] && $this->classesAnchorDefaultTarget[$this->displayedLinkHandlerId]
258 ? $this->classesAnchorDefaultTarget[$this->displayedLinkHandlerId]
259 : ($this->buttonConfig[$this->displayedLinkHandlerId]['properties']['target']['default'] ?? $this->buttonConfig['properties']['target']['default'] ?? '');
260
261 // todo: find new name for this option
262 // Initializing additional attributes
263 if ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['rte_ckeditor']['plugins']['TYPO3Link']['additionalAttributes']) {
264 $addAttributes = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['rte_ckeditor']['plugins']['TYPO3Link']['additionalAttributes'], true);
265 foreach ($addAttributes as $attribute) {
266 $this->additionalAttributes[$attribute] = $this->linkAttributeValues[$attribute] ?? '';
267 }
268 }
269 return parent::renderLinkAttributeFields();
270 }
271
272 /**
273 * Localize a label obtained from Page TSConfig
274 *
275 * @param string $string The label to be localized
276 * @param bool $JScharCode If needs to be converted to an array of char numbers
277 * @return string Localized string
278 */
279 public function getPageConfigLabel($string, $JScharCode = true)
280 {
281 if (strpos($string, 'LLL:') !== 0) {
282 $label = $string;
283 } else {
284 $label = $this->getLanguageService()->sL(trim($string));
285 }
286 $label = str_replace('"', '\\"', str_replace('\\\'', '\'', $label));
287 return $JScharCode ? GeneralUtility::quoteJSvalue($label) : $label;
288 }
289
290 /**
291 * @return string
292 */
293 protected function renderCurrentUrl()
294 {
295 $removeLink = ' <a href="#" class="t3js-removeCurrentLink">' . htmlspecialchars($this->getLanguageService()->getLL('removeLink')) . '</a>';
296 return '
297 <div class="element-browser-panel element-browser-title">' .
298 htmlspecialchars($this->getLanguageService()->getLL('currentLink')) .
299 ': ' .
300 htmlspecialchars($this->currentLinkHandler->formatCurrentUrl()) .
301 '<span class="pull-right">' . $removeLink . '</span>' .
302 '</div>';
303 }
304
305 /**
306 * Get the allowed items or tabs
307 *
308 * @return string[]
309 */
310 protected function getAllowedItems()
311 {
312 $allowedItems = parent::getAllowedItems();
313
314 $blindLinkOptions = isset($this->thisConfig['blindLinkOptions'])
315 ? GeneralUtility::trimExplode(',', $this->thisConfig['blindLinkOptions'], true)
316 : [];
317 $allowedItems = array_diff($allowedItems, $blindLinkOptions);
318
319 if (is_array($this->buttonConfig['options']) && $this->buttonConfig['options']['removeItems']) {
320 $allowedItems = array_diff($allowedItems, GeneralUtility::trimExplode(',', $this->buttonConfig['options']['removeItems'], true));
321 }
322
323 return $allowedItems;
324 }
325
326 /**
327 * Get the allowed link attributes
328 *
329 * @return string[]
330 */
331 protected function getAllowedLinkAttributes()
332 {
333 $allowedLinkAttributes = parent::getAllowedLinkAttributes();
334
335 $blindLinkFields = isset($this->thisConfig['blindLinkFields'])
336 ? GeneralUtility::trimExplode(',', $this->thisConfig['blindLinkFields'], true)
337 : [];
338 $allowedLinkAttributes = array_diff($allowedLinkAttributes, $blindLinkFields);
339
340 return $allowedLinkAttributes;
341 }
342
343 /**
344 * Create an array of link attribute field rendering definitions
345 *
346 * @return string[]
347 */
348 protected function getLinkAttributeFieldDefinitions()
349 {
350 $fieldRenderingDefinitions = parent::getLinkAttributeFieldDefinitions();
351 $fieldRenderingDefinitions['title'] = $this->getTitleField();
352 $fieldRenderingDefinitions['class'] = $this->getClassField();
353 $fieldRenderingDefinitions['target'] = $this->getTargetField();
354 $fieldRenderingDefinitions['rel'] = $this->getRelField();
355 if (empty($this->buttonConfig['queryParametersSelector']['enabled'])) {
356 unset($fieldRenderingDefinitions['params']);
357 }
358 return $fieldRenderingDefinitions;
359 }
360
361 /**
362 * Add rel field
363 *
364 * @return string
365 */
366 protected function getRelField()
367 {
368 if (empty($this->buttonConfig['relAttribute']['enabled'])) {
369 return '';
370 }
371
372 $currentRel = '';
373 if ($this->displayedLinkHandler === $this->currentLinkHandler
374 && !empty($this->currentLinkParts)
375 && isset($this->linkAttributeValues['rel'])
376 && is_string($this->linkAttributeValues['rel'])
377 ) {
378 $currentRel = $this->linkAttributeValues['rel'];
379 }
380
381 return '
382 <form action="" name="lrelform" id="lrelform" class="t3js-dummyform form-horizontal">
383 <div class="form-group form-group-sm">
384 <label class="col-xs-4 control-label">' .
385 htmlspecialchars($this->getLanguageService()->getLL('linkRelationship')) .
386 '</label>
387 <div class="col-xs-8">
388 <input type="text" name="lrel" class="form-control" value="' . htmlspecialchars($currentRel) . '" />
389 </div>
390 </div>
391 </form>
392 ';
393 }
394
395 /**
396 * Add target selector
397 *
398 * @return string
399 */
400 protected function getTargetField()
401 {
402 $targetSelectorConfig = [];
403 if (is_array($this->buttonConfig['targetSelector'])) {
404 $targetSelectorConfig = $this->buttonConfig['targetSelector'];
405 }
406 $target = $this->linkAttributeValues['target'] ?: $this->defaultLinkTarget;
407 $lang = $this->getLanguageService();
408 $targetSelector = '';
409
410 if (!$targetSelectorConfig['disabled']) {
411 $targetSelector = '
412 <select name="ltarget_type" class="t3js-targetPreselect form-control">
413 <option value=""></option>
414 <option value="_top">' . htmlspecialchars($lang->getLL('top')) . '</option>
415 <option value="_blank">' . htmlspecialchars($lang->getLL('newWindow')) . '</option>
416 </select>
417 ';
418 }
419
420 return '
421 <form action="" name="ltargetform" id="ltargetform" class="t3js-dummyform form-horizontal">
422 <div class="form-group form-group-sm" ' . ($targetSelectorConfig['disabled'] ? ' style="display: none;"' : '') . '>
423 <label class="col-xs-4 control-label">' . htmlspecialchars($lang->getLL('target')) . '</label>
424 <div class="col-xs-4">
425 <input type="text" name="ltarget" class="t3js-linkTarget form-control"
426 value="' . htmlspecialchars($target) . '" />
427 </div>
428 <div class="col-xs-4">
429 ' . $targetSelector . '
430 </div>
431 </div>
432 </form>
433 ';
434 }
435
436 /**
437 * Add title selector
438 *
439 * @return string
440 */
441 protected function getTitleField()
442 {
443 if ($this->linkAttributeValues['title']) {
444 $title = $this->linkAttributeValues['title'];
445 } else {
446 $title = $this->classesAnchorDefaultTitle[$this->displayedLinkHandlerId] ?: '';
447 }
448 if (isset($this->buttonConfig[$this->displayedLinkHandlerId]['properties']['title']['readOnly'])) {
449 $readOnly = (bool)$this->buttonConfig[$this->displayedLinkHandlerId]['properties']['title']['readOnly'];
450 } else {
451 $readOnly = isset($this->buttonConfig['properties']['title']['readOnly'])
452 ? (bool)$this->buttonConfig['properties']['title']['readOnly']
453 : false;
454 }
455
456 if ($readOnly) {
457 $currentClass = $this->linkAttributeFields['class'];
458 if (!$currentClass) {
459 $currentClass = empty($this->classesAnchorDefault[$this->displayedLinkHandlerId]) ? '' : $this->classesAnchorDefault[$this->displayedLinkHandlerId];
460 }
461 $title = $currentClass
462 ? $this->classesAnchorClassTitle[$currentClass]
463 : ($this->classesAnchorDefaultTitle[$this->displayedLinkHandlerId] ?? '');
464 }
465 return '
466 <form action="" name="ltitleform" id="ltitleform" class="t3js-dummyform form-horizontal">
467 <div class="form-group form-group-sm">
468 <label class="col-xs-4 control-label">
469 ' . htmlspecialchars($this->getLanguageService()->getLL('title')) . '
470 </label>
471 <div class="col-xs-8">
472 <input ' . ($readOnly ? 'disabled' : '') . ' type="text" name="ltitle" class="form-control t3js-linkTitle"
473 value="' . htmlspecialchars($title) . '" />
474 </div>
475 </div>
476 </form>
477 ';
478 }
479
480 /**
481 * Return html code for the class selector
482 *
483 * @return string the html code to be added to the form
484 */
485 protected function getClassField()
486 {
487 $selectClass = '';
488 if ($this->classesAnchorJSOptions[$this->displayedLinkHandlerId]) {
489 $selectClass = '
490 <form action="" name="lclassform" id="lclassform" class="t3js-dummyform form-horizontal">
491 <div class="form-group form-group-sm">
492 <label class="col-xs-4 control-label">
493 ' . htmlspecialchars($this->getLanguageService()->getLL('class')) . '
494 </label>
495 <div class="col-xs-8">
496 <select name="lclass" class="t3js-class-selector form-control">
497 ' . $this->classesAnchorJSOptions[$this->displayedLinkHandlerId] . '
498 </select>
499 </div>
500 </div>
501 </form>
502 ';
503 }
504 return $selectClass;
505 }
506
507 /**
508 * Return the ID of current page
509 *
510 * @return int
511 */
512 protected function getCurrentPageId()
513 {
514 return (int)$this->parameters['pid'];
515 }
516
517 /**
518 * Retrieve the configuration
519 *
520 * This is only used by RTE currently.
521 *
522 * @return array
523 */
524 public function getConfiguration()
525 {
526 return $this->buttonConfig;
527 }
528
529 /**
530 * Get attributes for the body tag
531 *
532 * @return string[] Array of body-tag attributes
533 */
534 protected function getBodyTagAttributes()
535 {
536 $parameters = parent::getBodyTagAttributes();
537 $parameters['data-site-url'] = $this->siteUrl;
538 $parameters['data-default-link-target'] = $this->defaultLinkTarget;
539 return $parameters;
540 }
541
542 /**
543 * @param array $overrides
544 *
545 * @return array Array of parameters which have to be added to URLs
546 */
547 public function getUrlParameters(array $overrides = null)
548 {
549 return [
550 'act' => $overrides['act'] ?? $this->displayedLinkHandlerId,
551 'editorId' => $this->editorId,
552 'contentsLanguage' => $this->contentsLanguage,
553 'P' => $this->parameters
554 ];
555 }
556 }