taxonomy.module 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. <?php
  2. /**
  3. * @file
  4. * Enables the organization of content into categories.
  5. */
  6. use Drupal\Component\Utility\Tags;
  7. use Drupal\Component\Utility\Unicode;
  8. use Drupal\Core\Entity\EntityInterface;
  9. use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
  10. use Drupal\Core\Render\Element;
  11. use Drupal\Core\Routing\RouteMatchInterface;
  12. use Drupal\Core\Url;
  13. use Drupal\taxonomy\Entity\Term;
  14. use Drupal\taxonomy\Entity\Vocabulary;
  15. use Drupal\taxonomy\TermInterface;
  16. use Drupal\taxonomy\VocabularyInterface;
  17. /**
  18. * Denotes that no term in the vocabulary has a parent.
  19. *
  20. * @deprecated in Drupal 8.2.x and will be removed before 9.0.0. Use
  21. * \Drupal\taxonomy\VocabularyInterface::HIERARCHY_DISABLED instead.
  22. *
  23. * @see https://www.drupal.org/node/2807795
  24. */
  25. const TAXONOMY_HIERARCHY_DISABLED = 0;
  26. /**
  27. * Denotes that one or more terms in the vocabulary has a single parent.
  28. *
  29. * @deprecated in Drupal 8.2.x and will be removed before 9.0.0. Use
  30. * \Drupal\taxonomy\VocabularyInterface::HIERARCHY_SINGLE instead.
  31. *
  32. * @see https://www.drupal.org/node/2807795
  33. */
  34. const TAXONOMY_HIERARCHY_SINGLE = 1;
  35. /**
  36. * Denotes that one or more terms in the vocabulary have multiple parents.
  37. *
  38. * @deprecated in Drupal 8.2.x and will be removed before 9.0.0. Use
  39. * \Drupal\taxonomy\VocabularyInterface::HIERARCHY_MULTIPLE instead.
  40. *
  41. * @see https://www.drupal.org/node/2807795
  42. */
  43. const TAXONOMY_HIERARCHY_MULTIPLE = 2;
  44. /**
  45. * Implements hook_help().
  46. */
  47. function taxonomy_help($route_name, RouteMatchInterface $route_match) {
  48. switch ($route_name) {
  49. case 'help.page.taxonomy':
  50. $field_ui_url = \Drupal::moduleHandler()->moduleExists('field_ui') ? \Drupal::url('help.page', ['name' => 'field_ui']) : '#';
  51. $output = '';
  52. $output .= '<h3>' . t('About') . '</h3>';
  53. $output .= '<p>' . t('The Taxonomy module allows users who have permission to create and edit content to categorize (tag) content of that type. Users who have the <em>Administer vocabularies and terms</em> <a href=":permissions" title="Taxonomy module permissions">permission</a> can add <em>vocabularies</em> that contain a set of related <em>terms</em>. The terms in a vocabulary can either be pre-set by an administrator or built gradually as content is added and edited. Terms may be organized hierarchically if desired.', [':permissions' => \Drupal::url('user.admin_permissions', [], ['fragment' => 'module-taxonomy'])]) . '</p>';
  54. $output .= '<p>' . t('For more information, see the <a href=":taxonomy">online documentation for the Taxonomy module</a>.', [':taxonomy' => 'https://www.drupal.org/documentation/modules/taxonomy/']) . '</p>';
  55. $output .= '<h3>' . t('Uses') . '</h3>';
  56. $output .= '<dl>';
  57. $output .= '<dt>' . t('Managing vocabularies') . '</dt>';
  58. $output .= '<dd>' . t('Users who have the <em>Administer vocabularies and terms</em> permission can add and edit vocabularies from the <a href=":taxonomy_admin">Taxonomy administration page</a>. Vocabularies can be deleted from their <em>Edit vocabulary</em> page. Users with the <em>Taxonomy term: Administer fields</em> permission may add additional fields for terms in that vocabulary using the <a href=":field_ui">Field UI module</a>.', [':taxonomy_admin' => \Drupal::url('entity.taxonomy_vocabulary.collection'), ':field_ui' => $field_ui_url]) . '</dd>';
  59. $output .= '<dt>' . t('Managing terms') . '</dt>';
  60. $output .= '<dd>' . t('Users who have the <em>Administer vocabularies and terms</em> permission or the <em>Edit terms</em> permission for a particular vocabulary can add, edit, and organize the terms in a vocabulary from a vocabulary\'s term listing page, which can be accessed by going to the <a href=":taxonomy_admin">Taxonomy administration page</a> and clicking <em>List terms</em> in the <em>Operations</em> column. Users must have the <em>Administer vocabularies and terms</em> permission or the <em>Delete terms</em> permission for a particular vocabulary to delete terms.', [':taxonomy_admin' => \Drupal::url('entity.taxonomy_vocabulary.collection')]) . ' </dd>';
  61. $output .= '<dt>' . t('Classifying entity content') . '</dt>';
  62. $output .= '<dd>' . t('A user with the <em>Administer fields</em> permission for a certain entity type may add <em>Taxonomy term</em> reference fields to the entity type, which will allow entities to be classified using taxonomy terms. See the <a href=":entity_reference">Entity Reference help</a> for more information about reference fields. See the <a href=":field">Field module help</a> and the <a href=":field_ui">Field UI help</a> pages for general information on fields and how to create and manage them.', [':field_ui' => $field_ui_url, ':field' => \Drupal::url('help.page', ['name' => 'field']), ':entity_reference' => \Drupal::url('help.page', ['name' => 'entity_reference'])]) . '</dd>';
  63. $output .= '<dt>' . t('Adding new terms during content creation') . '</dt>';
  64. $output .= '<dd>' . t("Allowing users to add new terms gradually builds a vocabulary as content is added and edited. Users can add new terms if either of the two <em>Autocomplete</em> widgets is chosen for the Taxonomy term reference field in the <em>Manage form display</em> page for the field. You will also need to enable the <em>Create referenced entities if they don't already exist</em> option, and restrict the field to one vocabulary.") . '</dd>';
  65. $output .= '<dt>' . t('Configuring displays and form displays') . '</dt>';
  66. $output .= '<dd>' . t('See the <a href=":entity_reference">Entity Reference help</a> page for the field widgets and formatters that can be configured for any reference field on the <em>Manage display</em> and <em>Manage form display</em> pages. Taxonomy additionally provides an <em>RSS category</em> formatter that displays nothing when the entity item is displayed as HTML, but displays an RSS category instead of a list when the entity item is displayed in an RSS feed.', [':entity_reference' => \Drupal::url('help.page', ['name' => 'entity_reference'])]) . '</li>';
  67. $output .= '</ul>';
  68. $output .= '</dd>';
  69. $output .= '</dl>';
  70. return $output;
  71. case 'entity.taxonomy_vocabulary.collection':
  72. $output = '<p>' . t('Taxonomy is for categorizing content. Terms are grouped into vocabularies. For example, a vocabulary called "Fruit" would contain the terms "Apple" and "Banana".') . '</p>';
  73. return $output;
  74. case 'entity.taxonomy_vocabulary.overview_form':
  75. $vocabulary = $route_match->getParameter('taxonomy_vocabulary');
  76. if (\Drupal::currentUser()->hasPermission('administer taxonomy') || \Drupal::currentUser()->hasPermission('edit terms in ' . $vocabulary->id())) {
  77. switch ($vocabulary->getHierarchy()) {
  78. case VocabularyInterface::HIERARCHY_DISABLED:
  79. return '<p>' . t('You can reorganize the terms in %capital_name using their drag-and-drop handles, and group terms under a parent term by sliding them under and to the right of the parent.', ['%capital_name' => Unicode::ucfirst($vocabulary->label()), '%name' => $vocabulary->label()]) . '</p>';
  80. case VocabularyInterface::HIERARCHY_SINGLE:
  81. return '<p>' . t('%capital_name contains terms grouped under parent terms. You can reorganize the terms in %capital_name using their drag-and-drop handles.', ['%capital_name' => Unicode::ucfirst($vocabulary->label()), '%name' => $vocabulary->label()]) . '</p>';
  82. case VocabularyInterface::HIERARCHY_MULTIPLE:
  83. return '<p>' . t('%capital_name contains terms with multiple parents. Drag and drop of terms with multiple parents is not supported, but you can re-enable drag-and-drop support by editing each term to include only a single parent.', ['%capital_name' => Unicode::ucfirst($vocabulary->label())]) . '</p>';
  84. }
  85. }
  86. else {
  87. switch ($vocabulary->getHierarchy()) {
  88. case VocabularyInterface::HIERARCHY_DISABLED:
  89. return '<p>' . t('%capital_name contains the following terms.', ['%capital_name' => Unicode::ucfirst($vocabulary->label())]) . '</p>';
  90. case VocabularyInterface::HIERARCHY_SINGLE:
  91. return '<p>' . t('%capital_name contains terms grouped under parent terms', ['%capital_name' => Unicode::ucfirst($vocabulary->label())]) . '</p>';
  92. case VocabularyInterface::HIERARCHY_MULTIPLE:
  93. return '<p>' . t('%capital_name contains terms with multiple parents.', ['%capital_name' => Unicode::ucfirst($vocabulary->label())]) . '</p>';
  94. }
  95. }
  96. }
  97. }
  98. /**
  99. * Entity URI callback.
  100. */
  101. function taxonomy_term_uri($term) {
  102. return new Url('entity.taxonomy_term.canonical', [
  103. 'taxonomy_term' => $term->id(),
  104. ]);
  105. }
  106. /**
  107. * Implements hook_page_attachments_alter().
  108. */
  109. function taxonomy_page_attachments_alter(array &$page) {
  110. $route_match = \Drupal::routeMatch();
  111. if ($route_match->getRouteName() == 'entity.taxonomy_term.canonical' && ($term = $route_match->getParameter('taxonomy_term')) && $term instanceof TermInterface) {
  112. foreach ($term->uriRelationships() as $rel) {
  113. // Set the URI relationships, like canonical.
  114. $page['#attached']['html_head_link'][] = [
  115. [
  116. 'rel' => $rel,
  117. 'href' => $term->url($rel),
  118. ],
  119. TRUE,
  120. ];
  121. // Set the term path as the canonical URL to prevent duplicate content.
  122. if ($rel == 'canonical') {
  123. // Set the non-aliased canonical path as a default shortlink.
  124. $page['#attached']['html_head_link'][] = [
  125. [
  126. 'rel' => 'shortlink',
  127. 'href' => $term->url($rel, ['alias' => TRUE]),
  128. ],
  129. TRUE,
  130. ];
  131. }
  132. }
  133. }
  134. }
  135. /**
  136. * Implements hook_theme().
  137. */
  138. function taxonomy_theme() {
  139. return [
  140. 'taxonomy_term' => [
  141. 'render element' => 'elements',
  142. ],
  143. ];
  144. }
  145. /**
  146. * Checks and updates the hierarchy flag of a vocabulary.
  147. *
  148. * Checks the current parents of all terms in a vocabulary and updates the
  149. * vocabulary's hierarchy setting to the lowest possible level. If no term
  150. * has parent terms then the vocabulary will be given a hierarchy of
  151. * VocabularyInterface::HIERARCHY_DISABLED. If any term has a single parent then
  152. * the vocabulary will be given a hierarchy of
  153. * VocabularyInterface::HIERARCHY_SINGLE. If any term has multiple parents then
  154. * the vocabulary will be given a hierarchy of
  155. * VocabularyInterface::HIERARCHY_MULTIPLE.
  156. *
  157. * @param \Drupal\taxonomy\VocabularyInterface $vocabulary
  158. * A taxonomy vocabulary entity.
  159. * @param $changed_term
  160. * An array of the term structure that was updated.
  161. *
  162. * @return
  163. * An integer that represents the level of the vocabulary's hierarchy.
  164. */
  165. function taxonomy_check_vocabulary_hierarchy(VocabularyInterface $vocabulary, $changed_term) {
  166. $tree = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree($vocabulary->id());
  167. $hierarchy = VocabularyInterface::HIERARCHY_DISABLED;
  168. foreach ($tree as $term) {
  169. // Update the changed term with the new parent value before comparison.
  170. if ($term->tid == $changed_term['tid']) {
  171. $term = (object) $changed_term;
  172. $term->parents = $term->parent;
  173. }
  174. // Check this term's parent count.
  175. if (count($term->parents) > 1) {
  176. $hierarchy = VocabularyInterface::HIERARCHY_MULTIPLE;
  177. break;
  178. }
  179. elseif (count($term->parents) == 1 && !isset($term->parents[0])) {
  180. $hierarchy = VocabularyInterface::HIERARCHY_SINGLE;
  181. }
  182. }
  183. if ($hierarchy != $vocabulary->getHierarchy()) {
  184. $vocabulary->setHierarchy($hierarchy);
  185. $vocabulary->save();
  186. }
  187. return $hierarchy;
  188. }
  189. /**
  190. * Generates an array which displays a term detail page.
  191. *
  192. * @param \Drupal\taxonomy\Entity\Term $term
  193. * A taxonomy term object.
  194. * @param string $view_mode
  195. * View mode; e.g., 'full', 'teaser', etc.
  196. * @param string $langcode
  197. * (optional) A language code to use for rendering. Defaults to the global
  198. * content language of the current request.
  199. *
  200. * @return array
  201. * A $page element suitable for use by drupal_render().
  202. */
  203. function taxonomy_term_view(Term $term, $view_mode = 'full', $langcode = NULL) {
  204. return entity_view($term, $view_mode, $langcode);
  205. }
  206. /**
  207. * Constructs a drupal_render() style array from an array of loaded terms.
  208. *
  209. * @param array $terms
  210. * An array of taxonomy terms as returned by Term::loadMultiple().
  211. * @param string $view_mode
  212. * View mode; e.g., 'full', 'teaser', etc.
  213. * @param string $langcode
  214. * (optional) A language code to use for rendering. Defaults to the global
  215. * content language of the current request.
  216. *
  217. * @return array
  218. * An array in the format expected by drupal_render().
  219. */
  220. function taxonomy_term_view_multiple(array $terms, $view_mode = 'full', $langcode = NULL) {
  221. return entity_view_multiple($terms, $view_mode, $langcode);
  222. }
  223. /**
  224. * Implements hook_theme_suggestions_HOOK().
  225. */
  226. function taxonomy_theme_suggestions_taxonomy_term(array $variables) {
  227. $suggestions = [];
  228. /** @var \Drupal\taxonomy\TermInterface $term */
  229. $term = $variables['elements']['#taxonomy_term'];
  230. $suggestions[] = 'taxonomy_term__' . $term->bundle();
  231. $suggestions[] = 'taxonomy_term__' . $term->id();
  232. return $suggestions;
  233. }
  234. /**
  235. * Prepares variables for taxonomy term templates.
  236. *
  237. * Default template: taxonomy-term.html.twig.
  238. *
  239. * @param array $variables
  240. * An associative array containing:
  241. * - elements: An associative array containing the taxonomy term and any
  242. * fields attached to the term. Properties used:
  243. * - #taxonomy_term: A \Drupal\taxonomy\TermInterface object.
  244. * - #view_mode: The current view mode for this taxonomy term, e.g.
  245. * 'full' or 'teaser'.
  246. * - attributes: HTML attributes for the containing element.
  247. */
  248. function template_preprocess_taxonomy_term(&$variables) {
  249. $variables['view_mode'] = $variables['elements']['#view_mode'];
  250. $variables['term'] = $variables['elements']['#taxonomy_term'];
  251. /** @var \Drupal\taxonomy\TermInterface $term */
  252. $term = $variables['term'];
  253. $variables['url'] = $term->url();
  254. // We use name here because that is what appears in the UI.
  255. $variables['name'] = $variables['elements']['name'];
  256. unset($variables['elements']['name']);
  257. $variables['page'] = $variables['view_mode'] == 'full' && taxonomy_term_is_page($term);
  258. // Helpful $content variable for templates.
  259. $variables['content'] = [];
  260. foreach (Element::children($variables['elements']) as $key) {
  261. $variables['content'][$key] = $variables['elements'][$key];
  262. }
  263. }
  264. /**
  265. * Returns whether the current page is the page of the passed-in term.
  266. *
  267. * @param \Drupal\taxonomy\Entity\Term $term
  268. * A taxonomy term entity.
  269. */
  270. function taxonomy_term_is_page(Term $term) {
  271. if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $page_term_id = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
  272. return $page_term_id == $term->id();
  273. }
  274. return FALSE;
  275. }
  276. /**
  277. * Clear all static cache variables for terms.
  278. */
  279. function taxonomy_terms_static_reset() {
  280. \Drupal::entityManager()->getStorage('taxonomy_term')->resetCache();
  281. }
  282. /**
  283. * Clear all static cache variables for vocabularies.
  284. *
  285. * @param $ids
  286. * An array of ids to reset in the entity cache.
  287. */
  288. function taxonomy_vocabulary_static_reset(array $ids = NULL) {
  289. \Drupal::entityManager()->getStorage('taxonomy_vocabulary')->resetCache($ids);
  290. }
  291. /**
  292. * Get names for all taxonomy vocabularies.
  293. *
  294. * @return array
  295. * A list of existing vocabulary IDs.
  296. */
  297. function taxonomy_vocabulary_get_names() {
  298. $names = &drupal_static(__FUNCTION__);
  299. if (!isset($names)) {
  300. $names = [];
  301. $config_names = \Drupal::configFactory()->listAll('taxonomy.vocabulary.');
  302. foreach ($config_names as $config_name) {
  303. $id = substr($config_name, strlen('taxonomy.vocabulary.'));
  304. $names[$id] = $id;
  305. }
  306. }
  307. return $names;
  308. }
  309. /**
  310. * Try to map a string to an existing term, as for glossary use.
  311. *
  312. * Provides a case-insensitive and trimmed mapping, to maximize the
  313. * likelihood of a successful match.
  314. *
  315. * @param $name
  316. * Name of the term to search for.
  317. * @param $vocabulary
  318. * (optional) Vocabulary machine name to limit the search. Defaults to NULL.
  319. *
  320. * @return
  321. * An array of matching term objects.
  322. */
  323. function taxonomy_term_load_multiple_by_name($name, $vocabulary = NULL) {
  324. $values = ['name' => trim($name)];
  325. if (isset($vocabulary)) {
  326. $vocabularies = taxonomy_vocabulary_get_names();
  327. if (isset($vocabularies[$vocabulary])) {
  328. $values['vid'] = $vocabulary;
  329. }
  330. else {
  331. // Return an empty array when filtering by a non-existing vocabulary.
  332. return [];
  333. }
  334. }
  335. return entity_load_multiple_by_properties('taxonomy_term', $values);
  336. }
  337. /**
  338. * Load multiple taxonomy terms based on certain conditions.
  339. *
  340. * This function should be used whenever you need to load more than one term
  341. * from the database. Terms are loaded into memory and will not require
  342. * database access if loaded again during the same page request.
  343. *
  344. * @see entity_load_multiple()
  345. * @see \Drupal\Core\Entity\Query\EntityQueryInterface
  346. *
  347. * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
  348. * Use \Drupal\taxonomy\Entity\Term::loadMultiple().
  349. *
  350. * @param array $tids
  351. * (optional) An array of entity IDs. If omitted, all entities are loaded.
  352. *
  353. * @return array
  354. * An array of taxonomy term entities, indexed by tid. When no results are
  355. * found, an empty array is returned.
  356. */
  357. function taxonomy_term_load_multiple(array $tids = NULL) {
  358. return Term::loadMultiple($tids);
  359. }
  360. /**
  361. * Loads multiple taxonomy vocabularies based on certain conditions.
  362. *
  363. * This function should be used whenever you need to load more than one
  364. * vocabulary from the database. Terms are loaded into memory and will not
  365. * require database access if loaded again during the same page request.
  366. *
  367. * @see entity_load_multiple()
  368. *
  369. * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
  370. * Use \Drupal\taxonomy\Entity\Vocabulary::loadMultiple().
  371. *
  372. * @param array $vids
  373. * (optional) An array of entity IDs. If omitted, all entities are loaded.
  374. *
  375. * @return array
  376. * An array of vocabulary objects, indexed by vid.
  377. */
  378. function taxonomy_vocabulary_load_multiple(array $vids = NULL) {
  379. return Vocabulary::loadMultiple($vids);
  380. }
  381. /**
  382. * Return the taxonomy vocabulary entity matching a vocabulary ID.
  383. *
  384. * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
  385. * Use \Drupal\taxonomy\Entity\Vocabulary::load().
  386. *
  387. * @param int $vid
  388. * The vocabulary's ID.
  389. *
  390. * @return \Drupal\taxonomy\Entity\Vocabulary|null
  391. * The taxonomy vocabulary entity, if exists, NULL otherwise. Results are
  392. * statically cached.
  393. */
  394. function taxonomy_vocabulary_load($vid) {
  395. return Vocabulary::load($vid);
  396. }
  397. /**
  398. * Return the taxonomy term entity matching a term ID.
  399. *
  400. * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
  401. * Use \Drupal\taxonomy\Entity\Term::load().
  402. *
  403. * @param $tid
  404. * A term's ID
  405. *
  406. * @return \Drupal\taxonomy\Entity\Term|null
  407. * A taxonomy term entity, or NULL if the term was not found. Results are
  408. * statically cached.
  409. */
  410. function taxonomy_term_load($tid) {
  411. if (!is_numeric($tid)) {
  412. return NULL;
  413. }
  414. return Term::load($tid);
  415. }
  416. /**
  417. * Implodes a list of tags of a certain vocabulary into a string.
  418. *
  419. * @see \Drupal\Component\Utility\Tags::explode()
  420. */
  421. function taxonomy_implode_tags($tags, $vid = NULL) {
  422. $typed_tags = [];
  423. foreach ($tags as $tag) {
  424. // Extract terms belonging to the vocabulary in question.
  425. if (!isset($vid) || $tag->bundle() == $vid) {
  426. // Make sure we have a completed loaded taxonomy term.
  427. if ($tag instanceof EntityInterface && $label = $tag->label()) {
  428. // Commas and quotes in tag names are special cases, so encode 'em.
  429. $typed_tags[] = Tags::encode($label);
  430. }
  431. }
  432. }
  433. return implode(', ', $typed_tags);
  434. }
  435. /**
  436. * Title callback for term pages.
  437. *
  438. * @param \Drupal\taxonomy\Entity\Term $term
  439. * A taxonomy term entity.
  440. *
  441. * @return
  442. * The term name to be used as the page title.
  443. */
  444. function taxonomy_term_title(Term $term) {
  445. return $term->getName();
  446. }
  447. /**
  448. * @defgroup taxonomy_index Taxonomy indexing
  449. * @{
  450. * Functions to maintain taxonomy indexing.
  451. *
  452. * Taxonomy uses default field storage to store canonical relationships
  453. * between terms and fieldable entities. However its most common use case
  454. * requires listing all content associated with a term or group of terms
  455. * sorted by creation date. To avoid slow queries due to joining across
  456. * multiple node and field tables with various conditions and order by criteria,
  457. * we maintain a denormalized table with all relationships between terms,
  458. * published nodes and common sort criteria such as status, sticky and created.
  459. * When using other field storage engines or alternative methods of
  460. * denormalizing this data you should set the
  461. * taxonomy.settings:maintain_index_table to '0' to avoid unnecessary writes in
  462. * SQL.
  463. */
  464. /**
  465. * Implements hook_ENTITY_TYPE_insert() for node entities.
  466. */
  467. function taxonomy_node_insert(EntityInterface $node) {
  468. // Add taxonomy index entries for the node.
  469. taxonomy_build_node_index($node);
  470. }
  471. /**
  472. * Builds and inserts taxonomy index entries for a given node.
  473. *
  474. * The index lists all terms that are related to a given node entity, and is
  475. * therefore maintained at the entity level.
  476. *
  477. * @param \Drupal\node\Entity\Node $node
  478. * The node entity.
  479. */
  480. function taxonomy_build_node_index($node) {
  481. // We maintain a denormalized table of term/node relationships, containing
  482. // only data for current, published nodes.
  483. if (!\Drupal::config('taxonomy.settings')->get('maintain_index_table') || !(\Drupal::entityManager()->getStorage('node') instanceof SqlContentEntityStorage)) {
  484. return;
  485. }
  486. $status = $node->isPublished();
  487. $sticky = (int) $node->isSticky();
  488. // We only maintain the taxonomy index for published nodes.
  489. if ($status && $node->isDefaultRevision()) {
  490. // Collect a unique list of all the term IDs from all node fields.
  491. $tid_all = [];
  492. $entity_reference_class = 'Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem';
  493. foreach ($node->getFieldDefinitions() as $field) {
  494. $field_name = $field->getName();
  495. $class = $field->getItemDefinition()->getClass();
  496. $is_entity_reference_class = ($class === $entity_reference_class) || is_subclass_of($class, $entity_reference_class);
  497. if ($is_entity_reference_class && $field->getSetting('target_type') == 'taxonomy_term') {
  498. foreach ($node->getTranslationLanguages() as $language) {
  499. foreach ($node->getTranslation($language->getId())->$field_name as $item) {
  500. if (!$item->isEmpty()) {
  501. $tid_all[$item->target_id] = $item->target_id;
  502. }
  503. }
  504. }
  505. }
  506. }
  507. // Insert index entries for all the node's terms.
  508. if (!empty($tid_all)) {
  509. foreach ($tid_all as $tid) {
  510. db_merge('taxonomy_index')
  511. ->key(['nid' => $node->id(), 'tid' => $tid, 'status' => $node->isPublished()])
  512. ->fields(['sticky' => $sticky, 'created' => $node->getCreatedTime()])
  513. ->execute();
  514. }
  515. }
  516. }
  517. }
  518. /**
  519. * Implements hook_ENTITY_TYPE_update() for node entities.
  520. */
  521. function taxonomy_node_update(EntityInterface $node) {
  522. // If we're not dealing with the default revision of the node, do not make any
  523. // change to the taxonomy index.
  524. if (!$node->isDefaultRevision()) {
  525. return;
  526. }
  527. taxonomy_delete_node_index($node);
  528. taxonomy_build_node_index($node);
  529. }
  530. /**
  531. * Implements hook_ENTITY_TYPE_predelete() for node entities.
  532. */
  533. function taxonomy_node_predelete(EntityInterface $node) {
  534. // Clean up the {taxonomy_index} table when nodes are deleted.
  535. taxonomy_delete_node_index($node);
  536. }
  537. /**
  538. * Deletes taxonomy index entries for a given node.
  539. *
  540. * @param \Drupal\Core\Entity\EntityInterface $node
  541. * The node entity.
  542. */
  543. function taxonomy_delete_node_index(EntityInterface $node) {
  544. if (\Drupal::config('taxonomy.settings')->get('maintain_index_table')) {
  545. db_delete('taxonomy_index')->condition('nid', $node->id())->execute();
  546. }
  547. }
  548. /**
  549. * Implements hook_ENTITY_TYPE_delete() for taxonomy_term entities.
  550. */
  551. function taxonomy_taxonomy_term_delete(Term $term) {
  552. if (\Drupal::config('taxonomy.settings')->get('maintain_index_table')) {
  553. // Clean up the {taxonomy_index} table when terms are deleted.
  554. db_delete('taxonomy_index')->condition('tid', $term->id())->execute();
  555. }
  556. }
  557. /**
  558. * @} End of "defgroup taxonomy_index".
  559. */