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