Projet

Général

Profil

Paste
Télécharger (70,2 ko) Statistiques
| Branche: | Révision:

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

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
    // The page callback also invokes drupal_set_title() in case
287
    // the menu router's title is overridden by a menu link.
288
    'page callback' => 'taxonomy_term_page',
289
    'page arguments' => array(2),
290
    'access arguments' => array('access content'),
291
    'file' => 'taxonomy.pages.inc',
292
  );
293
  $items['taxonomy/term/%taxonomy_term/view'] = array(
294
    'title' => 'View',
295
    'type' => MENU_DEFAULT_LOCAL_TASK,
296
  );
297
  $items['taxonomy/term/%taxonomy_term/edit'] = array(
298
    'title' => 'Edit',
299
    'page callback' => 'drupal_get_form',
300
    // Pass a NULL argument to ensure that additional path components are not
301
    // passed to taxonomy_form_term() as the vocabulary machine name argument.
302
    'page arguments' => array('taxonomy_form_term', 2, NULL),
303
    'access callback' => 'taxonomy_term_edit_access',
304
    'access arguments' => array(2),
305
    'type' => MENU_LOCAL_TASK,
306
    'weight' => 10,
307
    'file' => 'taxonomy.admin.inc',
308
  );
309
  $items['taxonomy/term/%taxonomy_term/feed'] = array(
310
    'title' => 'Taxonomy term',
311
    'title callback' => 'taxonomy_term_title',
312
    'title arguments' => array(2),
313
    'page callback' => 'taxonomy_term_feed',
314
    'page arguments' => array(2),
315
    'access arguments' => array('access content'),
316
    'type' => MENU_CALLBACK,
317
    'file' => 'taxonomy.pages.inc',
318
  );
319
  $items['taxonomy/autocomplete'] = array(
320
    'title' => 'Autocomplete taxonomy',
321
    'page callback' => 'taxonomy_autocomplete',
322
    'access arguments' => array('access content'),
323
    'type' => MENU_CALLBACK,
324
    'file' => 'taxonomy.pages.inc',
325
  );
326

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

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

    
359
  return $items;
360
}
361

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

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

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

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

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

    
435
  module_invoke_all('taxonomy_vocabulary_presave', $vocabulary);
436
  module_invoke_all('entity_presave', $vocabulary, 'taxonomy_vocabulary');
437

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

    
455
  unset($vocabulary->original);
456
  cache_clear_all();
457

    
458
  return $status;
459
}
460

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

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

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

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

    
516
    cache_clear_all();
517
    taxonomy_vocabulary_static_reset();
518

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

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

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

    
594
  return $hierarchy;
595
}
596

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

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

    
641
  field_attach_presave('taxonomy_term', $term);
642
  module_invoke_all('taxonomy_term_presave', $term);
643
  module_invoke_all('entity_presave', $term, 'taxonomy_term');
644

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

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

    
689
  // Reset the taxonomy term static variables.
690
  taxonomy_terms_static_reset();
691

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

    
697
  return $status;
698
}
699

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

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

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

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

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

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

    
787
    foreach ($entities as $entity) {
788
      $build['taxonomy_terms'][$entity->tid] = taxonomy_term_view($entity, $entity_view_mode, $langcode);
789
    }
790
  }
791

    
792
  foreach ($terms as $term) {
793
    $build['taxonomy_terms'][$term->tid]['#weight'] = $weight;
794
    $weight++;
795
  }
796
  // Sort here, to preserve the input order of the entities that were passed to
797
  // this function.
798
  uasort($build['taxonomy_terms'], 'element_sort');
799
  $build['taxonomy_terms']['#sorted'] = TRUE;
800

    
801
  return $build;
802
}
803

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

    
829
  // Remove previously built content, if exists.
830
  $term->content = array();
831

    
832
  // Allow modules to change the view mode.
833
  $view_mode = key(entity_view_mode_prepare('taxonomy_term', array($term->tid => $term), $view_mode, $langcode));
834

    
835
  // Add the term description if the term has one and it is visible.
836
  $type = 'taxonomy_term';
837
  $entity_ids = entity_extract_ids($type, $term);
838
  $settings = field_view_mode_settings($type, $entity_ids[2]);
