taxonomy.module 53 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

Dries's avatar
 
Dries committed
16 17 18 19 20 21 22
/**
 * 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:
 *
23
 * if (module_exists('taxonomy')) {
24 25
 *   $terms = taxonomy_link('taxonomy terms', $node);
 *   print theme('links', $terms);
Dries's avatar
 
Dries committed
26 27
 * }
 */
Dries's avatar
 
Dries committed
28
function taxonomy_link($type, $node = NULL) {
Dries's avatar
 
Dries committed
29
  if ($type == 'taxonomy terms' && $node != NULL) {
Kjartan's avatar
 
Kjartan committed
30
    $links = array();
31
    if (!empty($node->taxonomy)) {
32
      foreach ($node->taxonomy as $term) {
33 34 35 36
        // On preview, we get tids.
        if (is_numeric($term)) {
          $term = taxonomy_get_term($term);
        }
37
        $links['taxonomy_term_'. $term->tid] = array(
38 39 40
          'title' => $term->name,
          'href' => taxonomy_term_path($term),
          'attributes' => array('rel' => 'tag', 'title' => strip_tags($term->description))
41
        );
Dries's avatar
 
Dries committed
42
      }
Dries's avatar
 
Dries committed
43
    }
Kjartan's avatar
Kjartan committed
44

45
    // We call this hook again because some modules and themes call taxonomy_link('taxonomy terms') directly
46
    drupal_alter('link', $links, $node);
47 48

    return $links;
49 50 51
  }
}

52 53 54 55 56 57 58 59 60 61
/**
 * 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.
 */

62
function taxonomy_term_path($term) {
63
  $vocabulary = taxonomy_vocabulary_load($term->vid);
64 65 66 67 68 69
  if ($vocabulary->module != 'taxonomy' && $path = module_invoke($vocabulary->module, 'term_path', $term)) {
    return $path;
  }
  return 'taxonomy/term/'. $term->tid;
}

Dries's avatar
 
