taxonomy.module 50.7 KB
Newer Older
Dries's avatar
 
Dries committed
1
<?php
Dries's avatar
 
Dries committed
2

Dries's avatar
 
Dries committed
3 4 5 6 7
/**
 * @file
 * Enables the organization of content into categories.
 */

8 9 10
use Drupal\node\Plugin\Core\Entity\Node;
use Drupal\taxonomy\Plugin\Core\Entity\Term;
use Drupal\taxonomy\Plugin\Core\Entity\Vocabulary;
11
use Drupal\Core\Entity\EntityInterface;
12

13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/**
 * 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;

28 29 30 31 32 33 34 35
/**
 * 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().
 */

36
/**
37
 * Implements hook_help().
38 39 40 41 42 43
 */
function taxonomy_help($path, $arg) {
  switch ($path) {
    case 'admin/help#taxonomy':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
44
      $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>';
45 46 47
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Creating vocabularies') . '</dt>';
48
      $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'))));
49
      $output .= '<ul><li>' . t('<em>vocabulary</em>: Music') . '</li>';
50 51 52 53 54 55 56 57 58
      $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>';
59
      $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>';
60
      $output .= '<dt>' . t('Classifying content') . '</dt>';
61
      $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>';
62 63 64 65 66 67 68
      $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':
69
      $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>';
70 71
      return $output;
    case 'admin/structure/taxonomy/%':
72
      $vocabulary = taxonomy_vocabulary_load($arg[3]);
73
      switch ($vocabulary->hierarchy) {
74
        case TAXONOMY_HIERARCHY_DISABLED:
75
          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>';
76
        case TAXONOMY_HIERARCHY_SINGLE:
77
          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>';
78
        case TAXONOMY_HIERARCHY_MULTIPLE:
79
          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>';
80 81 82 83
      }
  }
}

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

108
/**
109
 * Implements hook_entity_info().
110
 */
111
function taxonomy_entity_info(&$info) {
112 113 114 115
  foreach (taxonomy_vocabulary_get_names() as $id) {
    $config = config('taxonomy.vocabulary.' . $id);
    $info['taxonomy_term']['bundles'][$id] = array(
      'label' => $config->get('name'),
116
      'admin' => array(
117 118
        'path' => 'admin/structure/taxonomy/%taxonomy_vocabulary',
        'real path' => 'admin/structure/taxonomy/' . $id,
119 120 121 122
        'bundle argument' => 3,
      ),
    );
  }
123 124
}

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

134 135 136 137 138
/**
 * Implements hook_field_extra_fields().
 */
