taxonomy.module 52.4 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();
Dries's avatar
 
Dries committed
31
    if (array_key_exists('taxonomy', $node)) {
32
      foreach ($node->taxonomy as $term) {
33
        $links['taxonomy_term_'. $term->tid] = array(
34 35 36
          'title' => $term->name,
          'href' => taxonomy_term_path($term),
          'attributes' => array('rel' => 'tag', 'title' => strip_tags($term->description))
37
        );
Dries's avatar
 
Dries committed
38
      }
Dries's avatar
 
Dries committed
39
    }
Kjartan's avatar
Kjartan committed
40

41
    // We call this hook again because some modules and themes call taxonomy_link('taxonomy terms') directly
42
    drupal_alter('link', $links, $node);
43 44

    return $links;
45 46 47
  }
}

48 49 50 51 52 53 54 55 56 57
/**
 * 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.
 */

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

Dries's avatar
 
Dries committed
66 67 68
/**
 * Implementation of hook_menu().
 */
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
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,
88
    'parent' => 'admin/content/taxonomy',
89 90
  );

91
  $items['admin/content/taxonomy/edit/vocabulary/%taxonomy_vocabulary'] = array(
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
    '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,
  );
117
  $items['admin/content/taxonomy/%taxonomy_vocabulary'] = array(
118 119 120 121 122 123 124
    'title' => t('List terms'),
    'page callback' => 'taxonomy_overview_terms',
    'page arguments' => array(3),
    'access arguments' => array('administer taxonomy'),
    'type' => MENU_CALLBACK,
  );

125
  $items['admin/content/taxonomy/%taxonomy_vocabulary/list'] = array(
126 127 128 129 130
    'title' => t('List'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

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

Dries's avatar
 
Dries committed
139 140
  return $items;
}
Dries's avatar
 
Dries committed
141

142 143 144 145
/**
 * List and manage vocabularies.
 */
function taxonomy_overview_vocabularies() {
146
  $vocabularies = taxonomy_get_vocabularies();
147
  $rows = array();
148 149 150
  foreach ($vocabularies as $vocabulary) {
    $types = array();
    foreach ($vocabulary->nodes as $type) {
151
      $node_type = node_get_types('name', $type);
152 153
      $types[] = $node_type ? $node_type : $type;
    }
154 155
    $rows[] = array('name' => check_plain($vocabulary->name),
      'type' => implode(', ', $types),
156 157 158
      '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")
159 160 161
    );
  }
  if (empty($rows)) {
Steven Wittens's avatar
Steven Wittens committed
162
    $rows[] = array(array('data' => t('No categories available.'), 'colspan' => '5'));
163
  }
drumm's avatar
drumm committed
164
  $header = array(t('Name'), t('Type'), array('data' => t('Operations'), 'colspan' => '3'));
165

166
  return theme('table', $header, $rows, array('id' => 'taxonomy'));
167 168 169 170 171 172
}

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

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

  drupal_set_title(check_plain($vocabulary->name));
  $start_from      = $_GET['page'] ? $_GET['page'] : 0;
  $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
187 188 189
    if (($start_from && ($start_from * $page_increment) >= $total_entries) || ($displayed_count == $page_increment)) {
      continue;
    }
190
    $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)));
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
    $displayed_count++; // we're counting tids displayed
  }

  if (!$rows) {
    $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
211
function taxonomy_form_vocabulary($edit = array()) {
212 213 214
  $form['name'] = array('#type' => 'textfield',
    '#title' => t('Vocabulary name'),
    '#default_value' => $edit['name'],
215
    '#maxlength' => 255,
216
    '#description' => t('The name for this vocabulary. Example: "Topic".'),
217 218 219 220 221 222 223 224 225
    '#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'),
226
    '#maxlength' => 255,
227 228 229 230 231 232
    '#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'],
233
    '#options' => node_get_types('names'),
234 235 236 237 238 239 240
    '#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')),
241
    '#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)))),
242 243 244 245
  );
  $form['relations'] = array('#type' => 'checkbox',
    '#title' => t('Related terms'),
    '#default_value' => $edit['relations'],
246
    '#description' => t('Allows <a href="@help-url">related terms</a> in this vocabulary.', array('@help-url' => url('admin/help/taxonomy', array('absolute' => TRUE)))),
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
  );
  $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.'),
  );
268

269
  $form['submit'] = array('#type' => 'submit', '#value' => t('Submit'));
Dries's avatar
 
