[TASK] Unify element- and linkbrowser styling
[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="element-browser-panel element-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->divClass = 'element-browser';
316
317 foreach ($this->getBodyTagAttributes() as $attributeName => $value) {
318 $this->doc->bodyTagAdditions .= ' ' . $attributeName . '="' . htmlspecialchars($value) . '"';
319 }
320
321 // Finally, add the accumulated JavaScript to the template object:
322 // also unset the default jumpToUrl() function before
323 unset($this->doc->JScodeArray['jumpToUrl']);
324 }
325
326 /**
327 * Render the currently set URL
328 *
329 * @return string
330 */
331 protected function renderCurrentUrl()
332 {
333 return '<!-- Print current URL -->
334 <div class="element-browser-panel element-browser-title">' .
335 htmlspecialchars($this->getLanguageService()->getLL('currentLink')) .
336 ': ' .
337 htmlspecialchars($this->currentLinkHandler->formatCurrentUrl()) .
338 '</div>';
339 }
340
341 /**
342 * Returns an array definition of the top menu
343 *
344 * @return mixed[][]
345 */
346 protected function buildMenuArray()
347 {
348 $allowedItems = $this->getAllowedItems();
349 if ($this->displayedLinkHandlerId && !in_array($this->displayedLinkHandlerId, $allowedItems, true)) {
350 $this->displayedLinkHandlerId = '';
351 }
352
353 $allowedHandlers = array_flip($allowedItems);
354 $menuDef = [];
355 foreach ($this->linkHandlers as $identifier => $configuration) {
356 if (!isset($allowedHandlers[$identifier])) {
357 continue;
358 }
359
360 /** @var LinkHandlerInterface $handlerInstance */
361 $handlerInstance = $configuration['handlerInstance'];
362 $isActive = $this->displayedLinkHandlerId === $identifier || !$this->displayedLinkHandlerId && $handlerInstance === $this->currentLinkHandler;
363 if ($isActive) {
364 $this->displayedLinkHandler = $handlerInstance;
365 if (!$this->displayedLinkHandlerId) {
366 $this->displayedLinkHandlerId = $this->currentLinkHandlerId;
367 }
368 }
369
370 if ($configuration['addParams']) {
371 $addParams = $configuration['addParams'];
372 } else {
373 $parameters = GeneralUtility::implodeArrayForUrl('', $this->getUrlParameters(['act' => $identifier]));
374 $addParams = 'onclick="jumpToUrl(' . GeneralUtility::quoteJSvalue('?' . ltrim($parameters, '&')) . ');return false;"';
375 }
376 $menuDef[$identifier] = [
377 'isActive' => $isActive,
378 'label' => $configuration['label'],
379 'url' => '#',
380 'addParams' => $addParams,
381 'before' => $configuration['displayBefore'],
382 'after' => $configuration['displayAfter']
383 ];
384 }
385
386 $menuDef = GeneralUtility::makeInstance(DependencyOrderingService::class)->orderByDependencies($menuDef);
387
388 // if there is no active tab
389 if (!$this->displayedLinkHandler) {
390 // empty the current link
391 $this->currentLinkParts = [];
392 $this->currentLinkHandler = null;
393 $this->currentLinkHandler = '';
394 // select first tab
395 reset($menuDef);
396 $this->displayedLinkHandlerId = key($menuDef);
397 $this->displayedLinkHandler = $this->linkHandlers[$this->displayedLinkHandlerId]['handlerInstance'];
398 $menuDef[$this->displayedLinkHandlerId]['isActive'] = true;
399 }
400
401 return $menuDef;
402 }
403
404 /**
405 * Get the allowed items or tabs
406 *
407 * @return string[]
408 */
409 protected function getAllowedItems()
410 {
411 $allowedItems = array_keys($this->linkHandlers);
412
413 foreach ($this->hookObjects as $hookObject) {
414 if (method_exists($hookObject, 'modifyAllowedItems')) {
415 $allowedItems = $hookObject->modifyAllowedItems($allowedItems, $this->currentLinkParts);
416 }
417 }
418
419 // Initializing the action value, possibly removing blinded values etc:
420 $blindLinkOptions = isset($this->parameters['params']['blindLinkOptions'])
421 ? GeneralUtility::trimExplode(',', $this->parameters['params']['blindLinkOptions'])
422 : [];
423 $allowedItems = array_diff($allowedItems, $blindLinkOptions);
424
425 return $allowedItems;
426 }
427
428 /**
429 * Get the allowed link attributes
430 *
431 * @return string[]
432 */
433 protected function getAllowedLinkAttributes()
434 {
435 $allowedLinkAttributes = $this->displayedLinkHandler->getLinkAttributes();
436
437 // Removing link fields if configured
438 $blindLinkFields = isset($this->parameters['params']['blindLinkFields'])
439 ? GeneralUtility::trimExplode(',', $this->parameters['params']['blindLinkFields'], true)
440 : [];
441 $allowedLinkAttributes = array_diff($allowedLinkAttributes, $blindLinkFields);
442
443 return $allowedLinkAttributes;
444 }
445
446 /**
447 * Renders the link attributes for the selected link handler
448 *
449 * @return string
450 */
451 public function renderLinkAttributeFields()
452 {
453 $fieldRenderingDefinitions = $this->getLinkAttributeFieldDefinitions();
454
455 $fieldRenderingDefinitions = $this->displayedLinkHandler->modifyLinkAttributes($fieldRenderingDefinitions);
456
457 $this->linkAttributeFields = $this->getAllowedLinkAttributes();
458
459 $content = '';
460 foreach ($this->linkAttributeFields as $attribute) {
461 $content .= $fieldRenderingDefinitions[$attribute];
462 }
463
464 // add update button if appropriate
465 if (!empty($this->currentLinkParts) && $this->displayedLinkHandler === $this->currentLinkHandler && $this->currentLinkHandler->isUpdateSupported()) {
466 $content .= '
467 <form action="" name="lparamsform" id="lparamsform" class="form-horizontal">
468 <div class="form-group form-group-sm">
469 <div class="col-xs-12">
470 <input class="btn btn-default t3js-linkCurrent" type="submit" value="' . htmlspecialchars($this->getLanguageService()->getLL('update')) . '" />
471 </div>
472 </div>
473 </form>';
474 }
475
476 return '<div class="element-browser-panel element-browser-attributes">' . $content . '</div>';
477 }
478
479 /**
480 * Create an array of link attribute field rendering definitions
481 *
482 * @return string[]
483 */
484 protected function getLinkAttributeFieldDefinitions()
485 {
486 $lang = $this->getLanguageService();
487
488 $fieldRenderingDefinitions = [];
489 $fieldRenderingDefinitions['target'] = '
490 <!-- Selecting target for link: -->
491 <form action="" name="ltargetform" id="ltargetform" class="t3js-dummyform form-horizontal">
492 <div class="form-group form-group-sm" id="typo3-linkTarget">
493 <label class="col-xs-4 control-label">' . htmlspecialchars($lang->getLL('target')) . '</label>
494 <div class="col-xs-3">
495 <input type="text" name="ltarget" class="t3js-linkTarget form-control"
496 value="' . htmlspecialchars($this->linkAttributeValues['target']) . '" />
497 </div>
498 <div class="col-xs-5">
499 <select name="ltarget_type" class="t3js-targetPreselect form-control">
500 <option value=""></option>
501 <option value="_top">' . htmlspecialchars($lang->getLL('top')) . '</option>
502 <option value="_blank">' . htmlspecialchars($lang->getLL('newWindow')) . '</option>
503 </select>
504 </div>
505 </div>
506 </form>';
507
508 $fieldRenderingDefinitions['title'] = '
509 <!-- Selecting title for link: -->
510 <form action="" name="ltitleform" id="ltitleform" class="t3js-dummyform form-horizontal">
511 <div class="form-group form-group-sm" id="typo3-linkTitle">
512 <label class="col-xs-4 control-label">' . htmlspecialchars($lang->getLL('title')) . '</label>
513 <div class="col-xs-8">
514 <input type="text" name="ltitle" class="form-control"
515 value="' . htmlspecialchars($this->linkAttributeValues['title']) . '" />
516 </div>
517 </div>
518 </form>';
519
520 $fieldRenderingDefinitions['class'] = '
521 <!-- Selecting class for link: -->
522 <form action="" name="lclassform" id="lclassform" class="t3js-dummyform form-horizontal">
523 <div class="form-group form-group-sm" id="typo3-linkClass">
524 <label class="col-xs-4 control-label">' . htmlspecialchars($lang->getLL('class')) . '</label>
525 <div class="col-xs-8">
526 <input type="text" name="lclass" class="form-control"
527 value="' . htmlspecialchars($this->linkAttributeValues['class']) . '" /></td>
528 </div>
529 </div>
530 </form>';
531
532 $fieldRenderingDefinitions['params'] = '
533 <!-- Selecting params for link: -->
534 <form action="" name="lparamsform" id="lparamsform" class="t3js-dummyform form-horizontal">
535 <div class="form-group form-group-sm" id="typo3-linkParams">
536 <label class="col-xs-4 control-label">' . htmlspecialchars($lang->getLL('params')) . '</label>
537 <div class="col-xs-8">
538 <input type="text" name="lparams" class="form-control"
539 value="' . htmlspecialchars($this->linkAttributeValues['params']) . '" />
540 </div>
541 </div>
542 </form>';
543
544 return $fieldRenderingDefinitions;
545 }
546
547 /**
548 * @param array $overrides
549 *
550 * @return array Array of parameters which have to be added to URLs
551 */
552 public function getUrlParameters(array $overrides = null)
553 {
554 return [
555 'act' => isset($overrides['act']) ? $overrides['act'] : $this->displayedLinkHandlerId
556 ];
557 }
558
559 /**
560 * Get attributes for the body tag
561 *
562 * @return string[] Array of body-tag attributes
563 */
564 protected function getBodyTagAttributes()
565 {
566 $parameters = [];
567 $parameters['uid'] = $this->parameters['uid'];
568 $parameters['pid'] = $this->parameters['pid'];
569 $parameters['itemName'] = $this->parameters['itemName'];
570 $parameters['formName'] = $this->parameters['formName'];
571 $parameters['params']['allowedExtensions'] = isset($this->parameters['params']['allowedExtensions']) ? $this->parameters['params']['allowedExtensions'] : '';
572 $parameters['params']['blindLinkOptions'] = isset($this->parameters['params']['blindLinkOptions']) ? $this->parameters['params']['blindLinkOptions'] : '';
573 $parameters['params']['blindLinkFields'] = isset($this->parameters['params']['blindLinkFields']) ? $this->parameters['params']['blindLinkFields']: '';
574 $addPassOnParams = GeneralUtility::implodeArrayForUrl('P', $parameters);
575
576 $attributes = $this->displayedLinkHandler->getBodyTagAttributes();
577 return array_merge(
578 $attributes,
579 [
580 'data-this-script-url' => strpos($this->thisScript, '?') === false ? $this->thisScript . '?' : $this->thisScript . '&',
581 'data-url-parameters' => json_encode($this->getUrlParameters()),
582 'data-parameters' => json_encode($this->parameters),
583 'data-add-on-params' => $addPassOnParams,
584 'data-link-attribute-fields' => json_encode($this->linkAttributeFields)
585 ]
586 );
587 }
588
589 /**
590 * Return the ID of current page
591 *
592 * @return int
593 */
594 abstract protected function getCurrentPageId();
595
596 /**
597 * @return array
598 */
599 public function getParameters()
600 {
601 return $this->parameters;
602 }
603
604 /**
605 * Retrieve the configuration
606 *
607 * @return array
608 */
609 public function getConfiguration()
610 {
611 return [];
612 }
613
614 /**
615 * @return string
616 */
617 public function getDisplayedLinkHandlerId()
618 {
619 return $this->displayedLinkHandlerId;
620 }
621
622 /**
623 * @return string
624 */
625 public function getScriptUrl()
626 {
627 return $this->thisScript;
628 }
629
630 /**
631 * @return LanguageService
632 */
633 protected function getLanguageService()
634 {
635 return $GLOBALS['LANG'];
636 }
637
638 /**
639 * @return BackendUserAuthentication
640 */
641 protected function getBackendUser()
642 {
643 return $GLOBALS['BE_USER'];
644 }
645 }