Skip to content
taxonomy.module 46.9 KiB
Newer Older
Dries Buytaert's avatar
Dries Buytaert committed
<?php
Kjartan Mannes's avatar
Kjartan Mannes committed
// $Id$
Dries Buytaert's avatar
 
Dries Buytaert committed

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

 */
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/handbook/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/config/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 conent 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 "Add 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">create 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('Configure the vocabularies and terms for your site.') . '</p>';
      return $output;
    case 'admin/structure/taxonomy/%':
      $vocabulary = taxonomy_vocabulary_load($arg[3]);
      switch ($vocabulary->hierarchy) {
        case 0:
          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>';
        case 1:
          return '<p>' . t('%capital_name contains terms grouped with 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>';
        case 2:
          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>';
      }
    case 'admin/structure/taxonomy/add':
      return '<p>' . t('To create a new taxonomy vocabulary, type in a name and a description.') . '</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_get_vocabularies() 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(
      'controller class' => 'TaxonomyTermController',
      'base table' => 'taxonomy_term_data',
      'fieldable' => TRUE,
      'object keys' => array(
        'id' => 'tid',
        'bundle' => 'vocabulary_machine_name',
      ),
      'bundle keys' => array(
        'bundle' => 'machine_name',
      ),
      'bundles' => array(),
  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',
        'real path' => 'admin/structure/taxonomy/' . $vocabulary->vid,
        'bundle argument' => 3,
        'access arguments' => array('administer taxonomy'),
      ),
    );
  }
  $return['taxonomy_vocabulary'] = array(
    'label' => t('Taxonomy vocabulary'),
    'controller class' => 'TaxonomyVocabularyController',
    'base table' => 'taxonomy_vocabulary',
    'object keys' => array(
      'id' => 'vid',
    ),
    'fieldable' => FALSE,
  );

/**
 * 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.
 * @order
 *   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');
  if ($pager) {
    $count_query = clone $query;
    $count_query->addExpression('COUNT(t.nid)');

    $query = $query->extend('PagerDefault');
    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();
}

 *
 * @TODO: build mode for display as a field (when attached to nodes etc.).
 */
