taxonomy.module 60.2 KB
Newer Older
1
<?php
2

3 4 5 6 7
/**
 * @file
 * Enables the organization of content into categories.
 */

8 9 10 11 12 13 14 15
/**
 * 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().
 */

16
/**
17
 * Implements hook_help().
18 19 20 21 22 23 24 25 26 27
 */
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>';
28
      $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'))));
29
      $output .= '<ul><li>' . t('<em>vocabulary</em>: Music') . '</li>';
30 31 32 33 34 35 36 37 38
      $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>';
39
      $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>';
40
      $output .= '<dt>' . t('Classifying content') . '</dt>';
41
      $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>';
42 43 44 45 46 47 48
      $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':
49
      $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>';
50 51
      return $output;
    case 'admin/structure/taxonomy/%':
52
      $vocabulary = taxonomy_vocabulary_machine_name_load($arg[3]);
53 54
      switch ($vocabulary->hierarchy) {
        case 0:
55
          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>';
56
        case 1:
57
          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>';
58
        case 2:
59
          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>';
60 61 62 63
      }
  }
}

Dries's avatar
Dries committed
64
/**
65
 * Implements hook_permission().
Dries's avatar
Dries committed
66
 */
67
function taxonomy_permission() {
68
  $permissions = array(
69
    'administer taxonomy' => array(
70
      'title' => t('Administer vocabularies and terms'),
71
    ),
72
  );
73 74 75 76 77 78 79 80
  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(
81
         'title' => t('Delete terms from %vocabulary', array('%vocabulary' => $vocabulary->name)),
82 83 84 85
      ),
    );
  }
  return $permissions;
Kjartan's avatar
Kjartan committed
86
}
87

88
/**
89
 * Implements hook_entity_info().
90
 */
91
function taxonomy_entity_info() {
92 93
  $return = array(
    'taxonomy_term' => array(
94
      'label' => t('Taxonomy term'),
95 96
      'controller class' => 'TaxonomyTermController',
      'base table' => 'taxonomy_term_data',
97
      'uri callback' => 'taxonomy_term_uri',
98
      'fieldable' => TRUE,
99
      'entity keys' => array(
100 101
        'id' => 'tid',
        'bundle' => 'vocabulary_machine_name',
102
        'label' => 'name',
103 104 105 106 107
      ),
      'bundle keys' => array(
        'bundle' => 'machine_name',
      ),
      'bundles' => array(),
108 109 110 111
      'view modes' => array(
        // @todo View mode for display as a field (when attached to nodes etc).
        'full' => array(
          'label' => t('Taxonomy term page'),
112
          'custom settings' => FALSE,
113 114
        ),
      ),
115 116
    ),
  );
117 118
  foreach (taxonomy_vocabulary_get_names() as $machine_name => $vocabulary) {
    $return['taxonomy_term']['bundles'][$machine_name] = array(
119 120
      'label' => $vocabulary->name,
      'admin' => array(
121 122
        'path' => 'admin/structure/taxonomy/%taxonomy_vocabulary_machine_name',
        'real path' => 'admin/structure/taxonomy/' . $machine_name,
123 124 125 126 127
        'bundle argument' => 3,
        'access arguments' => array('administer taxonomy'),
      ),
    );
  }
128 129 130 131
  $return['taxonomy_vocabulary'] = array(
    'label' => t('Taxonomy vocabulary'),
    'controller class' => 'TaxonomyVocabularyController',
    'base table' => 'taxonomy_vocabulary',
132
    'entity keys' => array(
133
      'id' => 'vid',
134
      'label' => 'name',
135 136 137 138
    ),
    'fieldable' => FALSE,
  );

139 140 141
  return $return;
}

142
/**
143
 * Entity uri callback.
144
 */
145 146 147 148
function taxonomy_term_uri($term) {
  return array(
    'path' => 'taxonomy/term/' . $term->tid,
  );
149 150
}

151 152 153 154 155
/**
 * Implements hook_field_extra_fields().
 */
