summaryrefslogtreecommitdiffstats
path: root/core/modules/shortcut/shortcut.module
blob: 3ad21f00aff1404aba3b3f0794f5ef8f9fc15e45 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
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
<?php

/**
 * @file
 * Allows users to manage customizable lists of shortcut links.
 */

use Drupal\Component\Utility\NestedArray;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Routing\UrlMatcher;
use Drupal\Core\Url;
use Drupal\shortcut\ShortcutSetInterface;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Implements hook_help().
 */
function shortcut_help($route_name, Request $request) {
  switch ($route_name) {
    case 'help.page.shortcut':
      $output = '<h3>' . t('About') . '</h3>';
      $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 online handbook entry for <a href="!shortcut">Shortcut module</a>.', array('!shortcut' => 'http://drupal.org/documentation/modules/shortcut')) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl><dt>' . t('Administering shortcuts') . '</dt>';
      $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>.', array('!shortcuts' => \Drupal::url('shortcut.set_admin'))) . '</dd>';
      $output .= '<dt>' . t('Choosing shortcut sets') . '</dt>';
      $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>';
      $output .= '<dt>' . t('Adding and removing shortcuts') . '</dt>';
      $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 small + or - sign. If you click on the + sign, 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 - sign, and will allow you to remove the current page from your shortcut set.') . '</dd>';
      $output .= '<dt>' . t('Displaying shortcuts') . '</dt>';
      $output .= '<dd>' . t('You can display your shortcuts by enabling the Shortcuts 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> displays them near the top of the page, along with an <em>Edit shortcuts</em> link.', array('!blocks' => \Drupal::url('block.admin_display'), '!toolbar-help' => \Drupal::url('help.page', array('name' => 'toolbar')))) . '</dd>';
      $output .= '</dl>';
      return $output;

    case 'shortcut.set_admin':
    case 'shortcut.set_add':
    case 'shortcut.set_edit':
      $user = \Drupal::currentUser();
      if ($user->hasPermission('switch shortcut sets')) {
        $output = '<p>' . t('Define which shortcut set you are using on the <a href="@shortcut-link">Shortcuts tab</a> of your account page.', array('@shortcut-link' => url("user/{$user->id()}/shortcuts"))) . '</p>';
        return $output;
      }
  }
}

/**
 * Implements hook_permission().
 */
function shortcut_permission() {
  return array(
    'administer shortcuts' => array(
      'title' => t('Administer shortcuts'),
    ),
    'customize shortcut links' => array(
      'title' => t('Edit current shortcut set'),
      'description' => t('Editing the current shortcut set will affect other users if that set has been assigned to or selected by other users. Granting "Select any shortcut set" permission along with this permission will grant permission to edit any shortcut set.'),
    ),
    'switch shortcut sets' => array(
      'title' => t('Select any shortcut set'),
      'description' => t('From all shortcut sets, select one to be own active set. Without this permission, an administrator selects shortcut sets for users.'),
    ),
  );
}

/**
 * Access callback for editing a shortcut set.
 *
 * @param Drupal\shortcut\ShortcutSetInterface $shortcut_set
 *   (optional) The shortcut set to be edited. If not set, the current user's
 *   shortcut set will be used.
 *
 * @return bool
 *   TRUE if the current user has access to edit the shortcut set, FALSE
 *   otherwise.
 */
function shortcut_set_edit_access(ShortcutSetInterface $shortcut_set = NULL) {
  $account = \Drupal::currentUser();
  // Sufficiently-privileged users can edit their currently displayed shortcut
  // set, but not other sets. Shortcut administrators can edit any set.
  if ($account->hasPermission('administer shortcuts')) {
    return TRUE;
  }
  if ($account->hasPermission('customize shortcut links')) {
    return !isset($shortcut_set) || $shortcut_set == shortcut_current_displayed_set();
  }
  return FALSE;
}