function taxonomy_field_build_modes($obj_type) {
  $modes = array();
  if ($obj_type == 'term') {
    $modes = array(
      'full' => t('Taxonomy term page'),
    );
  }
  return $modes;
}

    'taxonomy_overview_vocabularies' => array(
    ),
    'taxonomy_overview_terms' => array(
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' => 'drupal_get_form',
    'page arguments' => array('taxonomy_form_vocabulary'),
    '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(
    'title' => 'Edit term',
    'title callback' => 'taxonomy_term_title',
    'title arguments' => array(2),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_form_term', 2),
    'access callback' => 'taxonomy_term_edit_access',
    'access arguments' => array(2),
    '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,
    'page callback' => 'taxonomy_autocomplete',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  $items['admin/structure/taxonomy/%taxonomy_vocabulary'] = array(
    'title callback' => 'taxonomy_admin_vocabulary_title_callback',
    'title arguments' => array(3),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_overview_terms', 3),
    'access arguments' => array('administer taxonomy'),
  $items['admin/structure/taxonomy/%taxonomy_vocabulary/list'] = array(
    'title' => 'List',
  $items['admin/structure/taxonomy/%taxonomy_vocabulary/edit'] = array(
    'title' => 'Edit',
    'page arguments' => array('taxonomy_form_vocabulary', 3),
    'access arguments' => array('administer taxonomy'),
    'type' => MENU_LOCAL_TASK,

  $items['admin/structure/taxonomy/%taxonomy_vocabulary/add'] = array(
    'page arguments' => array('taxonomy_form_term', 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

/**
 * Return edit access for a given term.
 */
function taxonomy_term_edit_access($term) {
  return user_access("edit terms in $term->vid") || user_access('administer taxonomy');
}

/**
 * Return the vocabulary name given the vocabulary object.
 */
function taxonomy_admin_vocabulary_title_callback($vocabulary) {
  return check_plain($vocabulary->name);
}

/**
 * Save a vocabulary given a vocabulary object.
function taxonomy_vocabulary_save($vocabulary) {
  if (!empty($vocabulary->name)) {
    // Prevent leading and trailing spaces in vocabulary names.
    $vocabulary->name = trim($vocabulary->name);
  }
Dries Buytaert's avatar
 
Dries Buytaert committed

  if (!isset($vocabulary->module)) {
    $vocabulary->module = 'taxonomy';
  if (!empty($vocabulary->vid) && !empty($vocabulary->name)) {
    $status = drupal_write_record('taxonomy_vocabulary', $vocabulary, 'vid');
    module_invoke_all('taxonomy_vocabulary_update', $vocabulary);
Kjartan Mannes's avatar
Kjartan Mannes committed
  }
    $status = drupal_write_record('taxonomy_vocabulary', $vocabulary);
    field_attach_create_bundle('taxonomy_term', $vocabulary->machine_name);
    taxonomy_vocabulary_create_field($vocabulary);
    module_invoke_all('taxonomy_vocabulary_insert', $vocabulary);
Kjartan Mannes's avatar
Kjartan Mannes committed
  }
Dries Buytaert's avatar
 
Dries Buytaert committed

  cache_clear_all();
  entity_get_controller('taxonomy_vocabulary')->resetCache();
Dries Buytaert's avatar
 
Dries Buytaert committed

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

/**
 * Delete a vocabulary.
 *
 * @param $vid
 *   A vocabulary ID.
 * @return
 *   Constant indicating items were deleted.
 */
  $vocabulary = (array) taxonomy_vocabulary_load($vid);
Dries Buytaert's avatar
 
Dries Buytaert committed

  db_delete('taxonomy_vocabulary')
    ->condition('vid', $vid)
    ->execute();
  $result = db_query('SELECT tid FROM {taxonomy_term_data} WHERE vid = :vid', array(':vid' => $vid))->fetchCol();
  foreach ($result as $tid) {
    taxonomy_term_delete($tid);
Dries Buytaert's avatar
Dries Buytaert committed
  }
Dries Buytaert's avatar
 
Dries Buytaert committed

  field_attach_delete_bundle('taxonomy_term', $vocabulary['machine_name']);
Dries Buytaert's avatar
 
Dries Buytaert committed
  module_invoke_all('taxonomy', 'delete', 'vocabulary', $vocabulary);
Dries Buytaert's avatar
 
Dries Buytaert committed

Dries Buytaert's avatar
 
Dries Buytaert committed
  cache_clear_all();
  entity_get_controller('taxonomy_vocabulary')->resetCache();
Dries Buytaert's avatar
 
Dries Buytaert committed

Dries Buytaert's avatar
 
Dries Buytaert committed
}

 * Dynamically check and update the hierarchy flag of a vocabulary.
 * Checks the current parents of all terms in a vocabulary and updates the
 * vocabularies hierarchy setting to the lowest possible level. A hierarchy with
 * no parents in any of its terms will be given a hierarchy of 0. If terms
 * contain at most a single parent, the vocabulary will be given a hierarchy of
 * 1. If any term contain multiple parents, the vocabulary will be given a
 * @param $changed_term
 *   An array of the term structure that was updated.
 */
function taxonomy_check_vocabulary_hierarchy($vocabulary, $changed_term) {
  $hierarchy = 0;
  foreach ($tree as $term) {
    // Update the changed term with the new parent value before comparison.
    if ($term->tid == $changed_term['tid']) {
      $term = (object)$changed_term;
      $term->parents = $term->parent;
    }
    // Check this term's parent count.
    if (count($term->parents) > 1) {
      $hierarchy = 2;
      break;
    }
    elseif (count($term->parents) == 1 && 0 !== array_shift($term->parents)) {
      $hierarchy = 1;
    }
  }
  if ($hierarchy != $vocabulary->hierarchy) {
    $vocabulary->hierarchy = $hierarchy;
    taxonomy_vocabulary_save($vocabulary);
/**
 * Create a default field when a vocabulary is created.
 *
 * @param $vocabulary
 *   A taxonomy vocabulary object.
 */
function taxonomy_vocabulary_create_field($vocabulary) {
  $field = array(
    'field_name' => 'taxonomy_' . $vocabulary->machine_name,
    'type' => 'taxonomy_term',
    // Set cardinality to unlimited so that select
    // and autocomplete widgets behave as normal.
    'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    'settings' => array(
      'allowed_values' => array(
        array(
          'vid' => $vocabulary->vid,
          'parent' => 0,
        ),
      ),
    ),
  );
  field_create_field($field);
}

 * Save a term object to the database.
 * @param $term
 *  A term object.
 * @return
 *   Status constant indicating if term was inserted or updated.
 */
function taxonomy_term_save($term) {
  if ($term->name) {
    // Prevent leading and trailing spaces in term names.
    $term->name = trim($term->name);
  }
  if (!isset($term->vocabulary_machine_name)) {
    $vocabulary = taxonomy_vocabulary_load($term->vid);
    $term->vocabulary_machine_name = $vocabulary->machine_name;
  }

  field_attach_presave('taxonomy_term', $term);
  if (!empty($term->tid) && $term->name) {
    $status = drupal_write_record('taxonomy_term_data', $term, 'tid');
    field_attach_update('taxonomy_term', $term);
    module_invoke_all('taxonomy_term_update', $term);
Kjartan Mannes's avatar
Kjartan Mannes committed
  }
  else {
    $status = drupal_write_record('taxonomy_term_data', $term);
    field_attach_insert('taxonomy_term', $term);
    module_invoke_all('taxonomy_term_insert', $term);
Kjartan Mannes's avatar
Kjartan Mannes committed
  }
  db_delete('taxonomy_term_hierarchy')
    ->condition('tid', $term->tid)
    ->execute();
Dries Buytaert's avatar
Dries Buytaert committed

  if (!isset($term->parent) || empty($term->parent)) {
    $term->parent = array(0);
Kjartan Mannes's avatar
Kjartan Mannes committed
  }
  if (!is_array($term->parent)) {
    $term->parent = array($term->parent);
  }
  $query = db_insert('taxonomy_term_hierarchy')
    ->fields(array('tid', 'parent'));
  if (is_array($term->parent)) {
    foreach ($term->parent as $parent) {
      if (is_array($parent)) {
        foreach ($parent as $tid) {
        $query->values(array(
          'tid' => $term->tid,
          'parent' => $parent
        ));
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
  cache_clear_all();
Dries Buytaert's avatar
 
Dries Buytaert committed

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

/**
 * Delete a term.
 *
 * @param $tid
 *   The term ID.
 * @return
 *   Status constant indicating deletion.
 */
function taxonomy_term_delete($tid) {
  $tids = array($tid);
  while ($tids) {
    $children_tids = $orphans = array();
    foreach ($tids as $tid) {
      // See if any of the term's children are about to be become orphans:
      if ($children = taxonomy_get_children($tid)) {
        foreach ($children as $child) {
          // If the term has multiple parents, we don't delete it.
          $parents = taxonomy_get_parents($child->tid);
          if (count($parents) == 1) {
            $orphans[] = $child->tid;
          }
        }
      }
Dries Buytaert's avatar
 
Dries Buytaert committed

      $term = taxonomy_term_load($tid);
Dries Buytaert's avatar
 
Dries Buytaert committed

      db_delete('taxonomy_term_data')
        ->condition('tid', $tid)
        ->execute();
      db_delete('taxonomy_term_hierarchy')
        ->condition('tid', $tid)
        ->execute();
Dries Buytaert's avatar
 
Dries Buytaert committed

      field_attach_delete('taxonomy_term', $term);
      module_invoke_all('taxonomy_term_delete', $term);
Dries Buytaert's avatar
 
Dries Buytaert committed

Dries Buytaert's avatar
 
Dries Buytaert committed

Dries Buytaert's avatar
 
Dries Buytaert committed
  cache_clear_all();
Dries Buytaert's avatar
 
Dries Buytaert committed
}

/**
 * Clear all static cache variables for terms..
 */
function taxonomy_terms_static_reset() {
  drupal_static_reset('taxonomy_term_count_nodes');
  drupal_static_reset('taxonomy_get_tree');
  entity_get_controller('taxonomy_term')->resetCache();
 * Generate a set of options for selecting a term from all vocabularies.
  $vocabularies = taxonomy_get_vocabularies();
  $options = array();
  foreach ($vocabularies as $vid => $vocabulary) {
    $tree = taxonomy_get_tree($vid);
        $options[$vocabulary->name][$term->tid] = str_repeat('-', $term->depth) . $term->name;
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
 * Return an array of all vocabulary objects.
 *
 * @param $type
 *   If set, return only those vocabularies associated with this node type.
 */
function taxonomy_get_vocabularies() {
  return taxonomy_vocabulary_load_multiple(FALSE, array());
Kjartan Mannes's avatar
Kjartan Mannes committed
}
Dries Buytaert's avatar
Dries Buytaert committed

/**
 * Get names for all taxonomy vocabularies.
 *
 * @return
 *   An array of vocabulary ids, names, machine names, keyed by machine name.
 */
function taxonomy_vocabulary_get_names() {
  $names = db_query('SELECT name, machine_name, vid FROM {taxonomy_vocabulary}')->fetchAllAssoc('machine_name');
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
 * Find all parents of a given term ID.
 */
function taxonomy_get_parents($tid, $key = 'tid') {
Kjartan Mannes's avatar
Kjartan Mannes committed
  if ($tid) {
    $query = db_select('taxonomy_term_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.parent = t.tid');
    $result = $query
      ->fields('t')
      ->condition('h.tid', $tid)
      ->orderBy('weight')
      ->orderBy('name')
      ->execute();
Kjartan Mannes's avatar
Kjartan Mannes committed
    $parents = array();
Kjartan Mannes's avatar
Kjartan Mannes committed
      $parents[$parent->$key] = $parent;
Dries Buytaert's avatar
 
Dries Buytaert committed
    }
Kjartan Mannes's avatar
Kjartan Mannes committed
    return $parents;
Dries Buytaert's avatar
Dries Buytaert committed
  }
Kjartan Mannes's avatar
Kjartan Mannes committed
  else {
    return array();
  }
}
Dries Buytaert's avatar
Dries Buytaert committed

Dries Buytaert's avatar
 
Dries Buytaert committed
/**
 * Find all ancestors of a given term ID.
 */
function taxonomy_get_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_get_parents($parents[$n]->tid)) {
      $parents = array_merge($parents, $parent);
      $n++;
    }
  }
Dries Buytaert's avatar
 
Dries Buytaert committed
  return $parents;
}

Dries Buytaert's avatar
 
Dries Buytaert committed
/**
 * Find all children of a term ID.
 */
function taxonomy_get_children($tid, $vid = 0, $key = 'tid') {
  $query = db_select('taxonomy_term_data', 't');
  $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
  $query
    ->fields('t')
    ->condition('parent', $tid)
    ->orderBy('weight')
    ->orderBy('name');
Kjartan Mannes's avatar
Kjartan Mannes committed
  if ($vid) {
Kjartan Mannes's avatar
Kjartan Mannes committed
  }
Kjartan Mannes's avatar
Kjartan Mannes committed
  $children = array();
Kjartan Mannes's avatar
Kjartan Mannes committed
    $children[$term->$key] = $term;
  }
  return $children;
}
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.
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.
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
function taxonomy_get_tree($vid, $parent = 0, $max_depth = NULL, $depth = -1) {
  $children = &drupal_static(__FUNCTION__, array());
  $parents = &drupal_static(__FUNCTION__ . 'parents', array());
  $terms = &drupal_static(__FUNCTION__ . 'terms', array());
Kjartan Mannes's avatar
Kjartan Mannes committed
  $depth++;
Dries Buytaert's avatar
 
Dries Buytaert committed

Dries Buytaert's avatar
 
Dries Buytaert committed
  // We cache trees, so it's not CPU-intensive to call get_tree() on a term
  // and its children, too.
  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
      ->fields('t')
      ->fields('h', array('parent'))
      ->condition('t.vid', $vid)
      ->orderBy('weight')
      ->orderBy('name')
      ->execute();
    foreach ($result as $term) {
Dries Buytaert's avatar
 
Dries Buytaert committed
      $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

Dries Buytaert's avatar
 
Dries Buytaert committed
  $max_depth = (is_null($max_depth)) ? count($children[$vid]) : $max_depth;
  if ($max_depth > $depth && !empty($children[$vid][$parent])) {
Dries Buytaert's avatar
Dries Buytaert committed
    foreach ($children[$vid][$parent] as $child) {
      $term = clone $terms[$vid][$child];
      $term->depth = $depth;
      // The "parent" attribute is not useful, as it would show one parent only.
      unset($term->parent);
      $term->parents = $parents[$vid][$child];
      $tree[] = $term;
      if (!empty($children[$vid][$child])) {
        $tree = array_merge($tree, taxonomy_get_tree($vid, $child, $max_depth, $depth));
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.
 *
 * @param name
 *   Name of the term to search for.
 *
 * @return
 *   An array of matching term objects.
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
function taxonomy_get_term_by_name($name) {
  return taxonomy_term_load_multiple(array(), array('name' => trim($name)));
Dries Buytaert's avatar
 
Dries Buytaert committed
}

/**
 * Controller class for taxonomy terms.
 *
 * This extends the DrupalDefaultEntityController class. Only alteration is
 * that we match the condition on term name case-independently.
 */
class TaxonomyTermController extends DrupalDefaultEntityController {
  protected $type;
  public function load($ids = array(), $conditions = array()) {
    if (isset($conditions['type'])) {
      $this->type = $conditions['type'];
      unset($conditions['type']);
  protected function buildQuery() {
    parent::buildQuery();
    $this->query->addTag('translatable');
    $this->query->addTag('term_access');
    // When name is passed as a condition use LIKE.
    if (isset($this->conditions['name'])) {
      $conditions = &$this->query->conditions();
      foreach ($conditions as $key => $condition) {
        if ($condition['field'] == 'base.name') {
          $conditions[$key]['operator'] = 'LIKE';
        }
    // Add the machine name field from the {taxonomy_vocabulary} table.
    $this->query->innerJoin('taxonomy_vocabulary', 'v', 'base.vid = v.vid');
    $this->query->addField('v', 'machine_name', 'vocabulary_machine_name');
  }

  protected function cacheGet($ids, $conditions = array()) {
    $terms = parent::cacheGet($ids, $conditions);
    // Name matching is case insensitive, note that with some collations
    // LOWER() and drupal_strtolower() may return different results.
    foreach ($terms as $term) {
      $term_values = (array) $term;
      if (isset($this->conditions['name']) && drupal_strtolower($this->conditions['name'] != drupal_strtolower($term_values['name']))) {
        unset($terms[$term->tid]);
      }
/**
 * Controller class for taxonomy vocabularies.
 *
 * This extends the DrupalDefaultEntityController class, adding required
 * special handling for taxonomy vocabulary objects.
 */
class TaxonomyVocabularyController extends DrupalDefaultEntityController {
  protected function buildQuery() {
    parent::buildQuery();
    $this->query->orderBy('base.weight');
    $this->query->orderBy('base.name');
  }
  protected function attachLoad(&$records) {
    foreach ($records as $record) {
      // If no node types are associated with a vocabulary, the LEFT JOIN will
      // return a NULL value for type.
      $queried_vocabularies[$record->vid] = $record;
    }
    $records = $queried_vocabularies;
    parent::attachLoad($records);
Dries Buytaert's avatar
 
Dries Buytaert committed
  }
Kjartan Mannes's avatar
Kjartan Mannes committed
}
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.
 *
 * @param $tids
 *  An array of taxonomy term IDs.
 * @param $conditions
 *  An array of conditions to add to the query.
 *
 * @return
 *  An array of term objects, indexed by tid.
 */
function taxonomy_term_load_multiple($tids = array(), $conditions = array()) {
  return entity_load('taxonomy_term', $tids, $conditions);
}
/**
 * Load 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.
 *
 * @see entity_load()
 *
 * @param $vids
 *  An array of taxonomy vocabulary IDs, or FALSE to load all vocabularies.
 * @param $conditions
 *  An array of conditions to add to the query.
 *
 * @return
 *  An array of vocabulary objects, indexed by vid.
 */
function taxonomy_vocabulary_load_multiple($vids = array(), $conditions = array()) {
  return entity_load('taxonomy_vocabulary', $vids, $conditions);
}
/**
 * Return the vocabulary object matching a vocabulary ID.
 *
 * @param $vid
 *   The vocabulary's ID.
 *
 * @return
 *   The vocabulary object with all of its metadata, if exists, FALSE otherwise.
 *   Results are statically cached.
 */
function taxonomy_vocabulary_load($vid) {
  return reset(taxonomy_vocabulary_load_multiple(array($vid)));
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
 * Return the term object matching a term ID.
 *   A term object. Results are statically cached.
Dries Buytaert's avatar
 
Dries Buytaert committed
 */
  $term = taxonomy_term_load_multiple(array($tid), array());
  return $term ? $term[$tid] : FALSE;
Dries Buytaert's avatar
 
Dries Buytaert committed
/**
 * Helper function for array_map purposes.
 */
function _taxonomy_get_tid_from_term($term) {
  return $term->tid;
}

 * Implodes a list of tags of a certain vocabulary into a string.
 */
function taxonomy_implode_tags($tags, $vid = NULL) {
  $typed_tags = array();
  foreach ($tags as $tag) {
    // Extract terms belonging to the vocabulary in question.
    if (is_null($vid) || $tag->vid == $vid) {
      // Commas and quotes in tag names are special cases, so encode 'em.
      if (strpos($tag->name, ',') !== FALSE || strpos($tag->name, '"') !== FALSE) {
        $tag->name = '"' . str_replace('"', '""', $tag->name) . '"';
      $typed_tags[] = $tag->name;
 *
 * Field settings:
 * - allowed_values: a list array of one or more vocabulary trees:
 *   - vid: a vocabulary ID.
 *   - 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(
    'taxonomy_term' => array(
      'label' => t('Taxonomy term'),
      'description' => t('This field stores a reference to a taxonomy term.'),
      'default_widget' => 'options_select',
      'default_formatter' => 'taxonomy_term_link',
      'settings' => array(
        'allowed_values' => array(
          array(
            'vid' => '0',
            'parent' => '0',
          ),
        ),
      ),
    ),
  );
}

 *
 * We need custom handling of multiple values because we need
 * to combine them into a options list rather than display
 * cardinality elements. We will use the field module's default
 * handling for default values.
 *
 * Callbacks can be omitted if default handing is used.
 * They're included here just so this module can be used
 * as an example for custom modules that might do things
 * differently.
 */
function taxonomy_field_widget_info() {
  return array(
    'taxonomy_autocomplete' => array(
      'label' => t('Autocomplete term widget (tagging)'),
      'field types' => array('taxonomy_term'),