839
  $fields = field_extra_fields_get_display($type, $entity_ids[2], $view_mode);
840
  if (!empty($term->description) && isset($fields['description']) && $fields['description']['visible']) {
841
    $term->content['description'] = array(
842
      '#markup' => check_markup($term->description, $term->format, '', TRUE),
843
      '#weight' => $fields['description']['weight'],
844
      '#prefix' => '<div class="taxonomy-term-description">',
845
      '#suffix' => '</div>',
846
    );
847
  }
848

    
849
  // Build fields content.
850
  // In case of a multiple view, taxonomy_term_view_multiple() already ran the
851
  // 'prepare_view' step. An internal flag prevents the operation from running
852
  // twice.
853
  field_attach_prepare_view('taxonomy_term', array($term->tid => $term), $view_mode, $langcode);
854
  entity_prepare_view('taxonomy_term', array($term->tid => $term), $langcode);
855
  $term->content += field_attach_view('taxonomy_term', $term, $view_mode, $langcode);
856

    
857
  // Allow modules to make their own additions to the taxonomy term.
858
  module_invoke_all('taxonomy_term_view', $term, $view_mode, $langcode);
859
  module_invoke_all('entity_view', $term, 'taxonomy_term', $view_mode, $langcode);
860

    
861
  // Make sure the current view mode is stored if no module has already
862
  // populated the related key.
863
  $term->content += array('#view_mode' => $view_mode);
864
}
865

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

    
885
  // Populate $term->content with a render() array.
886
  taxonomy_term_build_content($term, $view_mode, $langcode);
887
  $build = $term->content;
888

    
889
  // We don't need duplicate rendering info in $term->content.
890
  unset($term->content);
891

    
892
  $build += array(
893
    '#theme' => 'taxonomy_term',
894
    '#term' => $term,
895
    '#view_mode' => $view_mode,
896
    '#language' => $langcode,
897
  );
898

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

    
901
  // Allow modules to modify the structured taxonomy term.
902
  $type = 'taxonomy_term';
903
  drupal_alter(array('taxonomy_term_view', 'entity_view'), $build, $type);
904

    
905
  return $build;
906
}
907

    
908
/**
909
 * Process variables for taxonomy-term.tpl.php.
910
 */
911
function template_preprocess_taxonomy_term(&$variables) {
912
  $variables['view_mode'] = $variables['elements']['#view_mode'];
913
  $variables['term'] = $variables['elements']['#term'];
914
  $term = $variables['term'];
915

    
916
  $uri = entity_uri('taxonomy_term', $term);
917
  $variables['term_url']  = url($uri['path'], $uri['options']);
918
  $variables['term_name'] = check_plain($term->name);
919
  $variables['page']      = $variables['view_mode'] == 'full' && taxonomy_term_is_page($term);
920

    
921
  // Flatten the term object's member fields.
922
  $variables = array_merge((array) $term, $variables);
923

    
924
  // Helpful $content variable for templates.
925
  $variables['content'] = array();
926
  foreach (element_children($variables['elements']) as $key) {
927
    $variables['content'][$key] = $variables['elements'][$key];
928
  }
929

    
930
  // field_attach_preprocess() overwrites the $[field_name] variables with the
931
  // values of the field in the language that was selected for display, instead
932
  // of the raw values in $term->[field_name], which contain all values in all
933
  // languages.
934
  field_attach_preprocess('taxonomy_term', $term, $variables['content'], $variables);
935

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

    
940
  $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->vocabulary_machine_name;
941
  $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->tid;
942
}
943

    
944
/**
945
 * Returns whether the current page is the page of the passed-in term.
946
 *
947
 * @param $term
948
 *   A term object.
949
 */
950
function taxonomy_term_is_page($term) {
951
  $page_term = menu_get_object('taxonomy_term', 2);
952
  return (!empty($page_term) ? $page_term->tid == $term->tid : FALSE);
953
}
954

    
955
/**
956
 * Clear all static cache variables for terms.
957
 */