function taxonomy_field_extra_fields() {
  $return = array();
139 140 141
  $info = entity_get_info('taxonomy_term');
  foreach (array_keys($info['bundles']) as $bundle) {
    $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 (!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
    'taxonomy_overview_vocabularies' => array(
228
      'render element' => 'form',
229 230
    ),
    'taxonomy_overview_terms' => array(
231
      'render element' => 'form',
232
    ),
233 234 235 236
    'taxonomy_term' => array(
      'render element' => 'elements',
      'template' => 'taxonomy-term',
    ),
237 238 239
  );
}

Dries's avatar
 
Dries committed
240
/**
241
 * Implements hook_menu().
Dries's avatar
 
Dries committed
242
 */
243
function taxonomy_menu() {
244
  $items['admin/structure/taxonomy'] = array(
245 246
    'title' => 'Taxonomy',
    'description' => 'Manage tagging, categorization, and classification of your content.',
247 248
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_overview_vocabularies'),
249
    'access arguments' => array('administer taxonomy'),
250
    'file' => 'taxonomy.admin.inc',
251
  );
252
  $items['admin/structure/taxonomy/list'] = array(
253
    'title' => 'List',
254 255 256
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
257
  $items['admin/structure/taxonomy/add'] = array(
258
    'title' => 'Add vocabulary',
259
    'page callback' => 'taxonomy_vocabulary_add',
260
    'access arguments' => array('administer taxonomy'),
261
    'type' => MENU_LOCAL_ACTION,
262
    'file' => 'taxonomy.admin.inc',
263 264
  );

265
  $items['taxonomy/term/%taxonomy_term'] = array(
266
    'title' => 'Taxonomy term',
267 268
    'title callback' => 'taxonomy_term_title',
    'title arguments' => array(2),
269 270 271
    'page callback' => 'taxonomy_term_page',
    'page arguments' => array(2),
    'access arguments' => array('access content'),
272
    'file' => 'taxonomy.pages.inc',
273
  );
274
  $items['taxonomy/term/%taxonomy_term/view'] = array(
275 276
    'title' => 'View',
    'type' => MENU_DEFAULT_LOCAL_TASK,
277
  );
278
  $items['taxonomy/term/%taxonomy_term/edit'] = array(
279
    'title' => 'Edit',
280
    'page callback' => 'entity_get_form',
281
    // Pass a NULL argument to ensure that additional path components are not
282 283
    // passed to taxonomy_term_form() as the vocabulary machine name argument.
    'page arguments' => array(2),
284 285
    'access callback' => 'taxonomy_term_access',
    'access arguments' => array('edit', 2),
286 287
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
288
    'file' => 'taxonomy.admin.inc',
289
  );
290 291 292 293 294 295 296 297 298 299
  $items['taxonomy/term/%taxonomy_term/delete'] = array(
    'title' => 'Delete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_term_confirm_delete', 2),
    'access callback' => 'taxonomy_term_access',
    'access arguments' => array('delete', 2),
    'type' => MENU_LOCAL_TASK,
    'weight' => 11,
    'file' => 'taxonomy.admin.inc',
  );
300 301 302 303 304 305 306 307
  $items['taxonomy/term/%taxonomy_term/feed'] = array(
    'title' => 'Taxonomy term',
    'title callback' => 'taxonomy_term_title',
    'title arguments' => array(2),
    'page callback' => 'taxonomy_term_feed',
    'page arguments' => array(2),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
308
    'file' => 'taxonomy.pages.inc',
309
  );
310
  $items['taxonomy/autocomplete/%'] = array(
311
    'title' => 'Autocomplete taxonomy',
312
    'page callback' => 'taxonomy_autocomplete',
313
    'page arguments' => array(2),
314 315
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
316
    'file' => 'taxonomy.pages.inc',
317
  );
318

319
  $items['admin/structure/taxonomy/%taxonomy_vocabulary'] = array(
320
    'title callback' => 'entity_page_label',
321
    'title arguments' => array(3),
322 323
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_overview_terms', 3),
324
    'access arguments' => array('administer taxonomy'),
325
    'file' => 'taxonomy.admin.inc',
326
  );
327
  $items['admin/structure/taxonomy/%taxonomy_vocabulary/list'] = array(
328
    'title' => 'List',
329
    'type' => MENU_DEFAULT_LOCAL_TASK,
330 331
    'weight' => -20,
  );
332
  $items['admin/structure/taxonomy/%taxonomy_vocabulary/edit'] = array(
333
    'title' => 'Edit',
334 335
    'page callback' => 'entity_get_form',
    'page arguments' => array(3),
336 337
    'access arguments' => array('administer taxonomy'),
    'type' => MENU_LOCAL_TASK,
338
    'weight' => -10,
339
    'file' => 'taxonomy.admin.inc',
340
  );
341

342
  $items['admin/structure/taxonomy/%taxonomy_vocabulary/add'] = array(
343
    'title' => 'Add term',
344 345
    'page callback' => 'taxonomy_term_add',
    'page arguments' => array(3),
346
    'access arguments' => array('administer taxonomy'),
347
    'type' => MENU_LOCAL_ACTION,
348
    'file' => 'taxonomy.admin.inc',
349
  );
Dries's avatar
 
Dries committed
350

Dries's avatar
 
Dries committed
351 352
  return $items;
}
Dries's avatar
 
Dries committed
353

354 355 356 357 358 359
/**
 * Implements hook_admin_paths().
 */
function taxonomy_admin_paths() {
  $paths = array(
    'taxonomy/term/*/edit' => TRUE,
360
    'taxonomy/term/*/delete' => TRUE,
361 362
    'taxonomy/term/*/translations' => TRUE,
    'taxonomy/term/*/translations/*' => TRUE,
363 364 365 366
  );
  return $paths;
}

367
/**
368 369 370 371 372 373 374 375 376 377 378 379 380 381
 * Access callback: Checks a user's permission for performing a taxonomy term
 * operation.
 *
 * @param $op
 *   The operation to be performed on the taxonomy term. Possible values are:
 *   - "edit"
 *   - "delete"
 * @param $term
 *   The $term object on which the operation is to be performed.
 *
 * @return
 *   TRUE if the operation may be performed, FALSE otherwise.
 *
 * @see taxonomy_menu()
382
 */
383 384 385 386 387 388 389
function taxonomy_term_access($op, $term) {
  if (!$term || !in_array($op, array('edit', 'delete'), TRUE)) {
    // If there was no term to check against, or the $op was not one of the
    // supported ones, we return access denied.
    return FALSE;
  }

390
  return user_access("$op terms in {$term->bundle()}") || user_access('administer taxonomy');
391 392
}

393
/**
394 395
 * Saves a vocabulary.
 *
396
 * @param Drupal\taxonomy\Plugin\Core\Entity\Vocabulary $vocabulary
397
 *   The taxonomy vocabulary entity to be saved.
398
 */
399
function taxonomy_vocabulary_save(Vocabulary $vocabulary) {
400
  return $vocabulary->save();
Kjartan's avatar
Kjartan committed
401
}
Dries's avatar
 
Dries committed
402

403
/**
404
 * Deletes a vocabulary.
405 406 407
 *
 * @param $vid
 *   A vocabulary ID.
408
 *
409
 */
410
function taxonomy_vocabulary_delete($vid) {
411 412
  taxonomy_vocabulary_delete_multiple(array($vid));
}
413

414 415 416 417 418 419 420 421
/**
 * Deletes vocabularies.
 *
 * @param $vids
 *   The vocabulary ids.
 */
function taxonomy_vocabulary_delete_multiple(array $vids) {
  entity_delete_multiple('taxonomy_vocabulary', $vids);
Dries's avatar
 
Dries committed
422 423
}

424
/**
425
 * Checks and updates the hierarchy flag of a vocabulary.
426
 *
427
 * Checks the current parents of all terms in a vocabulary and updates the
428
 * vocabulary's hierarchy setting to the lowest possible level. If no term
429 430 431 432 433
 * 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.
434
 *
435
 * @param Drupal\taxonomy\Plugin\Core\Entity\Vocabulary $vocabulary
436
 *   A taxonomy vocabulary entity.
437 438
 * @param $changed_term
 *   An array of the term structure that was updated.
439 440 441
 *
 * @return
 *   An integer that represents the level of the vocabulary's hierarchy.
442
 */
443
function taxonomy_check_vocabulary_hierarchy(Vocabulary $vocabulary, $changed_term) {
444
  $tree = taxonomy_get_tree($vocabulary->id());
445
  $hierarchy = TAXONOMY_HIERARCHY_DISABLED;
446
  foreach ($tree as $term) {
447
    // Update the changed term with the new parent value before comparison.
448
    if ($term->tid == $changed_term['tid']) {
449
      $term = (object) $changed_term;
450 451 452 453
      $term->parents = $term->parent;
    }
    // Check this term's parent count.
    if (count($term->parents) > 1) {
454
      $hierarchy = TAXONOMY_HIERARCHY_MULTIPLE;
455 456
      break;
    }
457
    elseif (count($term->parents) == 1 && !isset($term->parents[0])) {
458
      $hierarchy = TAXONOMY_HIERARCHY_SINGLE;
459 460
    }
  }
461 462 463
  if ($hierarchy != $vocabulary->hierarchy) {
    $vocabulary->hierarchy = $hierarchy;
    taxonomy_vocabulary_save($vocabulary);
464 465 466 467 468
  }

  return $hierarchy;
}

469
/**
470
 * Saves a term object to the database.
471
 *
472
 * @param Drupal\taxonomy\Plugin\Core\Entity\Term $term
473
 *   The taxonomy term entity to be saved.
474
 *
475
 * @return
476 477 478
 *   Status constant indicating whether term was inserted (SAVED_NEW) or updated
 *   (SAVED_UPDATED). When inserting a new term, $term->tid will contain the
 *   term ID of the newly created term.
479
 */
480
function taxonomy_term_save(Term $term) {
481
  return $term->save();
Kjartan's avatar
Kjartan committed
482
}
Dries's avatar
 
Dries committed
483

484
/**
485
 * Deletes a term.
486 487 488 489
 *
 * @param $tid
 *   The term ID.
 */
490
function taxonomy_term_delete($tid) {
491 492
  taxonomy_term_delete_multiple(array($tid));
}
Dries's avatar
 
Dries committed
493

494 495 496 497 498 499 500 501
/**
 * Deletes taxonomy terms.
 *
 * @param $tids
 *   The term ids to be deleted.
 */
function taxonomy_term_delete_multiple(array $tids) {
  entity_delete_multiple('taxonomy_term', $tids);
Dries's avatar
 
Dries committed
502 503
}

504
/**
505
 * Generates an array which displays a term detail page.
506
 *
507
 * @param Drupal\taxonomy\Plugin\Core\Entity\Term $term
508 509
 *   A taxonomy term object.
 * @param string $view_mode
510
 *   View mode, e.g. 'full', 'teaser'...
511
 * @param string $langcode
512 513
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
514
 *
515
 * @return array
516
 *   A $page element suitable for use by drupal_page_render().
517
 */
518 519
function taxonomy_term_view(Term $term, $view_mode = 'full', $langcode = NULL) {
  return entity_view($term, $view_mode, $langcode);
520
}
521

522 523
 /**
 * Constructs a drupal_render() style array from an array of loaded terms.
524
 *
525 526
 * @param array $terms
 *   An array of taxonomy terms as returned by taxonomy_term_load_multiple().
527 528 529 530 531 532
 * @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.
 *
533 534
 * @return array
 *   An array in the format expected by drupal_render().
535
 */
536 537
function taxonomy_term_view_multiple(array $terms, $view_mode = 'full', $langcode = NULL) {
  return entity_view_multiple($terms, $view_mode, $langcode);
538 539 540 541 542 543 544 545 546 547
}

/**
 * Process variables for taxonomy-term.tpl.php.
 */
function template_preprocess_taxonomy_term(&$variables) {
  $variables['view_mode'] = $variables['elements']['#view_mode'];
  $variables['term'] = $variables['elements']['#term'];
  $term = $variables['term'];

548
  $uri = $term->uri();
549 550
  $variables['url']  = url($uri['path'], $uri['options']);
  $variables['label'] = check_plain($term->label());
551
  $variables['page']      = $variables['view_mode'] == 'full' && taxonomy_term_is_page($term);
552 553

  // Helpful $content variable for templates.
554
  $variables['content'] = array();
555 556 557 558 559 560 561 562
  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.
563
  field_attach_preprocess($term, $variables['content'], $variables);
564

565
  // Gather classes, and clean up name so there are no underscores.
566
  $vocabulary_name_css = str_replace('_', '-', $term->bundle());
567
  $variables['attributes']['class'][] = 'vocabulary-' . $vocabulary_name_css;
568

569
  $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->bundle();
570
  $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->tid;
571 572 573
}

/**
574
 * Returns whether the current page is the page of the passed-in term.
575
 *
576
 * @param Drupal\taxonomy\Plugin\Core\Entity\Term $term
577
 *   A taxonomy term entity.
578
 */
579
function taxonomy_term_is_page(Term $term) {
580 581 582 583
  $page_term = menu_get_object('taxonomy_term', 2);
  return (!empty($page_term) ? $page_term->tid == $term->tid : FALSE);
}

584
/**
585
 * Clear all static cache variables for terms.
586 587
 */
function taxonomy_terms_static_reset() {
588
  entity_get_controller('taxonomy_term')->resetCache();
589 590
}

591 592
/**
 * Clear all static cache variables for vocabularies.
593
 *
594
 * @param $ids
595
 *   An array of ids to reset in entity controller cache.
596
 */
597
function taxonomy_vocabulary_static_reset(array $ids = NULL) {
598 599 600
  entity_get_controller('taxonomy_vocabulary')->resetCache($ids);
}

601 602 603
/**
 * Get names for all taxonomy vocabularies.
 *
604 605
 * @return array
 *   A list of existing vocabulary IDs.
606 607
 */
function taxonomy_vocabulary_get_names() {
608 609 610
  $names = &drupal_static(__FUNCTION__);

  if (!isset($names)) {
611 612 613 614 615 616
    $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;
    }
617
  }
618

619 620 621
  return $names;
}