function taxonomy_field_extra_fields() {
  $return = array();
156 157 158
  $info = entity_get_info('taxonomy_term');
  foreach (array_keys($info['bundles']) as $bundle) {
    $return['taxonomy_term'][$bundle] = array(
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
      '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,
        ),
177 178 179 180 181 182 183
      ),
    );
  }

  return $return;
}

184 185 186 187 188 189 190
/**
 * 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.
 *
191 192
 * @param $tid
 *   The term ID.
193 194
 * @param $pager
 *   Boolean to indicate whether a pager should be used.
195 196 197
 * @param $limit
 *   Integer. The maximum number of nodes to find.
 *   Set to FALSE for no limit.
198 199 200 201 202 203
 * @order
 *   An array of fields and directions.
 *
 * @return
 *   An array of nids matching the query.
 */
204
function taxonomy_select_nodes($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC')) {
205 206 207 208 209
  if (!variable_get('taxonomy_maintain_index_table', TRUE)) {
    return array();
  }
  $query = db_select('taxonomy_index', 't');
  $query->addTag('node_access');
210
  $query->condition('tid', $tid);
211 212 213 214
  if ($pager) {
    $count_query = clone $query;
    $count_query->addExpression('COUNT(t.nid)');

215 216 217 218
    $query = $query->extend('PagerDefault');
    if ($limit !== FALSE) {
      $query = $query->limit($limit);
    }
219 220 221
    $query->setCountQuery($count_query);
  }
  else {
222 223 224
    if ($limit !== FALSE) {
      $query->range(0, $limit);
    }
225 226 227 228 229 230 231 232 233 234 235 236 237
  }
  $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();
}

238
/**
239
 * Implements hook_theme().
240 241 242
 */
function taxonomy_theme() {
  return array(
243
    'taxonomy_overview_vocabularies' => array(
244
      'render element' => 'form',
245 246
    ),
    'taxonomy_overview_terms' => array(
247
      'render element' => 'form',
248
    ),
249 250 251 252
    'taxonomy_term' => array(
      'render element' => 'elements',
      'template' => 'taxonomy-term',
    ),
253 254 255
  );
}

Dries's avatar
Dries committed
256
/**
257
 * Implements hook_menu().
Dries's avatar
Dries committed
258
 */
259
function taxonomy_menu() {
260
  $items['admin/structure/taxonomy'] = array(
261 262
    'title' => 'Taxonomy',
    'description' => 'Manage tagging, categorization, and classification of your content.',
263 264
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_overview_vocabularies'),
265
    'access arguments' => array('administer taxonomy'),
266
    'file' => 'taxonomy.admin.inc',
267
  );
268
  $items['admin/structure/taxonomy/list'] = array(
269
    'title' => 'List',
270 271 272
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
273
  $items['admin/structure/taxonomy/add'] = array(
274
    'title' => 'Add vocabulary',
275 276
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_form_vocabulary'),
277
    'access arguments' => array('administer taxonomy'),
278
    'type' => MENU_LOCAL_ACTION,
279
    'file' => 'taxonomy.admin.inc',
280 281
  );

282
  $items['taxonomy/term/%taxonomy_term'] = array(
283
    'title' => 'Taxonomy term',
284 285
    'title callback' => 'taxonomy_term_title',
    'title arguments' => array(2),
286 287 288
    'page callback' => 'taxonomy_term_page',
    'page arguments' => array(2),
    'access arguments' => array('access content'),
289
    'file' => 'taxonomy.pages.inc',
290
  );
291
  $items['taxonomy/term/%taxonomy_term/view'] = array(
292 293
    'title' => 'View',
    'type' => MENU_DEFAULT_LOCAL_TASK,
294
  );
295
  $items['taxonomy/term/%taxonomy_term/edit'] = array(
296
    'title' => 'Edit',
297 298
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_form_term', 2),
299 300
    'access callback' => 'taxonomy_term_edit_access',
    'access arguments' => array(2),
301 302
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
303
    'file' => 'taxonomy.admin.inc',
304
  );
305 306 307 308 309 310 311 312
  $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,
313
    'file' => 'taxonomy.pages.inc',
314
  );
315
  $items['taxonomy/autocomplete'] = array(
316
    'title' => 'Autocomplete taxonomy',
317 318 319
    'page callback' => 'taxonomy_autocomplete',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
320
    'file' => 'taxonomy.pages.inc',
321
  );
322

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

346
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/add'] = array(
347
    'title' => 'Add term',
348
    'page callback' => 'drupal_get_form',
349
    'page arguments' => array('taxonomy_form_term', array(), 3),
350
    'access arguments' => array('administer taxonomy'),
351
    'type' => MENU_LOCAL_ACTION,
352
    'file' => 'taxonomy.admin.inc',
353
  );