958
function taxonomy_terms_static_reset() {
959
  drupal_static_reset('taxonomy_term_count_nodes');
960
  drupal_static_reset('taxonomy_get_tree');
961
  drupal_static_reset('taxonomy_get_tree:parents');
962
  drupal_static_reset('taxonomy_get_tree:terms');
963
  drupal_static_reset('taxonomy_get_parents');
964
  drupal_static_reset('taxonomy_get_parents_all');
965
  drupal_static_reset('taxonomy_get_children');
966
  entity_get_controller('taxonomy_term')->resetCache();
967
}
968

    
969
/**
970
 * Clear all static cache variables for vocabularies.
971
 *
972
 * @param $ids
973
 * An array of ids to reset in entity controller cache.
974
 */
975
function taxonomy_vocabulary_static_reset($ids = NULL) {
976
  drupal_static_reset('taxonomy_vocabulary_get_names');
977
  entity_get_controller('taxonomy_vocabulary')->resetCache($ids);
978
}
979

    
980
/**
981
 * Return an array of all vocabulary objects.
982
 *
983
 * @return
984
 *   An array of all vocabulary objects, indexed by vid.
985
 */
986
function taxonomy_get_vocabularies() {
987
  return taxonomy_vocabulary_load_multiple(FALSE, array());
988
}
989

    
990
/**
991
 * Get names for all taxonomy vocabularies.
992
 *
993
 * @return
994
 *   An associative array of objects keyed by vocabulary machine name with
995
 *   information about taxonomy vocabularies. Each object has properties:
996
 *   - name: The vocabulary name.
997
 *   - machine_name: The machine name.
998
 *   - vid: The vocabulary ID.
999
 */
1000
function taxonomy_vocabulary_get_names() {
1001
  $names = &drupal_static(__FUNCTION__);
1002

    
1003
  if (!isset($names)) {
1004
    $names = db_query('SELECT name, machine_name, vid FROM {taxonomy_vocabulary}')->fetchAllAssoc('machine_name');
1005
  }
1006

    
1007
  return $names;
1008
}
1009

    
1010
/**
1011
 * Finds all parents of a given term ID.
1012
 *
1013
 * @param $tid
1014
 *   A taxonomy term ID.
1015
 *
1016
 * @return
1017
 *   An array of term objects which are the parents of the term $tid, or an
1018
 *   empty array if parents are not found.
1019
 */
1020
function taxonomy_get_parents($tid) {
1021
  $parents = &drupal_static(__FUNCTION__, array());
1022

    
1023
  if ($tid && !isset($parents[$tid])) {
1024
    $query = db_select('taxonomy_term_data', 't');
1025
    $query->join('taxonomy_term_hierarchy', 'h', 'h.parent = t.tid');
1026
    $query->addField('t', 'tid');
1027
    $query->condition('h.tid', $tid);
1028
    $query->addTag('taxonomy_term_access');
1029
    $query->orderBy('t.weight');
1030
    $query->orderBy('t.name');
1031
    $tids = $query->execute()->fetchCol();
1032
    $parents[$tid] = taxonomy_term_load_multiple($tids);
1033
  }
1034

    
1035
  return isset($parents[$tid]) ? $parents[$tid] : array();
1036
}
1037

    
1038
/**
1039
 * Find all ancestors of a given term ID.
1040
 */
1041
function taxonomy_get_parents_all($tid) {
1042
  $cache = &drupal_static(__FUNCTION__, array());
1043

    
1044
  if (isset($cache[$tid])) {
1045
    return $cache[$tid];
1046
  }
1047

    
1048
  $parents = array();
1049
  if ($term = taxonomy_term_load($tid)) {
1050
    $parents[] = $term;
1051
    $n = 0;
1052
    while ($parent = taxonomy_get_parents($parents[$n]->tid)) {
1053
      $parents = array_merge($parents, $parent);
1054
      $n++;
1055
    }
1056
  }
1057

    
1058
  $cache[$tid] = $parents;
1059

    
1060
  return $parents;
1061
}
1062

    
1063
/**
1064
 * Finds all children of a term ID.
1065
 *
1066
 * @param $tid
1067
 *   A taxonomy term ID.
1068
 * @param $vid
1069
 *   An optional vocabulary ID to restrict the child search.
1070
 *
1071
 * @return
1072
 *   An array of term objects that are the children of the term $tid, or an
1073
 *   empty array when no children exist.
1074
 */