Dries's avatar
 
Dries committed
622
/**
623 624 625 626 627 628
 * Finds all parents of a given term ID.
 *
 * @param $tid
 *   A taxonomy term ID.
 *
 * @return
629 630
 *   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
631
 */
632
function taxonomy_term_load_parents($tid) {
633 634 635 636 637 638 639 640 641 642 643 644
  $parents = &drupal_static(__FUNCTION__, array());

  if ($tid && !isset($parents[$tid])) {
    $query = db_select('taxonomy_term_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.parent = t.tid');
    $query->addField('t', 'tid');
    $query->condition('h.tid', $tid);
    $query->addTag('term_access');
    $query->orderBy('t.weight');
    $query->orderBy('t.name');
    $tids = $query->execute()->fetchCol();
    $parents[$tid] = taxonomy_term_load_multiple($tids);
Kjartan's avatar
Kjartan committed
645
  }
646 647

  return isset($parents[$tid]) ? $parents[$tid] : array();
Kjartan's avatar
Kjartan committed
648
}
Dries's avatar
 
Dries committed
649

Dries's avatar
 
Dries committed
650 651 652
/**
 * Find all ancestors of a given term ID.
 */
653
function taxonomy_term_load_parents_all($tid) {
654 655 656 657 658 659
  $cache = &drupal_static(__FUNCTION__, array());

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

Dries's avatar
 
Dries committed
660
  $parents = array();
661 662
  if ($term = taxonomy_term_load($tid)) {
    $parents[] = $term;
Dries's avatar
 
Dries committed
663
    $n = 0;
664
    while ($parent = taxonomy_term_load_parents($parents[$n]->tid)) {
Dries's avatar
 
Dries committed
665 666 667 668
      $parents = array_merge($parents, $parent);
      $n++;
    }
  }
669 670 671

  $cache[$tid] = $parents;

Dries's avatar
 
Dries committed
672 673 674
  return $parents;
}

