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

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

Dries's avatar
   
Dries committed
27
28
29
30
31
32
33
/**
 * 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:
 *
34
 * if (module_exists('taxonomy')) {
35
36
 *   $terms = taxonomy_link('taxonomy terms', $node);
 *   print theme('links', $terms);
Dries's avatar
   
Dries committed
37
38
 * }
 */
Dries's avatar
   
Dries committed
39
function taxonomy_link($type, $node = NULL) {
Dries's avatar
   
Dries committed
40
  if ($type == 'taxonomy terms' && $node != NULL) {
Kjartan's avatar
   
Kjartan committed
41
    $links = array();
42
    if (!empty($node->taxonomy)) {
43
      foreach ($node->taxonomy as $term) {
44
45
46
47
        // On preview, we get tids.
        if (is_numeric($term)) {
          $term = taxonomy_get_term($term);
        }
48
        $links['taxonomy_term_'. $term->tid] = array(
49
50
51
          'title' => $term->name,
          'href' => taxonomy_term_path($term),
          'attributes' => array('rel' => 'tag', 'title' => strip_tags($term->description))
52
        );
Dries's avatar
   
Dries committed
53
      }
Dries's avatar
   
Dries committed
54
    }
Kjartan's avatar
Kjartan committed
55

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

    return $links;
60
61
62
  }
}

