taxonomy.module 51.6 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')) {
Dries's avatar
 
Dries committed
24 25 26
 *   $this->links(taxonomy_link('taxonomy terms', $node));
 * }
 */
Dries's avatar
 
Dries committed
27
function taxonomy_link($type, $node = NULL) {
Dries's avatar
 
Dries committed
28
  if ($type == 'taxonomy terms' && $node != NULL) {
Kjartan's avatar
 
Kjartan committed
29
    $links = array();
Dries's avatar
 
Dries committed
30
    if (array_key_exists('taxonomy', $node)) {
31
      foreach ($node->taxonomy as $term) {
32
        $links['taxonomy_term_'. $term->tid] = array(
33 34 35
          'title' => $term->name,
          'href' => taxonomy_term_path($term),
          'attributes' => array('rel' => 'tag', 'title' => strip_tags($term->description))
36
        );
Dries's avatar
 
Dries committed
37
      }
Dries's avatar
 
Dries committed
38
    }
Kjartan's avatar
Kjartan committed
39

40 41 42 43 44 45 46
    // We call this hook again because some modules and themes call taxonomy_link('taxonomy terms') directly
    foreach (module_implements('link_alter') AS $module) {
      $function = $module .'_link_alter';
      $function($node, $links);
    }

    return $links;
47 48 49
  }
}

50 51 52 53 54 55 56 57
function taxonomy_term_path($term) {
  $vocabulary = taxonomy_get_vocabulary($term->vid);
  if ($vocabulary->module != 'taxonomy' && $path = module_invoke($vocabulary->module, 'term_path', $term)) {
    return $path;
  }
  return 'taxonomy/term/'. $term->tid;
}

Dries's avatar
 
Dries committed
58 59 60
/**
 * Implementation of hook_menu().
 */
Dries's avatar
 
Dries committed
61
function taxonomy_menu($may_cache) {
Dries's avatar
 
Dries committed
62
  $items = array();
Dries's avatar
 
Dries committed
63

Dries's avatar
 
Dries committed
64
  if ($may_cache) {
65
    $items[] = array('path' => 'admin/content/taxonomy',
66
      'title' => t('Categories'),
67
      'description' => t('Create vocabularies and terms to categorize your content.'),
68
      'callback' => 'taxonomy_overview_vocabularies',
Dries's avatar
 
Dries committed
69
      'access' => user_access('administer taxonomy'));
70

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

76
    $items[] = array('path' => 'admin/content/taxonomy/add/vocabulary',
77
      'title' => t('Add vocabulary'),
78 79
      'callback' => 'drupal_get_form',
      'callback arguments' => array('taxonomy_form_vocabulary'),
Dries's avatar
 
Dries committed
80 81 82
      'access' => user_access('administer taxonomy'),
      'type' => MENU_LOCAL_TASK);

83
    $items[] = array('path' => 'admin/content/taxonomy/edit/vocabulary',
84
      'title' => t('Edit vocabulary'),
85
      'callback' => 'taxonomy_admin_vocabulary_edit',
86 87 88
      'access' => user_access('administer taxonomy'),
      'type' => MENU_CALLBACK);

89
    $items[] = array('path' => 'admin/content/taxonomy/edit/term',
90
      'title' => t('Edit term'),
91
      'callback' => 'taxonomy_admin_term_edit',
92 93 94
      'access' => user_access('administer taxonomy'),
      'type' => MENU_CALLBACK);

95
    $items[] = array('path' => 'taxonomy/term',
96
      'title' => t('Taxonomy term'),
Dries's avatar
 
Dries committed
97 98 99
      'callback' => 'taxonomy_term_page',
      'access' => user_access('access content'),
      'type' => MENU_CALLBACK);
Steven Wittens's avatar
Steven Wittens committed
100

101
    $items[] = array('path' => 'taxonomy/autocomplete',
102
      'title' => t('Autocomplete taxonomy'),
Steven Wittens's avatar
Steven Wittens committed
103 104 105
      'callback' => 'taxonomy_autocomplete',
      'access' => user_access('access content'),
      'type' => MENU_CALLBACK);
Dries's avatar
 
Dries committed
106
  }
Dries's avatar
Dries committed
107
  else {
108
    if (arg(0) == 'admin' && arg(1) == 'content' && arg(2) == 'taxonomy' && is_numeric(arg(3))) {
109 110
      $vid = arg(3);
      $items[] = array('path' => 'admin/content/taxonomy/'. $vid,
111
        'title' => t('List terms'),
112
        'callback' => 'taxonomy_overview_terms',
113
        'callback arguments' => array($vid),
Dries's avatar
Dries committed
114 115 116
        'access' => user_access('administer taxonomy'),
        'type' => MENU_CALLBACK);

117
      $items[] = array('path' => 'admin/content/taxonomy/'. $vid .'/list',
118
        'title' => t('List'),
119 120
        'type' => MENU_DEFAULT_LOCAL_TASK,
        'weight' => -10);
Dries's avatar
Dries committed
121

122
      $items[] = array('path' => 'admin/content/taxonomy/'. $vid .'/add/term',
123
        'title' => t('Add term'),
124 125
        'callback' => 'drupal_get_form',
        'callback arguments' => array('taxonomy_form_term', $vid),
Dries's avatar
Dries committed
126 127 128 129
        'access' => user_access('administer taxonomy'),
        'type' => MENU_LOCAL_TASK);
    }
  }
Dries's avatar
 
Dries committed
130

Dries's avatar
 
Dries committed
131 132
  return $items;
}
Dries's avatar
 
