views.module 34 KB

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