toolbar.module 17.4 KB
Newer Older
1
2
3
4
5
6
7
<?php

/**
 * @file
 * Administration toolbar for quick access to top level administration items.
 */

8
use Drupal\Core\Cache\Cache;
9
use Drupal\Core\Menu\MenuTreeParameters;
10
use Drupal\Core\Render\Element;
11
use Drupal\Core\Routing\RouteMatchInterface;
12
use Drupal\Core\Template\Attribute;
13
use Drupal\Component\Datetime\DateTimePlus;
14
use Drupal\Component\Utility\Crypt;
15
use Drupal\Component\Utility\String;
16
17
use Drupal\user\RoleInterface;
use Drupal\user\UserInterface;
18

19
20
21
/**
 * Implements hook_help().
 */
22
function toolbar_help($route_name, RouteMatchInterface $route_match) {
23
24
  switch ($route_name) {
    case 'help.page.toolbar':
25
      $output = '<h3>' . t('About') . '</h3>';
26
      $output .= '<p>' . t('The Toolbar module displays links to top-level administration menu items and links from other modules at the top of the screen. For more information, see the online handbook entry for <a href="@toolbar">Toolbar module</a>.', array('@toolbar' => 'http://drupal.org/documentation/modules/toolbar')) . '</p>';
27
28
29
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Displaying administrative links') . '</dt>';
30
      $output .= '<dd>' . t('The Toolbar module displays a bar containing top-level administrative components across the top of the screen. Below that, the Toolbar module has a <em>drawer</em> section where it displays links provided by other modules, such as the core <a href="@shortcuts-help">Shortcut module</a>. The drawer can be hidden/shown by clicking on its corresponding tab.', array('@shortcuts-help' => url('admin/help/shortcut'))) . '</dd>';
31
32
33
34
35
      $output .= '</dl>';
      return $output;
  }
}

36
/**
37
 * Implements hook_permission().
38
 */
39
function toolbar_permission() {
40
41
  return array(
    'access toolbar' => array(
42
      'title' => t('Use the administration toolbar'),
43
44
45
46
47
    ),
  );
}

/**
48
 * Implements hook_theme().
49
50
51
 */
function toolbar_theme($existing, $type, $theme, $path) {
  $items['toolbar'] = array(
52
    'render element' => 'element',
53
    'template' => 'toolbar',
54
55
56
57
  );
  $items['toolbar_item'] = array(
    'render element' => 'element',
  );
58

59
60
61
  return $items;
}

62
63
64
65
66
67
68
69
70
71
72
/**
 * Implements hook_element_info().
 */
function toolbar_element_info() {
  $elements = array();

  $elements['toolbar'] = array(
    '#pre_render' => array('toolbar_pre_render'),
    '#theme' => 'toolbar',
    '#attached' => array(
      'library' => array(
73
        'toolbar/toolbar',
74
75
76
77
78
79
80
      ),
    ),
    // Metadata for the toolbar wrapping element.
    '#attributes' => array(
      // The id cannot be simply "toolbar" or it will clash with the simpletest
      // tests listing which produces a checkbox with attribute id="toolbar"
      'id' => 'toolbar-administration',
81
82
      'role' => 'group',
      'aria-label' => t('Site administration toolbar'),
83
84
85
86
87
88
    ),
    // Metadata for the administration bar.
    '#bar' => array(
      '#heading' => t('Toolbar items'),
      '#attributes' => array(
        'id' => 'toolbar-bar',
89
90
        'role' => 'navigation',
        'aria-label' => t('Toolbar items'),
91
92
93
94
95
      ),
    ),
  );

  // A toolbar item is wrapped in markup for common styling.  The 'tray'
96
  // property contains a renderable array.
97
98
99
100
101
102
103
104
105
106
107
108
  $elements['toolbar_item'] = array(
    '#pre_render' => array('toolbar_pre_render_item'),
    '#theme' => 'toolbar_item',
    'tab' => array(
      '#type' => 'link',
      '#title' => NULL,
      '#href' => '',
    ),
  );
  return $elements;
}