Dries's avatar
 
Dries committed
675
/**
676 677 678 679 680 681 682 683
 * 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
684 685
 *   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
686
 */
687
function taxonomy_term_load_children($tid, $vid = NULL) {
688 689 690
  $children = &drupal_static(__FUNCTION__, array());

  if ($tid && !isset($children[$tid])) {
691 692
    $query = db_select('taxonomy_term_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
693 694
    $query->addField('t', 'tid');
    $query->condition('h.parent', $tid);
695 696 697
    if ($vid) {
      $query->condition('t.vid', $vid);
    }
698 699 700 701 702
    $query->addTag('term_access');
    $query->orderBy('t.weight');
    $query->orderBy('t.name');
    $tids = $query->execute()->fetchCol();
    $children[$tid] = taxonomy_term_load_multiple($tids);
Kjartan's avatar
Kjartan committed
703
  }
704 705

  return isset($children[$tid]) ? $children[$tid] : array();
Kjartan's avatar
Kjartan committed
706
}
Dries's avatar
 
Dries committed
707

Dries's avatar
 
Dries committed
708 709 710 711
/**
 * Create a hierarchical representation of a vocabulary.
 *
 * @param $vid
712
 *   The vocabulary ID to generate the tree for.
Dries's avatar
 
Dries committed
713 714 715
 * @param $parent
 *   The term ID under which to generate the tree. If 0, generate the tree
 *   for the entire vocabulary.
Dries's avatar
 
Dries committed
716 717
 * @param $max_depth
 *   The number of levels of the tree to return. Leave NULL to return all levels.
718 719 720 721 722
 * @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.
723
 *
Dries's avatar
 
Dries committed
724 725 726
 * @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.
727 728
 *   Results are statically cached. Term objects will be partial or complete
 *   depending on the $load_entities parameter.
Dries's avatar
 
Dries committed
729
 */
730
function taxonomy_get_tree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE) {
731
  $children = &drupal_static(__FUNCTION__, array());
732 733
  $parents = &drupal_static(__FUNCTION__ . ':parents', array());
  $terms = &drupal_static(__FUNCTION__ . ':terms', array());
734

735 736
  // 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
737 738
  if (!isset($children[$vid])) {
    $children[$vid] = array();
739 740
    $parents[$vid] = array();
    $terms[$vid] = array();
Dries's avatar
 
Dries committed
741

742 743
    $query = db_select('taxonomy_term_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
744 745 746 747 748 749 750 751 752 753 754 755 756 757
    $result = $query
      ->addTag('translatable')
      ->addTag('term_access')
      ->fields('t')
      ->fields('h', array('parent'))
      ->condition('t.vid', $vid)
      ->orderBy('t.weight')
      ->orderBy('t.name')
      ->execute();

    foreach ($result as $term) {
      $children[$vid][$term->parent][] = $term->tid;
      $parents[$vid][$term->tid][] = $term->parent;
      $terms[$vid][$term->tid] = $term;
Dries's avatar
 
Dries committed
758 759
    }
  }
Dries's avatar
 
Dries committed
760

761 762 763 764 765 766
  // Load full entities, if necessary. The entity controller statically
  // caches the results.
  if ($load_entities) {
    $term_entities = taxonomy_term_load_multiple(array_keys($terms[$vid]));
  }

767
  $max_depth = (!isset($max_depth)) ? count($children[$vid]) : $max_depth;
768
  $tree = array();
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788

  // 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];
789 790 791
        if (isset($parents[$vid][$term->tid])) {
          // Clone the term so that the depth attribute remains correct
          // in the event of multiple parents.
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
          $term = clone $term;
        }
        $term->depth = $depth;
        unset($term->parent);
        $term->parents = $parents[$vid][$term->tid];
        $tree[] = $term;
        if (!empty($children[$vid][$term->tid])) {
          $has_children = TRUE;

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

          // Reset pointers for child lists because we step in there more often
          // with multi parents.
          reset($children[$vid][$term->tid]);
          // 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]);
Dries's avatar
 
Dries committed
819
      }
Dries's avatar
 
Dries committed
820
    }
Kjartan's avatar
Kjartan committed
821
  }