Dries committed
70 71 72
/**
 * Implementation of hook_menu().
 */
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
function taxonomy_menu() {
  $items['admin/content/taxonomy'] = array(
    'title' => t('Categories'),
    'description' => t('Create vocabularies and terms to categorize your content.'),
    'page callback' => 'taxonomy_overview_vocabularies',
    'access arguments' => array('administer taxonomy'),
  );

  $items['admin/content/taxonomy/list'] = array(
    'title' => t('List'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

  $items['admin/content/taxonomy/add/vocabulary'] = array(
    'title' => t('Add vocabulary'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_form_vocabulary'),
    'type' => MENU_LOCAL_TASK,
92
    'parent' => 'admin/content/taxonomy',
93 94
  );

95
  $items['admin/content/taxonomy/edit/vocabulary/%taxonomy_vocabulary'] = array(
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    'title' => t('Edit vocabulary'),
    'page callback' => 'taxonomy_admin_vocabulary_edit',
    'page arguments' => array(5),
    'type' => MENU_CALLBACK,
  );

  $items['admin/content/taxonomy/edit/term'] = array(
    'title' => t('Edit term'),
    'page callback' => 'taxonomy_admin_term_edit',
    'type' => MENU_CALLBACK,
  );

  $items['taxonomy/term'] = array(
    'title' => t('Taxonomy term'),
    'page callback' => 'taxonomy_term_page',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  $items['taxonomy/autocomplete'] = array(
    'title' => t('Autocomplete taxonomy'),
    'page callback' => 'taxonomy_autocomplete',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
121
  $items['admin/content/taxonomy/%taxonomy_vocabulary'] = array(
122 123 124 125 126 127 128
    'title' => t('List terms'),
    'page callback' => 'taxonomy_overview_terms',
    'page arguments' => array(3),
    'access arguments' => array('administer taxonomy'),
    'type' => MENU_CALLBACK,
  );

129
  $items['admin/content/taxonomy/%taxonomy_vocabulary/list'] = array(
130 131 132 133 134
    'title' => t('List'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

135
  $items['admin/content/taxonomy/%taxonomy_vocabulary/add/term'] = array(
136 137 138 139
    'title' => t('Add term'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_form_term', 3),
    'type' => MENU_LOCAL_TASK,
140
    'parent' => 'admin/content/taxonomy/%taxonomy_vocabulary',
141
  );
Dries's avatar
 
Dries committed
142

Dries's avatar
 
Dries committed
143 144
  return $items;
}
Dries's avatar
 
Dries committed
145

146 147 148 149
/**
 * List and manage vocabularies.
 */
function taxonomy_overview_vocabularies() {
150
  $vocabularies = taxonomy_get_vocabularies();
151
  $rows = array();
152 153 154
  foreach ($vocabularies as $vocabulary) {
    $types = array();
    foreach ($vocabulary->nodes as $type) {
155
      $node_type = node_get_types('name', $type);
156 157
      $types[] = $node_type ? $node_type : $type;
    }
158 159
    $rows[] = array('name' => check_plain($vocabulary->name),
      'type' => implode(', ', $types),
160 161 162
      'edit' => l(t('edit vocabulary'), "admin/content/taxonomy/edit/vocabulary/$vocabulary->vid"),
      'list' => l(t('list terms'), "admin/content/taxonomy/$vocabulary->vid"),
      'add' => l(t('add terms'), "admin/content/taxonomy/$vocabulary->vid/add/term")
163 164 165
    );
  }
  if (empty($rows)) {
Steven Wittens's avatar
Steven Wittens committed
166
    $rows[] = array(array('data' => t('No categories available.'), 'colspan' => '5'));
167
  }
drumm's avatar
drumm committed
168
  $header = array(t('Name'), t('Type'), array('data' => t('Operations'), 'colspan' => '3'));
169

170
  return theme('table', $header, $rows, array('id' => 'taxonomy'));
171 172 173 174 175 176
}

/**
 * Display a tree of all the terms in a vocabulary, with options to edit
 * each one.
 */
177
function taxonomy_overview_terms($vocabulary) {
178 179 180 181 182
  $destination = drupal_get_destination();

  $header = array(t('Name'), t('Operations'));

  drupal_set_title(check_plain($vocabulary->name));
183
  $start_from      = isset($_GET['page']) ? $_GET['page'] : 0;
184 185 186 187 188 189 190
  $total_entries   = 0;  // total count for pager
  $page_increment  = 25; // number of tids per page
  $displayed_count = 0;  // number of tids shown

  $tree = taxonomy_get_tree($vocabulary->vid);
  foreach ($tree as $term) {
    $total_entries++; // we're counting all-totals, not displayed
191 192 193
    if (($start_from && ($start_from * $page_increment) >= $total_entries) || ($displayed_count == $page_increment)) {
      continue;
    }
194
    $rows[] = array(str_repeat('--', $term->depth) . ' ' . l($term->name, "taxonomy/term/$term->tid"), l(t('edit'), "admin/content/taxonomy/edit/term/$term->tid", array('query' => $destination)));
195 196 197
    $displayed_count++; // we're counting tids displayed
  }

198
  if (empty($rows)) {
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
    $rows[] = array(array('data' => t('No terms available.'), 'colspan' => '2'));
  }

  $GLOBALS['pager_page_array'][] = $start_from;  // FIXME
  $GLOBALS['pager_total'][] = intval($total_entries / $page_increment) + 1; // FIXME

  if ($total_entries >= $page_increment) {
    $rows[] = array(array('data' => theme('pager', NULL, $page_increment), 'colspan' => '2'));
  }

  return theme('table', $header, $rows, array('id' => 'taxonomy'));
}

/**
 * Display form for adding and editing vocabularies.
 */
Kjartan's avatar
Kjartan committed
215
function taxonomy_form_vocabulary($edit = array()) {
216 217 218 219 220 221 222 223 224 225 226 227
  $edit += array(
    'name' => '',
    'description' => '',
    'help' => '',
    'nodes' => array(),
    'hierarchy' => 0,
    'relations' => 0,
    'tags' => 0,
    'multiple' => 0,
    'required' => 0,
    'weight' => 0,
  );
228 229 230
  $form['name'] = array('#type' => 'textfield',
    '#title' => t('Vocabulary name'),
    '#default_value' => $edit['name'],
231
    '#maxlength' => 255,
232
    '#description' => t('The name for this vocabulary. Example: "Topic".'),
233 234 235 236 237 238 239 240 241
    '#required' => TRUE,
  );
  $form['description'] = array('#type' => 'textarea',
    '#title' => t('Description'),
    '#default_value' => $edit['description'],
    '#description' => t('Description of the vocabulary; can be used by modules.'),
  );
  $form['help'] = array('#type' => 'textfield',
    '#title' => t('Help text'),
242
    '#maxlength' => 255,
243 244 245 246 247 248
    '#default_value' => $edit['help'],
    '#description' => t('Instructions to present to the user when choosing a term.'),
  );
  $form['nodes'] = array('#type' => 'checkboxes',
    '#title' => t('Types'),
    '#default_value' => $edit['nodes'],
249
    '#options' => node_get_types('names'),
250 251 252 253 254 255 256
    '#description' => t('A list of node types you want to associate with this vocabulary.'),
    '#required' => TRUE,
  );
  $form['hierarchy'] = array('#type' => 'radios',
    '#title' => t('Hierarchy'),
    '#default_value' => $edit['hierarchy'],
    '#options' => array(t('Disabled'), t('Single'), t('Multiple')),
257
    '#description' => t('Allows <a href="@help-url">a tree-like hierarchy</a> between terms of this vocabulary.', array('@help-url' => url('admin/help/taxonomy', array('absolute' => TRUE)))),
258 259 260 261
  );
  $form['relations'] = array('#type' => 'checkbox',
    '#title' => t('Related terms'),
    '#default_value' => $edit['relations'],
262
    '#description' => t('Allows <a href="@help-url">related terms</a> in this vocabulary.', array('@help-url' => url('admin/help/taxonomy', array('absolute' => TRUE)))),
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
  );
  $form['tags'] = array('#type' => 'checkbox',
    '#title' => t('Free tagging'),
    '#default_value' => $edit['tags'],
    '#description' => t('Content is categorized by typing terms instead of choosing from a list.'),
  );
  $form['multiple'] = array('#type' => 'checkbox',
    '#title' => t('Multiple select'),
    '#default_value' => $edit['multiple'],
    '#description' => t('Allows nodes to have more than one term from this vocabulary (always true for free tagging).'),
  );
  $form['required'] = array('#type' => 'checkbox',
    '#title' => t('Required'),
    '#default_value' => $edit['required'],
    '#description' => t('If enabled, every node <strong>must</strong> have at least one term in this vocabulary.'),
  );
  $form['weight'] = array('#type' => 'weight',
    '#title' => t('Weight'),
    '#default_value' => $edit['weight'],
    '#description' => t('In listings, the heavier vocabularies will sink and the lighter vocabularies will be positioned nearer the top.'),
  );
284

285
  $form['submit'] = array('#type' => 'submit', '#value' => t('Submit'));
286
  if (isset($edit['vid'])) {
287
    $form['delete'] = array('#type' => 'submit', '#value' => t('Delete'));
288
    $form['vid'] = array('#type' => 'value', '#value' => $edit['vid']);
289
    $form['module'] = array('#type' => 'value', '#value' => $edit['module']);
Dries's avatar
 
Dries committed
290
  }
291
  return $form;
Kjartan's avatar
Kjartan committed
292
}
Kjartan's avatar
Kjartan committed
293

294 295 296 297 298 299 300
/**
 * Accept the form submission for a vocabulary and save the results.
 */
function taxonomy_form_vocabulary_submit($form_id, $form_values) {
  // Fix up the nodes array to remove unchecked nodes.
  $form_values['nodes'] = array_filter($form_values['nodes']);
  switch (taxonomy_save_vocabulary($form_values)) {
301 302 303 304 305 306
    case SAVED_NEW:
      drupal_set_message(t('Created new vocabulary %name.', array('%name' => $form_values['name'])));
      break;
    case SAVED_UPDATED:
      drupal_set_message(t('Updated vocabulary %name.', array('%name' => $form_values['name'])));
      break;
307
  }
308
  return 'admin/content/taxonomy';
309 310
}

311
function taxonomy_save_vocabulary(&$edit) {
312
  $edit['nodes'] = empty($edit['nodes']) ? array() : $edit['nodes'];
Dries's avatar
 
Dries committed
313

314
  if (!empty($edit['vid']) && !empty($edit['name'])) {
315
    db_query("UPDATE {vocabulary} SET name = '%s', description = '%s', help = '%s', multiple = %d, required = %d, hierarchy = %d, relations = %d, tags = %d, weight = %d, module = '%s' WHERE vid = %d", $edit['name'], $edit['description'], $edit['help'], $edit['multiple'], $edit['required'], $edit['hierarchy'], $edit['relations'], $edit['tags'], $edit['weight'], isset($edit['module']) ? $edit['module'] : 'taxonomy', $edit['vid']);
Dries's avatar
 
Dries committed
316
    db_query("DELETE FROM {vocabulary_node_types} WHERE vid = %d", $edit['vid']);
317
    foreach ($edit['nodes'] as $type => $selected) {
Dries's avatar
 
Dries committed
318 319
      db_query("INSERT INTO {vocabulary_node_types} (vid, type) VALUES (%d, '%s')", $edit['vid'], $type);
    }
Dries's avatar
 
Dries committed
320
    module_invoke_all('taxonomy', 'update', 'vocabulary', $edit);
321
    $status = SAVED_UPDATED;
Dries's avatar
 
Dries committed
322
  }
323
  else if (!empty($edit['vid'])) {
324
    $status = taxonomy_del_vocabulary($edit['vid']);
Kjartan's avatar
Kjartan committed
325 326
  }
  else {
327
    $edit['vid'] = db_next_id('{vocabulary}_vid');
328
    db_query("INSERT INTO {vocabulary} (vid, name, description, help, multiple, required, hierarchy, relations, tags, weight, module) VALUES (%d, '%s', '%s', '%s', %d, %d, %d, %d, %d, %d, '%s')", $edit['vid'], $edit['name'], isset($edit['description']) ? $edit['description'] : NULL, isset($edit['help']) ? $edit['help'] : NULL, $edit['multiple'], $edit['required'], $edit['hierarchy'], $edit['relations'], isset($edit['tags']) ? $edit['tags'] : NULL, $edit['weight'], isset($edit['module']) ? $edit['module'] : 'taxonomy');
329
    foreach ($edit['nodes'] as $type => $selected) {
Dries's avatar
 
Dries committed
330 331
      db_query("INSERT INTO {vocabulary_node_types} (vid, type) VALUES (%d, '%s')", $edit['vid'], $type);
    }
Dries's avatar
 
Dries committed
332
    module_invoke_all('taxonomy', 'insert', 'vocabulary', $edit);
333
    $status = SAVED_NEW;
Kjartan's avatar
Kjartan committed
334
  }
Dries's avatar
 
Dries committed
335 336

  cache_clear_all();
Dries's avatar
 
Dries committed
337

338
  return $status;
Kjartan's avatar
Kjartan committed
339
}
Dries's avatar
 
Dries committed
340

341 342 343 344 345 346 347 348
/**
 * Delete a vocabulary.
 *
 * @param $vid
 *   A vocabulary ID.
 * @return
 *   Constant indicating items were deleted.
 */
Kjartan's avatar
Kjartan committed
349
function taxonomy_del_vocabulary($vid) {
350
  $vocabulary = (array) taxonomy_vocabulary_load($vid);
Dries's avatar
 
Dries committed
351

Dries's avatar
 
Dries committed
352
  db_query('DELETE FROM {vocabulary} WHERE vid = %d', $vid);
Dries's avatar
 
Dries committed
353
  db_query('DELETE FROM {vocabulary_node_types} WHERE vid = %d', $vid);
Dries's avatar
 
Dries committed
354
  $result = db_query('SELECT tid FROM {term_data} WHERE vid = %d', $vid);
Kjartan's avatar
Kjartan committed
355 356
  while ($term = db_fetch_object($result)) {
    taxonomy_del_term($term->tid);
Dries's avatar
 
Dries committed
357
  }
Dries's avatar
 
Dries committed
358

Dries's avatar
 
Dries committed
359
  module_invoke_all('taxonomy', 'delete', 'vocabulary', $vocabulary);
Dries's avatar
 
Dries committed
360

Dries's avatar
 
Dries committed
361 362
  cache_clear_all();

363
  return SAVED_DELETED;
Dries's avatar
 
Dries committed
364 365
}

366
function taxonomy_vocabulary_confirm_delete($vid) {
367
  $vocabulary = taxonomy_vocabulary_load($vid);
Dries's avatar
 
Dries committed
368

369 370 371
  $form['type'] = array('#type' => 'value', '#value' => 'vocabulary');
  $form['vid'] = array('#type' => 'value', '#value' => $vid);
  $form['name'] = array('#type' => 'value', '#value' => $vocabulary->name);
372
  return confirm_form($form,
373
                  t('Are you sure you want to delete the vocabulary %title?',
374
                  array('%title' => $vocabulary->name)),
375 376
                  'admin/content/taxonomy',
                  t('Deleting a vocabulary will delete all the terms in it. This action cannot be undone.'),
377
                  t('Delete'),
378
                  t('Cancel'));
Kjartan's avatar
Kjartan committed
379
}
Dries's avatar
 
Dries committed
380

381 382
function taxonomy_vocabulary_confirm_delete_submit($form_id, $form_values) {
  $status = taxonomy_del_vocabulary($form_values['vid']);
383
  drupal_set_message(t('Deleted vocabulary %name.', array('%name' => $form_values['name'])));
384
  return 'admin/content/taxonomy';
385 386
}

387
function taxonomy_form_term($vocabulary, $edit = array()) {
388 389 390 391 392 393
  $edit += array(
    'name' => '',
    'description' => '',
    'tid' => NULL,
    'weight' => 0,
  );
394 395 396 397
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Term name'),
    '#default_value' => $edit['name'],
398
    '#maxlength' => 255,
399 400
    '#description' => t('The name of this term.'),
    '#required' => TRUE);
401

402 403 404 405 406
  $form['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Description'),
    '#default_value' => $edit['description'],
    '#description' => t('A description of the term.'));
Dries's avatar
 
Dries committed
407

Kjartan's avatar
Kjartan committed
408
  if ($vocabulary->hierarchy) {
Dries's avatar
 
Dries committed
409
    $parent = array_keys(taxonomy_get_parents($edit['tid']));
410
    $children = taxonomy_get_tree($vocabulary->vid, $edit['tid']);
Dries's avatar
 
Dries committed
411

Dries's avatar
 
Dries committed
412
    // A term can't be the child of itself, nor of its children.
Dries's avatar
 
Dries committed
413 414 415
    foreach ($children as $child) {
      $exclude[] = $child->tid;
    }
Dries's avatar
 
Dries committed
416
    $exclude[] = $edit['tid'];
Dries's avatar
 
Dries committed
417

Kjartan's avatar
Kjartan committed
418
    if ($vocabulary->hierarchy == 1) {
419
      $form['parent'] = _taxonomy_term_select(t('Parent'), 'parent', $parent, $vocabulary->vid, l(t('Parent term'), 'admin/help/taxonomy', array('fragment' => 'parent')) .'.', 0, '<'. t('root') .'>', $exclude);
Dries's avatar
 
Dries committed
420
    }
Kjartan's avatar
Kjartan committed
421
    elseif ($vocabulary->hierarchy == 2) {
422
      $form['parent'] = _taxonomy_term_select(t('Parents'), 'parent', $parent, $vocabulary->vid, l(t('Parent terms'), 'admin/help/taxonomy', array('fragment' => 'parent')) .'.', 1, '<'. t('root') .'>', $exclude);
Dries's avatar
 
Dries committed
423
    }
Kjartan's avatar
Kjartan committed
424
  }
Dries's avatar
 
Dries committed
425

426
  if ($vocabulary->relations) {
427
    $form['relations'] = _taxonomy_term_select(t('Related terms'), 'relations', array_keys(taxonomy_get_related($edit['tid'])), $vocabulary->vid, NULL, 1, '<'. t('none') .'>', array($edit['tid']));
428 429
  }

430 431 432 433
  $form['synonyms'] = array(
    '#type' => 'textarea',
    '#title' => t('Synonyms'),
    '#default_value' => implode("\n", taxonomy_get_synonyms($edit['tid'])),
434
    '#description' => t('<a href="@help-url">Synonyms</a> of this term, one synonym per line.', array('@help-url' => url('admin/help/taxonomy', array('absolute' => TRUE)))));
435 436 437 438 439 440 441 442 443 444 445
  $form['weight'] = array(
    '#type' => 'weight',
    '#title' => t('Weight'),
    '#default_value' => $edit['weight'],
    '#description' => t('In listings, the heavier terms will sink and the lighter terms will be positioned nearer the top.'));
  $form['vid'] = array(
    '#type' => 'value',
    '#value' => $vocabulary->vid);
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'));
Kjartan's avatar
Kjartan committed
446

Dries's avatar
 
Dries committed
447
  if ($edit['tid']) {
448 449 450 451 452 453
    $form['delete'] = array(
      '#type' => 'submit',
      '#value' => t('Delete'));
    $form['tid'] = array(
      '#type' => 'value',
      '#value' => $edit['tid']);
Dries's avatar
 
Dries committed
454
  }
455
  else {
456
    $form['destination'] = array('#type' => 'hidden', '#value' => $_GET['q']);
457
  }
Dries's avatar
 
Dries committed
458

459
  return $form;
Kjartan's avatar
Kjartan committed
460
}
Dries's avatar
 
Dries committed
461

462 463 464 465 466 467
/**
 * Accept the form submission for a taxonomy term and save the result.
 */
function taxonomy_form_term_submit($form_id, $form_values) {
  switch (taxonomy_save_term($form_values)) {
    case SAVED_NEW:
468
      drupal_set_message(t('Created new term %term.', array('%term' => $form_values['name'])));
469 470
      break;
    case SAVED_UPDATED:
471
      drupal_set_message(t('The term %term has been updated.', array('%term' => $form_values['name'])));
472 473
      break;
  }
474
  return 'admin/content/taxonomy';
475 476
}

477 478 479 480 481 482 483 484
/**
 * Helper function for taxonomy_form_term_submit().
 *
 * @param $form_values
 * @return
 *   Status constant indicating if term was inserted or updated.
 */
function taxonomy_save_term(&$form_values) {
485
  if (!empty($form_values['tid']) && $form_values['name']) {
486
    db_query("UPDATE {term_data} SET name = '%s', description = '%s', weight = %d WHERE tid = %d", $form_values['name'], $form_values['description'], $form_values['weight'], $form_values['tid']);
487
    $hook = 'update';
488
    $status = SAVED_UPDATED;
Kjartan's avatar
Kjartan committed
489
  }
490
  else if (!empty($form_values['tid'])) {
491
    return taxonomy_del_term($form_values['tid']);
Kjartan's avatar
Kjartan committed
492 493
  }
  else {
494 495
    $form_values['tid'] = db_next_id('{term_data}_tid');
    db_query("INSERT INTO {term_data} (tid, name, description, vid, weight) VALUES (%d, '%s', '%s', %d, %d)", $form_values['tid'], $form_values['name'], $form_values['description'], $form_values['vid'], $form_values['weight']);
496
    $hook = 'insert';
497
    $status = SAVED_NEW;
Kjartan's avatar
Kjartan committed
498
  }
Dries's avatar
 
Dries committed
499

500
  db_query('DELETE FROM {term_relation} WHERE tid1 = %d OR tid2 = %d', $form_values['tid'], $form_values['tid']);
501
  if (!empty($form_values['relations'])) {
502
    foreach ($form_values['relations'] as $related_id) {
Kjartan's avatar
Kjartan committed
503
      if ($related_id != 0) {
504
        db_query('INSERT INTO {term_relation} (tid1, tid2) VALUES (%d, %d)', $form_values['tid'], $related_id);
Dries's avatar
 
Dries committed
505
      }
Kjartan's avatar
Kjartan committed
506
    }
Kjartan's avatar
Kjartan committed
507
  }
Dries's avatar
 
Dries committed
508

509 510 511
  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
512
  }
513 514
  if (is_array($form_values['parent'])) {
    foreach ($form_values['parent'] as $parent) {
515 516
      if (is_array($parent)) {
        foreach ($parent as $tid) {
517
          db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $form_values['tid'], $tid);
518 519 520
        }
      }
      else {
521
        db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $form_values['tid'], $parent);
522
      }
Dries's avatar
 
Dries committed
523
    }
Kjartan's avatar
Kjartan committed
524
  }
525
  else {
526
    db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $form_values['tid'], $form_values['parent']);
527
  }
Dries's avatar
 
Dries committed
528

529
  db_query('DELETE FROM {term_synonym} WHERE tid = %d', $form_values['tid']);
530
  if (!empty($form_values['synonyms'])) {
531
    foreach (explode ("\n", str_replace("\r", '', $form_values['synonyms'])) as $synonym) {
Dries's avatar
 
Dries committed
532
      if ($synonym) {
533
        db_query("INSERT INTO {term_synonym} (tid, name) VALUES (%d, '%s')", $form_values['tid'], chop($synonym));
Dries's avatar
 
Dries committed
534
      }
Kjartan's avatar
Kjartan committed
535
    }
Dries's avatar
 
Dries committed
536
  }
Dries's avatar
 
Dries committed
537

538
  if (isset($hook)) {
539
    module_invoke_all('taxonomy', $hook, 'term', $form_values);
540 541
  }

Dries's avatar
 
Dries committed
542 543
  cache_clear_all();

544
  return $status;
Kjartan's avatar
Kjartan committed
545
}
Dries's avatar
 
Dries committed
546

547 548 549 550 551 552 553 554
/**
 * Delete a term.
 *
 * @param $tid
 *   The term ID.
 * @return
 *   Status constant indicating deletion.
 */
Kjartan's avatar
Kjartan committed
555
function taxonomy_del_term($tid) {
556 557 558 559 560 561 562 563 564 565 566 567 568 569
  $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
570

571
      $term = (array) taxonomy_get_term($tid);
Dries's avatar
 
Dries committed
572

573 574 575 576 577
      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
578

579 580
      module_invoke_all('taxonomy', 'delete', 'term', $term);
    }
Dries's avatar
 
Dries committed
581

582 583
    $tids = $orphans;
  }
Dries's avatar
 
Dries committed
584

Dries's avatar
 
Dries committed
585
  cache_clear_all();
586 587

  return SAVED_DELETED;
Dries's avatar
 
Dries committed
588 589
}

