Upgraded drupal core with security updates
[yaffs-website] / web / core / modules / shortcut / shortcut.module
1 <?php
2
3 /**
4  * @file
5  * Allows users to manage customizable lists of shortcut links.
6  */
7
8 use Drupal\Component\Utility\SafeMarkup;
9 use Drupal\Core\Access\AccessResult;
10 use Drupal\Core\Cache\Cache;
11 use Drupal\Core\Routing\RouteMatchInterface;
12 use Drupal\Core\Url;
13 use Drupal\shortcut\Entity\ShortcutSet;
14 use Drupal\shortcut\ShortcutSetInterface;
15
16 /**
17  * Implements hook_help().
18  */
19 function shortcut_help($route_name, RouteMatchInterface $route_match) {
20   switch ($route_name) {
21     case 'help.page.shortcut':
22       $output = '<h3>' . t('About') . '</h3>';
23       $output .= '<p>' . t('The Shortcut module allows users to create sets of <em>shortcut</em> links to commonly-visited pages of the site. Shortcuts are contained within <em>sets</em>. Each user with <em>Select any shortcut set</em> permission can select a shortcut set created by anyone at the site. For more information, see the <a href=":shortcut">online documentation for the Shortcut module</a>.', [':shortcut' => 'https://www.drupal.org/documentation/modules/shortcut']) . '</p>';
24       $output .= '<h3>' . t('Uses') . '</h3>';
25       $output .= '<dl><dt>' . t('Administering shortcuts') . '</dt>';
26       $output .= '<dd>' . t('Users with the <em>Administer shortcuts</em> permission can manage shortcut sets and edit the shortcuts within sets from the <a href=":shortcuts">Shortcuts administration page</a>.', [':shortcuts' => \Drupal::url('entity.shortcut_set.collection')]) . '</dd>';
27       $output .= '<dt>' . t('Choosing shortcut sets') . '</dt>';
28       $output .= '<dd>' . t('Users with permission to switch shortcut sets can choose a shortcut set to use from the Shortcuts tab of their user account page.') . '</dd>';
29       $output .= '<dt>' . t('Adding and removing shortcuts') . '</dt>';
30       $output .= '<dd>' . t('The Shortcut module creates an add/remove link for each page on your site; the link lets you add or remove the current page from the currently-enabled set of shortcuts (if your theme displays it and you have permission to edit your shortcut set). The core Seven administration theme displays this link next to the page title, as a grey or yellow star. If you click on the grey star, you will add that page to your preferred set of shortcuts. If the page is already part of your shortcut set, the link will be a yellow star, and will allow you to remove the current page from your shortcut set.') . '</dd>';
31       $output .= '<dt>' . t('Displaying shortcuts') . '</dt>';
32       $output .= '<dd>' . t('You can display your shortcuts by enabling the <em>Shortcuts</em> block on the <a href=":blocks">Blocks administration page</a>. Certain administrative modules also display your shortcuts; for example, the core <a href=":toolbar-help">Toolbar module</a> provides a corresponding menu item.', [':blocks' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#', ':toolbar-help' => (\Drupal::moduleHandler()->moduleExists('toolbar')) ? \Drupal::url('help.page', ['name' => 'toolbar']) : '#']) . '</dd>';
33       $output .= '</dl>';
34       return $output;
35
36     case 'entity.shortcut_set.collection':
37     case 'shortcut.set_add':
38     case 'entity.shortcut_set.edit_form':
39       $user = \Drupal::currentUser();
40       if ($user->hasPermission('access shortcuts') && $user->hasPermission('switch shortcut sets')) {
41         $output = '<p>' . t('Define which shortcut set you are using on the <a href=":shortcut-link">Shortcuts tab</a> of your account page.', [':shortcut-link' => \Drupal::url('shortcut.set_switch', ['user' => $user->id()])]) . '</p>';
42         return $output;
43       }
44   }
45 }
46
47 /**
48  * Access callback for editing a shortcut set.
49  *
50  * @param Drupal\shortcut\ShortcutSetInterface $shortcut_set
51  *   (optional) The shortcut set to be edited. If not set, the current user's
52  *   shortcut set will be used.
53  *
54  * @return \Drupal\Core\Access\AccessResultInterface
55  *   The access result.
56  */
57 function shortcut_set_edit_access(ShortcutSetInterface $shortcut_set = NULL) {
58   $account = \Drupal::currentUser();
59
60   // Shortcut administrators can edit any set.
61   if ($account->hasPermission('administer shortcuts')) {
62     return AccessResult::allowed()->cachePerPermissions();
63   }
64
65   // Sufficiently-privileged users can edit their currently displayed shortcut
66   // set, but not other sets. They must also be able to access shortcuts.
67   $may_edit_current_shortcut_set = $account->hasPermission('customize shortcut links') && (!isset($shortcut_set) || $shortcut_set == shortcut_current_displayed_set()) && $account->hasPermission('access shortcuts');
68   $result = AccessResult::allowedIf($may_edit_current_shortcut_set)->cachePerPermissions();
69   if (!$result->isAllowed()) {
70     $result->setReason("The shortcut set must be the currently displayed set for the user and the user must have 'access shortcuts' AND 'customize shortcut links' permissions.");
71   }
72   return $result;
73 }
74
75 /**
76  * Access callback for switching the shortcut set assigned to a user account.
77  *
78  * @param object $account
79  *   (optional) The user account whose shortcuts will be switched. If not set,
80  *   permissions will be checked for switching the logged-in user's own
81  *   shortcut set.
82  *
83  * @return \Drupal\Core\Access\AccessResultInterface
84  *   The access result.
85  */
86 function shortcut_set_switch_access($account = NULL) {
87   $user = \Drupal::currentUser();
88
89   if ($user->hasPermission('administer shortcuts')) {
90     // Administrators can switch anyone's shortcut set.
91     return AccessResult::allowed()->cachePerPermissions();
92   }
93
94   if (!$user->hasPermission('access shortcuts')) {
95     // The user has no permission to use shortcuts.
96     return AccessResult::neutral()->cachePerPermissions();
97   }
98
99   if (!$user->hasPermission('switch shortcut sets')) {
100     // The user has no permission to switch anyone's shortcut set.
101     return AccessResult::neutral()->cachePerPermissions();
102   }
103
104   // Users with the 'switch shortcut sets' permission can switch their own
105   // shortcuts sets.
106   if (!isset($account)) {
107     return AccessResult::allowed()->cachePerPermissions();
108   }
109   elseif ($user->id() == $account->id()) {
110     return AccessResult::allowed()->cachePerPermissions()->cachePerUser();
111   }
112
113   // No opinion.
114   return AccessResult::neutral()->cachePerPermissions();
115 }
116
117 /**
118  * Assigns a user to a particular shortcut set.
119  *
120  * @param $shortcut_set Drupal\shortcut\Entity\Shortcut
121  *   An object representing the shortcut set.
122  * @param $account
123  *   A user account that will be assigned to use the set.
124  *
125  * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
126  *   Use \Drupal::entityManager()->getStorage('shortcut_set')->assignUser().
127  */
128 function shortcut_set_assign_user($shortcut_set, $account) {
129   \Drupal::entityManager()
130     ->getStorage('shortcut_set')
131     ->assignUser($shortcut_set, $account);
132 }
133
134 /**
135  * Unassigns a user from any shortcut set they may have been assigned to.
136  *
137  * The user will go back to using whatever default set applies.
138  *
139  * @param $account
140  *   A user account that will be removed from the shortcut set assignment.
141  *
142  * @return
143  *   TRUE if the user was previously assigned to a shortcut set and has been
144  *   successfully removed from it. FALSE if the user was already not assigned
145  *   to any set.
146  *
147  * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
148  *   Use \Drupal::entityManager()->getStorage('shortcut_set')->unassignUser().
149  */
150 function shortcut_set_unassign_user($account) {
151   return (bool) \Drupal::entityManager()
152     ->getStorage('shortcut_set')
153     ->unassignUser($account);
154 }
155
156 /**
157  * Returns the current displayed shortcut set for the provided user account.
158  *
159  * @param $account
160  *   (optional) The user account whose shortcuts will be returned. Defaults to
161  *   the currently logged-in user.
162  *
163  * @return
164  *   An object representing the shortcut set that should be displayed to the
165  *   current user. If the user does not have an explicit shortcut set defined,
166  *   the default set is returned.
167  */
168 function shortcut_current_displayed_set($account = NULL) {
169   $shortcut_sets = &drupal_static(__FUNCTION__, []);
170   $user = \Drupal::currentUser();
171   if (!isset($account)) {
172     $account = $user;
173   }
174   // Try to return a shortcut set from the static cache.
175   if (isset($shortcut_sets[$account->id()])) {
176     return $shortcut_sets[$account->id()];
177   }
178   // If none was found, try to find a shortcut set that is explicitly assigned
179   // to this user.
180   $shortcut_set_name = \Drupal::entityManager()
181     ->getStorage('shortcut_set')
182     ->getAssignedToUser($account);
183   if ($shortcut_set_name) {
184     $shortcut_set = ShortcutSet::load($shortcut_set_name);
185   }
186   // Otherwise, use the default set.
187   else {
188     $shortcut_set = shortcut_default_set($account);
189   }
190
191   $shortcut_sets[$account->id()] = $shortcut_set;
192   return $shortcut_set;
193 }
194
195 /**
196  * Returns the default shortcut set for a given user account.
197  *
198  * @param object $account
199  *   (optional) The user account whose default shortcut set will be returned.
200  *   If not provided, the function will return the currently logged-in user's
201  *   default shortcut set.
202  *
203  * @return
204  *   An object representing the default shortcut set.
205  */
206 function shortcut_default_set($account = NULL) {
207   $user = \Drupal::currentUser();
208   if (!isset($account)) {
209     $account = $user;
210   }
211
212   // Allow modules to return a default shortcut set name. Since we can only
213   // have one, we allow the last module which returns a valid result to take
214   // precedence. If no module returns a valid set, fall back on the site-wide
215   // default, which is the lowest-numbered shortcut set.
216   $suggestions = array_reverse(\Drupal::moduleHandler()->invokeAll('shortcut_default_set', [$account]));
217   $suggestions[] = 'default';
218   foreach ($suggestions as $name) {
219     if ($shortcut_set = ShortcutSet::load($name)) {
220       break;
221     }
222   }
223
224   return $shortcut_set;
225 }
226
227 /**
228  * Check to see if a shortcut set with the given title already exists.
229  *
230  * @param $title
231  *   Human-readable name of the shortcut set to check.
232  *
233  * @return
234  *   TRUE if a shortcut set with that title exists; FALSE otherwise.
235  *
236  * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
237  */
238 function shortcut_set_title_exists($title) {
239   $sets = ShortcutSet::loadMultiple();
240   foreach ($sets as $set) {
241     if ($set->label() == $title) {
242       return TRUE;
243     }
244   }
245   return FALSE;
246 }
247
248 /**
249  * Returns an array of shortcut links, suitable for rendering.
250  *
251  * @param \Drupal\shortcut\ShortcutSetInterface $shortcut_set
252  *   (optional) An object representing the set whose links will be displayed.
253  *   If not provided, the user's current set will be displayed.
254  *
255  * @return \Drupal\shortcut\ShortcutInterface[]
256  *   An array of shortcut links, in the format returned by the menu system.
257  */
258 function shortcut_renderable_links($shortcut_set = NULL) {
259   $shortcut_links = [];
260
261   if (!isset($shortcut_set)) {
262     $shortcut_set = shortcut_current_displayed_set();
263   }
264
265   $cache_tags = [];
266   foreach ($shortcut_set->getShortcuts() as $shortcut) {
267     $shortcut = \Drupal::entityManager()->getTranslationFromContext($shortcut);
268     $url = $shortcut->getUrl();
269     if ($url->access()) {
270       $links[$shortcut->id()] = [
271         'type' => 'link',
272         'title' => $shortcut->label(),
273         'url' => $shortcut->getUrl(),
274       ];
275       $cache_tags = Cache::mergeTags($cache_tags, $shortcut->getCacheTags());
276     }
277   }
278
279   if (!empty($links)) {
280     $shortcut_links = [
281       '#theme' => 'links__toolbar_shortcuts',
282       '#links' => $links,
283       '#attributes' => [
284         'class' => ['toolbar-menu'],
285       ],
286       '#cache' => [
287         'tags' => $cache_tags,
288       ],
289     ];
290   }
291
292   return $shortcut_links;
293 }
294
295 /**
296  * Implements hook_preprocess_HOOK() for block templates.
297  */
298 function shortcut_preprocess_block(&$variables) {
299   if ($variables['configuration']['provider'] == 'shortcut') {
300     $variables['attributes']['role'] = 'navigation';
301   }
302 }
303
304 /**
305  * Implements hook_preprocess_HOOK() for page title templates.
306  */
307 function shortcut_preprocess_page_title(&$variables) {
308   // Only display the shortcut link if the user has the ability to edit
309   // shortcuts and if the page's actual content is being shown (for example,
310   // we do not want to display it on "access denied" or "page not found"
311   // pages).
312   if (shortcut_set_edit_access()->isAllowed() && !\Drupal::request()->attributes->has('exception')) {
313     $link = Url::fromRouteMatch(\Drupal::routeMatch())->getInternalPath();
314     $route_match = \Drupal::routeMatch();
315
316     // Replicate template_preprocess_html()'s processing to get the title in
317     // string form, so we can set the default name for the shortcut.
318     // Strip HTML tags from the title.
319     $name = trim(strip_tags(render($variables['title'])));
320     $query = [
321       'link' => $link,
322       'name' => $name,
323     ];
324
325     $shortcut_set = shortcut_current_displayed_set();
326
327     // Check if $link is already a shortcut and set $link_mode accordingly.
328     $shortcuts = \Drupal::entityManager()->getStorage('shortcut')->loadByProperties(['shortcut_set' => $shortcut_set->id()]);
329     /** @var \Drupal\shortcut\ShortcutInterface $shortcut */
330     foreach ($shortcuts as $shortcut) {
331       if (($shortcut_url = $shortcut->getUrl()) && $shortcut_url->isRouted() && $shortcut_url->getRouteName() == $route_match->getRouteName() && $shortcut_url->getRouteParameters() == $route_match->getRawParameters()->all()) {
332         $shortcut_id = $shortcut->id();
333         break;
334       }
335     }
336     $link_mode = isset($shortcut_id) ? "remove" : "add";
337
338     if ($link_mode == "add") {
339       $link_text = shortcut_set_switch_access()->isAllowed() ? t('Add to %shortcut_set shortcuts', ['%shortcut_set' => $shortcut_set->label()]) : t('Add to shortcuts');
340       $route_name = 'shortcut.link_add_inline';
341       $route_parameters = ['shortcut_set' => $shortcut_set->id()];
342     }
343     else {
344       $query['id'] = $shortcut_id;
345       $link_text = shortcut_set_switch_access()->isAllowed() ? t('Remove from %shortcut_set shortcuts', ['%shortcut_set' => $shortcut_set->label()]) : t('Remove from shortcuts');
346       $route_name = 'entity.shortcut.link_delete_inline';
347       $route_parameters = ['shortcut' => $shortcut_id];
348     }
349
350     if (theme_get_setting('third_party_settings.shortcut.module_link')) {
351       $query += \Drupal::destination()->getAsArray();
352       $variables['title_suffix']['add_or_remove_shortcut'] = [
353         '#attached' => [
354           'library' => [
355             'shortcut/drupal.shortcut',
356           ],
357         ],
358         '#type' => 'link',
359         '#title' => SafeMarkup::format('<span class="shortcut-action__icon"></span><span class="shortcut-action__message">@text</span>', ['@text' => $link_text]),
360         '#url' => Url::fromRoute($route_name, $route_parameters),
361         '#options' => ['query' => $query],
362         '#attributes' => [
363           'class' => [
364             'shortcut-action',
365             'shortcut-action--' . $link_mode,
366           ],
367         ],
368       ];
369     }
370   }
371 }
372
373 /**
374  * Implements hook_toolbar().
375  */
376 function shortcut_toolbar() {
377   $user = \Drupal::currentUser();
378
379   $items = [];
380   $items['shortcuts'] = [
381     '#cache' => [
382       'contexts' => [
383         // Cacheable per user, because each user can have their own shortcut
384         // set, even if they cannot create or select a shortcut set, because
385         // an administrator may have assigned a non-default shortcut set.
386         'user',
387       ],
388     ],
389   ];
390
391   if ($user->hasPermission('access shortcuts')) {
392     $links = shortcut_renderable_links();
393     $shortcut_set = shortcut_current_displayed_set();
394     \Drupal::service('renderer')->addCacheableDependency($items['shortcuts'], $shortcut_set);
395     $configure_link = NULL;
396     if (shortcut_set_edit_access($shortcut_set)->isAllowed()) {
397       $configure_link = [
398         '#type' => 'link',
399         '#title' => t('Edit shortcuts'),
400         '#url' => Url::fromRoute('entity.shortcut_set.customize_form', ['shortcut_set' => $shortcut_set->id()]),
401         '#options' => ['attributes' => ['class' => ['edit-shortcuts']]],
402       ];
403     }
404     if (!empty($links) || !empty($configure_link)) {
405       $items['shortcuts'] += [
406         '#type' => 'toolbar_item',
407         'tab' => [
408           '#type' => 'link',
409           '#title' => t('Shortcuts'),
410           '#url' => $shortcut_set->urlInfo('collection'),
411           '#attributes' => [
412             'title' => t('Shortcuts'),
413             'class' => ['toolbar-icon', 'toolbar-icon-shortcut'],
414           ],
415         ],
416         'tray' => [
417           '#heading' => t('User-defined shortcuts'),
418           'shortcuts' => $links,
419           'configure' => $configure_link,
420         ],
421         '#weight' => -10,
422         '#attached' => [
423           'library' => [
424             'shortcut/drupal.shortcut',
425           ],
426         ],
427       ];
428     }
429   }
430
431   return $items;
432 }
433
434 /**
435  * Implements hook_themes_installed().
436  */
437 function shortcut_themes_installed($theme_list) {
438   if (in_array('seven', $theme_list)) {
439     // Theme settings are not configuration entities and cannot depend on modules
440     // so to set a module-specific setting, we need to set it with logic.
441     if (\Drupal::moduleHandler()->moduleExists('shortcut')) {
442       \Drupal::configFactory()->getEditable('seven.settings')->set('third_party_settings.shortcut.module_link', TRUE)->save(TRUE);
443     }
444   }
445 }