taxonomy.module 24.2 KB
Newer Older
1
<?php
2

3 4 5 6 7
/**
 * @file
 * Enables the organization of content into categories.
 */

8
use Drupal\Component\Utility\Tags;
9
use Drupal\Core\Entity\EntityInterface;
10
use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
11
use Drupal\Core\Render\Element;
12
use Drupal\Core\Routing\RouteMatchInterface;
13
use Drupal\Core\Url;
14 15
use Drupal\taxonomy\Entity\Term;
use Drupal\taxonomy\Entity\Vocabulary;
16
use Drupal\taxonomy\TermInterface;
17
use Drupal\taxonomy\VocabularyInterface;
18

19 20
/**
 * Denotes that no term in the vocabulary has a parent.
21 22 23
 *
 * @deprecated in Drupal 8.2.x and will be removed before 9.0.0. Use
 *   \Drupal\taxonomy\VocabularyInterface::HIERARCHY_DISABLED instead.
24 25
 *
 * @see https://www.drupal.org/node/2807795
26 27 28 29 30
 */
const TAXONOMY_HIERARCHY_DISABLED = 0;

/**
 * Denotes that one or more terms in the vocabulary has a single parent.
31 32 33
 *
 * @deprecated in Drupal 8.2.x and will be removed before 9.0.0. Use
 *   \Drupal\taxonomy\VocabularyInterface::HIERARCHY_SINGLE instead.
34 35
 *
 * @see https://www.drupal.org/node/2807795
36 37 38 39 40
 */
const TAXONOMY_HIERARCHY_SINGLE = 1;

/**
 * Denotes that one or more terms in the vocabulary have multiple parents.
41 42 43
 *
 * @deprecated in Drupal 8.2.x and will be removed before 9.0.0. Use
 *   \Drupal\taxonomy\VocabularyInterface::HIERARCHY_MULTIPLE instead.
44 45
 *
 * @see https://www.drupal.org/node/2807795
46 47 48
 */
const TAXONOMY_HIERARCHY_MULTIPLE = 2;

49
/**
50
 * Implements hook_help().
51
 */
52
function taxonomy_help($route_name, RouteMatchInterface $route_match) {
53 54
  switch ($route_name) {
    case 'help.page.taxonomy':
55
      $field_ui_url = \Drupal::moduleHandler()->moduleExists('field_ui') ? Url::fromRoute('help.page', ['name' => 'field_ui'])->toString() : '#';
56 57
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
58
      $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' => Url::fromRoute('user.admin_permissions', [], ['fragment' => 'module-taxonomy'])->toString()]) . '</p>';
59
      $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>';
60 61
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
62
      $output .= '<dt>' . t('Managing vocabularies') . '</dt>';
63
      $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' => Url::fromRoute('entity.taxonomy_vocabulary.collection')->toString(), ':field_ui' => $field_ui_url]) . '</dd>';
64
      $output .= '<dt>' . t('Managing terms') . '</dt>';
65
      $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' => Url::fromRoute('entity.taxonomy_vocabulary.collection')->toString()]) . ' </dd>';
66
      $output .= '<dt>' . t('Classifying entity content') . '</dt>';
67
      $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' => Url::fromRoute('help.page', ['name' => 'field'])->toString(), ':entity_reference' => Url::fromRoute('help.page', ['name' => 'entity_reference'])->toString()]) . '</dd>';
68
      $output .= '<dt>' . t('Adding new terms during content creation') . '</dt>';
69
      $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>';
70
      $output .= '<dt>' . t('Configuring displays and form displays') . '</dt>';
71
      $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' => Url::fromRoute('help.page', ['name' => 'entity_reference'])->toString()]) . '</li>';
72 73
      $output .= '</ul>';
      $output .= '</dd>';
74 75
      $output .= '</dl>';
      return $output;
76

77
    case 'entity.taxonomy_vocabulary.collection':
78
      $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>';
79 80 81 82
      return $output;
  }
}

83 84 85 86
/**
 * Implements hook_entity_type_alter().
 */
function taxonomy_entity_type_alter(array &$entity_types) {
87 88 89
  // @todo Moderation is disabled for taxonomy terms until integration is
  //   enabled for them.
  //   @see https://www.drupal.org/project/drupal/issues/3047110
90 91 92
  $entity_types['taxonomy_term']->setHandlerClass('moderation', '');
}