590
function taxonomy_term_confirm_delete($tid) {
Dries's avatar
 
Dries committed
591 592
  $term = taxonomy_get_term($tid);

593 594 595
  $form['type'] = array('#type' => 'value', '#value' => 'term');
  $form['name'] = array('#type' => 'value', '#value' => $term->name);
  $form['tid'] = array('#type' => 'value', '#value' => $tid);
596
  return confirm_form($form,
597
                  t('Are you sure you want to delete the term %title?',
598
                  array('%title' => $term->name)),
599
                  'admin/content/taxonomy',
600 601
                  t('Deleting a term will delete all its children if there are any. This action cannot be undone.'),
                  t('Delete'),
602
                  t('Cancel'));
Kjartan's avatar
Kjartan committed
603
}
Dries's avatar
 
Dries committed
604

605 606
function taxonomy_term_confirm_delete_submit($form_id, $form_values) {
  taxonomy_del_term($form_values['tid']);
607
  drupal_set_message(t('Deleted term %name.', array('%name' => $form_values['name'])));
608
  return 'admin/content/taxonomy';
Kjartan's avatar
Kjartan committed
609 610
}

Dries's avatar
 
Dries committed
611 612 613
/**
 * Generate a form element for selecting terms from a vocabulary.
 */
Dries's avatar
 
