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

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

8
use Drupal\Core\Entity\FieldableDatabaseStorageController;
9
use Drupal\Core\Entity\EntityInterface;
10
use Drupal\Core\Field\FieldDefinitionInterface;
11 12
use Drupal\field\FieldInterface;
use Drupal\field\FieldInstanceInterface;
13
use Drupal\file\FileInterface;
14 15 16
use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Term;
use Drupal\taxonomy\Entity\Vocabulary;
17
use Drupal\taxonomy\VocabularyInterface;
18

19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/**
 * Denotes that no term in the vocabulary has a parent.
 */
const TAXONOMY_HIERARCHY_DISABLED = 0;

/**
 * Denotes that one or more terms in the vocabulary has a single parent.
 */
const TAXONOMY_HIERARCHY_SINGLE = 1;

/**
 * Denotes that one or more terms in the vocabulary have multiple parents.
 */
const TAXONOMY_HIERARCHY_MULTIPLE = 2;

34 35 36 37 38 39 40 41
/**
 * Users can create new terms in a free-tagging vocabulary when
 * submitting a taxonomy_autocomplete_widget. We store a term object
 * whose tid is 'autocreate' as a field data item during widget
 * validation and then actually create the term if/when that field
 * data item makes it to taxonomy_field_insert/update().
 */

42
/**
43
 * Implements hook_help().
44 45 46 47 48 49
 */
function taxonomy_help($path, $arg) {
  switch ($path) {
    case 'admin/help#taxonomy':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
50
      $output .= '<p>' . t('The Taxonomy module allows you to classify the content of your website. To classify content, you define <em>vocabularies</em> that contain related <em>terms</em>, and then assign the vocabularies to content types. For more information, see the online handbook entry for the <a href="@taxonomy">Taxonomy module</a>.', array('@taxonomy' => 'http://drupal.org/documentation/modules/taxonomy')) . '</p>';
51 52 53
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Creating vocabularies') . '</dt>';
54
      $output .= '<dd>' . t('Users with sufficient <a href="@perm">permissions</a> can create <em>vocabularies</em> and <em>terms</em> through the <a href="@taxo">Taxonomy page</a>. The page listing the terms provides a drag-and-drop interface for controlling the order of the terms and sub-terms within a vocabulary, in a hierarchical fashion. A <em>controlled vocabulary</em> classifying music by genre with terms and sub-terms could look as follows:', array('@taxo' => url('admin/structure/taxonomy'), '@perm' => url('admin/people/permissions', array('fragment'=>'module-taxonomy'))));
55
      $output .= '<ul><li>' . t('<em>vocabulary</em>: Music') . '</li>';
56 57 58 59 60 61 62 63 64
      $output .= '<ul><li>' . t('<em>term</em>: Jazz') . '</li>';
      $output .= '<ul><li>' . t('<em>sub-term</em>: Swing') . '</li>';
      $output .= '<li>' . t('<em>sub-term</em>: Fusion') . '</li></ul></ul>';
      $output .= '<ul><li>' . t('<em>term</em>: Rock') . '</li>';
      $output .= '<ul><li>' . t('<em>sub-term</em>: Country rock') . '</li>';
      $output .= '<li>' . t('<em>sub-term</em>: Hard rock') . '</li></ul></ul></ul>';
      $output .= t('You can assign a sub-term to multiple parent terms. For example, <em>fusion</em> can be assigned to both <em>rock</em> and <em>jazz</em>.') . '</dd>';
      $output .= '<dd>' . t('Terms in a <em>free-tagging vocabulary</em> can be built gradually as you create or edit content. This is often done used for blogs or photo management applications.') . '</dd>';
      $output .= '<dt>' . t('Assigning vocabularies to content types') . '</dt>';
65
      $output .= '<dd>' . t('Before you can use a new vocabulary to classify your content, a new Taxonomy term field must be added to a <a href="@ctedit">content type</a> on its <em>manage fields</em> page. When adding a taxonomy field, you choose a <em>widget</em> to use to enter the taxonomy information on the content editing page: a select list, checkboxes, radio buttons, or an auto-complete field (to build a free-tagging vocabulary). After choosing the field type and widget, on the subsequent <em>field settings</em> page you can choose the desired vocabulary, whether one or multiple terms can be chosen from the vocabulary, and other settings. The same vocabulary can be added to multiple content types, by using the "Re-use existing field" section on the manage fields page.', array('@ctedit' => url('admin/structure/types'))) . '</dd>';
66
      $output .= '<dt>' . t('Classifying content') . '</dt>';
67
      $output .= '<dd>' . t('After the vocabulary is assigned to the content type, you can start classifying content. The field with terms will appear on the content editing screen when you edit or <a href="@addnode">add new content</a>.', array('@addnode' => url('node/add'))) . '</dd>';
68 69 70 71 72 73 74
      $output .= '<dt>' . t('Viewing listings and RSS feeds by term') . '</dt>';
      $output .= '<dd>' . t("Each taxonomy term automatically provides a page listing content that has its classification, and a corresponding RSS feed. For example, if the taxonomy term <em>country rock</em> has the ID 123 (you can see this by looking at the URL when hovering on the linked term, which you can click to navigate to the listing page), then you will find this list at the path <em>taxonomy/term/123</em>. The RSS feed will use the path <em>taxonomy/term/123/feed</em> (the RSS icon for this term's listing will automatically display in your browser's address bar when viewing the listing page).") . '</dd>';
      $output .= '<dt>' . t('Extending Taxonomy module') . '</dt>';
      $output .= '<dd>' . t('There are <a href="@taxcontrib">many contributed modules</a> that extend the behavior of the Taxonomy module for both display and organization of terms.', array('@taxcontrib' => 'http://drupal.org/project/modules?filters=tid:71&solrsort=sis_project_release_usage%20desc'));
      $output .= '</dl>';
      return $output;
    case 'admin/structure/taxonomy':
75
      $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>';
76
      return $output;
77
    case 'admin/structure/taxonomy/manage/%':
78
      $vocabulary = entity_load('taxonomy_vocabulary', $arg[4]);
79
      switch ($vocabulary->hierarchy) {
80
        case TAXONOMY_HIERARCHY_DISABLED:
81
          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.', array('%capital_name' => drupal_ucfirst($vocabulary->name), '%name' => $vocabulary->name)) . '</p>';
82
        case TAXONOMY_HIERARCHY_SINGLE:
83
          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.', array('%capital_name' => drupal_ucfirst($vocabulary->name), '%name' => $vocabulary->name)) . '</p>';
84
        case TAXONOMY_HIERARCHY_MULTIPLE:
85
          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.', array('%capital_name' => drupal_ucfirst($vocabulary->name))) . '</p>';
86 87 88 89
      }
  }
}

