taxonomy.module 37.5 KB
Newer Older
Dries's avatar
 
Dries committed
1
<?php
Kjartan's avatar
Kjartan committed
2
// $Id$
Dries's avatar
 
Dries committed
3

Dries's avatar
 
Dries committed
4 5 6 7 8
/**
 * @file
 * Enables the organization of content into categories.
 */

Dries's avatar
 
Dries committed
9 10 11
/**
 * Implementation of hook_perm().
 */
Kjartan's avatar
Kjartan committed
12
function taxonomy_perm() {
Dries's avatar
 
Dries committed
13
  return array('administer taxonomy');
Kjartan's avatar
Kjartan committed
14
}
Dries's avatar
 
Dries committed
15

16 17 18 19 20 21 22
/**
 * Implementation of hook_theme()
 */
function taxonomy_theme() {
  return array(
    'taxonomy_term_select' => array(
      'arguments' => array('element' => NULL),
23 24 25
    ),
    'taxonomy_term_page' => array(
      'arguments' => array('tids' => array(), 'result' => NULL),
26 27 28 29
    ),
  );
}

Dries's avatar
 
Dries committed
30 31 32 33 34 35 36
/**
 * Implementation of hook_link().
 *
 * This hook is extended with $type = 'taxonomy terms' to allow themes to
 * print lists of terms associated with a node. Themes can print taxonomy
 * links with:
 *
37
 * if (module_exists('taxonomy')) {
38 39
 *   $terms = taxonomy_link('taxonomy terms', $node);
 *   print theme('links', $terms);
Dries's avatar
 
Dries committed
40 41
 * }
 */
Dries's avatar
 
Dries committed
42
function taxonomy_link($type, $node = NULL) {
Dries's avatar
 
Dries committed
43
  if ($type == 'taxonomy terms' && $node != NULL) {
Kjartan's avatar
 
Kjartan committed
44
    $links = array();
45
    if (!empty($node->taxonomy)) {
46
      foreach ($node->taxonomy as $term) {
47 48 49 50
        // On preview, we get tids.
        if (is_numeric($term)) {
          $term = taxonomy_get_term($term);
        }
51
        $links['taxonomy_term_'. $term->tid] = array(
52 53 54
          'title' => $term->name,
          'href' => taxonomy_term_path($term),
          'attributes' => array('rel' => 'tag', 'title' => strip_tags($term->description))
55
        );
Dries's avatar
 
Dries committed
56
      }
Dries's avatar
 
Dries committed
57
    }
Kjartan's avatar
Kjartan committed
58

59
    // We call this hook again because some modules and themes call taxonomy_link('taxonomy terms') directly
60
    drupal_alter('link', $links, $node);
61 62

    return $links;
63 64 65
  }
}

66 67 68 69 70 71 72 73 74 75
/**
 * For vocabularies not maintained by taxonomy.module, give the maintaining
 * module a chance to provide a path for terms in that vocabulary.
 *
 * @param $term
 *   A term object.
 * @return
 *   An internal Drupal path.
 */

76
function taxonomy_term_path($term) {
77
  $vocabulary = taxonomy_vocabulary_load($term->vid);
78 79 80 81 82 83
  if ($vocabulary->module != 'taxonomy' && $path = module_invoke($vocabulary->module, 'term_path', $term)) {
    return $path;
  }
  return 'taxonomy/term/'. $term->tid;
}

Dries's avatar
 
Dries committed
84 85 86
/**
 * Implementation of hook_menu().
 */