109
/**
110
 * Use Drupal's page cache for toolbar/subtrees/*, even for authenticated users.
111
 *
112
 * This gets invoked after full bootstrap, so must duplicate some of what's
113
 * done by \Drupal\Core\DrupalKernel::handlePageCache().
114
115
116
 *
 * @todo Replace this hack with something better integrated with DrupalKernel
 *   once Drupal's page caching itself is properly integrated.
117
 */
118
119
120
121
122
function _toolbar_initialize_page_cache() {
  $GLOBALS['conf']['system.performance']['cache']['page']['enabled'] = TRUE;
  drupal_page_is_cacheable(TRUE);

  // If we have a cache, serve it.
123
  // @see \Drupal\Core\DrupalKernel::handlePageCache()
124
  $request = \Drupal::request();
125
126
  $response = drupal_page_get_cache($request);
  if ($response) {
127
    $response->headers->set('X-Drupal-Cache', 'HIT');
128

129
    drupal_serve_page_from_cache($response, $request);
130

131
132
    $response->prepare($request);
    $response->send();
133
134
135
136
137
138
139
140
141
    // We are done.
    exit;
  }

  // The Expires HTTP header is the heart of the client-side HTTP caching. The
  // additional server-side page cache only takes effect when the client
  // accesses the callback URL again (e.g., after clearing the browser cache or
  // when force-reloading a Drupal page).
  $max_age = 3600 * 24 * 365;
142
  drupal_add_http_header('Expires', gmdate(DateTimePlus::RFC7231, REQUEST_TIME + $max_age));
143
  drupal_add_http_header('Cache-Control', 'private, max-age=' . $max_age);
144
145
}

146
/**
147
 * Implements hook_page_build().
148
 *
149
150
 * Add admin toolbar to the page_top region automatically.
 */
151
function toolbar_page_build(&$page) {
152
  $page['page_top']['toolbar'] = array(
153
    '#type' => 'toolbar',
154
    '#access' => \Drupal::currentUser()->hasPermission('access toolbar'),
155
156
157
158
  );
}

/**
159
 * Builds the Toolbar as a structured array ready for drupal_render().
160
161
162
 *
 * Since building the toolbar takes some time, it is done just prior to
 * rendering to ensure that it is built only if it will be displayed.
163
 *
164
165
166
167
168
169
 * @param array $element
 *  A renderable array.
 *
 * @return
 *  A renderable array.
 *
170
 * @see toolbar_page_build().
171
 */
172
173
174
175
function toolbar_pre_render($element) {

  // Get the configured breakpoints to switch from vertical to horizontal
  // toolbar presentation.
176
  $breakpoints = \Drupal::service('breakpoint.manager')->getBreakpointsByGroup('toolbar');
177
  if (!empty($breakpoints)) {
178
179
180
181
    $media_queries =  array();
    foreach ($breakpoints as $id => $breakpoint) {
      $media_queries[$id] = $breakpoint->getMediaQuery();
    }
182
183

    $element['#attached']['js'][] = array(
184
185
186
187
188
      'data' => array(
        'toolbar' => array(
          'breakpoints' => $media_queries,
        )
      ),
189
190
191
192
193
      'type' => 'setting',
    );
  }

  // Get toolbar items from all modules that implement hook_toolbar().
194
  $items = \Drupal::moduleHandler()->invokeAll('toolbar');
195
  // Allow for altering of hook_toolbar().
196
  \Drupal::moduleHandler()->alter('toolbar', $items);
197
  // Sort the children.
198
  uasort($items, array('\Drupal\Component\Utility\SortArray', 'sortByWeightProperty'));
199
200
201
202
203
204
205
206
207
208
209

  // Merge in the original toolbar values.
  $element = array_merge($element, $items);

  // Render the children.
  $element['#children'] = drupal_render_children($element);

  return $element;
}

/**
210
211
212
 * Prepares variables for administration toolbar templates.
 *
 * Default template: toolbar.html.twig.
213
214
215
216
217
218
 *
 * @param array $variables
 *   An associative array containing:
 *   - element: An associative array containing the properties and children of
 *     the tray. Properties used: #children, #attributes and #bar.
 */