Dries's avatar
Dries committed
90
/**
91
 * Implements hook_permission().
Dries's avatar
Dries committed
92
 */
93
function taxonomy_permission() {
94
  $permissions = array(
95
    'administer taxonomy' => array(
96
      'title' => t('Administer vocabularies and terms'),
97
    ),
98
  );
99
  foreach (entity_load_multiple('taxonomy_vocabulary') as $vocabulary) {
100
    $permissions += array(
101
      'edit terms in ' . $vocabulary->id() => array(
102 103 104 105
        'title' => t('Edit terms in %vocabulary', array('%vocabulary' => $vocabulary->name)),
      ),
    );
    $permissions += array(
106
       'delete terms in ' . $vocabulary->id() => array(
107
         'title' => t('Delete terms from %vocabulary', array('%vocabulary' => $vocabulary->name)),
108 109 110 111
      ),
    );
  }
  return $permissions;
Kjartan's avatar
Kjartan committed
112
}
113

114 115 116 117 118
/**
 * Implements hook_entity_bundle_info().
 */
function taxonomy_entity_bundle_info() {
  $bundles = array();
119
  foreach (taxonomy_vocabulary_get_names() as $id) {
120
    $config = \Drupal::config('taxonomy.vocabulary.' . $id);
121
    $bundles['taxonomy_term'][$id]['label'] = $config->get('name');
122
  }
123
  return $bundles;
124 125
}

126
/**
127
 * Entity URI callback.
128
 */
129 130
function taxonomy_term_uri($term) {
  return array(
131
    'path' => 'taxonomy/term/' . $term->id(),
132
  );
133 134
}

135 136 137 138 139
/**
 * Implements hook_field_extra_fields().
 */
function taxonomy_field_extra_fields() {
  $return = array();
140
  foreach (entity_get_bundles('taxonomy_term') as $bundle => $bundle_info) {
141
    $return['taxonomy_term'][$bundle] = array(
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
      'form' => array(
        'name' => array(
          'label' => t('Name'),
          'description' => t('Term name textfield'),
          'weight' => -5,
        ),
        'description' => array(
          'label' => t('Description'),
          'description' => t('Term description textarea'),
          'weight' => 0,
        ),
      ),
      'display' => array(
        'description' => array(
          'label' => t('Description'),
          'description' => t('Term description'),
          'weight' => 0,
        ),
160 161 162 163 164 165 166
      ),
    );
  }

  return $return;
}

167 168 169 170 171 172 173
/**
 * Return nodes attached to a term across all field instances.
 *
 * This function requires taxonomy module to be maintaining its own tables,
 * and will return an empty array if it is not. If using other field storage
 * methods alternatives methods for listing terms will need to be used.
 *
174 175
 * @param $tid
 *   The term ID.
176 177
 * @param $pager
 *   Boolean to indicate whether a pager should be used.
178 179 180
 * @param $limit
 *   Integer. The maximum number of nodes to find.
 *   Set to FALSE for no limit.
181
 * @param $order
182 183 184 185 186
 *   An array of fields and directions.
 *
 * @return
 *   An array of nids matching the query.
 */
187
function taxonomy_select_nodes($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC')) {
188
  if (!\Drupal::config('taxonomy.settings')->get('maintain_index_table')) {
189 190 191 192
    return array();
  }
  $query = db_select('taxonomy_index', 't');
  $query->addTag('node_access');
193
  $query->addMetaData('base_table', 'taxonomy_index');
194
  $query->condition('tid', $tid);
195 196 197 198
  if ($pager) {
    $count_query = clone $query;
    $count_query->addExpression('COUNT(t.nid)');

199
    $query = $query->extend('Drupal\Core\Database\Query\PagerSelectExtender');
200 201 202
    if ($limit !== FALSE) {
      $query = $query->limit($limit);
    }
203 204 205
    $query->setCountQuery($count_query);
  }
  else {
206 207 208
    if ($limit !== FALSE) {
      $query->range(0, $limit);
    }
209 210 211 212 213 214 215 216 217 218 219 220 221
  }
  $query->addField('t', 'nid');
  $query->addField('t', 'tid');
  foreach ($order as $field => $direction) {
    $query->orderBy($field, $direction);
    // ORDER BY fields need to be loaded too, assume they are in the form
    // table_alias.name
    list($table_alias, $name) = explode('.', $field);
    $query->addField($table_alias, $name);
  }
  return $query->execute()->fetchCol();
}

222
/**
223
 * Implements hook_theme().
224 225 226
 */
function taxonomy_theme() {
  return array(
227 228 229 230
    'taxonomy_term' => array(
      'render element' => 'elements',
      'template' => 'taxonomy-term',
    ),
231 232 233
  );
}

