0ec9b728753668097f6426b90ef5125de04df2e3
[Packages/TYPO3.CMS.git] / typo3 / sysext / recordlist / Classes / Controller / AbstractLinkBrowserController.php
1 <?php
2 namespace TYPO3\CMS\Recordlist\Controller;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use Psr\Http\Message\ResponseInterface;
18 use Psr\Http\Message\ServerRequestInterface;
19 use TYPO3\CMS\Backend\Routing\Router;
20 use TYPO3\CMS\Backend\Routing\UriBuilder;
21 use TYPO3\CMS\Backend\Template\DocumentTemplate;
22 use TYPO3\CMS\Backend\Utility\BackendUtility;
23 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
24 use TYPO3\CMS\Core\Service\DependencyOrderingService;
25 use TYPO3\CMS\Core\Utility\GeneralUtility;
26 use TYPO3\CMS\Lang\LanguageService;
27 use TYPO3\CMS\Recordlist\LinkHandler\LinkHandlerInterface;
28
29 /**
30 * Script class for the Link Browser window.
31 */
32 abstract class AbstractLinkBrowserController
33 {
34 /**
35 * @var DocumentTemplate
36 */
37 protected $doc;
38
39 /**
40 * @var array
41 */
42 protected $parameters;
43
44 /**
45 * URL of current request
46 *
47 * @var string
48 */
49 protected $thisScript = '';
50
51 /**
52 * @var LinkHandlerInterface[]
53 */
54 protected $linkHandlers = [];
55
56 /**
57 * All parts of the current link
58 *
59 * Comprised of url information and additional link parameters.
60 *
61 * @var string[]
62 */
63 protected $currentLinkParts = [];
64
65 /**
66 * Link handler responsible for the current active link
67 *
68 * @var LinkHandlerInterface $currentLinkHandler
69 */
70 protected $currentLinkHandler;
71
72 /**
73 * The ID of the currently active link handler
74 *
75 * @var string
76 */
77 protected $currentLinkHandlerId;
78
79 /**
80 * Link handler to be displayed
81 *
82 * @var LinkHandlerInterface $displayedLinkHandler
83 */
84 protected $displayedLinkHandler;
85
86 /**
87 * The ID of the displayed link handler
88 *
89 * This is read from the 'act' GET parameter
90 *
91 * @var string
92 */
93 protected $displayedLinkHandlerId = '';
94
95 /**
96 * List of available link attribute fields
97 *
98 * @var string[]
99 */
100 protected $linkAttributeFields = [];
101
102 /**
103 * Values of the link attributes
104 *
105 * @var string[]
106 */
107 protected $linkAttributeValues = [];
108
109 /**
110 * @var array
111 */
112 protected $hookObjects = [];
113
114 /**
115 * Constructor
116 */
117 public function __construct()
118 {
119 $this->initHookObjects();
120 $this->init();
121 }
122
123 /**
124 * Initialize the controller
125 */
126 protected function init()
127 {
128 $this->getLanguageService()->includeLLFile('EXT:lang/Resources/Private/Language/locallang_browse_links.xlf');
129 }
130
131 /**
132 * Initialize hook objects implementing the interface
133 *
134 * @throws \UnexpectedValueException
135 */
136 protected function initHookObjects()
137 {
138 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['LinkBrowser']['hooks'])
139 && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['LinkBrowser']['hooks'])
140 ) {
141 $hooks = GeneralUtility::makeInstance(DependencyOrderingService::class)->orderByDependencies(
142 $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['LinkBrowser']['hooks']
143 );
144 foreach ($hooks as $key => $hook) {
145 $this->hookObjects[] = GeneralUtility::makeInstance($hook['handler']);
146 }
147 }
148 }
149
150 /**
151 * Injects the request object for the current request or subrequest
152 * As this controller goes only through the main() method, it is rather simple for now
153 *
154 * @param ServerRequestInterface $request the current request
155 * @param ResponseInterface $response the prepared response object
156 * @return ResponseInterface the response with the content
157 */
158 public function mainAction(ServerRequestInterface $request, ResponseInterface $response)
159 {
160 $this->determineScriptUrl($request);
161 $this->initVariables($request);
162 $this->loadLinkHandlers();
163 $this->initCurrentUrl();
164
165 $menuData = $this->buildMenuArray();
166 $renderLinkAttributeFields = $this->renderLinkAttributeFields();
167 $browserContent = $this->displayedLinkHandler->render($request);
168
169 $this->initDocumentTemplate();
170 $content = $this->doc->startPage('Link Browser');
171 $content .= $this->doc->getFlashMessages();
172
173 if (!empty($this->currentLinkParts)) {
174 $content .= $this->renderCurrentUrl();
175 }
176
177 $content .= '<div class="link-browser-section link-browser-tabs">' . $this->doc->getTabMenuRaw($menuData) . '</div>';
178 $content .= $renderLinkAttributeFields;
179
180 $content .= $browserContent;
181 $content .= $this->doc->endPage();
182
183 $response->getBody()->write($this->doc->insertStylesAndJS($content));
184 return $response;
185 }
186
187 /**
188 * Sets the script url depending on being a module or script request
189 *
190 * @param ServerRequestInterface $request
191 *
192 * @throws \TYPO3\CMS\Backend\Routing\Exception\ResourceNotFoundException
193 * @throws \TYPO3\CMS\Backend\Routing\Exception\RouteNotFoundException
194 */
195 protected function determineScriptUrl(ServerRequestInterface $request)
196 {
197 if ($routePath = $request->getQueryParams()['route']) {
198 $router = GeneralUtility::makeInstance(Router::class);
199 $route = $router->match($routePath);
200 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
201 $this->thisScript = (string)$uriBuilder->buildUriFromRoute($route->getOption('_identifier'));
202 } elseif ($moduleName = $request->getQueryParams()['M']) {
203 $this->thisScript = BackendUtility::getModuleUrl($moduleName);
204 } else {
205 $this->thisScript = GeneralUtility::getIndpEnv('SCRIPT_NAME');
206 }
207 }
208
209 /**
210 * @param ServerRequestInterface $request
211 */
212 protected function initVariables(ServerRequestInterface $request)
213 {
214 $queryParams = $request->getQueryParams();
215 $this->displayedLinkHandlerId = isset($queryParams['act']) ? $queryParams['act'] : '';
216 $this->parameters = isset($queryParams['P']) ? $queryParams['P'] : [];
217 $this->linkAttributeValues = isset($queryParams['linkAttributes']) ? $queryParams['linkAttributes'] : [];
218 }
219
220 /**
221 * @throws \UnexpectedValueException
222 */
223 protected function loadLinkHandlers()
224 {
225 $linkHandlers = $this->getLinkHandlers();
226 if (empty($linkHandlers)) {
227 throw new \UnexpectedValueException('No link handlers are configured. Check page TSconfig TCEMAIN.linkHandler.', 1442787911);
228 }
229
230 $lang = $this->getLanguageService();
231 foreach ($linkHandlers as $identifier => $configuration) {
232 $identifier = rtrim($identifier, '.');
233 /** @var LinkHandlerInterface $handler */
234 $handler = GeneralUtility::makeInstance($configuration['handler']);
235 $handler->initialize(
236 $this,
237 $identifier,
238 isset($configuration['configuration.']) ? $configuration['configuration.'] : []
239 );
240
241 $label = !empty($configuration['label']) ? $lang->sL($configuration['label']) : '';
242 $label = $label ?: $lang->sL('LLL:EXT:recordlist/Resources/Private/Language/locallang.xlf:error.linkHandlerTitleMissing');
243 $this->linkHandlers[$identifier] = [
244 'handlerInstance' => $handler,
245 'label' => htmlspecialchars($label),
246 'displayBefore' => isset($configuration['displayBefore']) ? GeneralUtility::trimExplode(',', $configuration['displayBefore']) : [],
247 'displayAfter' => isset($configuration['displayAfter']) ? GeneralUtility::trimExplode(',', $configuration['displayAfter']) : [],
248 'scanBefore' => isset($configuration['scanBefore']) ? GeneralUtility::trimExplode(',', $configuration['scanBefore']) : [],
249 'scanAfter' => isset($configuration['scanAfter']) ? GeneralUtility::trimExplode(',', $configuration['scanAfter']) : [],
250 'addParams' => isset($configuration['addParams']) ? $configuration['addParams'] : '',
251 ];
252 }
253 }
254
255 /**
256 * Reads the configured link handlers from page TSconfig
257 *
258 * @return array
259 */
260 protected function getLinkHandlers()
261 {
262 $pageTSconfig = BackendUtility::getPagesTSconfig($this->getCurrentPageId());
263 $pageTSconfig = $this->getBackendUser()->getTSConfig('TCEMAIN.linkHandler.', $pageTSconfig);
264 $linkHandlers = (array)$pageTSconfig['properties'];
265
266 foreach ($this->hookObjects as $hookObject) {
267 if (method_exists($hookObject, 'modifyLinkHandlers')) {
268 $linkHandlers = $hookObject->modifyLinkHandlers($linkHandlers, $this->currentLinkParts);
269 }
270 }
271
272 return $linkHandlers;
273 }
274
275 /**
276 * Initialize $this->currentLinkParts and $this->currentLinkHandler
277 */
278 protected function initCurrentUrl()
279 {
280 if (empty($this->currentLinkParts)) {
281 return;
282 }
283
284 $orderedHandlers = GeneralUtility::makeInstance(DependencyOrderingService::class)->orderByDependencies($this->linkHandlers, 'scanBefore', 'scanAfter');
285
286 // find responsible handler for current link
287 foreach ($orderedHandlers as $key => $configuration) {
288 /** @var LinkHandlerInterface $handler */
289 $handler = $configuration['handlerInstance'];
290 if ($handler->canHandleLink($this->currentLinkParts)) {
291 $this->currentLinkHandler = $handler;
292 $this->currentLinkHandlerId = $key;
293 break;
294 }
295 }
296 // reset the link if we have no handler for it
297 if (!$this->currentLinkHandler) {
298 $this->currentLinkParts = [];
299 }
300
301 // overwrite any preexisting
302 foreach ($this->currentLinkParts as $key => $part) {
303 if ($key !== 'url') {
304 $this->linkAttributeValues[$key] = $part;
305 }
306 }
307 }
308
309 /**
310 * Initialize document template object
311 */
312 protected function initDocumentTemplate()
313 {
314 $this->doc = GeneralUtility::makeInstance(DocumentTemplate::class);
315 $this->doc->bodyTagId = 'typo3-browse-links-php';
316 $this->doc->divClass = 'link-browser';
317
318 foreach ($this->getBodyTagAttributes() as $attributeName => $value) {
319 $this->doc->bodyTagAdditions .= ' ' . $attributeName . '="' . htmlspecialchars($value) . '"';
320 }
321
322 // Finally, add the accumulated JavaScript to the template object:
323 // also unset the default jumpToUrl() function before
324 unset($this->doc->JScodeArray['jumpToUrl']);
325 }
326
327 /**
328 * Render the currently set URL
329 *
330 * @return string
331 */
332 protected function renderCurrentUrl()
333 {
334 return '<!-- Print current URL -->
335 <div class="link-browser-section link-browser-current-link">
336 <strong>' .
337 htmlspecialchars($this->getLanguageService()->getLL('currentLink')) .
338 ': ' .
339 htmlspecialchars($this->currentLinkHandler->formatCurrentUrl()) .
340 '</strong>
341 </div>';
342 }
343
344 /**
345 * Returns an array definition of the top menu
346 *
347 * @return mixed[][]
348 */
349 protected function buildMenuArray()
350 {
351 $allowedItems = $this->getAllowedItems();
352 if ($this->displayedLinkHandlerId && !in_array($this->displayedLinkHandlerId, $allowedItems, true)) {
353 $this->displayedLinkHandlerId = '';
354 }
355
356 $allowedHandlers = array_flip($allowedItems);
357 $menuDef = [];
358 foreach ($this->linkHandlers as $identifier => $configuration) {
359 if (!isset($allowedHandlers[$identifier])) {
360 continue;
361 }
362
363 /** @var LinkHandlerInterface $handlerInstance */
364 $handlerInstance = $configuration['handlerInstance'];
365 $isActive = $this->displayedLinkHandlerId === $identifier || !$this->displayedLinkHandlerId && $handlerInstance === $this->currentLinkHandler;
366 if ($isActive) {
367 $this->displayedLinkHandler = $handlerInstance;
368 if (!$this->displayedLinkHandlerId) {
369 $this->displayedLinkHandlerId = $this->currentLinkHandlerId;
370 }
371 }
372
373 if ($configuration['addParams']) {
374 $addParams = $configuration['addParams'];
375 } else {
376 $parameters = GeneralUtility::implodeArrayForUrl('', $this->getUrlParameters(['act' => $identifier]));
377 $addParams = 'onclick="jumpToUrl(' . GeneralUtility::quoteJSvalue('?' . ltrim($parameters, '&')) . ');return false;"';
378 }
379 $menuDef[$identifier] = [
380 'isActive' => $isActive,
381 'label' => $configuration['label'],
382 'url' => '#',
383 'addParams' => $addParams,
384 'before' => $configuration['displayBefore'],
385 'after' => $configuration['displayAfter']
386 ];
387 }
388
389 $menuDef = GeneralUtility::makeInstance(DependencyOrderingService::class)->orderByDependencies($menuDef);
390
391 // if there is no active tab
392 if (!$this->displayedLinkHandler) {
393 // empty the current link
394 $this->currentLinkParts = [];
395 $this->currentLinkHandler = null;
396 $this->currentLinkHandler = '';
397 // select first tab
398 reset($menuDef);
399 $this->displayedLinkHandlerId = key($menuDef);
400 $this->displayedLinkHandler = $this->linkHandlers[$this->displayedLinkHandlerId]['handlerInstance'];
401 $menuDef[$this->displayedLinkHandlerId]['isActive'] = true;
402 }
403
404 return $menuDef;
405 }
406
407 /**
408 * Get the allowed items or tabs
409 *
410 * @return string[]
411 */
412 protected function getAllowedItems()
413 {
414 $allowedItems = array_keys($this->linkHandlers);
415
416 foreach ($this->hookObjects as $hookObject) {
417 if (method_exists($hookObject, 'modifyAllowedItems')) {
418 $allowedItems = $hookObject->modifyAllowedItems($allowedItems, $this->currentLinkParts);
419 }
420 }
421
422 // Initializing the action value, possibly removing blinded values etc:
423 $blindLinkOptions = isset($this->parameters['params']['blindLinkOptions'])
424 ? GeneralUtility::trimExplode(',', $this->parameters['params']['blindLinkOptions'])
425 : [];
426 $allowedItems = array_diff($allowedItems, $blindLinkOptions);
427
428 return $allowedItems;
429 }
430
431 /**
432 * Get the allowed link attributes
433 *
434 * @return string[]
435 */
436 protected function getAllowedLinkAttributes()
437 {
438 $allowedLinkAttributes = $this->displayedLinkHandler->getLinkAttributes();
439
440 // Removing link fields if configured
441 $blindLinkFields = isset($this->parameters['params']['blindLinkFields'])
442 ? GeneralUtility::trimExplode(',', $this->parameters['params']['blindLinkFields'], true)
443 : [];
444 $allowedLinkAttributes = array_diff($allowedLinkAttributes, $blindLinkFields);
445
446 return $allowedLinkAttributes;
447 }
448
449 /**
450 * Renders the link attributes for the selected link handler
451 *
452 * @return string
453 */
454 public function renderLinkAttributeFields()
455 {
456 $fieldRenderingDefinitions = $this->getLinkAttributeFieldDefinitions();
457
458 $fieldRenderingDefinitions = $this->displayedLinkHandler->modifyLinkAttributes($fieldRenderingDefinitions);
459
460 $this->linkAttributeFields = $this->getAllowedLinkAttributes();
461
462 $content = '';
463 foreach ($this->linkAttributeFields as $attribute) {
464 $content .= $fieldRenderingDefinitions[$attribute];
465 }
466
467 // add update button if appropriate
468 if (!empty($this->currentLinkParts) && $this->displayedLinkHandler === $this->currentLinkHandler && $this->currentLinkHandler->isUpdateSupported()) {
469 $content .= '
470 <form action="" name="lparamsform" id="lparamsform" class="form-horizontal">
471 <div class="form-group form-group-sm">
472 <input class="btn btn-default t3js-linkCurrent" type="submit" value="' . htmlspecialchars($this->getLanguageService()->getLL('update')) . '" />
473 </div>
474 </form>';
475 }
476
477 return '<div class="link-browser-section link-browser-attributes">' . $content . '</div>';
478 }
479
480 /**
481 * Create an array of link attribute field rendering definitions
482 *
483 * @return string[]
484 */
485 protected function getLinkAttributeFieldDefinitions()
486 {
487 $lang = $this->getLanguageService();
488
489 $fieldRenderingDefinitions = [];
490 $fieldRenderingDefinitions['target'] = '
491 <!--
492 Selecting target for link:
493 -->
494 <form action="" name="ltargetform" id="ltargetform" class="t3js-dummyform form-horizontal">
495 <div class="form-group form-group-sm" id="typo3-linkTarget">
496 <label class="col-xs-4 control-label">' . htmlspecialchars($lang->getLL('target')) . '</label>
497 <div class="col-xs-3">
498 <input type="text" name="ltarget" class="t3js-linkTarget form-control"
499 value="' . htmlspecialchars($this->linkAttributeValues['target']) . '" />
500 </div>
501 <div class="col-xs-5">
502 <select name="ltarget_type" class="t3js-targetPreselect form-control">
503 <option value=""></option>
504 <option value="_top">' . htmlspecialchars($lang->getLL('top')) . '</option>
505 <option value="_blank">' . htmlspecialchars($lang->getLL('newWindow')) . '</option>
506 </select>
507 </div>
508 </div>
509 </form>';
510
511 $fieldRenderingDefinitions['title'] = '
512 <!--
513 Selecting title for link:
514 -->
515 <form action="" name="ltitleform" id="ltitleform" class="t3js-dummyform form-horizontal">
516 <div class="form-group form-group-sm" id="typo3-linkTitle">
517 <label class="col-xs-4 control-label">' . htmlspecialchars($lang->getLL('title')) . '</label>
518 <div class="col-xs-8">
519 <input type="text" name="ltitle" class="form-control"
520 value="' . htmlspecialchars($this->linkAttributeValues['title']) . '" />
521 </div>
522 </div>
523 </form>
524 ';
525
526 $fieldRenderingDefinitions['class'] = '
527 <!--
528 Selecting class for link:
529 -->
530 <form action="" name="lclassform" id="lclassform" class="t3js-dummyform form-horizontal">
531 <div class="form-group form-group-sm" id="typo3-linkClass">
532 <label class="col-xs-4 control-label">' . htmlspecialchars($lang->getLL('class')) . '</label>
533 <div class="col-xs-8">
534 <input type="text" name="lclass" class="form-control"
535 value="' . htmlspecialchars($this->linkAttributeValues['class']) . '" /></td>
536 </div>
537 </div>
538 </form>
539 ';
540
541 $fieldRenderingDefinitions['params'] = '
542 <!--
543 Selecting params for link:
544 -->
545 <form action="" name="lparamsform" id="lparamsform" class="t3js-dummyform form-horizontal">
546 <div class="form-group form-group-sm" id="typo3-linkParams">
547 <label class="col-xs-4 control-label">' . htmlspecialchars($lang->getLL('params')) . '</label>
548 <div class="col-xs-8">
549 <input type="text" name="lparams" class="form-control"
550 value="' . htmlspecialchars($this->linkAttributeValues['params']) . '" />
551 </div>
552 </div>
553 </form>
554 ';
555
556 return $fieldRenderingDefinitions;
557 }
558
559 /**
560 * @param array $overrides
561 *
562 * @return array Array of parameters which have to be added to URLs
563 */
564 public function getUrlParameters(array $overrides = null)
565 {
566 return [
567 'act' => isset($overrides['act']) ? $overrides['act'] : $this->displayedLinkHandlerId
568 ];
569 }
570
571 /**
572 * Get attributes for the body tag
573 *
574 * @return string[] Array of body-tag attributes
575 */
576 protected function getBodyTagAttributes()
577 {
578 $parameters = [];
579 $parameters['uid'] = $this->parameters['uid'];
580 $parameters['pid'] = $this->parameters['pid'];
581 $parameters['itemName'] = $this->parameters['itemName'];
582 $parameters['formName'] = $this->parameters['formName'];
583 $parameters['params']['allowedExtensions'] = isset($this->parameters['params']['allowedExtensions']) ? $this->parameters['params']['allowedExtensions'] : '';
584 $parameters['params']['blindLinkOptions'] = isset($this->parameters['params']['blindLinkOptions']) ? $this->parameters['params']['blindLinkOptions'] : '';
585 $parameters['params']['blindLinkFields'] = isset($this->parameters['params']['blindLinkFields']) ? $this->parameters['params']['blindLinkFields']: '';
586 $addPassOnParams = GeneralUtility::implodeArrayForUrl('P', $parameters);
587
588 $attributes = $this->displayedLinkHandler->getBodyTagAttributes();
589 return array_merge(
590 $attributes,
591 [
592 'data-this-script-url' => strpos($this->thisScript, '?') === false ? $this->thisScript . '?' : $this->thisScript . '&',
593 'data-url-parameters' => json_encode($this->getUrlParameters()),
594 'data-parameters' => json_encode($this->parameters),
595 'data-add-on-params' => $addPassOnParams,
596 'data-link-attribute-fields' => json_encode($this->linkAttributeFields)
597 ]
598 );
599 }
600
601 /**
602 * Return the ID of current page
603 *
604 * @return int
605 */
606 abstract protected function getCurrentPageId();
607
608 /**
609 * @return array
610 */
611 public function getParameters()
612 {
613 return $this->parameters;
614 }
615
616 /**
617 * Retrieve the configuration
618 *
619 * @return array
620 */
621 public function getConfiguration()
622 {
623 return [];
624 }
625
626 /**
627 * @return string
628 */
629 public function getDisplayedLinkHandlerId()
630 {
631 return $this->displayedLinkHandlerId;
632 }
633
634 /**
635 * @return string
636 */
637 public function getScriptUrl()
638 {
639 return $this->thisScript;
640 }
641
642 /**
643 * @return LanguageService
644 */
645 protected function getLanguageService()
646 {
647 return $GLOBALS['LANG'];
648 }
649
650 /**
651 * @return BackendUserAuthentication
652 */
653 protected function getBackendUser()
654 {
655 return $GLOBALS['BE_USER'];
656 }
657 }