/**
 * Access callback for switching the shortcut set assigned to a user account.
 *
 * @param object $account
 *   (optional) The user account whose shortcuts will be switched. If not set,
 *   permissions will be checked for switching the logged-in user's own
 *   shortcut set.
 *
 * @return bool
 *   TRUE if the current user has access to switch the shortcut set of the
 *   provided account, FALSE otherwise.
 */
function shortcut_set_switch_access($account = NULL) {
  $user = \Drupal::currentUser();

  if ($user->hasPermission('administer shortcuts')) {
    // Administrators can switch anyone's shortcut set.
    return TRUE;
  }

  if (!$user->hasPermission('switch shortcut sets')) {
    // The user has no permission to switch anyone's shortcut set.
    return FALSE;
  }

  if (!isset($account) || $user->id() == $account->id()) {
    // Users with the 'switch shortcut sets' permission can switch their own
    // shortcuts sets.
    return TRUE;
  }

  return FALSE;
}

/**
 * Loads the data for a shortcut set.
 *
 * @param string $id
 *   The machine-name of the shortcut set to load.
 *
 * @return \Drupal\shortcut\ShortcutSetInterface|null
 *   If the shortcut set exists, an object containing the following properties:
 *   - 'id': The internal name of the shortcut set.
 *   - 'label': The title of the shortcut set.
 *   If the shortcut set does not exist, the function returns NULL.
 */
function shortcut_set_load($id) {
  return entity_load('shortcut_set', $id);
}

/**
 * Assigns a user to a particular shortcut set.
 *
 * @param $shortcut_set Drupal\shortcut\Entity\Shortcut
 *   An object representing the shortcut set.
 * @param $account
 *   A user account that will be assigned to use the set.
 */
function shortcut_set_assign_user($shortcut_set, $account) {
  \Drupal::entityManager()
    ->getStorage('shortcut_set')
    ->assignUser($shortcut_set, $account);
}

/**
 * Unassigns a user from any shortcut set they may have been assigned to.
 *
 * The user will go back to using whatever default set applies.
 *
 * @param $account
 *   A user account that will be removed from the shortcut set assignment.
 *
 * @return
 *   TRUE if the user was previously assigned to a shortcut set and has been
 *   successfully removed from it. FALSE if the user was already not assigned
 *   to any set.
 */
function shortcut_set_unassign_user($account) {
  return (bool) \Drupal::entityManager()
    ->getStorage('shortcut_set')
    ->unassignUser($account);
}

/**
 * Returns the current displayed shortcut set for the provided user account.
 *
 * @param $account
 *   (optional) The user account whose shortcuts will be returned. Defaults to
 *   the currently logged-in user.
 *
 * @return
 *   An object representing the shortcut set that should be displayed to the
 *   current user. If the user does not have an explicit shortcut set defined,
 *   the default set is returned.
 */
function shortcut_current_displayed_set($account = NULL) {
  $shortcut_sets = &drupal_static(__FUNCTION__, array());
  $user = \Drupal::currentUser();
  if (!isset($account)) {
    $account = $user;
  }
  // Try to return a shortcut set from the static cache.
  if (isset($shortcut_sets[$account->id()])) {
    return $shortcut_sets[$account->id()];
  }
  // If none was found, try to find a shortcut set that is explicitly assigned
  // to this user.
  $shortcut_set_name = \Drupal::entityManager()
    ->getStorage('shortcut_set')
    ->getAssignedToUser($account);
  if ($shortcut_set_name) {
    $shortcut_set = shortcut_set_load($shortcut_set_name);
  }
  // Otherwise, use the default set.
  else {
    $shortcut_set = shortcut_default_set($account);
  }

  $shortcut_sets[$account->id()] = $shortcut_set;
  return $shortcut_set;
}

/**
 * Returns the default shortcut set for a given user account.
 *
 * @param object $account
 *   (optional) The user account whose default shortcut set will be returned.
 *   If not provided, the function will return the currently logged-in user's
 *   default shortcut set.
 *
 * @return
 *   An object representing the default shortcut set.
 */