Dries committed
270
  if ($edit['vid']) {
271
    $form['delete'] = array('#type' => 'submit', '#value' => t('Delete'));
272
    $form['vid'] = array('#type' => 'value', '#value' => $edit['vid']);
273
    $form['module'] = array('#type' => 'value', '#value' => $edit['module']);
Dries's avatar
 
Dries committed
274
  }
275
  return $form;
Kjartan's avatar
Kjartan committed
276
}
Kjartan's avatar
Kjartan committed
277

278 279 280 281 282 283 284
/**
 * 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)) {
285 286 287 288 289 290
    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;
291
  }
292
  return 'admin/content/taxonomy';
293 294
}

295
function taxonomy_save_vocabulary(&$edit) {
296
  $edit['nodes'] = empty($edit['nodes']) ? array() : $edit['nodes'];
Dries's avatar
 
Dries committed
297

298
  if (!empty($edit['vid']) && !empty($edit['name'])) {
299
    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
300
    db_query("DELETE FROM {vocabulary_node_types} WHERE vid = %d", $edit['vid']);
301
    foreach ($edit['nodes'] as $type => $selected) {
Dries's avatar
 
Dries committed
302 303
      db_query("INSERT INTO {vocabulary_node_types} (vid, type) VALUES (%d, '%s')", $edit['vid'], $type);
    }
Dries's avatar
 
Dries committed
304
    module_invoke_all('taxonomy', 'update', 'vocabulary', $edit);
305
    $status = SAVED_UPDATED;
Dries's avatar
 
Dries committed
306
  }
307
  else if (!empty($edit['vid'])) {
308
    $status = taxonomy_del_vocabulary($edit['vid']);
Kjartan's avatar
Kjartan committed
309 310
  }
  else {
311
    $edit['vid'] = db_next_id('{vocabulary}_vid');
312
    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');
313
    foreach ($edit['nodes'] as $type => $selected) {
Dries's avatar
 
Dries committed
314 315
      db_query("INSERT INTO {vocabulary_node_types} (vid, type) VALUES (%d, '%s')", $edit['vid'], $type);
    }
Dries's avatar
 
Dries committed
316
    module_invoke_all('taxonomy', 'insert', 'vocabulary', $edit);
317
    $status = SAVED_NEW;
Kjartan's avatar
Kjartan committed
318
  }
Dries's avatar
 
Dries committed
319 320

  cache_clear_all();
Dries's avatar
 
Dries committed
321

322
  return $status;
Kjartan's avatar
Kjartan committed
323
}
Dries's avatar
 
Dries committed
324

325 326 327 328 329 330 331 332
/**
 * Delete a vocabulary.
 *
 * @param $vid
 *   A vocabulary ID.
 * @return
 *   Constant indicating items were deleted.
 */
Kjartan's avatar
Kjartan committed
333
function taxonomy_del_vocabulary($vid) {
334
  $vocabulary = (array) taxonomy_vocabulary_load($vid);
Dries's avatar
 
Dries committed
335

Dries's avatar
 
Dries committed
336
  db_query('DELETE FROM {vocabulary} WHERE vid = %d', $vid);
Dries's avatar
 
Dries committed
337
  db_query('DELETE FROM {vocabulary_node_types} WHERE vid = %d', $vid);
Dries's avatar
 
Dries committed
338
  $result = db_query('SELECT tid FROM {term_data} WHERE vid = %d', $vid);
Kjartan's avatar
Kjartan committed
339 340
  while ($term = db_fetch_object($result)) {
    taxonomy_del_term($term->tid);
Dries's avatar
 
Dries committed
341
  }
Dries's avatar
 
Dries committed
342

Dries's avatar
 
Dries committed
343
  module_invoke_all('taxonomy', 'delete', 'vocabulary', $vocabulary);
Dries's avatar
 
Dries committed
344

Dries's avatar
 
Dries committed
345 346
  cache_clear_all();

347
  return SAVED_DELETED;
Dries's avatar
 
Dries committed
348 349
}

350
function taxonomy_vocabulary_confirm_delete($vid) {
351
  $vocabulary = taxonomy_vocabulary_load($vid);
Dries's avatar
 
Dries committed
352

353 354 355
  $form['type'] = array('#type' => 'value', '#value' => 'vocabulary');
  $form['vid'] = array('#type' => 'value', '#value' => $vid);
  $form['name'] = array('#type' => 'value', '#value' => $vocabulary->name);
356
  return confirm_form($form,
357
                  t('Are you sure you want to delete the vocabulary %title?',
358
                  array('%title' => $vocabulary->name)),
359 360
                  'admin/content/taxonomy',
                  t('Deleting a vocabulary will delete all the terms in it. This action cannot be undone.'),
361
                  t('Delete'),
362
                  t('Cancel'));
Kjartan's avatar
Kjartan committed
363
}
Dries's avatar
 