1075
function taxonomy_get_children($tid, $vid = 0) {
1076
  $children = &drupal_static(__FUNCTION__, array());
1077

    
1078
  if ($tid && !isset($children[$tid])) {
1079
    $query = db_select('taxonomy_term_data', 't');
1080
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
1081
    $query->addField('t', 'tid');
1082
    $query->condition('h.parent', $tid);
1083
    if ($vid) {
1084
      $query->condition('t.vid', $vid);
1085
    }
1086
    $query->addTag('taxonomy_term_access');
1087
    $query->orderBy('t.weight');
1088
    $query->orderBy('t.name');
1089
    $tids = $query->execute()->fetchCol();
1090
    $children[$tid] = taxonomy_term_load_multiple($tids);
1091
  }
1092

    
1093
  return isset($children[$tid]) ? $children[$tid] : array();
1094
}
1095

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

    
1123
  // We cache trees, so it's not CPU-intensive to call taxonomy_get_tree() on a
1124
  // term and its children, too.
1125
  if (!isset($children[$vid])) {
1126
    $children[$vid] = array();
1127
    $parents[$vid] = array();
1128
    $terms[$vid] = array();
1129

    
1130
    $query = db_select('taxonomy_term_data', 't');
1131
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
1132
    $result = $query
1133
      ->addTag('translatable')
1134
      ->addTag('taxonomy_term_access')
1135
      ->fields('t')
1136
      ->fields('h', array('parent'))
1137
      ->condition('t.vid', $vid)
1138
      ->orderBy('t.weight')
1139
      ->orderBy('t.name')
1140
      ->execute();
1141

    
1142
    foreach ($result as $term) {
1143
      $children[$vid][$term->parent][] = $term->tid;
1144
      $parents[$vid][$term->tid][] = $term->parent;
1145
      $terms[$vid][$term->tid] = $term;
1146
    }
1147
  }
1148

    
1149
  // Load full entities, if necessary. The entity controller statically
1150
  // caches the results.
1151
  if ($load_entities) {
1152
    $term_entities = taxonomy_term_load_multiple(array_keys($terms[$vid]));
1153
  }
1154

    
1155
  $max_depth = (!isset($max_depth)) ? count($children[$vid]) : $max_depth;
1156
  $tree = array();
1157

    
1158
  // Keeps track of the parents we have to process, the last entry is used
1159
  // for the next processing step.
1160
  $process_parents = array();
1161
  $process_parents[] = $parent;
1162

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

    
1189
          // We have to continue with this parent later.
1190
          $process_parents[] = $parent;
1191
          // Use the current term as parent for the next iteration.
1192
          $process_parents[] = $term->tid;
1193

    
1194
          // Reset pointers for child lists because we step in there more often
1195
          // with multi parents.
1196
          reset($children[$vid][$term->tid]);
1197
          // Move pointer so that we get the correct term the next time.
1198
          next($children[$vid][$parent]);
1199
          break;
1200
        }
1201
      } while ($child = next($children[$vid][$parent]));
1202

    
1203
      if (!$has_children) {
1204
        // We processed all terms in this hierarchy-level, reset pointer
1205
        // so that this function works the next time it gets called.
1206
        reset($children[$vid][$parent]);
1207
      }
1208
    }
1209
  }
1210

    
1211
  return $tree;
1212
}
1213

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

    
1243
/**
1244
 * Controller class for taxonomy terms.
1245
 *
1246
 * This extends the DrupalDefaultEntityController class. Only alteration is
1247
 * that we match the condition on term name case-independently.
1248
 */
1249
class TaxonomyTermController extends DrupalDefaultEntityController {
1250

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

    
1271
  protected function cacheGet($ids, $conditions = array()) {
1272
    $terms = parent::cacheGet($ids, $conditions);
1273
    // Name matching is case insensitive, note that with some collations
1274
    // LOWER() and drupal_strtolower() may return different results.
1275
    foreach ($terms as $term) {
1276
      $term_values = (array) $term;
1277
      if (isset($conditions['name']) && drupal_strtolower($conditions['name'] != drupal_strtolower($term_values['name']))) {
1278
        unset($terms[$term->tid]);
1279
      }
1280
    }
1281
    return $terms;
1282
  }
1283
}
1284

    
1285
/**
1286
 * Controller class for taxonomy vocabularies.
1287
 *
1288
 * This extends the DrupalDefaultEntityController class, adding required
1289
 * special handling for taxonomy vocabulary objects.
1290
 */