Dries committed
614
function taxonomy_form($vid, $value = 0, $help = NULL, $name = 'taxonomy') {
615
  $vocabulary = taxonomy_vocabulary_load($vid);
616
  $help = ($help) ? $help : $vocabulary->help;
Kjartan's avatar
Kjartan committed
617 618 619 620
  if ($vocabulary->required) {
    $blank = 0;
  }
  else {
Dries's avatar
 
Dries committed
621
    $blank = '<'. t('none') .'>';
Kjartan's avatar
Kjartan committed
622
  }
Dries's avatar
 
Dries committed
623

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

627
/**
628
 * Generate a set of options for selecting a term from all vocabularies.
629 630 631 632 633 634 635
 */
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);
636 637
    if ($tree && (count($tree) > 1)) {
      $options[$vocabulary->name] = array();
638
      foreach ($tree as $term) {
639
        $options[$vocabulary->name][$term->tid] = str_repeat('-', $term->depth) . $term->name;
640 641 642 643 644 645
      }
    }
  }
  return $options;
}

Dries's avatar
 
Dries committed
646 647 648 649 650 651
/**
 * 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
652
function taxonomy_get_vocabularies($type = NULL) {
Kjartan's avatar
Kjartan committed
653
  if ($type) {
654
    $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
655 656
  }
  else {
657
    $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
658
  }
Dries's avatar
 
Dries committed
659

Kjartan's avatar
Kjartan committed
660
  $vocabularies = array();
Dries's avatar
 
Dries committed
661
  $node_types = array();
Kjartan's avatar
Kjartan committed
662
  while ($voc = db_fetch_object($result)) {
Dries's avatar
 
Dries committed
663 664 665 666
    $node_types[$voc->vid][] = $voc->type;
    unset($voc->type);
    $voc->nodes = $node_types[$voc->vid];
    $vocabularies[$voc->vid] = $voc;
Dries's avatar
 
Dries committed
667
  }
Dries's avatar
 
Dries committed
668

Kjartan's avatar
Kjartan committed
669 670
  return $vocabularies;
}
Dries's avatar
 
Dries committed
671

Dries's avatar
 
Dries committed
672
/**
673
 * Implementation of hook_form_alter().
Dries's avatar
 
Dries committed
674 675
 * Generate a form for selecting terms to associate with a node.
 */
