shortcut.module 15.7 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\NestedArray;
9
use Drupal\Component\Utility\UrlHelper;
10
use Drupal\Core\Routing\RouteMatchInterface;
11
use Drupal\Core\Routing\UrlMatcher;
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 online handbook entry for <a href="!shortcut">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('shortcut.set_admin'))) . '</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 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>';
31
      $output .= '<dt>' . t('Displaying shortcuts') . '</dt>';
32
      $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>';
33 34
      $output .= '</dl>';
      return $output;
35

36 37
    case 'shortcut.set_admin':
    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' => url("user/{$user->id()}/shortcuts"))) . '</p>';
42 43
        return $output;
      }
44 45
  }
}
46

47
/**
48
 * Implements hook_permission().
49 50 51 52 53 54 55
 */
function shortcut_permission() {
  return array(
    'administer shortcuts' => array(
      'title' => t('Administer shortcuts'),
    ),
    'customize shortcut links' => array(
56 57
      '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.'),
58 59
    ),
    'switch shortcut sets' => array(
60 61
      '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.'),
62
    ),
63 64 65
    'access shortcuts' => array(
      'title' => t('Use shortcuts'),
    ),
66 67 68 69 70 71
  );
}

/**
 * Access callback for editing a shortcut set.
 *
72
 * @param Drupal\shortcut\ShortcutSetInterface $shortcut_set
73 74 75
 *   (optional) The shortcut set to be edited. If not set, the current user's
 *   shortcut set will be used.
 *
76
 * @return bool
77 78 79
 *   TRUE if the current user has access to edit the shortcut set, FALSE
 *   otherwise.
 */
80
function shortcut_set_edit_access(ShortcutSetInterface $shortcut_set = NULL) {
81
  $account = \Drupal::currentUser();
82 83

  // Shortcut administrators can edit any set.
84
  if ($account->hasPermission('administer shortcuts')) {
85 86
    return TRUE;
  }
87 88 89 90 91 92
  // Access to shortcuts is required for non-administrators.
  if (!$account->hasPermission('access shortcuts')) {
    return FALSE;
  }
  // Sufficiently-privileged users can edit their currently displayed shortcut
  // set, but not other sets.
93
  if ($account->hasPermission('customize shortcut links')) {
94 95 96 97 98 99 100 101
    return !isset($shortcut_set) || $shortcut_set == shortcut_current_displayed_set();
  }
  return FALSE;
}

/**
 * Access callback for switching the shortcut set assigned to a user account.
 *
102
 * @param object $account
103
 *   (optional) The user account whose shortcuts will be switched. If not set,
104 105 106
 *   permissions will be checked for switching the logged-in user's own
 *   shortcut set.
 *
107
 * @return bool
108 109 110 111
 *   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) {
112
  $user = \Drupal::currentUser();
113

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

119 120 121 122 123
  if (!$user->hasPermission('access shortcuts')) {
    // The user has no permission to use shortcuts.
    return FALSE;
  }

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

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

  return FALSE;
136 137 138
}

/**
139
 * Assigns a user to a particular shortcut set.
140
 *
141
 * @param $shortcut_set Drupal\shortcut\Entity\Shortcut
142 143 144 145 146
 *   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) {
147
  \Drupal::entityManager()
148
    ->getStorage('shortcut_set')
149
    ->assignUser($shortcut_set, $account);
150 151 152
}

/**
153
 * Unassigns a user from any shortcut set they may have been assigned to.
154 155 156 157 158
 *
 * 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.
159
 *
160 161 162 163 164 165
 * @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) {
166
  return (bool) \Drupal::entityManager()
167
    ->getStorage('shortcut_set')
168
    ->unassignUser($account);
169 170 171 172 173 174 175
}

/**
 * Returns the current displayed shortcut set for the provided user account.
 *
 * @param $account
 *   (optional) The user account whose shortcuts will be returned. Defaults to
176 177
 *   the currently logged-in user.
 *
178 179 180 181 182 183 184
 * @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());
185
  $user = \Drupal::currentUser();
186 187 188 189
  if (!isset($account)) {
    $account = $user;
  }
  // Try to return a shortcut set from the static cache.
190 191
  if (isset($shortcut_sets[$account->id()])) {
    return $shortcut_sets[$account->id()];
192 193 194
  }
  // If none was found, try to find a shortcut set that is explicitly assigned
  // to this user.
195
  $shortcut_set_name = \Drupal::entityManager()
196
    ->getStorage('shortcut_set')
197
    ->getAssignedToUser($account);
198
  if ($shortcut_set_name) {
199
    $shortcut_set = ShortcutSet::load($shortcut_set_name);
200
  }
201
  // Otherwise, use the default set.
202
  else {
203 204
    $shortcut_set = shortcut_default_set($account);
  }
205

206
  $shortcut_sets[$account->id()] = $shortcut_set;
207 208 209 210 211 212
  return $shortcut_set;
}

/**
 * Returns the default shortcut set for a given user account.
 *
213 214 215 216 217
 * @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.
 *
218 219 220 221
 * @return
 *   An object representing the default shortcut set.
 */
