Projet

Général

Profil

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

root / drupal7 / modules / taxonomy / taxonomy.module @ 4444412d

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
 * Deletes a vocabulary.
461
 *
462
 * This will update all Taxonomy fields so that they don't reference the
463
 * deleted vocabulary. It also will delete fields that have no remaining
464
 * vocabulary references. All taxonomy terms of the deleted vocabulary
465
 * will be deleted as well.
466
 *
467
 * @param $vid
468
 *   A vocabulary ID.
469
 * @return
470
 *   Constant indicating items were deleted.
471
 */
472
function taxonomy_vocabulary_delete($vid) {
473
  $vocabulary = taxonomy_vocabulary_load($vid);
474

    
475
  $transaction = db_transaction();
476
  try {
477
    // Only load terms without a parent, child terms will get deleted too.
478
    $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();
479
    foreach ($result as $tid) {
480
      taxonomy_term_delete($tid);
481
    }
482
    db_delete('taxonomy_vocabulary')
483
      ->condition('vid', $vid)
484
      ->execute();
485

    
486
    field_attach_delete_bundle('taxonomy_term', $vocabulary->machine_name);
487
    module_invoke_all('taxonomy_vocabulary_delete', $vocabulary);
488
    module_invoke_all('entity_delete', $vocabulary, 'taxonomy_vocabulary');
489

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

    
514
    cache_clear_all();
515
    taxonomy_vocabulary_static_reset();
516

    
517
    return SAVED_DELETED;
518
  }
519
  catch (Exception $e) {
520
    $transaction->rollback();
521
    watchdog_exception('taxonomy', $e);
522
    throw $e;
523
  }
524
}
525

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

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

    
592
  return $hierarchy;
593
}
594

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

    
634
  // Load the stored entity, if any.
635
  if (!empty($term->tid) && !isset($term->original)) {
636
    $term->original = entity_load_unchanged('taxonomy_term', $term->tid);
637
  }
638

    
639
  field_attach_presave('taxonomy_term', $term);
640
  module_invoke_all('taxonomy_term_presave', $term);
641
  module_invoke_all('entity_presave', $term, 'taxonomy_term');
642

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

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

    
687
  // Reset the taxonomy term static variables.
688
  taxonomy_terms_static_reset();
689

    
690
  // Invoke the taxonomy hooks.
691
  module_invoke_all("taxonomy_term_$op", $term);
692
  module_invoke_all("entity_$op", $term, 'taxonomy_term');
693
  unset($term->original);
694

    
695
  return $status;
696
}
697

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

    
724
        if ($term = taxonomy_term_load($tid)) {
725
          db_delete('taxonomy_term_data')
726
            ->condition('tid', $tid)
727
            ->execute();
728
          db_delete('taxonomy_term_hierarchy')
729
            ->condition('tid', $tid)
730
            ->execute();
731

    
732
          field_attach_delete('taxonomy_term', $term);
733
          module_invoke_all('taxonomy_term_delete', $term);
734
          module_invoke_all('entity_delete', $term, 'taxonomy_term');
735
          taxonomy_terms_static_reset();
736
        }
737
      }
738

    
739
      $tids = $orphans;
740
    }
741
    return SAVED_DELETED;
742
  }
743
  catch (Exception $e) {
744
    $transaction->rollback();
745
    watchdog_exception('taxonomy', $e);
746
    throw $e;
747
  }
748
}
749

    
750
/**
751
 * Generates an array which displays a term detail page.
752
 *
753
 * @param term
754
 *   A taxonomy term object.
755
 * @return
756
 *   A $page element suitable for use by drupal_render().
757
 */
758
function taxonomy_term_show($term) {
759
  return taxonomy_term_view_multiple(array($term->tid => $term), 'full');
760
}
761

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

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

    
816
  // Remove previously built content, if exists.
817
  $term->content = array();
818

    
819
  // Allow modules to change the view mode.
820
  $context = array(
821
    'entity_type' => 'taxonomy_term',
822
    'entity' => $term,
823
    'langcode' => $langcode,
824
  );
825
  drupal_alter('entity_view_mode', $view_mode, $context);
826

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

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

    
849
  // Allow modules to make their own additions to the taxonomy term.
850
  module_invoke_all('taxonomy_term_view', $term, $view_mode, $langcode);
851
  module_invoke_all('entity_view', $term, 'taxonomy_term', $view_mode, $langcode);
852

    
853
  // Make sure the current view mode is stored if no module has already
854
  // populated the related key.
855
  $term->content += array('#view_mode' => $view_mode);
856
}
857

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

    
877
  // Populate $term->content with a render() array.
878
  taxonomy_term_build_content($term, $view_mode, $langcode);
879
  $build = $term->content;
880

    
881
  // We don't need duplicate rendering info in $term->content.
882
  unset($term->content);
883

    
884
  $build += array(
885
    '#theme' => 'taxonomy_term',
886
    '#term' => $term,
887
    '#view_mode' => $view_mode,
888
    '#language' => $langcode,
889
  );
