shortcut.module 15.9 KB
Newer Older
1 2 3 4 5 6 7
<?php

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

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 18
/**
 * Implements hook_help().
 */
19
function shortcut_help($route_name, RouteMatchInterface $route_match) {
20 21
  switch ($route_name) {
    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>.', array('!shortcut' => 'http://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>.', array('!shortcuts' => \Drupal::url('entity.shortcut_set.collection'))) . '</dd>';
27 28
      $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>';
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.', array('!blocks' => \Drupal::url('block.admin_display'), '!toolbar-help' => \Drupal::url('help.page', array('name' => 'toolbar')))) . '</dd>';
33 34
      $output .= '</dl>';
      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.', array('@shortcut-link' => \Drupal::url('shortcut.set_switch', array('user' => $user->id())))) . '</p>';
42 43
        return $output;
      }
44 45
  }
}
46

47 48 49
/**
 * Access callback for editing a shortcut set.
 *
50
 * @param Drupal\shortcut\ShortcutSetInterface $shortcut_set
51 52 53
 *   (optional) The shortcut set to be edited. If not set, the current user's
 *   shortcut set will be used.
 *
54 55
 * @return \Drupal\Core\Access\AccessResultInterface
 *   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 67
  // set, but not other sets. They must also be able to access shortcuts.
  $may_edit_current_shortcut_set = $account->hasPermission('customize shortcut links') && (!isset($shortcut_set) || $shortcut_set == shortcut_current_displayed_set()) && $account->hasPermission('access shortcuts');
68
  return AccessResult::allowedIf($may_edit_current_shortcut_set)->cachePerPermissions();
69 70 71 72 73
}

/**
 * Access callback for switching the shortcut set assigned to a user account.
 *
74
 * @param object $account
75
 *   (optional) The user account whose shortcuts will be switched. If not set,
76 77 78
 *   permissions will be checked for switching the logged-in user's own
 *   shortcut set.
 *
79 80
 * @return \Drupal\Core\Access\AccessResultInterface
 *   The access result.
81 82
 */
function shortcut_set_switch_access($account = NULL) {
83
  $user = \Drupal::currentUser();
84

85
  if ($user->hasPermission('administer shortcuts')) {
86
    // Administrators can switch anyone's shortcut set.
87
    return AccessResult::allowed()->cachePerPermissions();
88 89
  }

90 91
  if (!$user->hasPermission('access shortcuts')) {
    // The user has no permission to use shortcuts.
92
    return AccessResult::neutral()->cachePerPermissions();
93 94
  }

95
  if (!$user->hasPermission('switch shortcut sets')) {
96
    // The user has no permission to switch anyone's shortcut set.
97
    return AccessResult::neutral()->cachePerPermissions();
98 99
  }

100 101 102
  // Users with the 'switch shortcut sets' permission can switch their own
  // shortcuts sets.
  if (!isset($account)) {
103
    return AccessResult::allowed()->cachePerPermissions();
104 105
  }
  else if ($user->id() == $account->id()) {
106
    return AccessResult::allowed()->cachePerPermissions()->cachePerUser();
107 108
  }

109
  // No opinion.
110
  return AccessResult::neutral()->cachePerPermissions();
111 112 113
}

/**
114
 * Assigns a user to a particular shortcut set.
115
 *
116
 * @param $shortcut_set Drupal\shortcut\Entity\Shortcut
117 118 119
 *   An object representing the shortcut set.
 * @param $account
 *   A user account that will be assigned to use the set.
120 121 122
 *
 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
 *   Use \Drupal::entityManager()->getStorage('shortcut_set')->assignUser().
123 124
 */
function shortcut_set_assign_user($shortcut_set, $account) {
125
  \Drupal::entityManager()
126
    ->getStorage('shortcut_set')
127
    ->assignUser($shortcut_set, $account);
128 129 130
}

/**
131
 * Unassigns a user from any shortcut set they may have been assigned to.
132 133 134 135 136
 *
 * 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.
137
 *
138 139 140 141
 * @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.
142 143 144
 *
 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
 *   Use \Drupal::entityManager()->getStorage('shortcut_set')->unassignUser().
145 146
 */
function shortcut_set_unassign_user($account) {
147
  return (bool) \Drupal::entityManager()
148
    ->getStorage('shortcut_set')
149
    ->unassignUser($account);
150 151 152 153 154 155 156
}