354

Dries's avatar
Dries committed
355 356
  return $items;
}
357

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

368 369 370 371 372 373 374
/**
 * 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');
}

375 376 377 378 379 380 381 382
/**
 * Return the vocabulary name given the vocabulary object.
 */
function taxonomy_admin_vocabulary_title_callback($vocabulary) {
  return check_plain($vocabulary->name);
}

/**
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
 * Saves a vocabulary.
 *
 * @param $vocabulary
 *   A vocabulary object with the following properties:
 *   - vid: The ID of the 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).
403
 */
404
function taxonomy_vocabulary_save($vocabulary) {
405
  // Prevent leading and trailing spaces in vocabulary names.
406 407 408
  if (!empty($vocabulary->name)) {
    $vocabulary->name = trim($vocabulary->name);
  }
409 410 411 412 413 414 415 416 417
  // 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;
418
  }
419

420
  module_invoke_all('taxonomy_vocabulary_presave', $vocabulary);
421
  module_invoke_all('entity_presave', $vocabulary, 'taxonomy_vocabulary');
422

423
  if (!empty($vocabulary->vid) && !empty($vocabulary->name)) {
424
    $status = drupal_write_record('taxonomy_vocabulary', $vocabulary, 'vid');
425 426 427
    if ($vocabulary->old_machine_name != $vocabulary->machine_name) {
      field_attach_rename_bundle('taxonomy_term', $vocabulary->old_machine_name, $vocabulary->machine_name);
    }
428
    module_invoke_all('taxonomy_vocabulary_update', $vocabulary);
429
    module_invoke_all('entity_update', $vocabulary, 'taxonomy_vocabulary');
Kjartan's avatar
Kjartan committed
430
  }
431
  elseif (empty($vocabulary->vid)) {
432
    $status = drupal_write_record('taxonomy_vocabulary', $vocabulary);
433
    field_attach_create_bundle('taxonomy_term', $vocabulary->machine_name);
434
    module_invoke_all('taxonomy_vocabulary_insert', $vocabulary);
435
    module_invoke_all('entity_insert', $vocabulary, 'taxonomy_vocabulary');
Kjartan's avatar
Kjartan committed
436
  }
Dries's avatar
Dries committed
437

438
  unset($vocabulary->original);
Dries's avatar
Dries committed
439
  cache_clear_all();
440
  taxonomy_vocabulary_static_reset(array($vocabulary->vid));
Dries's avatar
Dries committed
441

442
  return $status;
Kjartan's avatar
Kjartan committed
443
}
444

445 446 447 448 449 450 451 452
/**
 * Delete a vocabulary.
 *
 * @param $vid
 *   A vocabulary ID.
 * @return
 *   Constant indicating items were deleted.
 */
453
function taxonomy_vocabulary_delete($vid) {
454
  $vocabulary = taxonomy_vocabulary_load($vid);
455

456 457 458 459 460 461 462 463 464 465
  $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();
466

467 468 469
    field_attach_delete_bundle('taxonomy_term', $vocabulary->machine_name);
    module_invoke_all('taxonomy_vocabulary_delete', $vocabulary);
    module_invoke_all('entity_delete', $vocabulary, 'taxonomy_vocabulary');
470

471
    cache_clear_all();
472
    taxonomy_vocabulary_static_reset();
473

474 475 476 477 478 479
    return SAVED_DELETED;
  }
  catch (Exception $e) {
    $transaction->rollback();
    watchdog_exception('taxonomy', $e);
    throw $e;
480
  }