Dries's avatar
Dries committed
234
/**
235
 * Implements hook_menu().
Dries's avatar
Dries committed
236
 */
237
function taxonomy_menu() {
238
  $items['admin/structure/taxonomy'] = array(
239 240
    'title' => 'Taxonomy',
    'description' => 'Manage tagging, categorization, and classification of your content.',
241
    'route_name' => 'taxonomy.vocabulary_list',
242 243
  );

244
  $items['taxonomy/term/%taxonomy_term'] = array(
245
    'title' => 'Taxonomy term',
246 247
    'title callback' => 'taxonomy_term_title',
    'title arguments' => array(2),
248
    'route_name' => 'taxonomy.term_page',
249
  );
250 251 252 253
  $items['taxonomy/term/%taxonomy_term/feed'] = array(
    'title' => 'Taxonomy term',
    'title callback' => 'taxonomy_term_title',
    'title arguments' => array(2),
254
    'route_name' => 'taxonomy.term_feed',
255 256
    'type' => MENU_CALLBACK,
  );
257

258
  $items['admin/structure/taxonomy/manage/%taxonomy_vocabulary'] = array(
259
    'route_name' => 'taxonomy.overview_terms',
260
    'title callback' => 'entity_page_label',
261
    'title arguments' => array(4),
262
  );
263
  $items['admin/structure/taxonomy/manage/%taxonomy_vocabulary/list'] = array(
264
    'title' => 'List',
265
    'type' => MENU_DEFAULT_LOCAL_TASK,
266
  );
267
  $items['admin/structure/taxonomy/manage/%taxonomy_vocabulary/edit'] = array(
268
    'title' => 'Edit',
269
    'route_name' => 'taxonomy.vocabulary_edit',
270
    'type' => MENU_LOCAL_TASK,
271
  );
272

Dries's avatar
Dries committed
273 274
  return $items;
}
275

276 277 278 279 280 281
/**
 * Implements hook_admin_paths().
 */
function taxonomy_admin_paths() {
  $paths = array(
    'taxonomy/term/*/edit' => TRUE,
282
    'taxonomy/term/*/delete' => TRUE,
283 284
    'taxonomy/term/*/translations' => TRUE,
    'taxonomy/term/*/translations/*' => TRUE,
285 286 287 288
  );
  return $paths;
}

289
/**
290
 * Checks and updates the hierarchy flag of a vocabulary.
291
 *
292
 * Checks the current parents of all terms in a vocabulary and updates the
293
 * vocabulary's hierarchy setting to the lowest possible level. If no term
294 295 296 297 298
 * has parent terms then the vocabulary will be given a hierarchy of
 * TAXONOMY_HIERARCHY_DISABLED. If any term has a single parent then the
 * vocabulary will be given a hierarchy of TAXONOMY_HIERARCHY_SINGLE. If any
 * term has multiple parents then the vocabulary will be given a hierarchy of
 * TAXONOMY_HIERARCHY_MULTIPLE.
299
 *
300
 * @param \Drupal\taxonomy\VocabularyInterface $vocabulary
301
 *   A taxonomy vocabulary entity.
302 303
 * @param $changed_term
 *   An array of the term structure that was updated.
304 305 306
 *
 * @return
 *   An integer that represents the level of the vocabulary's hierarchy.
307
 */
308
function taxonomy_check_vocabulary_hierarchy(VocabularyInterface $vocabulary, $changed_term) {
309
  $tree = taxonomy_get_tree($vocabulary->id());
310
  $hierarchy = TAXONOMY_HIERARCHY_DISABLED;
311
  foreach ($tree as $term) {
312
    // Update the changed term with the new parent value before comparison.
313
    if ($term->tid == $changed_term['tid']) {
314
      $term = (object) $changed_term;
315 316 317 318
      $term->parents = $term->parent;
    }
    // Check this term's parent count.
    if (count($term->parents) > 1) {
319
      $hierarchy = TAXONOMY_HIERARCHY_MULTIPLE;
320 321
      break;
    }
322
    elseif (count($term->parents) == 1 && !isset($term->parents[0])) {
323
      $hierarchy = TAXONOMY_HIERARCHY_SINGLE;
324 325
    }
  }
326 327
  if ($hierarchy != $vocabulary->hierarchy) {
    $vocabulary->hierarchy = $hierarchy;
328
    $vocabulary->save();
329 330 331 332 333
  }

  return $hierarchy;
}

334
/**
335
 * Generates an array which displays a term detail page.
336
 *
337
 * @param \Drupal\taxonomy\Entity\Term $term
338 339
 *   A taxonomy term object.
 * @param string $view_mode
340
 *   View mode, e.g. 'full', 'teaser'...
341
 * @param string $langcode
342 343
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
344
 *
345
 * @return array
346
 *   A $page element suitable for use by drupal_page_render().
347
 */
348 349
function taxonomy_term_view(Term $term, $view_mode = 'full', $langcode = NULL) {
  return entity_view($term, $view_mode, $langcode);
350
}
351

352 353
 /**
 * Constructs a drupal_render() style array from an array of loaded terms.
354
 *
355
 * @param array $terms
356
 *   An array of taxonomy terms as returned by entity_load_multiple('taxonomy_term').
357 358 359 360 361 362
 * @param string $view_mode
 *   View mode, e.g. 'full', 'teaser'...
 * @param string $langcode
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
 *
363 364
 * @return array
 *   An array in the format expected by drupal_render().
365
 */
366 367
function taxonomy_term_view_multiple(array $terms, $view_mode = 'full', $langcode = NULL) {
  return entity_view_multiple($terms, $view_mode, $langcode);
368 369
}

