views.module 34 KB

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