63
64
65
66
67
68
69
70
71
72
/**
 * 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.
 */

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

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

  $items['admin/content/taxonomy/list'] = array(
93
    'title' => 'List',
94
95
96
97
98
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

  $items['admin/content/taxonomy/add/vocabulary'] = array(
99
    'title' => 'Add vocabulary',
100
101
102
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_form_vocabulary'),
    'type' => MENU_LOCAL_TASK,
103
    'parent' => 'admin/content/taxonomy',
104
105
  );

106
  $items['admin/content/taxonomy/edit/vocabulary/%taxonomy_vocabulary'] = array(
107
    'title' => 'Edit vocabulary',
108
109
110
111
112
113
    'page callback' => 'taxonomy_admin_vocabulary_edit',
    'page arguments' => array(5),
    'type' => MENU_CALLBACK,
  );

  $items['admin/content/taxonomy/edit/term'] = array(
114
    'title' => 'Edit term',
115
116
117
118
119
    'page callback' => 'taxonomy_admin_term_edit',
    'type' => MENU_CALLBACK,
  );

  $items['taxonomy/term'] = array(
120
    'title' => 'Taxonomy term',
121
122
123
124
125
126
    'page callback' => 'taxonomy_term_page',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  $items['taxonomy/autocomplete'] = array(
127
    'title' => 'Autocomplete taxonomy',
128
129
130
131
    'page callback' => 'taxonomy_autocomplete',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
132
  $items['admin/content/taxonomy/%taxonomy_vocabulary'] = array(
133
    'title' => 'List terms',
134
135
136
137
138
139
    'page callback' => 'taxonomy_overview_terms',
    'page arguments' => array(3),
    'access arguments' => array('administer taxonomy'),
    'type' => MENU_CALLBACK,
  );

140
  $items['admin/content/taxonomy/%taxonomy_vocabulary/list'] = array(
141
    'title' => 'List',
142
143
144
145
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

146
  $items['admin/content/taxonomy/%taxonomy_vocabulary/add/term'] = array(
147
    'title' => 'Add term',
148
149
150
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_form_term', 3),
    'type' => MENU_LOCAL_TASK,
151
    'parent' => 'admin/content/taxonomy/%taxonomy_vocabulary',
152
  );
Dries's avatar
   
Dries committed
153

Dries's avatar
   
Dries committed
154
155
  return $items;
}
Dries's avatar
   
Dries committed
156

157
158
159
160
/**
 * List and manage vocabularies.
 */
function taxonomy_overview_vocabularies() {
161
  $vocabularies = taxonomy_get_vocabularies();
162
  $rows = array();
163
164
165
  foreach ($vocabularies as $vocabulary) {
    $types = array();
    foreach ($vocabulary->nodes as $type) {
166
      $node_type = node_get_types('name', $type);
167
168
      $types[] = $node_type ? $node_type : $type;
    }
169
170
    $rows[] = array('name' => check_plain($vocabulary->name),
      'type' => implode(', ', $types),
171
172
173
      '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")
174
175
176
    );
  }
  if (empty($rows)) {
Steven Wittens's avatar
Steven Wittens committed
177
    $rows[] = array(array('data' => t('No categories available.'), 'colspan' => '5'));
178
  }
drumm's avatar
drumm committed
179
  $header = array(t('Name'), t('Type'), array('data' => t('Operations'), 'colspan' => '3'));
180

181
  return theme('table', $header, $rows, array('id' => 'taxonomy'));
182
183
184
185
186
187
}

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

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

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

209
  if (empty($rows)) {
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
    $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.
 */
226
function taxonomy_form_vocabulary(&$form_state, $edit = array()) {
227
228
229
230
231
232
233
234
235
236
237
238
  $edit += array(
    'name' => '',
    'description' => '',
    'help' => '',
    'nodes' => array(),
    'hierarchy' => 0,
    'relations' => 0,
    'tags' => 0,
    'multiple' => 0,
    'required' => 0,
    'weight' => 0,
  );
239
240
241
  $form['name'] = array('#type' => 'textfield',
    '#title' => t('Vocabulary name'),
    '#default_value' => $edit['name'],
242
    '#maxlength' => 255,
243
    '#description' => t('The name for this vocabulary. Example: "Topic".'),
244
245
246
247
248
249
250
251
252
    '#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'),
253
    '#maxlength' => 255,
254
255
256
257
    '#default_value' => $edit['help'],
    '#description' => t('Instructions to present to the user when choosing a term.'),
  );
  $form['nodes'] = array('#type' => 'checkboxes',
258
    '#title' => t('Content types'),
259
    '#default_value' => $edit['nodes'],
260
    '#options' => node_get_types('names'),
261
    '#description' => t('A list of content types you would like to categorize using this vocabulary.'),
262
263
264
265
266
  );
  $form['hierarchy'] = array('#type' => 'radios',
    '#title' => t('Hierarchy'),
    '#default_value' => $edit['hierarchy'],
    '#options' => array(t('Disabled'), t('Single'), t('Multiple')),
267
    '#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)))),
268
269
270
271
  );
  $form['relations'] = array('#type' => 'checkbox',
    '#title' => t('Related terms'),
    '#default_value' => $edit['relations'],
272
    '#description' => t('Allows <a href="@help-url">related terms</a> in this vocabulary.', array('@help-url' => url('admin/help/taxonomy', array('absolute' => TRUE)))),
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
  );
  $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.'),
  );
294

295
  $form['submit'] = array('#type' => 'submit', '#value' => t('Submit'));
296
  if (isset($edit['vid'])) {
297
    $form['delete'] = array('#type' => 'submit', '#value' => t('Delete'));
298
    $form['vid'] = array('#type' => 'value', '#value' => $edit['vid']);
299
    $form['module'] = array('#type' => 'value', '#value' => $edit['module']);
Dries's avatar
   
Dries committed
300
  }
301
  return $form;
Kjartan's avatar
Kjartan committed
302
}
Kjartan's avatar
Kjartan committed
303

304
305
306
/**
 * Accept the form submission for a vocabulary and save the results.
 */
307
function taxonomy_form_vocabulary_submit($form, &$form_state) {
308
  // Fix up the nodes array to remove unchecked nodes.
309
310
  $form_state['values']['nodes'] = array_filter($form_state['values']['nodes']);
  switch (taxonomy_save_vocabulary($form_state['values'])) {
311
    case SAVED_NEW:
312
313
      drupal_set_message(t('Created new vocabulary %name.', array('%name' => $form_state['values']['name'])));
      watchdog('taxonomy', 'Created new vocabulary %name.', array('%name' => $form_state['values']['name']), WATCHDOG_NOTICE, l(t('edit'), 'admin/content/taxonomy/edit/vocabulary/'. $form_state['values']['vid']));
314
315
      break;
    case SAVED_UPDATED:
316
317
      drupal_set_message(t('Updated vocabulary %name.', array('%name' => $form_state['values']['name'])));
      watchdog('taxonomy', 'Updated vocabulary %name.', array('%name' => $form_state['values']['name']), WATCHDOG_NOTICE, l(t('edit'), 'admin/content/taxonomy/edit/vocabulary/'. $form_state['values']['vid']));
318
      break;
319
  }
320

321
  $form_state['vid'] = $form_state['values']['vid'];
322
323
  $form_state['redirect'] = 'admin/content/taxonomy';
  return;
324
325
}

326
function taxonomy_save_vocabulary(&$edit) {
327
  $edit['nodes'] = empty($edit['nodes']) ? array() : $edit['nodes'];
Dries's avatar
   
Dries committed
328

329
  if (!empty($edit['vid']) && !empty($edit['name'])) {
330
    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
331
    db_query("DELETE FROM {vocabulary_node_types} WHERE vid = %d", $edit['vid']);
332
    foreach ($edit['nodes'] as $type => $selected) {
Dries's avatar
   
Dries committed
333
334
      db_query("INSERT INTO {vocabulary_node_types} (vid, type) VALUES (%d, '%s')", $edit['vid'], $type);
    }
Dries's avatar
   
Dries committed
335
    module_invoke_all('taxonomy', 'update', 'vocabulary', $edit);
336
    $status = SAVED_UPDATED;
Dries's avatar
   
Dries committed
337
  }
338
  else if (!empty($edit['vid'])) {
339
    $status = taxonomy_del_vocabulary($edit['vid']);
Kjartan's avatar
Kjartan committed
340
341
  }
  else {
342
343
    db_query("INSERT INTO {vocabulary} (name, description, help, multiple, required, hierarchy, relations, tags, weight, module) VALUES ('%s', '%s', '%s', %d, %d, %d, %d, %d, %d, '%s')", $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');
    $edit['vid'] = db_last_insert_id('vocabulary', 'vid');
344
    foreach ($edit['nodes'] as $type => $selected) {
Dries's avatar
   
Dries committed
345
346
      db_query("INSERT INTO {vocabulary_node_types} (vid, type) VALUES (%d, '%s')", $edit['vid'], $type);
    }
Dries's avatar
   
Dries committed
347
    module_invoke_all('taxonomy', 'insert', 'vocabulary', $edit);
348
    $status = SAVED_NEW;
Kjartan's avatar
Kjartan committed
349
  }
Dries's avatar
   
Dries committed
350
351

  cache_clear_all();
Dries's avatar
   
Dries committed
352

353
  return $status;
Kjartan's avatar
Kjartan committed
354
}
Dries's avatar
   
Dries committed
355

356
357
358
359
360
361
362
363
/**
 * Delete a vocabulary.
 *
 * @param $vid
 *   A vocabulary ID.
 * @return
 *   Constant indicating items were deleted.
 */
Kjartan's avatar
Kjartan committed
364
function taxonomy_del_vocabulary($vid) {
365
  $vocabulary = (array) taxonomy_vocabulary_load($vid);
Dries's avatar
   
Dries committed
366

Dries's avatar
   
Dries committed
367
  db_query('DELETE FROM {vocabulary} WHERE vid = %d', $vid);
Dries's avatar
   
Dries committed
368
  db_query('DELETE FROM {vocabulary_node_types} WHERE vid = %d', $vid);
Dries's avatar
   
Dries committed
369
  $result = db_query('SELECT tid FROM {term_data} WHERE vid = %d', $vid);
Kjartan's avatar
Kjartan committed
370
371
  while ($term = db_fetch_object($result)) {
    taxonomy_del_term($term->tid);
Dries's avatar
   
Dries committed
372
  }
Dries's avatar
   
Dries committed
373

Dries's avatar
   
Dries committed
374
  module_invoke_all('taxonomy', 'delete', 'vocabulary', $vocabulary);
Dries's avatar
   
Dries committed
375

Dries's avatar
   
Dries committed
376
377
  cache_clear_all();

378
  return SAVED_DELETED;
Dries's avatar
   
Dries committed
379
380
}

381
function taxonomy_vocabulary_confirm_delete(&$form_state, $vid) {
382
  $vocabulary = taxonomy_vocabulary_load($vid);
Dries's avatar
   
Dries committed
383

384
385
386
  $form['type'] = array('#type' => 'value', '#value' => 'vocabulary');
  $form['vid'] = array('#type' => 'value', '#value' => $vid);
  $form['name'] = array('#type' => 'value', '#value' => $vocabulary->name);
387
388
389

  $options = array('description' => t('Deleting a vocabulary will delete all the terms in it. This action cannot be undone.'));

390
  return confirm_form($form,
391
                  t('Are you sure you want to delete the vocabulary %title?',
392
                  array('%title' => $vocabulary->name)),
393
                  'admin/content/taxonomy',
394
                  $options);
Kjartan's avatar
Kjartan committed
395
}
Dries's avatar
   
Dries committed
396

397
398
399
400
function taxonomy_vocabulary_confirm_delete_submit($form, &$form_state) {
  $status = taxonomy_del_vocabulary($form_state['values']['vid']);
  drupal_set_message(t('Deleted vocabulary %name.', array('%name' => $form_state['values']['name'])));
  watchdog('taxonomy', 'Deleted vocabulary %name.', array('%name' => $form_state['values']['name']), WATCHDOG_NOTICE);
401
402
  $form_state['redirect'] = 'admin/content/taxonomy';
  return;
403
404
}

405
function taxonomy_form_term(&$form_state, $vocabulary, $edit = array()) {
406
407
408
409
410
411
  $edit += array(
    'name' => '',
    'description' => '',
    'tid' => NULL,
    'weight' => 0,
  );
412
413
414
415
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Term name'),
    '#default_value' => $edit['name'],
416
    '#maxlength' => 255,
417
418
    '#description' => t('The name of this term.'),
    '#required' => TRUE);
419

420
421
422
423
424
  $form['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Description'),
    '#default_value' => $edit['description'],
    '#description' => t('A description of the term.'));
Dries's avatar
   
Dries committed
425

Kjartan's avatar
Kjartan committed
426
  if ($vocabulary->hierarchy) {
Dries's avatar
   
Dries committed
427
    $parent = array_keys(taxonomy_get_parents($edit['tid']));
428
    $children = taxonomy_get_tree($vocabulary->vid, $edit['tid']);
Dries's avatar
   
Dries committed
429

Dries's avatar
   
Dries committed
430
    // A term can't be the child of itself, nor of its children.
Dries's avatar
   
Dries committed
431
432
433
    foreach ($children as $child) {
      $exclude[] = $child->tid;
    }
Dries's avatar
   
Dries committed
434
    $exclude[] = $edit['tid'];
Dries's avatar
   
Dries committed
435

Kjartan's avatar
Kjartan committed
436
    if ($vocabulary->hierarchy == 1) {
437
      $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
438
    }
Kjartan's avatar
Kjartan committed
439
    elseif ($vocabulary->hierarchy == 2) {
440
      $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
441
    }
Kjartan's avatar
Kjartan committed
442
  }
Dries's avatar
   
Dries committed
443

444
  if ($vocabulary->relations) {
445
    $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']));
446
447
  }

448
449
450
451
  $form['synonyms'] = array(
    '#type' => 'textarea',
    '#title' => t('Synonyms'),
    '#default_value' => implode("\n", taxonomy_get_synonyms($edit['tid'])),
452
    '#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)))));
453
454
455
456
457
458
459
460
461
462
463
  $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
464

Dries's avatar
   
Dries committed
465
  if ($edit['tid']) {
466
467
468
469
470
471
    $form['delete'] = array(
      '#type' => 'submit',
      '#value' => t('Delete'));
    $form['tid'] = array(
      '#type' => 'value',
      '#value' => $edit['tid']);
Dries's avatar
   
Dries committed
472
  }
473
  else {
474
    $form['destination'] = array('#type' => 'hidden', '#value' => $_GET['q']);
475
  }
Dries's avatar
   
Dries committed
476

477
  return $form;
Kjartan's avatar
Kjartan committed
478
}
Dries's avatar
   
Dries committed
479

480
481
482
/**
 * Accept the form submission for a taxonomy term and save the result.
 */
483
484
function taxonomy_form_term_submit($form, &$form_state) {
  switch (taxonomy_save_term($form_state['values'])) {
485
    case SAVED_NEW:
486
487
      drupal_set_message(t('Created new term %term.', array('%term' => $form_state['values']['name'])));
      watchdog('taxonomy', 'Created new term %term.', array('%term' => $form_state['values']['name']), WATCHDOG_NOTICE, l(t('edit'), 'admin/content/taxonomy/edit/term/'. $form_state['values']['tid']));
488
489
      break;
    case SAVED_UPDATED:
490
491
      drupal_set_message(t('Updated term %term.', array('%term' => $form_state['values']['name'])));
      watchdog('taxonomy', 'Updated term %term.', array('%term' => $form_state['values']['name']), WATCHDOG_NOTICE, l(t('edit'), 'admin/content/taxonomy/edit/term/'. $form_state['values']['tid']));
492
493
      break;
  }
494

495
  $form_state['tid'] = $form_state['values']['tid'];
496
497
  $form_state['redirect'] = 'admin/content/taxonomy';
  return;
498
499
}

500
501
502
/**
 * Helper function for taxonomy_form_term_submit().
 *
503
 * @param $form_state['values']
504
505
506
507
 * @return
 *   Status constant indicating if term was inserted or updated.
 */
function taxonomy_save_term(&$form_values) {
508
509
510
511
512
  $form_values += array(
    'description' => '',
    'weight' => 0
  );

513
  if (!empty($form_values['tid']) && $form_values['name']) {
514
    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']);
515
    $hook = 'update';
516
    $status = SAVED_UPDATED;
Kjartan's avatar
Kjartan committed
517
  }
518
  else if (!empty($form_values['tid'])) {
519
    return taxonomy_del_term($form_values['tid']);
Kjartan's avatar
Kjartan committed
520
521
  }
  else {
522
523
    db_query("INSERT INTO {term_data} (name, description, vid, weight) VALUES ('%s', '%s', %d, %d)", $form_values['name'], $form_values['description'], $form_values['vid'], $form_values['weight']);
    $form_values['tid'] = db_last_insert_id('term_data', 'tid');
524
    $hook = 'insert';
525
    $status = SAVED_NEW;
Kjartan's avatar
Kjartan committed
526
  }
Dries's avatar
   
Dries committed
527

528
  db_query('DELETE FROM {term_relation} WHERE tid1 = %d OR tid2 = %d', $form_values['tid'], $form_values['tid']);
529
  if (!empty($form_values['relations'])) {
530
    foreach ($form_values['relations'] as $related_id) {
Kjartan's avatar
Kjartan committed
531
      if ($related_id != 0) {
532
        db_query('INSERT INTO {term_relation} (tid1, tid2) VALUES (%d, %d)', $form_values['tid'], $related_id);
Dries's avatar
   
Dries committed
533
      }
Kjartan's avatar
Kjartan committed
534
    }
Kjartan's avatar
Kjartan committed
535
  }
Dries's avatar
   
Dries committed
536

537
538
539
  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
540
  }
541
542
  if (is_array($form_values['parent'])) {
    foreach ($form_values['parent'] as $parent) {
543
544
      if (is_array($parent)) {
        foreach ($parent as $tid) {
545
          db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $form_values['tid'], $tid);
546
547
548
        }
      }
      else {
549
        db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $form_values['tid'], $parent);
550
      }
Dries's avatar
   
Dries committed
551
    }
Kjartan's avatar
Kjartan committed
552
  }