219
220
221
222
223
224
225
226
227
228
229
230
231
function template_preprocess_toolbar(&$variables) {
  $element = $variables['element'];

  // Prepare the toolbar attributes.
  $variables['attributes'] = $element['#attributes'];
  $variables['toolbar_attributes'] = new Attribute($element['#bar']['#attributes']);
  $variables['toolbar_heading'] = $element['#bar']['#heading'];

  // Prepare the trays and tabs for each toolbar item as well as the remainder
  // variable that will hold any non-tray, non-tab elements.
  $variables['trays'] = array();
  $variables['tabs'] = array();
  $variables['remainder'] = array();
232
  foreach (Element::children($element) as $key) {
233
234
235
236
237
238
239
240
241
242
243
    // Add the tray.
    if (isset($element[$key]['tray'])) {
      $variables['trays'][$key] = array(
        'links' => $element[$key]['tray'],
        'attributes' => new Attribute($element[$key]['tray']['#wrapper_attributes']),
      );
      if (array_key_exists('#heading', $element[$key]['tray'])) {
        $variables['trays'][$key]['label'] = $element[$key]['tray']['#heading'];
      }
    }

244
    $attributes = array();
245
246
247
248
249
250
251
252
253
254
255
256
257
    // Pass the wrapper attributes along.
    if (array_key_exists('#wrapper_attributes', $element[$key])) {
      $attributes = $element[$key]['#wrapper_attributes'];
    }

    // Add the tab.
    $variables['tabs'][$key] = array(
      'link' => $element[$key]['tab'],
      'attributes' => new Attribute($attributes),
    );

    // Add other non-tray, non-tab child elements to the remainder variable for
    // later rendering.
258
    foreach (Element::children($element[$key]) as $child_key) {
259
260
261
      if (!in_array($child_key, array('tray', 'tab'))) {
        $variables['remainder'][$key][$child_key] = $element[$key][$child_key];
      }
262
263
    }
  }
264
265
266
}

/**
267
268
269
270
271
272
273
274
275
276
 * Provides markup for associating a tray trigger with a tray element.
 *
 * A tray is a responsive container that wraps renderable content. Trays present
 * content well on small and large screens alike.
 *
 * @param array $element
 *   A renderable array.
 *
 * @return
 *   A renderable array.
277
 */
278
function toolbar_pre_render_item($element) {
279
280
281
282
283
284
285
  // Assign each item a unique ID.
  $id = drupal_html_id('toolbar-item');

  // Provide attributes for a toolbar item.
  $attributes = array(
    'id' => $id,
  );
286
287
288

  // If tray content is present, markup the tray and its associated trigger.
  if (!empty($element['tray'])) {
289
290
291
    // Provide attributes necessary for trays.
    $attributes += array(
      'data-toolbar-tray' => $id . '-tray',
292
293
294
      'aria-owns' => $id,
      'role' => 'button',
      'aria-pressed' => 'false',
295
    );
296

297
298
299
300
301
302
303
    // Merge in module-provided attributes.
    $element['tab'] += array('#attributes' => array());
    $element['tab']['#attributes'] += $attributes;
    $element['tab']['#attributes']['class'][] = 'trigger';

    // Provide attributes for the tray theme wrapper.
    $attributes = array(
304
305
306
      'id' => $id . '-tray',
      'data-toolbar-tray' => $id . '-tray',
      'aria-owned-by' => $id,
307
308
309
310
311
312
    );
    // Merge in module-provided attributes.
    if (!isset($element['tray']['#wrapper_attributes'])) {
      $element['tray']['#wrapper_attributes'] = array();
    }
    $element['tray']['#wrapper_attributes'] += $attributes;
313
    $element['tray']['#wrapper_attributes']['class'][] = 'toolbar-tray';
314
315
  }

316
317
  $element['tab']['#attributes']['class'][] = 'toolbar-item';

318
319
320
  return $element;
}

321
/**
322
 * Implements hook_toolbar().
323
 */
