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