481 482
}

483
/**
484
 * Implements hook_taxonomy_vocabulary_update().
485
 */
486 487 488 489
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) {
490 491 492 493 494
    $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) {
495 496
          if ($value['vocabulary'] == $vocabulary->old_machine_name) {
            $value['vocabulary'] = $vocabulary->machine_name;
497 498 499 500 501 502 503 504 505 506 507
            $update = TRUE;
          }
        }
        if ($update) {
          field_update_field($field);
        }
      }
    }
  }
}

508
/**
509
 * Checks and updates the hierarchy flag of a vocabulary.
510
 *
511
 * Checks the current parents of all terms in a vocabulary and updates the
512 513 514 515 516
 * 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.
517
 *
518
 * @param $vocabulary
519
 *   A vocabulary object.
520 521
 * @param $changed_term
 *   An array of the term structure that was updated.
522 523 524
 *
 * @return
 *   An integer that represents the level of the vocabulary's hierarchy.
525 526
 */
function taxonomy_check_vocabulary_hierarchy($vocabulary, $changed_term) {
527
  $tree = taxonomy_get_tree($vocabulary->vid);
528 529
  $hierarchy = 0;
  foreach ($tree as $term) {
530
    // Update the changed term with the new parent value before comparison.
531
    if ($term->tid == $changed_term['tid']) {
532
      $term = (object) $changed_term;
533 534 535 536 537 538 539 540 541 542 543
      $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;
    }
  }
544 545 546
  if ($hierarchy != $vocabulary->hierarchy) {
    $vocabulary->hierarchy = $hierarchy;
    taxonomy_vocabulary_save($vocabulary);
547 548 549 550 551
  }

  return $hierarchy;
}

552
/**
553
 * Saves a term object to the database.
554
 *
555
 * @param $term
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
 *   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.
 *
578
 * @return
579 580 581
 *   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.
582
 */
583
function taxonomy_term_save($term) {
584 585
  // Prevent leading and trailing spaces in term names.
  $term->name = trim($term->name);
586 587 588 589 590
  if (!isset($term->vocabulary_machine_name)) {
    $vocabulary = taxonomy_vocabulary_load($term->vid);
    $term->vocabulary_machine_name = $vocabulary->machine_name;
  }

591 592 593 594 595
  // Load the stored entity, if any.
  if (!empty($term->tid) && !isset($term->original)) {
    $term->original = entity_load_unchanged('taxonomy_term', $term->tid);
  }

596
  field_attach_presave('taxonomy_term', $term);
597
  module_invoke_all('taxonomy_term_presave', $term);
598
  module_invoke_all('entity_presave', $term, 'taxonomy_term');
599

600
  if (empty($term->tid)) {
601
    $op = 'insert';
602
    $status = drupal_write_record('taxonomy_term_data', $term);
603
    field_attach_insert('taxonomy_term', $term);
604 605 606
    if (!isset($term->parent)) {
      $term->parent = array(0);
    }
Kjartan's avatar
Kjartan committed
607
  }
608
  else {
609
    $op = 'update';
610 611 612 613 614 615 616
    $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();
    }
617
  }
618

619 620 621 622 623 624
  if (isset($term->parent)) {
    if (!is_array($term->parent)) {
      $term->parent = array($term->parent);
    }
    $query = db_insert('taxonomy_term_hierarchy')
      ->fields(array('tid', 'parent'));
625 626 627
    foreach ($term->parent as $parent) {
      if (is_array($parent)) {
        foreach ($parent as $tid) {
628 629
          $query->values(array(
            'tid' => $term->tid,
630
            'parent' => $tid
631
          ));
632 633
        }
      }
634 635 636 637 638 639
      else {
        $query->values(array(
          'tid' => $term->tid,
          'parent' => $parent
        ));
      }
640
    }
641
    $query->execute();
Kjartan's avatar
Kjartan committed
642
  }