87 88
function taxonomy_menu() {
  $items['admin/content/taxonomy'] = array(
89 90
    'title' => 'Categories',
    'description' => 'Create vocabularies and terms to categorize your content.',
91 92
    'page callback' => 'taxonomy_overview_vocabularies',
    'access arguments' => array('administer taxonomy'),
93
    'file' => 'taxonomy.admin.inc',
94 95 96
  );

  $items['admin/content/taxonomy/list'] = array(
97
    'title' => 'List',
98 99 100 101 102
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

  $items['admin/content/taxonomy/add/vocabulary'] = array(
103
    'title' => 'Add vocabulary',
104 105 106
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_form_vocabulary'),
    'type' => MENU_LOCAL_TASK,
107
    'parent' => 'admin/content/taxonomy',
108
    'file' => 'taxonomy.admin.inc',
109 110
  );

111
  $items['admin/content/taxonomy/edit/vocabulary/%taxonomy_vocabulary'] = array(
112
    'title' => 'Edit vocabulary',
113 114 115
    'page callback' => 'taxonomy_admin_vocabulary_edit',
    'page arguments' => array(5),
    'type' => MENU_CALLBACK,
116
    'file' => 'taxonomy.admin.inc',
117 118 119
  );

  $items['admin/content/taxonomy/edit/term'] = array(
120
    'title' => 'Edit term',
121 122
    'page callback' => 'taxonomy_admin_term_edit',
    'type' => MENU_CALLBACK,
123
    'file' => 'taxonomy.admin.inc',
124 125 126
  );

  $items['taxonomy/term'] = array(
127
    'title' => 'Taxonomy term',
128 129 130
    'page callback' => 'taxonomy_term_page',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
131
    'file' => 'taxonomy.pages.inc',
132 133 134
  );

  $items['taxonomy/autocomplete'] = array(
135
    'title' => 'Autocomplete taxonomy',
136 137 138
    'page callback' => 'taxonomy_autocomplete',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
139
    'file' => 'taxonomy.pages.inc',
140
  );
141
  $items['admin/content/taxonomy/%taxonomy_vocabulary'] = array(
142
    'title' => 'List terms',
143 144 145 146
    'page callback' => 'taxonomy_overview_terms',
    'page arguments' => array(3),
    'access arguments' => array('administer taxonomy'),
    'type' => MENU_CALLBACK,
147
    'file' => 'taxonomy.admin.inc',
148 149
  );

150
  $items['admin/content/taxonomy/%taxonomy_vocabulary/list'] = array(
151
    'title' => 'List',
152 153 154 155
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

156
  $items['admin/content/taxonomy/%taxonomy_vocabulary/add/term'] = array(
157
    'title' => 'Add term',
158 159
    'page callback' => 'taxonomy_add_term_page',
    'page arguments' => array(3),
160
    'type' => MENU_LOCAL_TASK,
161
    'parent' => 'admin/content/taxonomy/%taxonomy_vocabulary',
162
    'file' => 'taxonomy.admin.inc',
163
  );
Dries's avatar
 
Dries committed
164

Dries's avatar
 
Dries committed
165 166
  return $items;
}
Dries's avatar
 
Dries committed
167

168
function taxonomy_save_vocabulary(&$edit) {
169
  $edit['nodes'] = empty($edit['nodes']) ? array() : $edit['nodes'];
Dries's avatar
 
Dries committed
170

171 172 173 174
  if (!isset($edit['module'])) {
    $edit['module'] = 'taxonomy';
  }

175
  if (!empty($edit['vid']) && !empty($edit['name'])) {
176
    drupal_write_record('vocabulary', $edit, 'vid');
Dries's avatar
 
Dries committed
177
    db_query("DELETE FROM {vocabulary_node_types} WHERE vid = %d", $edit['vid']);
178
    foreach ($edit['nodes'] as $type => $selected) {
Dries's avatar
 
Dries committed
179 180
      db_query("INSERT INTO {vocabulary_node_types} (vid, type) VALUES (%d, '%s')", $edit['vid'], $type);
    }
Dries's avatar
 
Dries committed
181
    module_invoke_all('taxonomy', 'update', 'vocabulary', $edit);
182
    $status = SAVED_UPDATED;
Dries's avatar
 
Dries committed
183
  }
184
  else if (!empty($edit['vid'])) {
185
    $status = taxonomy_del_vocabulary($edit['vid']);
Kjartan's avatar
Kjartan committed
186 187
  }
  else {
188
    drupal_write_record('vocabulary', $edit);
189
    foreach ($edit['nodes'] as $type => $selected) {
Dries's avatar
 
Dries committed
190 191
      db_query("INSERT INTO {vocabulary_node_types} (vid, type) VALUES (%d, '%s')", $edit['vid'], $type);
    }
Dries's avatar
 
Dries committed
192
    module_invoke_all('taxonomy', 'insert', 'vocabulary', $edit);
193
    $status = SAVED_NEW;
Kjartan's avatar
Kjartan committed
194
  }
Dries's avatar
 
Dries committed
195 196

  cache_clear_all();
Dries's avatar
 
Dries committed
197

198
  return $status;
Kjartan's avatar
Kjartan committed
199
}
Dries's avatar
 
Dries committed
200

201 202 203 204 205 206 207 208
/**
 * Delete a vocabulary.
 *
 * @param $vid
 *   A vocabulary ID.
 * @return
 *   Constant indicating items were deleted.
 */
Kjartan's avatar
Kjartan committed
209
function taxonomy_del_vocabulary($vid) {
210
  $vocabulary = (array) taxonomy_vocabulary_load($vid);
Dries's avatar
 
Dries committed
211

Dries's avatar
 
Dries committed
212
  db_query('DELETE FROM {vocabulary} WHERE vid = %d', $vid);
Dries's avatar
 
Dries committed
213
  db_query('DELETE FROM {vocabulary_node_types} WHERE vid = %d', $vid);
Dries's avatar
 
Dries committed
214
  $result = db_query('SELECT tid FROM {term_data} WHERE vid = %d', $vid);
Kjartan's avatar
Kjartan committed
215 216
  while ($term = db_fetch_object($result)) {
    taxonomy_del_term($term->tid);
Dries's avatar
 
Dries committed
217
  }
Dries's avatar
 
Dries committed
218

Dries's avatar
 
Dries committed
219
  module_invoke_all('taxonomy', 'delete', 'vocabulary', $vocabulary);
Dries's avatar
 
Dries committed
220

Dries's avatar
 
Dries committed
221 222
  cache_clear_all();

223
  return SAVED_DELETED;
Dries's avatar
 
Dries committed
224 225
}

226 227 228
/**
 * Helper function for taxonomy_form_term_submit().
 *
229
 * @param $form_state['values']
230 231 232 233
 * @return
 *   Status constant indicating if term was inserted or updated.
 */
function taxonomy_save_term(&$form_values) {
234 235 236 237 238
  $form_values += array(
    'description' => '',
    'weight' => 0
  );

239
  if (!empty($form_values['tid']) && $form_values['name']) {
240
    drupal_write_record('term_data', $form_values, 'tid');
241
    $hook = 'update';
242
    $status = SAVED_UPDATED;
Kjartan's avatar
Kjartan committed
243
  }
244
  else if (!empty($form_values['tid'])) {
245
    return taxonomy_del_term($form_values['tid']);
Kjartan's avatar
Kjartan committed
246 247
  }
  else {
248
    drupal_write_record('term_data', $form_values);
249
    $hook = 'insert';
250
    $status = SAVED_NEW;
Kjartan's avatar
Kjartan committed
251
  }
Dries's avatar
 
Dries committed
252

253
  db_query('DELETE FROM {term_relation} WHERE tid1 = %d OR tid2 = %d', $form_values['tid'], $form_values['tid']);
254
  if (!empty($form_values['relations'])) {
255
    foreach ($form_values['relations'] as $related_id) {
Kjartan's avatar
Kjartan committed
256
      if ($related_id != 0) {
257
        db_query('INSERT INTO {term_relation} (tid1, tid2) VALUES (%d, %d)', $form_values['tid'], $related_id);
Dries's avatar
 
Dries committed
258
      }
Kjartan's avatar
Kjartan committed
259
    }
Kjartan's avatar
Kjartan committed
260
  }
Dries's avatar
 
Dries committed
261

262 263 264
  db_query('DELETE FROM {term_hierarchy} WHERE tid = %d', $form_values['tid']);
  if (!isset($form_values['parent']) || empty($form_values['parent'])) {
    $form_values['parent'] = array(0);
Kjartan's avatar
Kjartan committed
265
  }
266 267
  if (is_array($form_values['parent'])) {
    foreach ($form_values['parent'] as $parent) {
268 269
      if (is_array($parent)) {
        foreach ($parent as $tid) {
270
          db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $form_values['tid'], $tid);
271 272 273
        }
      }
      else {
274
        db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $form_values['tid'], $parent);
275
      }
Dries's avatar
 
Dries committed
276
    }
Kjartan's avatar
Kjartan committed
277
  }
278
  else {
279
    db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $form_values['tid'], $form_values['parent']);
280
  }