553
  else {
554
    db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $form_values['tid'], $form_values['parent']);
555
  }
Dries's avatar
   
Dries committed
556

557
  db_query('DELETE FROM {term_synonym} WHERE tid = %d', $form_values['tid']);
558
  if (!empty($form_values['synonyms'])) {
559
    foreach (explode ("\n", str_replace("\r", '', $form_values['synonyms'])) as $synonym) {
Dries's avatar
   
Dries committed
560
      if ($synonym) {
561
        db_query("INSERT INTO {term_synonym} (tid, name) VALUES (%d, '%s')", $form_values['tid'], chop($synonym));
Dries's avatar
   
Dries committed
562
      }
Kjartan's avatar
Kjartan committed
563
    }
Dries's avatar
   
Dries committed
564
  }
Dries's avatar
   
Dries committed
565

566
  if (isset($hook)) {
567
    module_invoke_all('taxonomy', $hook, 'term', $form_values);
568
569
  }

Dries's avatar
   
Dries committed
570
571
  cache_clear_all();

572
  return $status;
Kjartan's avatar
Kjartan committed
573
}
Dries's avatar
   
Dries committed
574

575
576
577
578
579
580
581
582
/**
 * Delete a term.
 *
 * @param $tid
 *   The term ID.
 * @return
 *   Status constant indicating deletion.
 */
