ShortcutToolbarItem.php 40 KB
Newer Older
1
<?php
2
namespace TYPO3\CMS\Backend\Backend\ToolbarItems;
3

4
/*
5
 * This file is part of the TYPO3 CMS project.
6
 *
7
8
9
 * 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.
10
 *
11
12
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
13
 *
14
15
 * The TYPO3 project - inspiring people to share!
 */
16

17
18
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
19
20
use TYPO3\CMS\Backend\Module\ModuleLoader;
use TYPO3\CMS\Backend\Toolbar\ToolbarItemInterface;
Nicole Cordes's avatar
Nicole Cordes committed
21
use TYPO3\CMS\Backend\Utility\BackendUtility;
22
use TYPO3\CMS\Core\Database\Connection;
23
24
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\QueryHelper;
25
26
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Imaging\IconFactory;
27
use TYPO3\CMS\Core\Page\PageRenderer;
28
29
use TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException;
use TYPO3\CMS\Core\Resource\ResourceFactory;
Nicole Cordes's avatar
Nicole Cordes committed
30
31
32
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\MathUtility;

33
34
35
/**
 * Class to render the shortcut menu
 */
36
37
38
39
40
41
42
43
44
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
class ShortcutToolbarItem implements ToolbarItemInterface
{
    /**
     * @const integer Number of super global group
     */
    const SUPERGLOBAL_GROUP = -100;

    /**
     * @var string
     */
    public $perms_clause;

    /**
     * @var array
     */
    public $fieldArray;

    /**
     * All available shortcuts
     *
     * @var array
     */
    protected $shortcuts;

    /**
     * @var array
     */
    protected $shortcutGroups;

    /**
     * Labels of all groups.
     * If value is 1, the system will try to find a label in the locallang array.
     *
     * @var array
     */
    protected $groupLabels;

    /**
     * @var IconFactory
     */
    protected $iconFactory;

78
79
80
81
82
    /**
     * @var ModuleLoader
     */
    protected $moduleLoader;

83
84
85
86
87
88
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
89
        $this->getLanguageService()->includeLLFile('EXT:lang/Resources/Private/Language/locallang_misc.xlf');
90
91
92
        // Needed to get the correct icons when reloading the menu after saving it
        $this->moduleLoader = GeneralUtility::makeInstance(ModuleLoader::class);
        $this->moduleLoader->load($GLOBALS['TBE_MODULES']);
93
94

        // By default, 5 groups are set
95
        $this->shortcutGroups = [
96
97
98
99
100
            1 => '1',
            2 => '1',
            3 => '1',
            4 => '1',
            5 => '1'
101
        ];
102
103
104
105
        $this->shortcutGroups = $this->initShortcutGroups();
        $this->shortcuts = $this->initShortcuts();

