Projet

Général

Profil

Paste
Télécharger (69,4 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / taxonomy / taxonomy.module @ f7a2490e

1
<?php
2

    
3
/**
4
 * @file
5
 * Enables the organization of content into categories.
6
 */
7

    
8
/**
9
 * Users can create new terms in a free-tagging vocabulary when
10
 * submitting a taxonomy_autocomplete_widget. We store a term object
11
 * whose tid is 'autocreate' as a field data item during widget
12
 * validation and then actually create the term if/when that field
13
 * data item makes it to taxonomy_field_insert/update().
14
 */
15

    
16
/**
17
 * Implements hook_help().
18
 */
19
function taxonomy_help($path, $arg) {
20
  switch ($path) {
21
    case 'admin/help#taxonomy':
22
      $output = '';
23
      $output .= '<h3>' . t('About') . '</h3>';
24
      $output .= '<p>' . t('The Taxonomy module allows you to classify the content of your website. To classify content, you define <em>vocabularies</em> that contain related <em>terms</em>, and then assign the vocabularies to content types. For more information, see the online handbook entry for the <a href="@taxonomy">Taxonomy module</a>.', array('@taxonomy' => 'http://drupal.org/documentation/modules/taxonomy/')) . '</p>';
25
      $output .= '<h3>' . t('Uses') . '</h3>';
26
      $output .= '<dl>';
27
      $output .= '<dt>' . t('Creating vocabularies') . '</dt>';
28
      $output .= '<dd>' . t('Users with sufficient <a href="@perm">permissions</a> can create <em>vocabularies</em> and <em>terms</em> through the <a href="@taxo">Taxonomy page</a>. The page listing the terms provides a drag-and-drop interface for controlling the order of the terms and sub-terms within a vocabulary, in a hierarchical fashion. A <em>controlled vocabulary</em> classifying music by genre with terms and sub-terms could look as follows:', array('@taxo' => url('admin/structure/taxonomy'), '@perm' => url('admin/people/permissions', array('fragment'=>'module-taxonomy'))));
29
      $output .= '<ul><li>' . t('<em>vocabulary</em>: Music') . '</li>';
30
      $output .= '<ul><li>' . t('<em>term</em>: Jazz') . '</li>';
31
      $output .= '<ul><li>' . t('<em>sub-term</em>: Swing') . '</li>';
32
      $output .= '<li>' . t('<em>sub-term</em>: Fusion') . '</li></ul></ul>';
33
      $output .= '<ul><li>' . t('<em>term</em>: Rock') . '</li>';
34
      $output .= '<ul><li>' . t('<em>sub-term</em>: Country rock') . '</li>';
35
      $output .= '<li>' . t('<em>sub-term</em>: Hard rock') . '</li></ul></ul></ul>';
36
      $output .= t('You can assign a sub-term to multiple parent terms. For example, <em>fusion</em> can be assigned to both <em>rock</em> and <em>jazz</em>.') . '</dd>';
37
      $output .= '<dd>' . t('Terms in a <em>free-tagging vocabulary</em> can be built gradually as you create or edit content. This is often done used for blogs or photo management applications.') . '</dd>';
38
      $output .= '<dt>' . t('Assigning vocabularies to content types') . '</dt>';
39
      $output .= '<dd>' . t('Before you can use a new vocabulary to classify your content, a new Taxonomy term field must be added to a <a href="@ctedit">content type</a> on its <em>manage fields</em> page. When adding a taxonomy field, you choose a <em>widget</em> to use to enter the taxonomy information on the content editing page: a select list, checkboxes, radio buttons, or an auto-complete field (to build a free-tagging vocabulary). After choosing the field type and widget, on the subsequent <em>field settings</em> page you can choose the desired vocabulary, whether one or multiple terms can be chosen from the vocabulary, and other settings. The same vocabulary can be added to multiple content types, by using the "Add existing field" section on the manage fields page.', array('@ctedit' => url('admin/structure/types'))) . '</dd>';
40
      $output .= '<dt>' . t('Classifying content') . '</dt>';
41
      $output .= '<dd>' . t('After the vocabulary is assigned to the content type, you can start classifying content. The field with terms will appear on the content editing screen when you edit or <a href="@addnode">add new content</a>.', array('@addnode' => url('node/add'))) . '</dd>';
42
      $output .= '<dt>' . t('Viewing listings and RSS feeds by term') . '</dt>';
43
      $output .= '<dd>' . t("Each taxonomy term automatically provides a page listing content that has its classification, and a corresponding RSS feed. For example, if the taxonomy term <em>country rock</em> has the ID 123 (you can see this by looking at the URL when hovering on the linked term, which you can click to navigate to the listing page), then you will find this list at the path <em>taxonomy/term/123</em>. The RSS feed will use the path <em>taxonomy/term/123/feed</em> (the RSS icon for this term's listing will automatically display in your browser's address bar when viewing the listing page).") . '</dd>';
44
      $output .= '<dt>' . t('Extending Taxonomy module') . '</dt>';
45
      $output .= '<dd>' . t('There are <a href="@taxcontrib">many contributed modules</a> that extend the behavior of the Taxonomy module for both display and organization of terms.', array('@taxcontrib' => 'http://drupal.org/project/modules?filters=tid:71&solrsort=sis_project_release_usage%20desc'));
46
      $output .= '</dl>';
47
      return $output;
48
    case 'admin/structure/taxonomy':
49
      $output = '<p>' . t('Taxonomy is for categorizing content. Terms are grouped into vocabularies. For example, a vocabulary called "Fruit" would contain the terms "Apple" and "Banana".') . '</p>';
50
      return $output;
51
    case 'admin/structure/taxonomy/%':
52
      $vocabulary = taxonomy_vocabulary_machine_name_load($arg[3]);
53
      switch ($vocabulary->hierarchy) {
54
        case 0:
55
          return '<p>' . t('You can reorganize the terms in %capital_name using their drag-and-drop handles, and group terms under a parent term by sliding them under and to the right of the parent.', array('%capital_name' => drupal_ucfirst($vocabulary->name), '%name' => $vocabulary->name)) . '</p>';
56
        case 1:
57
          return '<p>' . t('%capital_name contains terms grouped under parent terms. You can reorganize the terms in %capital_name using their drag-and-drop handles.', array('%capital_name' => drupal_ucfirst($vocabulary->name), '%name' => $vocabulary->name)) . '</p>';
58
        case 2:
59
          return '<p>' . t('%capital_name contains terms with multiple parents. Drag and drop of terms with multiple parents is not supported, but you can re-enable drag-and-drop support by editing each term to include only a single parent.', array('%capital_name' => drupal_ucfirst($vocabulary->name))) . '</p>';
60
      }
61
  }
62
}
63

    
64
/**
65
 * Implements hook_permission().
66
 */
67
function taxonomy_permission() {
68
  $permissions = array(
69
    'administer taxonomy' => array(
70
      'title' => t('Administer vocabularies and terms'),
71
    ),
72
  );
73
  foreach (taxonomy_get_vocabularies() as $vocabulary) {
74
    $permissions += array(
75
      'edit terms in ' . $vocabulary->vid => array(
76
        'title' => t('Edit terms in %vocabulary', array('%vocabulary' => $vocabulary->name)),
77
      ),
78
    );
79
    $permissions += array(
80
       'delete terms in ' . $vocabulary->vid => array(
81
         'title' => t('Delete terms from %vocabulary', array('%vocabulary' => $vocabulary->name)),
82
      ),
83
    );
84
  }
85
  return $permissions;
86
}
87

    
88
/**
89
 * Implements hook_entity_info().
90
 */
91
function taxonomy_entity_info() {
92
  $return = array(
93
    'taxonomy_term' => array(
94
      'label' => t('Taxonomy term'),
95
      'controller class' => 'TaxonomyTermController',
96
      'base table' => 'taxonomy_term_data',
97
      'uri callback' => 'taxonomy_term_uri',
98
      'fieldable' => TRUE,
99
      'entity keys' => array(
100
        'id' => 'tid',
101
        'bundle' => 'vocabulary_machine_name',
102
        'label' => 'name',
103
      ),
104
      'bundle keys' => array(
105
        'bundle' => 'machine_name',
106
      ),
107
      'bundles' => array(),
108
      'view modes' => array(
109
        // @todo View mode for display as a field (when attached to nodes etc).
110
        'full' => array(
111
          'label' => t('Taxonomy term page'),
112
          'custom settings' => FALSE,
113
        ),
114
      ),
115
    ),
116
  );
117
  foreach (taxonomy_vocabulary_get_names() as $machine_name => $vocabulary) {
118
    $return['taxonomy_term']['bundles'][$machine_name] = array(
119
      'label' => $vocabulary->name,
120
      'admin' => array(
121
        'path' => 'admin/structure/taxonomy/%taxonomy_vocabulary_machine_name',
122
        'real path' => 'admin/structure/taxonomy/' . $machine_name,
123
        'bundle argument' => 3,
124
        'access arguments' => array('administer taxonomy'),
125
      ),
126
    );
127
  }
128
  $return['taxonomy_vocabulary'] = array(
129
    'label' => t('Taxonomy vocabulary'),
130
    'controller class' => 'TaxonomyVocabularyController',
131
    'base table' => 'taxonomy_vocabulary',
132
    'entity keys' => array(
133
      'id' => 'vid',
134
      'label' => 'name',
135
    ),
136
    'fieldable' => FALSE,
137
  );
138

    
139
  return $return;
140
}
141

    
142
/**
143
 * Implements callback_entity_info_uri().
144
 */
145
function taxonomy_term_uri($term) {
146
  return array(
147
    'path' => 'taxonomy/term/' . $term->tid,
148
  );
149
}
150

    
151
/**
152
 * Implements hook_field_extra_fields().
153
 */
154
function taxonomy_field_extra_fields() {
155
  $return = array();
156
  $info = entity_get_info('taxonomy_term');
157
  foreach (array_keys($info['bundles']) as $bundle) {
158
    $return['taxonomy_term'][$bundle] = array(
159
      'form' => array(
160
        'name' => array(
161
          'label' => t('Name'),
162
          'description' => t('Term name textfield'),
163
          'weight' => -5,
164
        ),
165
        'description' => array(
166
          'label' => t('Description'),
167
          'description' => t('Term description textarea'),
168
          'weight' => 0,
169
        ),
170
      ),
171
      'display' => array(
172
        'description' => array(
173
          'label' => t('Description'),
174
          'description' => t('Term description'),
175
          'weight' => 0,
176
        ),
177
      ),
178
    );
179
  }
180

    
181
  return $return;
182
}
183

    
184
/**
185
 * Return nodes attached to a term across all field instances.
186
 *
187
 * This function requires taxonomy module to be maintaining its own tables,
188
 * and will return an empty array if it is not. If using other field storage
189
 * methods alternatives methods for listing terms will need to be used.
190
 *
191
 * @param $tid
192
 *   The term ID.
193
 * @param $pager
194
 *   Boolean to indicate whether a pager should be used.
195
 * @param $limit
196
 *   Integer. The maximum number of nodes to find.
197
 *   Set to FALSE for no limit.
198
 * @param $order
199
 *   An array of fields and directions.
200
 *
201
 * @return
202
 *   An array of nids matching the query.
203
 */
204
function taxonomy_select_nodes($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC')) {
205
  if (!variable_get('taxonomy_maintain_index_table', TRUE)) {
206
    return array();
207
  }
208
  $query = db_select('taxonomy_index', 't');
209
  $query->addTag('node_access');
210
  $query->condition('tid', $tid);
211
  if ($pager) {
212
    $count_query = clone $query;
213
    $count_query->addExpression('COUNT(t.nid)');
214

    
215
    $query = $query->extend('PagerDefault');
216
    if ($limit !== FALSE) {
217
      $query = $query->limit($limit);
218
    }
219
    $query->setCountQuery($count_query);
220
  }
221
  else {
222
    if ($limit !== FALSE) {
223
      $query->range(0, $limit);
224
    }
225
  }
226
  $query->addField('t', 'nid');
227
  $query->addField('t', 'tid');
228
  foreach ($order as $field => $direction) {
229
    $query->orderBy($field, $direction);
230
    // ORDER BY fields need to be loaded too, assume they are in the form
231
    // table_alias.name
232
    list($table_alias, $name) = explode('.', $field);
233
    $query->addField($table_alias, $name);
234
  }
235
  return $query->execute()->fetchCol();
236
}
237

    
238
/**
239
 * Implements hook_theme().
240
 */
241
function taxonomy_theme() {
242
  return array(
243
    'taxonomy_overview_vocabularies' => array(
244
      'render element' => 'form',
245
    ),
246
    'taxonomy_overview_terms' => array(
247
      'render element' => 'form',
248
    ),
249
    'taxonomy_term' => array(
250
      'render element' => 'elements',
251
      'template' => 'taxonomy-term',
252
    ),
253
  );
254
}
255

    
256
/**
257
 * Implements hook_menu().
258
 */
259
function taxonomy_menu() {
260
  $items['admin/structure/taxonomy'] = array(
261
    'title' => 'Taxonomy',
262
    'description' => 'Manage tagging, categorization, and classification of your content.',
263
    'page callback' => 'drupal_get_form',
264
    'page arguments' => array('taxonomy_overview_vocabularies'),
265
    'access arguments' => array('administer taxonomy'),
266
    'file' => 'taxonomy.admin.inc',
267
  );
268
  $items['admin/structure/taxonomy/list'] = array(
269
    'title' => 'List',
270
    'type' => MENU_DEFAULT_LOCAL_TASK,
271
    'weight' => -10,
272
  );
273
  $items['admin/structure/taxonomy/add'] = array(
274
    'title' => 'Add vocabulary',
275
    'page callback' => 'drupal_get_form',
276
    'page arguments' => array('taxonomy_form_vocabulary'),
277
    'access arguments' => array('administer taxonomy'),
278
    'type' => MENU_LOCAL_ACTION,
279
    'file' => 'taxonomy.admin.inc',
280
  );
281

    
282
  $items['taxonomy/term/%taxonomy_term'] = array(
283
    'title' => 'Taxonomy term',
284
    'title callback' => 'taxonomy_term_title',
285
    'title arguments' => array(2),
286
    'page callback' => 'taxonomy_term_page',
287
    'page arguments' => array(2),
288
    'access arguments' => array('access content'),
289
    'file' => 'taxonomy.pages.inc',
290
  );
291
  $items['taxonomy/term/%taxonomy_term/view'] = array(
292
    'title' => 'View',
293
    'type' => MENU_DEFAULT_LOCAL_TASK,
294
  );
295
  $items['taxonomy/term/%taxonomy_term/edit'] = array(
296
    'title' => 'Edit',
297
    'page callback' => 'drupal_get_form',
298
    // Pass a NULL argument to ensure that additional path components are not
299
    // passed to taxonomy_form_term() as the vocabulary machine name argument.
300
    'page arguments' => array('taxonomy_form_term', 2, NULL),
301
    'access callback' => 'taxonomy_term_edit_access',
302
    'access arguments' => array(2),
303
    'type' => MENU_LOCAL_TASK,
304
    'weight' => 10,
305
    'file' => 'taxonomy.admin.inc',
306
  );
307
  $items['taxonomy/term/%taxonomy_term/feed'] = array(
308
    'title' => 'Taxonomy term',
309
    'title callback' => 'taxonomy_term_title',
310
    'title arguments' => array(2),
311
    'page callback' => 'taxonomy_term_feed',
312
    'page arguments' => array(2),
313
    'access arguments' => array('access content'),
314
    'type' => MENU_CALLBACK,
315
    'file' => 'taxonomy.pages.inc',
316
  );
317
  $items['taxonomy/autocomplete'] = array(
318
    'title' => 'Autocomplete taxonomy',
319
    'page callback' => 'taxonomy_autocomplete',
320
    'access arguments' => array('access content'),
321
    'type' => MENU_CALLBACK,
322
    'file' => 'taxonomy.pages.inc',
323
  );
324

    
325
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name'] = array(
326
    'title callback' => 'entity_label',
327
    'title arguments' => array('taxonomy_vocabulary', 3),
328
    'page callback' => 'drupal_get_form',
329
    'page arguments' => array('taxonomy_overview_terms', 3),
330
    'access arguments' => array('administer taxonomy'),
331
    'file' => 'taxonomy.admin.inc',
332
  );
333
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/list'] = array(
334
    'title' => 'List',
335
    'type' => MENU_DEFAULT_LOCAL_TASK,
336
    'weight' => -20,
337
  );
