BrowseLinksController.php 20.2 KB
Newer Older
1
<?php
2

3
declare(strict_types=1);
4
5
6
7
8
9
10
11
12
13
14
15
16
17

/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

18
19
namespace TYPO3\CMS\RteCKEditor\Controller;

20
use Psr\Http\Message\ServerRequestInterface;
21
use TYPO3\CMS\Core\Configuration\Richtext;
22
use TYPO3\CMS\Core\LinkHandling\LinkService;
23
use TYPO3\CMS\Core\Localization\LanguageService;
24
25
26
27
28
29
use TYPO3\CMS\Core\Page\PageRenderer;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Recordlist\Controller\AbstractLinkBrowserController;

/**
 * Extended controller for link browser
30
 * @internal This is a specific Backend Controller implementation and is not considered part of the Public TYPO3 API.
31
32
33
34
35
36
37
38
39
40
41
 */
class BrowseLinksController extends AbstractLinkBrowserController
{
    /**
     * @var string
     */
    protected $editorId;

    /**
     * TYPO3 language code of the content language
     *
42
     * @var string
43
     */
44
    protected $contentsLanguage;
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122

    /**
     * Language service object for localization to the content language
     *
     * @var LanguageService
     */
    protected $contentLanguageService;

    /**
     * @var array
     */
    protected $buttonConfig = [];

    /**
     * @var array
     */
    protected $thisConfig = [];

    /**
     * @var array
     */
    protected $classesAnchorDefault = [];

    /**
     * @var array
     */
    protected $classesAnchorDefaultTitle = [];

    /**
     * @var array
     */
    protected $classesAnchorClassTitle = [];

    /**
     * @var array
     */
    protected $classesAnchorDefaultTarget = [];

    /**
     * @var array
     */
    protected $classesAnchorJSOptions = [];

    /**
     * @var string
     */
    protected $defaultLinkTarget = '';

    /**
     * @var array
     */
    protected $additionalAttributes = [];

    /**
     * @var string
     */
    protected $siteUrl = '';

    /**
     * Initialize controller
     */
    protected function init()
    {
        parent::init();
        $this->contentLanguageService = GeneralUtility::makeInstance(LanguageService::class);
    }

    /**
     * @param ServerRequestInterface $request
     */
    protected function initVariables(ServerRequestInterface $request)
    {
        parent::initVariables($request);

        $queryParameters = $request->getQueryParams();

        $this->siteUrl = GeneralUtility::getIndpEnv('TYPO3_SITE_URL');

123
        $this->currentLinkParts = $queryParameters['P']['curUrl'] ?? [];
124
125
        $this->editorId = $queryParameters['editorId'];
        $this->contentsLanguage = $queryParameters['contentsLanguage'];
126

127
        $this->contentLanguageService = LanguageService::create($this->contentsLanguage);
128

129
130
131
132
133
        $tcaFieldConf = ['enableRichtext' => true];
        if (!empty($queryParameters['P']['richtextConfigurationName'])) {
            $tcaFieldConf['richtextConfiguration'] = $queryParameters['P']['richtextConfigurationName'];
        }

134
        /** @var Richtext $richtextConfigurationProvider */
135
        $richtextConfigurationProvider = GeneralUtility::makeInstance(Richtext::class);
136
        $this->thisConfig = $richtextConfigurationProvider->getConfiguration(
137
138
139
140
            $this->parameters['table'],
            $this->parameters['fieldName'],
            (int)$this->parameters['pid'],
            $this->parameters['recordType'],
141
            $tcaFieldConf
142
        );
143
        $this->buttonConfig = $this->thisConfig['buttons']['link'] ?? [];
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
    }