function shortcut_default_set($account = NULL) {
  $user = \Drupal::currentUser();
  if (!isset($account)) {
    $account = $user;
  }

  // Allow modules to return a default shortcut set name. Since we can only
  // have one, we allow the last module which returns a valid result to take
  // precedence. If no module returns a valid set, fall back on the site-wide
  // default, which is the lowest-numbered shortcut set.
  $suggestions = array_reverse(\Drupal::moduleHandler()->invokeAll('shortcut_default_set', array($account)));
  $suggestions[] = 'default';
  foreach ($suggestions as $name) {
    if ($shortcut_set = shortcut_set_load($name)) {
      break;
    }
  }

  return $shortcut_set;
}

/**
 * Check to see if a shortcut set with the given title already exists.
 *
 * @param $title
 *   Human-readable name of the shortcut set to check.
 *
 * @return
 *   TRUE if a shortcut set with that title exists; FALSE otherwise.
 */
function shortcut_set_title_exists($title) {
  $sets = entity_load_multiple('shortcut_set');
  foreach ($sets as $set) {
    if ($set->label == $title) {
      return TRUE;
    }
  }
  return FALSE;
}

/**
 * Determines if a path corresponds to a valid shortcut link.
 *
 * @param string $path
 *   The path to the link.
 *
 * @return bool
 *   TRUE if the shortcut link is valid, FALSE otherwise. Valid links are ones
 *   that correspond to actual paths on the site.
 *
 * @see menu_edit_item_validate()
 */
function shortcut_valid_link($path) {
  // Do not use URL aliases.
  $normal_path = \Drupal::service('path.alias_manager')->getPathByAlias($path);
  if ($path != $normal_path) {
    $path = $normal_path;
  }

  // An empty path is valid too and will be converted to <front>.
  return (!UrlHelper::isExternal($path) && (\Drupal::service('router.route_provider')->getRoutesByPattern('/' . $path)->count() > 0)) || empty($path) || $path == '<front>';
}

/**
 * Returns an array of shortcut links, suitable for rendering.
 *
 * @param \Drupal\shortcut\ShortcutSetInterface $shortcut_set
 *   (optional) An object representing the set whose links will be displayed.
 *   If not provided, the user's current set will be displayed.
 *
 * @return \Drupal\shortcut\ShortcutInterface[]
 *   An array of shortcut links, in the format returned by the menu system.
 */
function shortcut_renderable_links($shortcut_set = NULL) {
  $shortcut_links = array();

  if (!isset($shortcut_set)) {
    $shortcut_set = shortcut_current_displayed_set();
  }

  /** @var \Drupal\shortcut\ShortcutInterface[] $shortcuts  */
  $shortcuts = \Drupal::entityManager()->getStorage('shortcut')->loadByProperties(array('shortcut_set' => $shortcut_set->id()));
  $all_cache_tags = array();
  foreach ($shortcuts as $shortcut) {
    $links[] = array(
      'title' => $shortcut->label(),
      'href' => $shortcut->path->value,
    );
    $all_cache_tags[] = $shortcut->getCacheTag();
  }

  if (!empty($links)) {
    $shortcut_links = array(
      '#theme' => 'links__toolbar_shortcuts',
      '#links' => $links,
      '#attributes' => array(
        'class' => array('menu'),
      ),
      '#cache' => array(
        'tags' => NestedArray::mergeDeepArray($all_cache_tags),
      ),
    );
  }

  return $shortcut_links;
}

/**
 * Implements hook_preprocess_HOOK() for block templates.
 */
function shortcut_preprocess_block(&$variables) {
  if ($variables['configuration']['provider'] == 'shortcut') {
    $variables['attributes']['role'] = 'navigation';
  }
}

/**
 * Implements hook_preprocess_HOOK() for page templates.
 */
