"Fossies" - the Fresh Open Source Software Archive

Member "drupal-8.9.10/core/modules/contextual/contextual.module" (26 Nov 2020, 8374 Bytes) of package /linux/www/drupal-8.9.10.tar.gz:


As a special service "Fossies" has tried to format the requested text file into HTML format (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file.

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