93
/**
94
 * Entity URI callback.
95
 */
96
function taxonomy_term_uri($term) {
97
  return new Url('entity.taxonomy_term.canonical', [
98
    'taxonomy_term' => $term->id(),
99
  ]);
100 101
}

102
/**
103
 * Implements hook_page_attachments_alter().
104
 */
105
function taxonomy_page_attachments_alter(array &$page) {
106 107 108 109
  $route_match = \Drupal::routeMatch();
  if ($route_match->getRouteName() == 'entity.taxonomy_term.canonical' && ($term = $route_match->getParameter('taxonomy_term')) && $term instanceof TermInterface) {
    foreach ($term->uriRelationships() as $rel) {
      // Set the URI relationships, like canonical.
110 111
      $page['#attached']['html_head_link'][] = [
        [
112
          'rel' => $rel,
113
          'href' => $term->toUrl($rel)->toString(),
114
        ],
115
        TRUE,
116
      ];
117 118 119 120

      // Set the term path as the canonical URL to prevent duplicate content.
      if ($rel == 'canonical') {
        // Set the non-aliased canonical path as a default shortlink.
121 122
        $page['#attached']['html_head_link'][] = [
          [
123
            'rel' => 'shortlink',
124
            'href' => $term->toUrl($rel, ['alias' => TRUE])->toString(),
125
          ],
126
          TRUE,
127
        ];
128 129 130 131 132
      }
    }
  }
}

133
/**
134
 * Implements hook_theme().
135 136
 */
function taxonomy_theme() {
137 138
  return [
    'taxonomy_term' => [
139
      'render element' => 'elements',
140 141
    ],
  ];
142 143
}

144
/**
145
 * Checks the hierarchy flag of a vocabulary.
146
 *
147 148
 * Checks the current parents of all terms in a vocabulary. If no term has
 * parent terms then the vocabulary will be given a hierarchy of
149 150 151 152 153
 * VocabularyInterface::HIERARCHY_DISABLED. If any term has a single parent then
 * the vocabulary will be given a hierarchy of
 * VocabularyInterface::HIERARCHY_SINGLE. If any term has multiple parents then
 * the vocabulary will be given a hierarchy of
 * VocabularyInterface::HIERARCHY_MULTIPLE.
154
 *
155
 * @param \Drupal\taxonomy\VocabularyInterface $vocabulary
156
 *   A taxonomy vocabulary entity.
157 158
 * @param $changed_term
 *   An array of the term structure that was updated.
159
 *
160
 * @return int
161
 *   An integer that represents the level of the vocabulary's hierarchy.
162 163 164
 *
 * @deprecated in Drupal 8.7.x. Will be removed before Drupal 9.0.0. Use
 *   \Drupal\taxonomy\TermStorage::getVocabularyHierarchyType() instead.
165
 */
166
function taxonomy_check_vocabulary_hierarchy(VocabularyInterface $vocabulary, $changed_term) {
167 168
  @trigger_error('taxonomy_check_vocabulary_hierarchy() is deprecated in Drupal 8.7.x and will be removed before Drupal 9.0.x. Use \Drupal\taxonomy\TermStorage::getVocabularyHierarchyType() instead.', E_USER_DEPRECATED);
  return \Drupal::entityTypeManager()->getStorage('taxonomy_term')->getVocabularyHierarchyType($vocabulary->id());
169 170
}

171
/**
172
 * Generates an array which displays a term detail page.
173
 *
174
 * @param \Drupal\taxonomy\Entity\Term $term
175 176
 *   A taxonomy term object.
 * @param string $view_mode
177
 *   View mode; e.g., 'full', 'teaser', etc.
178
 * @param string $langcode
179 180
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
181
 *
182
 * @return array
183 184
 *   A $page element suitable for use by
 *   \Drupal\Core\Render\RendererInterface::render().
185 186 187 188 189 190
 *
 * @deprecated in Drupal 8.7.0 and will be removed before Drupal 9.0.0. Use
 *   \Drupal::entityTypeManager()->getViewBuilder('taxonomy_term')->view()
 *   instead.
 *
 * @see https://www.drupal.org/node/3033656
191
 */