324
325
326
function toolbar_toolbar() {
  // The 'Home' tab is a simple link, with no corresponding tray.
  $items['home'] = array(
327
    '#type' => 'toolbar_item',
328
    'tab' => array(
329
      '#type' => 'link',
330
      '#title' => t('Back to site'),
331
      '#href' => '<front>',
332
333
334
335
      '#attributes' => array(
        'title' => t('Return to site content'),
        'class' => array('toolbar-icon', 'toolbar-icon-escape-admin'),
        'data-toolbar-escape-admin' => TRUE,
336
      ),
337
    ),
338
339
340
341
342
    '#wrapper_attributes' => array(
      'class' => array('hidden'),
    ),
    '#attached' => array(
      'library' => array(
343
        'toolbar/toolbar.escapeAdmin',
344
345
      ),
    ),
346
    '#weight' => -20,
347
348
  );

349
  // To conserve bandwidth, we only include the top-level links in the HTML.
350
351
352
  // The subtrees are fetched through a JSONP script that is generated at the
  // toolbar_subtrees route. We provide the JavaScript requesting that JSONP
  // script here with the hash parameter that is needed for that route.
353
  // @see toolbar_subtrees_jsonp()
354
  $langcode = \Drupal::languageManager()->getCurrentLanguage()->id;
355
  $subtrees_attached['js'][] = array(
356
357
    'type' => 'setting',
    'data' => array('toolbar' => array(
358
359
      'subtreesHash' => _toolbar_get_subtrees_hash($langcode),
      'langcode' => $langcode,
360
361
    )),
  );
362

363
364
  // The administration element has a link that is themed to correspond to
  // a toolbar tray. The tray contains the full administrative menu of the site.
365
  $items['administration'] = array(
366
    '#type' => 'toolbar_item',
367
    'tab' => array(
368
      '#type' => 'link',
369
      '#title' => t('Manage'),
370
      '#href' => 'admin',
371
372
373
374
375
376
377
378
379
      '#attributes' => array(
        'title' => t('Admin menu'),
        'class' => array('toolbar-icon', 'toolbar-icon-menu'),
        // A data attribute that indicates to the client to defer loading of
        // the admin menu subtrees until this tab is activated. Admin menu
        // subtrees will not render to the DOM if this attribute is removed.
        // The value of the attribute is intentionally left blank. Only the
        // presence of the attribute is necessary.
        'data-drupal-subtrees' => '',
380
      ),
381
    ),
382
383
384
385
386
387
388
389
390
391
392
393
394
    'tray' => array(
      '#heading' => t('Administration menu'),
      '#attached' => $subtrees_attached,
      'toolbar_administration' => array(
        '#pre_render' => array(
          'toolbar_prerender_toolbar_administration_tray',
        ),
        '#type' => 'container',
        '#attributes' => array(
          'class' => array('toolbar-menu-administration'),
        ),
      ),
    ),
395
    '#weight' => -15,
396
397
398
399
400
  );

  return $items;
}

401
/**
402
 * Renders the toolbar's administration tray.
403
 *
404
405
406
407
408
409
410
 * @param array $element
 *   A renderable array.
 *
 * @return array
 *   The updated renderable array.
 *
 * @see drupal_render()
411
 */
412
413
414
415
function toolbar_prerender_toolbar_administration_tray(array $element) {
  $menu_tree = \Drupal::menuTree();
  // Render the top-level administration menu links.
  $parameters = new MenuTreeParameters();
416
  $parameters->setRoot('system.admin')->excludeRoot()->setTopLevelOnly()->onlyEnabledLinks();
417
418
419
420
421
422
423
424
425
  $tree = $menu_tree->load(NULL, $parameters);
  $manipulators = array(
    array('callable' => 'menu.default_tree_manipulators:checkAccess'),
    array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    array('callable' => 'toolbar_menu_navigation_links'),
  );
  $tree = $menu_tree->transform($tree, $manipulators);
  $element['administration_menu'] = $menu_tree->build($tree);
  return $element;
426
427
428
}

/**
429
 * Adds toolbar-specific attributes to the menu link tree.
430
 *
431
432
 * @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
 *   The menu link tree to manipulate.
433
 *
434
435
 * @return \Drupal\Core\Menu\MenuLinkTreeElement[]
 *   The manipulated menu link tree.
436
 */
