contextual.module 8.14 KB
Newer Older
1 2 3 4 5 6 7
<?php

/**
 * @file
 * Adds contextual links to perform actions related to elements on a page.
 */

8
use Drupal\Component\Serialization\Json;
9
use Drupal\Component\Utility\UrlHelper;
10
use Drupal\Core\Language\LanguageInterface;
11
use Drupal\Core\Routing\RouteMatchInterface;
12

13 14 15 16
/**
 * Implements hook_toolbar().
 */
function contextual_toolbar() {
17 18 19 20 21 22 23 24
  $items = [];
  $items['contextual'] = [
    '#cache' => [
      'contexts' => [
        'user.permissions',
      ],
    ],
  ];
25

26
  if (!\Drupal::currentUser()->hasPermission('access contextual links')) {
27
    return $items;
28 29
  }

30
  $items['contextual'] += [
31
    '#type' => 'toolbar_item',
32
    'tab' => [
33 34 35
      '#type' => 'html_tag',
      '#tag' => 'button',
      '#value' => t('Edit'),
36 37
      '#attributes' => [
        'class' => ['toolbar-icon', 'toolbar-icon-edit'],
38
        'aria-pressed' => 'false',
39
        'type' => 'button',
40 41 42 43 44 45 46
      ],
    ],
    '#wrapper_attributes' => [
      'class' => ['hidden', 'contextual-toolbar-tab'],
    ],
    '#attached' => [
      'library' => [
47
        'contextual/drupal.contextual-toolbar',
48 49 50
      ],
    ],
  ];
51

52
  return $items;
53 54
}

55
/**
56
 * Implements hook_page_attachments().
57 58 59 60 61 62
 *
 * Adds the drupal.contextual-links library to the page for any user who has the
 * 'access contextual links' permission.
 *
 * @see contextual_preprocess()
 */
63
function contextual_page_attachments(array &$page) {
64
  if (!\Drupal::currentUser()->hasPermission('access contextual links')) {
65 66 67
    return;
  }

68
  $page['#attached']['library'][] = 'contextual/drupal.contextual-links';
69 70
}

71 72 73
/**
 * Implements hook_help().
 */
74
function contextual_help($route_name, RouteMatchInterface $route_match) {
75 76
  switch ($route_name) {
    case 'help.page.contextual':
77 78
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
79
      $output .= '<p>' . t('The Contextual links module gives users with the <em>Use contextual links</em> permission quick access to tasks associated with certain areas of pages on your site. For example, a menu displayed as a block has links to edit the menu and configure the block. For more information, see the <a href=":contextual">online documentation for the Contextual Links module</a>.', [':contextual' => 'https://www.drupal.org/documentation/modules/contextual']) . '</p>';
80 81 82
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Displaying contextual links') . '</dt>';
83 84 85
      $output .= '<dd>';
      $output .= t('Contextual links for an area on a page are displayed using a contextual links button. There are two ways to make the contextual links button visible:');
      $output .= '<ol>';
86 87 88
      $sample_picture = [
        '#theme' => 'image',
        '#uri' => 'core/misc/icons/bebebe/pencil.svg',
89
        '#alt' => t('contextual links button'),
90 91
      ];
      $sample_picture = \Drupal::service('renderer')->render($sample_picture);
92 93
      $output .= '<li>' . t('Hovering over the area of interest will temporarily make the contextual links button visible (which looks like a pencil in most themes, and is normally displayed in the upper right corner of the area). The icon typically looks like this: @picture', ['@picture' => $sample_picture]) . '</li>';
      $output .= '<li>' . t('If you have the <a href=":toolbar">Toolbar module</a> enabled, clicking the contextual links button in the toolbar (which looks like a pencil) will make all contextual links buttons on the page visible. Clicking this button again will toggle them to invisible.', [':toolbar' => (\Drupal::moduleHandler()->moduleExists('toolbar')) ? \Drupal::url('help.page', ['name' => 'toolbar']) : '#']) . '</li>';
94 95 96
      $output .= '</ol>';
      $output .= t('Once the contextual links button for the area of interest is visible, click the button to display the links.');
      $output .= '</dd>';
97 98 99 100 101
      $output .= '</dl>';
      return $output;
  }
}

102
/**
103
 * Implements hook_preprocess().
104
 *
105
 * @see contextual_pre_render_placeholder()
106
 * @see contextual_page_attachments()
107
 * @see \Drupal\contextual\ContextualController::render()
108
 */