338
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/edit'] = array(
339
    'title' => 'Edit',
340
    'page callback' => 'drupal_get_form',
341
    'page arguments' => array('taxonomy_form_vocabulary', 3),
342
    'access arguments' => array('administer taxonomy'),
343
    'type' => MENU_LOCAL_TASK,
344
    'weight' => -10,
345
    'file' => 'taxonomy.admin.inc',
346
  );
347

    
348
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/add'] = array(
349
    'title' => 'Add term',
350
    'page callback' => 'drupal_get_form',
351
    'page arguments' => array('taxonomy_form_term', array(), 3),
352
    'access arguments' => array('administer taxonomy'),
353
    'type' => MENU_LOCAL_ACTION,
354
    'file' => 'taxonomy.admin.inc',
355
  );
356

    
357
  return $items;
358
}
359

    
360
/**
361
 * Implements hook_admin_paths().
362
 */
363
function taxonomy_admin_paths() {
364
  $paths = array(
365
    'taxonomy/term/*/edit' => TRUE,
366
  );
367
  return $paths;
368
}
369

    
370
/**
371
 * Return edit access for a given term.
372
 */
373
function taxonomy_term_edit_access($term) {
374
  return user_access("edit terms in $term->vid") || user_access('administer taxonomy');
375
}
376

    
377
/**
378
 * Returns the sanitized name of a vocabulary.
379
 *
380
 * Deprecated. This function was previously used as a menu item title callback
381
 * but has been replaced by using entity_label() (which does not
382
 * sanitize the title, since the menu system does that automatically). In
383
 * Drupal 7, use that function for title callbacks, and call check_plain()
384
 * directly if you need a sanitized title.
385
 */
386
function taxonomy_admin_vocabulary_title_callback($vocabulary) {
387
  return check_plain($vocabulary->name);
388
}
389

    
390
/**
391
 * Saves a vocabulary.
392
 *
393
 * @param $vocabulary
394
 *   A vocabulary object with the following properties:
395
 *   - vid: (optional) The ID of the vocabulary (omit if creating a new
396
 *     vocabulary; only use to update an existing vocabulary).
397
 *   - name: The human-readable name of the vocabulary.
398
 *   - machine_name: The machine name of the vocabulary.
399
 *   - description: (optional) The vocabulary's description.
400
 *   - hierarchy: The hierarchy level of the vocabulary.
401
 *   - module: (optional) The module altering the vocabulary.
402
 *   - weight: (optional) The weight of this vocabulary in relation to other
403
 *     vocabularies.
404
 *   - original: (optional) The original vocabulary object before any changes
405
 *     are applied.
406
 *   - old_machine_name: (optional) The original machine name of the
407
 *     vocabulary.
408
 *
409
 * @return
410
 *   Status constant indicating whether the vocabulary was inserted (SAVED_NEW)
411
 *   or updated (SAVED_UPDATED).
412
 */
413
function taxonomy_vocabulary_save($vocabulary) {
414
  // Prevent leading and trailing spaces in vocabulary names.
415
  if (!empty($vocabulary->name)) {
416
    $vocabulary->name = trim($vocabulary->name);
417
  }
418
  // Load the stored entity, if any.
419
  if (!empty($vocabulary->vid)) {
420
    if (!isset($vocabulary->original)) {
421
      $vocabulary->original = entity_load_unchanged('taxonomy_vocabulary', $vocabulary->vid);
422
    }
423
    // Make sure machine name changes are easily detected.
424
    // @todo: Remove in Drupal 8, as it is deprecated by directly reading from
425
    // $vocabulary->original.
426
    $vocabulary->old_machine_name = $vocabulary->original->machine_name;
427
  }
428

    
429
  if (!isset($vocabulary->module)) {
430
    $vocabulary->module = 'taxonomy';
431
  }
432

    
433
  module_invoke_all('taxonomy_vocabulary_presave', $vocabulary);
434
  module_invoke_all('entity_presave', $vocabulary, 'taxonomy_vocabulary');
435

    
436
  if (!empty($vocabulary->vid) && !empty($vocabulary->name)) {
437
    $status = drupal_write_record('taxonomy_vocabulary', $vocabulary, 'vid');
438
    taxonomy_vocabulary_static_reset(array($vocabulary->vid));
439
    if ($vocabulary->old_machine_name != $vocabulary->machine_name) {
440
      field_attach_rename_bundle('taxonomy_term', $vocabulary->old_machine_name, $vocabulary->machine_name);
441
    }
442
    module_invoke_all('taxonomy_vocabulary_update', $vocabulary);
443
    module_invoke_all('entity_update', $vocabulary, 'taxonomy_vocabulary');
444
  }
445
  elseif (empty($vocabulary->vid)) {
446
    $status = drupal_write_record('taxonomy_vocabulary', $vocabulary);
447
    taxonomy_vocabulary_static_reset();
448
    field_attach_create_bundle('taxonomy_term', $vocabulary->machine_name);
449
    module_invoke_all('taxonomy_vocabulary_insert', $vocabulary);
450
    module_invoke_all('entity_insert', $vocabulary, 'taxonomy_vocabulary');
451
  }
452

    
453
  unset($vocabulary->original);
454
  cache_clear_all();
455

    
456
  return $status;
457
}
458

    
459
/**
460
 * Delete a vocabulary.
461
 *
462
 * @param $vid
463
 *   A vocabulary ID.
464
 * @return
465
 *   Constant indicating items were deleted.
466
 */