Dries committed
133

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

158
  return theme('table', $header, $rows, array('id' => 'taxonomy'));
159 160 161 162 163 164 165 166 167 168 169
}

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

  $header = array(t('Name'), t('Operations'));
  $vocabulary = taxonomy_get_vocabulary($vid);
170 171 172
  if (!$vocabulary) {
    return drupal_not_found();
  }
173 174 175 176 177 178 179 180 181 182 183

  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
    if (($start_from && ($start_from * $page_increment) >= $total_entries) || ($displayed_count == $page_increment)) { continue; }
184
    $rows[] = array(str_repeat('--', $term->depth) . ' ' . l($term->name, "taxonomy/term/$term->tid"), l(t('edit'), "admin/content/taxonomy/edit/term/$term->tid", array(), $destination));
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    $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
205
function taxonomy_form_vocabulary($edit = array()) {
206 207 208 209
  $form['name'] = array('#type' => 'textfield',
    '#title' => t('Vocabulary name'),
    '#default_value' => $edit['name'],
    '#maxlength' => 64,
210
    '#description' => t('The name for this vocabulary. Example: "Topic".'),
211 212 213 214 215 216 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'),
    '#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'],
226
    '#options' => node_get_types('names'),
227 228 229 230 231 232 233
    '#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')),
234
    '#description' => t('Allows <a href="@help-url">a tree-like hierarchy</a> between terms of this vocabulary.', array('@help-url' => url('admin/help/taxonomy', NULL, NULL, 'hierarchy'))),
235 236 237 238
  );
  $form['relations'] = array('#type' => 'checkbox',
    '#title' => t('Related terms'),
    '#default_value' => $edit['relations'],
239
    '#description' => t('Allows <a href="@help-url">related terms</a> in this vocabulary.', array('@help-url' => url('admin/help/taxonomy', NULL, NULL, 'related-terms'))),
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
  );
  $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.'),
  );
261

262
  $form['submit'] = array('#type' => 'submit', '#value' => t('Submit'));
Dries's avatar
 
Dries committed
263
  if ($edit['vid']) {
264
    $form['delete'] = array('#type' => 'submit', '#value' => t('Delete'));
265
    $form['vid'] = array('#type' => 'value', '#value' => $edit['vid']);
266
    $form['module'] = array('#type' => 'value', '#value' => $edit['module']);
Dries's avatar
 
Dries committed
267
  }
268
  return $form;
Kjartan's avatar
Kjartan committed
269
}
Kjartan's avatar
Kjartan committed
270