/**
 * Returns the current displayed shortcut set for the provided user account.
 *
 * @param $account
 *   (optional) The user account whose shortcuts will be returned. Defaults to
157 158
 *   the currently logged-in user.
 *
159 160 161 162 163 164 165
 * @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());
166
  $user = \Drupal::currentUser();
167 168 169 170
  if (!isset($account)) {
    $account = $user;
  }
  // Try to return a shortcut set from the static cache.
171 172
  if (isset($shortcut_sets[$account->id()])) {
    return $shortcut_sets[$account->id()];
173 174 175
  }
  // If none was found, try to find a shortcut set that is explicitly assigned
  // to this user.
176
  $shortcut_set_name = \Drupal::entityManager()
177
    ->getStorage('shortcut_set')
178
    ->getAssignedToUser($account);
179
  if ($shortcut_set_name) {
180
    $shortcut_set = ShortcutSet::load($shortcut_set_name);
181
  }
182
  // Otherwise, use the default set.
183
  else {
184 185
    $shortcut_set = shortcut_default_set($account);
  }
186

187
  $shortcut_sets[$account->id()] = $shortcut_set;
188 189 190 191 192 193
  return $shortcut_set;
}

/**
 * Returns the default shortcut set for a given user account.
 *
194 195 196 197 198
 * @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.
 *
199 200 201 202
 * @return
 *   An object representing the default shortcut set.
 */
function shortcut_default_set($account = NULL) {
203
  $user = \Drupal::currentUser();
204 205 206
  if (!isset($account)) {
    $account = $user;
  }
207

208 209 210
  // 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
211
  // default, which is the lowest-numbered shortcut set.
212
  $suggestions = array_reverse(\Drupal::moduleHandler()->invokeAll('shortcut_default_set', array($account)));
213
  $suggestions[] = 'default';
214
  foreach ($suggestions as $name) {
215
    if ($shortcut_set = ShortcutSet::load($name)) {
216 217 218
      break;
    }
  }
219

220 221 222
  return $shortcut_set;
}

223 224 225 226 227 228 229 230
/**
 * 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.
231 232
 *
 * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
233 234
 */
function shortcut_set_title_exists($title) {
235
  $sets = ShortcutSet::loadMultiple();
236
  foreach ($sets as $set) {
237
    if ($set->label() == $title) {
238 239 240 241
      return TRUE;
    }
  }
  return FALSE;
242 243
}

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

257 258 259
  if (!isset($shortcut_set)) {
    $shortcut_set = shortcut_current_displayed_set();
  }
260

261
  $cache_tags = array();
262
  foreach ($shortcut_set->getShortcuts() as $shortcut) {
263
    $shortcut = \Drupal::entityManager()->getTranslationFromContext($shortcut);
264 265 266 267 268 269 270 271 272
    $url = $shortcut->getUrl();
    if ($url->access()) {
      $links[$shortcut->id()] = array(
        'type' => 'link',
        'title' => $shortcut->label(),
        'url' => $shortcut->getUrl(),
      );
      $cache_tags = Cache::mergeTags($cache_tags, $shortcut->getCacheTags());
    }
273 274 275 276 277 278 279 280 281
  }

  if (!empty($links)) {
    $shortcut_links = array(
      '#theme' => 'links__toolbar_shortcuts',
      '#links' => $links,
      '#attributes' => array(
        'class' => array('menu'),
      ),
282
      '#cache' => array(
283
        'tags' => $cache_tags,
284
      ),
285 286 287 288
    );
  }

  return $shortcut_links;
289 290
}

291
/**
292
 * Implements hook_preprocess_HOOK() for block templates.
293 294
 */
function shortcut_preprocess_block(&$variables) {
295
  if ($variables['configuration']['provider'] == 'shortcut') {
296
    $variables['attributes']['role'] = 'navigation';
297 298 299
  }
}

300
/**
301
 * Implements hook_preprocess_HOOK() for page templates.
302
 */