467
function taxonomy_vocabulary_delete($vid) {
468
  $vocabulary = taxonomy_vocabulary_load($vid);
469

    
470
  $transaction = db_transaction();
471
  try {
472
    // Only load terms without a parent, child terms will get deleted too.
473
    $result = db_query('SELECT t.tid FROM {taxonomy_term_data} t INNER JOIN {taxonomy_term_hierarchy} th ON th.tid = t.tid WHERE t.vid = :vid AND th.parent = 0', array(':vid' => $vid))->fetchCol();
474
    foreach ($result as $tid) {
475
      taxonomy_term_delete($tid);
476
    }
477
    db_delete('taxonomy_vocabulary')
478
      ->condition('vid', $vid)
479
      ->execute();
480

    
481
    field_attach_delete_bundle('taxonomy_term', $vocabulary->machine_name);
482
    module_invoke_all('taxonomy_vocabulary_delete', $vocabulary);
483
    module_invoke_all('entity_delete', $vocabulary, 'taxonomy_vocabulary');
484

    
485
    // Load all Taxonomy module fields and delete those which use only this
486
    // vocabulary.
487
    $taxonomy_fields = field_read_fields(array('module' => 'taxonomy'));
488
    foreach ($taxonomy_fields as $field_name => $taxonomy_field) {
489
      $modified_field = FALSE;
490
      // Term reference fields may reference terms from more than one
491
      // vocabulary.
492
      foreach ($taxonomy_field['settings']['allowed_values'] as $key => $allowed_value) {
493
        if ($allowed_value['vocabulary'] == $vocabulary->machine_name) {
494
          unset($taxonomy_field['settings']['allowed_values'][$key]);
495
          $modified_field = TRUE;
496
        }
497
      }
498
      if ($modified_field) {
499
        if (empty($taxonomy_field['settings']['allowed_values'])) {
500
          field_delete_field($field_name);
501
        }
502
        else {
503
          // Update the field definition with the new allowed values.
504
          field_update_field($taxonomy_field);
505
        }
506
      }
507
    }
508

    
509
    cache_clear_all();
510
    taxonomy_vocabulary_static_reset();
511

    
512
    return SAVED_DELETED;
513
  }
514
  catch (Exception $e) {
515
    $transaction->rollback();
516
    watchdog_exception('taxonomy', $e);
517
    throw $e;
518
  }
519
}
520

    
521
/**
522
 * Implements hook_taxonomy_vocabulary_update().
523
 */
524
function taxonomy_taxonomy_vocabulary_update($vocabulary) {
525
  // Reflect machine name changes in the definitions of existing 'taxonomy'
526
  // fields.
527
  if (!empty($vocabulary->old_machine_name) && $vocabulary->old_machine_name != $vocabulary->machine_name) {
528
    $fields = field_read_fields();
529
    foreach ($fields as $field_name => $field) {
530
      $update = FALSE;
531
      if ($field['type'] == 'taxonomy_term_reference') {
532
        foreach ($field['settings']['allowed_values'] as $key => &$value) {
533
          if ($value['vocabulary'] == $vocabulary->old_machine_name) {
534
            $value['vocabulary'] = $vocabulary->machine_name;
535
            $update = TRUE;
536
          }
537
        }
538
        if ($update) {
539
          field_update_field($field);
540
        }
541
      }
542
    }
543
  }
544
}
545

    
546
/**
547
 * Checks and updates the hierarchy flag of a vocabulary.
548
 *
549
 * Checks the current parents of all terms in a vocabulary and updates the
550
 * vocabulary's hierarchy setting to the lowest possible level. If no term
551
 * has parent terms then the vocabulary will be given a hierarchy of 0.
552
 * If any term has a single parent then the vocabulary will be given a
553
 * hierarchy of 1. If any term has multiple parents then the vocabulary
554
 * will be given a hierarchy of 2.
555
 *
556
 * @param $vocabulary
557
 *   A vocabulary object.
558
 * @param $changed_term
559
 *   An array of the term structure that was updated.
560
 *
561
 * @return
562
 *   An integer that represents the level of the vocabulary's hierarchy.
563
 */
564
function taxonomy_check_vocabulary_hierarchy($vocabulary, $changed_term) {
565
  $tree = taxonomy_get_tree($vocabulary->vid);
566
  $hierarchy = 0;
567
  foreach ($tree as $term) {
568
    // Update the changed term with the new parent value before comparison.
569
    if ($term->tid == $changed_term['tid']) {
570
      $term = (object) $changed_term;
571
      $term->parents = $term->parent;
572
    }
573
    // Check this term's parent count.
574
    if (count($term->parents) > 1) {
575
      $hierarchy = 2;
576
      break;
577
    }
578
    elseif (count($term->parents) == 1 && !isset($term->parents[0])) {
579
      $hierarchy = 1;
580
    }
581
  }
582
  if ($hierarchy != $vocabulary->hierarchy) {
583
    $vocabulary->hierarchy = $hierarchy;
584
    taxonomy_vocabulary_save($vocabulary);
585
  }
586

    
587
  return $hierarchy;
588
}
589

    
590
/**
591
 * Saves a term object to the database.
592
 *
593
 * @param $term
594
 *   The taxonomy term object with the following properties:
595
 *   - vid: The ID of the vocabulary the term is assigned to.
596
 *   - name: The name of the term.
597
 *   - tid: (optional) The unique ID for the term being saved. If $term->tid is
598
 *     empty or omitted, a new term will be inserted.
599
 *   - description: (optional) The term's description.
600
 *   - format: (optional) The text format for the term's description.
601
 *   - weight: (optional) The weight of this term in relation to other terms
602
 *     within the same vocabulary.
603
 *   - parent: (optional) The parent term(s) for this term. This can be a single
604
 *     term ID or an array of term IDs. A value of 0 means this term does not
605
 *     have any parents. When omitting this variable during an update, the
606
 *     existing hierarchy for the term remains unchanged.
607
 *   - vocabulary_machine_name: (optional) The machine name of the vocabulary
608
 *     the term is assigned to. If not given, this value will be set
609
 *     automatically by loading the vocabulary based on $term->vid.
610
 *   - original: (optional) The original taxonomy term object before any changes
611
 *     were applied. When omitted, the unchanged taxonomy term object is
612
 *     loaded from the database and stored in this property.
613
 *   Since a taxonomy term is an entity, any fields contained in the term object
614
 *   are saved alongside the term object.
615
 *
616
 * @return
617
 *   Status constant indicating whether term was inserted (SAVED_NEW) or updated
618
 *   (SAVED_UPDATED). When inserting a new term, $term->tid will contain the
619
 *   term ID of the newly created term.
620
 */
621
function taxonomy_term_save($term) {
622
  // Prevent leading and trailing spaces in term names.
623
  $term->name = trim($term->name);
624
  if (!isset($term->vocabulary_machine_name)) {
625
    $vocabulary = taxonomy_vocabulary_load($term->vid);
626
    $term->vocabulary_machine_name = $vocabulary->machine_name;
627
  }
628

    
629
  // Load the stored entity, if any.
630
  if (!empty($term->tid) && !isset($term->original)) {
631
    $term->original = entity_load_unchanged('taxonomy_term', $term->tid);
632
  }
633

    
634
  field_attach_presave('taxonomy_term', $term);
635
  module_invoke_all('taxonomy_term_presave', $term);
636
  module_invoke_all('entity_presave', $term, 'taxonomy_term');
637

    
638
  if (empty($term->tid)) {
639
    $op = 'insert';
640
    $status = drupal_write_record('taxonomy_term_data', $term);
641
    field_attach_insert('taxonomy_term', $term);
642
    if (!isset($term->parent)) {
643
      $term->parent = array(0);
644
    }
645
  }
646
  else {
647
    $op = 'update';
648
    $status = drupal_write_record('taxonomy_term_data', $term, 'tid');
649
    field_attach_update('taxonomy_term', $term);
650
    if (isset($term->parent)) {
651
      db_delete('taxonomy_term_hierarchy')
652
        ->condition('tid', $term->tid)
653
        ->execute();
654
    }
655
  }
656

    
657
  if (isset($term->parent)) {
658
    if (!is_array($term->parent)) {
659
      $term->parent = array($term->parent);
660
    }
661
    $query = db_insert('taxonomy_term_hierarchy')
662
      ->fields(array('tid', 'parent'));
663
    foreach ($term->parent as $parent) {
664
      if (is_array($parent)) {
665
        foreach ($parent as $tid) {
666
          $query->values(array(
667
            'tid' => $term->tid,
668
            'parent' => $tid
669
          ));
670
        }
671
      }
672
      else {
673
        $query->values(array(
674
          'tid' => $term->tid,
675
          'parent' => $parent
676
        ));
677
      }
678
    }
679
    $query->execute();
680
  }
681

    
682
  // Reset the taxonomy term static variables.
683
  taxonomy_terms_static_reset();
684

    
685
  // Invoke the taxonomy hooks.
686
  module_invoke_all("taxonomy_term_$op", $term);
687
  module_invoke_all("entity_$op", $term, 'taxonomy_term');
688
  unset($term->original);
689

    
690
  return $status;
691
}
692

    
693
/**
694
 * Delete a term.
695
 *
696
 * @param $tid
697
 *   The term ID.
698
 * @return
699
 *   Status constant indicating deletion.
700
 */