370 371 372 373 374 375 376 377 378 379 380 381 382 383
/**
 * Implements hook_theme_suggestions_HOOK().
 */
function taxonomy_theme_suggestions_taxonomy_term(array $variables) {
  $suggestions = array();

  $term = $variables['elements']['#term'];

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

  return $suggestions;
}

384
/**
385 386 387 388 389 390 391 392 393 394 395 396
 * 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:
 *     - #term: The term object.
 *     - #view_mode: The current view mode for this taxonomy term, e.g.
 *       'full' or 'teaser'.
 *   - attributes: HTML attributes for the containing element.
397 398 399 400 401 402
 */
function template_preprocess_taxonomy_term(&$variables) {
  $variables['view_mode'] = $variables['elements']['#view_mode'];
  $variables['term'] = $variables['elements']['#term'];
  $term = $variables['term'];

403
  $uri = $term->uri();
404
  $variables['url']  = url($uri['path'], $uri['options']);
405 406 407
  // We use name here because that is what appears in the UI.
  $variables['name'] = check_plain($term->label());
  $variables['page'] = $variables['view_mode'] == 'full' && taxonomy_term_is_page($term);
408 409

  // Helpful $content variable for templates.
410
  $variables['content'] = array();
411 412 413 414 415 416 417 418
  foreach (element_children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }

  // field_attach_preprocess() overwrites the $[field_name] variables with the
  // values of the field in the language that was selected for display, instead
  // of the raw values in $term->[field_name], which contain all values in all
  // languages.
419
  field_attach_preprocess($term, $variables['content'], $variables);
420

421
  // Gather classes, and clean up name so there are no underscores.
422
  $variables['attributes']['class'][] = 'taxonomy-term';
423
  $vocabulary_name_css = str_replace('_', '-', $term->bundle());
424
  $variables['attributes']['class'][] = 'vocabulary-' . $vocabulary_name_css;
425 426 427
}

/**
428
 * Returns whether the current page is the page of the passed-in term.
429
 *
430
 * @param \Drupal\taxonomy\Entity\Term $term
431
 *   A taxonomy term entity.
432
 */
433
function taxonomy_term_is_page(Term $term) {
434 435 436 437 438 439
  $request = \Drupal::request();
  if ($request->attributes->has('taxonomy_term')) {
    $page_term = $request->attributes->get('taxonomy_term');
    return $page_term->id() == $term->id();
  }
  return FALSE;
440 441
}

442
/**
443
 * Clear all static cache variables for terms.
444 445
 */
function taxonomy_terms_static_reset() {
446
  \Drupal::entityManager()->getStorageController('taxonomy_term')->resetCache();
447 448
}

449 450
/**
 * Clear all static cache variables for vocabularies.
451
 *
452
 * @param $ids
453
 *   An array of ids to reset in entity controller cache.
454
 */
455
function taxonomy_vocabulary_static_reset(array $ids = NULL) {
456
  \Drupal::entityManager()->getStorageController('taxonomy_vocabulary')->resetCache($ids);
457 458
}

459 460 461
/**
 * Get names for all taxonomy vocabularies.
 *
462 463
 * @return array
 *   A list of existing vocabulary IDs.
464 465
 */
function taxonomy_vocabulary_get_names() {
466 467 468
  $names = &drupal_static(__FUNCTION__);

  if (!isset($names)) {
469 470 471 472 473 474
    $names = array();
    $config_names = config_get_storage_names_with_prefix('taxonomy.vocabulary.');
    foreach ($config_names as $config_name) {
      $id = substr($config_name, strlen('taxonomy.vocabulary.'));
      $names[$id] = $id;
    }
475
  }
476

477 478 479
  return $names;
}

Dries's avatar
Dries committed
480
/**
481 482 483 484 485 486
 * Finds all parents of a given term ID.
 *
 * @param $tid
 *   A taxonomy term ID.
 *
 * @return
487 488
 *   An array of term objects which are the parents of the term $tid, or an
 *   empty array if parents are not found.
Dries's avatar
Dries committed
489
 */
490
function taxonomy_term_load_parents($tid) {
491 492 493
  $parents = &drupal_static(__FUNCTION__, array());

  if ($tid && !isset($parents[$tid])) {
494
    $tids = \Drupal::entityManager()->getStorageController('taxonomy_term')->loadParents($tid);
495
    $parents[$tid] = entity_load_multiple('taxonomy_term', $tids);
Kjartan's avatar
Kjartan committed
496
  }
497 498

  return isset($parents[$tid]) ? $parents[$tid] : array();
Kjartan's avatar
Kjartan committed
499
}
500

Dries's avatar
Dries committed
501 502 503
/**
 * Find all ancestors of a given term ID.
 */
504
function taxonomy_term_load_parents_all($tid) {
505 506 507 508 509 510
  $cache = &drupal_static(__FUNCTION__, array());

  if (isset($cache[$tid])) {
    return $cache[$tid];
  }

511
  $parents = array();
512
  if ($term = entity_load('taxonomy_term', $tid)) {
513
    $parents[] = $term;
514
    $n = 0;
515
    while ($parent = taxonomy_term_load_parents($parents[$n]->id())) {
516 517 518 519
      $parents = array_merge($parents, $parent);
      $n++;
    }
  }
520 521 522

  $cache[$tid] = $parents;

523 524 525
  return $parents;
}

Dries's avatar
Dries committed
526
/**
527 528 529 530 531 532 533 534
 * Finds all children of a term ID.
 *
 * @param $tid
 *   A taxonomy term ID.
 * @param $vid
 *   An optional vocabulary ID to restrict the child search.
 *
 * @return
535 536
 *   An array of term objects that are the children of the term $tid, or an
 *   empty array when no children exist.
Dries's avatar
Dries committed
537
 */