1291
class TaxonomyVocabularyController extends DrupalDefaultEntityController {
1292

    
1293
  protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
1294
    $query = parent::buildQuery($ids, $conditions, $revision_id);
1295
    $query->addTag('translatable');
1296
    $query->orderBy('base.weight');
1297
    $query->orderBy('base.name');
1298
    return $query;
1299
  }
1300
}
1301

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

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

    
1352
/**
1353
 * Return the vocabulary object matching a vocabulary ID.
1354
 *
1355
 * @param $vid
1356
 *   The vocabulary's ID.
1357
 *
1358
 * @return
1359
 *   The vocabulary object with all of its metadata, if exists, FALSE otherwise.
1360
 *   Results are statically cached.
1361
 *
1362
 * @see taxonomy_vocabulary_machine_name_load()
1363
 */
1364
function taxonomy_vocabulary_load($vid) {
1365
  $vocabularies = taxonomy_vocabulary_load_multiple(array($vid));
1366
  return reset($vocabularies);
1367
}
1368

    
1369
/**
1370
 * Return the vocabulary object matching a vocabulary machine name.
1371
 *
1372
 * @param $name
1373
 *   The vocabulary's machine name.
1374
 *
1375
 * @return
1376
 *   The vocabulary object with all of its metadata, if exists, FALSE otherwise.
1377
 *   Results are statically cached.
1378
 *
1379
 * @see taxonomy_vocabulary_load()
1380
 */
1381
function taxonomy_vocabulary_machine_name_load($name) {
1382
  $vocabularies = taxonomy_vocabulary_load_multiple(NULL, array('machine_name' => $name));
1383
  return reset($vocabularies);
1384
}
1385

    
1386
/**
1387
 * Return the term object matching a term ID.
1388
 *
1389
 * @param $tid
1390
 *   A term's ID
1391
 *
1392
 * @return
1393
 *   A taxonomy term object, or FALSE if the term was not found. Results are
1394
 *   statically cached.
1395
 */
1396
function taxonomy_term_load($tid) {
1397
  if (!is_numeric($tid)) {
1398
    return FALSE;
1399
  }
1400
  $term = taxonomy_term_load_multiple(array($tid), array());
1401
  return $term ? $term[$tid] : FALSE;
1402
}
1403

    
1404
/**
1405
 * Helper function for array_map purposes.
1406
 */
1407
function _taxonomy_get_tid_from_term($term) {
1408
  return $term->tid;
1409
}
1410

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

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

    
1466
/**
1467
 * Implements hook_field_widget_info().
1468
 */
1469
function taxonomy_field_widget_info() {
1470
  return array(
1471
    'taxonomy_autocomplete' => array(
1472
      'label' => t('Autocomplete term widget (tagging)'),
1473
      'field types' => array('taxonomy_term_reference'),
1474
      'settings' => array(
1475
        'size' => 60,
1476
        'autocomplete_path' => 'taxonomy/autocomplete',
1477
      ),
1478
      'behaviors' => array(
1479
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
1480
      ),
1481
    ),
1482
  );
1483
}
1484

    
1485
/**
1486
 * Implements hook_field_widget_info_alter().
1487
 */
1488
function taxonomy_field_widget_info_alter(&$info) {
1489
  $info['options_select']['field types'][] = 'taxonomy_term_reference';
1490
  $info['options_buttons']['field types'][] = 'taxonomy_term_reference';
1491
}
1492

    
1493
/**
1494
 * Implements hook_options_list().
1495
 */
1496
function taxonomy_options_list($field, $instance, $entity_type, $entity) {
1497
  $function = !empty($field['settings']['options_list_callback']) ? $field['settings']['options_list_callback'] : 'taxonomy_allowed_values';
1498
  return $function($field);
1499
}
1500

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

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

    
1560
/**
1561
 * Implements hook_field_is_empty().
1562
 */