Kjartan's avatar
Kjartan committed
583
function taxonomy_del_term($tid) {
584
585
586
587
588
589
590
591
592
593
594
595
596
597
  $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
598

599
      $term = (array) taxonomy_get_term($tid);
Dries's avatar
   
Dries committed
600

601
602
603
604
605
      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
606

607
608
      module_invoke_all('taxonomy', 'delete', 'term', $term);
    }
Dries's avatar
   
Dries committed
609

610
611
    $tids = $orphans;
  }
Dries's avatar
   
Dries committed
612

Dries's avatar
   
Dries committed
613
  cache_clear_all();
614
615

  return SAVED_DELETED;
Dries's avatar
   
Dries committed
616
617
}

618
function taxonomy_term_confirm_delete(&$form_state, $tid) {
Dries's avatar
   
Dries committed
619
620
  $term = taxonomy_get_term($tid);

621
622
623
  $form['type'] = array('#type' => 'value', '#value' => 'term');
  $form['name'] = array('#type' => 'value', '#value' => $term->name);
  $form['tid'] = array('#type' => 'value', '#value' => $tid);
624
625
626

  $options = array('description' => t('Deleting a term will delete all its children if there are any. This action cannot be undone.'));

627
  return confirm_form($form,
628
                  t('Are you sure you want to delete the term %title?',
629
                  array('%title' => $term->name)),
630
                  'admin/content/taxonomy',
631
                  $options);
Kjartan's avatar
Kjartan committed
632
}
Dries's avatar
   