192
function taxonomy_term_view(Term $term, $view_mode = 'full', $langcode = NULL) {
193 194 195 196
  @trigger_error("taxonomy_term_view() is deprecated in Drupal 8.7.0 and will be removed before Drupal 9.0.0. Use \Drupal::entityTypeManager()->getViewBuilder('taxonomy_term')->view() instead. See https://www.drupal.org/node/3033656", E_USER_DEPRECATED);
  return \Drupal::entityTypeManager()
    ->getViewBuilder('taxonomy_term')
    ->view($term, $view_mode, $langcode);
197
}
198

199
/**
200
 * Constructs a drupal_render() style array from an array of loaded terms.
201
 *
202
 * @param array $terms
203
 *   An array of taxonomy terms as returned by Term::loadMultiple().
204
 * @param string $view_mode
205
 *   View mode; e.g., 'full', 'teaser', etc.
206 207 208 209
 * @param string $langcode
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
 *
210
 * @return array
211 212
 *   An array in the format expected by
 *   \Drupal\Core\Render\RendererInterface::render().
213 214 215 216 217 218
 *
 * @deprecated in Drupal 8.7.0 and will be removed before Drupal 9.0.0. Use
 *   \Drupal::entityTypeManager()->getViewBuilder('taxonomy_term')->viewMultiple()
 *   instead.
 *
 * @see https://www.drupal.org/node/3033656
219
 */
220
function taxonomy_term_view_multiple(array $terms, $view_mode = 'full', $langcode = NULL) {
221 222 223 224
  @trigger_error("taxonomy_term_view_multiple() is deprecated in Drupal 8.7.0 and will be removed before Drupal 9.0.0. Use \Drupal::entityTypeManager()->getViewBuilder('taxonomy_term')->viewMultiple() instead. See https://www.drupal.org/node/3033656", E_USER_DEPRECATED);
  return \Drupal::entityTypeManager()
    ->getViewBuilder('taxonomy_term')
    ->viewMultiple($terms, $view_mode, $langcode);
225 226
}

227 228 229 230
/**
 * Implements hook_theme_suggestions_HOOK().
 */
function taxonomy_theme_suggestions_taxonomy_term(array $variables) {
231
  $suggestions = [];
232

233 234
  /** @var \Drupal\taxonomy\TermInterface $term */
  $term = $variables['elements']['#taxonomy_term'];
235 236 237 238 239 240 241

  $suggestions[] = 'taxonomy_term__' . $term->bundle();
  $suggestions[] = 'taxonomy_term__' . $term->id();

  return $suggestions;
}

242
/**
243 244 245 246 247 248 249 250
 * Prepares variables for taxonomy term templates.
 *
 * Default template: taxonomy-term.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - elements: An associative array containing the taxonomy term and any
 *     fields attached to the term. Properties used:
251
 *     - #taxonomy_term: A \Drupal\taxonomy\TermInterface object.
252 253 254
 *     - #view_mode: The current view mode for this taxonomy term, e.g.
 *       'full' or 'teaser'.
 *   - attributes: HTML attributes for the containing element.
255 256 257
 */
function template_preprocess_taxonomy_term(&$variables) {
  $variables['view_mode'] = $variables['elements']['#view_mode'];
258 259
  $variables['term'] = $variables['elements']['#taxonomy_term'];
  /** @var \Drupal\taxonomy\TermInterface $term */
260 261
  $term = $variables['term'];

262
  $variables['url'] = $term->toUrl()->toString();
263
  // We use name here because that is what appears in the UI.
264 265
  $variables['name'] = $variables['elements']['name'];
  unset($variables['elements']['name']);
266
  $variables['page'] = $variables['view_mode'] == 'full' && taxonomy_term_is_page($term);
267 268

  // Helpful $content variable for templates.
269
  $variables['content'] = [];
270
  foreach (Element::children($variables['elements']) as $key) {
271 272 273 274 275
    $variables['content'][$key] = $variables['elements'][$key];
  }
}

/**
276
 * Returns whether the current page is the page of the passed-in term.
277
 *
278
 * @param \Drupal\taxonomy\Entity\Term $term
279
 *   A taxonomy term entity.
280
 */
281
function taxonomy_term_is_page(Term $term) {
282 283
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $page_term_id = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
    return $page_term_id == $term->id();
284 285
  }
  return FALSE;