271 272 273 274 275 276 277 278
/**
 * 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)) {
  case SAVED_NEW:
279
    drupal_set_message(t('Created new vocabulary %name.', array('%name' => $form_values['name'])));
280 281
    break;
  case SAVED_UPDATED:
282
    drupal_set_message(t('Updated vocabulary %name.', array('%name' => $form_values['name'])));
283 284
    break;
  }
285
  return 'admin/content/taxonomy';
286 287
}

288
function taxonomy_save_vocabulary(&$edit) {
289
  $edit['nodes'] = empty($edit['nodes']) ? array() : $edit['nodes'];
Dries's avatar
 
Dries committed
290

Dries's avatar
 
Dries committed
291
  if ($edit['vid'] && $edit['name']) {
292
    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
293
    db_query("DELETE FROM {vocabulary_node_types} WHERE vid = %d", $edit['vid']);
294
    foreach ($edit['nodes'] as $type => $selected) {
Dries's avatar
 
Dries committed
295 296
      db_query("INSERT INTO {vocabulary_node_types} (vid, type) VALUES (%d, '%s')", $edit['vid'], $type);
    }
Dries's avatar
 
Dries committed
297
    module_invoke_all('taxonomy', 'update', 'vocabulary', $edit);
298
    $status = SAVED_UPDATED;
Dries's avatar
 
Dries committed
299
  }
Dries's avatar
 
Dries committed
300
  else if ($edit['vid']) {
301
    $status = taxonomy_del_vocabulary($edit['vid']);
Kjartan's avatar
Kjartan committed
302 303
  }
  else {
304 305
    $edit['vid'] = db_next_id('{vocabulary}_vid');
    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'], $edit['description'], $edit['help'], $edit['multiple'], $edit['required'], $edit['hierarchy'], $edit['relations'], $edit['tags'], $edit['weight'], isset($edit['module']) ? $edit['module'] : 'taxonomy');
306
    foreach ($edit['nodes'] as $type => $selected) {
Dries's avatar
 
Dries committed
307 308
      db_query("INSERT INTO {vocabulary_node_types} (vid, type) VALUES (%d, '%s')", $edit['vid'], $type);
    }
Dries's avatar
 
Dries committed
309
    module_invoke_all('taxonomy', 'insert', 'vocabulary', $edit);
310
    $status = SAVED_NEW;
Kjartan's avatar
Kjartan committed
311
  }
Dries's avatar
 
Dries committed
312 313

  cache_clear_all();
Dries's avatar
 
Dries committed
314

315
  return $status;
Kjartan's avatar
Kjartan committed
316
}
Dries's avatar
 
Dries committed
317

Kjartan's avatar
Kjartan committed
318
function taxonomy_del_vocabulary($vid) {
319
  $vocabulary = (array) taxonomy_get_vocabulary($vid);
Dries's avatar
 
Dries committed
320

Dries's avatar
 
Dries committed
321
  db_query('DELETE FROM {vocabulary} WHERE vid = %d', $vid);
Dries's avatar
 
Dries committed
322
  db_query('DELETE FROM {vocabulary_node_types} WHERE vid = %d', $vid);
Dries's avatar
 
Dries committed
323
  $result = db_query('SELECT tid FROM {term_data} WHERE vid = %d', $vid);
Kjartan's avatar
Kjartan committed
324 325
  while ($term = db_fetch_object($result)) {
    taxonomy_del_term($term->tid);
Dries's avatar
 
Dries committed
326
  }
Dries's avatar
 
Dries committed
327

Dries's avatar
 
Dries committed
328
  module_invoke_all('taxonomy', 'delete', 'vocabulary', $vocabulary);
Dries's avatar
 
Dries committed
329

Dries's avatar
 
Dries committed
330 331
  cache_clear_all();

332
  return SAVED_DELETED;
Dries's avatar
 
Dries committed
333 334
}

335
function taxonomy_vocabulary_confirm_delete($vid) {
Dries's avatar
 
Dries committed
336 337
  $vocabulary = taxonomy_get_vocabulary($vid);

338 339 340
  $form['type'] = array('#type' => 'value', '#value' => 'vocabulary');
  $form['vid'] = array('#type' => 'value', '#value' => $vid);
  $form['name'] = array('#type' => 'value', '#value' => $vocabulary->name);
341
  return confirm_form($form,
342
                  t('Are you sure you want to delete the vocabulary %title?',
343
                  array('%title' => $vocabulary->name)),
344 345
                  'admin/content/taxonomy',
                  t('Deleting a vocabulary will delete all the terms in it. This action cannot be undone.'),
346
                  t('Delete'),
347
                  t('Cancel'));
Kjartan's avatar
Kjartan committed
348
}
Dries's avatar
 
Dries committed
349

350 351
function taxonomy_vocabulary_confirm_delete_submit($form_id, $form_values) {
  $status = taxonomy_del_vocabulary($form_values['vid']);
352
  drupal_set_message(t('Deleted vocabulary %name.', array('%name' => $form_values['name'])));
353
  return 'admin/content/taxonomy';
354 355
}

356
function taxonomy_form_term($vocabulary_id, $edit = array()) {
Kjartan's avatar
Kjartan committed
357
  $vocabulary = taxonomy_get_vocabulary($vocabulary_id);
Dries's avatar
 
Dries committed
358

359
  $form['name'] = array('#type' => 'textfield', '#title' => t('Term name'), '#default_value' => $edit['name'], '#maxlength' => 64, '#description' => t('The name for this term. Example: "Linux".'), '#required' => TRUE);
360

361
  $form['description'] = array('#type' => 'textarea', '#title' => t('Description'), '#default_value' => $edit['description'], '#description' => t('A description of the term.'));
Dries's avatar
 
Dries committed
362

Kjartan's avatar
Kjartan committed
363
  if ($vocabulary->hierarchy) {
Dries's avatar
 
Dries committed
364 365
    $parent = array_keys(taxonomy_get_parents($edit['tid']));
    $children = taxonomy_get_tree($vocabulary_id, $edit['tid']);
Dries's avatar
 
Dries committed
366

Dries's avatar
 
Dries committed
367
    // A term can't be the child of itself, nor of its children.
Dries's avatar
 
Dries committed
368 369 370
    foreach ($children as $child) {
      $exclude[] = $child->tid;
    }
Dries's avatar
 
Dries committed
371
    $exclude[] = $edit['tid'];
Dries's avatar
 
Dries committed
372

Kjartan's avatar
Kjartan committed
373
    if ($vocabulary->hierarchy == 1) {
374
      $form['parent'] = _taxonomy_term_select(t('Parent'), 'parent', $parent, $vocabulary_id, l(t('Parent term'), 'admin/help/taxonomy', NULL, NULL, 'parent') .'.', 0, '<'. t('root') .'>', $exclude);
Dries's avatar
 
Dries committed
375
    }
Kjartan's avatar
Kjartan committed
376
    elseif ($vocabulary->hierarchy == 2) {
377
      $form['parent'] = _taxonomy_term_select(t('Parents'), 'parent', $parent, $vocabulary_id, l(t('Parent terms'), 'admin/help/taxonomy', NULL, NULL, 'parent') .'.', 1, '<'. t('root') .'>', $exclude);
Dries's avatar
 
Dries committed
378
    }
Kjartan's avatar
Kjartan committed
379
  }
Dries's avatar
 
Dries committed
380

381
  if ($vocabulary->relations) {
382
    $form['relations'] = _taxonomy_term_select(t('Related terms'), 'relations', array_keys(taxonomy_get_related($edit['tid'])), $vocabulary_id, NULL, 1, '<'. t('none') .'>', array($edit['tid']));
383 384
  }

385
  $form['synonyms'] = array('#type' => 'textarea', '#title' => t('Synonyms'), '#default_value' => implode("\n", taxonomy_get_synonyms($edit['tid'])), '#description' => t('<a href="@help-url">Synonyms</a> of this term, one synonym per line.', array('@help-url' => url('admin/help/taxonomy', NULL, NULL, 'synonyms'))));
386
  $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.'));
387
  $form['vid'] = array('#type' => 'value', '#value' => $vocabulary->vid);
388
  $form['submit'] = array('#type' => 'submit', '#value' => t('Submit'));
Kjartan's avatar
Kjartan committed
389

Dries's avatar
 
Dries committed
390
  if ($edit['tid']) {
391
    $form['delete'] = array('#type' => 'submit', '#value' => t('Delete'));
392
    $form['tid'] = array('#type' => 'value', '#value' => $edit['tid']);
Dries's avatar
 
Dries committed
393
  }
394
  else {
395
    $form['destination'] = array('#type' => 'hidden', '#value' => $_GET['q']);
396
  }
Dries's avatar
 
Dries committed
397

398
  return $form;
Kjartan's avatar
Kjartan committed
399
}
Dries's avatar
 
Dries committed
400

401 402 403 404 405 406
/**
 * 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:
407
      drupal_set_message(t('Created new term %term.', array('%term' => $form_values['name'])));
408 409
      break;
    case SAVED_UPDATED:
410
      drupal_set_message(t('The term %term has been updated.', array('%term' => $form_values['name'])));
411 412
      break;
  }
413
  return 'admin/content/taxonomy';
414 415
}

416
function taxonomy_save_term(&$edit) {
Dries's avatar
 
Dries committed
417
  if ($edit['tid'] && $edit['name']) {
418
    db_query("UPDATE {term_data} SET name = '%s', description = '%s', weight = %d WHERE tid = %d", $edit['name'], $edit['description'], $edit['weight'], $edit['tid']);
419
    $hook = 'update';
420
    $status = SAVED_UPDATED;
Kjartan's avatar
Kjartan committed
421
  }
Dries's avatar
 
Dries committed
422 423
  else if ($edit['tid']) {
    return taxonomy_del_term($edit['tid']);
Kjartan's avatar
Kjartan committed
424 425
  }
  else {
Dries's avatar
 
Dries committed
426
    $edit['tid'] = db_next_id('{term_data}_tid');
427
    db_query("INSERT INTO {term_data} (tid, name, description, vid, weight) VALUES (%d, '%s', '%s', %d, %d)", $edit['tid'], $edit['name'], $edit['description'], $edit['vid'], $edit['weight']);
428
    $hook = 'insert';
429
    $status = SAVED_NEW;
Kjartan's avatar
Kjartan committed
430
  }
Dries's avatar
 
Dries committed
431

Dries's avatar
 
Dries committed
432 433 434
  db_query('DELETE FROM {term_relation} WHERE tid1 = %d OR tid2 = %d', $edit['tid'], $edit['tid']);
  if ($edit['relations']) {
    foreach ($edit['relations'] as $related_id) {
Kjartan's avatar
Kjartan committed
435
      if ($related_id != 0) {
Dries's avatar
 
Dries committed
436
        db_query('INSERT INTO {term_relation} (tid1, tid2) VALUES (%d, %d)', $edit['tid'], $related_id);
Dries's avatar
 
Dries committed
437
      }
Kjartan's avatar
Kjartan committed
438
    }
Kjartan's avatar
Kjartan committed
439
  }
Dries's avatar
 
Dries committed
440

Dries's avatar
 
Dries committed
441
  db_query('DELETE FROM {term_hierarchy} WHERE tid = %d', $edit['tid']);
442
  if (!isset($edit['parent']) || empty($edit['parent'])) {
443
    $edit['parent'] = array(0);
Kjartan's avatar
Kjartan committed
444
  }
Dries's avatar
 
Dries committed
445 446
  if (is_array($edit['parent'])) {
    foreach ($edit['parent'] as $parent) {
447 448 449 450 451 452 453 454
      if (is_array($parent)) {
        foreach ($parent as $tid) {
          db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $edit['tid'], $tid);
        }
      }
      else {
        db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $edit['tid'], $parent);
      }
Dries's avatar
 
Dries committed
455
    }
Kjartan's avatar
Kjartan committed
456
  }
457 458 459
  else {
    db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $edit['tid'], $edit['parent']);
  }
Dries's avatar
 
Dries committed
460

Dries's avatar
 
Dries committed
461 462 463
  db_query('DELETE FROM {term_synonym} WHERE tid = %d', $edit['tid']);
  if ($edit['synonyms']) {
    foreach (explode ("\n", str_replace("\r", '', $edit['synonyms'])) as $synonym) {
Dries's avatar
 
Dries committed
464
      if ($synonym) {
Dries's avatar
 
Dries committed
465
        db_query("INSERT INTO {term_synonym} (tid, name) VALUES (%d, '%s')", $edit['tid'], chop($synonym));
Dries's avatar
 
Dries committed
466
      }
Kjartan's avatar
Kjartan committed
467
    }
Dries's avatar
 
Dries committed
468
  }
Dries's avatar
 
Dries committed
469

470 471 472 473
  if (isset($hook)) {
    module_invoke_all('taxonomy', $hook, 'term', $edit);
  }

Dries's avatar
 
Dries committed
474 475
  cache_clear_all();

476
  return $status;
Kjartan's avatar
Kjartan committed
477
}
Dries's avatar
 
Dries committed
478

Kjartan's avatar
Kjartan committed
479
function taxonomy_del_term($tid) {
480 481 482 483 484 485 486 487 488 489 490 491 492 493
  $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
494

495
      $term = (array) taxonomy_get_term($tid);
Dries's avatar
 
Dries committed
496

497 498 499 500 501
      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
502

503 504
      module_invoke_all('taxonomy', 'delete', 'term', $term);
    }
Dries's avatar
 
Dries committed
505

506 507
    $tids = $orphans;
  }
Dries's avatar
 
Dries committed
508

Dries's avatar
 
Dries committed
509
  cache_clear_all();
510 511

  return SAVED_DELETED;
Dries's avatar
 
Dries committed
512 513
}

514
function taxonomy_term_confirm_delete($tid) {
Dries's avatar
 
Dries committed
515 516
  $term = taxonomy_get_term($tid);

517 518 519
  $form['type'] = array('#type' => 'value', '#value' => 'term');
  $form['name'] = array('#type' => 'value', '#value' => $term->name);
  $form['tid'] = array('#type' => 'value', '#value' => $tid);
520
  return confirm_form($form,
521
                  t('Are you sure you want to delete the term %title?',
522
                  array('%title' => $term->name)),
523
                  'admin/content/taxonomy',
524 525
                  t('Deleting a term will delete all its children if there are any. This action cannot be undone.'),
                  t('Delete'),
526
                  t('Cancel'));
Kjartan's avatar
Kjartan committed
527
}
Dries's avatar
 
Dries committed
528

529 530
function taxonomy_term_confirm_delete_submit($form_id, $form_values) {
  taxonomy_del_term($form_values['tid']);
531
  drupal_set_message(t('Deleted term %name.', array('%name' => $form_values['name'])));
532
  return 'admin/content/taxonomy';
Kjartan's avatar
Kjartan committed
533 534
}

Dries's avatar
 
Dries committed
535 536 537
/**
 * Generate a form element for selecting terms from a vocabulary.
 */