Dries committed
633

634
635
636
637
function taxonomy_term_confirm_delete_submit($form, &$form_state) {
  taxonomy_del_term($form_state['values']['tid']);
  drupal_set_message(t('Deleted term %name.', array('%name' => $form_state['values']['name'])));
  watchdog('taxonomy', 'Deleted term %name.', array('%name' => $form_state['values']['name']), WATCHDOG_NOTICE);
638
639
  $form_state['redirect'] = 'admin/content/taxonomy';
  return;
Kjartan's avatar
Kjartan committed
640
641
}

Dries's avatar
   
Dries committed
642
643
644
/**
 * Generate a form element for selecting terms from a vocabulary.
 */
645
function taxonomy_form($vid, $value = 0, $help = NULL, $name = 'taxonomy') {
646
  $vocabulary = taxonomy_vocabulary_load($vid);
647
  $help = ($help) ? $help : $vocabulary->help;
Kjartan's avatar
Kjartan committed
648
649
650
651
  if ($vocabulary->required) {
    $blank = 0;
  }
  else {
Dries's avatar
   
Dries committed
652
    $blank = '<'. t('none') .'>';
Kjartan's avatar
Kjartan committed
653
  }
Dries's avatar
   
Dries committed
654

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

658
/**
659
 * Generate a set of options for selecting a term from all vocabularies.
660
661
662
663
664
665
666
 */
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);
667
668
    if ($tree && (count($tree) > 1)) {
      $options[$vocabulary->name] = array();
669
      foreach ($tree as $term) {
670
        $options[$vocabulary->name][$term->tid] = str_repeat('-', $term->depth) . $term->name;
671
672
673
674
675
676
      }
    }
  }
  return $options;
}