Dries's avatar
 
Dries committed
281

282
  db_query('DELETE FROM {term_synonym} WHERE tid = %d', $form_values['tid']);
283
  if (!empty($form_values['synonyms'])) {
284
    foreach (explode ("\n", str_replace("\r", '', $form_values['synonyms'])) as $synonym) {
Dries's avatar
 
Dries committed
285
      if ($synonym) {
286
        db_query("INSERT INTO {term_synonym} (tid, name) VALUES (%d, '%s')", $form_values['tid'], chop($synonym));
Dries's avatar
 
Dries committed
287
      }
Kjartan's avatar
Kjartan committed
288
    }
Dries's avatar
 
Dries committed
289
  }
Dries's avatar
 
Dries committed
290

291
  if (isset($hook)) {
292
    module_invoke_all('taxonomy', $hook, 'term', $form_values);
293 294
  }

Dries's avatar
 
Dries committed
295 296
  cache_clear_all();

297
  return $status;
Kjartan's avatar
Kjartan committed
298
}
Dries's avatar
 
Dries committed
299

300 301 302 303 304 305 306 307
/**
 * Delete a term.
 *
 * @param $tid
 *   The term ID.
 * @return
 *   Status constant indicating deletion.
 */
Kjartan's avatar
Kjartan committed
308
function taxonomy_del_term($tid) {
309 310 311 312 313 314 315 316 317 318 319 320 321 322
  $tids = array($tid);
  while ($tids) {
    $children_tids = $orphans = array();
    foreach ($tids as $tid) {
      // See if any of the term's children are about to be become orphans:
      if ($children = taxonomy_get_children($tid)) {
        foreach ($children as $child) {
          // If the term has multiple parents, we don't delete it.
          $parents = taxonomy_get_parents($child->tid);
          if (count($parents) == 1) {
            $orphans[] = $child->tid;
          }
        }
      }
Dries's avatar
 
Dries committed
323

324
      $term = (array) taxonomy_get_term($tid);
Dries's avatar
 
Dries committed
325

326 327 328 329 330
      db_query('DELETE FROM {term_data} WHERE tid = %d', $tid);
      db_query('DELETE FROM {term_hierarchy} WHERE tid = %d', $tid);
      db_query('DELETE FROM {term_relation} WHERE tid1 = %d OR tid2 = %d', $tid, $tid);
      db_query('DELETE FROM {term_synonym} WHERE tid = %d', $tid);
      db_query('DELETE FROM {term_node} WHERE tid = %d', $tid);
Dries's avatar
 
Dries committed
331

332 333
      module_invoke_all('taxonomy', 'delete', 'term', $term);
    }
Dries's avatar
 
Dries committed
334

335 336
    $tids = $orphans;
  }
Dries's avatar
 
Dries committed
337

Dries's avatar
 
Dries committed
338
  cache_clear_all();
339 340

  return SAVED_DELETED;
Dries's avatar
 
Dries committed
341 342
}