1563
function taxonomy_field_is_empty($item, $field) {
1564
  if (!is_array($item) || (empty($item['tid']) && (string) $item['tid'] !== '0')) {
1565
    return TRUE;
1566
  }
1567
  return FALSE;
1568
}
1569

    
1570
/**
1571
 * Implements hook_field_formatter_info().
1572
 */
1573
function taxonomy_field_formatter_info() {
1574
  return array(
1575
    'taxonomy_term_reference_link' => array(
1576
      'label' => t('Link'),
1577
      'field types' => array('taxonomy_term_reference'),
1578
    ),
1579
    'taxonomy_term_reference_plain' => array(
1580
      'label' => t('Plain text'),
1581
      'field types' => array('taxonomy_term_reference'),
1582
    ),
1583
    'taxonomy_term_reference_rss_category' => array(
1584
      'label' => t('RSS category'),
1585
      'field types' => array('taxonomy_term_reference'),
1586
    ),
1587
  );
1588
}
1589

    
1590
/**
1591
 * Implements hook_field_formatter_view().
1592
 */
1593
function taxonomy_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
1594
  $element = array();
1595

    
1596
  // Terms whose tid is 'autocreate' do not exist
1597
  // yet and $item['taxonomy_term'] is not set. Theme such terms as
1598
  // just their name.
1599

    
1600
  switch ($display['type']) {
1601
    case 'taxonomy_term_reference_link':
1602
      foreach ($items as $delta => $item) {
1603
        if ($item['tid'] == 'autocreate') {
1604
          $element[$delta] = array(
1605
            '#markup' => check_plain($item['name']),
1606
          );
1607
        }
1608
        else {
1609
          $term = $item['taxonomy_term'];
1610
          $uri = entity_uri('taxonomy_term', $term);
1611
          $element[$delta] = array(
1612
            '#type' => 'link',
1613
            '#title' => $term->name,
1614
            '#href' => $uri['path'],
1615
            '#options' => $uri['options'],
1616
          );
1617
        }
1618
      }
1619
      break;
1620

    
1621
    case 'taxonomy_term_reference_plain':
1622
      foreach ($items as $delta => $item) {
1623
        $name = ($item['tid'] != 'autocreate' ? $item['taxonomy_term']->name : $item['name']);
1624
        $element[$delta] = array(
1625
          '#markup' => check_plain($name),
1626
        );
1627
      }
1628
      break;
1629

    
1630
    case 'taxonomy_term_reference_rss_category':
1631
      foreach ($items as $delta => $item) {
1632
        $entity->rss_elements[] = array(
1633
          'key' => 'category',
1634
          'value' => $item['tid'] != 'autocreate' ? $item['taxonomy_term']->name : $item['name'],
1635
          'attributes' => array(
1636
            'domain' => $item['tid'] != 'autocreate' ? url('taxonomy/term/' . $item['tid'], array('absolute' => TRUE)) : '',
1637
          ),
1638
        );
1639
      }
1640
      break;
1641
  }
1642

    
1643
  return $element;
1644
}
1645

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

    
1668
/**
1669
 * Implements hook_field_formatter_prepare_view().
1670
 *
1671
 * This preloads all taxonomy terms for multiple loaded objects at once and
1672
 * unsets values for invalid terms that do not exist.
1673
 */
1674
function taxonomy_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays) {
1675
  $tids = array();
1676

    
1677
  // Collect every possible term attached to any of the fieldable entities.
1678
  foreach ($entities as $id => $entity) {
1679
    foreach ($items[$id] as $delta => $item) {
1680
      // Force the array key to prevent duplicates.
1681
      if ($item['tid'] != 'autocreate') {
1682
        $tids[$item['tid']] = $item['tid'];
1683
      }
1684
    }
1685
  }
1686
  if ($tids) {
1687
    $terms = taxonomy_term_load_multiple($tids);
1688

    
1689
    // Iterate through the fieldable entities again to attach the loaded term data.
1690
    foreach ($entities as $id => $entity) {
1691
      $rekey = FALSE;
1692

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

    
1710
      if ($rekey) {
1711
        // Rekey the items array.
1712
        $items[$id] = array_values($items[$id]);
1713
      }
1714
    }
1715
  }
1716
}
1717

    
1718
/**
1719
 * Title callback: Returns the title of the taxonomy term.
1720
 *
1721
 * @param $term
1722
 *   A term object.
1723
 *
1724
 * @return
1725
 *   An unsanitized string that is the title of the taxonomy term.
1726
 *
1727
 * @see taxonomy_menu()
1728
 */
