This repository has been archived on 2025-01-19. You can view files and clone it, but cannot push or open issues or pull requests.
drupalcampbristol/core/modules/toolbar/toolbar.module

347 lines
12 KiB
Plaintext

<?php
/**
* @file
* Administration toolbar for quick access to top level administration items.
*/
use Drupal\Core\Cache\Cache;
use Drupal\Core\Menu\MenuTreeParameters;
use Drupal\Core\Render\Element;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Template\Attribute;
use Drupal\Component\Datetime\DateTimePlus;
use Drupal\Component\Utility\Crypt;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\user\Entity\Role;
use Drupal\Core\Url;
/**
* Implements hook_help().
*/
function toolbar_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.toolbar':
$output = '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The Toolbar module provides a toolbar for site administrators, which displays tabs and trays provided by the Toolbar module itself and other modules. For more information, see the <a href="!toolbar_docs">online documentation for the Toolbar module</a>.', array('!toolbar_docs' => 'https://www.drupal.org/documentation/modules/toolbar')) . '</p>';
$output .= '<h4>' . t('Terminology') . '</h4>';
$output .= '<dl>';
$output .= '<dt>' . t('Tabs') . '</dt>';
$output .= '<dd>' . t('Tabs are buttons, displayed in a bar across the top of the screen. Some tabs execute an action (such as starting Edit mode), while other tabs toggle which tray is open.') . '</dd>';
$output .= '<dt>' . t('Trays') . '</dt>';
$output .= '<dd>' . t('Trays are usually lists of links, which can be hierarchical like a menu. If a tray has been toggled open, it is displayed either vertically or horizontally below the tab bar, depending on the browser width. Only one tray may be open at a time. If you click another tab, that tray will replace the tray being displayed. In wide browser widths, the user has the ability to toggle from vertical to horizontal, using a link at the bottom or right of the tray. Hierarchical menus only have open/close behavior in vertical mode; if you display a tray containing a hierarchical menu horizontally, only the top-level links will be available.') . '</dd>';
$output .= '</dl>';
return $output;
}
}
/**
* Implements hook_theme().
*/
function toolbar_theme($existing, $type, $theme, $path) {
$items['toolbar'] = array(
'render element' => 'element',
);
$items['menu__toolbar'] = array(
'base hook' => 'menu',
'variables' => array('items' => array(), 'attributes' => array()),
);
return $items;
}
/**
* Implements hook_page_top().
*
* Add admin toolbar to the top of the page automatically.
*/
function toolbar_page_top(array &$page_top) {
$page_top['toolbar'] = array(
'#type' => 'toolbar',
'#access' => \Drupal::currentUser()->hasPermission('access toolbar'),
'#cache' => [
'keys' => ['toolbar'],
'contexts' => ['user.permissions'],
],
);
}
/**
* Prepares variables for administration toolbar templates.
*
* Default template: toolbar.html.twig.
*
* @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.
*/
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();
foreach (Element::children($element) as $key) {
// 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'];
}
}
// Add the tab.
if (isset($element[$key]['tab'])) {
$attributes = array();
// Pass the wrapper attributes along.
if (array_key_exists('#wrapper_attributes', $element[$key])) {
$attributes = $element[$key]['#wrapper_attributes'];
}
$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.
foreach (Element::children($element[$key]) as $child_key) {
if (!in_array($child_key, array('tray', 'tab'))) {
$variables['remainder'][$key][$child_key] = $element[$key][$child_key];
}
}
}
}
/**
* Implements hook_toolbar().
*/
function toolbar_toolbar() {
// The 'Home' tab is a simple link, with no corresponding tray.
$items['home'] = array(
'#type' => 'toolbar_item',
'tab' => array(
'#type' => 'link',
'#title' => t('Back to site'),
'#url' => Url::fromRoute('<front>'),
'#attributes' => array(
'title' => t('Return to site content'),
'class' => array('toolbar-icon', 'toolbar-icon-escape-admin'),
'data-toolbar-escape-admin' => TRUE,
),
),
'#wrapper_attributes' => array(
'class' => array('hidden', 'home-toolbar-tab'),
),
'#attached' => array(
'library' => array(
'toolbar/toolbar.escapeAdmin',
),
),
'#weight' => -20,
);
// To conserve bandwidth, we only include the top-level links in the HTML.
// 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.
// @see toolbar_subtrees_jsonp()
$langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
$subtrees_attached['drupalSettings']['toolbar'] = [
'subtreesHash' => _toolbar_get_subtrees_hash($langcode),
'langcode' => $langcode,
];
// 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.
$items['administration'] = array(
'#type' => 'toolbar_item',
'tab' => array(
'#type' => 'link',
'#title' => t('Manage'),
'#url' => Url::fromRoute('system.admin'),
'#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' => '',
),
),
'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'),
),
),
),
'#weight' => -15,
);
return $items;
}
/**
* Renders the toolbar's administration tray.
*
* @param array $element
* A renderable array.
*
* @return array
* The updated renderable array.
*
* @see drupal_render()
*/
function toolbar_prerender_toolbar_administration_tray(array $element) {
$menu_tree = \Drupal::service('toolbar.menu_tree');
// Render the top-level administration menu links.
$parameters = new MenuTreeParameters();
$parameters->setRoot('system.admin')->excludeRoot()->setTopLevelOnly()->onlyEnabledLinks();
$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;
}
/**
* Adds toolbar-specific attributes to the menu link tree.
*
* @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
* The menu link tree to manipulate.
*
* @return \Drupal\Core\Menu\MenuLinkTreeElement[]
* The manipulated menu link tree.
*/
function toolbar_menu_navigation_links(array $tree) {
foreach ($tree as $element) {
if ($element->subtree) {
toolbar_menu_navigation_links($element->subtree);
}
// Make sure we have a path specific ID in place, so we can attach icons
// 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->getUri()), 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';
$element->options['attributes']['class'][] = 'toolbar-icon-' . strtolower(str_replace(array('.', ' ', '_'), array('-', '-', '-'), $definition['id']));
$element->options['attributes']['title'] = SafeMarkup::checkPlain($link->getDescription());
}
return $tree;
}
/**
* Returns the rendered subtree of each top-level toolbar link.
*/
function toolbar_get_rendered_subtrees() {
$menu_tree = \Drupal::service('toolbar.menu_tree');
$parameters = new MenuTreeParameters();
$parameters->setRoot('system.admin')->excludeRoot()->setMaxDepth(3)->onlyEnabledLinks();
$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);
$subtrees = array();
foreach ($tree as $element) {
/** @var \Drupal\Core\Menu\MenuLinkInterface $link */
$link = $element->link;
if ($element->subtree) {
$subtree = $menu_tree->build($element->subtree);
$output = \Drupal::service('renderer')->renderPlain($subtree);
}
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;
}
return $subtrees;
}
/**
* Returns the hash of the per-user rendered toolbar subtrees.
*
* @param string $langcode
* The langcode of the current request.
*
* @return string
* The hash of the admin_menu subtrees.
*/
function _toolbar_get_subtrees_hash($langcode) {
$uid = \Drupal::currentUser()->id();
$cid = _toolbar_get_user_cid($uid, $langcode);
if ($cache = \Drupal::cache('toolbar')->get($cid)) {
$hash = $cache->data;
}
else {
$subtrees = toolbar_get_rendered_subtrees();
$hash = Crypt::hashBase64(serialize($subtrees));
// 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.
$role_list_cache_tags = \Drupal::entityManager()->getDefinition('user_role')->getListCacheTags();
\Drupal::cache('toolbar')->set($cid, $hash, Cache::PERMANENT, Cache::mergeTags(array('user:' . $uid, 'locale', 'config:system.menu.admin'), $role_list_cache_tags));
}
return $hash;
}
/**
* Returns a cache ID from the user and language IDs.
*
* @param int $uid
* A user ID.
* @param string $langcode
* The langcode of the current request.
*
* @return string
* A unique cache ID for the user.
*/
function _toolbar_get_user_cid($uid, $langcode) {
return 'toolbar_' . $uid . ':' . $langcode;
}