Dries's avatar
 
Dries committed
343 344 345
/**
 * Generate a form element for selecting terms from a vocabulary.
 */
346
function taxonomy_form($vid, $value = 0, $help = NULL, $name = 'taxonomy') {
347
  $vocabulary = taxonomy_vocabulary_load($vid);
348
  $help = ($help) ? $help : $vocabulary->help;
Kjartan's avatar
Kjartan committed
349 350 351 352
  if ($vocabulary->required) {
    $blank = 0;
  }
  else {
Dries's avatar
 
Dries committed
353
    $blank = '<'. t('none') .'>';
Kjartan's avatar
Kjartan committed
354
  }
Dries's avatar
 
Dries committed
355

356
  return _taxonomy_term_select(check_plain($vocabulary->name), $name, $value, $vid, $help, intval($vocabulary->multiple), $blank);
Kjartan's avatar
Kjartan committed
357
}
Dries's avatar
 
Dries committed
358

359
/**
360
 * Generate a set of options for selecting a term from all vocabularies.
361 362 363 364 365 366 367
 */
function taxonomy_form_all($free_tags = 0) {
  $vocabularies = taxonomy_get_vocabularies();
  $options = array();
  foreach ($vocabularies as $vid => $vocabulary) {
    if ($vocabulary->tags && !$free_tags) { continue; }
    $tree = taxonomy_get_tree($vid);
368
    if ($tree && (count($tree) > 0)) {
369
      $options[$vocabulary->name] = array();
370
      foreach ($tree as $term) {
371
        $options[$vocabulary->name][$term->tid] = str_repeat('-', $term->depth) . $term->name;
372 373 374 375 376 377
      }
    }
  }
  return $options;
}

Dries's avatar
 
Dries committed
378 379 380 381 382 383
/**
 * Return an array of all vocabulary objects.
 *
 * @param $type
 *   If set, return only those vocabularies associated with this node type.
 */
Dries's avatar
 
Dries committed
384
function taxonomy_get_vocabularies($type = NULL) {
Kjartan's avatar
Kjartan committed
385
  if ($type) {
386
    $result = db_query(db_rewrite_sql("SELECT v.vid, v.*, n.type FROM {vocabulary} v LEFT JOIN {vocabulary_node_types} n ON v.vid = n.vid WHERE n.type = '%s' ORDER BY v.weight, v.name", 'v', 'vid'), $type);
Kjartan's avatar
Kjartan committed
387 388
  }
  else {
389
    $result = db_query(db_rewrite_sql('SELECT v.*, n.type FROM {vocabulary} v LEFT JOIN {vocabulary_node_types} n ON v.vid = n.vid ORDER BY v.weight, v.name', 'v', 'vid'));
Kjartan's avatar
Kjartan committed
390
  }
Dries's avatar
 
Dries committed
391

Kjartan's avatar
Kjartan committed
392
  $vocabularies = array();
Dries's avatar
 
Dries committed
393
  $node_types = array();
Kjartan's avatar
Kjartan committed
394
  while ($voc = db_fetch_object($result)) {
395 396 397 398 399 400 401 402 403 404
    // If no node types are associated with a vocabulary, the LEFT JOIN will
    // return a NULL value for type.
    if (isset($voc->type)) {
      $node_types[$voc->vid][] = $voc->type;
      unset($voc->type);
      $voc->nodes = $node_types[$voc->vid];
    }
    elseif (!isset($voc->nodes)) {
      $voc->nodes = array();
    }
Dries's avatar
 
Dries committed
405
    $vocabularies[$voc->vid] = $voc;
Dries's avatar
 
Dries committed
406
  }
Dries's avatar
 
Dries committed
407

Kjartan's avatar
Kjartan committed
408 409
  return $vocabularies;
}
Dries's avatar
 
Dries committed
410

Dries's avatar
 