643 644

  // Reset the taxonomy term static variables.
645
  taxonomy_terms_static_reset();
Dries's avatar
Dries committed
646

647 648 649
  // Invoke the taxonomy hooks.
  module_invoke_all("taxonomy_term_$op", $term);
  module_invoke_all("entity_$op", $term, 'taxonomy_term');
650
  unset($term->original);
651

652
  return $status;
Kjartan's avatar
Kjartan committed
653
}
654

655 656 657 658 659 660 661 662
/**
 * Delete a term.
 *
 * @param $tid
 *   The term ID.
 * @return
 *   Status constant indicating deletion.
 */
663
function taxonomy_term_delete($tid) {
664 665 666 667 668 669 670 671 672 673 674 675 676 677
  $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;
            }
678 679
          }
        }
680

681 682 683 684 685 686 687 688 689 690 691 692 693
        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();
        }
694
      }
695

696 697 698 699 700 701 702 703
      $tids = $orphans;
    }
    return SAVED_DELETED;
  }
  catch (Exception $e) {
    $transaction->rollback();
    watchdog_exception('taxonomy', $e);
    throw $e;
704
  }
705 706
}

707 708 709 710 711 712 713
/**
 * Generate an array for rendering the given term.
 *
 * @param $term
 *   A term object.
 * @param $view_mode
 *   View mode, e.g. 'full', 'teaser'...
714 715 716
 * @param $langcode
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
717 718 719 720
 *
 * @return
 *   An array as expected by drupal_render().
 */
721 722 723 724 725
function taxonomy_term_view($term, $view_mode = 'full', $langcode = NULL) {
  if (!isset($langcode)) {
    $langcode = $GLOBALS['language_content']->language;
  }

726 727
  field_attach_prepare_view('taxonomy_term', array($term->tid => $term), $view_mode, $langcode);
  entity_prepare_view('taxonomy_term', array($term->tid => $term), $langcode);
728 729 730 731 732

  $build = array(
    '#theme' => 'taxonomy_term',
    '#term' => $term,
    '#view_mode' => $view_mode,
733
    '#language' => $langcode,
734 735
  );

736
  $build += field_attach_view('taxonomy_term', $term, $view_mode, $langcode);
737

738 739 740 741 742 743 744 745 746
  // Add term description if the term has one.
  if (!empty($term->description)) {
    $build['description'] = array(
      '#markup' => check_markup($term->description, $term->format, '', TRUE),
      '#weight' => 0,
      '#prefix' => '<div class="taxonomy-term-description">',
      '#suffix' => '</div>',
    );
  }
747 748 749

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

750 751 752 753
  // Allow modules to modify the structured term.
  $type = 'taxonomy_term';
  drupal_alter(array('taxonomy_term_view', 'entity_view'), $build, $type);

754 755 756 757 758 759 760 761 762 763 764
  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'];

765 766
  $uri = entity_uri('taxonomy_term', $term);
  $variables['term_url']  = url($uri['path'], $uri['options']);
767
  $variables['term_name'] = check_plain($term->name);
768
  $variables['page']      = $variables['view_mode'] == 'full' && taxonomy_term_is_page($term);
769 770

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

  // Helpful $content variable for templates.
774
  $variables['content'] = array();
775 776 777 778 779 780 781 782 783 784
  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);

785
  // Gather classes, and clean up name so there are no underscores.
786 787 788
  $vocabulary_name_css = str_replace('_', '-', $term->vocabulary_machine_name);
  $variables['classes_array'][] = 'vocabulary-' . $vocabulary_name_css;

789 790
  $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->vocabulary_machine_name;
  $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->tid;
791 792 793
}