701
function taxonomy_term_delete($tid) {
702
  $transaction = db_transaction();
703
  try {
704
    $tids = array($tid);
705
    while ($tids) {
706
      $children_tids = $orphans = array();
707
      foreach ($tids as $tid) {
708
        // See if any of the term's children are about to be become orphans:
709
        if ($children = taxonomy_get_children($tid)) {
710
          foreach ($children as $child) {
711
            // If the term has multiple parents, we don't delete it.
712
            $parents = taxonomy_get_parents($child->tid);
713
            if (count($parents) == 1) {
714
              $orphans[] = $child->tid;
715
            }
716
          }
717
        }
718

    
719
        if ($term = taxonomy_term_load($tid)) {
720
          db_delete('taxonomy_term_data')
721
            ->condition('tid', $tid)
722
            ->execute();
723
          db_delete('taxonomy_term_hierarchy')
724
            ->condition('tid', $tid)
725
            ->execute();
726

    
727
          field_attach_delete('taxonomy_term', $term);
728
          module_invoke_all('taxonomy_term_delete', $term);
729
          module_invoke_all('entity_delete', $term, 'taxonomy_term');
730
          taxonomy_terms_static_reset();
731
        }
732
      }
733

    
734
      $tids = $orphans;
735
    }
736
    return SAVED_DELETED;
737
  }
738
  catch (Exception $e) {
739
    $transaction->rollback();
740
    watchdog_exception('taxonomy', $e);
741
    throw $e;
742
  }
743
}
744

    
745
/**
746
 * Generates an array which displays a term detail page.
747
 *
748
 * @param term
749
 *   A taxonomy term object.
750
 * @return
751
 *   A $page element suitable for use by drupal_page_render().
752
 */
753
function taxonomy_term_show($term) {
754
  return taxonomy_term_view_multiple(array($term->tid => $term), 'full');
755
}
756

    
757
/**
758
 * Constructs a drupal_render() style array from an array of loaded terms.
759
 *
760
 * @param $terms
761
 *   An array of taxonomy terms as returned by taxonomy_term_load_multiple().
762
 * @param $view_mode
763
 *   View mode, e.g. 'full', 'teaser'...
764
 * @param $weight
765
 *   An integer representing the weight of the first taxonomy term in the list.
766
 * @param $langcode
767
 *   (optional) A language code to use for rendering. Defaults to the global
768
 *   content language of the current request.
769
 *
770
 * @return
771
 *   An array in the format expected by drupal_render().
772
 */
773
function taxonomy_term_view_multiple($terms, $view_mode = 'teaser', $weight = 0, $langcode = NULL) {
774
  field_attach_prepare_view('taxonomy_term', $terms, $view_mode, $langcode);
775
  entity_prepare_view('taxonomy_term', $terms, $langcode);
776
  $build = array();
777
  foreach ($terms as $term) {
778
    $build['taxonomy_terms'][$term->tid] = taxonomy_term_view($term, $view_mode, $langcode);
779
    $build['taxonomy_terms'][$term->tid]['#weight'] = $weight;
780
    $weight++;
781
  }
782
  $build['taxonomy_terms']['#sorted'] = TRUE;
783
  return $build;
784
}
785

    
786
/**
787
 * Builds a structured array representing the term's content.
788
 *
789
 * The content built for the taxonomy term (field values, file attachments or
790
 * other term components) will vary depending on the $view_mode parameter.
791
 *
792
 * Drupal core defines the following view modes for terms, with the following
793
 * default use cases:
794
 *   - full (default): term is displayed on its own page (taxonomy/term/123)
795
 * Contributed modules might define additional view modes, or use existing
796
 * view modes in additional contexts.
797
 *
798
 * @param $term
799
 *   A taxonomy term object.
800
 * @param $view_mode
801
 *   View mode, e.g. 'full', 'teaser'...
802
 * @param $langcode
803
 *   (optional) A language code to use for rendering. Defaults to the global
804
 *   content language of the current request.
805
 */
806
function taxonomy_term_build_content($term, $view_mode = 'full', $langcode = NULL) {
807
  if (!isset($langcode)) {
808
    $langcode = $GLOBALS['language_content']->language;
809
  }
810

    
811
  // Remove previously built content, if exists.
812
  $term->content = array();
813

    
814
  // Allow modules to change the view mode.
815
  $context = array(
816
    'entity_type' => 'taxonomy_term',
817
    'entity' => $term,
818
    'langcode' => $langcode,
819
  );
820
  drupal_alter('entity_view_mode', $view_mode, $context);
821

    
822
  // Add the term description if the term has one and it is visible.
823
  $type = 'taxonomy_term';
824
  $entity_ids = entity_extract_ids($type, $term);
825
  $settings = field_view_mode_settings($type, $entity_ids[2]);
826
  $fields = field_extra_fields_get_display($type, $entity_ids[2], $view_mode);
827
  if (!empty($term->description) && isset($fields['description']) && $fields['description']['visible']) {
828
    $term->content['description'] = array(
829
      '#markup' => check_markup($term->description, $term->format, '', TRUE),
830
      '#weight' => $fields['description']['weight'],
831
      '#prefix' => '<div class="taxonomy-term-description">',
832
      '#suffix' => '</div>',
833
    );
834
  }
835

    
836
  // Build fields content.
837
  // In case of a multiple view, taxonomy_term_view_multiple() already ran the
838
  // 'prepare_view' step. An internal flag prevents the operation from running
839
  // twice.
840
  field_attach_prepare_view('taxonomy_term', array($term->tid => $term), $view_mode, $langcode);
841
  entity_prepare_view('taxonomy_term', array($term->tid => $term), $langcode);
842
  $term->content += field_attach_view('taxonomy_term', $term, $view_mode, $langcode);
843

    
844
  // Allow modules to make their own additions to the taxonomy term.
845
  module_invoke_all('taxonomy_term_view', $term, $view_mode, $langcode);
846
  module_invoke_all('entity_view', $term, 'taxonomy_term', $view_mode, $langcode);
847

    
848
  // Make sure the current view mode is stored if no module has already
849
  // populated the related key.
850
  $term->content += array('#view_mode' => $view_mode);
851
}
852

    
853
/**
854
 * Generate an array for rendering the given term.
855
 *
856
 * @param $term
857
 *   A term object.
858
 * @param $view_mode
859
 *   View mode, e.g. 'full', 'teaser'...
860
 * @param $langcode
861
 *   (optional) A language code to use for rendering. Defaults to the global
862
 *   content language of the current request.
863
 *
864
 * @return
865
 *   An array as expected by drupal_render().
866
 */
867
function taxonomy_term_view($term, $view_mode = 'full', $langcode = NULL) {
868
  if (!isset($langcode)) {
869
    $langcode = $GLOBALS['language_content']->language;
870
  }
871

    
872
  // Populate $term->content with a render() array.
873
  taxonomy_term_build_content($term, $view_mode, $langcode);
874
  $build = $term->content;
875

    
876
  // We don't need duplicate rendering info in $term->content.
877
  unset($term->content);
878

    
879
  $build += array(
880
    '#theme' => 'taxonomy_term',
881
    '#term' => $term,
882
    '#view_mode' => $view_mode,
883
    '#language' => $langcode,
884
  );
885

    
886
  $build['#attached']['css'][] = drupal_get_path('module', 'taxonomy') . '/taxonomy.css';
887

    
888
  // Allow modules to modify the structured taxonomy term.
889
  $type = 'taxonomy_term';
890
  drupal_alter(array('taxonomy_term_view', 'entity_view'), $build, $type);
891

    
892
  return $build;
893
}
894

    
895
/**
896
 * Process variables for taxonomy-term.tpl.php.
897
 */
898
function template_preprocess_taxonomy_term(&$variables) {
899
  $variables['view_mode'] = $variables['elements']['#view_mode'];
900
  $variables['term'] = $variables['elements']['#term'];
901
  $term = $variables['term'];
902

    
903
  $uri = entity_uri('taxonomy_term', $term);
904
  $variables['term_url']  = url($uri['path'], $uri['options']);
905
  $variables['term_name'] = check_plain($term->name);
906
  $variables['page']      = $variables['view_mode'] == 'full' && taxonomy_term_is_page($term);
907

    
908
  // Flatten the term object's member fields.
909
  $variables = array_merge((array) $term, $variables);
910

    
911
  // Helpful $content variable for templates.
912
  $variables['content'] = array();
913
  foreach (element_children($variables['elements']) as $key) {
914
    $variables['content'][$key] = $variables['elements'][$key];
915
  }
916

    
917
  // field_attach_preprocess() overwrites the $[field_name] variables with the
918
  // values of the field in the language that was selected for display, instead
919
  // of the raw values in $term->[field_name], which contain all values in all
920
  // languages.
921
  field_attach_preprocess('taxonomy_term', $term, $variables['content'], $variables);
922

    
923
  // Gather classes, and clean up name so there are no underscores.
924
  $vocabulary_name_css = str_replace('_', '-', $term->vocabulary_machine_name);
925
  $variables['classes_array'][] = 'vocabulary-' . $vocabulary_name_css;
926

    
927
  $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->vocabulary_machine_name;
928
  $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->tid;
929
}
930

    
931
/**
932
 * Returns whether the current page is the page of the passed-in term.
933
 *
934
 * @param $term
935
 *   A term object.
936
 */
937
function taxonomy_term_is_page($term) {
938
  $page_term = menu_get_object('taxonomy_term', 2);
939
  return (!empty($page_term) ? $page_term->tid == $term->tid : FALSE);
940
}
941

    
942
/**
943
 * Clear all static cache variables for terms.
944
 */
945
function taxonomy_terms_static_reset() {
946
  drupal_static_reset('taxonomy_term_count_nodes');
947
  drupal_static_reset('taxonomy_get_tree');
948
  drupal_static_reset('taxonomy_get_tree:parents');
949
  drupal_static_reset('taxonomy_get_tree:terms');
950
  drupal_static_reset('taxonomy_get_parents');
951
  drupal_static_reset('taxonomy_get_parents_all');
952
  drupal_static_reset('taxonomy_get_children');
953
  entity_get_controller('taxonomy_term')->resetCache();
954
}
955

    
956
/**
957
 * Clear all static cache variables for vocabularies.
958
 *
959
 * @param $ids
960
 * An array of ids to reset in entity controller cache.
961
 */