286 287
}

288
/**
289
 * Clear all static cache variables for terms.
290 291
 */
function taxonomy_terms_static_reset() {
292
  \Drupal::entityTypeManager()->getStorage('taxonomy_term')->resetCache();
293 294
}

295 296
/**
 * Clear all static cache variables for vocabularies.
297
 *
298
 * @param $ids
299
 *   An array of ids to reset in the entity cache.
300
 */
301
function taxonomy_vocabulary_static_reset(array $ids = NULL) {
302
  \Drupal::entityTypeManager()->getStorage('taxonomy_vocabulary')->resetCache($ids);
303 304
}

305 306 307
/**
 * Get names for all taxonomy vocabularies.
 *
308 309
 * @return array
 *   A list of existing vocabulary IDs.
310 311
 */
function taxonomy_vocabulary_get_names() {
312 313 314
  $names = &drupal_static(__FUNCTION__);

  if (!isset($names)) {
315
    $names = [];
316
    $config_names = \Drupal::configFactory()->listAll('taxonomy.vocabulary.');
317 318 319 320
    foreach ($config_names as $config_name) {
      $id = substr($config_name, strlen('taxonomy.vocabulary.'));
      $names[$id] = $id;
    }
321
  }
322

323 324 325
  return $names;
}

Dries's avatar
Dries committed
326
/**
Dries's avatar
Dries committed
327
 * Try to map a string to an existing term, as for glossary use.
Dries's avatar
Dries committed
328
 *
Dries's avatar
Dries committed
329 330 331
 * Provides a case-insensitive and trimmed mapping, to maximize the
 * likelihood of a successful match.
 *
332
 * @param $name
Dries's avatar
Dries committed
333
 *   Name of the term to search for.
334 335
 * @param $vocabulary
 *   (optional) Vocabulary machine name to limit the search. Defaults to NULL.
Dries's avatar
Dries committed
336 337 338
 *
 * @return
 *   An array of matching term objects.
Dries's avatar
Dries committed
339
 */
340
function taxonomy_term_load_multiple_by_name($name, $vocabulary = NULL) {
341
  $values = ['name' => trim($name)];
342 343
  if (isset($vocabulary)) {
    $vocabularies = taxonomy_vocabulary_get_names();
344
    if (isset($vocabularies[$vocabulary])) {
345
      $values['vid'] = $vocabulary;
346 347 348
    }
    else {
      // Return an empty array when filtering by a non-existing vocabulary.
349
      return [];
350 351
    }
  }
352
  return \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadByProperties($values);
Dries's avatar
Dries committed
353 354
}

355 356 357 358 359 360 361
/**
 * Load multiple taxonomy terms based on certain conditions.
 *
 * This function should be used whenever you need to load more than one term
 * from the database. Terms are loaded into memory and will not require
 * database access if loaded again during the same page request.
 *
362 363
 * @param array $tids
 *   (optional) An array of entity IDs. If omitted, all entities are loaded.
364
 *
365
 * @return array
366 367
 *   An array of taxonomy term entities, indexed by tid. When no results are
 *   found, an empty array is returned.
368 369 370 371 372
 *
 * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use
 *   \Drupal\taxonomy\Entity\Term::loadMultiple().
 *
 * @see https://www.drupal.org/node/2266845
373
 */
374
function taxonomy_term_load_multiple(array $tids = NULL) {
375
  @trigger_error('taxonomy_term_load_multiple() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\taxonomy\Entity\Term::loadMultiple(). See https://www.drupal.org/node/2266845', E_USER_DEPRECATED);
376
  return Term::loadMultiple($tids);
377
}
378

379
/**
380
 * Loads multiple taxonomy vocabularies based on certain conditions.
381 382 383 384 385
 *
 * This function should be used whenever you need to load more than one
 * vocabulary from the database. Terms are loaded into memory and will not
 * require database access if loaded again during the same page request.
 *
386 387
 * @param array $vids
 *   (optional) An array of entity IDs. If omitted, all entities are loaded.
388
 *
389
 * @return array
390
 *   An array of vocabulary objects, indexed by vid.
391 392 393 394 395
 *
 * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use
 *   \Drupal\taxonomy\Entity\Vocabulary::loadMultiple().
 *
 * @see https://www.drupal.org/node/2266845
396
 */