Dries committed
411
/**
412
 * Implementation of hook_form_alter().
Dries's avatar
 
Dries committed
413 414
 * Generate a form for selecting terms to associate with a node.
 */
415
function taxonomy_form_alter(&$form, $form_state, $form_id) {
416
  if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] .'_node_form' == $form_id) {
417 418
    $node = $form['#node'];

419
    if (!isset($node->taxonomy)) {
420
      $terms = empty($node->nid) ? array() : taxonomy_node_get_terms($node);
Kjartan's avatar
Kjartan committed
421 422
    }
    else {
423
      $terms = $node->taxonomy;
Dries's avatar
 
Dries committed
424 425
    }

426
    $c = db_query(db_rewrite_sql("SELECT v.* FROM {vocabulary} v INNER JOIN {vocabulary_node_types} n ON v.vid = n.vid WHERE n.type = '%s' ORDER BY v.weight, v.name", 'v', 'vid'), $node->type);
Dries's avatar
Dries committed
427

428 429
    while ($vocabulary = db_fetch_object($c)) {
      if ($vocabulary->tags) {
430
        $typed_string = taxonomy_implode_tags($terms, $vocabulary->vid) . (array_key_exists('tags', $terms) ? $terms['tags'][$vocabulary->vid] : NULL);
431

432 433 434 435
        if ($vocabulary->help) {
          $help = $vocabulary->help;
        }
        else {
436
          $help = t('A comma-separated list of terms describing this content. Example: funny, bungee jumping, "Company, Inc.".');
437
        }
438 439 440 441 442 443 444
        $form['taxonomy']['tags'][$vocabulary->vid] = array('#type' => 'textfield',
          '#title' => $vocabulary->name,
          '#description' => $help,
          '#required' => $vocabulary->required,
          '#default_value' => $typed_string,
          '#autocomplete_path' => 'taxonomy/autocomplete/'. $vocabulary->vid,
          '#weight' => $vocabulary->weight,
445
          '#maxlength' => 255,
446
        );
447 448
      }
      else {
449 450 451 452 453 454 455 456
        // Extract terms belonging to the vocabulary in question.
        $default_terms = array();
        foreach ($terms as $term) {
          if ($term->vid == $vocabulary->vid) {
            $default_terms[$term->tid] = $term;
          }
        }
        $form['taxonomy'][$vocabulary->vid] = taxonomy_form($vocabulary->vid, array_keys($default_terms), $vocabulary->help);
457
        $form['taxonomy'][$vocabulary->vid]['#weight'] = $vocabulary->weight;
458
        $form['taxonomy'][$vocabulary->vid]['#required'] = $vocabulary->required;
459
      }
Dries's avatar
Dries committed
460
    }
461
    if (!empty($form['taxonomy']) && is_array($form['taxonomy'])) {
462 463 464 465 466 467 468 469
      if (count($form['taxonomy']) > 1) { // Add fieldset only if form has more than 1 element.
        $form['taxonomy'] += array(
          '#type' => 'fieldset',
          '#title' => t('Categories'),
          '#collapsible' => TRUE,
          '#collapsed' => FALSE,
        );
      }
470 471
      $form['taxonomy']['#weight'] = -3;
      $form['taxonomy']['#tree'] = TRUE;
Dries's avatar
Dries committed
472
    }
Dries's avatar
 
Dries committed
473
  }
Kjartan's avatar
Kjartan committed
474
}
Dries's avatar
 
Dries committed
475

Dries's avatar
 
Dries committed
476
/**
477
 * Find all terms associated with the given node, within one vocabulary.
Dries's avatar
 
Dries committed
478
 */
479 480
function taxonomy_node_get_terms_by_vocabulary($node, $vid, $key = 'tid') {
  $result = db_query(db_rewrite_sql('SELECT t.tid, t.* FROM {term_data} t INNER JOIN {term_node} r ON r.tid = t.tid WHERE t.vid = %d AND r.vid = %d ORDER BY weight', 't', 'tid'), $vid, $node->vid);
Kjartan's avatar
Kjartan committed
481 482 483
  $terms = array();
  while ($term = db_fetch_object($result)) {
    $terms[$term->$key] = $term;
Dries's avatar
 
Dries committed
484
  }
Kjartan's avatar
Kjartan committed
485 486 487
  return $terms;
}

Dries's avatar
 
Dries committed
488
/**
489
 * Find all terms associated with the given node, ordered by vocabulary and term weight.
Dries's avatar
 
Dries committed
490
 */