Dries's avatar
   
Dries committed
677
678
679
680
681
682
/**
 * 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
683
function taxonomy_get_vocabularies($type = NULL) {
Kjartan's avatar
Kjartan committed
684
  if ($type) {
685
    $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
686
687
  }
  else {
688
    $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
689
  }
Dries's avatar
   
Dries committed
690

Kjartan's avatar
Kjartan committed
691
  $vocabularies = array();
Dries's avatar
   
Dries committed
692
  $node_types = array();
Kjartan's avatar
Kjartan committed
693
  while ($voc = db_fetch_object($result)) {
Dries's avatar
   
Dries committed
694
695
696
697
    $node_types[$voc->vid][] = $voc->type;
    unset($voc->type);
    $voc->nodes = $node_types[$voc->vid];
    $vocabularies[$voc->vid] = $voc;
Dries's avatar
   
Dries committed
698
  }
Dries's avatar
   
Dries committed
699

Kjartan's avatar
Kjartan committed
700
701
  return $vocabularies;
}
Dries's avatar
   
Dries committed
702

Dries's avatar
   
Dries committed
703
/**
704
 * Implementation of hook_form_alter().
Dries's avatar
   
Dries committed
705
706
 * Generate a form for selecting terms to associate with a node.
 */
707
function taxonomy_form_alter(&$form, $form_state, $form_id) {
708
  if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] .'_node_form' == $form_id) {
709
710
    $node = $form['#node'];

711
    if (!isset($node->taxonomy)) {
712
      $terms = empty($node->nid) ? array() : taxonomy_node_get_terms($node);
Kjartan's avatar
Kjartan committed
713
714
    }
    else {
715
      $terms = $node->taxonomy;
Dries's avatar
   
Dries committed
716
717
    }

718
    $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
719

720
721
    while ($vocabulary = db_fetch_object($c)) {
      if ($vocabulary->tags) {
722
        $typed_string = taxonomy_implode_tags($terms, $vocabulary->vid) . (array_key_exists('tags', $terms) ? $terms['tags'][$vocabulary->vid] : NULL);
723

724
725
726
727
        if ($vocabulary->help) {
          $help = $vocabulary->help;
        }
        else {
728
          $help = t('A comma-separated list of terms describing this content. Example: funny, bungee jumping, "Company, Inc.".');
729
        }
730
731
732
733
734
735
736
        $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,
737
          '#maxlength' => 255,
738
        );
739
740
      }
      else {
741
742
743
744
745
746
747
748
        // 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);
749
        $form['taxonomy'][$vocabulary->vid]['#weight'] = $vocabulary->weight;
750
        $form['taxonomy'][$vocabulary->vid]['#required'] = $vocabulary->required;
751
      }
Dries's avatar
Dries committed
752
    }