1729
function taxonomy_term_title($term) {
1730
  return $term->name;
1731
}
1732

    
1733
/**
1734
 * Implements hook_field_widget_form().
1735
 */
1736
function taxonomy_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
1737
  $tags = array();
1738
  foreach ($items as $item) {
1739
    $tags[$item['tid']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
1740
  }
1741

    
1742
  $element += array(
1743
    '#type' => 'textfield',
1744
    '#default_value' => taxonomy_implode_tags($tags),
1745
    '#autocomplete_path' => $instance['widget']['settings']['autocomplete_path'] . '/' . $field['field_name'],
1746
    '#size' => $instance['widget']['settings']['size'],
1747
    '#maxlength' => 1024,
1748
    '#element_validate' => array('taxonomy_autocomplete_validate'),
1749
  );
1750

    
1751
  return $element;
1752
}
1753

    
1754
/**
1755
 * Form element validate handler for taxonomy term autocomplete element.
1756
 */
1757
function taxonomy_autocomplete_validate($element, &$form_state) {
1758
  // Autocomplete widgets do not send their tids in the form, so we must detect
1759
  // them here and process them independently.
1760
  $value = array();
1761
  if ($tags = $element['#value']) {
1762
    // Collect candidate vocabularies.
1763
    $field = field_widget_field($element, $form_state);
1764
    $vocabularies = array();
1765
    foreach ($field['settings']['allowed_values'] as $tree) {
1766
      if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
1767
        $vocabularies[$vocabulary->vid] = $vocabulary;
1768
      }
1769
    }
1770

    
1771
    // Translate term names into actual terms.
1772
    $typed_terms = drupal_explode_tags($tags);
1773
    foreach ($typed_terms as $typed_term) {
1774
      // See if the term exists in the chosen vocabulary and return the tid;
1775
      // otherwise, create a new 'autocreate' term for insert/update.
1776
      if ($possibilities = taxonomy_term_load_multiple(array(), array('name' => trim($typed_term), 'vid' => array_keys($vocabularies)))) {
1777
        $term = array_pop($possibilities);
1778
      }
1779
      else {
1780
        $vocabulary = reset($vocabularies);
1781
        $term = array(
1782
          'tid' => 'autocreate',
1783
          'vid' => $vocabulary->vid,
1784
          'name' => $typed_term,
1785
          'vocabulary_machine_name' => $vocabulary->machine_name,
1786
        );
1787
      }
1788
      $value[] = (array)$term;
1789
    }
1790
  }
1791

    
1792
  form_set_value($element, $value, $form_state);
1793
}
1794

    
1795
/**
1796
 * Implements hook_field_widget_error().
1797
 */
1798
function taxonomy_field_widget_error($element, $error, $form, &$form_state) {
1799
  form_error($element, $error['message']);
1800
}
1801
/**
1802
 * Implements hook_field_settings_form().
1803
 */
1804
function taxonomy_field_settings_form($field, $instance, $has_data) {
1805
  // Get proper values for 'allowed_values_function', which is a core setting.
1806
  $vocabularies = taxonomy_get_vocabularies();
1807
  $options = array();
1808
  foreach ($vocabularies as $vocabulary) {
1809
    $options[$vocabulary->machine_name] = $vocabulary->name;
1810
  }
1811
  $form['allowed_values'] = array(
1812
    '#tree' => TRUE,
1813
  );
1814

    
1815
  foreach ($field['settings']['allowed_values'] as $delta => $tree) {
1816
    $form['allowed_values'][$delta]['vocabulary'] = array(
1817
      '#type' => 'select',
1818
      '#title' => t('Vocabulary'),
1819
      '#default_value' => $tree['vocabulary'],
1820
      '#options' => $options,
1821
      '#required' => TRUE,
1822
      '#description' => t('The vocabulary which supplies the options for this field.'),
1823
      '#disabled' => $has_data,
1824
    );
1825
    $form['allowed_values'][$delta]['parent'] = array(
1826
      '#type' => 'value',
1827
      '#value' => $tree['parent'],
1828
    );
1829
  }
1830

    
1831
  return $form;
1832
}
1833

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

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

    
1897
/**
1898
 * Implements hook_field_presave().
1899
 *
1900
 * Create any new terms defined in a freetagging vocabulary.
1901
 */