        $this->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/Toolbar/ShortcutMenu');
106
107
        $languageService = $this->getLanguageService();
        $this->getPageRenderer()->addInlineLanguageLabelArray([
108
109
110
111
112
            'bookmark.delete' => $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:toolbarItems.bookmarksDelete'),
            'bookmark.confirmDelete' => $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:toolbarItems.confirmBookmarksDelete'),
            'bookmark.create' => $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:toolbarItems.createBookmark'),
            'bookmark.savedTitle' => $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:toolbarItems.bookmarkSavedTitle'),
            'bookmark.savedMessage' => $languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:toolbarItems.bookmarkSavedMessage'),
113
        ]);
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
    }

    /**
     * Checks whether the user has access to this toolbar item
     *
     * @return bool TRUE if user has access, FALSE if not
     */
    public function checkAccess()
    {
        return (bool)$this->getBackendUser()->getTSConfigVal('options.enableBookmarks');
    }

    /**
     * Render shortcut icon
     *
     * @return string HTML
     */
    public function getItem()
    {
133
        $title = htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:toolbarItems.bookmarks'));
134
135
136
137
138
        $icon = $this->iconFactory->getIcon('apps-toolbar-menu-shortcut', Icon::SIZE_SMALL)->render('inline');
        return '
            <span class="toolbar-item-icon" title="' . $title . '">' . $icon . '</span>
            <span class="toolbar-item-title">' . $title . '</span>
            ';
139
140
141
142
143
144
145
146
147
148
    }

    /**
     * Render drop down content
     *
     * @return string HTML
     */
    public function getDropDown()
    {
        $languageService = $this->getLanguageService();
149
150
        $shortcutEdit = htmlspecialchars($languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:toolbarItems.bookmarksEdit'));
        $shortcutDelete = htmlspecialchars($languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:toolbarItems.bookmarksDelete'));
151
        $editIcon = '<a href="#" class="dropdown-table-actions-btn dropdown-table-actions-btn-edit t3js-shortcut-edit" title="' . $shortcutEdit . '">'
152
            . $this->iconFactory->getIcon('actions-open', Icon::SIZE_SMALL)->render('inline') . '</a>';
153
        $deleteIcon = '<a href="#" class="dropdown-table-actions-btn dropdown-table-actions-btn-delete t3js-shortcut-delete" title="' . $shortcutDelete . '">'
154
            . $this->iconFactory->getIcon('actions-delete', Icon::SIZE_SMALL)->render('inline') . '</a>';
155

156
        $shortcutMenu = [];
157
        $shortcutMenu[] = '<h3 class="dropdown-headline">' . htmlspecialchars($this->getLanguageService()->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:toolbarItems.bookmarks')) . '</h3>';
158
159
160
        $shortcutMenu[] = '<hr>';

        // Render groups and the contained shortcuts
161
        $groups = $this->getGroupsFromShortcuts();
162
163
        $groupCount = 0;
        arsort($groups, SORT_NUMERIC);
164
        foreach ($groups as $groupId => $groupLabel) {
165
166
167
168
169
170
171
172
            $shortcuts = $this->getShortcutsByGroup($groupId);
            if (count($shortcuts) > 0) {
                if ($groupCount !== 0) {
                    $shortcutMenu[] = '<hr>';
                }
                $groupCount++;
                if ($groupLabel) {
                    $shortcutMenu[] = '<h3 class="dropdown-headline" id="shortcut-group-' . (int)$groupId . '">' . $groupLabel . '</h3>';
173
                }
174
                $shortcutMenu[] = '<div class="dropdown-table" data-shortcutgroup="' . (int)$groupId . '">';
175
                foreach ($shortcuts as $shortcut) {
176
177
178
179
180
181
182
183
184
185
186
187
                    $shortcutItem  = '<div class="dropdown-table-row t3js-topbar-shortcut" data-shortcutid="' . (int)$shortcut['raw']['uid'] . '" data-shortcutgroup="' . (int)$groupId . '">';
                    $shortcutItem .= '<div class="dropdown-table-column dropdown-table-icon">';
                    $shortcutItem .= $shortcut['icon'];
                    $shortcutItem .= '</div>';
                    $shortcutItem .= '<div class="dropdown-table-column dropdown-table-title">';
                    $shortcutItem .= '<a class="dropdown-table-title-ellipsis" href="#" onclick="' . htmlspecialchars($shortcut['action']) . ' return false;">';
                    $shortcutItem .= htmlspecialchars($shortcut['label']);
                    $shortcutItem .= '</a>';
                    $shortcutItem .= '</div>';
                    $shortcutItem .= '<div class="dropdown-table-column dropdown-table-actions">' . $editIcon . $deleteIcon . '</div>';
                    $shortcutItem .= '</div>';
                    $shortcutMenu[] = $shortcutItem;
188
                }
189
                $shortcutMenu[] = '</div>';
190
191
192
            }
        }

193
        $compiledShortcutMenu = implode(LF, $shortcutMenu);
194
195
        if (count($shortcutMenu) === 2) {
            // No shortcuts added yet, show a small help message how to add shortcuts
196
            $title = htmlspecialchars($languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:toolbarItems.bookmarks'));
197
            $icon = '<span title="' . $title . '">' . $this->iconFactory->getIcon('actions-system-shortcut-new', Icon::SIZE_SMALL)->render('inline') . '</span>';
198
            $label = str_replace('%icon%', $icon, htmlspecialchars($languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_misc.xlf:bookmarkDescription')));
199
            $compiledShortcutMenu .= '<p>' . $label . '</p>';
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
        }

        return $compiledShortcutMenu;
    }

    /**
     * Renders the menu so that it can be returned as response to an AJAX call
     *
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @return ResponseInterface
     */
    public function menuAction(ServerRequestInterface $request, ResponseInterface $response)
    {
        $menuContent = $this->getDropDown();

        $response->getBody()->write($menuContent);
        $response = $response->withHeader('Content-Type', 'text/html; charset=utf-8');
        return $response;
    }

    /**
     * This toolbar item needs no additional attributes
     *
     * @return array
     */
    public function getAdditionalAttributes()
    {
228
        return [];
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
    }

    /**
     * This item has a drop down
     *
     * @return bool
     */
    public function hasDropDown()
    {
        return true;
    }

    /**
     * Retrieves the shortcuts for the current user
     *
     * @return array Array of shortcuts
     */
    protected function initShortcuts()
    {
        $backendUser = $this->getBackendUser();
        // Traverse shortcuts
        $lastGroup = 0;
251
        $shortcuts = [];
252
253
254
255
256
257
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getQueryBuilderForTable('sys_be_shortcuts');
        $result = $queryBuilder->select('*')
            ->from('sys_be_shortcuts')
            ->where(
                $queryBuilder->expr()->andX(
258
259
260
261
262
263
264
265
                    $queryBuilder->expr()->eq(
                        'userid',
                        $queryBuilder->createNamedParameter($backendUser->user['uid'], \PDO::PARAM_INT)
                    ),
                    $queryBuilder->expr()->gte(
                        'sc_group',
                        $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)
                    )
266
267
268
                )
            )
            ->orWhere(
269
270
271
272
273
274
275
                $queryBuilder->expr()->in(
                    'sc_group',
                    $queryBuilder->createNamedParameter(
                        array_keys($this->getGlobalShortcutGroups()),
                        Connection::PARAM_INT_ARRAY
                    )
                )
276
277
278
279
280
281
            )
            ->orderBy('sc_group')
            ->addOrderBy('sorting')
            ->execute();

        while ($row = $result->fetch()) {
282
            $shortcut = ['raw' => $row];
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303

            list($row['module_name'], $row['M_module_name']) = explode('|', $row['module_name']);

            $queryParts = parse_url($row['url']);
            $queryParameters = GeneralUtility::explodeUrl2Array($queryParts['query'], 1);
            if ($row['module_name'] === 'xMOD_alt_doc.php' && is_array($queryParameters['edit'])) {
                $shortcut['table'] = key($queryParameters['edit']);
                $shortcut['recordid'] = key($queryParameters['edit'][$shortcut['table']]);
                if ($queryParameters['edit'][$shortcut['table']][$shortcut['recordid']] === 'edit') {
                    $shortcut['type'] = 'edit';
                } elseif ($queryParameters['edit'][$shortcut['table']][$shortcut['recordid']] === 'new') {
                    $shortcut['type'] = 'new';
                }
                if (substr($shortcut['recordid'], -1) === ',') {
                    $shortcut['recordid'] = substr($shortcut['recordid'], 0, -1);
                }
            } else {
                $shortcut['type'] = 'other';
            }
            // Check for module access
            $moduleName = $row['M_module_name'] ?: $row['module_name'];
304

305
306
            // Check if the user has access to this module
            if (!is_array($this->moduleLoader->checkMod($moduleName))) {
307
308
                continue;
            }
309
310
            $pageId = $this->getLinkedPageId($row['url']);

311
312
313
            if (!$backendUser->isAdmin()) {
                if (MathUtility::canBeInterpretedAsInteger($pageId)) {
                    // Check for webmount access
314
                    if ($backendUser->isInWebMount($pageId) === null) {
315
316
317
318
                        continue;
                    }
                    // Check for record access
                    $pageRow = BackendUtility::getRecord('pages', $pageId);
319
320
321
                    if ($pageRow === null) {
                        continue;
                    }
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
                    if (!$backendUser->doesUserHaveAccess($pageRow, ($perms = 1))) {
                        continue;
                    }
                }
            }
            $moduleParts = explode('_', $moduleName);
            $shortcutGroup = (int)$row['sc_group'];
            if ($shortcutGroup && $lastGroup !== $shortcutGroup && $shortcutGroup !== self::SUPERGLOBAL_GROUP) {
                $shortcut['groupLabel'] = $this->getShortcutGroupLabel($shortcutGroup);
            }
            $lastGroup = $shortcutGroup;

            if ($row['description']) {
                $shortcut['label'] = $row['description'];
            } else {
                $shortcut['label'] = GeneralUtility::fixed_lgd_cs(rawurldecode($queryParts['query']), 150);
            }
            $shortcut['group'] = $shortcutGroup;
            $shortcut['icon'] = $this->getShortcutIcon($row, $shortcut);
            $shortcut['iconTitle'] = $this->getShortcutIconTitle($shortcut['label'], $row['module_name'], $row['M_module_name']);
            $shortcut['action'] = 'jump(' . GeneralUtility::quoteJSvalue($this->getTokenUrl($row['url'])) . ',' . GeneralUtility::quoteJSvalue($moduleName) . ',' . GeneralUtility::quoteJSvalue($moduleParts[0]) . ', ' . (int)$pageId . ');';

            $shortcuts[] = $shortcut;
        }
        return $shortcuts;
    }

    /**
     * Adds the correct token, if the url is an index.php script
     *
     * @param string $url
     * @return string
     */
    protected function getTokenUrl($url)
    {
        $parsedUrl = parse_url($url);
        parse_str($parsedUrl['query'], $parameters);

        // parse the returnUrl and replace the module token of it
        if (isset($parameters['returnUrl'])) {
            $parsedReturnUrl = parse_url($parameters['returnUrl']);
            parse_str($parsedReturnUrl['query'], $returnUrlParameters);
            if (strpos($parsedReturnUrl['path'], 'index.php') !== false && isset($returnUrlParameters['M'])) {
                $module = $returnUrlParameters['M'];
                $returnUrl = BackendUtility::getModuleUrl($module, $returnUrlParameters);
                $parameters['returnUrl'] = $returnUrl;
                $url = $parsedUrl['path'] . '?' . http_build_query($parameters);
            }
        }

        if (strpos($parsedUrl['path'], 'index.php') !== false && isset($parameters['M'])) {
            $module = $parameters['M'];
            $url = BackendUtility::getModuleUrl($module, $parameters);
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
        } elseif (strpos($parsedUrl['path'], 'index.php') !== false && isset($parameters['route'])) {
            $routePath = $parameters['route'];
            /** @var \TYPO3\CMS\Backend\Routing\Router $router */
            $router = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\Router::class);
            try {
                $route = $router->match($routePath);
                if ($route) {
                    $routeIdentifier = $route->getOption('_identifier');
                    /** @var \TYPO3\CMS\Backend\Routing\UriBuilder $uriBuilder */
                    $uriBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\UriBuilder::class);
                    unset($parameters['route']);
                    $url = (string)$uriBuilder->buildUriFromRoute($routeIdentifier, $parameters);
                }
            } catch (\TYPO3\CMS\Backend\Routing\Exception\ResourceNotFoundException $e) {
                $url = '';
            }
391
392
393
394
395
396
397
398
399
400
401
402
        }
        return $url;
    }

    /**
     * Gets shortcuts for a specific group
     *
     * @param int $groupId Group Id
     * @return array Array of shortcuts that matched the group
     */
    protected function getShortcutsByGroup($groupId)
    {
403
        $shortcuts = [];
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
        foreach ($this->shortcuts as $shortcut) {
            if ($shortcut['group'] == $groupId) {
                $shortcuts[] = $shortcut;
            }
        }
        return $shortcuts;
    }

    /**
     * Gets a shortcut by its uid
     *
     * @param int $shortcutId Shortcut id to get the complete shortcut for
     * @return mixed An array containing the shortcut's data on success or FALSE on failure
     */
    protected function getShortcutById($shortcutId)
    {
        $returnShortcut = false;
        foreach ($this->shortcuts as $shortcut) {
            if ($shortcut['raw']['uid'] == (int)$shortcutId) {
                $returnShortcut = $shortcut;
                continue;
            }
        }
        return $returnShortcut;
    }

    /**
     * Gets the available shortcut groups from default groups, user TSConfig, and global groups
     *
     * @return array
     */
    protected function initShortcutGroups()
    {
        $languageService = $this->getLanguageService();
        $backendUser = $this->getBackendUser();
        // Groups from TSConfig
        $bookmarkGroups = $backendUser->getTSConfigProp('options.bookmarkGroups');
        if (is_array($bookmarkGroups) && !empty($bookmarkGroups)) {
            foreach ($bookmarkGroups as $groupId => $label) {
                if (!empty($label)) {
                    $this->shortcutGroups[$groupId] = (string)$label;
                } elseif ($backendUser->isAdmin()) {
                    unset($this->shortcutGroups[$groupId]);
                }
            }
        }
        // Generate global groups, all global groups have negative IDs.
        if (!empty($this->shortcutGroups)) {
            $groups = $this->shortcutGroups;
            foreach ($groups as $groupId => $groupLabel) {
                $this->shortcutGroups[$groupId * -1] = $groupLabel;
            }
        }
        // Group -100 is kind of superglobal and can't be changed.
        $this->shortcutGroups[self::SUPERGLOBAL_GROUP] = 1;
        // Add labels
        foreach ($this->shortcutGroups as $groupId => $groupLabel) {
            $groupId = (int)$groupId;
            $label = $groupLabel;
            if ($groupLabel == '1') {
464
                $label = htmlspecialchars($languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_misc.xlf:bookmark_group_' . abs($groupId)));
465
466
                if (empty($label)) {
                    // Fallback label
467
                    $label = htmlspecialchars($languageService->getLL('bookmark_group')) . ' ' . abs($groupId);
468
469
470
471
                }
            }
            if ($groupId < 0) {
                // Global group
472
                $label = htmlspecialchars($languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_misc.xlf:bookmark_global')) . ': ' . (!empty($label) ? $label : abs($groupId));
473
                if ($groupId === self::SUPERGLOBAL_GROUP) {
474
                    $label = htmlspecialchars($languageService->getLL('bookmark_global')) . ': ' . htmlspecialchars($languageService->getLL('bookmark_all'));
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
                }
            }
            $this->shortcutGroups[$groupId] = $label;
        }
        return $this->shortcutGroups;
    }

    /**
     * Fetches the available shortcut groups, renders a form so it can be saved later on, usually called via AJAX
     *
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @return ResponseInterface the full HTML for the form
     */
    public function editFormAction(ServerRequestInterface $request, ResponseInterface $response)
    {
491
        $languageService = $this->getLanguageService();
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
        $parsedBody = $request->getParsedBody();
        $queryParams = $request->getQueryParams();

        $selectedShortcutId = (int)(isset($parsedBody['shortcutId']) ? $parsedBody['shortcutId'] : $queryParams['shortcutId']);
        $selectedShortcutGroupId = (int)(isset($parsedBody['shortcutGroup']) ? $parsedBody['shortcutGroup'] : $queryParams['shortcutGroup']);
        $selectedShortcut = $this->getShortcutById($selectedShortcutId);

        $shortcutGroups = $this->shortcutGroups;
        if (!$this->getBackendUser()->isAdmin()) {
            foreach ($shortcutGroups as $groupId => $groupName) {
                if ((int)$groupId < 0) {
                    unset($shortcutGroups[$groupId]);
                }
            }
        }

        // build the form
        $content = '
510
511
			<form class="shortcut-form" role="form" data-shortcutid="' . (int)$selectedShortcutId . '">
                <h3 class="dropdown-headline">
512
                    ' . htmlspecialchars($languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:toolbarItems.bookmarksEdit')) . '
513
514
                </h3>
                <hr>
Benjamin Kott's avatar
Benjamin Kott committed
515
516
517
				<div class="form-group">
					<input type="text" class="form-control" name="shortcut-title" value="' . htmlspecialchars($selectedShortcut['label']) . '">
				</div>';
518
        $content .= '
Benjamin Kott's avatar
Benjamin Kott committed
519
520
				<div class="form-group">
					<select class="form-control" name="shortcut-group">';
521
522
523
524
        foreach ($shortcutGroups as $shortcutGroupId => $shortcutGroupTitle) {
            $content .= '<option value="' . (int)$shortcutGroupId . '"' . ($selectedShortcutGroupId == $shortcutGroupId ? ' selected="selected"' : '') . '>' . htmlspecialchars($shortcutGroupTitle) . '</option>';
        }
        $content .= '
Benjamin Kott's avatar
Benjamin Kott committed
525
526
					</select>
				</div>
527
                <hr>
Benjamin Kott's avatar
Benjamin Kott committed
528
529
530
				<input type="button" class="btn btn-default shortcut-form-cancel" value="Cancel">
				<input type="button" class="btn btn-success shortcut-form-save" value="Save">
			</form>';
531

532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
        $response->getBody()->write($content);
        $response = $response->withHeader('Content-Type', 'text/html; charset=utf-8');
        return $response;
    }

    /**
     * Deletes a shortcut through an AJAX call
     *
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @return ResponseInterface
     */
    public function removeShortcutAction(ServerRequestInterface $request, ResponseInterface $response)
    {
        $parsedBody = $request->getParsedBody();
        $queryParams = $request->getQueryParams();

        $shortcutId = (int)(isset($parsedBody['shortcutId']) ? $parsedBody['shortcutId'] : $queryParams['shortcutId']);
        $fullShortcut = $this->getShortcutById($shortcutId);
        $success = false;
        if ($fullShortcut['raw']['userid'] == $this->getBackendUser()->user['uid']) {
553
554
555
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
                ->getQueryBuilderForTable('sys_be_shortcuts');
            $affectedRows = $queryBuilder->delete('sys_be_shortcuts')
556
557
558
559
560
561
                ->where(
                    $queryBuilder->expr()->eq(
                        'uid',
                        $queryBuilder->createNamedParameter($shortcutId, \PDO::PARAM_INT)
                    )
                )
562
563
                ->execute();
            if ($affectedRows === 1) {
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
                $success = true;
            }
        }
        $response->getBody()->write(json_encode(['success' => $success]));
        return $response;
    }

    /**
     * Creates a shortcut through an AJAX call
     *
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @return ResponseInterface
     */
    public function createShortcutAction(ServerRequestInterface $request, ResponseInterface $response)
    {
        $languageService = $this->getLanguageService();
        $parsedBody = $request->getParsedBody();
        $queryParams = $request->getQueryParams();

        // Default name
        $shortcutName = 'Shortcut';
        $shortcutNamePrepend = '';
        $url = isset($parsedBody['url']) ? $parsedBody['url'] : $queryParams['url'];

589
590
591
592
593
        // Use given display name
        if (!empty($parsedBody['displayName'])) {
            $shortcutName = $parsedBody['displayName'];
        }

594
595
596
597
598
599
600
601
602
603
604
605
606
        // Determine shortcut type
        $url = rawurldecode($url);
        $queryParts = parse_url($url);
        $queryParameters = GeneralUtility::explodeUrl2Array($queryParts['query'], true);

        // Proceed only if no scheme is defined, as URL is expected to be relative
        if (empty($queryParts['scheme'])) {
            if (is_array($queryParameters['edit'])) {
                $shortcut['table'] = key($queryParameters['edit']);
                $shortcut['recordid'] = key($queryParameters['edit'][$shortcut['table']]);
                $shortcut['pid'] = BackendUtility::getRecord($shortcut['table'], $shortcut['recordid'])['pid'];
                if ($queryParameters['edit'][$shortcut['table']][$shortcut['recordid']] == 'edit') {
                    $shortcut['type'] = 'edit';
607
                    $shortcutNamePrepend = htmlspecialchars($languageService->getLL('shortcut_edit'));
608
609
                } elseif ($queryParameters['edit'][$shortcut['table']][$shortcut['recordid']] == 'new') {
                    $shortcut['type'] = 'new';
610
                    $shortcutNamePrepend = htmlspecialchars($languageService->getLL('shortcut_create'));
611
612
613
614
615
616
617
                }
            } else {
                $shortcut['type'] = 'other';
                $shortcut['table'] = '';
                $shortcut['recordid'] = 0;
            }

618
619
620
621
622
623
            // Check if given id is a combined identifier
            if (!empty($queryParameters['id']) && preg_match('/^[0-9]+:/', $queryParameters['id'])) {
                try {
                    $resourceFactory = ResourceFactory::getInstance();
                    $resource = $resourceFactory->getObjectFromCombinedIdentifier($queryParameters['id']);
                    $shortcutName = trim($shortcutNamePrepend . ' ' . $resource->getName());
Claus Due's avatar
Claus Due committed
624
625
                } catch (ResourceDoesNotExistException $e) {
                }
626
            } else {
627
628
                // Lookup the title of this page and use it as default description
                $pageId = (int)($shortcut['pid'] ?: ($shortcut['recordid'] ?: $this->getLinkedPageId($url)));
Claus Due's avatar
Claus Due committed
629
                $page = false;
630
631
                if ($pageId) {
                    $page = BackendUtility::getRecord('pages', $pageId);
632
633
634
635
                }
                if (!empty($page)) {
                    // Set the name to the title of the page
                    if ($shortcut['type'] === 'other') {
636
637
638
639
640
                        if (empty($shortcutName)) {
                            $shortcutName = $page['title'];
                        } else {
                            $shortcutName .= ' (' . $page['title'] . ')';
                        }
641
642
643
644
                    } else {
                        $shortcutName = $shortcutNamePrepend . ' ' .
                            $languageService->sL($GLOBALS['TCA'][$shortcut['table']]['ctrl']['title']) .
                            ' (' . $page['title'] . ')';
645
                    }
646
647
648
                } elseif ($shortcut['table'] !== '' && $shortcut['type'] !== 'other') {
                    $shortcutName = $shortcutNamePrepend . ' ' .
                        $languageService->sL($GLOBALS['TCA'][$shortcut['table']]['ctrl']['title']);
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
                }
            }

            return $this->tryAddingTheShortcut($response, $url, $shortcutName);
        }
    }

    /**
     * Try to adding a shortcut
     *
     * @param ResponseInterface $response
     * @param string $url
     * @param string $shortcutName
     * @return ResponseInterface
     */
    protected function tryAddingTheShortcut(ResponseInterface $response, $url, $shortcutName)
    {
        $module = GeneralUtility::_POST('module');
        $shortcutCreated = 'failed';

        if (!empty($module) && !empty($url)) {
            $shortcutCreated = 'alreadyExists';

672
            if (!BackendUtility::shortcutExists($url) && !is_array($module)) {
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
                $shortcutCreated = $this->addShortcut($url, $shortcutName, $module);
            }
        }

        $response->getBody()->write($shortcutCreated);
        $response = $response->withHeader('Content-Type', 'text/html; charset=utf-8');
        return $response;
    }

    /**
     * Add a shortcut now with some user stuffs
     *
     * @param string $url
     * @param string $shortcutName
     * @param string $module
     *
     * @return string
     */
    protected function addShortcut($url, $shortcutName, $module)
    {
693
694
695
        $moduleLabels = $this->moduleLoader->getLabelsForModule($module);
        if ($shortcutName === 'Shortcut' && !empty($moduleLabels['shortdescription'])) {
            $shortcutName = $this->getLanguageService()->sL($moduleLabels['shortdescription']);
696
697
698
699
700
701
702
703
704
705
706
        }

        $motherModule = GeneralUtility::_POST('motherModName');
        $fieldValues = [
            'userid' => $this->getBackendUser()->user['uid'],
            'module_name' => $module . '|' . $motherModule,
            'url' => $url,
            'description' => $shortcutName,
            'sorting' => $GLOBALS['EXEC_TIME']
        ];

707
708
709
710
711
712
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getQueryBuilderForTable('sys_be_shortcuts');
        $affectedRows = $queryBuilder
            ->insert('sys_be_shortcuts')
            ->values($fieldValues)
            ->execute();
713

714
        if ($affectedRows === 1) {
715
716
717
            return 'success';
        } else {
            return 'failed';
718
719
720
721
722
723
724
725
726
727
728
729
        }
    }

    /**
     * Exists already a shortcut entry for this TYPO3 url?
     *
     * @param string $url
     *
     * @return bool
     */
    protected function shortcutExists($url)
    {
730
731
732
733
734
735
736
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getQueryBuilderForTable('sys_be_shortcuts');
        $uid = $queryBuilder->select('uid')
            ->from('sys_be_shortcuts')
            ->where(
                $queryBuilder->expr()->eq(
                    'userid',
737
                    $queryBuilder->createNamedParameter($this->getBackendUser()->user['uid'], \PDO::PARAM_INT)
738
                ),
739
                $queryBuilder->expr()->eq('url', $queryBuilder->createNamedParameter($url, \PDO::PARAM_STR))
740
741
742
743
744
            )
            ->execute()
            ->fetchColumn();

        return (bool)$uid;
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
    }

    /**
     * Gets called when a shortcut is changed, checks whether the user has
     * permissions to do so and saves the changes if everything is ok
     *
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @return ResponseInterface
     */
    public function saveFormAction(ServerRequestInterface $request, ResponseInterface $response)
    {
        $parsedBody = $request->getParsedBody();
        $queryParams = $request->getQueryParams();

        $backendUser = $this->getBackendUser();
        $shortcutId = (int)(isset($parsedBody['shortcutId']) ? $parsedBody['shortcutId'] : $queryParams['shortcutId']);
        $shortcutName = strip_tags(isset($parsedBody['shortcutTitle']) ? $parsedBody['shortcutTitle'] : $queryParams['shortcutTitle']);
        $shortcutGroupId = (int)(isset($parsedBody['shortcutGroup']) ? $parsedBody['shortcutGroup'] : $queryParams['shortcutGroup']);
764
765
766
767

        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
            ->getQueryBuilderForTable('sys_be_shortcuts');
        $queryBuilder->update('sys_be_shortcuts')
768
769
770
771
772
773
            ->where(
                $queryBuilder->expr()->eq(
                    'uid',
                    $queryBuilder->createNamedParameter($shortcutId, \PDO::PARAM_INT)
                )
            )
774
775
776
777
778
            ->set('description', $shortcutName)
            ->set('sc_group', $shortcutGroupId);

        if (!$backendUser->isAdmin()) {
            // Users can only modify their own shortcuts
779
780
781
782
783
784
            $queryBuilder->andWhere(
                $queryBuilder->expr()->eq(
                    'userid',
                    $queryBuilder->createNamedParameter($backendUser->user['uid'], \PDO::PARAM_INT)
                )
            );
785
786
787
788

            if ($shortcutGroupId < 0) {
                $queryBuilder->set('sc_group', 0);
            }
789
        }
790
791

        if ($queryBuilder->execute() === 1) {
792
793
794
795
            $response->getBody()->write($shortcutName);
        } else {
            $response->getBody()->write('failed');
        }
796
        return $response->withHeader('Content-Type', 'text/html; charset=utf-8');
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
    }

    /**
     * Gets the label for a shortcut group
     *
     * @param int $groupId A shortcut group id
     * @return string The shortcut group label, can be an empty string if no group was found for the id
     */
    protected function getShortcutGroupLabel($groupId)
    {
        return isset($this->shortcutGroups[$groupId]) ? $this->shortcutGroups[$groupId] : '';
    }

    /**
     * Gets a list of global groups, shortcuts in these groups are available to all users
     *
     * @return array Array of global groups
     */
    protected function getGlobalShortcutGroups()
    {
817
        $globalGroups = [];
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
        foreach ($this->shortcutGroups as $groupId => $groupLabel) {
            if ($groupId < 0) {
                $globalGroups[$groupId] = $groupLabel;
            }
        }
        return $globalGroups;
    }

    /**
     * runs through the available shortcuts an collects their groups
     *
     * @return array Array of groups which have shortcuts
     */
    protected function getGroupsFromShortcuts()
    {
833
        $groups = [];
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
        foreach ($this->shortcuts as $shortcut) {
            $groups[$shortcut['group']] = $this->shortcutGroups[$shortcut['group']];
        }
        return array_unique($groups);
    }

    /**
     * Gets the icon for the shortcut
     *
     * @param array $row
     * @param array $shortcut
     * @return string Shortcut icon as img tag
     */
    protected function getShortcutIcon($row, $shortcut)
    {
        $languageService = $this->getLanguageService();
850
        $titleAttribute = htmlspecialchars($languageService->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:toolbarItems.shortcut'));
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
        switch ($row['module_name']) {
            case 'xMOD_alt_doc.php':
                $table = $shortcut['table'];
                $recordid = $shortcut['recordid'];
                $icon = '';
                if ($shortcut['type'] == 'edit') {
                    // Creating the list of fields to include in the SQL query:
                    $selectFields = $this->fieldArray;
                    $selectFields[] = 'uid';
                    $selectFields[] = 'pid';
                    if ($table == 'pages') {
                        $selectFields[] = 'module';
                        $selectFields[] = 'extendToSubpages';
                        $selectFields[] = 'doktype';
                    }
                    if (is_array($GLOBALS['TCA'][$table]['ctrl']['enablecolumns'])) {
                        $selectFields = array_merge($selectFields, $GLOBALS['TCA'][$table]['ctrl']['enablecolumns']);
                    }
                    if ($GLOBALS['TCA'][$table]['ctrl']['type']) {
                        $selectFields[] = $GLOBALS['TCA'][$table]['ctrl']['type'];
                    }
                    if ($GLOBALS['TCA'][$table]['ctrl']['typeicon_column']) {
                        $selectFields[] = $GLOBALS['TCA'][$table]['ctrl']['typeicon_column'];
                    }
                    if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
                        $selectFields[] = 't3ver_state';
                    }
878
879
880
881
882

                    $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
                        ->getQueryBuilderForTable($table);
                    $queryBuilder->select(...array_unique(array_values($selectFields)))
                        ->from($table)
883
884
885
886
887
888
                        ->where(
                            $queryBuilder->expr()->in(
                                'uid',
                                $queryBuilder->createNamedParameter($recordid, \PDO::PARAM_INT)
                            )
                        );
889
890
891
892
893
894
895

                    if ($table === 'pages' && $this->perms_clause) {
                        $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($this->perms_clause));
                    }

                    $row = $queryBuilder->execute()->fetch();

896
897
                    $icon = '<span title="' . $titleAttribute . '">' . $this->iconFactory->getIconForRecord($table, (array)$row, Icon::SIZE_SMALL)->render() . '</span>';
                } elseif ($shortcut['type'] == 'new') {
898
                    $icon = '<span title="' . $titleAttribute . '">' . $this->iconFactory->getIconForRecord($table, [], Icon::SIZE_SMALL)->render() . '</span>';
899
900
901
902
903
904
905
906
907
                }
                break;
            case 'file_edit':
                $icon = '<span title="' . $titleAttribute . '">' . $this->iconFactory->getIcon('mimetypes-text-html', Icon::SIZE_SMALL)->render() . '</span>';
                break;
            case 'wizard_rte':
                $icon = '<span title="' . $titleAttribute . '">' . $this->iconFactory->getIcon('mimetypes-word', Icon::SIZE_SMALL)->render() . '</span>';
                break;
            default:
908
                $iconIdentifier = '';
909
910
911
                $moduleName = $row['module_name'];
                if (strpos($moduleName, '_') !== false) {
                    list($mainModule, $subModule) = explode('_', $moduleName, 2);
912
                    $iconIdentifier = $this->moduleLoader->modules[$mainModule]['sub'][$subModule]['iconIdentifier'];
913
                } elseif (!empty($moduleName)) {
914
                    $iconIdentifier = $this->moduleLoader->modules[$moduleName]['iconIdentifier'];
915
                }
916
917
                if (!$iconIdentifier) {
                    $iconIdentifier = 'empty-empty';
918
                }
919
                $icon = '<span title="' . $titleAttribute . '">' . $this->iconFactory->getIcon($iconIdentifier, Icon::SIZE_SMALL)->render() . '</span>';
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
        }
        return $icon;
    }

    /**
     * Returns title for the shortcut icon
     *
     * @param string $shortcutLabel Shortcut label
     * @param string $moduleName Backend module name (key)
     * @param string $parentModuleName Parent module label
     * @return string Title for the shortcut icon
     */
    protected function getShortcutIconTitle($shortcutLabel, $moduleName, $parentModuleName = '')
    {
        $languageService = $this->getLanguageService();
        if (substr($moduleName, 0, 5) == 'xMOD_') {
            $title = substr($moduleName, 5);
        } else {
938
939
940
941
942
943
            list($mainModule, $subModule) = explode('_', $moduleName);
            $mainModuleLabels = $this->moduleLoader->getLabelsForModule($mainModule);
            $title = $languageService->sL($mainModuleLabels['title']);
            if (!empty($subModule)) {
                $subModuleLabels = $this->moduleLoader->getLabelsForModule($moduleName);
                $title .= '>' . $languageService->sL($subModuleLabels['title']);
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
            }
        }
        if ($parentModuleName) {
            $title .= ' (' . $parentModuleName . ')';
        }
        $title .= ': ' . $shortcutLabel;
        return $title;
    }

    /**
     * Return the ID of the page in the URL if found.
     *
     * @param string $url The URL of the current shortcut link
     * @return string If a page ID was found, it is returned. Otherwise: 0
     */
    protected function getLinkedPageId($url)
    {
        return preg_replace('/.*[\\?&]id=([^&]+).*/', '$1', $url);
    }

    /**
     * Position relative to others, live search should be very right
     *
     * @return int
     */
    public function getIndex()
    {
        return 20;
    }

    /**
     * Returns the current BE user.
     *
     * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
     */
    protected function getBackendUser()
    {
        return $GLOBALS['BE_USER'];
    }

    /**
     * Returns current PageRenderer
     *
     * @return PageRenderer
     */
    protected function getPageRenderer()
    {
        return GeneralUtility::makeInstance(PageRenderer::class);
    }

    /**
     * Returns LanguageService
     *
     * @return \TYPO3\CMS\Lang\LanguageService
     */
    protected function getLanguageService()
    {
        return $GLOBALS['LANG'];
    }
1003
}