303
function shortcut_preprocess_page(&$variables) {
304 305 306 307
  // 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).
308
  if (shortcut_set_edit_access()->isAllowed() && !\Drupal::request()->attributes->has('exception')) {
309
    $link = Url::fromRouteMatch(\Drupal::routeMatch())->getInternalPath();
310
    $route_match = \Drupal::routeMatch();
311

312
    $query = array(
313 314
      'link' => $link,
      'name' => $variables['title'],
315
    );
316
    $query += \Drupal::destination()->getAsArray();
317 318

    $shortcut_set = shortcut_current_displayed_set();
319 320

    // Check if $link is already a shortcut and set $link_mode accordingly.
321
    $shortcuts = \Drupal::entityManager()->getStorage('shortcut')->loadByProperties(array('shortcut_set' => $shortcut_set->id()));
322
    /** @var \Drupal\shortcut\ShortcutInterface $shortcut */
323
    foreach ($shortcuts as $shortcut) {
324
      if (($shortcut_url = $shortcut->getUrl()) && $shortcut_url->isRouted() && $shortcut_url->getRouteName() == $route_match->getRouteName()) {
325
        $shortcut_id = $shortcut->id();
326 327 328
        break;
      }
    }
329
    $link_mode = isset($shortcut_id) ? "remove" : "add";
330 331

    if ($link_mode == "add") {
332
      $link_text = shortcut_set_switch_access()->isAllowed() ? t('Add to %shortcut_set shortcuts', array('%shortcut_set' => $shortcut_set->label())) : t('Add to shortcuts');
333 334
      $route_name = 'shortcut.link_add_inline';
      $route_parameters = array('shortcut_set' => $shortcut_set->id());
335 336
    }
    else {
337
      $query['id'] = $shortcut_id;
338
      $link_text = shortcut_set_switch_access()->isAllowed() ? t('Remove from %shortcut_set shortcuts', array('%shortcut_set' => $shortcut_set->label())) : t('Remove from shortcuts');
339
      $route_name = 'entity.shortcut.link_delete_inline';
340
      $route_parameters = array('shortcut' => $shortcut_id);
341 342
    }

343
    if (theme_get_setting('third_party_settings.shortcut.module_link')) {
344
      $variables['title_suffix']['add_or_remove_shortcut'] = array(
345
        '#attached' => array(
346
          'library' => array(
347
            'shortcut/drupal.shortcut',
348 349
          ),
        ),
350 351
        '#prefix' => '<div class="add-or-remove-shortcuts ' . $link_mode . '-shortcut">',
        '#type' => 'link',
352
        '#title' => SafeMarkup::format('<span class="icon"></span><span class="text">@text</span>', array('@text' => $link_text)),
353
        '#url' => Url::fromRoute($route_name, $route_parameters),
354
        '#options' => array('query' => $query),
355 356 357
        '#suffix' => '</div>',
      );
    }
358
  }
359 360 361
}

/**
362
 * Implements hook_toolbar().
363
 */
364
function shortcut_toolbar() {
365 366
  $user = \Drupal::currentUser();

367
  $items = array();
368 369 370 371
  if ($user->hasPermission('access shortcuts')) {
    $links = shortcut_renderable_links();
    $shortcut_set = shortcut_current_displayed_set();
    $configure_link = NULL;
372
    if (shortcut_set_edit_access($shortcut_set)->isAllowed()) {
373
      $configure_link = array(
374
        '#type' => 'link',
375
        '#title' => t('Edit shortcuts'),
376
        '#url' => Url::fromRoute('entity.shortcut_set.customize_form', ['shortcut_set' => $shortcut_set->id()]),
377 378 379 380 381 382 383 384 385
        '#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'),
386
          '#url' => $shortcut_set->urlInfo('collection'),
387 388 389 390
          '#attributes' => array(
            'title' => t('Shortcuts'),
            'class' => array('toolbar-icon', 'toolbar-icon-shortcut'),
          ),
391
        ),
392 393 394 395
        'tray' => array(
          '#heading' => t('User-defined shortcuts'),
          'shortcuts' => $links,
          'configure' => $configure_link,
396
        ),
397 398 399 400 401 402 403 404
        '#weight' => -10,
        '#attached' => array(
          'library' => array(
            'shortcut/drupal.shortcut',
          ),
        ),
      );
    }
405 406
  }

407
  return $items;
408
}
409 410 411 412 413 414 415 416 417

/**
 * Implements hook_themes_installed().
 */
function shortcut_themes_installed($theme_list) {
  if (in_array('seven', $theme_list)) {
    // Theme settings are not configuration entities and cannot depend on modules
    // so to set a module-specific setting, we need to set it with logic.
    if (\Drupal::moduleHandler()->moduleExists('shortcut')) {
418
      \Drupal::configFactory()->getEditable('seven.settings')->set('third_party_settings.shortcut.module_link', TRUE)->save();
419 420 421
    }
  }
}