Dries's avatar
 
Dries committed
538
function taxonomy_form($vid, $value = 0, $help = NULL, $name = 'taxonomy') {
Dries's avatar
 
Dries committed
539
  $vocabulary = taxonomy_get_vocabulary($vid);
540
  $help = ($help) ? $help : $vocabulary->help;
Kjartan's avatar
Kjartan committed
541 542 543 544
  if ($vocabulary->required) {
    $blank = 0;
  }
  else {
Dries's avatar
 
Dries committed
545
    $blank = '<'. t('none') .'>';
Kjartan's avatar
Kjartan committed
546
  }
Dries's avatar
 
Dries committed
547

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

551 552 553 554 555 556 557 558 559 560
/**
 * Generate a set of options for selecting a term from all vocabularies. Can be
 * passed to form_select.
 */
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);
561 562
    if ($tree && (count($tree) > 1)) {
      $options[$vocabulary->name] = array();
563
      foreach ($tree as $term) {
564
        $options[$vocabulary->name][$term->tid] = str_repeat('-', $term->depth) . $term->name;
565 566 567 568 569 570
      }
    }
  }
  return $options;
}

Dries's avatar
 
Dries committed
571 572 573 574 575 576
/**
 * 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
577
function taxonomy_get_vocabularies($type = NULL) {
Kjartan's avatar
Kjartan committed
578
  if ($type) {
579
    $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
580 581
  }
  else {
582
    $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
583
  }
Dries's avatar
 
Dries committed
584

Kjartan's avatar
Kjartan committed
585
  $vocabularies = array();
Dries's avatar
 
Dries committed
586
  $node_types = array();
Kjartan's avatar
Kjartan committed
587
  while ($voc = db_fetch_object($result)) {
Dries's avatar
 
Dries committed
588 589 590 591
    $node_types[$voc->vid][] = $voc->type;
    unset($voc->type);
    $voc->nodes = $node_types[$voc->vid];
    $vocabularies[$voc->vid] = $voc;
Dries's avatar
 
Dries committed
592
  }
Dries's avatar
 
Dries committed
593

Kjartan's avatar
Kjartan committed
594 595
  return $vocabularies;
}
Dries's avatar
 
Dries committed
596

Dries's avatar
 
Dries committed
597 598 599
/**
 * Generate a form for selecting terms to associate with a node.
 */