/**
794
 * Returns whether the current page is the page of the passed-in term.
795 796 797 798 799 800 801 802 803
 *
 * @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);
}

804 805 806 807 808 809
/**
 * 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');
810 811
  drupal_static_reset('taxonomy_get_tree:parents');
  drupal_static_reset('taxonomy_get_tree:terms');
812
  drupal_static_reset('taxonomy_get_parents');
813
  drupal_static_reset('taxonomy_get_parents_all');
814
  drupal_static_reset('taxonomy_get_children');
815
  entity_get_controller('taxonomy_term')->resetCache();
816 817
}

818 819
/**
 * Clear all static cache variables for vocabularies.
820
 *
821 822 823 824 825 826 827 828
 * @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);
}

Dries's avatar
Dries committed
829 830 831
/**
 * Return an array of all vocabulary objects.
 *
832 833
 * @return
 *   An array of all vocabulary objects, indexed by vid.
Dries's avatar
Dries committed
834
 */
835 836
function taxonomy_get_vocabularies() {
  return taxonomy_vocabulary_load_multiple(FALSE, array());
Kjartan's avatar
Kjartan committed
837
}
838

839 840 841 842
/**
 * Get names for all taxonomy vocabularies.
 *
 * @return
843
 *   An array of vocabulary ids, names, machine names, keyed by machine name.
844 845
 */
function taxonomy_vocabulary_get_names() {
846 847 848 849 850
  $names = &drupal_static(__FUNCTION__);

  if (!isset($names)) {
    $names = db_query('SELECT name, machine_name, vid FROM {taxonomy_vocabulary}')->fetchAllAssoc('machine_name');
  }
851

852 853 854
  return $names;
}

Dries's avatar
Dries committed
855
/**
856 857 858 859 860 861 862
 * 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.
Dries's avatar
Dries committed
863
 */
864 865 866 867 868 869 870 871 872 873 874 875 876
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);
Kjartan's avatar
Kjartan committed
877
  }
878 879

  return isset($parents[$tid]) ? $parents[$tid] : array();
Kjartan's avatar
Kjartan committed
880
}
881

Dries's avatar
Dries committed
882 883 884 885
/**
 * Find all ancestors of a given term ID.
 */
function taxonomy_get_parents_all($tid) {
886 887 888 889 890 891
  $cache = &drupal_static(__FUNCTION__, array());

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

892
  $parents = array();
893 894
  if ($term = taxonomy_term_load($tid)) {
    $parents[] = $term;
895 896 897 898 899 900
    $n = 0;
    while ($parent = taxonomy_get_parents($parents[$n]->tid)) {
      $parents = array_merge($parents, $parent);
      $n++;
    }
  }
901 902 903

  $cache[$tid] = $parents;

904 905 906
  return $parents;
}

Dries's avatar
Dries committed
907
/**
908 909 910 911 912 913 914 915
 * 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
916 917
 *   An array of term objects that are the children of the term $tid, or an
 *   empty array when no children exist.
Dries's avatar
Dries committed
918
 */
919 920 921 922
function taxonomy_get_children($tid, $vid = 0) {
  $children = &drupal_static(__FUNCTION__, array());

  if ($tid && !isset($children[$tid])) {
923 924
    $query = db_select('taxonomy_term_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
925 926
    $query->addField('t', 'tid');
    $query->condition('h.parent', $tid);
927 928 929
    if ($vid) {
      $query->condition('t.vid', $vid);
    }
930 931 932 933 934
    $query->addTag('term_access');
    $query->orderBy('t.weight');
    $query->orderBy('t.name');
    $tids = $query->execute()->fetchCol();
    $children[$tid] = taxonomy_term_load_multiple($tids);
Kjartan's avatar
Kjartan committed
935
  }
936 937

  return isset($children[$tid]) ? $children[$tid] : array();
Kjartan's avatar
Kjartan committed
938
}
939

Dries's avatar
Dries committed
940 941 942 943 944 945 946 947
/**
 * 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.
948 949
 * @param $max_depth
 *   The number of levels of the tree to return. Leave NULL to return all levels.
950 951 952 953 954
 * @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.
955
 *
Dries's avatar
Dries committed
956 957 958
 * @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.
959 960
 *   Results are statically cached. Term objects will be partial or complete
 *   depending on the $load_entities parameter.
Dries's avatar
Dries committed
961
 */
962
function taxonomy_get_tree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE) {
963
  $children = &drupal_static(__FUNCTION__, array());
964 965
  $parents = &drupal_static(__FUNCTION__ . ':parents', array());
  $terms = &drupal_static(__FUNCTION__ . ':terms', array());
966

Dries's avatar
Dries committed
967 968 969 970
  // 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();
971 972
    $parents[$vid] = array();
    $terms[$vid] = array();
Dries's avatar
Dries committed
973

974 975
    $query = db_select('taxonomy_term_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
976 977 978 979 980 981 982 983 984 985 986 987 988 989
    $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;
990 991
    }
  }