Dries committed
364

365 366
function taxonomy_vocabulary_confirm_delete_submit($form_id, $form_values) {
  $status = taxonomy_del_vocabulary($form_values['vid']);
367
  drupal_set_message(t('Deleted vocabulary %name.', array('%name' => $form_values['name'])));
368
  return 'admin/content/taxonomy';
369 370
}

371
function taxonomy_form_term($vocabulary, $edit = array()) {
372 373 374 375
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Term name'),
    '#default_value' => $edit['name'],
376
    '#maxlength' => 255,
377 378
    '#description' => t('The name of this term.'),
    '#required' => TRUE);
379

380 381 382 383 384
  $form['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Description'),
    '#default_value' => $edit['description'],
    '#description' => t('A description of the term.'));
Dries's avatar
 
Dries committed
385

Kjartan's avatar
Kjartan committed
386
  if ($vocabulary->hierarchy) {
Dries's avatar
 
Dries committed
387
    $parent = array_keys(taxonomy_get_parents($edit['tid']));
388
    $children = taxonomy_get_tree($vocabulary->vid, $edit['tid']);
Dries's avatar
 
Dries committed
389

Dries's avatar
 
Dries committed
390
    // A term can't be the child of itself, nor of its children.
Dries's avatar
 
Dries committed
391 392 393
    foreach ($children as $child) {
      $exclude[] = $child->tid;
    }
Dries's avatar
 
Dries committed
394
    $exclude[] = $edit['tid'];
Dries's avatar
 
Dries committed
395

Kjartan's avatar
Kjartan committed
396
    if ($vocabulary->hierarchy == 1) {
397
      $form['parent'] = _taxonomy_term_select(t('Parent'), 'parent', $parent, $vocabulary_id, l(t('Parent term'), 'admin/help/taxonomy', array('fragment' => 'parent')) .'.', 0, '<'. t('root') .'>', $exclude);
Dries's avatar
 
Dries committed
398
    }
Kjartan's avatar
Kjartan committed
399
    elseif ($vocabulary->hierarchy == 2) {
400
      $form['parent'] = _taxonomy_term_select(t('Parents'), 'parent', $parent, $vocabulary_id, l(t('Parent terms'), 'admin/help/taxonomy', array('fragment' => 'parent')) .'.', 1, '<'. t('root') .'>', $exclude);
Dries's avatar
 
Dries committed
401
    }
Kjartan's avatar
Kjartan committed
402
  }
Dries's avatar
 
Dries committed
403

404
  if ($vocabulary->relations) {
405
    $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']));
406 407
  }

408 409 410 411
  $form['synonyms'] = array(
    '#type' => 'textarea',
    '#title' => t('Synonyms'),
    '#default_value' => implode("\n", taxonomy_get_synonyms($edit['tid'])),
412
    '#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)))));
413 414 415 416 417 418 419 420 421 422 423
  $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
424

Dries's avatar
 
Dries committed
425
  if ($edit['tid']) {
426 427 428 429 430 431
    $form['delete'] = array(
      '#type' => 'submit',
      '#value' => t('Delete'));
    $form['tid'] = array(
      '#type' => 'value',
      '#value' => $edit['tid']);
Dries's avatar
 
Dries committed
432
  }
433
  else {
434
    $form['destination'] = array('#type' => 'hidden', '#value' => $_GET['q']);
435
  }
Dries's avatar
 
Dries committed
436

437
  return $form;
Kjartan's avatar
Kjartan committed
438
}
Dries's avatar
 
Dries committed
439