962
function taxonomy_vocabulary_static_reset($ids = NULL) {
963
  drupal_static_reset('taxonomy_vocabulary_get_names');
964
  entity_get_controller('taxonomy_vocabulary')->resetCache($ids);
965
}
966

    
967
/**
968
 * Return an array of all vocabulary objects.
969
 *
970
 * @return
971
 *   An array of all vocabulary objects, indexed by vid.
972
 */
973
function taxonomy_get_vocabularies() {
974
  return taxonomy_vocabulary_load_multiple(FALSE, array());
975
}
976

    
977
/**
978
 * Get names for all taxonomy vocabularies.
979
 *
980
 * @return
981
 *   An associative array of objects keyed by vocabulary machine name with
982
 *   information about taxonomy vocabularies. Each object has properties:
983
 *   - name: The vocabulary name.
984
 *   - machine_name: The machine name.
985
 *   - vid: The vocabulary ID.
986
 */
987
function taxonomy_vocabulary_get_names() {
988
  $names = &drupal_static(__FUNCTION__);
989

    
990
  if (!isset($names)) {
991
    $names = db_query('SELECT name, machine_name, vid FROM {taxonomy_vocabulary}')->fetchAllAssoc('machine_name');
992
  }
993

    
994
  return $names;
995
}
996

    
997
/**
998
 * Finds all parents of a given term ID.
999
 *
1000
 * @param $tid
1001
 *   A taxonomy term ID.
1002
 *
1003
 * @return
1004
 *   An array of term objects which are the parents of the term $tid, or an
1005
 *   empty array if parents are not found.
1006
 */
1007
function taxonomy_get_parents($tid) {
1008
  $parents = &drupal_static(__FUNCTION__, array());
1009

    
1010
  if ($tid && !isset($parents[$tid])) {
1011
    $query = db_select('taxonomy_term_data', 't');
1012
    $query->join('taxonomy_term_hierarchy', 'h', 'h.parent = t.tid');
1013
    $query->addField('t', 'tid');
1014
    $query->condition('h.tid', $tid);
1015
    $query->addTag('term_access');
1016
    $query->orderBy('t.weight');
1017
    $query->orderBy('t.name');
1018
    $tids = $query->execute()->fetchCol();
1019
    $parents[$tid] = taxonomy_term_load_multiple($tids);
1020
  }
1021

    
1022
  return isset($parents[$tid]) ? $parents[$tid] : array();
1023
}
1024

    
1025
/**
1026
 * Find all ancestors of a given term ID.
1027
 */
1028
function taxonomy_get_parents_all($tid) {
1029
  $cache = &drupal_static(__FUNCTION__, array());
1030

    
1031
  if (isset($cache[$tid])) {
1032
    return $cache[$tid];
1033
  }
1034

    
1035
  $parents = array();
1036
  if ($term = taxonomy_term_load($tid)) {
1037
    $parents[] = $term;
1038
    $n = 0;
1039
    while ($parent = taxonomy_get_parents($parents[$n]->tid)) {
1040
      $parents = array_merge($parents, $parent);
1041
      $n++;
1042
    }
1043
  }
1044

    
1045
  $cache[$tid] = $parents;
1046

    
1047
  return $parents;
1048
}
1049

    
1050
/**
1051
 * Finds all children of a term ID.
1052
 *
1053
 * @param $tid
1054
 *   A taxonomy term ID.
1055
 * @param $vid
1056
 *   An optional vocabulary ID to restrict the child search.
1057
 *
1058
 * @return
1059
 *   An array of term objects that are the children of the term $tid, or an
1060
 *   empty array when no children exist.
1061
 */
1062
function taxonomy_get_children($tid, $vid = 0) {
1063
  $children = &drupal_static(__FUNCTION__, array());
1064

    
1065
  if ($tid && !isset($children[$tid])) {
1066
    $query = db_select('taxonomy_term_data', 't');
1067
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
1068
    $query->addField('t', 'tid');
1069
    $query->condition('h.parent', $tid);
1070
    if ($vid) {
1071
      $query->condition('t.vid', $vid);
1072
    }
1073
    $query->addTag('term_access');
1074
    $query->orderBy('t.weight');
1075
    $query->orderBy('t.name');
1076
    $tids = $query->execute()->fetchCol();
1077
    $children[$tid] = taxonomy_term_load_multiple($tids);
1078
  }
1079

    
1080
  return isset($children[$tid]) ? $children[$tid] : array();
1081
}
1082

    
1083
/**
1084
 * Create a hierarchical representation of a vocabulary.
1085
 *
1086
 * @param $vid
1087
 *   Which vocabulary to generate the tree for.
1088
 * @param $parent
1089
 *   The term ID under which to generate the tree. If 0, generate the tree
1090
 *   for the entire vocabulary.
1091
 * @param $max_depth
1092
 *   The number of levels of the tree to return. Leave NULL to return all levels.
1093
 * @param $load_entities
1094
 *   If TRUE, a full entity load will occur on the term objects. Otherwise they
1095
 *   are partial objects queried directly from the {taxonomy_term_data} table to
1096
 *   save execution time and memory consumption when listing large numbers of
1097
 *   terms. Defaults to FALSE.
1098
 *
1099
 * @return
1100
 *   An array of all term objects in the tree. Each term object is extended
1101
 *   to have "depth" and "parents" attributes in addition to its normal ones.
1102
 *   Results are statically cached. Term objects will be partial or complete
1103
 *   depending on the $load_entities parameter.
1104
 */
1105
function taxonomy_get_tree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE) {
1106
  $children = &drupal_static(__FUNCTION__, array());
1107
  $parents = &drupal_static(__FUNCTION__ . ':parents', array());
1108
  $terms = &drupal_static(__FUNCTION__ . ':terms', array());
1109

    
1110
  // We cache trees, so it's not CPU-intensive to call taxonomy_get_tree() on a
1111
  // term and its children, too.
1112
  if (!isset($children[$vid])) {
1113
    $children[$vid] = array();
1114
    $parents[$vid] = array();
1115
    $terms[$vid] = array();
1116

    
1117
    $query = db_select('taxonomy_term_data', 't');
1118
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
1119
    $result = $query
1120
      ->addTag('translatable')
1121
      ->addTag('term_access')
1122
      ->fields('t')
1123
      ->fields('h', array('parent'))
1124
      ->condition('t.vid', $vid)
1125
      ->orderBy('t.weight')
1126
      ->orderBy('t.name')
1127
      ->execute();
1128

    
1129
    foreach ($result as $term) {
1130
      $children[$vid][$term->parent][] = $term->tid;
1131
      $parents[$vid][$term->tid][] = $term->parent;
1132
      $terms[$vid][$term->tid] = $term;
1133
    }
1134
  }
1135

    
1136
  // Load full entities, if necessary. The entity controller statically
1137
  // caches the results.
1138
  if ($load_entities) {
1139
    $term_entities = taxonomy_term_load_multiple(array_keys($terms[$vid]));
1140
  }
1141

    
1142
  $max_depth = (!isset($max_depth)) ? count($children[$vid]) : $max_depth;
1143
  $tree = array();
1144

    
1145
  // Keeps track of the parents we have to process, the last entry is used
1146
  // for the next processing step.
1147
  $process_parents = array();
1148
  $process_parents[] = $parent;
1149

    
1150
  // Loops over the parent terms and adds its children to the tree array.
1151
  // Uses a loop instead of a recursion, because it's more efficient.
1152
  while (count($process_parents)) {
1153
    $parent = array_pop($process_parents);
1154
    // The number of parents determines the current depth.
1155
    $depth = count($process_parents);
1156
    if ($max_depth > $depth && !empty($children[$vid][$parent])) {
1157
      $has_children = FALSE;
1158
      $child = current($children[$vid][$parent]);
1159
      do {
1160
        if (empty($child)) {
1161
          break;
1162
        }
1163
        $term = $load_entities ? $term_entities[$child] : $terms[$vid][$child];
1164
        if (isset($parents[$vid][$term->tid])) {
1165
          // Clone the term so that the depth attribute remains correct
1166
          // in the event of multiple parents.
1167
          $term = clone $term;
1168
        }
1169
        $term->depth = $depth;
1170
        unset($term->parent);
1171
        $term->parents = $parents[$vid][$term->tid];
1172
        $tree[] = $term;
1173
        if (!empty($children[$vid][$term->tid])) {
1174
          $has_children = TRUE;
1175

    
1176
          // We have to continue with this parent later.
1177
          $process_parents[] = $parent;
1178
          // Use the current term as parent for the next iteration.
1179
          $process_parents[] = $term->tid;
1180

    
1181
          // Reset pointers for child lists because we step in there more often
1182
          // with multi parents.
1183
          reset($children[$vid][$term->tid]);
1184
          // Move pointer so that we get the correct term the next time.
1185
          next($children[$vid][$parent]);
1186
          break;
1187
        }
1188
      } while ($child = next($children[$vid][$parent]));
1189

    
1190
      if (!$has_children) {
1191
        // We processed all terms in this hierarchy-level, reset pointer
1192
        // so that this function works the next time it gets called.
1193
        reset($children[$vid][$parent]);
1194
      }
1195
    }
1196
  }
1197

    
1198
  return $tree;
1199
}
1200

    
1201
/**
1202
 * Try to map a string to an existing term, as for glossary use.
1203
 *
1204
 * Provides a case-insensitive and trimmed mapping, to maximize the
1205
 * likelihood of a successful match.
1206
 *
1207
 * @param $name
1208
 *   Name of the term to search for.
1209
 * @param $vocabulary
1210
 *   (optional) Vocabulary machine name to limit the search. Defaults to NULL.
1211
 *
1212
 * @return
1213
 *   An array of matching term objects.
1214
 */
1215
function taxonomy_get_term_by_name($name, $vocabulary = NULL) {
1216
  $conditions = array('name' => trim($name));
1217
  if (isset($vocabulary)) {
1218
    $vocabularies = taxonomy_vocabulary_get_names();
1219
    if (isset($vocabularies[$vocabulary])) {
1220
      $conditions['vid'] = $vocabularies[$vocabulary]->vid;
1221
    }
1222
    else {
1223
      // Return an empty array when filtering by a non-existing vocabulary.
1224
      return array();
1225
    }
1226
  }
1227
  return taxonomy_term_load_multiple(array(), $conditions);
1228
}
1229

    
1230
/**
1231
 * Controller class for taxonomy terms.
1232
 *
1233
 * This extends the DrupalDefaultEntityController class. Only alteration is
1234
 * that we match the condition on term name case-independently.
1235
 */