109
function contextual_preprocess(&$variables, $hook, $info) {
110 111 112 113 114
  $variables['#cache']['contexts'][] = 'user.permissions';
  if (!\Drupal::currentUser()->hasPermission('access contextual links')) {
    return;
  }

115
  // Determine the primary theme function argument.
116 117
  if (!empty($info['variables'])) {
    $keys = array_keys($info['variables']);
118 119
    $key = $keys[0];
  }
120 121
  elseif (!empty($info['render element'])) {
    $key = $info['render element'];
122
  }
123
  if (!empty($key) && isset($variables[$key])) {
124 125 126 127
    $element = $variables[$key];
  }

  if (isset($element) && is_array($element) && !empty($element['#contextual_links'])) {
128
    // Mark this element as potentially having contextual links attached to it.
129
    $variables['attributes']['class'][] = 'contextual-region';
130 131 132

    // Renders a contextual links placeholder unconditionally, thus not breaking
    // the render cache. Although the empty placeholder is rendered for all
133 134 135
    // users, contextual_page_attachments() only adds the asset library for
    // users with the 'access contextual links' permission, thus preventing
    // unnecessary HTTP requests for users without that permission.
136
    $variables['title_suffix']['contextual_links'] = [
137 138
      '#type' => 'contextual_links_placeholder',
      '#id' => _contextual_links_to_id($element['#contextual_links']),
139
    ];
140 141 142
  }
}

143 144 145 146 147 148 149
/**
 * Implements hook_contextual_links_view_alter().
 *
 * @see \Drupal\contextual\Plugin\views\field\ContextualLinks::render()
 */
function contextual_contextual_links_view_alter(&$element, $items) {
  if (isset($element['#contextual_links']['contextual'])) {
150
    $encoded_links = $element['#contextual_links']['contextual']['metadata']['contextual-views-field-links'];
151
    $element['#links'] = Json::decode(rawurldecode($encoded_links));
152 153 154 155 156 157 158
  }
}

/**
 * Serializes #contextual_links property value array to a string.
 *
 * Examples:
159 160 161
 *  - node:node=1:langcode=en
 *  - views_ui_edit:view=frontpage:location=page&view_name=frontpage&view_display_id=page_1&langcode=en
 *  - menu:menu=tools:langcode=en|block:block=bartik.tools:langcode=en
162 163
 *
 * So, expressed in a pattern:
164
 *  <group>:<route parameters>:<metadata>
165
 *
166
 * The route parameters and options are encoded as query strings.
167 168 169 170 171 172 173 174 175
 *
 * @param array $contextual_links
 *   The $element['#contextual_links'] value for some render element.
 *
 * @return string
 *   A serialized representation of a #contextual_links property value array for
 *   use in a data- attribute.
 */
function _contextual_links_to_id($contextual_links) {
176
  $ids = [];
177
  $langcode = \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_URL)->getId();
178
  foreach ($contextual_links as $group => $args) {
179
    $route_parameters = UrlHelper::buildQuery($args['route_parameters']);
180 181 182 183 184 185
    $args += ['metadata' => []];
    // Add the current URL language to metadata so a different ID will be
    // computed when URLs vary by language. This allows to store different
    // language-aware contextual links on the client side.
    $args['metadata'] += ['langcode' => $langcode];
    $metadata = UrlHelper::buildQuery($args['metadata']);
186
    $ids[] = "{$group}:{$route_parameters}:{$metadata}";
187
  }
188
  return implode('|', $ids);
189 190 191 192 193
}

/**
 * Unserializes the result of _contextual_links_to_id().
 *
194 195 196 197
 * Note that $id is user input. Before calling this method the ID should be
 * checked against the token stored in the 'data-contextual-token' attribute
 * which is passed via the 'tokens' request parameter to
 * \Drupal\contextual\ContextualController::render().
198 199 200 201 202 203
 *
 * @param string $id
 *   A serialized representation of a #contextual_links property value array.
 *
 * @return array
 *   The value for a #contextual_links property.
204 205 206
 *
 * @see _contextual_links_to_id()
 * @see \Drupal\contextual\ContextualController::render()
207 208
 */
function _contextual_id_to_links($id) {
209
  $contextual_links = [];
210 211
  $contexts = explode('|', $id);
  foreach ($contexts as $context) {
212 213
    list($group, $route_parameters_raw, $metadata_raw) = explode(':', $context);
    parse_str($route_parameters_raw, $route_parameters);
214
    $metadata = [];
215
    parse_str($metadata_raw, $metadata);
216
    $contextual_links[$group] = [
217 218
      'route_parameters' => $route_parameters,
      'metadata' => $metadata,
219
    ];
220 221 222
  }
  return $contextual_links;
}