440 441 442 443 444 445
/**
 * 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:
446
      drupal_set_message(t('Created new term %term.', array('%term' => $form_values['name'])));
447 448
      break;
    case SAVED_UPDATED:
449
      drupal_set_message(t('The term %term has been updated.', array('%term' => $form_values['name'])));
450 451
      break;
  }
452
  return 'admin/content/taxonomy';
453 454
}

455 456 457 458 459 460 461 462 463 464
/**
 * 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) {
  if ($form_values['tid'] && $form_values['name']) {
    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']);
465
    $hook = 'update';
466
    $status = SAVED_UPDATED;
Kjartan's avatar
Kjartan committed
467
  }
468 469
  else if ($form_values['tid']) {
    return taxonomy_del_term($form_values['tid']);
Kjartan's avatar
Kjartan committed
470 471
  }
  else {
472 473
    $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']);
474
    $hook = 'insert';
475
    $status = SAVED_NEW;
Kjartan's avatar
Kjartan committed
476
  }
Dries's avatar
 
Dries committed
477

478 479 480
  db_query('DELETE FROM {term_relation} WHERE tid1 = %d OR tid2 = %d', $form_values['tid'], $form_values['tid']);
  if ($form_values['relations']) {
    foreach ($form_values['relations'] as $related_id) {
Kjartan's avatar
Kjartan committed
481
      if ($related_id != 0) {
482
        db_query('INSERT INTO {term_relation} (tid1, tid2) VALUES (%d, %d)', $form_values['tid'], $related_id);
Dries's avatar
 
Dries committed
483
      }
Kjartan's avatar
Kjartan committed
484
    }
Kjartan's avatar
Kjartan committed
485
  }
Dries's avatar
 
Dries committed
486

487 488 489
  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
490
  }
491 492
  if (is_array($form_values['parent'])) {
    foreach ($form_values['parent'] as $parent) {
493 494
      if (is_array($parent)) {
        foreach ($parent as $tid) {
495
          db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $form_values['tid'], $tid);
496 497 498
        }
      }
      else {
499
        db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $form_values['tid'], $parent);
500
      }
Dries's avatar
 
Dries committed
501
    }
Kjartan's avatar
Kjartan committed
502
  }
503
  else {
504
    db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $form_values['tid'], $form_values['parent']);
505
  }
Dries's avatar
 
Dries committed
506

507 508 509
  db_query('DELETE FROM {term_synonym} WHERE tid = %d', $form_values['tid']);
  if ($form_values['synonyms']) {
    foreach (explode ("\n", str_replace("\r", '', $form_values['synonyms'])) as $synonym) {
Dries's avatar
 
Dries committed
510
      if ($synonym) {
511
        db_query("INSERT INTO {term_synonym} (tid, name) VALUES (%d, '%s')", $form_values['tid'], chop($synonym));
Dries's avatar
 
Dries committed
512
      }
Kjartan's avatar
Kjartan committed
513
    }
Dries's avatar
 
Dries committed
514
  }
Dries's avatar
 
Dries committed
515

516
  if (isset($hook)) {
517
    module_invoke_all('taxonomy', $hook, 'term', $form_values);
518 519
  }

Dries's avatar
 
Dries committed
520 521
  cache_clear_all();

522
  return $status;
Kjartan's avatar
Kjartan committed
523
}
Dries's avatar
 
Dries committed
524

525 526 527 528 529 530 531 532
/**
 * Delete a term.
 *
 * @param $tid
 *   The term ID.
 * @return
 *   Status constant indicating deletion.
 */
Kjartan's avatar
Kjartan committed
533
function taxonomy_del_term($tid) {
534 535 536 537 538 539 540 541 542 543 544 545 546 547
  $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
548

549
      $term = (array) taxonomy_get_term($tid);
Dries's avatar
 
Dries committed
550

551 552 553 554 555
      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
556

557 558
      module_invoke_all('taxonomy', 'delete', 'term', $term);
    }
Dries's avatar
 
Dries committed
559

560 561
    $tids = $orphans;
  }
Dries's avatar
 
Dries committed
562

Dries's avatar
 
Dries committed
563
  cache_clear_all();
564 565

  return SAVED_DELETED;
Dries's avatar
 
Dries committed
566 567
}

568
function taxonomy_term_confirm_delete($tid) {
Dries's avatar
 
Dries committed
569 570
  $term = taxonomy_get_term($tid);

571 572 573
  $form['type'] = array('#type' => 'value', '#value' => 'term');
  $form['name'] = array('#type' => 'value', '#value' => $term->name);
  $form['tid'] = array('#type' => 'value', '#value' => $tid);
574
  return confirm_form($form,
575
                  t('Are you sure you want to delete the term %title?',
576
                  array('%title' => $term->name)),
577
                  'admin/content/taxonomy',
578 579
                  t('Deleting a term will delete all its children if there are any. This action cannot be undone.'),
                  t('Delete'),
580
                  t('Cancel'));
Kjartan's avatar
Kjartan committed
581
}
Dries's avatar
 