437
438
439
440
function toolbar_menu_navigation_links(array $tree) {
  foreach ($tree as $element) {
    if ($element->subtree) {
      toolbar_menu_navigation_links($element->subtree);
441
    }
442

443
    // Make sure we have a path specific ID in place, so we can attach icons
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
    // and behaviors to the menu links.
    $link = $element->link;
    $url = $link->getUrlObject();
    if ($url->isExternal()) {
      // This is an unusual case, so just get a distinct, safe string.
      $id = substr(Crypt::hashBase64($url->getPath()), 0, 16);
    }
    else {
      $id = str_replace(array('.', '<', '>'), array('-', '', ''), $url->getRouteName());
    }

    // Get the non-localized title to make the icon class.
    $definition = $link->getPluginDefinition();

    $element->options['attributes']['id'] = 'toolbar-link-' . $id;
    $element->options['attributes']['class'][] = 'toolbar-icon';
460
    $element->options['attributes']['class'][] = 'toolbar-icon-' . strtolower(str_replace(array('.', ' ', '_'), array('-', '-', '-'), $definition['id']));
461
    $element->options['attributes']['title'] = String::checkPlain($link->getDescription());
462
  }
463
  return $tree;
464
}
465

466
467
468
469
/**
 * Returns the rendered subtree of each top-level toolbar link.
 */
function toolbar_get_rendered_subtrees() {
470
471
  $menu_tree = \Drupal::menuTree();
  $parameters = new MenuTreeParameters();
472
  $parameters->setRoot('system.admin')->excludeRoot()->setMaxDepth(3)->onlyEnabledLinks();
473
474
475
476
477
478
479
  $tree = $menu_tree->load(NULL, $parameters);
  $manipulators = array(
    array('callable' => 'menu.default_tree_manipulators:checkAccess'),
    array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    array('callable' => 'toolbar_menu_navigation_links'),
  );
  $tree = $menu_tree->transform($tree, $manipulators);
480
  $subtrees = array();
481
482
483
484
485
486
  foreach ($tree as $element) {
    /** @var \Drupal\Core\Menu\MenuLinkInterface $link */
    $link = $element->link;
    if ($element->subtree) {
      $subtree = $menu_tree->build($element->subtree);
      $output = drupal_render($subtree);
487
    }
488
489
490
491
492
493
494
495
    else {
      $output = '';
    }
    // Many routes have dots as route name, while some special ones like <front>
    // have <> characters in them.
    $id = str_replace(array('.', '<', '>'), array('-', '', '' ), $link->getUrlObject()->getRouteName());

    $subtrees[$id] = $output;
496
  }
497
  return $subtrees;
498
499
}

500
501
/**
 * Returns the hash of the per-user rendered toolbar subtrees.
502
 *
503
504
505
 * @param string $langcode
 *   The langcode of the current request.
 *
506
507
 * @return string
 *   The hash of the admin_menu subtrees.
508
 */
509
function _toolbar_get_subtrees_hash($langcode) {
510
  $uid = \Drupal::currentUser()->id();
511
  $cid = _toolbar_get_user_cid($uid, $langcode);
512
  if ($cache = \Drupal::cache('toolbar')->get($cid)) {
513
514
515
516
    $hash = $cache->data;
  }
  else {
    $subtrees = toolbar_get_rendered_subtrees();
517
    $hash = Crypt::hashBase64(serialize($subtrees));
518
519
520
521
    // Cache using a tag 'user' so that we can invalidate all user-specific
    // caches later, based on the user's ID regardless of language.
    // Clear the cache when the 'locale' tag is deleted. This ensures a fresh
    // subtrees rendering when string translations are made.
522
    \Drupal::cache('toolbar')->set($cid, $hash, Cache::PERMANENT, array('user' => array($uid), 'locale' => TRUE, 'menu' => 'admin', 'user_roles' => TRUE));
523
524
525
  }
  return $hash;
}
526
527
528
529
530
531

/**
 * Returns a cache ID from the user and language IDs.
 *
 * @param int $uid
 *   A user ID.
532
533
 * @param string $langcode
 *   The langcode of the current request.
534
535
536
537
 *
 * @return string
 *   A unique cache ID for the user.
 */
538
539
function _toolbar_get_user_cid($uid, $langcode) {
  return 'toolbar_' . $uid . ':' . $langcode;
540
541
}