1902
function taxonomy_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
1903
  foreach ($items as $delta => $item) {
1904
    if ($item['tid'] == 'autocreate') {
1905
      $term = (object) $item;
1906
      unset($term->tid);
1907
      taxonomy_term_save($term);
1908
      $items[$delta]['tid'] = $term->tid;
1909
    }
1910
  }
1911
}
1912

    
1913
/**
1914
 * Implements hook_node_insert().
1915
 */
1916
function taxonomy_node_insert($node) {
1917
  // Add taxonomy index entries for the node.
1918
  taxonomy_build_node_index($node);
1919
}
1920

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

    
1990
/**
1991
 * Implements hook_node_update().
1992
 */
1993
function taxonomy_node_update($node) {
1994
  // Always rebuild the node's taxonomy index entries on node save.
1995
  taxonomy_delete_node_index($node);
1996
  taxonomy_build_node_index($node);
1997
}
1998

    
1999
/**
2000
 * Implements hook_node_delete().
2001
 */
2002
function taxonomy_node_delete($node) {
2003
  // Clean up the {taxonomy_index} table when nodes are deleted.
2004
  taxonomy_delete_node_index($node);
2005
}
2006

    
2007
/**
2008
 * Deletes taxonomy index entries for a given node.
2009
 *
2010
 * @param $node
2011
 *   The node object.
2012
 */
2013
function taxonomy_delete_node_index($node) {
2014
  if (variable_get('taxonomy_maintain_index_table', TRUE)) {
2015
    db_delete('taxonomy_index')->condition('nid', $node->nid)->execute();
2016
  }
2017
}
2018

    
2019
/**
2020
 * Implements hook_taxonomy_term_delete().
2021
 */
2022
function taxonomy_taxonomy_term_delete($term) {
2023
  if (variable_get('taxonomy_maintain_index_table', TRUE)) {
2024
    // Clean up the {taxonomy_index} table when terms are deleted.
2025
    db_delete('taxonomy_index')->condition('tid', $term->tid)->execute();
2026
  }
2027
}
2028

    
2029
/**
2030
 * @} End of "defgroup taxonomy_index".
2031
 */
2032

    
2033
/**
2034
 * Implements hook_entity_query_alter().
2035
 *
2036
 * Converts EntityFieldQuery instances on taxonomy terms that have an entity
2037
 * condition on term bundles (vocabulary machine names). Since the vocabulary
2038
 * machine name is not present in the {taxonomy_term_data} table itself, we have
2039
 * to convert the bundle condition into a property condition of vocabulary IDs
2040
 * to match against {taxonomy_term_data}.vid.
2041
 */
2042
function taxonomy_entity_query_alter($query) {
2043
  $conditions = &$query->entityConditions;
2044

    
2045
  // Alter only taxonomy term queries with bundle conditions.
2046
  if (isset($conditions['entity_type']) && $conditions['entity_type']['value'] == 'taxonomy_term' && isset($conditions['bundle'])) {
2047
    // Convert vocabulary machine names to vocabulary IDs.
2048
    $vocabulary_data = taxonomy_vocabulary_get_names();
2049
    $vids = array();
2050
    if (is_array($conditions['bundle']['value'])) {
2051
      foreach ($conditions['bundle']['value'] as $vocabulary_machine_name) {
2052
        $vids[] = $vocabulary_data[$vocabulary_machine_name]->vid;
2053
      }
2054
    }
2055
    else {
2056
      $vocabulary_machine_name = $conditions['bundle']['value'];
2057
      $vids = $vocabulary_data[$vocabulary_machine_name]->vid;
2058
    }
2059

    
2060
    $query->propertyCondition('vid', $vids, $conditions['bundle']['operator']);
2061
    unset($conditions['bundle']);
2062
  }
2063
}