function shortcut_default_set($account = NULL) {
222
  $user = \Drupal::currentUser();
223 224 225
  if (!isset($account)) {
    $account = $user;
  }
226

227 228 229
  // 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
230
  // default, which is the lowest-numbered shortcut set.
231
  $suggestions = array_reverse(\Drupal::moduleHandler()->invokeAll('shortcut_default_set', array($account)));
232
  $suggestions[] = 'default';
233
  foreach ($suggestions as $name) {
234
    if ($shortcut_set = ShortcutSet::load($name)) {
235 236 237
      break;
    }
  }
238

239 240 241
  return $shortcut_set;
}

242 243 244 245 246 247 248 249 250 251
/**
 * 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) {
252
  $sets = ShortcutSet::loadMultiple();
253
  foreach ($sets as $set) {
254 255 256 257 258
    if ($set->label == $title) {
      return TRUE;
    }
  }
  return FALSE;
259 260
}

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

274 275 276
  if (!isset($shortcut_set)) {
    $shortcut_set = shortcut_current_displayed_set();
  }
277

278
  /** @var \Drupal\shortcut\ShortcutInterface[] $shortcuts  */
279
  $shortcuts = \Drupal::entityManager()->getStorage('shortcut')->loadByProperties(array('shortcut_set' => $shortcut_set->id()));
280
  $all_cache_tags = array();
281
  foreach ($shortcuts as $shortcut) {
282
    $shortcut = \Drupal::entityManager()->getTranslationFromContext($shortcut);
283 284 285 286
    $links[] = array(
      'title' => $shortcut->label(),
      'href' => $shortcut->path->value,
    );
287
    $all_cache_tags[] = $shortcut->getCacheTag();
288 289 290 291 292 293 294 295 296
  }

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

  return $shortcut_links;
304 305
}

306
/**
307
 * Implements hook_preprocess_HOOK() for block templates.
308 309
 */
function shortcut_preprocess_block(&$variables) {
310
  if ($variables['configuration']['provider'] == 'shortcut') {
311
    $variables['attributes']['role'] = 'navigation';
312 313 314
  }
}

315
/**
316
 * Implements hook_preprocess_HOOK() for page templates.
317
 */
318
function shortcut_preprocess_page(&$variables) {
319 320 321 322
  // 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).
323
  $item = array();
324
  if (\Drupal::routeMatch()->getRouteObject()) {
325 326 327 328 329
    // @todo What should be done on a 404/403 page?
    $item['access'] = TRUE;
  }

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

336
    $query = array(
337 338
      'link' => $link,
      'name' => $variables['title'],
339 340 341 342
    );
    $query += drupal_get_destination();

    $shortcut_set = shortcut_current_displayed_set();
343 344

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

    if ($link_mode == "add") {
355
      $link_text = shortcut_set_switch_access() ? t('Add to %shortcut_set shortcuts', array('%shortcut_set' => $shortcut_set->label())) : t('Add to shortcuts');
356 357
      $route_name = 'shortcut.link_add_inline';
      $route_parameters = array('shortcut_set' => $shortcut_set->id());
358 359
    }
    else {
360
      $query['id'] = $shortcut_id;
361
      $link_text = shortcut_set_switch_access() ? t('Remove from %shortcut_set shortcuts', array('%shortcut_set' => $shortcut_set->label())) : t('Remove from shortcuts');
362
      $route_name = 'entity.shortcut.link_delete_inline';
363
      $route_parameters = array('shortcut' => $shortcut_id);
364 365
    }

366 367
    if (theme_get_setting('shortcut_module_link')) {
      $variables['title_suffix']['add_or_remove_shortcut'] = array(
368
        '#attached' => array(
369
          'library' => array(
370
            'shortcut/drupal.shortcut',
371 372
          ),
        ),
373 374
        '#prefix' => '<div class="add-or-remove-shortcuts ' . $link_mode . '-shortcut">',
        '#type' => 'link',
375
        '#title' => '<span class="icon"></span><span class="text">'. $link_text .'</span>',
376 377
        '#route_name' => $route_name,
        '#route_parameters' => $route_parameters,
378 379 380 381
        '#options' => array('query' => $query, 'html' => TRUE),
        '#suffix' => '</div>',
      );
    }
382
  }
383 384 385
}

/**
386
 * Implements hook_toolbar().
387
 */
388
function shortcut_toolbar() {
389 390
  $user = \Drupal::currentUser();

391
  $items = array();
392 393 394 395 396 397
  if ($user->hasPermission('access shortcuts')) {
    $links = shortcut_renderable_links();
    $shortcut_set = shortcut_current_displayed_set();
    $configure_link = NULL;
    if (shortcut_set_edit_access($shortcut_set)) {
      $configure_link = array(
398
        '#type' => 'link',
399
        '#title' => t('Edit shortcuts'),
400
        '#route_name' => 'entity.shortcut_set.customize_form',
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
        '#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'),
          ),
416
        ),
417 418 419 420
        'tray' => array(
          '#heading' => t('User-defined shortcuts'),
          'shortcuts' => $links,
          'configure' => $configure_link,
421
        ),
422 423 424 425 426 427 428 429
        '#weight' => -10,
        '#attached' => array(
          'library' => array(
            'shortcut/drupal.shortcut',
          ),
        ),
      );
    }
430 431
  }

432
  return $items;
433
}