890

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

    
893
  // Allow modules to modify the structured taxonomy term.
894
  $type = 'taxonomy_term';
895
  drupal_alter(array('taxonomy_term_view', 'entity_view'), $build, $type);
896

    
897
  return $build;
898
}
899

    
900
/**
901
 * Process variables for taxonomy-term.tpl.php.
902
 */
903
function template_preprocess_taxonomy_term(&$variables) {
904
  $variables['view_mode'] = $variables['elements']['#view_mode'];
905
  $variables['term'] = $variables['elements']['#term'];
906
  $term = $variables['term'];
907

    
908
  $uri = entity_uri('taxonomy_term', $term);
909
  $variables['term_url']  = url($uri['path'], $uri['options']);
910
  $variables['term_name'] = check_plain($term->name);
911
  $variables['page']      = $variables['view_mode'] == 'full' && taxonomy_term_is_page($term);
912

    
913
  // Flatten the term object's member fields.
914
  $variables = array_merge((array) $term, $variables);
915

    
916
  // Helpful $content variable for templates.
917
  $variables['content'] = array();
918
  foreach (element_children($variables['elements']) as $key) {
919
    $variables['content'][$key] = $variables['elements'][$key];
920
  }
921

    
922
  // field_attach_preprocess() overwrites the $[field_name] variables with the
923
  // values of the field in the language that was selected for display, instead
924
  // of the raw values in $term->[field_name], which contain all values in all
925
  // languages.
926
  field_attach_preprocess('taxonomy_term', $term, $variables['content'], $variables);
927

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

    
932
  $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->vocabulary_machine_name;
933
  $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->tid;
934
}
935

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

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

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

    
972
/**
973
 * Return an array of all vocabulary objects.
974
 *
975
 * @return
976
 *   An array of all vocabulary objects, indexed by vid.
977
 */
978
function taxonomy_get_vocabularies() {
979
  return taxonomy_vocabulary_load_multiple(FALSE, array());
980
}
981

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

    
995
  if (!isset($names)) {
996
    $names = db_query('SELECT name, machine_name, vid FROM {taxonomy_vocabulary}')->fetchAllAssoc('machine_name');
997
  }
998

    
999
  return $names;
1000
}
1001

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

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

    
1027
  return isset($parents[$tid]) ? $parents[$tid] : array();
1028
}
1029

    
1030
/**
1031
 * Find all ancestors of a given term ID.
1032
 */
1033
function taxonomy_get_parents_all($tid) {
1034
  $cache = &drupal_static(__FUNCTION__, array());
1035

    
1036
  if (isset($cache[$tid])) {
1037
    return $cache[$tid];
1038
  }
1039

    
1040
  $parents = array();
1041
  if ($term = taxonomy_term_load($tid)) {
1042
    $parents[] = $term;
1043
    $n = 0;
1044
    while ($parent = taxonomy_get_parents($parents[$n]->tid)) {
1045
      $parents = array_merge($parents, $parent);
1046
      $n++;
1047
    }
1048
  }
1049

    
1050
  $cache[$tid] = $parents;
1051

    
1052
  return $parents;
1053
}
1054

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

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

    
1085
  return isset($children[$tid]) ? $children[$tid] : array();
1086
}
1087

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

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

    
1122
    $query = db_select('taxonomy_term_data', 't');
1123
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
1124
    $result = $query
1125
      ->addTag('translatable')
1126
      ->addTag('term_access')
1127
      ->fields('t')
1128
      ->fields('h', array('parent'))
1129
      ->condition('t.vid', $vid)
1130
      ->orderBy('t.weight')
1131
      ->orderBy('t.name')
1132
      ->execute();
1133

    
1134
    foreach ($result as $term) {
1135
      $children[$vid][$term->parent][] = $term->tid;
1136
      $parents[$vid][$term->tid][] = $term->parent;
1137
      $terms[$vid][$term->tid] = $term;
1138
    }
1139
  }
1140

    
1141
  // Load full entities, if necessary. The entity controller statically
1142
  // caches the results.
1143
  if ($load_entities) {
1144
    $term_entities = taxonomy_term_load_multiple(array_keys($terms[$vid]));
1145
  }
1146

    
1147
  $max_depth = (!isset($max_depth)) ? count($children[$vid]) : $max_depth;
1148
  $tree = array();
1149

    
1150
  // Keeps track of the parents we have to process, the last entry is used
1151
  // for the next processing step.
1152
  $process_parents = array();
1153
  $process_parents[] = $parent;
1154

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

    
1181
          // We have to continue with this parent later.
1182
          $process_parents[] = $parent;
1183
          // Use the current term as parent for the next iteration.
1184
          $process_parents[] = $term->tid;
1185

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

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

    
1203
  return $tree;
1204
}
1205

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

    
1235
/**
1236
 * Controller class for taxonomy terms.
1237
 *
1238
 * This extends the DrupalDefaultEntityController class. Only alteration is
1239
 * that we match the condition on term name case-independently.
1240
 */
