Further Drupal 8.6.4 changes. Some core files were not committed before a commit...
[yaffs-website] / web / core / modules / views / views.module
1 <?php
2
3 /**
4  * @file
5  * Primarily Drupal hooks and global API functions to manipulate views.
6  */
7
8 use Drupal\Component\Render\MarkupInterface;
9 use Drupal\Component\Utility\Html;
10 use Drupal\Core\Database\Query\AlterableInterface;
11 use Drupal\Core\Entity\EntityInterface;
12 use Drupal\Core\Form\FormStateInterface;
13 use Drupal\Core\Routing\RouteMatchInterface;
14 use Drupal\Core\Url;
15 use Drupal\views\Plugin\Derivative\ViewsLocalTask;
16 use Drupal\views\ViewEntityInterface;
17 use Drupal\views\ViewExecutable;
18 use Drupal\views\Entity\View;
19 use Drupal\views\Render\ViewsRenderPipelineMarkup;
20 use Drupal\views\Views;
21
22 /**
23  * Implements hook_help().
24  */
25 function views_help($route_name, RouteMatchInterface $route_match) {
26   switch ($route_name) {
27     case 'help.page.views':
28       $output = '';
29       $output .= '<h3>' . t('About') . '</h3>';
30       $output .= '<p>' . t('The Views module provides a back end to fetch information from content, user accounts, taxonomy terms, and other entities from the database and present it to the user as a grid, HTML list, table, unformatted list, etc. The resulting displays are known generally as <em>views</em>.') . '</p>';
31       $output .= '<p>' . t('For more information, see the <a href=":views">online documentation for the Views module</a>.', [':views' => 'https://www.drupal.org/documentation/modules/views']) . '</p>';
32       $output .= '<p>' . t('In order to create and modify your own views using the administration and configuration user interface, you will need to enable either the Views UI module in core or a contributed module that provides a user interface for Views. See the <a href=":views-ui">Views UI module help page</a> for more information.', [':views-ui' => (\Drupal::moduleHandler()->moduleExists('views_ui')) ? \Drupal::url('help.page', ['name' => 'views_ui']) : '#']) . '</p>';
33       $output .= '<h3>' . t('Uses') . '</h3>';
34       $output .= '<dl>';
35       $output .= '<dt>' . t('Adding functionality to administrative pages') . '</dt>';
36       $output .= '<dd>' . t('The Views module adds functionality to some core administration pages. For example, <em>admin/content</em> uses Views to filter and sort content. With Views uninstalled, <em>admin/content</em> is more limited.') . '</dd>';
37       $output .= '<dt>' . t('Expanding Views functionality') . '</dt>';
38       $output .= '<dd>' . t('Contributed projects that support the Views module can be found in the <a href=":node">online documentation for Views-related contributed modules</a>.', [':node' => 'https://www.drupal.org/documentation/modules/views/add-ons']) . '</dd>';
39       $output .= '<dt>' . t('Improving table accessibility') . '</dt>';
40       $output .= '<dd>' . t('Views tables include semantic markup to improve accessibility. Data cells are automatically associated with header cells through id and header attributes. To improve the accessibility of your tables you can add descriptive elements within the Views table settings. The <em>caption</em> element can introduce context for a table, making it easier to understand. The <em>summary</em> element can provide an overview of how the data has been organized and how to navigate the table. Both the caption and summary are visible by default and also implemented according to HTML5 guidelines.') . '</dd>';
41       $output .= '<dt>' . t('Working with multilingual views') . '</dt>';
42       $output .= '<dd>' . t('If your site has multiple languages and translated entities, each result row in a view will contain one translation of each involved entity (a view can involve multiple entities if it uses relationships). You can use a filter to restrict your view to one language: without filtering, if an entity has three translations it will add three rows to the results; if you filter by language, at most one result will appear (it could be zero if that particular entity does not have a translation matching your language filter choice). If a view uses relationships, each entity in the relationship needs to be filtered separately. You can filter a view to a fixed language choice, such as English or Spanish, or to the language selected by the page the view is displayed on (the language that is selected for the page by the language detection settings either for Content or User interface).') . '</dd>';
43       $output .= '<dd>' . t('Because each result row contains a specific translation of each entity, field-level filters are also relative to these entity translations. For example, if your view has a filter that specifies that the entity title should contain a particular English word, you will presumably filter out all rows containing Chinese translations, since they will not contain the English word. If your view also has a second filter specifying that the title should contain a particular Chinese word, and if you are using "And" logic for filtering, you will presumably end up with no results in the view, because there are probably not any entity translations containing both the English and Chinese words in the title.') . '</dd>';
44       $output .= '<dd>' . t('Independent of filtering, you can choose the display language (the language used to display the entities and their fields) via a setting on the display. Your language choices are the same as the filter language choices, with an additional choice of "Content language of view row" and "Original language of content in view row", which means to display each entity in the result row using the language that entity has or in which it was originally created. In theory, this would give you the flexibility to filter to French translations, for instance, and then display the results in Spanish. The more usual choices would be to use the same language choices for the display language and each entity filter in the view, or to use the Row language setting for the display.') . '</dd>';
45       $output .= '</dl>';
46       return $output;
47   }
48 }
49
50 /**
51  * Implements hook_views_pre_render().
52  */
53 function views_views_pre_render($view) {
54   // If using AJAX, send identifying data about this view.
55   if ($view->ajaxEnabled() && empty($view->is_attachment) && empty($view->live_preview)) {
56     $view->element['#attached']['drupalSettings']['views'] = [
57       'ajax_path' => \Drupal::url('views.ajax'),
58       'ajaxViews' => [
59         'views_dom_id:' . $view->dom_id => [
60           'view_name' => $view->storage->id(),
61           'view_display_id' => $view->current_display,
62           'view_args' => Html::escape(implode('/', $view->args)),
63           'view_path' => Html::escape(Url::fromRoute('<current>')->toString()),
64           'view_base_path' => $view->getPath(),
65           'view_dom_id' => $view->dom_id,
66           // To fit multiple views on a page, the programmer may have
67           // overridden the display's pager_element.
68           'pager_element' => isset($view->pager) ? $view->pager->getPagerId() : 0,
69         ],
70       ],
71     ];
72     $view->element['#attached']['library'][] = 'views/views.ajax';
73   }
74
75   return $view;
76 }
77
78 /**
79  * Implements hook_theme().
80  *
81  * Register views theming functions and those that are defined via views plugin
82  * definitions.
83  */
84 function views_theme($existing, $type, $theme, $path) {
85   \Drupal::moduleHandler()->loadInclude('views', 'inc', 'views.theme');
86
87   // Some quasi clever array merging here.
88   $base = [
89     'file' => 'views.theme.inc',
90   ];
91
92   // Our extra version of pager from pager.inc
93   $hooks['views_mini_pager'] = $base + [
94     'variables' => ['tags' => [], 'quantity' => 9, 'element' => 0, 'parameters' => []],
95   ];
96
97   $variables = [
98     // For displays, we pass in a dummy array as the first parameter, since
99     // $view is an object but the core contextual_preprocess() function only
100     // attaches contextual links when the primary theme argument is an array.
101     'display' => [
102       'view_array' => [],
103       'view' => NULL,
104       'rows' => [],
105       'header' => [],
106       'footer' => [],
107       'empty' => [],
108       'exposed' => [],
109       'more' => [],
110       'feed_icons' => [],
111       'pager' => [],
112       'title' => '',
113       'attachment_before' => [],
114       'attachment_after' => [],
115     ],
116     'style' => ['view' => NULL, 'options' => NULL, 'rows' => NULL, 'title' => NULL],
117     'row' => ['view' => NULL, 'options' => NULL, 'row' => NULL, 'field_alias' => NULL],
118     'exposed_form' => ['view' => NULL, 'options' => NULL],
119     'pager' => [
120       'view' => NULL,
121       'options' => NULL,
122       'tags' => [],
123       'quantity' => 9,
124       'element' => 0,
125       'parameters' => [],
126     ],
127   ];
128
129   // Default view themes
130   $hooks['views_view_field'] = $base + [
131     'variables' => ['view' => NULL, 'field' => NULL, 'row' => NULL],
132   ];
133   $hooks['views_view_grouping'] = $base + [
134     'variables' => ['view' => NULL, 'grouping' => NULL, 'grouping_level' => NULL, 'rows' => NULL, 'title' => NULL],
135   ];
136
137   // Only display, pager, row, and style plugins can provide theme hooks.
138   $plugin_types = [
139     'display',
140     'pager',
141     'row',
142     'style',
143     'exposed_form',
144   ];
145   $plugins = [];
146   foreach ($plugin_types as $plugin_type) {
147     $plugins[$plugin_type] = Views::pluginManager($plugin_type)->getDefinitions();
148   }
149
150   $module_handler = \Drupal::moduleHandler();
151
152   // Register theme functions for all style plugins. It provides a basic auto
153   // implementation of theme functions or template files by using the plugin
154   // definitions (theme, theme_file, module, register_theme). Template files are
155   // assumed to be located in the templates folder.
156   foreach ($plugins as $type => $info) {
157     foreach ($info as $def) {
158       // Not all plugins have theme functions, and they can also explicitly
159       // prevent a theme function from being registered automatically.
160       if (!isset($def['theme']) || empty($def['register_theme'])) {
161         continue;
162       }
163       // For each theme registration, we have a base directory to check for the
164       // templates folder. This will be relative to the root of the given module
165       // folder, so we always need a module definition.
166       // @todo: watchdog or exception?
167       if (!isset($def['provider']) || !$module_handler->moduleExists($def['provider'])) {
168         continue;
169       }
170
171       $hooks[$def['theme']] = [
172         'variables' => $variables[$type],
173       ];
174
175       // We always use the module directory as base dir.
176       $module_dir = drupal_get_path('module', $def['provider']);
177       $hooks[$def['theme']]['path'] = $module_dir;
178
179       // For the views module we ensure views.theme.inc is included.
180       if ($def['provider'] == 'views') {
181         if (!isset($hooks[$def['theme']]['includes'])) {
182           $hooks[$def['theme']]['includes'] = [];
183         }
184         if (!in_array('views.theme.inc', $hooks[$def['theme']]['includes'])) {
185           $hooks[$def['theme']]['includes'][] = $module_dir . '/views.theme.inc';
186         }
187       }
188       // The theme_file definition is always relative to the modules directory.
189       elseif (!empty($def['theme_file'])) {
190         $hooks[$def['theme']]['file'] = $def['theme_file'];
191       }
192
193       // Whenever we have a theme file, we include it directly so we can
194       // auto-detect the theme function.
195       if (isset($def['theme_file'])) {
196         $include = \Drupal::root() . '/' . $module_dir . '/' . $def['theme_file'];
197         if (is_file($include)) {
198           require_once $include;
199         }
200       }
201
202       // If there is no theme function for the given theme definition, it must
203       // be a template file. By default this file is located in the /templates
204       // directory of the module's folder. If a module wants to define its own
205       // location it has to set register_theme of the plugin to FALSE and
206       // implement hook_theme() by itself.
207       if (!function_exists('theme_' . $def['theme'])) {
208         $hooks[$def['theme']]['path'] .= '/templates';
209         $hooks[$def['theme']]['template'] = Html::cleanCssIdentifier($def['theme']);
210       }
211       else {
212         $hooks[$def['theme']]['function'] = 'theme_' . $def['theme'];
213       }
214     }
215   }
216
217   $hooks['views_form_views_form'] = $base + [
218     'render element' => 'form',
219   ];
220
221   $hooks['views_exposed_form'] = $base + [
222     'render element' => 'form',
223   ];
224
225   return $hooks;
226 }
227
228 /**
229  * A theme preprocess function to automatically allow view-based node
230  * templates if called from a view.
231  *
232  * The 'modules/node.views.inc' file is a better place for this, but
233  * we haven't got a chance to load that file before Drupal builds the
234  * node portion of the theme registry.
235  */
236 function views_preprocess_node(&$variables) {
237   // The 'view' attribute of the node is added in
238   // \Drupal\views\Plugin\views\row\EntityRow::preRender().
239   if (!empty($variables['node']->view) && $variables['node']->view->storage->id()) {
240     $variables['view'] = $variables['node']->view;
241     // If a node is being rendered in a view, and the view does not have a path,
242     // prevent drupal from accidentally setting the $page variable:
243     if (!empty($variables['view']->current_display)
244         && $variables['page']
245         && $variables['view_mode'] == 'full'
246         && !$variables['view']->display_handler->hasPath()) {
247       $variables['page'] = FALSE;
248     }
249   }
250 }
251
252 /**
253  * Implements hook_theme_suggestions_HOOK_alter().
254  */
255 function views_theme_suggestions_node_alter(array &$suggestions, array $variables) {
256   $node = $variables['elements']['#node'];
257   if (!empty($node->view) && $node->view->storage->id()) {
258     $suggestions[] = 'node__view__' . $node->view->storage->id();
259     if (!empty($node->view->current_display)) {
260       $suggestions[] = 'node__view__' . $node->view->storage->id() . '__' . $node->view->current_display;
261     }
262   }
263 }
264
265 /**
266  * A theme preprocess function to automatically allow view-based node
267  * templates if called from a view.
268  */
269 function views_preprocess_comment(&$variables) {
270   // The view data is added to the comment in
271   // \Drupal\views\Plugin\views\row\EntityRow::preRender().
272   if (!empty($variables['comment']->view) && $variables['comment']->view->storage->id()) {
273     $variables['view'] = $variables['comment']->view;
274   }
275 }
276
277 /**
278  * Implements hook_theme_suggestions_HOOK_alter().
279  */
280 function views_theme_suggestions_comment_alter(array &$suggestions, array $variables) {
281   $comment = $variables['elements']['#comment'];
282   if (!empty($comment->view) && $comment->view->storage->id()) {
283     $suggestions[] = 'comment__view__' . $comment->view->storage->id();
284     if (!empty($comment->view->current_display)) {
285       $suggestions[] = 'comment__view__' . $comment->view->storage->id() . '__' . $comment->view->current_display;
286     }
287   }
288 }
289
290 /**
291  * Implements hook_theme_suggestions_HOOK_alter().
292  */
293 function views_theme_suggestions_container_alter(array &$suggestions, array $variables) {
294   if (!empty($variables['element']['#type']) && $variables['element']['#type'] == 'more_link' && !empty($variables['element']['#view']) && $variables['element']['#view'] instanceof ViewExecutable) {
295     $suggestions = array_merge($suggestions, $variables['element']['#view']->buildThemeFunctions('container__more_link'));
296   }
297 }
298
299 /**
300  * Adds contextual links associated with a view display to a renderable array.
301  *
302  * This function should be called when a view is being rendered in a particular
303  * location and you want to attach the appropriate contextual links (e.g.,
304  * links for editing the view) to it.
305  *
306  * The function operates by checking the view's display plugin to see if it has
307  * defined any contextual links that are intended to be displayed in the
308  * requested location; if so, it attaches them. The contextual links intended
309  * for a particular location are defined by the 'contextual links' and
310  * 'contextual_links_locations' properties in the plugin annotation; as a
311  * result, these hook implementations have full control over where and how
312  * contextual links are rendered for each display.
313  *
314  * In addition to attaching the contextual links to the passed-in array (via
315  * the standard #contextual_links property), this function also attaches
316  * additional information via the #views_contextual_links_info property. This
317  * stores an array whose keys are the names of each module that provided
318  * views-related contextual links (same as the keys of the #contextual_links
319  * array itself) and whose values are themselves arrays whose keys ('location',
320  * 'view_name', and 'view_display_id') store the location, name of the view,
321  * and display ID that were passed in to this function. This allows you to
322  * access information about the contextual links and how they were generated in
323  * a variety of contexts where you might be manipulating the renderable array
324  * later on (for example, alter hooks which run later during the same page
325  * request).
326  *
327  * @param $render_element
328  *   The renderable array to which contextual links will be added. This array
329  *   should be suitable for passing in to
330  *   \Drupal\Core\Render\RendererInterface::render() and will normally contain a
331  *   representation of the view display whose contextual links are being
332  *   requested.
333  * @param $location
334  *   The location in which the calling function intends to render the view and
335  *   its contextual links. The core system supports three options for this
336  *   parameter:
337  *   - 'block': Used when rendering a block which contains a view. This
338  *     retrieves any contextual links intended to be attached to the block
339  *     itself.
340  *   - 'page': Used when rendering the main content of a page which contains a
341  *     view. This retrieves any contextual links intended to be attached to the
342  *     page itself (for example, links which are displayed directly next to the
343  *     page title).
344  *   - 'view': Used when rendering the view itself, in any context. This
345  *     retrieves any contextual links intended to be attached directly to the
346  *     view.
347  *   If you are rendering a view and its contextual links in another location,
348  *   you can pass in a different value for this parameter. However, you will
349  *   also need to set 'contextual_links_locations' in your plugin annotation to
350  *   indicate which view displays support having their contextual links
351  *   rendered in the location you have defined.
352  * @param string $display_id
353  *   The ID of the display within $view whose contextual links will be added.
354  * @param array $view_element
355  *   The render array of the view. It should contain the following properties:
356  *     - #view_id: The ID of the view.
357  *     - #view_display_show_admin_links: A boolean whether the admin links
358  *       should be shown.
359  *     - #view_display_plugin_id: The plugin ID of the display.
360  *
361  * @see \Drupal\views\Plugin\Block\ViewsBlock::addContextualLinks()
362  * @see template_preprocess_views_view()
363  */
364 function views_add_contextual_links(&$render_element, $location, $display_id, array $view_element = NULL) {
365   if (!isset($view_element)) {
366     $view_element = $render_element;
367   }
368   $view_element['#cache_properties'] = ['view_id', 'view_display_show_admin_links', 'view_display_plugin_id'];
369   $view_id = $view_element['#view_id'];
370   $show_admin_links = $view_element['#view_display_show_admin_links'];
371   $display_plugin_id = $view_element['#view_display_plugin_id'];
372
373   // Do not do anything if the view is configured to hide its administrative
374   // links or if the Contextual Links module is not enabled.
375   if (\Drupal::moduleHandler()->moduleExists('contextual') && $show_admin_links) {
376     // Also do not do anything if the display plugin has not defined any
377     // contextual links that are intended to be displayed in the requested
378     // location.
379     $plugin = Views::pluginManager('display')->getDefinition($display_plugin_id);
380     // If contextual_links_locations are not set, provide a sane default. (To
381     // avoid displaying any contextual links at all, a display plugin can still
382     // set 'contextual_links_locations' to, e.g., {""}.)
383
384     if (!isset($plugin['contextual_links_locations'])) {
385       $plugin['contextual_links_locations'] = ['view'];
386     }
387     elseif ($plugin['contextual_links_locations'] == [] || $plugin['contextual_links_locations'] == ['']) {
388       $plugin['contextual_links_locations'] = [];
389     }
390     else {
391       $plugin += ['contextual_links_locations' => ['view']];
392     }
393
394     // On exposed_forms blocks contextual links should always be visible.
395     $plugin['contextual_links_locations'][] = 'exposed_filter';
396     $has_links = !empty($plugin['contextual links']) && !empty($plugin['contextual_links_locations']);
397     if ($has_links && in_array($location, $plugin['contextual_links_locations'])) {
398       foreach ($plugin['contextual links'] as $group => $link) {
399         $args = [];
400         $valid = TRUE;
401         if (!empty($link['route_parameters_names'])) {
402           $view_storage = \Drupal::entityManager()
403             ->getStorage('view')
404             ->load($view_id);
405           foreach ($link['route_parameters_names'] as $parameter_name => $property) {
406             // If the plugin is trying to create an invalid contextual link
407             // (for example, "path/to/{$view->storage->property}", where
408             // $view->storage->{property} does not exist), we cannot construct
409             // the link, so we skip it.
410             if (!property_exists($view_storage, $property)) {
411               $valid = FALSE;
412               break;
413             }
414             else {
415               $args[$parameter_name] = $view_storage->get($property);
416             }
417           }
418         }
419         // If the link was valid, attach information about it to the renderable
420         // array.
421         if ($valid) {
422           $render_element['#views_contextual_links'] = TRUE;
423           $render_element['#contextual_links'][$group] = [
424             'route_parameters' => $args,
425             'metadata' => [
426               'location' => $location,
427               'name' => $view_id,
428               'display_id' => $display_id,
429             ],
430           ];
431           // If we're setting contextual links on a page, for a page view, for a
432           // user that may use contextual links, attach Views' contextual links
433           // JavaScript.
434           $render_element['#cache']['contexts'][] = 'user.permissions';
435         }
436       }
437     }
438   }
439 }
440
441 /**
442  * Implements hook_ENTITY_TYPE_insert() for 'field_config'.
443  */
444 function views_field_config_insert(EntityInterface $field) {
445   Views::viewsData()->clear();
446 }
447
448 /**
449  * Implements hook_ENTITY_TYPE_update() for 'field_config'.
450  */
451 function views_field_config_update(EntityInterface $entity) {
452   Views::viewsData()->clear();
453 }
454
455 /**
456  * Implements hook_ENTITY_TYPE_delete() for 'field_config'.
457  */
458 function views_field_config_delete(EntityInterface $entity) {
459   Views::viewsData()->clear();
460 }
461
462 /**
463  * Implements hook_ENTITY_TYPE_insert().
464  */
465 function views_base_field_override_insert(EntityInterface $entity) {
466   Views::viewsData()->clear();
467 }
468
469 /**
470  * Implements hook_ENTITY_TYPE_update().
471  */
472 function views_base_field_override_update(EntityInterface $entity) {
473   Views::viewsData()->clear();
474 }
475
476 /**
477  * Implements hook_ENTITY_TYPE_delete().
478  */
479 function views_base_field_override_delete(EntityInterface $entity) {
480   Views::viewsData()->clear();
481 }
482
483 /**
484  * Invalidate the views cache, forcing a rebuild on the next grab of table data.
485  */
486 function views_invalidate_cache() {
487   // Set the menu as needed to be rebuilt.
488   \Drupal::service('router.builder')->setRebuildNeeded();
489
490   $module_handler = \Drupal::moduleHandler();
491
492   // Reset the RouteSubscriber from views.
493   \Drupal::getContainer()->get('views.route_subscriber')->reset();
494
495   // Invalidate the block cache to update views block derivatives.
496   if ($module_handler->moduleExists('block')) {
497     \Drupal::service('plugin.manager.block')->clearCachedDefinitions();
498   }
499
500   // Allow modules to respond to the Views cache being cleared.
501   $module_handler->invokeAll('views_invalidate_cache');
502 }
503
504 /**
505  * Set the current 'current view' that is being built/rendered so that it is
506  * easy for other modules or items in drupal_eval to identify
507  *
508  * @return \Drupal\views\ViewExecutable
509  */
510 function &views_set_current_view($view = NULL) {
511   static $cache = NULL;
512   if (isset($view)) {
513     $cache = $view;
514   }
515
516   return $cache;
517 }
518
519 /**
520  * Find out what, if any, current view is currently in use.
521  *
522  * Note that this returns a reference, so be careful! You can unintentionally
523  * modify the $view object.
524  *
525  * @return \Drupal\views\ViewExecutable
526  *   The current view object.
527  */
528 function &views_get_current_view() {
529   return views_set_current_view();
530 }
531
532 /**
533  * Implements hook_hook_info().
534  */
535 function views_hook_info() {
536   $hooks = [];
537
538   $hooks += array_fill_keys([
539     'views_data',
540     'views_data_alter',
541     'views_analyze',
542     'views_invalidate_cache',
543   ], ['group' => 'views']);
544
545   // Register a views_plugins alter hook for all plugin types.
546   foreach (ViewExecutable::getPluginTypes() as $type) {
547     $hooks['views_plugins_' . $type . '_alter'] = [
548       'group' => 'views',
549     ];
550   }
551
552   $hooks += array_fill_keys([
553     'views_query_substitutions',
554     'views_form_substitutions',
555     'views_pre_view',
556     'views_pre_build',
557     'views_post_build',
558     'views_pre_execute',
559     'views_post_execute',
560     'views_pre_render',
561     'views_post_render',
562     'views_query_alter',
563   ], ['group' => 'views_execution']);
564
565   $hooks['field_views_data'] = [
566     'group' => 'views',
567   ];
568   $hooks['field_views_data_alter'] = [
569     'group' => 'views',
570   ];
571
572   return $hooks;
573 }
574
575 /**
576  * Returns whether the view is enabled.
577  *
578  * @param \Drupal\views\Entity\View $view
579  *   The view object to check.
580  *
581  * @return bool
582  *   Returns TRUE if a view is enabled, FALSE otherwise.
583  */
584 function views_view_is_enabled(View $view) {
585   return $view->status();
586 }
587
588 /**
589  * Returns whether the view is disabled.
590  *
591  * @param \Drupal\views\Entity\View $view
592  *   The view object to check.
593  *
594  * @return bool
595  *   Returns TRUE if a view is disabled, FALSE otherwise.
596  */
597 function views_view_is_disabled(View $view) {
598   return !$view->status();
599 }
600
601 /**
602  * Enables and saves a view.
603  *
604  * @param \Drupal\views\Entity\View $view
605  *   The View object to disable.
606  */
607 function views_enable_view(View $view) {
608   $view->enable()->save();
609 }
610
611 /**
612  * Disables and saves a view.
613  *
614  * @param \Drupal\views\Entity\View $view
615  *   The View object to disable.
616  */
617 function views_disable_view(View $view) {
618   $view->disable()->save();
619 }
620
621 /**
622  * Replaces views substitution placeholders.
623  *
624  * @param array $element
625  *   An associative array containing the properties of the element.
626  *   Properties used: #substitutions, #children.
627  * @return array
628  *   The $element with prepared variables ready for #theme 'form'
629  *   in views_form_views_form.
630  */
631 function views_pre_render_views_form_views_form($element) {
632   // Placeholders and their substitutions (usually rendered form elements).
633   $search = [];
634   $replace = [];
635
636   // Add in substitutions provided by the form.
637   foreach ($element['#substitutions']['#value'] as $substitution) {
638     $field_name = $substitution['field_name'];
639     $row_id = $substitution['row_id'];
640
641     $search[] = $substitution['placeholder'];
642     $replace[] = isset($element[$field_name][$row_id]) ? \Drupal::service('renderer')->render($element[$field_name][$row_id]) : '';
643   }
644   // Add in substitutions from hook_views_form_substitutions().
645   $substitutions = \Drupal::moduleHandler()->invokeAll('views_form_substitutions');
646   foreach ($substitutions as $placeholder => $substitution) {
647     $search[] = Html::escape($placeholder);
648     // Ensure that any replacements made are safe to make.
649     if (!($substitution instanceof MarkupInterface)) {
650       $substitution = Html::escape($substitution);
651     }
652     $replace[] = $substitution;
653   }
654
655   // Apply substitutions to the rendered output.
656   $output = str_replace($search, $replace, \Drupal::service('renderer')->render($element['output']));
657   $element['output'] = ['#markup' => ViewsRenderPipelineMarkup::create($output)];
658
659   return $element;
660 }
661
662 /**
663  * Implements hook_form_alter() for the exposed form.
664  *
665  * Since the exposed form is a GET form, we don't want it to send a wide
666  * variety of information.
667  */
668 function views_form_views_exposed_form_alter(&$form, FormStateInterface $form_state) {
669   $form['form_build_id']['#access'] = FALSE;
670   $form['form_token']['#access'] = FALSE;
671   $form['form_id']['#access'] = FALSE;
672 }
673
674 /**
675  * Implements hook_query_TAG_alter().
676  *
677  * This is the hook_query_alter() for queries tagged by Views and is used to
678  * add in substitutions from hook_views_query_substitutions().
679  */
680 function views_query_views_alter(AlterableInterface $query) {
681   $substitutions = $query->getMetaData('views_substitutions');
682   $tables = &$query->getTables();
683   $where = &$query->conditions();
684
685   // Replaces substitutions in tables.
686   foreach ($tables as $table_name => $table_metadata) {
687     foreach ($table_metadata['arguments'] as $replacement_key => $value) {
688       if (!is_array($value)) {
689         if (isset($substitutions[$value])) {
690           $tables[$table_name]['arguments'][$replacement_key] = $substitutions[$value];
691         }
692       }
693       else {
694         foreach ($value as $sub_key => $sub_value) {
695           if (isset($substitutions[$sub_value])) {
696             $tables[$table_name]['arguments'][$replacement_key][$sub_key] = $substitutions[$sub_value];
697           }
698         }
699       }
700     }
701   }
702
703   // Replaces substitutions in filter criteria.
704   _views_query_tag_alter_condition($query, $where, $substitutions);
705 }
706
707 /**
708  * Replaces the substitutions recursive foreach condition.
709  */
710 function _views_query_tag_alter_condition(AlterableInterface $query, &$conditions, $substitutions) {
711   foreach ($conditions as $condition_id => &$condition) {
712     if (is_numeric($condition_id)) {
713       if (is_string($condition['field'])) {
714         $condition['field'] = str_replace(array_keys($substitutions), array_values($substitutions), $condition['field']);
715       }
716       elseif (is_object($condition['field'])) {
717         $sub_conditions = &$condition['field']->conditions();
718         _views_query_tag_alter_condition($query, $sub_conditions, $substitutions);
719       }
720       // $condition['value'] is a subquery so alter the subquery recursive.
721       // Therefore make sure to get the metadata of the main query.
722       if (is_object($condition['value'])) {
723         $subquery = $condition['value'];
724         $subquery->addMetaData('views_substitutions', $query->getMetaData('views_substitutions'));
725         views_query_views_alter($condition['value']);
726       }
727       elseif (isset($condition['value'])) {
728         // We can not use a simple str_replace() here because it always returns
729         // a string and we have to keep the type of the condition value intact.
730         if (is_array($condition['value'])) {
731           foreach ($condition['value'] as &$value) {
732             if (is_string($value)) {
733               $value = str_replace(array_keys($substitutions), array_values($substitutions), $value);
734             }
735           }
736         }
737         elseif (is_string($condition['value'])) {
738           $condition['value'] = str_replace(array_keys($substitutions), array_values($substitutions), $condition['value']);
739         }
740       }
741     }
742   }
743 }
744
745 /**
746  * Embed a view using a PHP snippet.
747  *
748  * This function is meant to be called from PHP snippets, should one wish to
749  * embed a view in a node or something. It's meant to provide the simplest
750  * solution and doesn't really offer a lot of options, but breaking the function
751  * apart is pretty easy, and this provides a worthwhile guide to doing so.
752  *
753  * Note that this function does NOT display the title of the view. If you want
754  * to do that, you will need to do what this function does manually, by
755  * loading the view, getting the preview and then getting $view->getTitle().
756  *
757  * @param $name
758  *   The name of the view to embed.
759  * @param $display_id
760  *   The display id to embed. If unsure, use 'default', as it will always be
761  *   valid. But things like 'page' or 'block' should work here.
762  * @param ...
763  *   Any additional parameters will be passed as arguments.
764  *
765  * @return array|null
766  *   A renderable array containing the view output or NULL if the display ID
767  *   of the view to be executed doesn't exist.
768  */
769 function views_embed_view($name, $display_id = 'default') {
770   $args = func_get_args();
771   // Remove $name and $display_id from the arguments.
772   unset($args[0], $args[1]);
773
774   $view = Views::getView($name);
775   if (!$view || !$view->access($display_id)) {
776     return;
777   }
778
779   return [
780     '#type' => 'view',
781     '#name' => $name,
782     '#display_id' => $display_id,
783     '#arguments' => $args,
784   ];
785 }
786
787 /**
788  * Get the result of a view.
789  *
790  * @param string $name
791  *   The name of the view to retrieve the data from.
792  * @param string $display_id
793  *   The display id. On the edit page for the view in question, you'll find
794  *   a list of displays at the left side of the control area. "Master"
795  *   will be at the top of that list. Hover your cursor over the name of the
796  *   display you want to use. A URL will appear in the status bar of your
797  *   browser. This is usually at the bottom of the window, in the chrome.
798  *   Everything after #views-tab- is the display ID, e.g. page_1.
799  * @param ...
800  *   Any additional parameters will be passed as arguments.
801  * @return array
802  *   An array containing an object for each view item.
803  */
804 function views_get_view_result($name, $display_id = NULL) {
805   $args = func_get_args();
806   // Remove $name and $display_id from the arguments.
807   unset($args[0], $args[1]);
808
809   $view = Views::getView($name);
810   if (is_object($view)) {
811     if (is_array($args)) {
812       $view->setArguments($args);
813     }
814     if (is_string($display_id)) {
815       $view->setDisplay($display_id);
816     }
817     else {
818       $view->initDisplay();
819     }
820     $view->preExecute();
821     $view->execute();
822     return $view->result;
823   }
824   else {
825     return [];
826   }
827 }
828
829 /**
830  * Validation callback for query tags.
831  */
832 function views_element_validate_tags($element, FormStateInterface $form_state) {
833   $values = array_map('trim', explode(',', $element['#value']));
834   foreach ($values as $value) {
835     if (preg_match("/[^a-z_]/", $value)) {
836       $form_state->setError($element, t('The query tags may only contain lower-case alphabetical characters and underscores.'));
837       return;
838     }
839   }
840 }
841
842 /**
843  * Implements hook_local_tasks_alter().
844  */
845 function views_local_tasks_alter(&$local_tasks) {
846   $container = \Drupal::getContainer();
847   $local_task = ViewsLocalTask::create($container, 'views_view');
848   $local_task->alterLocalTasks($local_tasks);
849 }
850
851 /**
852  * Implements hook_ENTITY_TYPE_delete().
853  */
854 function views_view_delete(EntityInterface $entity) {
855   // Rebuild the routes in case there is a routed display.
856   $executable = Views::executableFactory()->get($entity);
857   $executable->initDisplay();
858   foreach ($executable->displayHandlers as $display) {
859     if ($display->getRoutedDisplay()) {
860       \Drupal::service('router.builder')->setRebuildNeeded();
861       break;
862     }
863   }
864 }
865
866 /**
867  * Implements hook_view_presave().
868  *
869  * Provides a BC layer for modules providing old configurations.
870  */
871 function views_view_presave(ViewEntityInterface $view) {
872   $displays = $view->get('display');
873   $changed = FALSE;
874   foreach ($displays as $display_name => &$display) {
875     if (isset($display['display_options']['fields'])) {
876       foreach ($display['display_options']['fields'] as $field_name => &$field) {
877         if (isset($field['plugin_id']) && $field['plugin_id'] === 'entity_link') {
878           // Add any missing settings for entity_link.
879           if (!isset($field['output_url_as_text'])) {
880             $field['output_url_as_text'] = FALSE;
881             $changed = TRUE;
882           }
883           if (!isset($field['absolute'])) {
884             $field['absolute'] = FALSE;
885             $changed = TRUE;
886           }
887         }
888         elseif (isset($field['plugin_id']) && $field['plugin_id'] === 'node_path') {
889           // Convert the use of node_path to entity_link.
890           $field['plugin_id'] = 'entity_link';
891           $field['field'] = 'view_node';
892           $field['output_url_as_text'] = TRUE;
893           $changed = TRUE;
894         }
895       }
896     }
897   }
898   if ($changed) {
899     $view->set('display', $displays);
900   }
901 }