function shortcut_preprocess_page(&$variables) {
  // Only display the shortcut link if the user has the ability to edit
  // shortcuts and if the page's actual content is being shown (for example,
  // we do not want to display it on "access denied" or "page not found"
  // pages).
  // Load the router item corresponding to the current page.
  $request = \Drupal::request();
  $item = array();
  if ($route = $request->attributes->get(RouteObjectInterface::ROUTE_NAME)) {
    // @todo What should be done on a 404/403 page?
    $item['access'] = TRUE;
  }

  if (shortcut_set_edit_access() && !empty($item['access'])) {
    $link = current_path();
    if (!($url = Url::createFromPath($link))) {
      // Bail out early if we couldn't find a matching route.
      return;
    }

    $query = array(
      'link' => $link,
      'name' => $variables['title'],
    );
    $query += drupal_get_destination();

    $shortcut_set = shortcut_current_displayed_set();

    // Check if $link is already a shortcut and set $link_mode accordingly.
    $shortcuts = \Drupal::entityManager()->getStorage('shortcut')->loadByProperties(array('shortcut_set' => $shortcut_set->id()));
    foreach ($shortcuts as $shortcut) {
      if ($shortcut->getRouteName() == $url->getRouteName() && $shortcut->getRouteParams() == $url->getRouteParameters()) {
        $shortcut_id = $shortcut->id();
        break;
      }
    }
    $link_mode = isset($shortcut_id) ? "remove" : "add";

    if ($link_mode == "add") {
      $link_text = shortcut_set_switch_access() ? t('Add to %shortcut_set shortcuts', array('%shortcut_set' => $shortcut_set->label())) : t('Add to shortcuts');
      $route_name = 'shortcut.link_add_inline';
      $route_parameters = array('shortcut_set' => $shortcut_set->id());
    }
    else {
      $query['id'] = $shortcut_id;
      $link_text = shortcut_set_switch_access() ? t('Remove from %shortcut_set shortcuts', array('%shortcut_set' => $shortcut_set->label())) : t('Remove from shortcuts');
      $route_name = 'shortcut.link_delete';
      $route_parameters = array('shortcut' => $shortcut_id);
    }

    if (theme_get_setting('shortcut_module_link')) {
      $variables['title_suffix']['add_or_remove_shortcut'] = array(
        '#attached' => array(
          'library' => array(
            'shortcut/drupal.shortcut',
          ),
        ),
        '#prefix' => '<div class="add-or-remove-shortcuts ' . $link_mode . '-shortcut">',
        '#type' => 'link',
        '#title' => '<span class="icon"></span><span class="text">'. $link_text .'</span>',
        '#route_name' => $route_name,
        '#route_parameters' => $route_parameters,
        '#options' => array('query' => $query, 'html' => TRUE),
        '#suffix' => '</div>',
      );
    }
  }
}

/**
 * Implements hook_toolbar().
 */
function shortcut_toolbar() {
  $items = array();
  $links = shortcut_renderable_links();
  $shortcut_set = shortcut_current_displayed_set();
  $configure_link = NULL;
  if (shortcut_set_edit_access($shortcut_set)) {
    $configure_link = array(
      '#type' => 'link',
      '#title' => t('Edit shortcuts'),
      '#route_name' => 'shortcut.set_customize',
      '#route_parameters' => array('shortcut_set' => $shortcut_set->id()),
      '#options' => array('attributes' => array('class' => array('edit-shortcuts'))),
    );
  }
  if (!empty($links) || !empty($configure_link)) {
    $items['shortcuts'] = array(
      '#type' => 'toolbar_item',
      'tab' => array(
        '#type' => 'link',
        '#title' => t('Shortcuts'),
        '#href' => 'admin/config/user-interface/shortcut',
        '#attributes' => array(
          'title' => t('Shortcuts'),
          'class' => array('toolbar-icon', 'toolbar-icon-shortcut'),
        ),
      ),
      'tray' => array(
        '#heading' => t('User-defined shortcuts'),
        'shortcuts' => $links,
        'configure' => $configure_link,
      ),
      '#weight' => -10,
      '#attached' => array(
        'library' => array(
          'shortcut/drupal.shortcut',
        ),
      ),
    );
  }

  return $items;
}