491
function taxonomy_node_get_terms($node, $key = 'tid') {
Kjartan's avatar
Kjartan committed
492
  static $terms;
Dries's avatar
 
Dries committed
493

494
  if (!isset($terms[$node->vid][$key])) {
495
    $result = db_query(db_rewrite_sql('SELECT t.* FROM {term_node} r INNER JOIN {term_data} t ON r.tid = t.tid INNER JOIN {vocabulary} v ON t.vid = v.vid WHERE r.vid = %d ORDER BY v.weight, t.weight, t.name', 't', 'tid'), $node->vid);
496
    $terms[$node->vid][$key] = array();
Dries's avatar
 
Dries committed
497
    while ($term = db_fetch_object($result)) {
498
      $terms[$node->vid][$key][$term->$key] = $term;
Dries's avatar
 
Dries committed
499 500
    }
  }
501
  return $terms[$node->vid][$key];
Kjartan's avatar
Kjartan committed
502
}
Dries's avatar
 
Dries committed
503

Dries's avatar
Dries committed
504 505 506
/**
 * Make sure incoming vids are free tagging enabled.
 */
507
function taxonomy_node_validate(&$node) {
508
  if (!empty($node->taxonomy)) {
509
    $terms = $node->taxonomy;
510
    if (!empty($terms['tags'])) {
Dries's avatar
Dries committed
511
      foreach ($terms['tags'] as $vid => $vid_value) {
512
        $vocabulary = taxonomy_vocabulary_load($vid);
513
        if (empty($vocabulary->tags)) {
514 515
          // see form_get_error $key = implode('][', $element['#parents']);
          // on why this is the key
516
          form_set_error("taxonomy][tags][$vid", t('The %name vocabulary can not be modified in this way.', array('%name' => $vocabulary->name)));
Dries's avatar
Dries committed
517 518 519 520 521 522
        }
      }
    }
  }
}

Dries's avatar
 
Dries committed
523 524 525
/**
 * Save term associations for a given node.
 */
526 527 528
function taxonomy_node_save($node, $terms) {

  taxonomy_node_delete_revision($node);
Dries's avatar
Dries committed
529 530 531

  // Free tagging vocabularies do not send their tids in the form,
  // so we'll detect them here and process them independently.
532 533 534
  if (isset($terms['tags'])) {
    $typed_input = $terms['tags'];
    unset($terms['tags']);
Dries's avatar
Dries committed
535 536

    foreach ($typed_input as $vid => $vid_value) {
537
      $typed_terms = drupal_explode_tags($vid_value);
Dries's avatar
Dries committed
538

539
      $inserted = array();
Dries's avatar
Dries committed
540 541
      foreach ($typed_terms as $typed_term) {
        // See if the term exists in the chosen vocabulary
542
        // and return the tid; otherwise, add a new record.
Dries's avatar
Dries committed
543
        $possibilities = taxonomy_get_term_by_name($typed_term);
544
        $typed_term_tid = NULL; // tid match, if any.
Dries's avatar
Dries committed
545 546 547 548 549 550 551
        foreach ($possibilities as $possibility) {
          if ($possibility->vid == $vid) {
            $typed_term_tid = $possibility->tid;
          }
        }

        if (!$typed_term_tid) {
552 553 554
          $edit = array('vid' => $vid, 'name' => $typed_term);
          $status = taxonomy_save_term($edit);
          $typed_term_tid = $edit['tid'];
Dries's avatar
Dries committed
555 556
        }

557
        // Defend against duplicate, differently cased tags
558
        if (!isset($inserted[$typed_term_tid])) {
559
          db_query('INSERT INTO {term_node} (nid, vid, tid) VALUES (%d, %d, %d)', $node->nid, $node->vid, $typed_term_tid);
560 561
          $inserted[$typed_term_tid] = TRUE;
        }
Dries's avatar
Dries committed
562 563 564
      }
    }
  }
Dries's avatar
 
Dries committed
565

566 567
  if (is_array($terms)) {
    foreach ($terms as $term) {
568 569 570
      if (is_array($term)) {
        foreach ($term as $tid) {
          if ($tid) {
571
            db_query('INSERT INTO {term_node} (nid, vid, tid) VALUES (%d, %d, %d)', $node->nid, $node->vid, $tid);
572 573 574
          }
        }
      }
575
      else if (is_object($term)) {
576
        db_query('INSERT INTO {term_node} (nid, vid, tid) VALUES (%d, %d, %d)', $node->nid, $node->vid, $term->tid);
577
      }
578
      else if ($term) {
579
        db_query('INSERT INTO {term_node} (nid, vid, tid) VALUES (%d, %d, %d)', $node->nid, $node->vid, $term);
580
      }
Dries's avatar
 
Dries committed
581 582
    }
  }
Kjartan's avatar
Kjartan committed
583
}
Dries's avatar
 
Dries committed
584

Dries's avatar
 
Dries committed
585 586 587
/**
 * Remove associations of a node to its terms.
 */
588
function taxonomy_node_delete($node) {
589
  db_query('DELETE FROM {term_node} WHERE nid = %d', $node->nid);
590 591 592 593 594 595
}

/**
 * Remove associations of a node to its terms.
 */