1236
class TaxonomyTermController extends DrupalDefaultEntityController {
1237

    
1238
  protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
1239
    $query = parent::buildQuery($ids, $conditions, $revision_id);
1240
    $query->addTag('translatable');
1241
    $query->addTag('term_access');
1242
    // When name is passed as a condition use LIKE.
1243
    if (isset($conditions['name'])) {
1244
      $query_conditions = &$query->conditions();
1245
      foreach ($query_conditions as $key => $condition) {
1246
        if (is_array($condition) && $condition['field'] == 'base.name') {
1247
          $query_conditions[$key]['operator'] = 'LIKE';
1248
          $query_conditions[$key]['value'] = db_like($query_conditions[$key]['value']);
1249
        }
1250
      }
1251
    }
1252
    // Add the machine name field from the {taxonomy_vocabulary} table.
1253
    $query->innerJoin('taxonomy_vocabulary', 'v', 'base.vid = v.vid');
1254
    $query->addField('v', 'machine_name', 'vocabulary_machine_name');
1255
    return $query;
1256
  }
1257

    
1258
  protected function cacheGet($ids, $conditions = array()) {
1259
    $terms = parent::cacheGet($ids, $conditions);
1260
    // Name matching is case insensitive, note that with some collations
1261
    // LOWER() and drupal_strtolower() may return different results.
1262
    foreach ($terms as $term) {
1263
      $term_values = (array) $term;
1264
      if (isset($conditions['name']) && drupal_strtolower($conditions['name'] != drupal_strtolower($term_values['name']))) {
1265
        unset($terms[$term->tid]);
1266
      }
1267
    }
1268
    return $terms;
1269
  }
1270
}
1271

    
1272
/**
1273
 * Controller class for taxonomy vocabularies.
1274
 *
1275
 * This extends the DrupalDefaultEntityController class, adding required
1276
 * special handling for taxonomy vocabulary objects.
1277
 */
1278
class TaxonomyVocabularyController extends DrupalDefaultEntityController {
1279

    
1280
  protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
1281
    $query = parent::buildQuery($ids, $conditions, $revision_id);
1282
    $query->addTag('translatable');
1283
    $query->orderBy('base.weight');
1284
    $query->orderBy('base.name');
1285
    return $query;
1286
  }
1287
}
1288

    
1289
/**
1290
 * Load multiple taxonomy terms based on certain conditions.
1291
 *
1292
 * This function should be used whenever you need to load more than one term
1293
 * from the database. Terms are loaded into memory and will not require
1294
 * database access if loaded again during the same page request.
1295
 *
1296
 * @see entity_load()
1297
 * @see EntityFieldQuery
1298
 *
1299
 * @param $tids
1300
 *   An array of taxonomy term IDs.
1301
 * @param $conditions
1302
 *   (deprecated) An associative array of conditions on the {taxonomy_term}
1303
 *   table, where the keys are the database fields and the values are the
1304
 *   values those fields must have. Instead, it is preferable to use
1305
 *   EntityFieldQuery to retrieve a list of entity IDs loadable by
1306
 *   this function.
1307
 *
1308
 * @return
1309
 *   An array of term objects, indexed by tid. When no results are found, an
1310
 *   empty array is returned.
1311
 *
1312
 * @todo Remove $conditions in Drupal 8.
1313
 */
1314
function taxonomy_term_load_multiple($tids = array(), $conditions = array()) {
1315
  return entity_load('taxonomy_term', $tids, $conditions);
1316
}
1317

    
1318
/**
1319
 * Load multiple taxonomy vocabularies based on certain conditions.
1320
 *
1321
 * This function should be used whenever you need to load more than one
1322
 * vocabulary from the database. Terms are loaded into memory and will not
1323
 * require database access if loaded again during the same page request.
1324
 *
1325
 * @see entity_load()
1326
 *
1327
 * @param $vids
1328
 *  An array of taxonomy vocabulary IDs, or FALSE to load all vocabularies.
1329
 * @param $conditions
1330
 *  An array of conditions to add to the query.
1331
 *
1332
 * @return
1333
 *  An array of vocabulary objects, indexed by vid.
1334
 */
1335
function taxonomy_vocabulary_load_multiple($vids = array(), $conditions = array()) {
1336
  return entity_load('taxonomy_vocabulary', $vids, $conditions);
1337
}
1338

    
1339
/**
1340
 * Return the vocabulary object matching a vocabulary ID.
1341
 *
1342
 * @param $vid
1343
 *   The vocabulary's ID.
1344
 *
1345
 * @return
1346
 *   The vocabulary object with all of its metadata, if exists, FALSE otherwise.
1347
 *   Results are statically cached.
1348
 *
1349
 * @see taxonomy_vocabulary_machine_name_load()
1350
 */
1351
function taxonomy_vocabulary_load($vid) {
1352
  $vocabularies = taxonomy_vocabulary_load_multiple(array($vid));
1353
  return reset($vocabularies);
1354
}
1355

    
1356
/**
1357
 * Return the vocabulary object matching a vocabulary machine name.
1358
 *
1359
 * @param $name
1360
 *   The vocabulary's machine name.
1361
 *
1362
 * @return
1363
 *   The vocabulary object with all of its metadata, if exists, FALSE otherwise.
1364
 *   Results are statically cached.
1365
 *
1366
 * @see taxonomy_vocabulary_load()
1367
 */
1368
function taxonomy_vocabulary_machine_name_load($name) {
1369
  $vocabularies = taxonomy_vocabulary_load_multiple(NULL, array('machine_name' => $name));
1370
  return reset($vocabularies);
1371
}
1372

    
1373
/**
1374
 * Return the term object matching a term ID.
1375
 *
1376
 * @param $tid
1377
 *   A term's ID
1378
 *
1379
 * @return
1380
 *   A taxonomy term object, or FALSE if the term was not found. Results are
1381
 *   statically cached.
1382
 */
1383
function taxonomy_term_load($tid) {
1384
  if (!is_numeric($tid)) {
1385
    return FALSE;
1386
  }
1387
  $term = taxonomy_term_load_multiple(array($tid), array());
1388
  return $term ? $term[$tid] : FALSE;
1389
}
1390

    
1391
/**
1392
 * Helper function for array_map purposes.
1393
 */
1394
function _taxonomy_get_tid_from_term($term) {
1395
  return $term->tid;
1396
}
1397

    
1398
/**
1399
 * Implodes a list of tags of a certain vocabulary into a string.
1400
 *
1401
 * @see drupal_explode_tags()
1402
 */
1403
function taxonomy_implode_tags($tags, $vid = NULL) {
1404
  $typed_tags = array();
1405
  foreach ($tags as $tag) {
1406
    // Extract terms belonging to the vocabulary in question.
1407
    if (!isset($vid) || $tag->vid == $vid) {
1408
      // Make sure we have a completed loaded taxonomy term.
1409
      if (isset($tag->name)) {
1410
        // Commas and quotes in tag names are special cases, so encode 'em.
1411
        if (strpos($tag->name, ',') !== FALSE || strpos($tag->name, '"') !== FALSE) {
1412
          $typed_tags[] = '"' . str_replace('"', '""', $tag->name) . '"';
1413
        }
1414
        else {
1415
          $typed_tags[] = $tag->name;
1416
        }
1417
      }
1418
    }
1419
  }
1420
  return implode(', ', $typed_tags);
1421
}
1422

    
1423
/**
1424
 * Implements hook_field_info().
1425
 *
1426
 * Field settings:
1427
 * - allowed_values: a list array of one or more vocabulary trees:
1428
 *   - vocabulary: a vocabulary machine name.
1429
 *   - parent: a term ID of a term whose children are allowed. This should be
1430
 *     '0' if all terms in a vocabulary are allowed. The allowed values do not
1431
 *     include the parent term.
1432
 *
1433
 */
1434
function taxonomy_field_info() {
1435
  return array(
1436
    'taxonomy_term_reference' => array(
1437
      'label' => t('Term reference'),
1438
      'description' => t('This field stores a reference to a taxonomy term.'),
1439
      'default_widget' => 'options_select',
1440
      'default_formatter' => 'taxonomy_term_reference_link',
1441
      'settings' => array(
1442
        'allowed_values' => array(
1443
          array(
1444
            'vocabulary' => '',
1445
            'parent' => '0',
1446
          ),
1447
        ),
1448
      ),
1449
    ),
1450
  );
1451
}
1452

    
1453
/**
1454
 * Implements hook_field_widget_info().
1455
 */
1456
function taxonomy_field_widget_info() {
1457
  return array(
1458
    'taxonomy_autocomplete' => array(
1459
      'label' => t('Autocomplete term widget (tagging)'),
1460
      'field types' => array('taxonomy_term_reference'),
1461
      'settings' => array(
1462
        'size' => 60,
1463
        'autocomplete_path' => 'taxonomy/autocomplete',
1464
      ),
1465
      'behaviors' => array(
1466
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
1467
      ),
1468
    ),
1469
  );
1470
}
1471

    
1472
/**
1473
 * Implements hook_field_widget_info_alter().
1474
 */
1475
function taxonomy_field_widget_info_alter(&$info) {
1476
  $info['options_select']['field types'][] = 'taxonomy_term_reference';
1477
  $info['options_buttons']['field types'][] = 'taxonomy_term_reference';
1478
}
1479

    
1480
/**
1481
 * Implements hook_options_list().
1482
 */
1483
function taxonomy_options_list($field, $instance, $entity_type, $entity) {
1484
  $function = !empty($field['settings']['options_list_callback']) ? $field['settings']['options_list_callback'] : 'taxonomy_allowed_values';
1485
  return $function($field);
1486
}
1487

    
1488
/**
1489
 * Implements hook_field_validate().
1490
 *
1491
 * Taxonomy field settings allow for either a single vocabulary ID, multiple
1492
 * vocabulary IDs, or sub-trees of a vocabulary to be specified as allowed
1493
 * values, although only the first of these is supported via the field UI.
1494
 * Confirm that terms entered as values meet at least one of these conditions.
1495
 *
1496
 * Possible error codes:
1497
 * - 'taxonomy_term_illegal_value': The value is not part of the list of allowed values.
1498
 */
1499
function taxonomy_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
1500
  // Build an array of existing term IDs so they can be loaded with