Dries committed
582

583 584
function taxonomy_term_confirm_delete_submit($form_id, $form_values) {
  taxonomy_del_term($form_values['tid']);
585
  drupal_set_message(t('Deleted term %name.', array('%name' => $form_values['name'])));
586
  return 'admin/content/taxonomy';
Kjartan's avatar
Kjartan committed
587 588
}

Dries's avatar
 
Dries committed
589 590 591
/**
 * Generate a form element for selecting terms from a vocabulary.
 */
Dries's avatar
 
Dries committed
592
function taxonomy_form($vid, $value = 0, $help = NULL, $name = 'taxonomy') {
593
  $vocabulary = taxonomy_vocabulary_load($vid);
594
  $help = ($help) ? $help : $vocabulary->help;
Kjartan's avatar
Kjartan committed
595 596 597 598
  if ($vocabulary->required) {
    $blank = 0;
  }
  else {
Dries's avatar
 
Dries committed
599
    $blank = '<'. t('none') .'>';
Kjartan's avatar
Kjartan committed
600
  }
Dries's avatar
 
Dries committed
601

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

605
/**
606
 * Generate a set of options for selecting a term from all vocabularies.
607 608 609 610 611 612 613
 */
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);
614 615
    if ($tree && (count($tree) > 1)) {
      $options[$vocabulary->name] = array();
616
      foreach ($tree as $term) {
617
        $options[$vocabulary->name][$term->tid] = str_repeat('-', $term->depth) . $term->name;
618 619 620 621 622 623
      }
    }
  }
  return $options;
}

Dries's avatar
 
Dries committed
624 625 626 627 628 629
/**
 * 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
630
function taxonomy_get_vocabularies($type = NULL) {
Kjartan's avatar
Kjartan committed
631
  if ($type) {
632
    $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
633 634
  }
  else {
635
    $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
636
  }
Dries's avatar
 
Dries committed
637

Kjartan's avatar
Kjartan committed
638
  $vocabularies = array();
Dries's avatar
 
Dries committed
639
  $node_types = array();
Kjartan's avatar
Kjartan committed
640
  while ($voc = db_fetch_object($result)) {
Dries's avatar
 
Dries committed
641 642 643 644
    $node_types[$voc->vid][] = $voc->type;
    unset($voc->type);
    $voc->nodes = $node_types[$voc->vid];
    $vocabularies[$voc->vid] = $voc;
Dries's avatar
 
Dries committed
645
  }
Dries's avatar
 
Dries committed
646

Kjartan's avatar
Kjartan committed
647 648
  return $vocabularies;
}
Dries's avatar
 
Dries committed
649

Dries's avatar
 
Dries committed
650
/**
651
 * Implementation of hook_form_alter().
Dries's avatar
 
Dries committed
652 653
 * Generate a form for selecting terms to associate with a node.
 */
654
function taxonomy_form_alter(&$form, $form_id) {
655 656 657
  if (isset($form['type']) && $form['type']['#value'] .'_node_form' == $form_id) {
    $node = $form['#node'];

658
    if (!isset($node->taxonomy)) {
659
      $terms = empty($node->nid) ? array() : taxonomy_node_get_terms($node);
Kjartan's avatar
Kjartan committed
660 661
    }
    else {
662
      $terms = $node->taxonomy;
Dries's avatar
 
Dries committed
663 664
    }

665
    $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
666

667 668 669 670
    while ($vocabulary = db_fetch_object($c)) {
      if ($vocabulary->tags) {
        $typed_terms = array();
        foreach ($terms as $term) {
671
          // Extract terms belonging to the vocabulary in question.
672
          if ($term->vid == $vocabulary->vid) {
Dries's avatar
Dries committed
673

674
            // Commas and quotes in terms are special cases, so encode 'em.
675 676
            if (strpos($term->name, ',') !== FALSE || strpos($term->name, '"') !== FALSE) {
              $term->name = '"'.str_replace('"', '""', $term->name).'"';
677 678 679 680
            }

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

684 685 686 687
        if ($vocabulary->help) {
          $help = $vocabulary->help;
        }
        else {
688
          $help = t('A comma-separated list of terms describing this content. Example: funny, bungee jumping, "Company, Inc.".');
689
        }
690 691 692 693 694 695 696
        $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,
697
          '#maxlength' => 255,
698
        );
699 700
      }
      else {
701 702 703 704 705 706 707 708
        // 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);
709
        $form['taxonomy'][$vocabulary->vid]['#weight'] = $vocabulary->weight;
710
        $form['taxonomy'][$vocabulary->vid]['#required'] = $vocabulary->required;
711
      }
Dries's avatar
Dries committed
712
    }
713
    if (!empty($form['taxonomy']) && is_array($form['taxonomy'])) {
714 715 716 717 718 719 720 721
      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,
        );
      }
722 723
      $form['taxonomy']['#weight'] = -3;
      $form['taxonomy']['#tree'] = TRUE;
Dries's avatar
Dries committed
724
    }
Dries's avatar
 
Dries committed
725
  }