function taxonomy_node_delete_revision($node) {
596
  db_query('DELETE FROM {term_node} WHERE vid = %d', $node->vid);
Kjartan's avatar
Kjartan committed
597
}
Dries's avatar
 
Dries committed
598

599 600 601 602 603
/**
 * Implementation of hook_node_type().
 */
function taxonomy_node_type($op, $info) {
  if ($op == 'update' && !empty($info->old_type) && $info->type != $info->old_type) {
604 605 606 607
    db_query("UPDATE {vocabulary_node_types} SET type = '%s' WHERE type = '%s'", $info->type, $info->old_type);
  }
  elseif ($op == 'delete') {
    db_query("DELETE FROM {vocabulary_node_types} WHERE type = '%s'", $info->type);
608 609 610
  }
}

Dries's avatar
 
Dries committed
611 612 613 614
/**
 * Find all term objects related to a given term ID.
 */
function taxonomy_get_related($tid, $key = 'tid') {
Kjartan's avatar
Kjartan committed
615
  if ($tid) {
Dries's avatar
 
Dries committed
616
    $result = db_query('SELECT t.*, tid1, tid2 FROM {term_relation}, {term_data} t WHERE (t.tid = tid1 OR t.tid = tid2) AND (tid1 = %d OR tid2 = %d) AND t.tid != %d ORDER BY weight, name', $tid, $tid, $tid);
Kjartan's avatar
Kjartan committed
617 618 619
    $related = array();
    while ($term = db_fetch_object($result)) {
      $related[$term->$key] = $term;
Dries's avatar
 
Dries committed
620
    }
Kjartan's avatar
Kjartan committed
621
    return $related;
Dries's avatar
 
Dries committed
622
  }
Kjartan's avatar
Kjartan committed
623 624
  else {
    return array();
Dries's avatar
 
Dries committed
625
  }
Kjartan's avatar
Kjartan committed
626
}
Dries's avatar
 
Dries committed
627

Dries's avatar
 
Dries committed
628 629 630 631
/**
 * Find all parents of a given term ID.
 */
function taxonomy_get_parents($tid, $key = 'tid') {
Kjartan's avatar
Kjartan committed
632
  if ($tid) {
633
    $result = db_query(db_rewrite_sql('SELECT t.tid, t.* FROM {term_data} t INNER JOIN {term_hierarchy} h ON h.parent = t.tid WHERE h.tid = %d ORDER BY weight, name', 't', 'tid'), $tid);
Kjartan's avatar
Kjartan committed
634 635 636
    $parents = array();
    while ($parent = db_fetch_object($result)) {
      $parents[$parent->$key] = $parent;
Dries's avatar
 
Dries committed
637
    }
Kjartan's avatar
Kjartan committed
638
    return $parents;
Dries's avatar
 
Dries committed
639
  }
Kjartan's avatar
Kjartan committed
640 641 642 643
  else {
    return array();
  }
}
Dries's avatar
 
Dries committed
644

Dries's avatar
 
Dries committed
645 646 647 648
/**
 * Find all ancestors of a given term ID.
 */
function taxonomy_get_parents_all($tid) {
Dries's avatar
 
Dries committed
649 650 651 652 653 654 655 656 657 658 659 660
  $parents = array();
  if ($tid) {
    $parents[] = taxonomy_get_term($tid);
    $n = 0;
    while ($parent = taxonomy_get_parents($parents[$n]->tid)) {
      $parents = array_merge($parents, $parent);
      $n++;
    }
  }
  return $parents;
}

Dries's avatar
 
Dries committed
661 662 663 664
/**
 * Find all children of a term ID.
 */
function taxonomy_get_children($tid, $vid = 0, $key = 'tid') {
Kjartan's avatar
Kjartan committed
665
  if ($vid) {
666
    $result = db_query(db_rewrite_sql('SELECT t.* FROM {term_data} t INNER JOIN {term_hierarchy} h ON h.tid = t.tid WHERE t.vid = %d AND h.parent = %d ORDER BY weight, name', 't', 'tid'), $vid, $tid);
Dries's avatar
 
Dries committed
667
  }
Kjartan's avatar
Kjartan committed
668
  else {
669
    $result = db_query(db_rewrite_sql('SELECT t.* FROM {term_data} t INNER JOIN {term_hierarchy} h ON h.tid = t.tid WHERE parent = %d ORDER BY weight, name', 't', 'tid'), $tid);
Kjartan's avatar
Kjartan committed
670 671 672 673 674 675 676
  }
  $children = array();
  while ($term = db_fetch_object($result)) {
    $children[$term->$key] = $term;
  }
  return $children;
}
Dries's avatar
 
Dries committed
677

Dries's avatar
 
