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