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