1241
class TaxonomyTermController extends DrupalDefaultEntityController {
1242

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

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

    
1277
/**
1278
 * Controller class for taxonomy vocabularies.
1279
 *
1280
 * This extends the DrupalDefaultEntityController class, adding required
1281
 * special handling for taxonomy vocabulary objects.
1282
 */
1283
class TaxonomyVocabularyController extends DrupalDefaultEntityController {
1284

    
1285
  protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
1286
    $query = parent::buildQuery($ids, $conditions, $revision_id);
1287
    $query->addTag('translatable');
1288
    $query->orderBy('base.weight');
1289
    $query->orderBy('base.name');
1290
    return $query;
1291
  }
1292
}
1293

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

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

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

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

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

    
1396
/**
1397
 * Helper function for array_map purposes.
1398
 */
1399
function _taxonomy_get_tid_from_term($term) {
1400
  return $term->tid;
1401
}
1402

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

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

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

    
1477
/**
1478
 * Implements hook_field_widget_info_alter().
1479
 */
1480
function taxonomy_field_widget_info_alter(&$info) {
1481
  $info['options_select']['field types'][] = 'taxonomy_term_reference';
1482
  $info['options_buttons']['field types'][] = 'taxonomy_term_reference';
1483
}
1484

    
1485
/**
1486
 * Implements hook_options_list().
1487
 */
1488
function taxonomy_options_list($field, $instance, $entity_type, $entity) {
1489
  $function = !empty($field['settings']['options_list_callback']) ? $field['settings']['options_list_callback'] : 'taxonomy_allowed_values';
1490
  return $function($field);
1491
}
1492

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

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

    
1552
/**
1553
 * Implements hook_field_is_empty().
1554
 */
1555
function taxonomy_field_is_empty($item, $field) {
1556
  if (!is_array($item) || (empty($item['tid']) && (string) $item['tid'] !== '0')) {
1557
    return TRUE;
1558
  }
1559
  return FALSE;
1560
}
1561

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

    
1582
/**
1583
 * Implements hook_field_formatter_view().
1584
 */
1585
function taxonomy_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
1586
  $element = array();
1587

    
1588
  // Terms whose tid is 'autocreate' do not exist
1589
  // yet and $item['taxonomy_term'] is not set. Theme such terms as
1590
  // just their name.
1591

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

    
1613
    case 'taxonomy_term_reference_plain':
1614
      foreach ($items as $delta => $item) {
1615
        $name = ($item['tid'] != 'autocreate' ? $item['taxonomy_term']->name : $item['name']);
1616
        $element[$delta] = array(
1617
          '#markup' => check_plain($name),
1618
        );
1619
      }
1620
      break;
1621

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

    
1635
  return $element;
1636
}
1637

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

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

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

    
1681
    // Iterate through the fieldable entities again to attach the loaded term data.
1682
    foreach ($entities as $id => $entity) {
1683
      $rekey = FALSE;
1684

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

    
1702
      if ($rekey) {
1703
        // Rekey the items array.
1704
        $items[$id] = array_values($items[$id]);
1705
      }
1706
    }
1707
  }
1708
}
1709

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

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

    
1732
  $element += array(
1733
    '#type' => 'textfield',
1734
    '#default_value' => taxonomy_implode_tags($tags),
1735
    '#autocomplete_path' => $instance['widget']['settings']['autocomplete_path'] . '/' . $field['field_name'],
1736
    '#size' => $instance['widget']['settings']['size'],
1737
    '#maxlength' => 1024,
1738
    '#element_validate' => array('taxonomy_autocomplete_validate'),
1739
  );
1740

    
1741
  return $element;
1742
}
1743

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

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

    
1782
  form_set_value($element, $value, $form_state);
1783
}
1784

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

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

    
1821
  return $form;
1822
}
1823

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

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

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

    
1903
/**
1904
 * Implements hook_node_insert().
1905
 */
1906
function taxonomy_node_insert($node) {
1907
  // Add taxonomy index entries for the node.
1908
  taxonomy_build_node_index($node);
1909
}
1910

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

    
1980
/**
1981
 * Implements hook_node_update().
1982
 */
1983
function taxonomy_node_update($node) {
1984
  // Always rebuild the node's taxonomy index entries on node save.
1985
  taxonomy_delete_node_index($node);
1986
  taxonomy_build_node_index($node);
1987
}
1988

    
1989
/**
1990
 * Implements hook_node_delete().
1991
 */
1992
function taxonomy_node_delete($node) {
1993
  // Clean up the {taxonomy_index} table when nodes are deleted.
1994
  taxonomy_delete_node_index($node);
1995
}
1996

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

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

    
2019
/**
2020
 * @} End of "defgroup taxonomy_index".
2021
 */
2022

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

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

    
2050
    $query->propertyCondition('vid', $vids, $conditions['bundle']['operator']);
2051
    unset($conditions['bundle']);
2052
  }
2053
}