600 601 602 603
function taxonomy_form_alter($form_id, &$form) {
  if (isset($form['type']) && $form['type']['#value'] .'_node_form' == $form_id) {
    $node = $form['#node'];

604
    if (!isset($node->taxonomy)) {
605 606 607 608 609 610
      if ($node->nid) {
        $terms = taxonomy_node_get_terms($node->nid);
      }
      else {
        $terms = array();
      }
Kjartan's avatar
Kjartan committed
611 612
    }
    else {
613
      $terms = $node->taxonomy;
Dries's avatar
 
Dries committed
614 615
    }

616
    $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
617

618 619 620 621
    while ($vocabulary = db_fetch_object($c)) {
      if ($vocabulary->tags) {
        $typed_terms = array();
        foreach ($terms as $term) {
622
          // Extract terms belonging to the vocabulary in question.
623
          if ($term->vid == $vocabulary->vid) {
Dries's avatar
Dries committed
624

625 626 627 628 629 630 631
            // Commas and quotes in terms are special cases, so encode 'em.
            if (preg_match('/,/', $term->name) || preg_match('/"/', $term->name)) {
              $term->name = '"'.preg_replace('/"/', '""', $term->name).'"';
            }

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

635 636 637 638
        if ($vocabulary->help) {
          $help = $vocabulary->help;
        }
        else {
639
          $help = t('A comma-separated list of terms describing this content. Example: funny, bungee jumping, "Company, Inc.".');
640
        }
641 642 643 644 645 646 647
        $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,
648
          '#maxlength' => 255,
649
        );
650 651
      }
      else {
652 653 654 655 656 657 658 659
        // 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);
660
        $form['taxonomy'][$vocabulary->vid]['#weight'] = $vocabulary->weight;
661
        $form['taxonomy'][$vocabulary->vid]['#required'] = $vocabulary->required;
662
      }
Dries's avatar
Dries committed
663
    }
664 665 666 667 668 669 670 671 672
    if (is_array($form['taxonomy']) && !empty($form['taxonomy'])) {
      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,
        );
      }
673 674
      $form['taxonomy']['#weight'] = -3;
      $form['taxonomy']['#tree'] = TRUE;
Dries's avatar
Dries committed
675
    }
Dries's avatar
 
Dries committed
676
  }