538
function taxonomy_term_load_children($tid, $vid = NULL) {
539 540 541
  $children = &drupal_static(__FUNCTION__, array());

  if ($tid && !isset($children[$tid])) {
542
    $tids = \Drupal::entityManager()->getStorageController('taxonomy_term')->loadChildren($tid);
543
    $children[$tid] = entity_load_multiple('taxonomy_term', $tids);
Kjartan's avatar
Kjartan committed
544
  }
545 546

  return isset($children[$tid]) ? $children[$tid] : array();
Kjartan's avatar
Kjartan committed
547
}
548

Dries's avatar
Dries committed
549 550 551 552
/**
 * Create a hierarchical representation of a vocabulary.
 *
 * @param $vid
553
 *   The vocabulary ID to generate the tree for.
Dries's avatar
Dries committed
554 555 556
 * @param $parent
 *   The term ID under which to generate the tree. If 0, generate the tree
 *   for the entire vocabulary.
557 558
 * @param $max_depth
 *   The number of levels of the tree to return. Leave NULL to return all levels.
559 560 561 562 563
 * @param $load_entities
 *   If TRUE, a full entity load will occur on the term objects. Otherwise they
 *   are partial objects queried directly from the {taxonomy_term_data} table to
 *   save execution time and memory consumption when listing large numbers of
 *   terms. Defaults to FALSE.
564
 *
Dries's avatar
Dries committed
565 566 567
 * @return
 *   An array of all term objects in the tree. Each term object is extended
 *   to have "depth" and "parents" attributes in addition to its normal ones.
568 569
 *   Results are statically cached. Term objects will be partial or complete
 *   depending on the $load_entities parameter.
Dries's avatar
Dries committed
570
 */
571
function taxonomy_get_tree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE) {
572
  $children = &drupal_static(__FUNCTION__, array());
573 574
  $parents = &drupal_static(__FUNCTION__ . ':parents', array());
  $terms = &drupal_static(__FUNCTION__ . ':terms', array());
575

576 577
  // We cache trees, so it's not CPU-intensive to call taxonomy_get_tree() on a
  // term and its children, too.
Dries's avatar
Dries committed
578 579
  if (!isset($children[$vid])) {
    $children[$vid] = array();
580 581
    $parents[$vid] = array();
    $terms[$vid] = array();
Dries's avatar
Dries committed
582

583
    $result = \Drupal::entityManager()->getStorageController('taxonomy_term')->loadTree($vid);
584 585 586 587 588

    foreach ($result as $term) {
      $children[$vid][$term->parent][] = $term->tid;
      $parents[$vid][$term->tid][] = $term->parent;
      $terms[$vid][$term->tid] = $term;
589 590
    }
  }
591

592 593 594
  // Load full entities, if necessary. The entity controller statically
  // caches the results.
  if ($load_entities) {
595
    $term_entities = entity_load_multiple('taxonomy_term', array_keys($terms[$vid]));
596 597
  }

598
  $max_depth = (!isset($max_depth)) ? count($children[$vid]) : $max_depth;
599
  $tree = array();
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619

  // Keeps track of the parents we have to process, the last entry is used
  // for the next processing step.
  $process_parents = array();
  $process_parents[] = $parent;

  // Loops over the parent terms and adds its children to the tree array.
  // Uses a loop instead of a recursion, because it's more efficient.
  while (count($process_parents)) {
    $parent = array_pop($process_parents);
    // The number of parents determines the current depth.
    $depth = count($process_parents);
    if ($max_depth > $depth && !empty($children[$vid][$parent])) {
      $has_children = FALSE;
      $child = current($children[$vid][$parent]);
      do {
        if (empty($child)) {
          break;
        }
        $term = $load_entities ? $term_entities[$child] : $terms[$vid][$child];
620
        if (isset($parents[$vid][$load_entities ? $term->id() : $term->tid])) {
621 622
          // Clone the term so that the depth attribute remains correct
          // in the event of multiple parents.
623 624 625 626
          $term = clone $term;
        }
        $term->depth = $depth;
        unset($term->parent);
627 628
        $tid = $load_entities ? $term->id() : $term->tid;
        $term->parents = $parents[$vid][$tid];
629
        $tree[] = $term;
630
        if (!empty($children[$vid][$tid])) {
631 632 633 634 635
          $has_children = TRUE;

          // We have to continue with this parent later.
          $process_parents[] = $parent;
          // Use the current term as parent for the next iteration.
636
          $process_parents[] = $tid;
637 638 639

          // Reset pointers for child lists because we step in there more often
          // with multi parents.
640
          reset($children[$vid][$tid]);
641 642 643 644 645 646 647 648 649 650
          // Move pointer so that we get the correct term the next time.
          next($children[$vid][$parent]);
          break;
        }
      } while ($child = next($children[$vid][$parent]));

      if (!$has_children) {
        // We processed all terms in this hierarchy-level, reset pointer
        // so that this function works the next time it gets called.
        reset($children[$vid][$parent]);
651
      }
652
    }
Kjartan's avatar
Kjartan committed
653
  }
654

655
  return $tree;
Kjartan's avatar
Kjartan committed
656
}
657

Dries's avatar
Dries committed
658
/**
Dries's avatar
Dries committed
659
 * Try to map a string to an existing term, as for glossary use.
Dries's avatar
Dries committed
660
 *
Dries's avatar
Dries committed
661 662 663
 * Provides a case-insensitive and trimmed mapping, to maximize the
 * likelihood of a successful match.
 *
664
 * @param $name
Dries's avatar
Dries committed
665
 *   Name of the term to search for.
666 667
 * @param $vocabulary
 *   (optional) Vocabulary machine name to limit the search. Defaults to NULL.
Dries's avatar
Dries committed
668 669 670
 *
 * @return
 *   An array of matching term objects.
Dries's avatar
Dries committed
671
 */