    protected function initDocumentTemplate()
    {
        parent::initDocumentTemplate();
        $pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
        $pageRenderer->loadRequireJsModule(
            'TYPO3/CMS/RteCkeditor/RteLinkBrowser',
            'function(RteLinkBrowser) {
                RteLinkBrowser.initialize(' . GeneralUtility::quoteJSvalue($this->editorId) . ');
            }'
        );
    }

    /**
     * Initialize $this->currentLink and $this->currentLinkHandler
     */
    protected function initCurrentUrl()
    {
        if (empty($this->currentLinkParts)) {
            return;
        }

        if (!empty($this->currentLinkParts['url'])) {
            $linkService = GeneralUtility::makeInstance(LinkService::class);
            $data = $linkService->resolve($this->currentLinkParts['url']);
            $this->currentLinkParts['type'] = $data['type'];
            unset($data['type']);
            $this->currentLinkParts['url'] = $data;
173
174
175
            if (!empty($this->currentLinkParts['url']['parameters'])) {
                $this->currentLinkParts['params'] = '&' . $this->currentLinkParts['url']['parameters'];
            }
176
177
178
179
180
181
182
183
184
185
        }

        parent::initCurrentUrl();
    }

    /**
     * Renders the link attributes for the selected link handler
     *
     * @return string
     */
186
    protected function renderLinkAttributeFields()
187
188
    {
        // Processing the classes configuration
189
190
        if (!empty($this->buttonConfig['properties']['class']['allowedClasses'])) {
            $classesAnchorArray = is_array($this->buttonConfig['properties']['class']['allowedClasses']) ? $this->buttonConfig['properties']['class']['allowedClasses'] : GeneralUtility::trimExplode(',', $this->buttonConfig['properties']['class']['allowedClasses'], true);
191
192
193
194
            // Collecting allowed classes and configured default values
            $classesAnchor = [
                'all' => []
            ];
195
196

            if (is_array($this->thisConfig['classesAnchor'])) {
197
                $readOnlyTitle = $this->isReadonlyTitle();
198
                foreach ($this->thisConfig['classesAnchor'] as $label => $conf) {
199
200
201
202
                    if (in_array($conf['class'], $classesAnchorArray, true)) {
                        $classesAnchor['all'][] = $conf['class'];
                        if ($conf['type'] === $this->displayedLinkHandlerId) {
                            $classesAnchor[$conf['type']][] = $conf['class'];
203
                            if ($this->buttonConfig[$conf['type']]['properties']['class']['default'] == $conf['class']) {
204
205
206
207
208
209
210
211
212
                                $this->classesAnchorDefault[$conf['type']] = $conf['class'];
                                if ($conf['titleText']) {
                                    $this->classesAnchorDefaultTitle[$conf['type']] = $this->contentLanguageService->sL(trim($conf['titleText']));
                                }
                                if (isset($conf['target'])) {
                                    $this->classesAnchorDefaultTarget[$conf['type']] = trim($conf['target']);
                                }
                            }
                        }
213
                        if ($readOnlyTitle && $conf['titleText']) {
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
                            $this->classesAnchorClassTitle[$conf['class']] = ($this->classesAnchorDefaultTitle[$conf['type']] = $this->contentLanguageService->sL(trim($conf['titleText'])));
                        }
                    }
                }
            }
            if (isset($this->linkAttributeValues['class'])
                && isset($classesAnchor[$this->displayedLinkHandlerId])
                && !in_array($this->linkAttributeValues['class'], $classesAnchor[$this->displayedLinkHandlerId], true)
            ) {
                unset($this->linkAttributeValues['class']);
            }
            // Constructing the class selector options
            foreach ($classesAnchorArray as $class) {
                if (!in_array($class, $classesAnchor['all']) || in_array($class, $classesAnchor['all']) && is_array($classesAnchor[$this->displayedLinkHandlerId]) && in_array($class, $classesAnchor[$this->displayedLinkHandlerId])) {
                    $selected = '';
                    if ($this->linkAttributeValues['class'] === $class || !$this->linkAttributeValues['class'] && $this->classesAnchorDefault[$this->displayedLinkHandlerId] == $class) {
                        $selected = 'selected="selected"';
                    }
232
                    $classLabel = !empty($this->thisConfig['classes'][$class]['name'])
233
                        ? $this->getPageConfigLabel($this->thisConfig['classes'][$class]['name'], false)
234
                        : $class;
235
236
                    $classStyle = !empty($this->thisConfig['classes'][$class]['value'])
                        ? $this->thisConfig['classes'][$class]['value']
237
                        : '';
238
239
240
241
242
243
                    $title = $this->classesAnchorClassTitle[$class] ?? $this->classesAnchorDefaultTitle[$class] ?? '';
                    $this->classesAnchorJSOptions[$this->displayedLinkHandlerId] .= '<option ' . $selected . ' value="' . htmlspecialchars($class) . '"'
                        . ($classStyle ? ' style="' . htmlspecialchars($classStyle) . '"' : '')
                        . 'data-link-title="' . htmlspecialchars($title) . '"'
                        . '>' . htmlspecialchars($classLabel)
                        . '</option>';
244
245
                }
            }
246
            if ($this->classesAnchorJSOptions[$this->displayedLinkHandlerId] && !($this->buttonConfig['properties']['class']['required'] || $this->buttonConfig[$this->displayedLinkHandlerId]['properties']['class']['required'])) {
247
248
249
250
251
252
253
254
255
256
                $selected = '';
                if (!$this->linkAttributeValues['class'] && !$this->classesAnchorDefault[$this->displayedLinkHandlerId]) {
                    $selected = 'selected="selected"';
                }
                $this->classesAnchorJSOptions[$this->displayedLinkHandlerId] = '<option ' . $selected . ' value=""></option>' . $this->classesAnchorJSOptions[$this->displayedLinkHandlerId];
            }
        }
        // Default target
        $this->defaultLinkTarget = $this->classesAnchorDefault[$this->displayedLinkHandlerId] && $this->classesAnchorDefaultTarget[$this->displayedLinkHandlerId]
            ? $this->classesAnchorDefaultTarget[$this->displayedLinkHandlerId]
257
            : ($this->buttonConfig[$this->displayedLinkHandlerId]['properties']['target']['default'] ?? $this->buttonConfig['properties']['target']['default'] ?? '');
258
259
260

        // todo: find new name for this option
        // Initializing additional attributes
261
262
        if ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['rte_ckeditor']['plugins']['TYPO3Link']['additionalAttributes']) {
            $addAttributes = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['rte_ckeditor']['plugins']['TYPO3Link']['additionalAttributes'], true);