Kjartan's avatar
Kjartan committed
677
}
Dries's avatar
 
Dries committed
678

Dries's avatar
 
Dries committed
679 680 681 682
/**
 * Find all terms associated to the given node, within one vocabulary.
 */
function taxonomy_node_get_terms_by_vocabulary($nid, $vid, $key = 'tid') {
683
  $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.nid = %d ORDER BY weight', 't', 'tid'), $vid, $nid);
Kjartan's avatar
Kjartan committed
684 685 686
  $terms = array();
  while ($term = db_fetch_object($result)) {
    $terms[$term->$key] = $term;
Dries's avatar
 
Dries committed
687
  }
Kjartan's avatar
Kjartan committed
688 689 690
  return $terms;
}

Dries's avatar
 
Dries committed
691
/**
692
 * Find all terms associated to the given node, ordered by vocabulary and term weight.
Dries's avatar
 
Dries committed
693 694
 */
function taxonomy_node_get_terms($nid, $key = 'tid') {
Kjartan's avatar
Kjartan committed
695
  static $terms;
Dries's avatar
 
Dries committed
696

Dries's avatar
 
Dries committed
697
  if (!isset($terms[$nid])) {
698
    $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.nid = %d ORDER BY v.weight, t.weight, t.name', 't', 'tid'), $nid);
Kjartan's avatar
Kjartan committed
699
    $terms[$nid] = array();
Dries's avatar
 
Dries committed
700
    while ($term = db_fetch_object($result)) {
Kjartan's avatar
Kjartan committed
701
      $terms[$nid][$term->$key] = $term;
Dries's avatar
 
Dries committed
702 703
    }
  }
Kjartan's avatar
Kjartan committed
704 705
  return $terms[$nid];
}
Dries's avatar
 
