Newer
Older
/**
* @file
* Enables the organization of content into categories.
*/
/**
* 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().
*/
/**
Dries Buytaert
committed
* Implements hook_help().
*/
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>';
Angie Byron
committed
$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 "Add existing field" section on the manage fields page.', array('@ctedit' => url('admin/structure/types'))) . '</dd>';
$output .= '<dt>' . t('Classifying content') . '</dt>';
Angie Byron
committed
$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':
Angie Byron
committed
$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/%':
Dries Buytaert
committed
$vocabulary = taxonomy_vocabulary_machine_name_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 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>';
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>';
}
}
}
Dries Buytaert
committed
* Implements hook_permission().
function taxonomy_permission() {
Dries Buytaert
committed
$permissions = array(
Angie Byron
committed
'administer taxonomy' => array(
'title' => t('Administer vocabularies and terms'),
Angie Byron
committed
),
);
Dries Buytaert
committed
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)),
Dries Buytaert
committed
),
);
}
return $permissions;
Dries Buytaert
committed
/**
Dries Buytaert
committed
* Implements hook_entity_info().
Dries Buytaert
committed
*/
Dries Buytaert
committed
function taxonomy_entity_info() {
Dries Buytaert
committed
$return = array(
'taxonomy_term' => array(
'label' => t('Taxonomy term'),
Dries Buytaert
committed
'controller class' => 'TaxonomyTermController',
'base table' => 'taxonomy_term_data',
Angie Byron
committed
'uri callback' => 'taxonomy_term_uri',
Dries Buytaert
committed
'fieldable' => TRUE,
'entity keys' => array(
'id' => 'tid',
'bundle' => 'vocabulary_machine_name',
Angie Byron
committed
'label' => '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'),
Dries Buytaert
committed
'custom settings' => FALSE,
Dries Buytaert
committed
),
);
Dries Buytaert
committed
foreach (taxonomy_vocabulary_get_names() as $machine_name => $vocabulary) {
$return['taxonomy_term']['bundles'][$machine_name] = array(
'label' => $vocabulary->name,
'admin' => array(
Dries Buytaert
committed
'path' => 'admin/structure/taxonomy/%taxonomy_vocabulary_machine_name',
'real path' => 'admin/structure/taxonomy/' . $machine_name,
'bundle argument' => 3,
'access arguments' => array('administer taxonomy'),
),
);
}
Dries Buytaert
committed
$return['taxonomy_vocabulary'] = array(
'label' => t('Taxonomy vocabulary'),
'controller class' => 'TaxonomyVocabularyController',
'base table' => 'taxonomy_vocabulary',
'entity keys' => array(
Dries Buytaert
committed
'id' => 'vid',
Angie Byron
committed
'label' => 'name',
Dries Buytaert
committed
),
'fieldable' => FALSE,
);
Dries Buytaert
committed
return $return;
}
Angie Byron
committed
/**
Angie Byron
committed
* Entity uri callback.
Angie Byron
committed
*/
Angie Byron
committed
function taxonomy_term_uri($term) {
return array(
'path' => 'taxonomy/term/' . $term->tid,
);
Angie Byron
committed
}
/**
* Implements hook_field_extra_fields().
*/
function taxonomy_field_extra_fields() {
$return = array();
Dries Buytaert
committed
$info = entity_get_info('taxonomy_term');
foreach (array_keys($info['bundles']) as $bundle) {
$return['taxonomy_term'][$bundle] = array(
Dries Buytaert
committed
'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 $return;
}
Angie Byron
committed
/**
* 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 $tid
* The term ID.
Angie Byron
committed
* @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.
Angie Byron
committed
* @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')) {
Angie Byron
committed
if (!variable_get('taxonomy_maintain_index_table', TRUE)) {
return array();
}
$query = db_select('taxonomy_index', 't');
$query->addTag('node_access');
Dries Buytaert
committed
$query->condition('tid', $tid);
Angie Byron
committed
if ($pager) {
$count_query = clone $query;
$count_query->addExpression('COUNT(t.nid)');
$query = $query->extend('PagerDefault');
if ($limit !== FALSE) {
$query = $query->limit($limit);
}
Angie Byron
committed
$query->setCountQuery($count_query);
}
else {
if ($limit !== FALSE) {
$query->range(0, $limit);
}
Angie Byron
committed
}
$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();
}
Dries Buytaert
committed
/**
Dries Buytaert
committed
* Implements hook_theme().
Dries Buytaert
committed
*/
function taxonomy_theme() {
return array(
'taxonomy_overview_vocabularies' => array(
'render element' => 'form',
),
'taxonomy_overview_terms' => array(
'render element' => 'form',
'taxonomy_term' => array(
'render element' => 'elements',
'template' => 'taxonomy-term',
),
Dries Buytaert
committed
);
}
Dries Buytaert
committed
* Implements hook_menu().
Dries Buytaert
committed
function taxonomy_menu() {
Dries Buytaert
committed
$items['admin/structure/taxonomy'] = array(
Gábor Hojtsy
committed
'title' => 'Taxonomy',
'description' => 'Manage tagging, categorization, and classification of your content.',
'page callback' => 'drupal_get_form',
'page arguments' => array('taxonomy_overview_vocabularies'),
Dries Buytaert
committed
'access arguments' => array('administer taxonomy'),
'file' => 'taxonomy.admin.inc',
Dries Buytaert
committed
);
Dries Buytaert
committed
$items['admin/structure/taxonomy/list'] = array(
'title' => 'List',
Dries Buytaert
committed
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10,
);
Dries Buytaert
committed
$items['admin/structure/taxonomy/add'] = array(
'title' => 'Add vocabulary',
Dries Buytaert
committed
'page callback' => 'drupal_get_form',
'page arguments' => array('taxonomy_form_vocabulary'),
Dries Buytaert
committed
'access arguments' => array('administer taxonomy'),
Angie Byron
committed
'type' => MENU_LOCAL_ACTION,
'file' => 'taxonomy.admin.inc',
Dries Buytaert
committed
);
Dries Buytaert
committed
$items['taxonomy/term/%taxonomy_term'] = array(
Dries Buytaert
committed
'title' => 'Taxonomy term',
Dries Buytaert
committed
'title callback' => 'taxonomy_term_title',
'title arguments' => array(2),
Dries Buytaert
committed
'page callback' => 'taxonomy_term_page',
'page arguments' => array(2),
'access arguments' => array('access content'),
'file' => 'taxonomy.pages.inc',
Dries Buytaert
committed
);
Dries Buytaert
committed
$items['taxonomy/term/%taxonomy_term/view'] = array(
Dries Buytaert
committed
'title' => 'View',
'type' => MENU_DEFAULT_LOCAL_TASK,
Dries Buytaert
committed
);
Dries Buytaert
committed
$items['taxonomy/term/%taxonomy_term/edit'] = array(
Dries Buytaert
committed
'title' => 'Edit',
'page callback' => 'drupal_get_form',
'page arguments' => array('taxonomy_form_term', 2),
Dries Buytaert
committed
'access callback' => 'taxonomy_term_edit_access',
'access arguments' => array(2),
Dries Buytaert
committed
'type' => MENU_LOCAL_TASK,
'weight' => 10,
'file' => 'taxonomy.admin.inc',
Dries Buytaert
committed
);
Dries Buytaert
committed
$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,
Dries Buytaert
committed
'file' => 'taxonomy.pages.inc',
Dries Buytaert
committed
);
Dries Buytaert
committed
$items['taxonomy/autocomplete'] = array(
'title' => 'Autocomplete taxonomy',
Dries Buytaert
committed
'page callback' => 'taxonomy_autocomplete',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
'file' => 'taxonomy.pages.inc',
Dries Buytaert
committed
);
Dries Buytaert
committed
Dries Buytaert
committed
$items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name'] = array(
Dries Buytaert
committed
'title callback' => 'taxonomy_admin_vocabulary_title_callback',
'title arguments' => array(3),
Angie Byron
committed
'page callback' => 'drupal_get_form',
'page arguments' => array('taxonomy_overview_terms', 3),
Dries Buytaert
committed
'access arguments' => array('administer taxonomy'),
'file' => 'taxonomy.admin.inc',
Dries Buytaert
committed
);
Dries Buytaert
committed
$items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/list'] = array(
Angie Byron
committed
'title' => 'List',
Dries Buytaert
committed
'type' => MENU_DEFAULT_LOCAL_TASK,
Dries Buytaert
committed
'weight' => -20,
);
Dries Buytaert
committed
$items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/edit'] = array(
Angie Byron
committed
'title' => 'Edit',
Dries Buytaert
committed
'page callback' => 'drupal_get_form',
Angie Byron
committed
'page arguments' => array('taxonomy_form_vocabulary', 3),
Dries Buytaert
committed
'access arguments' => array('administer taxonomy'),
'type' => MENU_LOCAL_TASK,
Dries Buytaert
committed
'weight' => -10,
'file' => 'taxonomy.admin.inc',
Dries Buytaert
committed
);
Angie Byron
committed
Dries Buytaert
committed
$items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/add'] = array(
'title' => 'Add term',
Dries Buytaert
committed
'page callback' => 'drupal_get_form',
'page arguments' => array('taxonomy_form_term', array(), 3),
Dries Buytaert
committed
'access arguments' => array('administer taxonomy'),
Angie Byron
committed
'type' => MENU_LOCAL_ACTION,
'file' => 'taxonomy.admin.inc',
Dries Buytaert
committed
);
Angie Byron
committed
/**
* Implements hook_admin_paths().
*/
function taxonomy_admin_paths() {
$paths = array(
'taxonomy/term/*/edit' => TRUE,
);
return $paths;
}
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');
}
Dries Buytaert
committed
/**
* Return the vocabulary name given the vocabulary object.
*/
function taxonomy_admin_vocabulary_title_callback($vocabulary) {
return check_plain($vocabulary->name);
}
/**
Dries Buytaert
committed
* Save a vocabulary given a vocabulary object.
Dries Buytaert
committed
*/
Dries Buytaert
committed
function taxonomy_vocabulary_save($vocabulary) {
// Prevent leading and trailing spaces in vocabulary names.
Dries Buytaert
committed
if (!empty($vocabulary->name)) {
$vocabulary->name = trim($vocabulary->name);
}
Dries Buytaert
committed
// Load the stored entity, if any.
if (!empty($vocabulary->vid)) {
if (!isset($vocabulary->original)) {
$vocabulary->original = entity_load_unchanged('taxonomy_vocabulary', $vocabulary->vid);
}
// Make sure machine name changes are easily detected.
// @todo: Remove in Drupal 8, as it is deprecated by directly reading from
// $vocabulary->original.
$vocabulary->old_machine_name = $vocabulary->original->machine_name;
Dries Buytaert
committed
if (!isset($vocabulary->module)) {
$vocabulary->module = 'taxonomy';
Dries Buytaert
committed
}
module_invoke_all('taxonomy_vocabulary_presave', $vocabulary);
module_invoke_all('entity_presave', $vocabulary, 'taxonomy_vocabulary');
Dries Buytaert
committed
if (!empty($vocabulary->vid) && !empty($vocabulary->name)) {
Dries Buytaert
committed
$status = drupal_write_record('taxonomy_vocabulary', $vocabulary, 'vid');
if ($vocabulary->old_machine_name != $vocabulary->machine_name) {
field_attach_rename_bundle('taxonomy_term', $vocabulary->old_machine_name, $vocabulary->machine_name);
}
Dries Buytaert
committed
module_invoke_all('taxonomy_vocabulary_update', $vocabulary);
module_invoke_all('entity_update', $vocabulary, 'taxonomy_vocabulary');
Dries Buytaert
committed
elseif (empty($vocabulary->vid)) {
Dries Buytaert
committed
$status = drupal_write_record('taxonomy_vocabulary', $vocabulary);
Dries Buytaert
committed
field_attach_create_bundle('taxonomy_term', $vocabulary->machine_name);
Dries Buytaert
committed
module_invoke_all('taxonomy_vocabulary_insert', $vocabulary);
module_invoke_all('entity_insert', $vocabulary, 'taxonomy_vocabulary');
Dries Buytaert
committed
unset($vocabulary->original);
Dries Buytaert
committed
entity_get_controller('taxonomy_vocabulary')->resetCache(array($vocabulary->vid));
Dries Buytaert
committed
return $status;
/**
* Delete a vocabulary.
*
* @param $vid
* A vocabulary ID.
* @return
* Constant indicating items were deleted.
*/
Dries Buytaert
committed
function taxonomy_vocabulary_delete($vid) {
$vocabulary = taxonomy_vocabulary_load($vid);
Angie Byron
committed
$transaction = db_transaction();
try {
// Only load terms without a parent, child terms will get deleted too.
$result = db_query('SELECT t.tid FROM {taxonomy_term_data} t INNER JOIN {taxonomy_term_hierarchy} th ON th.tid = t.tid WHERE t.vid = :vid AND th.parent = 0', array(':vid' => $vid))->fetchCol();
foreach ($result as $tid) {
taxonomy_term_delete($tid);
}
db_delete('taxonomy_vocabulary')
->condition('vid', $vid)
->execute();
Dries Buytaert
committed
Angie Byron
committed
field_attach_delete_bundle('taxonomy_term', $vocabulary->machine_name);
module_invoke_all('taxonomy_vocabulary_delete', $vocabulary);
module_invoke_all('entity_delete', $vocabulary, 'taxonomy_vocabulary');
Dries Buytaert
committed
Angie Byron
committed
cache_clear_all();
entity_get_controller('taxonomy_vocabulary')->resetCache();
Dries Buytaert
committed
Angie Byron
committed
return SAVED_DELETED;
}
catch (Exception $e) {
$transaction->rollback();
watchdog_exception('taxonomy', $e);
throw $e;
/**
Angie Byron
committed
* Implements hook_taxonomy_vocabulary_update().
*/
Angie Byron
committed
function taxonomy_taxonomy_vocabulary_update($vocabulary) {
// Reflect machine name changes in the definitions of existing 'taxonomy'
// fields.
if (!empty($vocabulary->old_machine_name) && $vocabulary->old_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) {
Angie Byron
committed
if ($value['vocabulary'] == $vocabulary->old_machine_name) {
$value['vocabulary'] = $vocabulary->machine_name;
$update = TRUE;
}
}
if ($update) {
field_update_field($field);
}
}
}
}
}
* 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
* hierarchy of 2.
* @param $vocabulary
Dries Buytaert
committed
* A vocabulary object.
* @param $changed_term
* An array of the term structure that was updated.
*/
function taxonomy_check_vocabulary_hierarchy($vocabulary, $changed_term) {
Dries Buytaert
committed
$tree = taxonomy_get_tree($vocabulary->vid);
$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;
}
}
Dries Buytaert
committed
if ($hierarchy != $vocabulary->hierarchy) {
$vocabulary->hierarchy = $hierarchy;
taxonomy_vocabulary_save($vocabulary);
}
return $hierarchy;
}
* 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) {
// Prevent leading and trailing spaces in term names.
$term->name = trim($term->name);
Dries Buytaert
committed
if (!isset($term->vocabulary_machine_name)) {
$vocabulary = taxonomy_vocabulary_load($term->vid);
$term->vocabulary_machine_name = $vocabulary->machine_name;
}
Dries Buytaert
committed
// Load the stored entity, if any.
if (!empty($term->tid) && !isset($term->original)) {
$term->original = entity_load_unchanged('taxonomy_term', $term->tid);
}
Dries Buytaert
committed
field_attach_presave('taxonomy_term', $term);
module_invoke_all('taxonomy_term_presave', $term);
module_invoke_all('entity_presave', $term, 'taxonomy_term');
Dries Buytaert
committed
if (empty($term->tid)) {
Dries Buytaert
committed
$op = 'insert';
Dries Buytaert
committed
$status = drupal_write_record('taxonomy_term_data', $term);
Dries Buytaert
committed
field_attach_insert('taxonomy_term', $term);
Dries Buytaert
committed
if (!isset($term->parent)) {
$term->parent = array(0);
}
Dries Buytaert
committed
else {
Dries Buytaert
committed
$op = 'update';
Dries Buytaert
committed
$status = drupal_write_record('taxonomy_term_data', $term, 'tid');
field_attach_update('taxonomy_term', $term);
if (isset($term->parent)) {
db_delete('taxonomy_term_hierarchy')
->condition('tid', $term->tid)
->execute();
}
Angie Byron
committed
}
Dries Buytaert
committed
Dries Buytaert
committed
if (isset($term->parent)) {
if (!is_array($term->parent)) {
$term->parent = array($term->parent);
}
$query = db_insert('taxonomy_term_hierarchy')
->fields(array('tid', 'parent'));
foreach ($term->parent as $parent) {
if (is_array($parent)) {
foreach ($parent as $tid) {
Dries Buytaert
committed
$query->values(array(
'tid' => $term->tid,
'parent' => $tid
Dries Buytaert
committed
));
Dries Buytaert
committed
}
}
else {
$query->values(array(
'tid' => $term->tid,
'parent' => $parent
));
}
Dries Buytaert
committed
$query->execute();
Dries Buytaert
committed
// Reset the taxonomy term static variables.
Dries Buytaert
committed
taxonomy_terms_static_reset();
Dries Buytaert
committed
// Invoke the taxonomy hooks.
module_invoke_all("taxonomy_term_$op", $term);
module_invoke_all("entity_$op", $term, 'taxonomy_term');
Dries Buytaert
committed
unset($term->original);
Dries Buytaert
committed
Dries Buytaert
committed
return $status;
/**
* Delete a term.
*
* @param $tid
* The term ID.
* @return
* Status constant indicating deletion.
*/
function taxonomy_term_delete($tid) {
Angie Byron
committed
$transaction = db_transaction();
try {
$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
committed
}
}
Angie Byron
committed
if ($term = taxonomy_term_load($tid)) {
db_delete('taxonomy_term_data')
->condition('tid', $tid)
->execute();
db_delete('taxonomy_term_hierarchy')
->condition('tid', $tid)
->execute();
field_attach_delete('taxonomy_term', $term);
module_invoke_all('taxonomy_term_delete', $term);
module_invoke_all('entity_delete', $term, 'taxonomy_term');
taxonomy_terms_static_reset();
}
Angie Byron
committed
$tids = $orphans;
}
return SAVED_DELETED;
}
catch (Exception $e) {
$transaction->rollback();
watchdog_exception('taxonomy', $e);
throw $e;
Dries Buytaert
committed
}
/**
* Generate an array for rendering the given term.
*
* @param $term
* A term object.
* @param $view_mode
* View mode, e.g. 'full', 'teaser'...
Dries Buytaert
committed
* @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().
*/
Dries Buytaert
committed
function taxonomy_term_view($term, $view_mode = 'full', $langcode = NULL) {
if (!isset($langcode)) {
$langcode = $GLOBALS['language_content']->language;
}
field_attach_prepare_view('taxonomy_term', array($term->tid => $term), $view_mode);
entity_prepare_view('taxonomy_term', array($term->tid => $term));
$build = array(
'#theme' => 'taxonomy_term',
'#term' => $term,
'#view_mode' => $view_mode,
Dries Buytaert
committed
'#language' => $langcode,
Dries Buytaert
committed
$build += field_attach_view('taxonomy_term', $term, $view_mode, $langcode);
$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.
$type = 'taxonomy_term';
drupal_alter(array('taxonomy_term_view', 'entity_view'), $build, $type);
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'];
Dries Buytaert
committed
$uri = entity_uri('taxonomy_term', $term);
$variables['term_url'] = url($uri['path'], $uri['options']);
$variables['term_name'] = check_plain($term->name);
Dries Buytaert
committed
$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);
Dries Buytaert
committed
// Gather classes, and clean up name so there are no underscores.
$vocabulary_name_css = str_replace('_', '-', $term->vocabulary_machine_name);
$variables['classes_array'][] = 'vocabulary-' . $vocabulary_name_css;
Dries Buytaert
committed
$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.
*
* @param $term
* A term object.
*/
function taxonomy_term_is_page($term) {
$page_term = menu_get_object('taxonomy_term', 2);
return (!empty($page_term) ? $page_term->tid == $term->tid : FALSE);
}
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');
drupal_static_reset('taxonomy_get_tree:parents');
drupal_static_reset('taxonomy_get_tree:terms');
Dries Buytaert
committed
drupal_static_reset('taxonomy_get_parents');
Dries Buytaert
committed
drupal_static_reset('taxonomy_get_parents_all');
Dries Buytaert
committed
drupal_static_reset('taxonomy_get_children');
Dries Buytaert
committed
entity_get_controller('taxonomy_term')->resetCache();
Dries Buytaert
committed
}
Dries Buytaert
committed
* @return
* An array of all vocabulary objects, indexed by vid.
Angie Byron
committed
function taxonomy_get_vocabularies() {
return taxonomy_vocabulary_load_multiple(FALSE, array());
Dries Buytaert
committed
/**
* Get names for all taxonomy vocabularies.
*
* @return
Dries Buytaert
committed
* An array of vocabulary ids, names, machine names, keyed by machine name.
Dries Buytaert
committed
*/
function taxonomy_vocabulary_get_names() {
Dries Buytaert
committed
$names = db_query('SELECT name, machine_name, vid FROM {taxonomy_vocabulary}')->fetchAllAssoc('machine_name');
Dries Buytaert
committed
return $names;
}
* 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.
function taxonomy_get_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);
return isset($parents[$tid]) ? $parents[$tid] : array();
/**
* Find all ancestors of a given term ID.
*/
function taxonomy_get_parents_all($tid) {
Dries Buytaert
committed
$cache = &drupal_static(__FUNCTION__, array());
if (isset($cache[$tid])) {
return $cache[$tid];
}
Angie Byron
committed
if ($term = taxonomy_term_load($tid)) {
$parents[] = $term;
$n = 0;
while ($parent = taxonomy_get_parents($parents[$n]->tid)) {
$parents = array_merge($parents, $parent);
$n++;
}
}
Dries Buytaert
committed
$cache[$tid] = $parents;
* 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 which are the children of the term $tid.
function taxonomy_get_children($tid, $vid = 0) {
$children = &drupal_static(__FUNCTION__, array());
if ($tid && !isset($children[$tid])) {
Dries Buytaert
committed
$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);
Dries Buytaert
committed
if ($vid) {
$query->condition('t.vid', $vid);
}
$query->addTag('term_access');
$query->orderBy('t.weight');
$query->orderBy('t.name');
$tids = $query->execute()->fetchCol();
$children[$tid] = taxonomy_term_load_multiple($tids);
return isset($children[$tid]) ? $children[$tid] : array();
/**
* 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.
* @param $max_depth
* The number of levels of the tree to return. Leave NULL to return all levels.
Angie Byron
committed
* @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.
* @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.
Angie Byron
committed
* Results are statically cached. Term objects will be partial or complete
* depending on the $load_entities parameter.
Angie Byron
committed
function taxonomy_get_tree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE) {
Dries Buytaert
committed
$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 get_tree() on a term
// and its children, too.
if (!isset($children[$vid])) {
$children[$vid] = array();
Dries Buytaert
committed
$parents[$vid] = array();
$terms[$vid] = array();
Dries Buytaert
committed
$query = db_select('taxonomy_term_data', 't');
$query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
Angie Byron
committed
$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;
Angie Byron
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;
Dries Buytaert
committed
$tree = array();
Angie Byron
committed
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
// 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 (count($parents[$vid][$term->tid]) > 1) {
// We have a term with multi parents here. Clone the term,
// so that the depth attribute remains correct.
$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
committed
return $tree;
* Provides a case-insensitive and trimmed mapping, to maximize the
* likelihood of a successful match.