397
function taxonomy_vocabulary_load_multiple(array $vids = NULL) {
398
  @trigger_error('taxonomy_vocabulary_load_multiple() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\taxonomy\Entity\Vocabulary::loadMultiple(). See https://www.drupal.org/node/2266845', E_USER_DEPRECATED);
399
  return Vocabulary::loadMultiple($vids);
400
}
401

402
/**
403
 * Return the taxonomy vocabulary entity matching a vocabulary ID.
404
 *
405 406
 * @param int $vid
 *   The vocabulary's ID.
407
 *
408
 * @return \Drupal\taxonomy\Entity\Vocabulary|null
409
 *   The taxonomy vocabulary entity, if exists, NULL otherwise. Results are
410
 *   statically cached.
411 412 413 414 415
 *
 * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use
 *   \Drupal\taxonomy\Entity\Vocabulary::load().
 *
 * @see https://www.drupal.org/node/2266845
416
 */
417
function taxonomy_vocabulary_load($vid) {
418
  @trigger_error('taxonomy_vocabulary_load() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\taxonomy\Entity\Vocabulary::load(). See https://www.drupal.org/node/2266845', E_USER_DEPRECATED);
419
  return Vocabulary::load($vid);
420 421
}

Dries's avatar
Dries committed
422
/**
423
 * Return the taxonomy term entity matching a term ID.
424 425 426 427
 *
 * @param $tid
 *   A term's ID
 *
428
 * @return \Drupal\taxonomy\Entity\Term|null
429
 *   A taxonomy term entity, or NULL if the term was not found. Results are
430
 *   statically cached.
431 432 433 434 435
 *
 * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use
 *   Drupal\taxonomy\Entity\Term::load().
 *
 * @see https://www.drupal.org/node/2266845
Dries's avatar
Dries committed
436
 */
437
function taxonomy_term_load($tid) {
438
  @trigger_error('taxonomy_term_load() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use \Drupal\taxonomy\Entity\Term::load(). See https://www.drupal.org/node/2266845', E_USER_DEPRECATED);
439
  if (!is_numeric($tid)) {
440
    return NULL;
441
  }
442
  return Term::load($tid);
443 444
}

445
/**
446
 * Implodes a list of tags of a certain vocabulary into a string.
447
 *
448
 * @see \Drupal\Component\Utility\Tags::explode()
449 450
 */
function taxonomy_implode_tags($tags, $vid = NULL) {
451
  $typed_tags = [];
452 453
  foreach ($tags as $tag) {
    // Extract terms belonging to the vocabulary in question.
454
    if (!isset($vid) || $tag->bundle() == $vid) {
455
      // Make sure we have a completed loaded taxonomy term.
456
      if ($tag instanceof EntityInterface && $label = $tag->label()) {
457
        // Commas and quotes in tag names are special cases, so encode 'em.
458
        $typed_tags[] = Tags::encode($label);
459 460 461
      }
    }
  }
462
  return implode(', ', $typed_tags);
463
}
464

465 466 467
/**
 * Title callback for term pages.
 *
468
 * @param \Drupal\taxonomy\Entity\Term $term
469
 *   A taxonomy term entity.
470
 *
471 472 473
 * @return
 *   The term name to be used as the page title.
 */
474
function taxonomy_term_title(Term $term) {
475
  return $term->getName();
476
}
477

478
/**
479
 * @defgroup taxonomy_index Taxonomy indexing
480 481
 * @{
 * Functions to maintain taxonomy indexing.
482 483 484 485 486 487 488
 *
 * Taxonomy uses default field storage to store canonical relationships
 * between terms and fieldable entities. However its most common use case
 * requires listing all content associated with a term or group of terms
 * sorted by creation date. To avoid slow queries due to joining across
 * multiple node and field tables with various conditions and order by criteria,
 * we maintain a denormalized table with all relationships between terms,
489 490 491 492 493
 * published nodes and common sort criteria such as status, sticky and created.
 * When using other field storage engines or alternative methods of
 * denormalizing this data you should set the
 * taxonomy.settings:maintain_index_table to '0' to avoid unnecessary writes in
 * SQL.
494 495 496
 */