263
264
265
266
267
268
269
270
271
272
273
274
275
276
            foreach ($addAttributes as $attribute) {
                $this->additionalAttributes[$attribute] = $this->linkAttributeValues[$attribute] ?? '';
            }
        }
        return parent::renderLinkAttributeFields();
    }

    /**
     * Localize a label obtained from Page TSConfig
     *
     * @param string $string The label to be localized
     * @param bool $JScharCode If needs to be converted to an array of char numbers
     * @return string Localized string
     */
277
    protected function getPageConfigLabel($string, $JScharCode = true)
278
279
280
281
282
283
    {
        if (strpos($string, 'LLL:') !== 0) {
            $label = $string;
        } else {
            $label = $this->getLanguageService()->sL(trim($string));
        }
284
        $label = str_replace(['\\\'', '"'], ['\'', '\\"'], $label);
285
286
287
288
289
        return $JScharCode ? GeneralUtility::quoteJSvalue($label) : $label;
    }

    protected function renderCurrentUrl()
    {
290
291
        $this->moduleTemplate->getView()->assign('removeCurrentLink', true);
        parent::renderCurrentUrl();
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
    }

    /**
     * Get the allowed items or tabs
     *
     * @return string[]
     */
    protected function getAllowedItems()
    {
        $allowedItems = parent::getAllowedItems();

        $blindLinkOptions = isset($this->thisConfig['blindLinkOptions'])
            ? GeneralUtility::trimExplode(',', $this->thisConfig['blindLinkOptions'], true)
            : [];
        $allowedItems = array_diff($allowedItems, $blindLinkOptions);

308
309
        if (is_array($this->buttonConfig['options']) && $this->buttonConfig['options']['removeItems']) {
            $allowedItems = array_diff($allowedItems, GeneralUtility::trimExplode(',', $this->buttonConfig['options']['removeItems'], true));
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
        }

        return $allowedItems;
    }

    /**
     * Get the allowed link attributes
     *
     * @return string[]
     */
    protected function getAllowedLinkAttributes()
    {
        $allowedLinkAttributes = parent::getAllowedLinkAttributes();

        $blindLinkFields = isset($this->thisConfig['blindLinkFields'])
            ? GeneralUtility::trimExplode(',', $this->thisConfig['blindLinkFields'], true)
            : [];
        $allowedLinkAttributes = array_diff($allowedLinkAttributes, $blindLinkFields);

        return $allowedLinkAttributes;
    }

    /**
     * Create an array of link attribute field rendering definitions
     *
     * @return string[]
     */
    protected function getLinkAttributeFieldDefinitions()
    {
        $fieldRenderingDefinitions = parent::getLinkAttributeFieldDefinitions();
        $fieldRenderingDefinitions['title'] = $this->getTitleField();
        $fieldRenderingDefinitions['class'] = $this->getClassField();
        $fieldRenderingDefinitions['target'] = $this->getTargetField();
        $fieldRenderingDefinitions['rel'] = $this->getRelField();
344
        if (empty($this->buttonConfig['queryParametersSelector']['enabled'])) {
345
346
347
348
349
350
351
352
353
354
355
356
            unset($fieldRenderingDefinitions['params']);
        }
        return $fieldRenderingDefinitions;
    }

    /**
     * Add rel field
     *
     * @return string
     */
    protected function getRelField()
    {
357
        if (empty($this->buttonConfig['relAttribute']['enabled'])) {
358
359
360
            return '';
        }

361
362
363
364
365
366
367
368
        $currentRel = '';
        if ($this->displayedLinkHandler === $this->currentLinkHandler
            && !empty($this->currentLinkParts)
            && isset($this->linkAttributeValues['rel'])
            && is_string($this->linkAttributeValues['rel'])
        ) {
            $currentRel = $this->linkAttributeValues['rel'];
        }
369
370
371

        return '
            <form action="" name="lrelform" id="lrelform" class="t3js-dummyform form-horizontal">
372
373
                 <div class="row mb-3">
                    <label class="col-sm-3 col-form-label">' .
374
375
                        htmlspecialchars($this->getLanguageService()->getLL('linkRelationship')) .
                    '</label>
376
                    <div class="col-sm-9">
377
                        <input type="text" name="lrel" class="form-control" value="' . htmlspecialchars($currentRel) . '" />
378
379
380
381
382
383
384
385
386
387
388
389
390
391
                    </div>
                </div>
            </form>
            ';
    }

    /**
     * Add target selector
     *
     * @return string
     */
    protected function getTargetField()
    {
        $targetSelectorConfig = [];
392
393
        if (is_array($this->buttonConfig['targetSelector'])) {
            $targetSelectorConfig = $this->buttonConfig['targetSelector'];
394
395
396
397
398
399
400
        }
        $target = $this->linkAttributeValues['target'] ?: $this->defaultLinkTarget;
        $lang = $this->getLanguageService();
        $targetSelector = '';

        if (!$targetSelectorConfig['disabled']) {
            $targetSelector = '
401
						<select name="ltarget_type" class="t3js-targetPreselect form-select">
402
403
404
405
406
407
408
409
410
							<option value=""></option>
							<option value="_top">' . htmlspecialchars($lang->getLL('top')) . '</option>
							<option value="_blank">' . htmlspecialchars($lang->getLL('newWindow')) . '</option>
						</select>
			';
        }

        return '
				<form action="" name="ltargetform" id="ltargetform" class="t3js-dummyform form-horizontal">
411
412
413
                    <div class="row mb-3" ' . ($targetSelectorConfig['disabled'] ? ' style="display: none;"' : '') . '>
                        <label class="col-sm-3 col-form-label">' . htmlspecialchars($lang->getLL('target')) . '</label>
						<div class="col-sm-4">
414
415
416
							<input type="text" name="ltarget" class="t3js-linkTarget form-control"
							    value="' . htmlspecialchars($target) . '" />
						</div>
417
						<div class="col-sm-5">
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
							' . $targetSelector . '
						</div>
					</div>
				</form>
				';
    }

    /**
     * Add title selector
     *
     * @return string
     */
    protected function getTitleField()
    {
        if ($this->linkAttributeValues['title']) {
            $title = $this->linkAttributeValues['title'];
        } else {
435
            $title = $this->classesAnchorDefaultTitle[$this->displayedLinkHandlerId] ?: '';
436
        }
437
        $readOnlyTitle = $this->isReadonlyTitle();
438

439
        if ($readOnlyTitle) {
440
441
442
443
            $currentClass = $this->linkAttributeFields['class'];
            if (!$currentClass) {
                $currentClass = empty($this->classesAnchorDefault[$this->displayedLinkHandlerId]) ? '' : $this->classesAnchorDefault[$this->displayedLinkHandlerId];
            }
444
            $title = $this->classesAnchorClassTitle[$currentClass] ?? $this->classesAnchorDefaultTitle[$this->displayedLinkHandlerId] ?? '';
445
446
447
        }
        return '
                <form action="" name="ltitleform" id="ltitleform" class="t3js-dummyform form-horizontal">
448
449
                    <div class="row mb-3">
                        <label class="col-sm-3 col-form-label">
450
451
                            ' . htmlspecialchars($this->getLanguageService()->getLL('title')) . '
                         </label>
452
                         <div class="col-sm-9">
453
                                <input ' . ($readOnlyTitle ? 'disabled' : '') . ' type="text" name="ltitle" class="form-control t3js-linkTitle"
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
                                        value="' . htmlspecialchars($title) . '" />
                        </div>
                    </div>
                </form>
                ';
    }

    /**
     * Return html code for the class selector
     *
     * @return string the html code to be added to the form
     */
    protected function getClassField()
    {
        $selectClass = '';
        if ($this->classesAnchorJSOptions[$this->displayedLinkHandlerId]) {
            $selectClass = '
471
                <form action="" name="lclassform" id="lclassform" class="t3js-dummyform form-horizontal">
472
473
                    <div class="row mb-3">
                        <label class="col-sm-3 col-form-label">
474
475
                            ' . htmlspecialchars($this->getLanguageService()->getLL('class')) . '
                        </label>
476
                        <div class="col-sm-9">
477
                            <select name="lclass" class="t3js-class-selector form-select">
478
479
480
481
482
483
                                ' . $this->classesAnchorJSOptions[$this->displayedLinkHandlerId] . '
                            </select>
                        </div>
                    </div>
                </form>
            ';
484
485
486
487
488
489
490
491
492
493
494
        }
        return $selectClass;
    }

    /**
     * Return the ID of current page
     *
     * @return int
     */
    protected function getCurrentPageId()
    {
495
        return (int)$this->parameters['pid'];
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
    }

    /**
     * Retrieve the configuration
     *
     * This is only used by RTE currently.
     *
     * @return array
     */
    public function getConfiguration()
    {
        return $this->buttonConfig;
    }

    /**
     * Get attributes for the body tag
     *
     * @return string[] Array of body-tag attributes
     */
    protected function getBodyTagAttributes()
    {
        $parameters = parent::getBodyTagAttributes();
        $parameters['data-site-url'] = $this->siteUrl;
        $parameters['data-default-link-target'] = $this->defaultLinkTarget;
        return $parameters;
    }

    /**
     * @param array $overrides
     *
     * @return array Array of parameters which have to be added to URLs
     */
    public function getUrlParameters(array $overrides = null)
    {
530
        return [
531
            'act' => $overrides['act'] ?? $this->displayedLinkHandlerId,
532
            'P' => $overrides['P'] ?? $this->parameters,
533
            'editorId' => $this->editorId,
534
            'contentsLanguage' => $this->contentsLanguage
535
        ];
536
    }
537
538
539
540
541
542
543
544
545

    protected function isReadonlyTitle(): bool
    {
        if (isset($this->buttonConfig[$this->displayedLinkHandlerId]['properties']['title']['readOnly'])) {
            return (bool)$this->buttonConfig[$this->displayedLinkHandlerId]['properties']['title']['readOnly'];
        }

        return (bool)($this->buttonConfig['properties']['title']['readOnly'] ?? false);
    }
546
}