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