1501
  // taxonomy_term_load_multiple();
1502
  foreach ($items as $delta => $item) {
1503
    if (!empty($item['tid']) && $item['tid'] != 'autocreate') {
1504
      $tids[] = $item['tid'];
1505
    }
1506
  }
1507
  if (!empty($tids)) {
1508
    $terms = taxonomy_term_load_multiple($tids);
1509

    
1510
    // Check each existing item to ensure it can be found in the
1511
    // allowed values for this field.
1512
    foreach ($items as $delta => $item) {
1513
      $validate = TRUE;
1514
      if (!empty($item['tid']) && $item['tid'] != 'autocreate') {
1515
        $validate = FALSE;
1516
        foreach ($field['settings']['allowed_values'] as $settings) {
1517
          // If no parent is specified, check if the term is in the vocabulary.
1518
          if (isset($settings['vocabulary']) && empty($settings['parent'])) {
1519
            if ($settings['vocabulary'] == $terms[$item['tid']]->vocabulary_machine_name) {
1520
              $validate = TRUE;
1521
              break;
1522
            }
1523
          }
1524
          // If a parent is specified, then to validate it must appear in the
1525
          // array returned by taxonomy_get_parents_all().
1526
          elseif (!empty($settings['parent'])) {
1527
            $ancestors = taxonomy_get_parents_all($item['tid']);
1528
            foreach ($ancestors as $ancestor) {
1529
              if ($ancestor->tid == $settings['parent']) {
1530
                $validate = TRUE;
1531
                break 2;
1532
              }
1533
            }
1534
          }
1535
        }
1536
      }
1537
      if (!$validate) {
1538
        $errors[$field['field_name']][$langcode][$delta][] = array(
1539
          'error' => 'taxonomy_term_reference_illegal_value',
1540
          'message' => t('%name: illegal value.', array('%name' => $instance['label'])),
1541
        );
1542
      }
1543
    }
1544
  }
1545
}
1546

    
1547
/**
1548
 * Implements hook_field_is_empty().
1549
 */
1550
function taxonomy_field_is_empty($item, $field) {
1551
  if (!is_array($item) || (empty($item['tid']) && (string) $item['tid'] !== '0')) {
1552
    return TRUE;
1553
  }
1554
  return FALSE;
1555
}
1556

    
1557
/**
1558
 * Implements hook_field_formatter_info().
1559
 */
1560
function taxonomy_field_formatter_info() {
1561
  return array(
1562
    'taxonomy_term_reference_link' => array(
1563
      'label' => t('Link'),
1564
      'field types' => array('taxonomy_term_reference'),
1565
    ),
1566
    'taxonomy_term_reference_plain' => array(
1567
      'label' => t('Plain text'),
1568
      'field types' => array('taxonomy_term_reference'),
1569
    ),
1570
    'taxonomy_term_reference_rss_category' => array(
1571
      'label' => t('RSS category'),
1572
      'field types' => array('taxonomy_term_reference'),
1573
    ),
1574
  );
1575
}
1576

    
1577
/**
1578
 * Implements hook_field_formatter_view().
1579
 */
1580
function taxonomy_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
1581
  $element = array();
1582

    
1583
  // Terms whose tid is 'autocreate' do not exist
1584
  // yet and $item['taxonomy_term'] is not set. Theme such terms as
1585
  // just their name.
1586

    
1587
  switch ($display['type']) {
1588
    case 'taxonomy_term_reference_link':
1589
      foreach ($items as $delta => $item) {
1590
        if ($item['tid'] == 'autocreate') {
1591
          $element[$delta] = array(
1592
            '#markup' => check_plain($item['name']),
1593
          );
1594
        }
1595
        else {
1596
          $term = $item['taxonomy_term'];
1597
          $uri = entity_uri('taxonomy_term', $term);
1598
          $element[$delta] = array(
1599
            '#type' => 'link',
1600
            '#title' => $term->name,
1601
            '#href' => $uri['path'],
1602
            '#options' => $uri['options'],
1603
          );
1604
        }
1605
      }
1606
      break;
1607

    
1608
    case 'taxonomy_term_reference_plain':
1609
      foreach ($items as $delta => $item) {
1610
        $name = ($item['tid'] != 'autocreate' ? $item['taxonomy_term']->name : $item['name']);
1611
        $element[$delta] = array(
1612
          '#markup' => check_plain($name),
1613
        );
1614
      }
1615
      break;
1616

    
1617
    case 'taxonomy_term_reference_rss_category':
1618
      foreach ($items as $delta => $item) {
1619
        $entity->rss_elements[] = array(
1620
          'key' => 'category',
1621
          'value' => $item['tid'] != 'autocreate' ? $item['taxonomy_term']->name : $item['name'],
1622
          'attributes' => array(
1623
            'domain' => $item['tid'] != 'autocreate' ? url('taxonomy/term/' . $item['tid'], array('absolute' => TRUE)) : '',
1624
          ),
1625
        );
1626
      }
1627
      break;
1628
  }
1629

    
1630
  return $element;
1631
}
1632

    
1633
/**
1634
 * Returns the set of valid terms for a taxonomy field.
1635
 *
1636
 * @param $field
1637
 *   The field definition.
1638
 * @return
1639
 *   The array of valid terms for this field, keyed by term id.
1640
 */
1641
function taxonomy_allowed_values($field) {
1642
  $options = array();
1643
  foreach ($field['settings']['allowed_values'] as $tree) {
1644
    if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
1645
      if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'])) {
1646
        foreach ($terms as $term) {
1647
          $options[$term->tid] = str_repeat('-', $term->depth) . $term->name;
1648
        }
1649
      }
1650
    }
1651
  }
1652
  return $options;
1653
}
1654

    
1655
/**
1656
 * Implements hook_field_formatter_prepare_view().
1657
 *
1658
 * This preloads all taxonomy terms for multiple loaded objects at once and
1659
 * unsets values for invalid terms that do not exist.
1660
 */
1661
function taxonomy_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays) {
1662
  $tids = array();
1663

    
1664
  // Collect every possible term attached to any of the fieldable entities.
1665
  foreach ($entities as $id => $entity) {
1666
    foreach ($items[$id] as $delta => $item) {
1667
      // Force the array key to prevent duplicates.
1668
      if ($item['tid'] != 'autocreate') {
1669
        $tids[$item['tid']] = $item['tid'];
1670
      }
1671
    }
1672
  }
1673
  if ($tids) {
1674
    $terms = taxonomy_term_load_multiple($tids);
1675

    
1676
    // Iterate through the fieldable entities again to attach the loaded term data.
1677
    foreach ($entities as $id => $entity) {
1678
      $rekey = FALSE;
1679

    
1680
      foreach ($items[$id] as $delta => $item) {
1681
        // Check whether the taxonomy term field instance value could be loaded.
1682
        if (isset($terms[$item['tid']])) {
1683
          // Replace the instance value with the term data.
1684
          $items[$id][$delta]['taxonomy_term'] = $terms[$item['tid']];
1685
        }
1686
        // Terms to be created are not in $terms, but are still legitimate.
1687
        elseif ($item['tid'] == 'autocreate') {
1688
          // Leave the item in place.
1689
        }
1690
        // Otherwise, unset the instance value, since the term does not exist.
1691
        else {
1692
          unset($items[$id][$delta]);
1693
          $rekey = TRUE;
1694
        }
1695
      }
1696

    
1697
      if ($rekey) {
1698
        // Rekey the items array.
1699
        $items[$id] = array_values($items[$id]);
1700
      }
1701
    }
1702
  }
1703
}
1704

    
1705
/**
1706
 * Title callback for term pages.
1707
 *
1708
 * @param $term
1709
 *   A term object.
1710
 *
1711
 * @return
1712
 *   The term name to be used as the page title.
1713
 */
1714
function taxonomy_term_title($term) {
1715
  return $term->name;
1716
}
1717

    
1718
/**
1719
 * Implements hook_field_widget_form().
1720
 */
1721
function taxonomy_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
1722
  $tags = array();
1723
  foreach ($items as $item) {
1724
    $tags[$item['tid']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
1725
  }
1726

    
1727
  $element += array(
1728
    '#type' => 'textfield',
1729
    '#default_value' => taxonomy_implode_tags($tags),
1730
    '#autocomplete_path' => $instance['widget']['settings']['autocomplete_path'] . '/' . $field['field_name'],
1731
    '#size' => $instance['widget']['settings']['size'],
1732
    '#maxlength' => 1024,
1733
    '#element_validate' => array('taxonomy_autocomplete_validate'),
1734
  );
1735

    
1736
  return $element;
1737
}
1738

    
1739
/**
1740
 * Form element validate handler for taxonomy term autocomplete element.
1741
 */
1742
function taxonomy_autocomplete_validate($element, &$form_state) {
1743
  // Autocomplete widgets do not send their tids in the form, so we must detect
1744
  // them here and process them independently.
1745
  $value = array();
1746
  if ($tags = $element['#value']) {
1747
    // Collect candidate vocabularies.
1748
    $field = field_widget_field($element, $form_state);
1749
    $vocabularies = array();
1750
    foreach ($field['settings']['allowed_values'] as $tree) {
1751
      if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
1752
        $vocabularies[$vocabulary->vid] = $vocabulary;
1753
      }
1754
    }
1755

    
1756
    // Translate term names into actual terms.
1757
    $typed_terms = drupal_explode_tags($tags);
1758
    foreach ($typed_terms as $typed_term) {
1759
      // See if the term exists in the chosen vocabulary and return the tid;
1760
      // otherwise, create a new 'autocreate' term for insert/update.
1761
      if ($possibilities = taxonomy_term_load_multiple(array(), array('name' => trim($typed_term), 'vid' => array_keys($vocabularies)))) {
1762
        $term = array_pop($possibilities);
1763
      }
1764
      else {
1765
        $vocabulary = reset($vocabularies);
1766
        $term = array(
1767
          'tid' => 'autocreate',
1768
          'vid' => $vocabulary->vid,
1769
          'name' => $typed_term,
1770
          'vocabulary_machine_name' => $vocabulary->machine_name,
1771
        );
1772
      }
1773
      $value[] = (array)$term;
1774
    }
1775
  }
1776

    
1777
  form_set_value($element, $value, $form_state);
1778
}
1779

    
1780
/**
1781
 * Implements hook_field_widget_error().
1782
 */
