- <?php
-
- * @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().
- */
-
- * 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/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 "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">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]);
- 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>';
- }
- }
- }
-
- * Implements hook_permission().
- */
- function taxonomy_permission() {
- $permissions = array(
- 'administer taxonomy' => array(
- '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)),
- ),
- );
- }
- return $permissions;
- }
-
- * Implements hook_entity_info().
- */
- function taxonomy_entity_info() {
- $return = array(
- 'taxonomy_term' => array(
- 'label' => t('Taxonomy term'),
- 'controller class' => 'TaxonomyTermController',
- 'base table' => 'taxonomy_term_data',
- 'uri callback' => 'taxonomy_term_uri',
- 'fieldable' => TRUE,
- 'entity keys' => array(
- 'id' => 'tid',
- 'bundle' => 'vocabulary_machine_name',
- 'label' => 'name',
- ),
- 'bundle keys' => array(
- 'bundle' => 'machine_name',
- ),
- 'bundles' => array(),
- 'view modes' => array(
-
- 'full' => array(
- 'label' => t('Taxonomy term page'),
- 'custom settings' => FALSE,
- ),
- ),
- ),
- );
- 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'),
- 'controller class' => 'TaxonomyVocabularyController',
- 'base table' => 'taxonomy_vocabulary',
- 'entity keys' => array(
- 'id' => 'vid',
- 'label' => 'name',
- ),
- 'fieldable' => FALSE,
- );
-
- return $return;
- }
-
- * Implements callback_entity_info_uri().
- */
- 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 $return;
- }
-
- * 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.
- * @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.
- * @param $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');
- $query->condition('tid', $tid);
- if ($pager) {
- $count_query = clone $query;
- $count_query->addExpression('COUNT(t.nid)');
-
- $query = $query->extend('PagerDefault');
- if ($limit !== FALSE) {
- $query = $query->limit($limit);
- }
- $query->setCountQuery($count_query);
- }
- else {
- if ($limit !== FALSE) {
- $query->range(0, $limit);
- }
- }
- $query->addField('t', 'nid');
- $query->addField('t', 'tid');
- foreach ($order as $field => $direction) {
- $query->orderBy($field, $direction);
-
-
- list($table_alias, $name) = explode('.', $field);
- $query->addField($table_alias, $name);
- }
- return $query->execute()->fetchCol();
- }
-
- * Implements hook_theme().
- */
- 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',
- ),
- );
- }
-
- * Implements hook_menu().
- */
- function taxonomy_menu() {
- $items['admin/structure/taxonomy'] = array(
- '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'),
- 'file' => 'taxonomy.admin.inc',
- );
- $items['admin/structure/taxonomy/list'] = array(
- 'title' => 'List',
- 'type' => MENU_DEFAULT_LOCAL_TASK,
- 'weight' => -10,
- );
- $items['admin/structure/taxonomy/add'] = array(
- 'title' => 'Add vocabulary',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('taxonomy_form_vocabulary'),
- 'access arguments' => array('administer taxonomy'),
- 'type' => MENU_LOCAL_ACTION,
- 'file' => 'taxonomy.admin.inc',
- );
-
- $items['taxonomy/term/%taxonomy_term'] = array(
- 'title' => 'Taxonomy term',
- 'title callback' => 'taxonomy_term_title',
- 'title arguments' => array(2),
- 'page callback' => 'taxonomy_term_page',
- 'page arguments' => array(2),
- 'access arguments' => array('access content'),
- 'file' => 'taxonomy.pages.inc',
- );
- $items['taxonomy/term/%taxonomy_term/view'] = array(
- 'title' => 'View',
- 'type' => MENU_DEFAULT_LOCAL_TASK,
- );
- $items['taxonomy/term/%taxonomy_term/edit'] = array(
- 'title' => 'Edit',
- 'page callback' => 'drupal_get_form',
-
-
- 'page arguments' => array('taxonomy_form_term', 2, NULL),
- 'access callback' => 'taxonomy_term_edit_access',
- 'access arguments' => array(2),
- 'type' => MENU_LOCAL_TASK,
- 'weight' => 10,
- '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,
- 'file' => 'taxonomy.pages.inc',
- );
- $items['taxonomy/autocomplete'] = array(
- 'title' => 'Autocomplete taxonomy',
- 'page callback' => 'taxonomy_autocomplete',
- 'access arguments' => array('access content'),
- 'type' => MENU_CALLBACK,
- 'file' => 'taxonomy.pages.inc',
- );
-
- $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name'] = array(
- 'title callback' => 'entity_label',
- 'title arguments' => array('taxonomy_vocabulary', 3),
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('taxonomy_overview_terms', 3),
- 'access arguments' => array('administer taxonomy'),
- 'file' => 'taxonomy.admin.inc',
- );
- $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/list'] = array(
- 'title' => 'List',
- 'type' => MENU_DEFAULT_LOCAL_TASK,
- 'weight' => -20,
- );
- $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/edit'] = array(
- 'title' => 'Edit',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('taxonomy_form_vocabulary', 3),
- 'access arguments' => array('administer taxonomy'),
- 'type' => MENU_LOCAL_TASK,
- 'weight' => -10,
- 'file' => 'taxonomy.admin.inc',
- );
-
- $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/add'] = array(
- 'title' => 'Add term',
- 'page callback' => 'drupal_get_form',
- 'page arguments' => array('taxonomy_form_term', array(), 3),
- 'access arguments' => array('administer taxonomy'),
- 'type' => MENU_LOCAL_ACTION,
- 'file' => 'taxonomy.admin.inc',
- );
-
- return $items;
- }
-
- * Implements hook_admin_paths().
- */
- function taxonomy_admin_paths() {
- $paths = array(
- 'taxonomy/term/*/edit' => TRUE,
- );
- return $paths;
- }
-
- * 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');
- }
-
- * Returns the sanitized name of a vocabulary.
- *
- * Deprecated. This function was previously used as a menu item title callback
- * but has been replaced by using entity_label() (which does not
- * sanitize the title, since the menu system does that automatically). In
- * Drupal 7, use that function for title callbacks, and call check_plain()
- * directly if you need a sanitized title.
- */
- function taxonomy_admin_vocabulary_title_callback($vocabulary) {
- return check_plain($vocabulary->name);
- }
-
- * Saves a vocabulary.
- *
- * @param $vocabulary
- * A vocabulary object with the following properties:
- * - vid: (optional) The ID of the vocabulary (omit if creating a new
- * vocabulary; only use to update an existing vocabulary).
- * - name: The human-readable name of the vocabulary.
- * - machine_name: The machine name of the vocabulary.
- * - description: (optional) The vocabulary's description.
- * - hierarchy: The hierarchy level of the vocabulary.
- * - module: (optional) The module altering the vocabulary.
- * - weight: (optional) The weight of this vocabulary in relation to other
- * vocabularies.
- * - original: (optional) The original vocabulary object before any changes
- * are applied.
- * - old_machine_name: (optional) The original machine name of the
- * vocabulary.
- *
- * @return
- * Status constant indicating whether the vocabulary was inserted (SAVED_NEW)
- * or updated (SAVED_UPDATED).
- */
- function taxonomy_vocabulary_save($vocabulary) {
-
- if (!empty($vocabulary->name)) {
- $vocabulary->name = trim($vocabulary->name);
- }
-
- if (!empty($vocabulary->vid)) {
- if (!isset($vocabulary->original)) {
- $vocabulary->original = entity_load_unchanged('taxonomy_vocabulary', $vocabulary->vid);
- }
-
-
-
- $vocabulary->old_machine_name = $vocabulary->original->machine_name;
- }
-
- if (!isset($vocabulary->module)) {
- $vocabulary->module = 'taxonomy';
- }
-
- module_invoke_all('taxonomy_vocabulary_presave', $vocabulary);
- module_invoke_all('entity_presave', $vocabulary, 'taxonomy_vocabulary');
-
- if (!empty($vocabulary->vid) && !empty($vocabulary->name)) {
- $status = drupal_write_record('taxonomy_vocabulary', $vocabulary, 'vid');
- taxonomy_vocabulary_static_reset(array($vocabulary->vid));
- if ($vocabulary->old_machine_name != $vocabulary->machine_name) {
- field_attach_rename_bundle('taxonomy_term', $vocabulary->old_machine_name, $vocabulary->machine_name);
- }
- module_invoke_all('taxonomy_vocabulary_update', $vocabulary);
- module_invoke_all('entity_update', $vocabulary, 'taxonomy_vocabulary');
- }
- elseif (empty($vocabulary->vid)) {
- $status = drupal_write_record('taxonomy_vocabulary', $vocabulary);
- taxonomy_vocabulary_static_reset();
- field_attach_create_bundle('taxonomy_term', $vocabulary->machine_name);
- module_invoke_all('taxonomy_vocabulary_insert', $vocabulary);
- module_invoke_all('entity_insert', $vocabulary, 'taxonomy_vocabulary');
- }
-
- unset($vocabulary->original);
- cache_clear_all();
-
- return $status;
- }
-
- * Delete a vocabulary.
- *
- * @param $vid
- * A vocabulary ID.
- * @return
- * Constant indicating items were deleted.
- */
- function taxonomy_vocabulary_delete($vid) {
- $vocabulary = taxonomy_vocabulary_load($vid);
-
- $transaction = db_transaction();
- try {
-
- $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();
-
- field_attach_delete_bundle('taxonomy_term', $vocabulary->machine_name);
- module_invoke_all('taxonomy_vocabulary_delete', $vocabulary);
- module_invoke_all('entity_delete', $vocabulary, 'taxonomy_vocabulary');
-
-
-
- $taxonomy_fields = field_read_fields(array('module' => 'taxonomy'));
- foreach ($taxonomy_fields as $field_name => $taxonomy_field) {
- $modified_field = FALSE;
-
-
- foreach ($taxonomy_field['settings']['allowed_values'] as $key => $allowed_value) {
- if ($allowed_value['vocabulary'] == $vocabulary->machine_name) {
- unset($taxonomy_field['settings']['allowed_values'][$key]);
- $modified_field = TRUE;
- }
- }
- if ($modified_field) {
- if (empty($taxonomy_field['settings']['allowed_values'])) {
- field_delete_field($field_name);
- }
- else {
-
- field_update_field($taxonomy_field);
- }
- }
- }
-
- cache_clear_all();
- taxonomy_vocabulary_static_reset();
-
- return SAVED_DELETED;
- }
- catch (Exception $e) {
- $transaction->rollback();
- watchdog_exception('taxonomy', $e);
- throw $e;
- }
- }
-
- * Implements hook_taxonomy_vocabulary_update().
- */
- function taxonomy_taxonomy_vocabulary_update($vocabulary) {
-
-
- 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) {
- if ($value['vocabulary'] == $vocabulary->old_machine_name) {
- $value['vocabulary'] = $vocabulary->machine_name;
- $update = TRUE;
- }
- }
- if ($update) {
- field_update_field($field);
- }
- }
- }
- }
- }
-
- * 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 0.
- * If any term has a single parent then the vocabulary will be given a
- * hierarchy of 1. If any term has multiple parents then the vocabulary
- * will be given a hierarchy of 2.
- *
- * @param $vocabulary
- * A vocabulary object.
- * @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, $changed_term) {
- $tree = taxonomy_get_tree($vocabulary->vid);
- $hierarchy = 0;
- foreach ($tree as $term) {
-
- if ($term->tid == $changed_term['tid']) {
- $term = (object) $changed_term;
- $term->parents = $term->parent;
- }
-
- if (count($term->parents) > 1) {
- $hierarchy = 2;
- break;
- }
- elseif (count($term->parents) == 1 && !isset($term->parents[0])) {
- $hierarchy = 1;
- }
- }
- if ($hierarchy != $vocabulary->hierarchy) {
- $vocabulary->hierarchy = $hierarchy;
- taxonomy_vocabulary_save($vocabulary);
- }
-
- return $hierarchy;
- }
-
- * Saves a term object to the database.
- *
- * @param $term
- * The taxonomy term object with the following properties:
- * - vid: The ID of the vocabulary the term is assigned to.
- * - name: The name of the term.
- * - tid: (optional) The unique ID for the term being saved. If $term->tid is
- * empty or omitted, a new term will be inserted.
- * - description: (optional) The term's description.
- * - format: (optional) The text format for the term's description.
- * - weight: (optional) The weight of this term in relation to other terms
- * within the same vocabulary.
- * - parent: (optional) The parent term(s) for this term. This can be a single
- * term ID or an array of term IDs. A value of 0 means this term does not
- * have any parents. When omitting this variable during an update, the
- * existing hierarchy for the term remains unchanged.
- * - vocabulary_machine_name: (optional) The machine name of the vocabulary
- * the term is assigned to. If not given, this value will be set
- * automatically by loading the vocabulary based on $term->vid.
- * - original: (optional) The original taxonomy term object before any changes
- * were applied. When omitted, the unchanged taxonomy term object is
- * loaded from the database and stored in this property.
- * Since a taxonomy term is an entity, any fields contained in the term object
- * are saved alongside the term object.
- *
- * @return
- * 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.
- */
- function taxonomy_term_save($term) {
-
- $term->name = trim($term->name);
- if (!isset($term->vocabulary_machine_name)) {
- $vocabulary = taxonomy_vocabulary_load($term->vid);
- $term->vocabulary_machine_name = $vocabulary->machine_name;
- }
-
-
- if (!empty($term->tid) && !isset($term->original)) {
- $term->original = entity_load_unchanged('taxonomy_term', $term->tid);
- }
-
- field_attach_presave('taxonomy_term', $term);
- module_invoke_all('taxonomy_term_presave', $term);
- module_invoke_all('entity_presave', $term, 'taxonomy_term');
-
- if (empty($term->tid)) {
- $op = 'insert';
- $status = drupal_write_record('taxonomy_term_data', $term);
- field_attach_insert('taxonomy_term', $term);
- if (!isset($term->parent)) {
- $term->parent = array(0);
- }
- }
- else {
- $op = 'update';
- $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();
- }
- }
-
- 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) {
- $query->values(array(
- 'tid' => $term->tid,
- 'parent' => $tid
- ));
- }
- }
- else {
- $query->values(array(
- 'tid' => $term->tid,
- 'parent' => $parent
- ));
- }
- }
- $query->execute();
- }
-
-
- taxonomy_terms_static_reset();
-
-
- module_invoke_all("taxonomy_term_$op", $term);
- module_invoke_all("entity_$op", $term, 'taxonomy_term');
- unset($term->original);
-
- return $status;
- }
-
- * Delete a term.
- *
- * @param $tid
- * The term ID.
- * @return
- * Status constant indicating deletion.
- */
- function taxonomy_term_delete($tid) {
- $transaction = db_transaction();
- try {
- $tids = array($tid);
- while ($tids) {
- $children_tids = $orphans = array();
- foreach ($tids as $tid) {
-
- if ($children = taxonomy_get_children($tid)) {
- foreach ($children as $child) {
-
- $parents = taxonomy_get_parents($child->tid);
- if (count($parents) == 1) {
- $orphans[] = $child->tid;
- }
- }
- }
-
- 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();
- }
- }
-
- $tids = $orphans;
- }
- return SAVED_DELETED;
- }
- catch (Exception $e) {
- $transaction->rollback();
- watchdog_exception('taxonomy', $e);
- throw $e;
- }
- }
-
- * Generates an array which displays a term detail page.
- *
- * @param term
- * A taxonomy term object.
- * @return
- * A $page element suitable for use by drupal_page_render().
- */
- function taxonomy_term_show($term) {
- return taxonomy_term_view_multiple(array($term->tid => $term), 'full');
- }
-
- * Constructs a drupal_render() style array from an array of loaded terms.
- *
- * @param $terms
- * An array of taxonomy terms as returned by taxonomy_term_load_multiple().
- * @param $view_mode
- * View mode, e.g. 'full', 'teaser'...
- * @param $weight
- * An integer representing the weight of the first taxonomy term in the list.
- * @param $langcode
- * (optional) A language code to use for rendering. Defaults to the global
- * content language of the current request.
- *
- * @return
- * An array in the format expected by drupal_render().
- */
- function taxonomy_term_view_multiple($terms, $view_mode = 'teaser', $weight = 0, $langcode = NULL) {
- field_attach_prepare_view('taxonomy_term', $terms, $view_mode, $langcode);
- entity_prepare_view('taxonomy_term', $terms, $langcode);
- $build = array();
- foreach ($terms as $term) {
- $build['taxonomy_terms'][$term->tid] = taxonomy_term_view($term, $view_mode, $langcode);
- $build['taxonomy_terms'][$term->tid]['#weight'] = $weight;
- $weight++;
- }
- $build['taxonomy_terms']['#sorted'] = TRUE;
- return $build;
- }
-
- * Builds a structured array representing the term's content.
- *
- * The content built for the taxonomy term (field values, file attachments or
- * other term components) will vary depending on the $view_mode parameter.
- *
- * Drupal core defines the following view modes for terms, with the following
- * default use cases:
- * - full (default): term is displayed on its own page (taxonomy/term/123)
- * Contributed modules might define additional view modes, or use existing
- * view modes in additional contexts.
- *
- * @param $term
- * A taxonomy term object.
- * @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.
- */
- function taxonomy_term_build_content($term, $view_mode = 'full', $langcode = NULL) {
- if (!isset($langcode)) {
- $langcode = $GLOBALS['language_content']->language;
- }
-
-
- $term->content = array();
-
-
- $context = array(
- 'entity_type' => 'taxonomy_term',
- 'entity' => $term,
- 'langcode' => $langcode,
- );
- drupal_alter('entity_view_mode', $view_mode, $context);
-
-
- $type = 'taxonomy_term';
- $entity_ids = entity_extract_ids($type, $term);
- $settings = field_view_mode_settings($type, $entity_ids[2]);
- $fields = field_extra_fields_get_display($type, $entity_ids[2], $view_mode);
- if (!empty($term->description) && isset($fields['description']) && $fields['description']['visible']) {
- $term->content['description'] = array(
- '#markup' => check_markup($term->description, $term->format, '', TRUE),
- '#weight' => $fields['description']['weight'],
- '#prefix' => '<div class="taxonomy-term-description">',
- '#suffix' => '</div>',
- );
- }
-
-
-
-
-
- field_attach_prepare_view('taxonomy_term', array($term->tid => $term), $view_mode, $langcode);
- entity_prepare_view('taxonomy_term', array($term->tid => $term), $langcode);
- $term->content += field_attach_view('taxonomy_term', $term, $view_mode, $langcode);
-
-
- module_invoke_all('taxonomy_term_view', $term, $view_mode, $langcode);
- module_invoke_all('entity_view', $term, 'taxonomy_term', $view_mode, $langcode);
-
-
-
- $term->content += array('#view_mode' => $view_mode);
- }
-
- * Generate an array for rendering the given term.
- *
- * @param $term
- * A term object.
- * @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, $view_mode = 'full', $langcode = NULL) {
- if (!isset($langcode)) {
- $langcode = $GLOBALS['language_content']->language;
- }
-
-
- taxonomy_term_build_content($term, $view_mode, $langcode);
- $build = $term->content;
-
-
- unset($term->content);
-
- $build += array(
- '#theme' => 'taxonomy_term',
- '#term' => $term,
- '#view_mode' => $view_mode,
- '#language' => $langcode,
- );
-
- $build['#attached']['css'][] = drupal_get_path('module', 'taxonomy') . '/taxonomy.css';
-
-
- $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'];
-
- $uri = entity_uri('taxonomy_term', $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);
-
-
- $variables = array_merge((array) $term, $variables);
-
-
- $variables['content'] = array();
- foreach (element_children($variables['elements']) as $key) {
- $variables['content'][$key] = $variables['elements'][$key];
- }
-
-
-
-
-
- field_attach_preprocess('taxonomy_term', $term, $variables['content'], $variables);
-
-
- $vocabulary_name_css = str_replace('_', '-', $term->vocabulary_machine_name);
- $variables['classes_array'][] = '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.
- *
- * @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);
- }
-
- * 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');
- drupal_static_reset('taxonomy_get_parents');
- drupal_static_reset('taxonomy_get_parents_all');
- drupal_static_reset('taxonomy_get_children');
- entity_get_controller('taxonomy_term')->resetCache();
- }
-
- * Clear all static cache variables for vocabularies.
- *
- * @param $ids
- * An array of ids to reset in entity controller cache.
- */
- function taxonomy_vocabulary_static_reset($ids = NULL) {
- drupal_static_reset('taxonomy_vocabulary_get_names');
- entity_get_controller('taxonomy_vocabulary')->resetCache($ids);
- }
-
- * Return an array of all vocabulary objects.
- *
- * @return
- * An array of all vocabulary objects, indexed by vid.
- */
- function taxonomy_get_vocabularies() {
- return taxonomy_vocabulary_load_multiple(FALSE, array());
- }
-
- * 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');
- }
-
- 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, or an
- * empty array if parents are not found.
- */
- 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) {
- $cache = &drupal_static(__FUNCTION__, array());
-
- if (isset($cache[$tid])) {
- return $cache[$tid];
- }
-
- $parents = array();
- if ($term = taxonomy_term_load($tid)) {
- $parents[] = $term;
- $n = 0;
- while ($parent = taxonomy_get_parents($parents[$n]->tid)) {
- $parents = array_merge($parents, $parent);
- $n++;
- }
- }
-
- $cache[$tid] = $parents;
-
- return $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 that are the children of the term $tid, or an
- * empty array when no children exist.
- */
- function taxonomy_get_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);
- 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.
- * @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.
- * Results are statically cached. Term objects will be partial or complete
- * depending on the $load_entities parameter.
- */
- 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());
-
-
-
- if (!isset($children[$vid])) {
- $children[$vid] = array();
- $parents[$vid] = array();
- $terms[$vid] = array();
-
- $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;
- }
- }
-
-
-
- if ($load_entities) {
- $term_entities = taxonomy_term_load_multiple(array_keys($terms[$vid]));
- }
-
- $max_depth = (!isset($max_depth)) ? count($children[$vid]) : $max_depth;
- $tree = array();
-
-
-
- $process_parents = array();
- $process_parents[] = $parent;
-
-
-
- while (count($process_parents)) {
- $parent = array_pop($process_parents);
-
- $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])) {
-
-
- $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;
-
-
- $process_parents[] = $parent;
-
- $process_parents[] = $term->tid;
-
-
-
- reset($children[$vid][$term->tid]);
-
- next($children[$vid][$parent]);
- break;
- }
- } while ($child = next($children[$vid][$parent]));
-
- if (!$has_children) {
-
-
- reset($children[$vid][$parent]);
- }
- }
- }
-
- return $tree;
- }
-
- * Try to map a string to an existing term, as for glossary use.
- *
- * Provides a case-insensitive and trimmed mapping, to maximize the
- * likelihood of a successful match.
- *
- * @param $name
- * Name of the term to search for.
- * @param $vocabulary
- * (optional) Vocabulary machine name to limit the search. Defaults to NULL.
- *
- * @return
- * An array of matching term objects.
- */
- function taxonomy_get_term_by_name($name, $vocabulary = NULL) {
- $conditions = array('name' => trim($name));
- if (isset($vocabulary)) {
- $vocabularies = taxonomy_vocabulary_get_names();
- if (isset($vocabularies[$vocabulary])) {
- $conditions['vid'] = $vocabularies[$vocabulary]->vid;
- }
- else {
-
- return array();
- }
- }
- return taxonomy_term_load_multiple(array(), $conditions);
- }
-
- * 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 function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
- $query = parent::buildQuery($ids, $conditions, $revision_id);
- $query->addTag('translatable');
- $query->addTag('term_access');
-
- if (isset($conditions['name'])) {
- $query_conditions = &$query->conditions();
- foreach ($query_conditions as $key => $condition) {
- if (is_array($condition) && $condition['field'] == 'base.name') {
- $query_conditions[$key]['operator'] = 'LIKE';
- $query_conditions[$key]['value'] = db_like($query_conditions[$key]['value']);
- }
- }
- }
-
- $query->innerJoin('taxonomy_vocabulary', 'v', 'base.vid = v.vid');
- $query->addField('v', 'machine_name', 'vocabulary_machine_name');
- return $query;
- }
-
- protected function cacheGet($ids, $conditions = array()) {
- $terms = parent::cacheGet($ids, $conditions);
-
-
- foreach ($terms as $term) {
- $term_values = (array) $term;
- if (isset($conditions['name']) && drupal_strtolower($conditions['name'] != drupal_strtolower($term_values['name']))) {
- unset($terms[$term->tid]);
- }
- }
- return $terms;
- }
- }
-
- * 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($ids, $conditions = array(), $revision_id = FALSE) {
- $query = parent::buildQuery($ids, $conditions, $revision_id);
- $query->addTag('translatable');
- $query->orderBy('base.weight');
- $query->orderBy('base.name');
- return $query;
- }
- }
-
- * 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 entity_load()
- * @see EntityFieldQuery
- *
- * @param $tids
- * An array of taxonomy term IDs.
- * @param $conditions
- * (deprecated) An associative array of conditions on the {taxonomy_term}
- * table, where the keys are the database fields and the values are the
- * values those fields must have. Instead, it is preferable to use
- * EntityFieldQuery to retrieve a list of entity IDs loadable by
- * this function.
- *
- * @return
- * An array of term objects, indexed by tid. When no results are found, an
- * empty array is returned.
- *
- * @todo Remove $conditions in Drupal 8.
- */
- 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.
- *
- * @see taxonomy_vocabulary_machine_name_load()
- */
- function taxonomy_vocabulary_load($vid) {
- $vocabularies = taxonomy_vocabulary_load_multiple(array($vid));
- return reset($vocabularies);
- }
-
- * Return the vocabulary object matching a vocabulary machine name.
- *
- * @param $name
- * The vocabulary's machine name.
- *
- * @return
- * The vocabulary object with all of its metadata, if exists, FALSE otherwise.
- * Results are statically cached.
- *
- * @see taxonomy_vocabulary_load()
- */
- function taxonomy_vocabulary_machine_name_load($name) {
- $vocabularies = taxonomy_vocabulary_load_multiple(NULL, array('machine_name' => $name));
- return reset($vocabularies);
- }
-
- * Return the term object matching a term ID.
- *
- * @param $tid
- * A term's ID
- *
- * @return
- * A taxonomy term object, or FALSE if the term was not found. Results are
- * statically cached.
- */
- function taxonomy_term_load($tid) {
- if (!is_numeric($tid)) {
- return FALSE;
- }
- $term = taxonomy_term_load_multiple(array($tid), array());
- return $term ? $term[$tid] : FALSE;
- }
-
- * 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.
- *
- * @see drupal_explode_tags()
- */
- function taxonomy_implode_tags($tags, $vid = NULL) {
- $typed_tags = array();
- foreach ($tags as $tag) {
-
- if (!isset($vid) || $tag->vid == $vid) {
-
- if (isset($tag->name)) {
-
- if (strpos($tag->name, ',') !== FALSE || strpos($tag->name, '"') !== FALSE) {
- $typed_tags[] = '"' . str_replace('"', '""', $tag->name) . '"';
- }
- else {
- $typed_tags[] = $tag->name;
- }
- }
- }
- }
- return implode(', ', $typed_tags);
- }
-
- * Implements hook_field_info().
- *
- * Field settings:
- * - allowed_values: a list array of one or more vocabulary trees:
- * - vocabulary: a vocabulary machine name.
- * - 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_reference' => array(
- 'label' => t('Term reference'),
- 'description' => t('This field stores a reference to a taxonomy term.'),
- 'default_widget' => 'options_select',
- 'default_formatter' => 'taxonomy_term_reference_link',
- 'settings' => array(
- 'allowed_values' => array(
- array(
- 'vocabulary' => '',
- 'parent' => '0',
- ),
- ),
- ),
- ),
- );
- }
-
- * Implements hook_field_widget_info().
- */
- function taxonomy_field_widget_info() {
- return array(
- 'taxonomy_autocomplete' => array(
- 'label' => t('Autocomplete term widget (tagging)'),
- 'field types' => array('taxonomy_term_reference'),
- 'settings' => array(
- 'size' => 60,
- 'autocomplete_path' => 'taxonomy/autocomplete',
- ),
- 'behaviors' => array(
- 'multiple values' => FIELD_BEHAVIOR_CUSTOM,
- ),
- ),
- );
- }
-
- * Implements hook_field_widget_info_alter().
- */
- function taxonomy_field_widget_info_alter(&$info) {
- $info['options_select']['field types'][] = 'taxonomy_term_reference';
- $info['options_buttons']['field types'][] = 'taxonomy_term_reference';
- }
-
- * Implements hook_options_list().
- */
- function taxonomy_options_list($field, $instance, $entity_type, $entity) {
- $function = !empty($field['settings']['options_list_callback']) ? $field['settings']['options_list_callback'] : 'taxonomy_allowed_values';
- return $function($field);
- }
-
- * Implements hook_field_validate().
- *
- * Taxonomy field settings allow for either a single vocabulary ID, multiple
- * vocabulary IDs, or sub-trees of a vocabulary to be specified as allowed
- * values, although only the first of these is supported via the field UI.
- * Confirm that terms entered as values meet at least one of these conditions.
- *
- * Possible error codes:
- * - 'taxonomy_term_illegal_value': The value is not part of the list of allowed values.
- */
- function taxonomy_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
-
-
- foreach ($items as $delta => $item) {
- if (!empty($item['tid']) && $item['tid'] != 'autocreate') {
- $tids[] = $item['tid'];
- }
- }
- if (!empty($tids)) {
- $terms = taxonomy_term_load_multiple($tids);
-
-
-
- foreach ($items as $delta => $item) {
- $validate = TRUE;
- if (!empty($item['tid']) && $item['tid'] != 'autocreate') {
- $validate = FALSE;
- foreach ($field['settings']['allowed_values'] as $settings) {
-
- if (isset($settings['vocabulary']) && empty($settings['parent'])) {
- if ($settings['vocabulary'] == $terms[$item['tid']]->vocabulary_machine_name) {
- $validate = TRUE;
- break;
- }
- }
-
-
- elseif (!empty($settings['parent'])) {
- $ancestors = taxonomy_get_parents_all($item['tid']);
- foreach ($ancestors as $ancestor) {
- if ($ancestor->tid == $settings['parent']) {
- $validate = TRUE;
- break 2;
- }
- }
- }
- }
- }
- if (!$validate) {
- $errors[$field['field_name']][$langcode][$delta][] = array(
- 'error' => 'taxonomy_term_reference_illegal_value',
- 'message' => t('%name: illegal value.', array('%name' => $instance['label'])),
- );
- }
- }
- }
- }
-
- * Implements hook_field_is_empty().
- */
- function taxonomy_field_is_empty($item, $field) {
- if (!is_array($item) || (empty($item['tid']) && (string) $item['tid'] !== '0')) {
- return TRUE;
- }
- return FALSE;
- }
-
- * Implements hook_field_formatter_info().
- */
- function taxonomy_field_formatter_info() {
- return array(
- 'taxonomy_term_reference_link' => array(
- 'label' => t('Link'),
- 'field types' => array('taxonomy_term_reference'),
- ),
- 'taxonomy_term_reference_plain' => array(
- 'label' => t('Plain text'),
- 'field types' => array('taxonomy_term_reference'),
- ),
- 'taxonomy_term_reference_rss_category' => array(
- 'label' => t('RSS category'),
- 'field types' => array('taxonomy_term_reference'),
- ),
- );
- }
-
- * Implements hook_field_formatter_view().
- */
- function taxonomy_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
- $element = array();
-
-
-
-
-
- switch ($display['type']) {
- case 'taxonomy_term_reference_link':
- foreach ($items as $delta => $item) {
- if ($item['tid'] == 'autocreate') {
- $element[$delta] = array(
- '#markup' => check_plain($item['name']),
- );
- }
- else {
- $term = $item['taxonomy_term'];
- $uri = entity_uri('taxonomy_term', $term);
- $element[$delta] = array(
- '#type' => 'link',
- '#title' => $term->name,
- '#href' => $uri['path'],
- '#options' => $uri['options'],
- );
- }
- }
- break;
-
- case 'taxonomy_term_reference_plain':
- foreach ($items as $delta => $item) {
- $name = ($item['tid'] != 'autocreate' ? $item['taxonomy_term']->name : $item['name']);
- $element[$delta] = array(
- '#markup' => check_plain($name),
- );
- }
- break;
-
- case 'taxonomy_term_reference_rss_category':
- foreach ($items as $delta => $item) {
- $entity->rss_elements[] = array(
- 'key' => 'category',
- 'value' => $item['tid'] != 'autocreate' ? $item['taxonomy_term']->name : $item['name'],
- 'attributes' => array(
- 'domain' => $item['tid'] != 'autocreate' ? url('taxonomy/term/' . $item['tid'], array('absolute' => TRUE)) : '',
- ),
- );
- }
- break;
- }
-
- return $element;
- }
-
- * Returns the set of valid terms for a taxonomy field.
- *
- * @param $field
- * The field definition.
- * @return
- * The array of valid terms for this field, keyed by term id.
- */
- function taxonomy_allowed_values($field) {
- $options = array();
- foreach ($field['settings']['allowed_values'] as $tree) {
- if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
- if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'])) {
- foreach ($terms as $term) {
- $options[$term->tid] = str_repeat('-', $term->depth) . $term->name;
- }
- }
- }
- }
- return $options;
- }
-
- * Implements hook_field_formatter_prepare_view().
- *
- * This preloads all taxonomy terms for multiple loaded objects at once and
- * unsets values for invalid terms that do not exist.
- */
- function taxonomy_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays) {
- $tids = array();
-
-
- foreach ($entities as $id => $entity) {
- foreach ($items[$id] as $delta => $item) {
-
- if ($item['tid'] != 'autocreate') {
- $tids[$item['tid']] = $item['tid'];
- }
- }
- }
- if ($tids) {
- $terms = taxonomy_term_load_multiple($tids);
-
-
- foreach ($entities as $id => $entity) {
- $rekey = FALSE;
-
- foreach ($items[$id] as $delta => $item) {
-
- if (isset($terms[$item['tid']])) {
-
- $items[$id][$delta]['taxonomy_term'] = $terms[$item['tid']];
- }
-
- elseif ($item['tid'] == 'autocreate') {
-
- }
-
- else {
- unset($items[$id][$delta]);
- $rekey = TRUE;
- }
- }
-
- if ($rekey) {
-
- $items[$id] = array_values($items[$id]);
- }
- }
- }
- }
-
- * Title callback for term pages.
- *
- * @param $term
- * A term object.
- *
- * @return
- * The term name to be used as the page title.
- */
- function taxonomy_term_title($term) {
- return $term->name;
- }
-
- * Implements hook_field_widget_form().
- */
- function taxonomy_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
- $tags = array();
- foreach ($items as $item) {
- $tags[$item['tid']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
- }
-
- $element += array(
- '#type' => 'textfield',
- '#default_value' => taxonomy_implode_tags($tags),
- '#autocomplete_path' => $instance['widget']['settings']['autocomplete_path'] . '/' . $field['field_name'],
- '#size' => $instance['widget']['settings']['size'],
- '#maxlength' => 1024,
- '#element_validate' => array('taxonomy_autocomplete_validate'),
- );
-
- return $element;
- }
-
- * Form element validate handler for taxonomy term autocomplete element.
- */
- function taxonomy_autocomplete_validate($element, &$form_state) {
-
-
- $value = array();
- if ($tags = $element['#value']) {
-
- $field = field_widget_field($element, $form_state);
- $vocabularies = array();
- foreach ($field['settings']['allowed_values'] as $tree) {
- if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
- $vocabularies[$vocabulary->vid] = $vocabulary;
- }
- }
-
-
- $typed_terms = drupal_explode_tags($tags);
- foreach ($typed_terms as $typed_term) {
-
-
- if ($possibilities = taxonomy_term_load_multiple(array(), array('name' => trim($typed_term), 'vid' => array_keys($vocabularies)))) {
- $term = array_pop($possibilities);
- }
- else {
- $vocabulary = reset($vocabularies);
- $term = array(
- 'tid' => 'autocreate',
- 'vid' => $vocabulary->vid,
- 'name' => $typed_term,
- 'vocabulary_machine_name' => $vocabulary->machine_name,
- );
- }
- $value[] = (array)$term;
- }
- }
-
- form_set_value($element, $value, $form_state);
- }
-
- * Implements hook_field_widget_error().
- */
- function taxonomy_field_widget_error($element, $error, $form, &$form_state) {
- form_error($element, $error['message']);
- }
- * Implements hook_field_settings_form().
- */
- function taxonomy_field_settings_form($field, $instance, $has_data) {
-
- $vocabularies = taxonomy_get_vocabularies();
- $options = array();
- foreach ($vocabularies as $vocabulary) {
- $options[$vocabulary->machine_name] = $vocabulary->name;
- }
- $form['allowed_values'] = array(
- '#tree' => TRUE,
- );
-
- foreach ($field['settings']['allowed_values'] as $delta => $tree) {
- $form['allowed_values'][$delta]['vocabulary'] = array(
- '#type' => 'select',
- '#title' => t('Vocabulary'),
- '#default_value' => $tree['vocabulary'],
- '#options' => $options,
- '#required' => TRUE,
- '#description' => t('The vocabulary which supplies the options for this field.'),
- '#disabled' => $has_data,
- );
- $form['allowed_values'][$delta]['parent'] = array(
- '#type' => 'value',
- '#value' => $tree['parent'],
- );
- }
-
- return $form;
- }
-
- * Implements hook_rdf_mapping().
- *
- * @return array
- * The rdf mapping for vocabularies and terms.
- */
- function taxonomy_rdf_mapping() {
- return array(
- array(
- 'type' => 'taxonomy_term',
- 'bundle' => RDF_DEFAULT_BUNDLE,
- 'mapping' => array(
- 'rdftype' => array('skos:Concept'),
- 'name' => array(
- 'predicates' => array('rdfs:label', 'skos:prefLabel'),
- ),
- 'description' => array(
- 'predicates' => array('skos:definition'),
- ),
- 'vid' => array(
- 'predicates' => array('skos:inScheme'),
- 'type' => 'rel',
- ),
- 'parent' => array(
- 'predicates' => array('skos:broader'),
- 'type' => 'rel',
- ),
- ),
- ),
- array(
- 'type' => 'taxonomy_vocabulary',
- 'bundle' => RDF_DEFAULT_BUNDLE,
- 'mapping' => array(
- 'rdftype' => array('skos:ConceptScheme'),
- 'name' => array(
- 'predicates' => array('dc:title'),
- ),
- 'description' => array(
- 'predicates' => array('rdfs:comment'),
- ),
- ),
- ),
- );
- }
-
- * @defgroup taxonomy_index Taxonomy indexing
- * @{
- * Functions to maintain taxonomy indexing.
- *
- * Taxonomy uses default field storage to store canonical relationships
- * between terms and fieldable entities. However its most common use case
- * requires listing all content associated with a term or group of terms
- * sorted by creation date. To avoid slow queries due to joining across
- * multiple node and field tables with various conditions and order by criteria,
- * we maintain a denormalized table with all relationships between terms,
- * published nodes and common sort criteria such as sticky and created.
- * This is used as a lookup table by taxonomy_select_nodes(). When using other
- * field storage engines or alternative methods of denormalizing this data
- * you should set the variable 'taxonomy_maintain_index_table' to FALSE
- * to avoid unnecessary writes in SQL.
- */
-
- * Implements hook_field_presave().
- *
- * Create any new terms defined in a freetagging vocabulary.
- */
- function taxonomy_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
- foreach ($items as $delta => $item) {
- if ($item['tid'] == 'autocreate') {
- $term = (object) $item;
- unset($term->tid);
- taxonomy_term_save($term);
- $items[$delta]['tid'] = $term->tid;
- }
- }
- }
-
- * Implements hook_node_insert().
- */
- function taxonomy_node_insert($node) {
-
- taxonomy_build_node_index($node);
- }
-
- * Builds and inserts taxonomy index entries for a given node.
- *
- * The index lists all terms that are related to a given node entity, and is
- * therefore maintained at the entity level.
- *
- * @param $node
- * The node object.
- */
- function taxonomy_build_node_index($node) {
-
-
- $status = NULL;
- if (variable_get('taxonomy_maintain_index_table', TRUE)) {
-
-
- if (!empty($node->original)) {
- $status = (int)(!empty($node->status) || (!isset($node->status) && !empty($node->original->status)));
- $sticky = (int)(!empty($node->sticky) || (!isset($node->sticky) && !empty($node->original->sticky)));
- }
- else {
- $status = (int)(!empty($node->status));
- $sticky = (int)(!empty($node->sticky));
- }
- }
-
- if ($status) {
-
- $tid_all = array();
- foreach (field_info_instances('node', $node->type) as $instance) {
- $field_name = $instance['field_name'];
- $field = field_info_field($field_name);
- if ($field['module'] == 'taxonomy' && $field['storage']['type'] == 'field_sql_storage') {
-
-
- if (isset($node->{$field_name})) {
- $items = $node->{$field_name};
- }
- elseif (isset($node->original->{$field_name})) {
- $items = $node->original->{$field_name};
- }
- else {
- continue;
- }
- foreach (field_available_languages('node', $field) as $langcode) {
- if (!empty($items[$langcode])) {
- foreach ($items[$langcode] as $item) {
- $tid_all[$item['tid']] = $item['tid'];
- }
- }
- }
- }
- }
-
- if (!empty($tid_all)) {
- $query = db_insert('taxonomy_index')->fields(array('nid', 'tid', 'sticky', 'created'));
- foreach ($tid_all as $tid) {
- $query->values(array(
- 'nid' => $node->nid,
- 'tid' => $tid,
- 'sticky' => $sticky,
- 'created' => $node->created,
- ));
- }
- $query->execute();
- }
- }
- }
-
- * Implements hook_node_update().
- */
- function taxonomy_node_update($node) {
-
- taxonomy_delete_node_index($node);
- taxonomy_build_node_index($node);
- }
-
- * Implements hook_node_delete().
- */
- function taxonomy_node_delete($node) {
-
- taxonomy_delete_node_index($node);
- }
-
- * Deletes taxonomy index entries for a given node.
- *
- * @param $node
- * The node object.
- */
- function taxonomy_delete_node_index($node) {
- if (variable_get('taxonomy_maintain_index_table', TRUE)) {
- db_delete('taxonomy_index')->condition('nid', $node->nid)->execute();
- }
- }
-
- * Implements hook_taxonomy_term_delete().
- */
- function taxonomy_taxonomy_term_delete($term) {
- if (variable_get('taxonomy_maintain_index_table', TRUE)) {
-
- db_delete('taxonomy_index')->condition('tid', $term->tid)->execute();
- }
- }
-
- * @} End of "defgroup taxonomy_index".
- */
-
- * Implements hook_entity_query_alter().
- *
- * Converts EntityFieldQuery instances on taxonomy terms that have an entity
- * condition on term bundles (vocabulary machine names). Since the vocabulary
- * machine name is not present in the {taxonomy_term_data} table itself, we have
- * to convert the bundle condition into a property condition of vocabulary IDs
- * to match against {taxonomy_term_data}.vid.
- */
- function taxonomy_entity_query_alter($query) {
- $conditions = &$query->entityConditions;
-
-
- if (isset($conditions['entity_type']) && $conditions['entity_type']['value'] == 'taxonomy_term' && isset($conditions['bundle'])) {
-
- $vocabulary_data = taxonomy_vocabulary_get_names();
- $vids = array();
- if (is_array($conditions['bundle']['value'])) {
- foreach ($conditions['bundle']['value'] as $vocabulary_machine_name) {
- $vids[] = $vocabulary_data[$vocabulary_machine_name]->vid;
- }
- }
- else {
- $vocabulary_machine_name = $conditions['bundle']['value'];
- $vids = $vocabulary_data[$vocabulary_machine_name]->vid;
- }
-
- $query->propertyCondition('vid', $vids, $conditions['bundle']['operator']);
- unset($conditions['bundle']);
- }
- }
-