753
    if (!empty($form['taxonomy']) && is_array($form['taxonomy'])) {
754
755
756
757
758
759
760
761
      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,
        );
      }
762
763
      $form['taxonomy']['#weight'] = -3;
      $form['taxonomy']['#tree'] = TRUE;
Dries's avatar
Dries committed
764
    }
Dries's avatar
   
Dries committed
765
  }
Kjartan's avatar
Kjartan committed
766
}
Dries's avatar
   
Dries committed
767

Dries's avatar
   
Dries committed
768
/**
769
 * Find all terms associated with the given node, within one vocabulary.
Dries's avatar
   
Dries committed
770
 */
771
772
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
773
774
775
  $terms = array();
  while ($term = db_fetch_object($result)) {
    $terms[$term->$key] = $term;
Dries's avatar
   
Dries committed
776
  }
Kjartan's avatar
Kjartan committed
777
778
779
  return $terms;
}

Dries's avatar
   
Dries committed
780
/**
781
 * Find all terms associated with the given node, ordered by vocabulary and term weight.
Dries's avatar
   
Dries committed
782
 */
783
function taxonomy_node_get_terms($node, $key = 'tid') {
Kjartan's avatar
Kjartan committed
784
  static $terms;
Dries's avatar
   
Dries committed
785

786
  if (!isset($terms[$node->vid][$key])) {
787
    $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);
788
    $terms[$node->vid][$key] = array();
Dries's avatar
   
Dries committed
789
    while ($term = db_fetch_object($result)) {
790
      $terms[$node->vid][$key][$term->$key] = $term;
Dries's avatar
   
Dries committed
791
792
    }
  }