672
function taxonomy_term_load_multiple_by_name($name, $vocabulary = NULL) {
673
  $values = array('name' => trim($name));
674 675 676
  if (isset($vocabulary)) {
    $vocabularies = taxonomy_vocabulary_get_names();
    if (isset($vocabularies[$vocabulary])){
677
      $values['vid'] = $vocabulary;
678 679 680 681 682 683
    }
    else {
      // Return an empty array when filtering by a non-existing vocabulary.
      return array();
    }
  }
684
  return entity_load_multiple_by_properties('taxonomy_term', $values);
Dries's avatar
Dries committed
685 686
}

687 688 689 690 691 692 693
/**
 * 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.
 *
694
 * @see entity_load_multiple()
695
 * @see \Drupal\Core\Entity\Query\EntityQueryInterface
696
 *
697 698
 * @deprecated use entity_load_multiple('taxonomy_term', $tids) instead.
 *
699 700
 * @param array $tids
 *   (optional) An array of entity IDs. If omitted, all entities are loaded.
701
 *
702
 * @return array
703 704
 *   An array of taxonomy term entities, indexed by tid. When no results are
 *   found, an empty array is returned.
705
 */
706 707
function taxonomy_term_load_multiple(array $tids = NULL) {
  return entity_load_multiple('taxonomy_term', $tids);
708
}
709

710
/**
711
 * Loads multiple taxonomy vocabularies based on certain conditions.
712 713 714 715 716
 *
 * 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.
 *
717
 * @see entity_load_multiple()
718
 *
719 720
 * @deprecated use entity_load_multiple('taxonomy_vocabulary', $vids) instead.
 *
721 722
 * @param array $vids
 *   (optional) An array of entity IDs. If omitted, all entities are loaded.
723
 *
724
 * @return array
725 726
 *  An array of vocabulary objects, indexed by vid.
 */
727 728
function taxonomy_vocabulary_load_multiple(array $vids = NULL) {
  return entity_load_multiple('taxonomy_vocabulary', $vids);
729
}
730

731
/**
732
 * Sorts vocabularies by its weight and label.
733
 *
734
 * @param array $vocabularies
735
 *   An array of \Drupal\taxonomy\Entity\Vocabulary objects.
736
 */
737 738 739 740
function taxonomy_vocabulary_sort(array &$vocabularies = array()) {
  // @todo Remove error suppressing when http://drupal.org/node/1799600 is
  // fixed.
  @uasort($vocabularies, 'Drupal\Core\Config\Entity\ConfigEntityBase::sort');
741 742
}

743
/**
744
 * Return the taxonomy vocabulary entity matching a vocabulary ID.
745
 *
746 747
 * @deprecated use entity_load('taxonomy_vocabulary', $vid) instead.
 *
748 749
 * @param int $vid
 *   The vocabulary's ID.
750
 *
751
 * @return \Drupal\taxonomy\Entity\Vocabulary|null
752
 *   The taxonomy vocabulary entity, if exists, NULL otherwise. Results are
753
 *   statically cached.
754
 */
755 756
function taxonomy_vocabulary_load($vid) {
  return entity_load('taxonomy_vocabulary', $vid);
757 758
}

Dries's avatar
Dries committed
759
/**
760
 * Return the taxonomy term entity matching a term ID.
761
 *
762 763
 * @deprecated use entity_load('taxonomy_term', $tid) instead.
 *
764 765 766
 * @param $tid
 *   A term's ID
 *
767
 * @return \Drupal\taxonomy\Entity\Term|null
768
 *   A taxonomy term entity, or NULL if the term was not found. Results are
769
 *   statically cached.
Dries's avatar
Dries committed
770
 */
771
function taxonomy_term_load($tid) {
772
  if (!is_numeric($tid)) {
773
    return NULL;
774
  }
775
  return entity_load('taxonomy_term', $tid);
776 777
}

778 779 780 781 782 783 784 785 786
/**
 * Implements hook_file_download_access().
 */
function taxonomy_file_download_access($field, EntityInterface $entity, FileInterface $file) {
  if ($entity->entityType() == 'taxonomy_term') {
    return $entity->access('view');
  }
}

787
/**
788
 * Implodes a list of tags of a certain vocabulary into a string.
789 790
 *
 * @see drupal_explode_tags()
791 792 793 794 795
 */
function taxonomy_implode_tags($tags, $vid = NULL) {
  $typed_tags = array();
  foreach ($tags as $tag) {
    // Extract terms belonging to the vocabulary in question.
796
    if (!isset($vid) || $tag->bundle() == $vid) {
797
      // Make sure we have a completed loaded taxonomy term.
798
      if ($tag instanceof EntityInterface && $label = $tag->label()) {
799
        // Commas and quotes in tag names are special cases, so encode 'em.
800 801
        if (strpos($label, ',') !== FALSE || strpos($label, '"') !== FALSE) {
          $typed_tags[] = '"' . str_replace('"', '""', $label) . '"';
802 803
        }
        else {
804
          $typed_tags[] = $label;
805
        }
806 807 808
      }
    }
  }
809
  return implode(', ', $typed_tags);
810
}
811

812
/**
813
 * Implements hook_field_info().
814 815 816
 *
 * Field settings:
 * - allowed_values: a list array of one or more vocabulary trees:
817
 *   - vocabulary: a vocabulary machine name.
818 819 820 821 822 823 824
 *   - parent: a term ID of a term whose children are allowed. This should be
 *     '0' if all terms in a vocabulary are allowed. The allowed values do not
 *     include the parent term.
 *
 */