Dries committed
678 679 680 681 682 683 684 685 686 687 688 689 690
/**
 * 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 $depth
 *   Internal use only.
 *
Dries's avatar
 
Dries committed
691 692 693
 * @param $max_depth
 *   The number of levels of the tree to return. Leave NULL to return all levels.
 *
Dries's avatar
 
Dries committed
694 695 696
 * @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.
697
 *   Results are statically cached.
Dries's avatar
 
Dries committed
698 699
 */
function taxonomy_get_tree($vid, $parent = 0, $depth = -1, $max_depth = NULL) {
Dries's avatar
 
Dries committed
700
  static $children, $parents, $terms;
Dries's avatar
 
Dries committed
701

Kjartan's avatar
Kjartan committed
702
  $depth++;
Dries's avatar
 
Dries committed
703

Dries's avatar
 
Dries committed
704 705 706 707
  // We cache trees, so it's not CPU-intensive to call get_tree() on a term
  // and its children, too.
  if (!isset($children[$vid])) {
    $children[$vid] = array();
Dries's avatar
 
Dries committed
708

709
    $result = db_query(db_rewrite_sql('SELECT t.tid, t.*, parent FROM {term_data} t INNER JOIN  {term_hierarchy} h ON t.tid = h.tid WHERE t.vid = %d ORDER BY weight, name', 't', 'tid'), $vid);
Dries's avatar
 
Dries committed
710
    while ($term = db_fetch_object($result)) {
Dries's avatar
 
Dries committed
711 712 713
      $children[$vid][$term->parent][] = $term->tid;
      $parents[$vid][$term->tid][] = $term->parent;
      $terms[$vid][$term->tid] = $term;
Dries's avatar
 
Dries committed
714 715
    }
  }
Dries's avatar
 
Dries committed
716

Dries's avatar
 
Dries committed
717
  $max_depth = (is_null($max_depth)) ? count($children[$vid]) : $max_depth;
718 719
  $tree = array();
  if (!empty($children[$vid][$parent])) {
Dries's avatar
Dries committed
720 721
    foreach ($children[$vid][$parent] as $child) {
      if ($max_depth > $depth) {
722 723
        $term = drupal_clone($terms[$vid][$child]);
        $term->depth = $depth;
Dries's avatar
Dries committed
724
        // The "parent" attribute is not useful, as it would show one parent only.
725 726 727
        unset($term->parent);
        $term->parents = $parents[$vid][$child];
        $tree[] = $term;
Dries's avatar
Dries committed
728

729
        if (!empty($children[$vid][$child])) {
Dries's avatar
Dries committed
730 731
          $tree = array_merge($tree, taxonomy_get_tree($vid, $child, $depth, $max_depth));
        }
Dries's avatar
 
Dries committed
732
      }
Dries's avatar
 
Dries committed
733
    }
Kjartan's avatar
Kjartan committed
734
  }
Dries's avatar
 
Dries committed
735

736
  return $tree;
Kjartan's avatar
Kjartan committed
737
}
Dries's avatar
 
Dries committed
738

Dries's avatar
 
Dries committed
739 740 741
/**
 * Return an array of synonyms of the given term ID.
 */
Kjartan's avatar
Kjartan committed
742 743
function taxonomy_get_synonyms($tid) {
  if ($tid) {
744
    $synonyms = array();
Dries's avatar
 
Dries committed
745
    $result = db_query('SELECT name FROM {term_synonym} WHERE tid = %d', $tid);
Kjartan's avatar
Kjartan committed
746
    while ($synonym = db_fetch_array($result)) {
Dries's avatar
 
Dries committed
747
      $synonyms[] = $synonym['name'];
Dries's avatar
 
Dries committed
748
    }
749
    return $synonyms;
Dries's avatar
 
Dries committed
750
  }
Kjartan's avatar
Kjartan committed
751 752
  else {
    return array();
Dries's avatar
 
Dries committed
753
  }
Kjartan's avatar
Kjartan committed
754
}
Dries's avatar
 
Dries committed
755

Dries's avatar
 
Dries committed
756 757 758 759 760
/**
 * Return the term object that has the given string as a synonym.
 */
function taxonomy_get_synonym_root($synonym) {
  return db_fetch_object(db_query("SELECT * FROM {term_synonym} s, {term_data} t WHERE t.tid = s.tid AND s.name = '%s'", $synonym));
Kjartan's avatar
Kjartan committed
761
}
Dries's avatar
 
Dries committed
762

Dries's avatar
 
Dries committed
763
/**
764 765 766 767 768 769 770 771 772 773 774 775
 * Count the number of published nodes classified by a term.
 *
 * @param $tid
 *   The term's ID
 *
 * @param $type
 *   The $node->type. If given, taxonomy_term_count_nodes only counts
 *   nodes of $type that are classified with the term $tid.
 *
 * @return int
 *   An integer representing a number of nodes.
 *   Results are statically cached.
Dries's avatar
 
Dries committed
776
 */
Dries's avatar
 
Dries committed
777
function taxonomy_term_count_nodes($tid, $type = 0) {