992

993 994 995 996 997 998
  // 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]));
  }

999
  $max_depth = (!isset($max_depth)) ? count($children[$vid]) : $max_depth;
1000
  $tree = array();
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050

  // 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]);
1051
      }
1052
    }
Kjartan's avatar
Kjartan committed
1053
  }
1054

1055
  return $tree;
Kjartan's avatar
Kjartan committed
1056
}
1057

Dries's avatar
Dries committed
1058
/**
Dries's avatar
Dries committed
1059
 * Try to map a string to an existing term, as for glossary use.
Dries's avatar
Dries committed
1060
 *
Dries's avatar
Dries committed
1061 1062 1063
 * Provides a case-insensitive and trimmed mapping, to maximize the
 * likelihood of a successful match.
 *
1064
 * @param $name
Dries's avatar
Dries committed
1065 1066 1067 1068
 *   Name of the term to search for.
 *
 * @return
 *   An array of matching term objects.
Dries's avatar
Dries committed
1069 1070
 */
function taxonomy_get_term_by_name($name) {
1071
  return taxonomy_term_load_multiple(array(), array('name' => trim($name)));
Dries's avatar
Dries committed
1072 1073
}

1074 1075 1076 1077 1078 1079 1080
/**
 * 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 {
1081

1082 1083 1084 1085
  protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
    $query = parent::buildQuery($ids, $conditions, $revision_id);
    $query->addTag('translatable');
    $query->addTag('term_access');
1086
    // When name is passed as a condition use LIKE.
1087 1088 1089
    if (isset($conditions['name'])) {
      $query_conditions = &$query->conditions();
      foreach ($query_conditions as $key => $condition) {
1090
        if ($condition['field'] == 'base.name') {
1091 1092
          $query_conditions[$key]['operator'] = 'LIKE';
          $query_conditions[$key]['value'] = db_like($query_conditions[$key]['value']);
1093
        }
1094 1095
      }
    }
1096
    // Add the machine name field from the {taxonomy_vocabulary} table.
1097 1098 1099
    $query->innerJoin('taxonomy_vocabulary', 'v', 'base.vid = v.vid');
    $query->addField('v', 'machine_name', 'vocabulary_machine_name');
    return $query;
1100 1101
  }

1102 1103
  protected function cacheGet($ids, $conditions = array()) {
    $terms = parent::cacheGet($ids, $conditions);
1104 1105 1106 1107
    // Name matching is case insensitive, note that with some collations
    // LOWER() and drupal_strtolower() may return different results.
    foreach ($terms as $term) {
      $term_values = (array) $term;
1108
      if (isset($conditions['name']) && drupal_strtolower($conditions['name'] != drupal_strtolower($term_values['name']))) {
1109 1110
        unset($terms[$term->tid]);
      }
1111
    }
1112 1113 1114
    return $terms;
  }
}
1115

1116 1117 1118 1119 1120 1121 1122
/**
 * Controller class for taxonomy vocabularies.
 *
 * This extends the DrupalDefaultEntityController class, adding required
 * special handling for taxonomy vocabulary objects.
 */
class TaxonomyVocabularyController extends DrupalDefaultEntityController {
1123 1124 1125 1126 1127 1128 1129

  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;
1130
  }
Kjartan's avatar
Kjartan committed
1131
}