Kjartan's avatar
Kjartan committed
726
}
Dries's avatar
 
Dries committed
727

Dries's avatar
 
Dries committed
728
/**
729
 * Find all terms associated with the given node, within one vocabulary.
Dries's avatar
 
Dries committed
730
 */
731 732
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
733 734 735
  $terms = array();
  while ($term = db_fetch_object($result)) {
    $terms[$term->$key] = $term;
Dries's avatar
 
Dries committed
736
  }
Kjartan's avatar
Kjartan committed
737 738 739
  return $terms;
}

Dries's avatar
 
Dries committed
740
/**
741
 * Find all terms associated with the given node, ordered by vocabulary and term weight.
Dries's avatar
 
Dries committed
742
 */
743
function taxonomy_node_get_terms($node, $key = 'tid') {
Kjartan's avatar
Kjartan committed
744
  static $terms;
Dries's avatar
 
Dries committed
745

746 747 748
  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
749
    while ($term = db_fetch_object($result)) {
750
      $terms[$node->vid][$term->$key] = $term;
Dries's avatar
 
Dries committed
751 752
    }
  }
753
  return $terms[$node->vid];
Kjartan's avatar
Kjartan committed
754
}
Dries's avatar
 
Dries committed
755

Dries's avatar
Dries committed
756 757 758
/**
 * Make sure incoming vids are free tagging enabled.
 */
759 760 761
function taxonomy_node_validate(&$node) {
  if ($node->taxonomy) {
    $terms = $node->taxonomy;
Dries's avatar
Dries committed
762 763
    if ($terms['tags']) {
      foreach ($terms['tags'] as $vid => $vid_value) {
764
        $vocabulary = taxonomy_vocabulary_load($vid);
765
        if (empty($vocabulary->tags)) {
766 767
          // see form_get_error $key = implode('][', $element['#parents']);
          // on why this is the key
768
          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
769 770 771 772 773 774
        }
      }
    }
  }
}

Dries's avatar
 
Dries committed
775 776 777
/**
 * Save term associations for a given node.
 */
778 779 780
function taxonomy_node_save($node, $terms) {

  taxonomy_node_delete_revision($node);
Dries's avatar
Dries committed
781 782 783

  // Free tagging vocabularies do not send their tids in the form,
  // so we'll detect them here and process them independently.
784 785 786
  if (isset($terms['tags'])) {
    $typed_input = $terms['tags'];
    unset($terms['tags']);
Dries's avatar
Dries committed
787 788 789 790 791 792

    foreach ($typed_input as $vid => $vid_value) {
      // This regexp allows the following types of user input:
      // this, "somecmpany, llc", "and ""this"" w,o.rks", foo bar
      $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
      preg_match_all($regexp, $vid_value, $matches);
793
      $typed_terms = array_unique($matches[1]);
Dries's avatar
Dries committed
794

795
      $inserted = array();
Dries's avatar
Dries committed
796 797 798
      foreach ($typed_terms as $typed_term) {
        // If a user has escaped a term (to demonstrate that it is a group,
        // or includes a comma or quote character), we remove the escape
799
        // formatting so to save the term into the database as the user intends.
Dries's avatar
Dries committed
800 801 802 803 804
        $typed_term = str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $typed_term));
        $typed_term = trim($typed_term);
        if ($typed_term == "") { continue; }

        // See if the term exists in the chosen vocabulary
805
        // and return the tid; otherwise, add a new record.
Dries's avatar
Dries committed
806
        $possibilities = taxonomy_get_term_by_name($typed_term);
807
        $typed_term_tid = NULL; // tid match, if any.
Dries's avatar
Dries committed
808 809 810 811 812 813 814
        foreach ($possibilities as $possibility) {
          if ($possibility->vid == $vid) {
            $typed_term_tid = $possibility->tid;
          }
        }

        if (!$typed_term_tid) {