676
function taxonomy_form_alter(&$form, $form_id) {
677
  if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] .'_node_form' == $form_id) {
678 679
    $node = $form['#node'];

680
    if (!isset($node->taxonomy)) {
681
      $terms = empty($node->nid) ? array() : taxonomy_node_get_terms($node);
Kjartan's avatar
Kjartan committed
682 683
    }
    else {
684
      $terms = $node->taxonomy;
Dries's avatar
 
Dries committed
685 686
    }

687
    $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
688

689 690 691 692
    while ($vocabulary = db_fetch_object($c)) {
      if ($vocabulary->tags) {
        $typed_terms = array();
        foreach ($terms as $term) {
693
          // Extract terms belonging to the vocabulary in question.
694
          if ($term->vid == $vocabulary->vid) {
Dries's avatar
Dries committed
695

696
            // Commas and quotes in terms are special cases, so encode 'em.
697 698
            if (strpos($term->name, ',') !== FALSE || strpos($term->name, '"') !== FALSE) {
              $term->name = '"'.str_replace('"', '""', $term->name).'"';
699 700 701 702
            }

            $typed_terms[] = $term->name;
          }
Dries's avatar
Dries committed
703
        }
704
        $typed_string = implode(', ', $typed_terms) . (array_key_exists('tags', $terms) ? $terms['tags'][$vocabulary->vid] : NULL);
705

706 707 708 709
        if ($vocabulary->help) {
          $help = $vocabulary->help;
        }
        else {
710
          $help = t('A comma-separated list of terms describing this content. Example: funny, bungee jumping, "Company, Inc.".');
711
        }
712 713 714 715 716 717 718
        $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,
719
          '#maxlength' => 255,
720
        );
721 722
      }
      else {
723 724 725 726 727 728 729 730
        // 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);
731
        $form['taxonomy'][$vocabulary->vid]['#weight'] = $vocabulary->weight;
732
        $form['taxonomy'][$vocabulary->vid]['#required'] = $vocabulary->required;
733
      }
Dries's avatar
Dries committed
734
    }