/**
497
 * Implements hook_ENTITY_TYPE_insert() for node entities.
498
 */
499
function taxonomy_node_insert(EntityInterface $node) {
500 501
  // Add taxonomy index entries for the node.
  taxonomy_build_node_index($node);
502 503 504
}

/**
505 506 507 508 509
 * Builds and inserts taxonomy index entries for a given node.
 *
 * The index lists all terms that are related to a given node entity, and is
 * therefore maintained at the entity level.
 *
510
 * @param \Drupal\node\Entity\Node $node
511
 *   The node entity.
512
 */
513 514 515
function taxonomy_build_node_index($node) {
  // We maintain a denormalized table of term/node relationships, containing
  // only data for current, published nodes.
516
  if (!\Drupal::config('taxonomy.settings')->get('maintain_index_table') || !(\Drupal::entityTypeManager()->getStorage('node') instanceof SqlContentEntityStorage)) {
517
    return;
518
  }
519 520 521

  $status = $node->isPublished();
  $sticky = (int) $node->isSticky();
522
  // We only maintain the taxonomy index for published nodes.
523
  if ($status && $node->isDefaultRevision()) {
524
    // Collect a unique list of all the term IDs from all node fields.
525
    $tid_all = [];
526
    $entity_reference_class = 'Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem';
527
    foreach ($node->getFieldDefinitions() as $field) {
528
      $field_name = $field->getName();
529 530 531
      $class = $field->getItemDefinition()->getClass();
      $is_entity_reference_class = ($class === $entity_reference_class) || is_subclass_of($class, $entity_reference_class);
      if ($is_entity_reference_class && $field->getSetting('target_type') == 'taxonomy_term') {
532
        foreach ($node->getTranslationLanguages() as $language) {
533
          foreach ($node->getTranslation($language->getId())->$field_name as $item) {
534 535
            if (!$item->isEmpty()) {
              $tid_all[$item->target_id] = $item->target_id;
536 537 538 539 540 541 542
            }
          }
        }
      }
    }
    // Insert index entries for all the node's terms.
    if (!empty($tid_all)) {
543
      $connection = \Drupal::database();
544
      foreach ($tid_all as $tid) {
545
        $connection->merge('taxonomy_index')
546 547
          ->key(['nid' => $node->id(), 'tid' => $tid, 'status' => $node->isPublished()])
          ->fields(['sticky' => $sticky, 'created' => $node->getCreatedTime()])
548
          ->execute();
549 550 551 552 553
      }
    }
  }
}

554
/**
555
 * Implements hook_ENTITY_TYPE_update() for node entities.
556
 */
557
function taxonomy_node_update(EntityInterface $node) {
558 559 560 561 562
  // If we're not dealing with the default revision of the node, do not make any
  // change to the taxonomy index.
  if (!$node->isDefaultRevision()) {
    return;
  }
563 564 565 566
  taxonomy_delete_node_index($node);
  taxonomy_build_node_index($node);
}

567
/**
568
 * Implements hook_ENTITY_TYPE_predelete() for node entities.
569
 */
570
function taxonomy_node_predelete(EntityInterface $node) {
571 572 573 574 575 576 577
  // Clean up the {taxonomy_index} table when nodes are deleted.
  taxonomy_delete_node_index($node);
}

/**
 * Deletes taxonomy index entries for a given node.
 *
578
 * @param \Drupal\Core\Entity\EntityInterface $node
579
 *   The node entity.
580
 */
581
function taxonomy_delete_node_index(EntityInterface $node) {
582
  if (\Drupal::config('taxonomy.settings')->get('maintain_index_table')) {
583
    \Drupal::database()->delete('taxonomy_index')->condition('nid', $node->id())->execute();
584 585 586 587
  }
}

/**
588
 * Implements hook_ENTITY_TYPE_delete() for taxonomy_term entities.
589
 */
590
function taxonomy_taxonomy_term_delete(Term $term) {
591
  if (\Drupal::config('taxonomy.settings')->get('maintain_index_table')) {
592
    // Clean up the {taxonomy_index} table when terms are deleted.
593
    \Drupal::database()->delete('taxonomy_index')->condition('tid', $term->id())->execute();
594 595 596 597
  }
}

/**
598
 * @} End of "defgroup taxonomy_index".
599
 */