function taxonomy_field_info() {
  return array(
825 826
    'taxonomy_term_reference' => array(
      'label' => t('Term reference'),
827 828
      'description' => t('This field stores a reference to a taxonomy term.'),
      'default_widget' => 'options_select',
829
      'default_formatter' => 'taxonomy_term_reference_link',
830
      'class' => 'Drupal\taxonomy\Type\TaxonomyTermReferenceItem',
831
      'settings' => array(
832
        'options_list_callback' => NULL,
833 834
        'allowed_values' => array(
          array(
835
            'vocabulary' => '',
836 837 838 839
            'parent' => '0',
          ),
        ),
      ),
840
      'list_class' => '\Drupal\taxonomy\Plugin\Field\FieldType\TaxonomyTermReferenceFieldItemList',
841 842 843 844 845
    ),
  );
}

/**
846
 * Implements hook_field_widget_info_alter().
847 848
 */
function taxonomy_field_widget_info_alter(&$info) {
849 850
  $info['options_select']['field_types'][] = 'taxonomy_term_reference';
  $info['options_buttons']['field_types'][] = 'taxonomy_term_reference';
851 852
}

853 854 855
/**
 * Implements hook_options_list().
 */
856 857 858
function taxonomy_options_list(FieldDefinitionInterface $field_definition, EntityInterface $entity) {
  $function = $field_definition->getFieldSetting('options_list_callback') ?: 'taxonomy_allowed_values';
  return $function($field_definition, $entity);
859 860
}

861
/**
862
 * Implements hook_field_validate().
863
 *
864 865 866 867 868
 * Taxonomy field settings allow for either a single vocabulary ID, multiple
 * vocabulary IDs, or sub-trees of a vocabulary to be specified as allowed
 * values, although only the first of these is supported via the field UI.
 * Confirm that terms entered as values meet at least one of these conditions.
 *
869 870 871
 * Possible error codes:
 * - 'taxonomy_term_illegal_value': The value is not part of the list of allowed values.
 */
872
function taxonomy_field_validate(EntityInterface $entity = NULL, FieldInterface $field, FieldInstanceInterface $instance, $langcode, $items, &$errors) {
873
  // Build an array of existing term IDs so they can be loaded with
874
  // entity_load_multiple('taxonomy_term');
875
  foreach ($items as $delta => $item) {
876 877
    if (!empty($item['target_id']) && $item['target_id'] != 'autocreate') {
      $tids[] = $item['target_id'];
878 879 880
    }
  }
  if (!empty($tids)) {
881
    $terms = entity_load_multiple('taxonomy_term', $tids);
882

883 884
    // Check each existing item to ensure it can be found in the
    // allowed values for this field.
885 886
    foreach ($items as $delta => $item) {
      $validate = TRUE;
887
      if (!empty($item['target_id']) && $item['target_id'] != 'autocreate') {
888
        $validate = FALSE;
889
        foreach ($instance->getFieldSetting('allowed_values') as $settings) {
890
          // If no parent is specified, check if the term is in the vocabulary.
891
          if (isset($settings['vocabulary']) && empty($settings['parent'])) {
892
            if ($settings['vocabulary'] == $terms[$item['target_id']]->bundle()) {
893 894 895 896 897
              $validate = TRUE;
              break;
            }
          }
          // If a parent is specified, then to validate it must appear in the
898
          // array returned by taxonomy_term_load_parents_all().
899
          elseif (!empty($settings['parent'])) {
900
            $ancestors = taxonomy_term_load_parents_all($item['target_id']);
901
            foreach ($ancestors as $ancestor) {
902
              if ($ancestor->id() == $settings['parent']) {
903 904 905 906 907 908 909 910
                $validate = TRUE;
                break 2;
              }
            }
          }
        }
      }
      if (!$validate) {
911
        $errors[$instance->getFieldName()][$langcode][$delta][] = array(
912
          'error' => 'taxonomy_term_reference_illegal_value',
913
          'message' => t('%name: illegal value.', array('%name' => $instance->getFieldLabel())),
914 915 916 917 918 919 920
        );
      }
    }
  }
}

/**
921
 * Implements hook_field_is_empty().
922
 */
923
function taxonomy_field_is_empty($item, $field_type) {
924
  return !is_array($item) || (empty($item['target_id']) && empty($item['entity']));
925 926 927
}

/**
928
 * Returns the set of valid terms for a taxonomy field.
929
 *
930
 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
931
 *   The field definition.
932
 * @param \Drupal\Core\Entity\EntityInterface $entity
933
 *   The entity object the field is attached to.
934
 *
935 936
 * @return
 *   The array of valid terms for this field, keyed by term id.
937
 */
938
function taxonomy_allowed_values(FieldDefinitionInterface $field_definition, EntityInterface $entity) {
939
  $options = array();
940
  foreach ($field_definition->getFieldSetting('allowed_values') as $tree) {
941
    if ($vocabulary = entity_load('taxonomy_vocabulary', $tree['vocabulary'])) {
942
      if ($terms = taxonomy_get_tree($vocabulary->id(), $tree['parent'], NULL, TRUE)) {
943
        foreach ($terms as $term) {
944
          $options[$term->id()] = str_repeat('-', $term->depth) . $term->label();
945
        }
946 947 948 949 950 951
      }
    }
  }
  return $options;
}

952 953 954
/**
 * Title callback for term pages.
 *
955
 * @param \Drupal\taxonomy\Entity\Term $term
956
 *   A taxonomy term entity.
957
 *
958 959 960
 * @return
 *   The term name to be used as the page title.
 */
