Drupal investigation

contextual.module 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. <?php
  2. /**
  3. * @file
  4. * Adds contextual links to perform actions related to elements on a page.
  5. */
  6. use Drupal\Component\Serialization\Json;
  7. use Drupal\Component\Utility\UrlHelper;
  8. use Drupal\Core\Language\LanguageInterface;
  9. use Drupal\Core\Routing\RouteMatchInterface;
  10. /**
  11. * Implements hook_toolbar().
  12. */
  13. function contextual_toolbar() {
  14. $items = [];
  15. $items['contextual'] = [
  16. '#cache' => [
  17. 'contexts' => [
  18. 'user.permissions',
  19. ],
  20. ],
  21. ];
  22. if (!\Drupal::currentUser()->hasPermission('access contextual links')) {
  23. return $items;
  24. }
  25. $items['contextual'] += [
  26. '#type' => 'toolbar_item',
  27. 'tab' => [
  28. '#type' => 'html_tag',
  29. '#tag' => 'button',
  30. '#value' => t('Edit'),
  31. '#attributes' => [
  32. 'class' => ['toolbar-icon', 'toolbar-icon-edit'],
  33. 'aria-pressed' => 'false',
  34. ],
  35. ],
  36. '#wrapper_attributes' => [
  37. 'class' => ['hidden', 'contextual-toolbar-tab'],
  38. ],
  39. '#attached' => [
  40. 'library' => [
  41. 'contextual/drupal.contextual-toolbar',
  42. ],
  43. ],
  44. ];
  45. return $items;
  46. }
  47. /**
  48. * Implements hook_page_attachments().
  49. *
  50. * Adds the drupal.contextual-links library to the page for any user who has the
  51. * 'access contextual links' permission.
  52. *
  53. * @see contextual_preprocess()
  54. */
  55. function contextual_page_attachments(array &$page) {
  56. if (!\Drupal::currentUser()->hasPermission('access contextual links')) {
  57. return;
  58. }
  59. $page['#attached']['library'][] = 'contextual/drupal.contextual-links';
  60. }
  61. /**
  62. * Implements hook_help().
  63. */
  64. function contextual_help($route_name, RouteMatchInterface $route_match) {
  65. switch ($route_name) {
  66. case 'help.page.contextual':
  67. $output = '';
  68. $output .= '<h3>' . t('About') . '</h3>';
  69. $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>';
  70. $output .= '<h3>' . t('Uses') . '</h3>';
  71. $output .= '<dl>';
  72. $output .= '<dt>' . t('Displaying contextual links') . '</dt>';
  73. $output .= '<dd>';
  74. $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:');
  75. $output .= '<ol>';
  76. $sample_picture = [
  77. '#theme' => 'image',
  78. '#uri' => 'core/misc/icons/bebebe/pencil.svg',
  79. '#alt' => t('contextual links button')
  80. ];
  81. $sample_picture = \Drupal::service('renderer')->render($sample_picture);
  82. $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>';
  83. $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>';
  84. $output .= '</ol>';
  85. $output .= t('Once the contextual links button for the area of interest is visible, click the button to display the links.');
  86. $output .= '</dd>';
  87. $output .= '</dl>';
  88. return $output;
  89. }
  90. }
  91. /**
  92. * Implements hook_preprocess().
  93. *
  94. * @see contextual_pre_render_placeholder()
  95. * @see contextual_page_attachments()
  96. * @see \Drupal\contextual\ContextualController::render()
  97. */
  98. function contextual_preprocess(&$variables, $hook, $info) {
  99. $variables['#cache']['contexts'][] = 'user.permissions';
  100. if (!\Drupal::currentUser()->hasPermission('access contextual links')) {
  101. return;
  102. }
  103. // Determine the primary theme function argument.
  104. if (!empty($info['variables'])) {
  105. $keys = array_keys($info['variables']);
  106. $key = $keys[0];
  107. }
  108. elseif (!empty($info['render element'])) {
  109. $key = $info['render element'];
  110. }
  111. if (!empty($key) && isset($variables[$key])) {
  112. $element = $variables[$key];
  113. }
  114. if (isset($element) && is_array($element) && !empty($element['#contextual_links'])) {
  115. // Mark this element as potentially having contextual links attached to it.
  116. $variables['attributes']['class'][] = 'contextual-region';
  117. // Renders a contextual links placeholder unconditionally, thus not breaking
  118. // the render cache. Although the empty placeholder is rendered for all
  119. // users, contextual_page_attachments() only adds the asset library for
  120. // users with the 'access contextual links' permission, thus preventing
  121. // unnecessary HTTP requests for users without that permission.
  122. $variables['title_suffix']['contextual_links'] = [
  123. '#type' => 'contextual_links_placeholder',
  124. '#id' => _contextual_links_to_id($element['#contextual_links']),
  125. ];
  126. }
  127. }
  128. /**
  129. * Implements hook_contextual_links_view_alter().
  130. *
  131. * @see \Drupal\contextual\Plugin\views\field\ContextualLinks::render()
  132. */
  133. function contextual_contextual_links_view_alter(&$element, $items) {
  134. if (isset($element['#contextual_links']['contextual'])) {
  135. $encoded_links = $element['#contextual_links']['contextual']['metadata']['contextual-views-field-links'];
  136. $element['#links'] = Json::decode(rawurldecode($encoded_links));
  137. }
  138. }
  139. /**
  140. * Serializes #contextual_links property value array to a string.
  141. *
  142. * Examples:
  143. * - node:node=1:langcode=en
  144. * - views_ui_edit:view=frontpage:location=page&view_name=frontpage&view_display_id=page_1&langcode=en
  145. * - menu:menu=tools:langcode=en|block:block=bartik.tools:langcode=en
  146. *
  147. * So, expressed in a pattern:
  148. * <group>:<route parameters>:<metadata>
  149. *
  150. * The route parameters and options are encoded as query strings.
  151. *
  152. * @param array $contextual_links
  153. * The $element['#contextual_links'] value for some render element.
  154. *
  155. * @return string
  156. * A serialized representation of a #contextual_links property value array for
  157. * use in a data- attribute.
  158. */
  159. function _contextual_links_to_id($contextual_links) {
  160. $ids = [];
  161. $langcode = \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_URL)->getId();
  162. foreach ($contextual_links as $group => $args) {
  163. $route_parameters = UrlHelper::buildQuery($args['route_parameters']);
  164. $args += ['metadata' => []];
  165. // Add the current URL language to metadata so a different ID will be
  166. // computed when URLs vary by language. This allows to store different
  167. // language-aware contextual links on the client side.
  168. $args['metadata'] += ['langcode' => $langcode];
  169. $metadata = UrlHelper::buildQuery($args['metadata']);
  170. $ids[] = "{$group}:{$route_parameters}:{$metadata}";
  171. }
  172. return implode('|', $ids);
  173. }
  174. /**
  175. * Unserializes the result of _contextual_links_to_id().
  176. *
  177. * @see _contextual_links_to_id
  178. *
  179. * @param string $id
  180. * A serialized representation of a #contextual_links property value array.
  181. *
  182. * @return array
  183. * The value for a #contextual_links property.
  184. */
  185. function _contextual_id_to_links($id) {
  186. $contextual_links = [];
  187. $contexts = explode('|', $id);
  188. foreach ($contexts as $context) {
  189. list($group, $route_parameters_raw, $metadata_raw) = explode(':', $context);
  190. parse_str($route_parameters_raw, $route_parameters);
  191. $metadata = [];
  192. parse_str($metadata_raw, $metadata);
  193. $contextual_links[$group] = [
  194. 'route_parameters' => $route_parameters,
  195. 'metadata' => $metadata,
  196. ];
  197. }
  198. return $contextual_links;
  199. }