Skip to content
taxonomy.module 56.4 KiB
Newer Older
Dries Buytaert's avatar
Dries Buytaert committed
<?php
Dries Buytaert's avatar
 
Dries Buytaert committed

Dries Buytaert's avatar
 
Dries Buytaert committed
/**
 * @file
 * Enables the organization of content into categories.
 */

use Drupal\taxonomy\Term;
use Drupal\taxonomy\Vocabulary;
/**
 * 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;

/**
 * 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().
 */

 */
function taxonomy_help($path, $arg) {
  switch ($path) {
    case 'admin/help#taxonomy':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $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>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Creating vocabularies') . '</dt>';
      $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'))));
      $output .= '<ul><li>' . t('<em>vocabulary</em>: Music') . '</li>';
      $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>';
      $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>';
      $output .= '<dt>' . t('Classifying content') . '</dt>';
      $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>';
      $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':
      $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>';
      return $output;
    case 'admin/structure/taxonomy/%':
      $vocabulary = taxonomy_vocabulary_machine_name_load($arg[3]);
          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>';
          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>';
          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>';
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
function taxonomy_permission() {
      'title' => t('Administer vocabularies and terms'),
  foreach (taxonomy_vocabulary_load_multiple() as $vocabulary) {
    $permissions += array(
      'edit terms in ' . $vocabulary->vid => array(
        'title' => t('Edit terms in %vocabulary', array('%vocabulary' => $vocabulary->name)),
      ),
    );
    $permissions += array(
       'delete terms in ' . $vocabulary->vid => array(
         'title' => t('Delete terms from %vocabulary', array('%vocabulary' => $vocabulary->name)),
Kjartan Mannes's avatar
Kjartan Mannes committed
}
Dries Buytaert's avatar
Dries Buytaert committed

  $return = array(
    'taxonomy_term' => array(
      'entity class' => 'Drupal\taxonomy\Term',
      'controller class' => 'Drupal\taxonomy\TermStorageController',
      'form controller class' => array(
        'default' => 'Drupal\taxonomy\TermFormController',
      ),
        'id' => 'tid',
        'bundle' => 'vocabulary_machine_name',
      ),
      'bundle keys' => array(
        'bundle' => 'machine_name',
      ),
      'bundles' => array(),
      'view modes' => array(
        // @todo View mode for display as a field (when attached to nodes etc).
        'full' => array(
          'label' => t('Taxonomy term page'),
  foreach (taxonomy_vocabulary_get_names() as $machine_name => $vocabulary) {
    $return['taxonomy_term']['bundles'][$machine_name] = array(
      'label' => $vocabulary->name,
      'admin' => array(
        'path' => 'admin/structure/taxonomy/%taxonomy_vocabulary_machine_name',
        'real path' => 'admin/structure/taxonomy/' . $machine_name,
        'bundle argument' => 3,
        'access arguments' => array('administer taxonomy'),
      ),
    );
  }
  $return['taxonomy_vocabulary'] = array(
    'label' => t('Taxonomy vocabulary'),
    'entity class' => 'Drupal\taxonomy\Vocabulary',
    'controller class' => 'Drupal\taxonomy\VocabularyStorageController',
    'form controller class' => array(
      'default' => 'Drupal\taxonomy\VocabularyFormController',
    ),
function taxonomy_term_uri($term) {
  return array(
    'path' => 'taxonomy/term/' . $term->tid,
  );
/**
 * Implements hook_field_extra_fields().
 */
function taxonomy_field_extra_fields() {
  $return = array();
  $info = entity_get_info('taxonomy_term');
  foreach (array_keys($info['bundles']) as $bundle) {
    $return['taxonomy_term'][$bundle] = array(
      '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,
        ),
/**
 * 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.
 *
 * @param $pager
 *   Boolean to indicate whether a pager should be used.
 * @param $limit
 *   Integer. The maximum number of nodes to find.
 *   Set to FALSE for no limit.
 *   An array of fields and directions.
 *
 * @return
 *   An array of nids matching the query.
 */
function taxonomy_select_nodes($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC')) {
  if (!variable_get('taxonomy_maintain_index_table', TRUE)) {
    return array();
  }
  $query = db_select('taxonomy_index', 't');
  $query->addTag('node_access');
  $query->addMetaData('base_table', 'taxonomy_index');
  if ($pager) {
    $count_query = clone $query;
    $count_query->addExpression('COUNT(t.nid)');

    $query = $query->extend('Drupal\Core\Database\Query\PagerSelectExtender');
    if ($limit !== FALSE) {
      $query = $query->limit($limit);
    }
    if ($limit !== FALSE) {
      $query->range(0, $limit);
    }
  }
  $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();
}

    'taxonomy_overview_vocabularies' => array(
    ),
    'taxonomy_overview_terms' => array(
    'taxonomy_term' => array(
      'render element' => 'elements',
      'template' => 'taxonomy-term',
    ),
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
    'title' => 'Taxonomy',
    'description' => 'Manage tagging, categorization, and classification of your content.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_overview_vocabularies'),
    'access arguments' => array('administer taxonomy'),
  $items['admin/structure/taxonomy/list'] = array(
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
    'page callback' => 'taxonomy_vocabulary_add',
    'access arguments' => array('administer taxonomy'),
  $items['taxonomy/term/%taxonomy_term'] = array(
    'title callback' => 'taxonomy_term_title',
    'title arguments' => array(2),
    'page callback' => 'taxonomy_term_page',
    'page arguments' => array(2),
    'access arguments' => array('access content'),
  $items['taxonomy/term/%taxonomy_term/view'] = array(
    'title' => 'View',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  $items['taxonomy/term/%taxonomy_term/edit'] = array(
    'page callback' => 'entity_get_form',
    // Pass a NULL argument to ensure that additional path components are not
    // passed to taxonomy_term_form() as the vocabulary machine name argument.
    'page arguments' => array(2),
    'access callback' => 'taxonomy_term_access',
    'access arguments' => array('edit', 2),
    'file' => 'taxonomy.admin.inc',
  $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',
  );
  $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,
  $items['taxonomy/autocomplete'] = array(
    'page callback' => 'taxonomy_autocomplete',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name'] = array(
    'title callback' => 'entity_page_label',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_overview_terms', 3),
    'access arguments' => array('administer taxonomy'),
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/list'] = array(
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/edit'] = array(
    'page callback' => 'entity_get_form',
    'page arguments' => array(3),
    'access arguments' => array('administer taxonomy'),
    'type' => MENU_LOCAL_TASK,
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/add'] = array(
    'page callback' => 'taxonomy_term_add',
    'page arguments' => array(3),
    'access arguments' => array('administer taxonomy'),
Dries Buytaert's avatar
 
Dries Buytaert committed

Dries Buytaert's avatar
 
Dries Buytaert committed
  return $items;
}
Dries Buytaert's avatar
Dries Buytaert committed

/**
 * Implements hook_admin_paths().
 */
function taxonomy_admin_paths() {
  $paths = array(
    'taxonomy/term/*/edit' => TRUE,
 * 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()
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;
  }

  return user_access("$op terms in $term->vid") || user_access('administer taxonomy');
 * @param Drupal\taxonomy\Vocabulary $vocabulary
 *   The taxonomy vocabulary entity to be saved.
function taxonomy_vocabulary_save(Vocabulary $vocabulary) {
Kjartan Mannes's avatar
Kjartan Mannes committed
}
Dries Buytaert's avatar
Dries Buytaert committed

  taxonomy_vocabulary_delete_multiple(array($vid));
}
/**
 * Deletes vocabularies.
 *
 * @param $vids
 *   The vocabulary ids.
 */
function taxonomy_vocabulary_delete_multiple(array $vids) {
  entity_delete_multiple('taxonomy_vocabulary', $vids);
Dries Buytaert's avatar
 
Dries Buytaert committed
}

 * Implements hook_taxonomy_vocabulary_update().
function taxonomy_taxonomy_vocabulary_update(Vocabulary $vocabulary) {
  // Reflect machine name changes in the definitions of existing 'taxonomy'
  // fields.
  if (!empty($vocabulary->original->machine_name) && $vocabulary->original->machine_name != $vocabulary->machine_name) {
    $fields = field_read_fields();
    foreach ($fields as $field_name => $field) {
      $update = FALSE;
      if ($field['type'] == 'taxonomy_term_reference') {
        foreach ($field['settings']['allowed_values'] as $key => &$value) {
          if ($value['vocabulary'] == $vocabulary->original->machine_name) {
            $value['vocabulary'] = $vocabulary->machine_name;
 * Checks and updates the hierarchy flag of a vocabulary.
 * Checks the current parents of all terms in a vocabulary and updates the
 * vocabulary's hierarchy setting to the lowest possible level. If no term
 * 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.
 * @param Drupal\taxonomy\Vocabulary $vocabulary
 * @param $changed_term
 *   An array of the term structure that was updated.
 *
 * @return
 *   An integer that represents the level of the vocabulary's hierarchy.
function taxonomy_check_vocabulary_hierarchy(Vocabulary $vocabulary, $changed_term) {
  $hierarchy = TAXONOMY_HIERARCHY_DISABLED;
    // Update the changed term with the new parent value before comparison.
    if ($term->tid == $changed_term['tid']) {
      $term->parents = $term->parent;
    }
    // Check this term's parent count.
    if (count($term->parents) > 1) {
      $hierarchy = TAXONOMY_HIERARCHY_MULTIPLE;
    elseif (count($term->parents) == 1 && !isset($term->parents[0])) {
      $hierarchy = TAXONOMY_HIERARCHY_SINGLE;
  if ($hierarchy != $vocabulary->hierarchy) {
    $vocabulary->hierarchy = $hierarchy;
    taxonomy_vocabulary_save($vocabulary);
 *   The taxonomy term entity to be saved.
 *   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.
Kjartan Mannes's avatar
Kjartan Mannes committed
}
Dries Buytaert's avatar
Dries Buytaert committed

function taxonomy_term_delete($tid) {
  taxonomy_term_delete_multiple(array($tid));
}
Dries Buytaert's avatar
 
Dries Buytaert committed

/**
 * 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 Buytaert's avatar
 
Dries Buytaert committed
}

/**
 * Generate an array for rendering the given term.
 *
 * @param $view_mode
 *   View mode, e.g. 'full', 'teaser'...
 * @param $langcode
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
 *
 * @return
 *   An array as expected by drupal_render().
 */
function taxonomy_term_view(Term $term, $view_mode = 'full', $langcode = NULL) {
    $langcode = language(LANGUAGE_TYPE_CONTENT)->langcode;
  field_attach_prepare_view('taxonomy_term', array($term->tid => $term), $view_mode, $langcode);
  entity_prepare_view('taxonomy_term', array($term->tid => $term), $langcode);

  $build = array(
    '#theme' => 'taxonomy_term',
    '#term' => $term,
    '#view_mode' => $view_mode,
  $build += field_attach_view('taxonomy_term', $term, $view_mode, $langcode);
  // Add term description if the term has one.
  if (!empty($term->description)) {
    $build['description'] = array(
      '#markup' => check_markup($term->description, $term->format, '', TRUE),
      '#weight' => 0,
      '#prefix' => '<div class="taxonomy-term-description">',
      '#suffix' => '</div>',
    );
  }

  $build['#attached']['css'][] = drupal_get_path('module', 'taxonomy') . '/taxonomy.css';

  // Allow modules to modify the structured term.
  drupal_alter(array('taxonomy_term_view', 'entity_view'), $build, $term);
  return $build;
}

/**
 * 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'];

  $variables['term_url']  = url($uri['path'], $uri['options']);
  $variables['term_name'] = check_plain($term->name);
  $variables['page']      = $variables['view_mode'] == 'full' && taxonomy_term_is_page($term);

  // Flatten the term object's member fields.
  $variables = array_merge((array) $term, $variables);

  // Helpful $content variable for templates.
  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.
  field_attach_preprocess('taxonomy_term', $term, $variables['content'], $variables);

  // Gather classes, and clean up name so there are no underscores.
  $vocabulary_name_css = str_replace('_', '-', $term->vocabulary_machine_name);
  $variables['attributes']['class'][] = 'vocabulary-' . $vocabulary_name_css;
  $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->vocabulary_machine_name;
  $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->tid;
 * Returns whether the current page is the page of the passed-in term.
  $page_term = menu_get_object('taxonomy_term', 2);
  return (!empty($page_term) ? $page_term->tid == $term->tid : FALSE);
}

 * Clear all static cache variables for terms.
  entity_get_controller('taxonomy_term')->resetCache();
/**
 * Clear all static cache variables for vocabularies.
 *   An array of ids to reset in entity controller cache.
function taxonomy_vocabulary_static_reset(array $ids = NULL) {
  entity_get_controller('taxonomy_vocabulary')->resetCache($ids);
}

/**
 * Get names for all taxonomy vocabularies.
 *
 * @return
 *   An associative array of objects keyed by vocabulary machine name with
 *   information about taxonomy vocabularies. Each object has properties:
 *   - name: The vocabulary name.
 *   - machine_name: The machine name.
 *   - vid: The vocabulary ID.
 */
function taxonomy_vocabulary_get_names() {
  $names = &drupal_static(__FUNCTION__);

  if (!isset($names)) {
    $names = db_query('SELECT name, machine_name, vid FROM {taxonomy_vocabulary}')->fetchAllAssoc('machine_name');
  }
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
 * Finds all parents of a given term ID.
 *
 * @param $tid
 *   A taxonomy term ID.
 *
 * @return
 *   An array of term objects which are the parents of the term $tid, or an
 *   empty array if parents are not found.
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
function taxonomy_term_load_parents($tid) {
  $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 Mannes's avatar
Kjartan Mannes committed
  }

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

Dries Buytaert's avatar
 
Dries Buytaert committed
/**
 * Find all ancestors of a given term ID.
 */
function taxonomy_term_load_parents_all($tid) {
  $cache = &drupal_static(__FUNCTION__, array());

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

Dries Buytaert's avatar
 
Dries Buytaert committed
  $parents = array();
  if ($term = taxonomy_term_load($tid)) {
    $parents[] = $term;
Dries Buytaert's avatar
 
Dries Buytaert committed
    $n = 0;
    while ($parent = taxonomy_term_load_parents($parents[$n]->tid)) {
Dries Buytaert's avatar
 
Dries Buytaert committed
      $parents = array_merge($parents, $parent);
      $n++;
    }
  }
Dries Buytaert's avatar
 
Dries Buytaert committed
  return $parents;
}

Dries Buytaert's avatar
 
Dries Buytaert committed
/**
 * 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
 *   An array of term objects that are the children of the term $tid, or an
 *   empty array when no children exist.
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
function taxonomy_term_load_children($tid, $vid = 0) {
  $children = &drupal_static(__FUNCTION__, array());

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

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

Dries Buytaert's avatar
 
Dries Buytaert committed
/**
 * Create a hierarchical representation of a vocabulary.
 *
 * @param $vid
 *   Which vocabulary to generate the tree for.
 * @param $parent
 *   The term ID under which to generate the tree. If 0, generate the tree
 *   for the entire vocabulary.
Dries Buytaert's avatar
 
Dries Buytaert committed
 * @param $max_depth
 *   The number of levels of the tree to return. Leave NULL to return all levels.
 * @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.
Dries Buytaert's avatar
 
Dries Buytaert committed
 * @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.
 *   Results are statically cached. Term objects will be partial or complete
 *   depending on the $load_entities parameter.
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
function taxonomy_get_tree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE) {
  $children = &drupal_static(__FUNCTION__, array());
  $parents = &drupal_static(__FUNCTION__ . ':parents', array());
  $terms = &drupal_static(__FUNCTION__ . ':terms', array());
  // We cache trees, so it's not CPU-intensive to call taxonomy_get_tree() on a
  // term and its children, too.
Dries Buytaert's avatar
 
Dries Buytaert committed
  if (!isset($children[$vid])) {
    $children[$vid] = array();
    $parents[$vid] = array();
    $terms[$vid] = array();
Dries Buytaert's avatar
 
Dries Buytaert committed

    $query = db_select('taxonomy_term_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
    $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 Buytaert's avatar
Dries Buytaert committed
    }
  }
Dries Buytaert's avatar
 
Dries Buytaert committed

  // 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]));
  }

  $max_depth = (!isset($max_depth)) ? count($children[$vid]) : $max_depth;

  // 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];
        if (isset($parents[$vid][$term->tid])) {
          // Clone the term so that the depth attribute remains correct
          // in the event of multiple parents.
          $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 Buytaert's avatar
 
Dries Buytaert committed
      }
Dries Buytaert's avatar
 
Dries Buytaert committed
    }
Kjartan Mannes's avatar
Kjartan Mannes committed
  }
Dries Buytaert's avatar
 
Dries Buytaert committed

Kjartan Mannes's avatar
Kjartan Mannes committed
}
Dries Buytaert's avatar
Dries Buytaert committed

Dries Buytaert's avatar
 
Dries Buytaert committed
/**
Dries Buytaert's avatar
 
Dries Buytaert committed
 * Try to map a string to an existing term, as for glossary use.
Dries Buytaert's avatar
 
Dries Buytaert committed
 *
Dries Buytaert's avatar
 
Dries Buytaert committed
 * Provides a case-insensitive and trimmed mapping, to maximize the
 * likelihood of a successful match.
 *
Dries Buytaert's avatar
 
Dries Buytaert committed
 *   Name of the term to search for.
 * @param $vocabulary
 *   (optional) Vocabulary machine name to limit the search. Defaults to NULL.
Dries Buytaert's avatar
 
Dries Buytaert committed
 *
 * @return
 *   An array of matching term objects.
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
function taxonomy_term_load_multiple_by_name($name, $vocabulary = NULL) {
  $values = array('name' => trim($name));
  if (isset($vocabulary)) {
    $vocabularies = taxonomy_vocabulary_get_names();
    if (isset($vocabularies[$vocabulary])){
      $values['vid'] = $vocabularies[$vocabulary]->vid;
    }
    else {
      // Return an empty array when filtering by a non-existing vocabulary.
      return array();
    }
  }
  return entity_load_multiple_by_properties('taxonomy_term', $values);
Dries Buytaert's avatar
 
Dries Buytaert committed
}

/**
 * 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.
 *
 * @see Drupal\entity\EntityFieldQuery
 * @param array $tids
 *   (optional) An array of entity IDs. If omitted, all entities are loaded.
 *   An array of taxonomy term entities, indexed by tid. When no results are
 *   found, an empty array is returned.
function taxonomy_term_load_multiple(array $tids = NULL) {
  return entity_load_multiple('taxonomy_term', $tids);
 * Loads multiple taxonomy vocabularies based on certain conditions.
 *
 * 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.
 *
 * @param array $vids
 *   (optional) An array of entity IDs. If omitted, all entities are loaded.
 *  An array of vocabulary objects, indexed by vid.
 */
function taxonomy_vocabulary_load_multiple(array $vids = NULL) {
  return entity_load_multiple('taxonomy_vocabulary', $vids);
 * Return the taxonomy vocabulary entity matching a vocabulary ID.
 *   The taxonomy vocabulary entity, if exists, FALSE otherwise. Results are
 *   statically cached.
 *
 * @see taxonomy_vocabulary_machine_name_load()
  return entity_load('taxonomy_vocabulary', $vid);
 * Return the taxonomy vocabulary entity matching a vocabulary machine name.
 *   The taxonomy vocabulary entity, if exists, FALSE otherwise. Results are