taxonomy.module 25 KB

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