1783
function taxonomy_field_widget_error($element, $error, $form, &$form_state) {
1784
  form_error($element, $error['message']);
1785
}
1786
/**
1787
 * Implements hook_field_settings_form().
1788
 */
1789
function taxonomy_field_settings_form($field, $instance, $has_data) {
1790
  // Get proper values for 'allowed_values_function', which is a core setting.
1791
  $vocabularies = taxonomy_get_vocabularies();
1792
  $options = array();
1793
  foreach ($vocabularies as $vocabulary) {
1794
    $options[$vocabulary->machine_name] = $vocabulary->name;
1795
  }
1796
  $form['allowed_values'] = array(
1797
    '#tree' => TRUE,
1798
  );
1799

    
1800
  foreach ($field['settings']['allowed_values'] as $delta => $tree) {
1801
    $form['allowed_values'][$delta]['vocabulary'] = array(
1802
      '#type' => 'select',
1803
      '#title' => t('Vocabulary'),
1804
      '#default_value' => $tree['vocabulary'],
1805
      '#options' => $options,
1806
      '#required' => TRUE,
1807
      '#description' => t('The vocabulary which supplies the options for this field.'),
1808
      '#disabled' => $has_data,
1809
    );
1810
    $form['allowed_values'][$delta]['parent'] = array(
1811
      '#type' => 'value',
1812
      '#value' => $tree['parent'],
1813
    );
1814
  }
1815

    
1816
  return $form;
1817
}
1818

    
1819
/**
1820
 * Implements hook_rdf_mapping().
1821
 *
1822
 * @return array
1823
 *   The rdf mapping for vocabularies and terms.
1824
 */
1825
function taxonomy_rdf_mapping() {
1826
  return array(
1827
    array(
1828
      'type' => 'taxonomy_term',
1829
      'bundle' => RDF_DEFAULT_BUNDLE,
1830
      'mapping' => array(
1831
        'rdftype' => array('skos:Concept'),
1832
        'name'   => array(
1833
          'predicates' => array('rdfs:label', 'skos:prefLabel'),
1834
        ),
1835
        'description'   => array(
1836
          'predicates' => array('skos:definition'),
1837
        ),
1838
        'vid'   => array(
1839
          'predicates' => array('skos:inScheme'),
1840
          'type' => 'rel',
1841
        ),
1842
        'parent'   => array(
1843
          'predicates' => array('skos:broader'),
1844
          'type' => 'rel',
1845
        ),
1846
      ),
1847
    ),
1848
    array(
1849
      'type' => 'taxonomy_vocabulary',
1850
      'bundle' => RDF_DEFAULT_BUNDLE,
1851
      'mapping' => array(
1852
        'rdftype' => array('skos:ConceptScheme'),
1853
        'name'   => array(
1854
          'predicates' => array('dc:title'),
1855
        ),
1856
        'description'   => array(
1857
          'predicates' => array('rdfs:comment'),
1858
        ),
1859
      ),
1860
    ),
1861
  );
1862
}
1863

    
1864
/**
1865
 * @defgroup taxonomy_index Taxonomy indexing
1866
 * @{
1867
 * Functions to maintain taxonomy indexing.
1868
 *
1869
 * Taxonomy uses default field storage to store canonical relationships
1870
 * between terms and fieldable entities. However its most common use case
1871
 * requires listing all content associated with a term or group of terms
1872
 * sorted by creation date. To avoid slow queries due to joining across
1873
 * multiple node and field tables with various conditions and order by criteria,
1874
 * we maintain a denormalized table with all relationships between terms,
1875
 * published nodes and common sort criteria such as sticky and created.
1876
 * This is used as a lookup table by taxonomy_select_nodes(). When using other
1877
 * field storage engines or alternative methods of denormalizing this data
1878
 * you should set the variable 'taxonomy_maintain_index_table' to FALSE
1879
 * to avoid unnecessary writes in SQL.
1880
 */
1881

    
1882
/**
1883
 * Implements hook_field_presave().
1884
 *
1885
 * Create any new terms defined in a freetagging vocabulary.
1886
 */
1887
function taxonomy_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
1888
  foreach ($items as $delta => $item) {
1889
    if ($item['tid'] == 'autocreate') {
1890
      $term = (object) $item;
1891
      unset($term->tid);
1892
      taxonomy_term_save($term);
1893
      $items[$delta]['tid'] = $term->tid;
1894
    }
1895
  }
1896
}
1897

    
1898
/**
1899
 * Implements hook_node_insert().
1900
 */
1901
function taxonomy_node_insert($node) {
1902
  // Add taxonomy index entries for the node.
1903
  taxonomy_build_node_index($node);
1904
}
1905

    
1906
/**
1907
 * Builds and inserts taxonomy index entries for a given node.
1908
 *
1909
 * The index lists all terms that are related to a given node entity, and is
1910
 * therefore maintained at the entity level.
1911
 *
1912
 * @param $node
1913
 *   The node object.
1914
 */
1915
function taxonomy_build_node_index($node) {
1916
  // We maintain a denormalized table of term/node relationships, containing
1917
  // only data for current, published nodes.
1918
  $status = NULL;
1919
  if (variable_get('taxonomy_maintain_index_table', TRUE)) {
1920
    // If a node property is not set in the node object when node_save() is
1921
    // called, the old value from $node->original is used.
1922
    if (!empty($node->original)) {
1923
      $status = (int)(!empty($node->status) || (!isset($node->status) && !empty($node->original->status)));
1924
      $sticky = (int)(!empty($node->sticky) || (!isset($node->sticky) && !empty($node->original->sticky)));
1925
    }
1926
    else {
1927
      $status = (int)(!empty($node->status));
1928
      $sticky = (int)(!empty($node->sticky));
1929
    }
1930
  }
1931
  // We only maintain the taxonomy index for published nodes.
1932
  if ($status) {
1933
    // Collect a unique list of all the term IDs from all node fields.
1934
    $tid_all = array();
1935
    foreach (field_info_instances('node', $node->type) as $instance) {
1936
      $field_name = $instance['field_name'];
1937
      $field = field_info_field($field_name);
1938
      if ($field['module'] == 'taxonomy' && $field['storage']['type'] == 'field_sql_storage') {
1939
        // If a field value is not set in the node object when node_save() is
1940
        // called, the old value from $node->original is used.
1941
        if (isset($node->{$field_name})) {
1942
          $items = $node->{$field_name};
1943
        }
1944
        elseif (isset($node->original->{$field_name})) {
1945
          $items = $node->original->{$field_name};
1946
        }
1947
        else {
1948
          continue;
1949
        }
1950
        foreach (field_available_languages('node', $field) as $langcode) {
1951
          if (!empty($items[$langcode])) {
1952
            foreach ($items[$langcode] as $item) {
1953
              $tid_all[$item['tid']] = $item['tid'];
1954
            }
1955
          }
1956
        }
1957
      }
1958
    }
1959
    // Insert index entries for all the node's terms.
1960
    if (!empty($tid_all)) {
1961
      $query = db_insert('taxonomy_index')->fields(array('nid', 'tid', 'sticky', 'created'));
1962
      foreach ($tid_all as $tid) {
1963
        $query->values(array(
1964
          'nid' => $node->nid,
1965
          'tid' => $tid,
1966
          'sticky' => $sticky,
1967
          'created' => $node->created,
1968
        ));
1969
      }
1970
      $query->execute();
1971
    }
1972
  }
1973
}
1974

    
1975
/**
1976
 * Implements hook_node_update().
1977
 */
1978
function taxonomy_node_update($node) {
1979
  // Always rebuild the node's taxonomy index entries on node save.
1980
  taxonomy_delete_node_index($node);
1981
  taxonomy_build_node_index($node);
1982
}
1983

    
1984
/**
1985
 * Implements hook_node_delete().
1986
 */
1987
function taxonomy_node_delete($node) {
1988
  // Clean up the {taxonomy_index} table when nodes are deleted.
1989
  taxonomy_delete_node_index($node);
1990
}
1991

    
1992
/**
1993
 * Deletes taxonomy index entries for a given node.
1994
 *
1995
 * @param $node
1996
 *   The node object.
1997
 */
1998
function taxonomy_delete_node_index($node) {
1999
  if (variable_get('taxonomy_maintain_index_table', TRUE)) {
2000
    db_delete('taxonomy_index')->condition('nid', $node->nid)->execute();
2001
  }
2002
}
2003

    
2004
/**
2005
 * Implements hook_taxonomy_term_delete().
2006
 */
2007
function taxonomy_taxonomy_term_delete($term) {
2008
  if (variable_get('taxonomy_maintain_index_table', TRUE)) {
2009
    // Clean up the {taxonomy_index} table when terms are deleted.
2010
    db_delete('taxonomy_index')->condition('tid', $term->tid)->execute();
2011
  }
2012
}
2013

    
2014
/**
2015
 * @} End of "defgroup taxonomy_index".
2016
 */
2017

    
2018
/**
2019
 * Implements hook_entity_query_alter().
2020
 *
2021
 * Converts EntityFieldQuery instances on taxonomy terms that have an entity
2022
 * condition on term bundles (vocabulary machine names). Since the vocabulary
2023
 * machine name is not present in the {taxonomy_term_data} table itself, we have
2024
 * to convert the bundle condition into a property condition of vocabulary IDs
2025
 * to match against {taxonomy_term_data}.vid.
2026
 */
2027
function taxonomy_entity_query_alter($query) {
2028
  $conditions = &$query->entityConditions;
2029

    
2030
  // Alter only taxonomy term queries with bundle conditions.
2031
  if (isset($conditions['entity_type']) && $conditions['entity_type']['value'] == 'taxonomy_term' && isset($conditions['bundle'])) {
2032
    // Convert vocabulary machine names to vocabulary IDs.
2033
    $vocabulary_data = taxonomy_vocabulary_get_names();
2034
    $vids = array();
2035
    if (is_array($conditions['bundle']['value'])) {
2036
      foreach ($conditions['bundle']['value'] as $vocabulary_machine_name) {
2037
        $vids[] = $vocabulary_data[$vocabulary_machine_name]->vid;
2038
      }
2039
    }
2040
    else {
2041
      $vocabulary_machine_name = $conditions['bundle']['value'];
2042
      $vids = $vocabulary_data[$vocabulary_machine_name]->vid;
2043
    }
2044

    
2045
    $query->propertyCondition('vid', $vids, $conditions['bundle']['operator']);
2046
    unset($conditions['bundle']);
2047
  }
2048
}