Dries committed
706

Dries's avatar
Dries committed
707 708 709
/**
 * Make sure incoming vids are free tagging enabled.
 */
710 711 712
function taxonomy_node_validate(&$node) {
  if ($node->taxonomy) {
    $terms = $node->taxonomy;
Dries's avatar
Dries committed
713 714 715 716
    if ($terms['tags']) {
      foreach ($terms['tags'] as $vid => $vid_value) {
        $vocabulary = taxonomy_get_vocabulary($vid);
        if (!$vocabulary->tags) {
717 718
          // see form_get_error $key = implode('][', $element['#parents']);
          // on why this is the key
719
          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
720 721 722 723 724 725
        }
      }
    }
  }
}

Dries's avatar
 
Dries committed
726 727 728
/**
 * Save term associations for a given node.
 */
729 730
function taxonomy_node_save($nid, $terms) {
  taxonomy_node_delete($nid);
Dries's avatar
Dries committed
731 732 733

  // Free tagging vocabularies do not send their tids in the form,
  // so we'll detect them here and process them independently.
734 735 736
  if (isset($terms['tags'])) {
    $typed_input = $terms['tags'];
    unset($terms['tags']);
Dries's avatar
Dries committed
737 738 739 740 741 742

    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);
743
      $typed_terms = array_unique($matches[1]);
Dries's avatar
Dries committed
744

745
      $inserted = array();
Dries's avatar
Dries committed
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
      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
        // formatting so to save the term into the DB as the user intends.
        $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
        // and return the tid, otherwise, add a new record.
        $possibilities = taxonomy_get_term_by_name($typed_term);
        $typed_term_tid = NULL; // tid match if any.
        foreach ($possibilities as $possibility) {
          if ($possibility->vid == $vid) {
            $typed_term_tid = $possibility->tid;
          }
        }

        if (!$typed_term_tid) {
765 766 767
          $edit = array('vid' => $vid, 'name' => $typed_term);
          $status = taxonomy_save_term($edit);
          $typed_term_tid = $edit['tid'];
Dries's avatar
Dries committed
768 769
        }

770 771
        // Defend against duplicate, different cased tags
        if (!isset($inserted[$typed_term_tid])) {
772
          db_query('INSERT INTO {term_node} (nid, tid) VALUES (%d, %d)', $nid, $typed_term_tid);
773 774
          $inserted[$typed_term_tid] = TRUE;
        }