961
function taxonomy_term_title(Term $term) {
962
  return $term->label();
963
}
964 965

/**
966
 * Form element validate handler for taxonomy term autocomplete element.
967 968
 */
function taxonomy_autocomplete_validate($element, &$form_state) {
969
  // Split the values into an array.
970
  // @see \Drupal\taxonomy\Plugin\Field\FieldWidget\TaxonomyAutocompleteWidget:massageFormValues()
971
  $typed_terms = array();
972
  if ($tags = $element['#value']) {
973
    $typed_terms = drupal_explode_tags($tags);
974
  }
975
  form_set_value($element, $typed_terms, $form_state);
976 977
}

978
/**
979
 * Implements hook_field_settings_form().
980
 */
981
function taxonomy_field_settings_form($field, $instance) {
982
  // Get proper values for 'allowed_values_function', which is a core setting.
983
  $vocabularies = entity_load_multiple('taxonomy_vocabulary');
984 985
  $options = array();
  foreach ($vocabularies as $vocabulary) {
986
    $options[$vocabulary->id()] = $vocabulary->name;
987 988 989 990 991
  }
  $form['allowed_values'] = array(
    '#tree' => TRUE,
  );

992
  foreach ($field->getFieldSetting('allowed_values') as $delta => $tree) {
993
    $form['allowed_values'][$delta]['vocabulary'] = array(
994 995
      '#type' => 'select',
      '#title' => t('Vocabulary'),
996
      '#default_value' => $tree['vocabulary'],
997 998 999
      '#options' => $options,
      '#required' => TRUE,
      '#description' => t('The vocabulary which supplies the options for this field.'),
1000
      '#disabled' => $field->hasData(),
1001 1002 1003 1004 1005 1006 1007 1008 1009
    );
    $form['allowed_values'][$delta]['parent'] = array(
      '#type' => 'value',
      '#value' => $tree['parent'],
    );
  }

  return $form;
}
1010 1011

/**
1012
 * @defgroup taxonomy_index Taxonomy indexing
1013 1014
 * @{
 * Functions to maintain taxonomy indexing.
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
 *
 * 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,
 * published nodes and common sort criteria such as sticky and created.
 * This is used as a lookup table by taxonomy_select_nodes(). When using other
 * field storage engines or alternative methods of denormalizing this data
1025 1026
 * you should set the taxonomy.settings:maintain_index_table to '0' to avoid
 * unnecessary writes in SQL.
1027 1028
 */

1029 1030 1031 1032 1033
/**
 * Implements hook_field_presave().
 *
 * Create any new terms defined in a freetagging vocabulary.
 */
1034
function taxonomy_field_presave(EntityInterface $entity, $field, $instance, $langcode, &$items) {
1035
  foreach ($items as $delta => $item) {
1036
    if (!$item['target_id'] && isset($item['target_id'])) {
1037
      $item['entity']->save();
1038
      $items[$delta]['target_id'] = $item['entity']->id();
1039 1040 1041 1042
    }
  }
}

1043
/**
1044
 * Implements hook_node_insert().
1045
 */
1046
function taxonomy_node_insert(EntityInterface $node) {
1047 1048
  // Add taxonomy index entries for the node.
  taxonomy_build_node_index($node);
1049 1050 1051
}

/**
1052 1053 1054 1055 1056
 * 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.
 *
1057
 * @param \Drupal\node\Entity\Node $node
1058
 *   The node entity.
1059
 */
1060 1061 1062
function taxonomy_build_node_index($node) {
  // We maintain a denormalized table of term/node relationships, containing
  // only data for current, published nodes.
1063
  if (!\Drupal::config('taxonomy.settings')->get('maintain_index_table') || !(\Drupal::entityManager()->getStorageController('node') instanceof FieldableDatabaseStorageController)) {
1064
    return;
1065
  }
1066 1067 1068

  $status = $node->isPublished();
  $sticky = (int) $node->isSticky();
1069
  // We only maintain the taxonomy index for published nodes.
1070
  if ($status && $node->isDefaultRevision()) {
1071 1072
    // Collect a unique list of all the term IDs from all node fields.
    $tid_all = array();
1073
    foreach (field_info_instances('node', $node->getType()) as $instance) {
1074 1075
      $field = $instance->getField();
      $field_name = $field->getFieldName();
1076
      if ($field->module == 'taxonomy') {
1077 1078 1079 1080
        foreach ($node->getTranslationLanguages() as $language) {
          foreach ($node->getTranslation($language->id)->$field_name as $item) {
            if (!$item->isEmpty()) {
              $tid_all[$item->target_id] = $item->target_id;
1081 1082 1083 1084 1085 1086 1087
            }
          }
        }
      }
    }
    // Insert index entries for all the node's terms.
    if (!empty($tid_all)) {
1088
      $query = db_insert('taxonomy_index')->fields(array('nid', 'tid', 'sticky', 'created'));
1089
      foreach ($tid_all as $tid) {
1090
        $query->values(array(
1091
          'nid' => $node->id(),
1092 1093
          'tid' => $tid,
          'sticky' => $sticky,
1094
          'created' => $node->getCreatedTime(),
1095 1096 1097 1098 1099 1100 1101
        ));
      }
      $query->execute();
    }
  }
}

1102 1103 1104
/**
 * Implements hook_node_update().
 */
1105
function taxonomy_node_update(EntityInterface $node) {
1106 1107 1108 1109 1110
  // Always rebuild the node's taxonomy index entries on node save.
  taxonomy_delete_node_index($node);
  taxonomy_build_node_index($node);
}

1111
/**
1112
 * Implements hook_node_predelete().
1113
 */