Dries's avatar
 
Dries committed
822

823
  return $tree;
Kjartan's avatar
Kjartan committed
824
}
Dries's avatar
 
Dries committed
825

Dries's avatar
 
Dries committed
826
/**
Dries's avatar
 
Dries committed
827
 * Try to map a string to an existing term, as for glossary use.
Dries's avatar
 
Dries committed
828
 *
Dries's avatar
 
Dries committed
829 830 831
 * Provides a case-insensitive and trimmed mapping, to maximize the
 * likelihood of a successful match.
 *
832
 * @param $name
Dries's avatar
 
Dries committed
833
 *   Name of the term to search for.
834 835
 * @param $vocabulary
 *   (optional) Vocabulary machine name to limit the search. Defaults to NULL.
Dries's avatar
 
Dries committed
836 837 838
 *
 * @return
 *   An array of matching term objects.
Dries's avatar
 
Dries committed
839
 */
840
function taxonomy_term_load_multiple_by_name($name, $vocabulary = NULL) {
841
  $values = array('name' => trim($name));
842 843 844
  if (isset($vocabulary)) {
    $vocabularies = taxonomy_vocabulary_get_names();
    if (isset($vocabularies[$vocabulary])){
845
      $values['vid'] = $vocabulary;
846 847 848 849 850 851
    }
    else {
      // Return an empty array when filtering by a non-existing vocabulary.
      return array();
    }
  }
852
  return entity_load_multiple_by_properties('taxonomy_term', $values);
Dries's avatar
 
Dries committed
853 854
}

855 856 857 858 859 860 861
/**
 * 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.
 *
862
 * @see entity_load_multiple()
863
 * @see Drupal\Core\Entity\Query\EntityQueryInterface
864
 *
865 866
 * @param array $tids
 *   (optional) An array of entity IDs. If omitted, all entities are loaded.
867
 *
868
 * @return array
869 870
 *   An array of taxonomy term entities, indexed by tid. When no results are
 *   found, an empty array is returned.
871
 */
872 873
function taxonomy_term_load_multiple(array $tids = NULL) {
  return entity_load_multiple('taxonomy_term', $tids);
874
}
875

876
/**
877
 * Loads multiple taxonomy vocabularies based on certain conditions.
878 879 880 881 882
 *
 * 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.
 *
883
 * @see entity_load_multiple()
884
 *
885 886
 * @param array $vids
 *   (optional) An array of entity IDs. If omitted, all entities are loaded.
887
 *
888
 * @return array
889 890
 *  An array of vocabulary objects, indexed by vid.
 */
891 892
function taxonomy_vocabulary_load_multiple(array $vids = NULL) {
  return entity_load_multiple('taxonomy_vocabulary', $vids);
893
}
894

895
/**
896
 * Sorts vocabularies by its weight and label.