735
    if (!empty($form['taxonomy']) && is_array($form['taxonomy'])) {
736 737 738 739 740 741 742 743
      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,
        );
      }
744 745
      $form['taxonomy']['#weight'] = -3;
      $form['taxonomy']['#tree'] = TRUE;
Dries's avatar
Dries committed
746
    }
Dries's avatar
 
Dries committed
747
  }
Kjartan's avatar
Kjartan committed
748
}
Dries's avatar
 
Dries committed
749

Dries's avatar
 
Dries committed
750
/**
751
 * Find all terms associated with the given node, within one vocabulary.
Dries's avatar
 
Dries committed
752
 */
753 754
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
755 756 757
  $terms = array();
  while ($term = db_fetch_object($result)) {
    $terms[$term->$key] = $term;
Dries's avatar
 
Dries committed
758
  }
Kjartan's avatar
Kjartan committed
759 760 761
  return $terms;
}

Dries's avatar
 
Dries committed
762
/**
763
 * Find all terms associated with the given node, ordered by vocabulary and term weight.
Dries's avatar
 
Dries committed
764
 */
765
function taxonomy_node_get_terms($node, $key = 'tid') {
Kjartan's avatar
Kjartan committed
766
  static $terms;
Dries's avatar
 
Dries committed
767

768 769 770
  if (!isset($terms[$node->vid])) {
    $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);
    $terms[$node->vid] = array();
Dries's avatar
 
Dries committed
771
    while ($term = db_fetch_object($result)) {
772
      $terms[$node->vid][$term->$key] = $term;
Dries's avatar
 
Dries committed
773 774
    }
  }
775
  return $terms[$node->vid];
Kjartan's avatar
Kjartan committed
776
}
Dries's avatar
 
Dries committed
777

Dries's avatar
Dries committed
778 779 780
/**
 * Make sure incoming vids are free tagging enabled.
 */
781
function taxonomy_node_validate(&$node) {
782
  if (!empty($node->taxonomy)) {
783
    $terms = $node->taxonomy;
784
    if (!empty($terms['tags'])) {
Dries's avatar
Dries committed
785
      foreach ($terms['tags'] as $vid => $vid_value) {
786
        $vocabulary = taxonomy_vocabulary_load($vid);
787
        if (empty($vocabulary->tags)) {
788 789
          // see form_get_error $key = implode('][', $element['#parents']);
          // on why this is the key
790
          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
791 792 793 794 795 796
        }
      }
    }
  }
}

Dries's avatar
 
Dries committed
797 798 799
/**
 * Save term associations for a given node.