793
  return $terms[$node->vid][$key];
Kjartan's avatar
Kjartan committed
794
}
Dries's avatar
   
Dries committed
795

Dries's avatar
Dries committed
796
797
798
/**
 * Make sure incoming vids are free tagging enabled.
 */
799
function taxonomy_node_validate(&$node) {
800
  if (!empty($node->taxonomy)) {
801
    $terms = $node->taxonomy;
802
    if (!empty($terms['tags'])) {
Dries's avatar
Dries committed
803
      foreach ($terms['tags'] as $vid => $vid_value) {
804
        $vocabulary = taxonomy_vocabulary_load($vid);
805
        if (empty($vocabulary->tags)) {
806
807
          // see form_get_error $key = implode('][', $element['#parents']);
          // on why this is the key
808
          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
809
810
811
812
813
814
        }
      }
    }
  }
}

Dries's avatar
   
Dries committed
815
816
817
/**
 * Save term associations for a given node.
 */
818
819
820
function taxonomy_node_save($node, $terms) {

  taxonomy_node_delete_revision($node);
Dries's avatar
Dries committed
821
822
823

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

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

831
      $inserted = array();
Dries's avatar
Dries committed
832
833
      foreach ($typed_terms as $typed_term) {
        // See if the term exists in the chosen vocabulary
834
        // and return the tid; otherwise, add a new record.
Dries's avatar
Dries committed
835
        $possibilities = taxonomy_get_term_by_name($typed_term);
836
        $typed_term_tid = NULL; // tid match, if any.
Dries's avatar
Dries committed
837
838
839
840
841
842
843
        foreach ($possibilities as $possibility) {
          if ($possibility->vid == $vid) {
            $typed_term_tid = $possibility->tid;
          }
        }

        if (!$typed_term_tid) {
844
845
846
          $edit = array('vid' => $vid, 'name' => $typed_term);
          $status = taxonomy_save_term($edit);
          $typed_term_tid = $edit['tid'];
Dries's avatar
Dries committed
847
848
        }

849
        // Defend against duplicate, differently cased tags
850
        if (!isset($inserted[$typed_term_tid])) {
851
          db_query('INSERT INTO {term_node} (nid, vid, tid) VALUES (%d, %d, %d)', $node->nid, $node->vid, $typed_term_tid);
852
853
          $inserted[$typed_term_tid] = TRUE;
        }
Dries's avatar
Dries committed
854
855
856
      }
    }
  }
Dries's avatar
   
Dries committed
857

858
859
  if (is_array($terms)) {
    foreach ($terms as $term) {
860
861
862
      if (is_array($term)) {
        foreach ($term as $tid) {
          if ($tid) {
863
            db_query('INSERT INTO {term_node} (nid, vid, tid) VALUES (%d, %d, %d)', $node->nid, $node->vid, $tid);
864
865
866
          }
        }
      }
867
      else if (is_object($term)) {
868
        db_query('INSERT INTO {term_node} (nid, vid, tid) VALUES (%d, %d, %d)', $node->nid, $node->vid, $term->tid);
869
      }
870
      else if ($term) {
871
        db_query('INSERT INTO {term_node} (nid, vid, tid) VALUES (%d, %d, %d)', $node->nid, $node->vid, $term);
872
      }
Dries's avatar
   
Dries committed
873
874
    }
  }
Kjartan's avatar
Kjartan committed
875
}
Dries's avatar
   
Dries committed
876

Dries's avatar
   
Dries committed
877
878
879
/**
 * Remove associations of a node to its terms.
 */
880
function taxonomy_node_delete($node) {
881
  drupal_delete_add_query('DELETE FROM {term_node} WHERE nid = %d', $node->nid);
882
883
884
885
886
887
}

/**
 * Remove associations of a node to its terms.
 */
function taxonomy_node_delete_revision($node) {
888
  drupal_delete_add_query('DELETE FROM {term_node} WHERE vid = %d', $node->vid);