views.module 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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\ViewEntityInterface;
  15. use Drupal\views\ViewExecutable;
  16. use Drupal\views\Entity\View;
  17. use Drupal\views\Render\ViewsRenderPipelineMarkup;
  18. use Drupal\views\Views;
  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')) ? \Drupal::url('help.page', ['name' => 'views_ui']) : '#']) . '</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' => \Drupal::url('views.ajax'),
  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(Url::fromRoute('<current>')->toString()),
  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 drupal_render() and will normally
  303. * contain a representation of the view display whose contextual links are
  304. * being requested.
  305. * @param $location
  306. * The location in which the calling function intends to render the view and
  307. * its contextual links. The core system supports three options for this
  308. * parameter:
  309. * - 'block': Used when rendering a block which contains a view. This
  310. * retrieves any contextual links intended to be attached to the block
  311. * itself.
  312. * - 'page': Used when rendering the main content of a page which contains a
  313. * view. This retrieves any contextual links intended to be attached to the
  314. * page itself (for example, links which are displayed directly next to the
  315. * page title).
  316. * - 'view': Used when rendering the view itself, in any context. This
  317. * retrieves any contextual links intended to be attached directly to the
  318. * view.
  319. * If you are rendering a view and its contextual links in another location,
  320. * you can pass in a different value for this parameter. However, you will
  321. * also need to set 'contextual_links_locations' in your plugin annotation to
  322. * indicate which view displays support having their contextual links
  323. * rendered in the location you have defined.
  324. * @param string $display_id
  325. * The ID of the display within $view whose contextual links will be added.
  326. * @param array $view_element
  327. * The render array of the view. It should contain the following properties:
  328. * - #view_id: The ID of the view.
  329. * - #view_display_show_admin_links: A boolean whether the admin links
  330. * should be shown.
  331. * - #view_display_plugin_id: The plugin ID of the display.
  332. *
  333. * @see \Drupal\views\Plugin\Block\ViewsBlock::addContextualLinks()
  334. * @see views_preprocess_page()
  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::entityManager()
  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. * @return array
  573. * The $element with prepared variables ready for #theme 'form'
  574. * in views_form_views_form.
  575. */
  576. function views_pre_render_views_form_views_form($element) {
  577. // Placeholders and their substitutions (usually rendered form elements).
  578. $search = [];
  579. $replace = [];
  580. // Add in substitutions provided by the form.
  581. foreach ($element['#substitutions']['#value'] as $substitution) {
  582. $field_name = $substitution['field_name'];
  583. $row_id = $substitution['row_id'];
  584. $search[] = $substitution['placeholder'];
  585. $replace[] = isset($element[$field_name][$row_id]) ? \Drupal::service('renderer')->render($element[$field_name][$row_id]) : '';
  586. }
  587. // Add in substitutions from hook_views_form_substitutions().
  588. $substitutions = \Drupal::moduleHandler()->invokeAll('views_form_substitutions');
  589. foreach ($substitutions as $placeholder => $substitution) {
  590. $search[] = Html::escape($placeholder);
  591. // Ensure that any replacements made are safe to make.
  592. if (!($substitution instanceof MarkupInterface)) {
  593. $substitution = Html::escape($substitution);
  594. }
  595. $replace[] = $substitution;
  596. }
  597. // Apply substitutions to the rendered output.
  598. $output = str_replace($search, $replace, \Drupal::service('renderer')->render($element['output']));
  599. $element['output'] = ['#markup' => ViewsRenderPipelineMarkup::create($output)];
  600. return $element;
  601. }
  602. /**
  603. * Implements hook_form_alter() for the exposed form.
  604. *
  605. * Since the exposed form is a GET form, we don't want it to send a wide
  606. * variety of information.
  607. */
  608. function views_form_views_exposed_form_alter(&$form, FormStateInterface $form_state) {
  609. $form['form_build_id']['#access'] = FALSE;
  610. $form['form_token']['#access'] = FALSE;
  611. $form['form_id']['#access'] = FALSE;
  612. }
  613. /**
  614. * Implements hook_query_TAG_alter().
  615. *
  616. * This is the hook_query_alter() for queries tagged by Views and is used to
  617. * add in substitutions from hook_views_query_substitutions().
  618. */
  619. function views_query_views_alter(AlterableInterface $query) {
  620. $substitutions = $query->getMetaData('views_substitutions');
  621. $tables = &$query->getTables();
  622. $where = &$query->conditions();
  623. // Replaces substitutions in tables.
  624. foreach ($tables as $table_name => $table_metadata) {
  625. foreach ($table_metadata['arguments'] as $replacement_key => $value) {
  626. if (!is_array($value)) {
  627. if (isset($substitutions[$value])) {
  628. $tables[$table_name]['arguments'][$replacement_key] = $substitutions[$value];
  629. }
  630. }
  631. else {
  632. foreach ($value as $sub_key => $sub_value) {
  633. if (isset($substitutions[$sub_value])) {
  634. $tables[$table_name]['arguments'][$replacement_key][$sub_key] = $substitutions[$sub_value];
  635. }
  636. }
  637. }
  638. }
  639. }
  640. // Replaces substitutions in filter criteria.
  641. _views_query_tag_alter_condition($query, $where, $substitutions);
  642. }
  643. /**
  644. * Replaces the substitutions recursive foreach condition.
  645. */
  646. function _views_query_tag_alter_condition(AlterableInterface $query, &$conditions, $substitutions) {
  647. foreach ($conditions as $condition_id => &$condition) {
  648. if (is_numeric($condition_id)) {
  649. if (is_string($condition['field'])) {
  650. $condition['field'] = str_replace(array_keys($substitutions), array_values($substitutions), $condition['field']);
  651. }
  652. elseif (is_object($condition['field'])) {
  653. $sub_conditions = &$condition['field']->conditions();
  654. _views_query_tag_alter_condition($query, $sub_conditions, $substitutions);
  655. }
  656. // $condition['value'] is a subquery so alter the subquery recursive.
  657. // Therefore make sure to get the metadata of the main query.
  658. if (is_object($condition['value'])) {
  659. $subquery = $condition['value'];
  660. $subquery->addMetaData('views_substitutions', $query->getMetaData('views_substitutions'));
  661. views_query_views_alter($condition['value']);
  662. }
  663. elseif (isset($condition['value'])) {
  664. // We can not use a simple str_replace() here because it always returns
  665. // a string and we have to keep the type of the condition value intact.
  666. if (is_array($condition['value'])) {
  667. foreach ($condition['value'] as &$value) {
  668. if (is_string($value)) {
  669. $value = str_replace(array_keys($substitutions), array_values($substitutions), $value);
  670. }
  671. }
  672. }
  673. elseif (is_string($condition['value'])) {
  674. $condition['value'] = str_replace(array_keys($substitutions), array_values($substitutions), $condition['value']);
  675. }
  676. }
  677. }
  678. }
  679. }
  680. /**
  681. * Embed a view using a PHP snippet.
  682. *
  683. * This function is meant to be called from PHP snippets, should one wish to
  684. * embed a view in a node or something. It's meant to provide the simplest
  685. * solution and doesn't really offer a lot of options, but breaking the function
  686. * apart is pretty easy, and this provides a worthwhile guide to doing so.
  687. *
  688. * Note that this function does NOT display the title of the view. If you want
  689. * to do that, you will need to do what this function does manually, by
  690. * loading the view, getting the preview and then getting $view->getTitle().
  691. *
  692. * @param $name
  693. * The name of the view to embed.
  694. * @param $display_id
  695. * The display id to embed. If unsure, use 'default', as it will always be
  696. * valid. But things like 'page' or 'block' should work here.
  697. * @param ...
  698. * Any additional parameters will be passed as arguments.
  699. *
  700. * @return array|null
  701. * A renderable array containing the view output or NULL if the display ID
  702. * of the view to be executed doesn't exist.
  703. */
  704. function views_embed_view($name, $display_id = 'default') {
  705. $args = func_get_args();
  706. // Remove $name and $display_id from the arguments.
  707. unset($args[0], $args[1]);
  708. $view = Views::getView($name);
  709. if (!$view || !$view->access($display_id)) {
  710. return;
  711. }
  712. return [
  713. '#type' => 'view',
  714. '#name' => $name,
  715. '#display_id' => $display_id,
  716. '#arguments' => $args,
  717. ];
  718. }
  719. /**
  720. * Get the result of a view.
  721. *
  722. * @param string $name
  723. * The name of the view to retrieve the data from.
  724. * @param string $display_id
  725. * The display id. On the edit page for the view in question, you'll find
  726. * a list of displays at the left side of the control area. "Master"
  727. * will be at the top of that list. Hover your cursor over the name of the
  728. * display you want to use. A URL will appear in the status bar of your
  729. * browser. This is usually at the bottom of the window, in the chrome.
  730. * Everything after #views-tab- is the display ID, e.g. page_1.
  731. * @param ...
  732. * Any additional parameters will be passed as arguments.
  733. * @return array
  734. * An array containing an object for each view item.
  735. */
  736. function views_get_view_result($name, $display_id = NULL) {
  737. $args = func_get_args();
  738. // Remove $name and $display_id from the arguments.
  739. unset($args[0], $args[1]);
  740. $view = Views::getView($name);
  741. if (is_object($view)) {
  742. if (is_array($args)) {
  743. $view->setArguments($args);
  744. }
  745. if (is_string($display_id)) {
  746. $view->setDisplay($display_id);
  747. }
  748. else {
  749. $view->initDisplay();
  750. }
  751. $view->preExecute();
  752. $view->execute();
  753. return $view->result;
  754. }
  755. else {
  756. return [];
  757. }
  758. }
  759. /**
  760. * Validation callback for query tags.
  761. */
  762. function views_element_validate_tags($element, FormStateInterface $form_state) {
  763. $values = array_map('trim', explode(',', $element['#value']));
  764. foreach ($values as $value) {
  765. if (preg_match("/[^a-z_]/", $value)) {
  766. $form_state->setError($element, t('The query tags may only contain lower-case alphabetical characters and underscores.'));
  767. return;
  768. }
  769. }
  770. }
  771. /**
  772. * Implements hook_local_tasks_alter().
  773. */
  774. function views_local_tasks_alter(&$local_tasks) {
  775. $container = \Drupal::getContainer();
  776. $local_task = ViewsLocalTask::create($container, 'views_view');
  777. $local_task->alterLocalTasks($local_tasks);
  778. }
  779. /**
  780. * Implements hook_ENTITY_TYPE_delete().
  781. */
  782. function views_view_delete(EntityInterface $entity) {
  783. // Rebuild the routes in case there is a routed display.
  784. $executable = Views::executableFactory()->get($entity);
  785. $executable->initDisplay();
  786. foreach ($executable->displayHandlers as $display) {
  787. if ($display->getRoutedDisplay()) {
  788. \Drupal::service('router.builder')->setRebuildNeeded();
  789. break;
  790. }
  791. }
  792. }
  793. /**
  794. * Implements hook_view_presave().
  795. *
  796. * Provides a BC layer for modules providing old configurations.
  797. */
  798. function views_view_presave(ViewEntityInterface $view) {
  799. $displays = $view->get('display');
  800. $changed = FALSE;
  801. foreach ($displays as $display_name => &$display) {
  802. if (isset($display['display_options']['fields'])) {
  803. foreach ($display['display_options']['fields'] as $field_name => &$field) {
  804. if (isset($field['plugin_id']) && $field['plugin_id'] === 'entity_link') {
  805. // Add any missing settings for entity_link.
  806. if (!isset($field['output_url_as_text'])) {
  807. $field['output_url_as_text'] = FALSE;
  808. $changed = TRUE;
  809. }
  810. if (!isset($field['absolute'])) {
  811. $field['absolute'] = FALSE;
  812. $changed = TRUE;
  813. }
  814. }
  815. elseif (isset($field['plugin_id']) && $field['plugin_id'] === 'node_path') {
  816. // Convert the use of node_path to entity_link.
  817. $field['plugin_id'] = 'entity_link';
  818. $field['field'] = 'view_node';
  819. $field['output_url_as_text'] = TRUE;
  820. $changed = TRUE;
  821. }
  822. }
  823. }
  824. }
  825. if ($changed) {
  826. $view->set('display', $displays);
  827. }
  828. }