summaryrefslogtreecommitdiff
path: root/modules/taxonomy/taxonomy.module
blob: 6cacb25f383a277ce724becd92c66b4c395a1624 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
<?php
// $Id$

/**
 * @file
 * Enables the organization of content into categories.
 */

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

/**
 * Implements hook_help().
 */
function taxonomy_help($path, $arg) {
  switch ($path) {
    case 'admin/help#taxonomy':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $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/handbook/modules/taxonomy/')) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Creating vocabularies') . '</dt>';
      $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'))));
      $output .= '<ul><li>' . t('<em>vocabulary</em>: Music') . '</li>';
      $output .= '<ul><li>' . t('<em>term</em>: Jazz') . '</li>';
      $output .= '<ul><li>' . t('<em>sub-term</em>: Swing') . '</li>';
      $output .= '<li>' . t('<em>sub-term</em>: Fusion') . '</li></ul></ul>';
      $output .= '<ul><li>' . t('<em>term</em>: Rock') . '</li>';
      $output .= '<ul><li>' . t('<em>sub-term</em>: Country rock') . '</li>';
      $output .= '<li>' . t('<em>sub-term</em>: Hard rock') . '</li></ul></ul></ul>';
      $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>';
      $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>';
      $output .= '<dt>' . t('Assigning vocabularies to content types') . '</dt>';
      $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>';
      $output .= '<dt>' . t('Classifying content') . '</dt>';
      $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>';
      $output .= '<dt>' . t('Viewing listings and RSS feeds by term') . '</dt>';
      $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>';
      $output .= '<dt>' . t('Extending Taxonomy module') . '</dt>';
      $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'));
      $output .= '</dl>';
      return $output;
    case 'admin/structure/taxonomy':
      $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>';
      return $output;
    case 'admin/structure/taxonomy/%':
      $vocabulary = taxonomy_vocabulary_machine_name_load($arg[3]);
      switch ($vocabulary->hierarchy) {
        case 0:
          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>';
        case 1:
          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>';
        case 2:
          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>';
      }
  }
}

/**
 * Implements hook_permission().
 */
function taxonomy_permission() {
  $permissions = array(
    'administer taxonomy' => array(
      'title' => t('Administer vocabularies and terms'),
    ),
  );
  foreach (taxonomy_get_vocabularies() as $vocabulary) {
    $permissions += array(
      'edit terms in ' . $vocabulary->vid => array(
        'title' => t('Edit terms in %vocabulary', array('%vocabulary' => $vocabulary->name)),
      ),
    );
    $permissions += array(
       'delete terms in ' . $vocabulary->vid => array(
         'title' => t('Delete terms from %vocabulary', array('%vocabulary' => $vocabulary->name)),
      ),
    );
  }
  return $permissions;
}

/**
 * Implements hook_entity_info().
 */
function taxonomy_entity_info() {
  $return = array(
    'taxonomy_term' => array(
      'label' => t('Taxonomy term'),
      'controller class' => 'TaxonomyTermController',
      'base table' => 'taxonomy_term_data',
      'uri callback' => 'taxonomy_term_uri',
      'fieldable' => TRUE,
      'entity keys' => array(
        'id' => 'tid',
        'bundle' => 'vocabulary_machine_name',
        'label' => 'name',
      ),
      'bundle keys' => array(
        'bundle' => 'machine_name',
      ),
      'bundles' => array(),
      'view modes' => array(
        // @todo View mode for display as a field (when attached to nodes etc).
        'full' => array(
          'label' => t('Taxonomy term page'),
          'custom settings' => FALSE,
        ),
      ),
    ),
  );
  foreach (taxonomy_vocabulary_get_names() as $machine_name => $vocabulary) {
    $return['taxonomy_term']['bundles'][$machine_name] = array(
      'label' => $vocabulary->name,
      'admin' => array(
        'path' => 'admin/structure/taxonomy/%taxonomy_vocabulary_machine_name',
        'real path' => 'admin/structure/taxonomy/' . $machine_name,
        'bundle argument' => 3,
        'access arguments' => array('administer taxonomy'),
      ),
    );
  }
  $return['taxonomy_vocabulary'] = array(
    'label' => t('Taxonomy vocabulary'),
    'controller class' => 'TaxonomyVocabularyController',
    'base table' => 'taxonomy_vocabulary',
    'entity keys' => array(
      'id' => 'vid',
      'label' => 'name',
    ),
    'fieldable' => FALSE,
  );

  return $return;
}

/**
 * Entity uri callback.
 */
function taxonomy_term_uri($term) {
  return array(
    'path' => 'taxonomy/term/' . $term->tid,
  );
}

/**
 * Implements hook_field_extra_fields().
 */
function taxonomy_field_extra_fields() {
  $return = array();
  $info = entity_get_info('taxonomy_term');
  foreach (array_keys($info['bundles']) as $bundle) {
    $return['taxonomy_term'][$bundle] = array(
      'form' => array(
        'name' => array(
          'label' => t('Name'),
          'description' => t('Term name textfield'),
          'weight' => -5,
        ),
        'description' => array(
          'label' => t('Description'),
          'description' => t('Term description textarea'),
          'weight' => 0,
        ),
      ),
      'display' => array(
        'description' => array(
          'label' => t('Description'),
          'description' => t('Term description'),
          'weight' => 0,
        ),
      ),
    );
  }

  return $return;
}

/**
 * Return nodes attached to a term across all field instances.
 *
 * This function requires taxonomy module to be maintaining its own tables,
 * and will return an empty array if it is not. If using other field storage
 * methods alternatives methods for listing terms will need to be used.
 *
 * @param $tid
 *   The term ID.
 * @param $pager
 *   Boolean to indicate whether a pager should be used.
 * @param $limit
 *   Integer. The maximum number of nodes to find.
 *   Set to FALSE for no limit.
 * @order
 *   An array of fields and directions.
 *
 * @return
 *   An array of nids matching the query.
 */
function taxonomy_select_nodes($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC')) {
  if (!variable_get('taxonomy_maintain_index_table', TRUE)) {
    return array();
  }
  $query = db_select('taxonomy_index', 't');
  $query->addTag('node_access');
  $query->condition('tid', $tid);
  if ($pager) {
    $count_query = clone $query;
    $count_query->addExpression('COUNT(t.nid)');

    $query = $query->extend('PagerDefault');
    if ($limit !== FALSE) {
      $query = $query->limit($limit);
    }
    $query->setCountQuery($count_query);
  }
  else {
    if ($limit !== FALSE) {
      $query->range(0, $limit);
    }
  }
  $query->addField('t', 'nid');
  $query->addField('t', 'tid');
  foreach ($order as $field => $direction) {
    $query->orderBy($field, $direction);
    // ORDER BY fields need to be loaded too, assume they are in the form
    // table_alias.name
    list($table_alias, $name) = explode('.', $field);
    $query->addField($table_alias, $name);
  }
  return $query->execute()->fetchCol();
}

/**
 * Implements hook_theme().
 */
function taxonomy_theme() {
  return array(
    'taxonomy_overview_vocabularies' => array(
      'render element' => 'form',
    ),
    'taxonomy_overview_terms' => array(
      'render element' => 'form',
    ),
    'taxonomy_term' => array(
      'render element' => 'elements',
      'template' => 'taxonomy-term',
    ),
  );
}

/**
 * Implements hook_menu().
 */
function taxonomy_menu() {
  $items['admin/structure/taxonomy'] = array(
    'title' => 'Taxonomy',
    'description' => 'Manage tagging, categorization, and classification of your content.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_overview_vocabularies'),
    'access arguments' => array('administer taxonomy'),
    'file' => 'taxonomy.admin.inc',
  );
  $items['admin/structure/taxonomy/list'] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/structure/taxonomy/add'] = array(
    'title' => 'Add vocabulary',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_form_vocabulary'),
    'access arguments' => array('administer taxonomy'),
    'type' => MENU_LOCAL_ACTION,
    'file' => 'taxonomy.admin.inc',
  );

  $items['taxonomy/term/%taxonomy_term'] = array(
    'title' => 'Taxonomy term',
    'title callback' => 'taxonomy_term_title',
    'title arguments' => array(2),
    'page callback' => 'taxonomy_term_page',
    'page arguments' => array(2),
    'access arguments' => array('access content'),
    'file' => 'taxonomy.pages.inc',
  );
  $items['taxonomy/term/%taxonomy_term/view'] = array(
    'title' => 'View',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
  $items['taxonomy/term/%taxonomy_term/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_form_term', 2),
    'access callback' => 'taxonomy_term_edit_access',
    'access arguments' => array(2),
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
    'file' => 'taxonomy.admin.inc',
  );
  $items['taxonomy/term/%taxonomy_term/feed'] = array(
    'title' => 'Taxonomy term',
    'title callback' => 'taxonomy_term_title',
    'title arguments' => array(2),
    'page callback' => 'taxonomy_term_feed',
    'page arguments' => array(2),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'file' => 'taxonomy.pages.inc',
  );
  $items['taxonomy/autocomplete'] = array(
    'title' => 'Autocomplete taxonomy',
    'page callback' => 'taxonomy_autocomplete',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'file' => 'taxonomy.pages.inc',
  );

  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name'] = array(
    'title callback' => 'taxonomy_admin_vocabulary_title_callback',
    'title arguments' => array(3),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_overview_terms', 3),
    'access arguments' => array('administer taxonomy'),
    'file' => 'taxonomy.admin.inc',
  );
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/list'] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -20,
  );
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_form_vocabulary', 3),
    'access arguments' => array('administer taxonomy'),
    'type' => MENU_LOCAL_TASK,
    'weight' => -10,
    'file' => 'taxonomy.admin.inc',
  );

  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/add'] = array(
    'title' => 'Add term',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_form_term', array(), 3),
    'access arguments' => array('administer taxonomy'),
    'type' => MENU_LOCAL_ACTION,
    'file' => 'taxonomy.admin.inc',
  );

  return $items;
}

/**
 * Implements hook_admin_paths().
 */
function taxonomy_admin_paths() {
  $paths = array(
    'taxonomy/term/*/edit' => TRUE,
  );
  return $paths;
}

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

/**
 * Return the vocabulary name given the vocabulary object.
 */
function taxonomy_admin_vocabulary_title_callback($vocabulary) {
  return check_plain($vocabulary->name);
}

/**
 * Save a vocabulary given a vocabulary object.
 */
function taxonomy_vocabulary_save($vocabulary) {
  // Prevent leading and trailing spaces in vocabulary names.
  if (!empty($vocabulary->name)) {
    $vocabulary->name = trim($vocabulary->name);
  }
  // Load the stored entity, if any.
  if (!empty($vocabulary->vid)) {
    if (!isset($vocabulary->original)) {
      $vocabulary->original = entity_load_unchanged('taxonomy_vocabulary', $vocabulary->vid);
    }
    // Make sure machine name changes are easily detected.
    // @todo: Remove in Drupal 8, as it is deprecated by directly reading from
    // $vocabulary->original.
    $vocabulary->old_machine_name = $vocabulary->original->machine_name;
  }

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

  module_invoke_all('taxonomy_vocabulary_presave', $vocabulary);
  module_invoke_all('entity_presave', $vocabulary, 'taxonomy_vocabulary');

  if (!empty($vocabulary->vid) && !empty($vocabulary->name)) {
    $status = drupal_write_record('taxonomy_vocabulary', $vocabulary, 'vid');
    if ($vocabulary->old_machine_name != $vocabulary->machine_name) {
      field_attach_rename_bundle('taxonomy_term', $vocabulary->old_machine_name, $vocabulary->machine_name);
    }
    module_invoke_all('taxonomy_vocabulary_update', $vocabulary);
    module_invoke_all('entity_update', $vocabulary, 'taxonomy_vocabulary');
  }
  elseif (empty($vocabulary->vid)) {
    $status = drupal_write_record('taxonomy_vocabulary', $vocabulary);
    field_attach_create_bundle('taxonomy_term', $vocabulary->machine_name);
    module_invoke_all('taxonomy_vocabulary_insert', $vocabulary);
    module_invoke_all('entity_insert', $vocabulary, 'taxonomy_vocabulary');
  }

  unset($vocabulary->original);
  cache_clear_all();
  entity_get_controller('taxonomy_vocabulary')->resetCache(array($vocabulary->vid));

  return $status;
}

/**
 * Delete a vocabulary.
 *
 * @param $vid
 *   A vocabulary ID.
 * @return
 *   Constant indicating items were deleted.
 */
function taxonomy_vocabulary_delete($vid) {
  $vocabulary = taxonomy_vocabulary_load($vid);

  $transaction = db_transaction();
  try {
    // Only load terms without a parent, child terms will get deleted too.
    $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();
    foreach ($result as $tid) {
      taxonomy_term_delete($tid);
    }
    db_delete('taxonomy_vocabulary')
      ->condition('vid', $vid)
      ->execute();

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

    cache_clear_all();
    entity_get_controller('taxonomy_vocabulary')->resetCache();

    return SAVED_DELETED;
  }
  catch (Exception $e) {
    $transaction->rollback();
    watchdog_exception('taxonomy', $e);
    throw $e;
  }
}

/**
 * Implements hook_taxonomy_vocabulary_update().
 */
function taxonomy_taxonomy_vocabulary_update($vocabulary) {
  // Reflect machine name changes in the definitions of existing 'taxonomy'
  // fields.
  if (!empty($vocabulary->old_machine_name) && $vocabulary->old_machine_name != $vocabulary->machine_name) {
    $fields = field_read_fields();
    foreach ($fields as $field_name => $field) {
      $update = FALSE;
      if ($field['type'] == 'taxonomy_term_reference') {
        foreach ($field['settings']['allowed_values'] as $key => &$value) {
          if ($value['vocabulary'] == $vocabulary->old_machine_name) {
            $value['vocabulary'] = $vocabulary->machine_name;
            $update = TRUE;
          }
        }
        if ($update) {
          field_update_field($field);
        }
      }
    }
  }
}

/**
 * Dynamically check and update the hierarchy flag of a vocabulary.
 *
 * Checks the current parents of all terms in a vocabulary and updates the
 * vocabularies hierarchy setting to the lowest possible level. A hierarchy with
 * no parents in any of its terms will be given a hierarchy of 0. If terms
 * contain at most a single parent, the vocabulary will be given a hierarchy of
 * 1. If any term contain multiple parents, the vocabulary will be given a
 * hierarchy of 2.
 *
 * @param $vocabulary
 *   A vocabulary object.
 * @param $changed_term
 *   An array of the term structure that was updated.
 */
function taxonomy_check_vocabulary_hierarchy($vocabulary, $changed_term) {
  $tree = taxonomy_get_tree($vocabulary->vid);
  $hierarchy = 0;
  foreach ($tree as $term) {
    // Update the changed term with the new parent value before comparison.
    if ($term->tid == $changed_term['tid']) {
      $term = (object) $changed_term;
      $term->parents = $term->parent;
    }
    // Check this term's parent count.
    if (count($term->parents) > 1) {
      $hierarchy = 2;
      break;
    }
    elseif (count($term->parents) == 1 && 0 !== array_shift($term->parents)) {
      $hierarchy = 1;
    }
  }
  if ($hierarchy != $vocabulary->hierarchy) {
    $vocabulary->hierarchy = $hierarchy;
    taxonomy_vocabulary_save($vocabulary);
  }

  return $hierarchy;
}

/**
 * Save a term object to the database.
 *
 * @param $term
 *  A term object.
 * @return
 *   Status constant indicating if term was inserted or updated.
 */
function taxonomy_term_save($term) {
  // Prevent leading and trailing spaces in term names.
  $term->name = trim($term->name);
  if (!isset($term->vocabulary_machine_name)) {
    $vocabulary = taxonomy_vocabulary_load($term->vid);
    $term->vocabulary_machine_name = $vocabulary->machine_name;
  }

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

  field_attach_presave('taxonomy_term', $term);
  module_invoke_all('taxonomy_term_presave', $term);
  module_invoke_all('entity_presave', $term, 'taxonomy_term');

  if (empty($term->tid)) {
    $op = 'insert';
    $status = drupal_write_record('taxonomy_term_data', $term);
    field_attach_insert('taxonomy_term', $term);
    if (!isset($term->parent)) {
      $term->parent = array(0);
    }
  }
  else {
    $op = 'update';
    $status = drupal_write_record('taxonomy_term_data', $term, 'tid');
    field_attach_update('taxonomy_term', $term);
    if (isset($term->parent)) {
      db_delete('taxonomy_term_hierarchy')
        ->condition('tid', $term->tid)
        ->execute();
    }
  }

  if (isset($term->parent)) {
    if (!is_array($term->parent)) {
      $term->parent = array($term->parent);
    }
    $query = db_insert('taxonomy_term_hierarchy')
      ->fields(array('tid', 'parent'));
    foreach ($term->parent as $parent) {
      if (is_array($parent)) {
        foreach ($parent as $tid) {
          $query->values(array(
            'tid' => $term->tid,
            'parent' => $tid
          ));
        }
      }
      else {
        $query->values(array(
          'tid' => $term->tid,
          'parent' => $parent
        ));
      }
    }
    $query->execute();
  }

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

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

  return $status;
}

/**
 * Delete a term.
 *
 * @param $tid
 *   The term ID.
 * @return
 *   Status constant indicating deletion.
 */
function taxonomy_term_delete($tid) {
  $transaction = db_transaction();
  try {
    $tids = array($tid);
    while ($tids) {
      $children_tids = $orphans = array();
      foreach ($tids as $tid) {
        // See if any of the term's children are about to be become orphans:
        if ($children = taxonomy_get_children($tid)) {
          foreach ($children as $child) {
            // If the term has multiple parents, we don't delete it.
            $parents = taxonomy_get_parents($child->tid);
            if (count($parents) == 1) {
              $orphans[] = $child->tid;
            }
          }
        }

        if ($term = taxonomy_term_load($tid)) {
          db_delete('taxonomy_term_data')
            ->condition('tid', $tid)
            ->execute();
          db_delete('taxonomy_term_hierarchy')
            ->condition('tid', $tid)
            ->execute();

          field_attach_delete('taxonomy_term', $term);
          module_invoke_all('taxonomy_term_delete', $term);
          module_invoke_all('entity_delete', $term, 'taxonomy_term');
          taxonomy_terms_static_reset();
        }
      }

      $tids = $orphans;
    }
    return SAVED_DELETED;
  }
  catch (Exception $e) {
    $transaction->rollback();
    watchdog_exception('taxonomy', $e);
    throw $e;
  }
}

/**
 * Generate an array for rendering the given term.
 *
 * @param $term
 *   A term object.
 * @param $view_mode
 *   View mode, e.g. 'full', 'teaser'...
 * @param $langcode
 *   (optional) A language code to use for rendering. Defaults to the global
 *   content language of the current request.
 *
 * @return
 *   An array as expected by drupal_render().
 */
function taxonomy_term_view($term, $view_mode = 'full', $langcode = NULL) {
  if (!isset($langcode)) {
    $langcode = $GLOBALS['language_content']->language;
  }

  field_attach_prepare_view('taxonomy_term', array($term->tid => $term), $view_mode);
  entity_prepare_view('taxonomy_term', array($term->tid => $term));

  $build = array(
    '#theme' => 'taxonomy_term',
    '#term' => $term,
    '#view_mode' => $view_mode,
    '#language' => $langcode,
  );

  $build += field_attach_view('taxonomy_term', $term, $view_mode, $langcode);

  $build['description'] = array(
    '#markup' => check_markup($term->description, $term->format, '', TRUE),
    '#weight' => 0,
    '#prefix' => '<div class="taxonomy-term-description">',
    '#suffix' => '</div>',
  );

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

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

  return $build;
}

/**
 * Process variables for taxonomy-term.tpl.php.
 */
function template_preprocess_taxonomy_term(&$variables) {
  $variables['view_mode'] = $variables['elements']['#view_mode'];
  $variables['term'] = $variables['elements']['#term'];
  $term = $variables['term'];

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

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

  // Helpful $content variable for templates.
  foreach (element_children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }

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

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

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

/**
 * Returns whether the current page is the page of the passed in term.
 *
 * @param $term
 *   A term object.
 */
function taxonomy_term_is_page($term) {
  $page_term = menu_get_object('taxonomy_term', 2);
  return (!empty($page_term) ? $page_term->tid == $term->tid : FALSE);
}

/**
 * Clear all static cache variables for terms..
 */
function taxonomy_terms_static_reset() {
  drupal_static_reset('taxonomy_term_count_nodes');
  drupal_static_reset('taxonomy_get_tree');
  drupal_static_reset('taxonomy_get_tree:parents');
  drupal_static_reset('taxonomy_get_tree:terms');
  drupal_static_reset('taxonomy_get_parents');
  drupal_static_reset('taxonomy_get_parents_all');
  drupal_static_reset('taxonomy_get_children');
  entity_get_controller('taxonomy_term')->resetCache();
}

/**
 * Return an array of all vocabulary objects.
 *
 * @return
 *   An array of all vocabulary objects, indexed by vid.
 */
function taxonomy_get_vocabularies() {
  return taxonomy_vocabulary_load_multiple(FALSE, array());
}

/**
 * Get names for all taxonomy vocabularies.
 *
 * @return
 *   An array of vocabulary ids, names, machine names, keyed by machine name.
 */
function taxonomy_vocabulary_get_names() {
  $names = db_query('SELECT name, machine_name, vid FROM {taxonomy_vocabulary}')->fetchAllAssoc('machine_name');
  return $names;
}

/**
 * Finds all parents of a given term ID.
 *
 * @param $tid
 *   A taxonomy term ID.
 *
 * @return
 *   An array of term objects which are the parents of the term $tid.
 */
function taxonomy_get_parents($tid) {
  $parents = &drupal_static(__FUNCTION__, array());

  if ($tid && !isset($parents[$tid])) {
    $query = db_select('taxonomy_term_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.parent = t.tid');
    $query->addField('t', 'tid');
    $query->condition('h.tid', $tid);
    $query->addTag('term_access');
    $query->orderBy('t.weight');
    $query->orderBy('t.name');
    $tids = $query->execute()->fetchCol();
    $parents[$tid] = taxonomy_term_load_multiple($tids);
  }

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

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

  if (isset($cache[$tid])) {
    return $cache[$tid];
  }

  $parents = array();
  if ($term = taxonomy_term_load($tid)) {
    $parents[] = $term;
    $n = 0;
    while ($parent = taxonomy_get_parents($parents[$n]->tid)) {
      $parents = array_merge($parents, $parent);
      $n++;
    }
  }

  $cache[$tid] = $parents;

  return $parents;
}

/**
 * Finds all children of a term ID.
 *
 * @param $tid
 *   A taxonomy term ID.
 * @param $vid
 *   An optional vocabulary ID to restrict the child search.
 *
 * @return
 *   An array of term objects which are the children of the term $tid.
 */
function taxonomy_get_children($tid, $vid = 0) {
  $children = &drupal_static(__FUNCTION__, array());

  if ($tid && !isset($children[$tid])) {
    $query = db_select('taxonomy_term_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
    $query->addField('t', 'tid');
    $query->condition('h.parent', $tid);
    if ($vid) {
      $query->condition('t.vid', $vid);
    }
    $query->addTag('term_access');
    $query->orderBy('t.weight');
    $query->orderBy('t.name');
    $tids = $query->execute()->fetchCol();
    $children[$tid] = taxonomy_term_load_multiple($tids);
  }

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

/**
 * Create a hierarchical representation of a vocabulary.
 *
 * @param $vid
 *   Which vocabulary to generate the tree for.
 * @param $parent
 *   The term ID under which to generate the tree. If 0, generate the tree
 *   for the entire vocabulary.
 * @param $max_depth
 *   The number of levels of the tree to return. Leave NULL to return all levels.
 * @param $load_entities
 *   If TRUE, a full entity load will occur on the term objects. Otherwise they
 *   are partial objects queried directly from the {taxonomy_term_data} table to
 *   save execution time and memory consumption when listing large numbers of
 *   terms. Defaults to FALSE.
 *
 * @return
 *   An array of all term objects in the tree. Each term object is extended
 *   to have "depth" and "parents" attributes in addition to its normal ones.
 *   Results are statically cached. Term objects will be partial or complete
 *   depending on the $load_entities parameter.
 */
function taxonomy_get_tree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE) {
  $children = &drupal_static(__FUNCTION__, array());
  $parents = &drupal_static(__FUNCTION__ . ':parents', array());
  $terms = &drupal_static(__FUNCTION__ . ':terms', array());

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

    $query = db_select('taxonomy_term_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
    $result = $query
      ->addTag('translatable')
      ->addTag('term_access')
      ->fields('t')
      ->fields('h', array('parent'))
      ->condition('t.vid', $vid)
      ->orderBy('t.weight')
      ->orderBy('t.name')
      ->execute();

    foreach ($result as $term) {
      $children[$vid][$term->parent][] = $term->tid;
      $parents[$vid][$term->tid][] = $term->parent;
      $terms[$vid][$term->tid] = $term;
    }
  }

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

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

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

  // Loops over the parent terms and adds its children to the tree array.
  // Uses a loop instead of a recursion, because it's more efficient.
  while (count($process_parents)) {
    $parent = array_pop($process_parents);
    // The number of parents determines the current depth.
    $depth = count($process_parents);
    if ($max_depth > $depth && !empty($children[$vid][$parent])) {
      $has_children = FALSE;
      $child = current($children[$vid][$parent]);
      do {
        if (empty($child)) {
          break;
        }
        $term = $load_entities ? $term_entities[$child] : $terms[$vid][$child];
        if (count($parents[$vid][$term->tid]) > 1) {
          // We have a term with multi parents here. Clone the term,
          // so that the depth attribute remains correct.
          $term = clone $term;
        }
        $term->depth = $depth;
        unset($term->parent);
        $term->parents = $parents[$vid][$term->tid];
        $tree[] = $term;
        if (!empty($children[$vid][$term->tid])) {
          $has_children = TRUE;

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

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

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

  return $tree;
}

/**
 * Try to map a string to an existing term, as for glossary use.
 *
 * Provides a case-insensitive and trimmed mapping, to maximize the
 * likelihood of a successful match.
 *
 * @param name
 *   Name of the term to search for.
 *
 * @return
 *   An array of matching term objects.
 */
function taxonomy_get_term_by_name($name) {
  return taxonomy_term_load_multiple(array(), array('name' => trim($name)));
}

/**
 * Controller class for taxonomy terms.
 *
 * This extends the DrupalDefaultEntityController class. Only alteration is
 * that we match the condition on term name case-independently.
 */
class TaxonomyTermController extends DrupalDefaultEntityController {

  protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
    $query = parent::buildQuery($ids, $conditions, $revision_id);
    $query->addTag('translatable');
    $query->addTag('term_access');
    // When name is passed as a condition use LIKE.
    if (isset($conditions['name'])) {
      $query_conditions = &$query->conditions();
      foreach ($query_conditions as $key => $condition) {
        if ($condition['field'] == 'base.name') {
          $query_conditions[$key]['operator'] = 'LIKE';
          $query_conditions[$key]['value'] = db_like($query_conditions[$key]['value']);
        }
      }
    }
    // Add the machine name field from the {taxonomy_vocabulary} table.
    $query->innerJoin('taxonomy_vocabulary', 'v', 'base.vid = v.vid');
    $query->addField('v', 'machine_name', 'vocabulary_machine_name');
    return $query;
  }

  protected function cacheGet($ids, $conditions = array()) {
    $terms = parent::cacheGet($ids, $conditions);
    // Name matching is case insensitive, note that with some collations
    // LOWER() and drupal_strtolower() may return different results.
    foreach ($terms as $term) {
      $term_values = (array) $term;
      if (isset($conditions['name']) && drupal_strtolower($conditions['name'] != drupal_strtolower($term_values['name']))) {
        unset($terms[$term->tid]);
      }
    }
    return $terms;
  }
}

/**
 * Controller class for taxonomy vocabularies.
 *
 * This extends the DrupalDefaultEntityController class, adding required
 * special handling for taxonomy vocabulary objects.
 */
class TaxonomyVocabularyController extends DrupalDefaultEntityController {

  protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
    $query = parent::buildQuery($ids, $conditions, $revision_id);
    $query->addTag('translatable');
    $query->orderBy('base.weight');
    $query->orderBy('base.name');
    return $query;
  }
}

/**
 * Load multiple taxonomy terms based on certain conditions.
 *
 * This function should be used whenever you need to load more than one term
 * from the database. Terms are loaded into memory and will not require
 * database access if loaded again during the same page request.
 *
 * @see entity_load()
 * @see EntityFieldQuery
 *
 * @param $tids
 *   An array of taxonomy term IDs.
 * @param $conditions
 *   (deprecated) An associative array of conditions on the {taxonomy_term}
 *   table, where the keys are the database fields and the values are the
 *   values those fields must have. Instead, it is preferable to use
 *   EntityFieldQuery to retrieve a list of entity IDs loadable by
 *   this function.
 *
 * @return
 *   An array of term objects, indexed by tid.
 *
 * @todo Remove $conditions in Drupal 8.
 */
function taxonomy_term_load_multiple($tids = array(), $conditions = array()) {
  return entity_load('taxonomy_term', $tids, $conditions);
}

/**
 * Load multiple taxonomy vocabularies based on certain conditions.
 *
 * This function should be used whenever you need to load more than one
 * vocabulary from the database. Terms are loaded into memory and will not
 * require database access if loaded again during the same page request.
 *
 * @see entity_load()
 *
 * @param $vids
 *  An array of taxonomy vocabulary IDs, or FALSE to load all vocabularies.
 * @param $conditions
 *  An array of conditions to add to the query.
 *
 * @return
 *  An array of vocabulary objects, indexed by vid.
 */
function taxonomy_vocabulary_load_multiple($vids = array(), $conditions = array()) {
  return entity_load('taxonomy_vocabulary', $vids, $conditions);
}

/**
 * Return the vocabulary object matching a vocabulary ID.
 *
 * @param $vid
 *   The vocabulary's ID.
 *
 * @return
 *   The vocabulary object with all of its metadata, if exists, FALSE otherwise.
 *   Results are statically cached.
 */
function taxonomy_vocabulary_load($vid) {
  $vocabularies = taxonomy_vocabulary_load_multiple(array($vid));
  return reset($vocabularies);
}

/**
 * Return the vocabulary object matching a vocabulary machine name.
 *
 * @param $name
 *   The vocabulary's machine name.
 *
 * @return
 *   The vocabulary object with all of its metadata, if exists, FALSE otherwise.
 *   Results are statically cached.
 */
function taxonomy_vocabulary_machine_name_load($name) {
  $vocabularies = taxonomy_vocabulary_load_multiple(NULL, array('machine_name' => $name));
  return reset($vocabularies);
}

/**
 * Return the term object matching a term ID.
 *
 * @param $tid
 *   A term's ID
 *
 * @return
 *   A term object. Results are statically cached.
 */
function taxonomy_term_load($tid) {
  if (!is_numeric($tid)) {
    return FALSE;
  }
  $term = taxonomy_term_load_multiple(array($tid), array());
  return $term ? $term[$tid] : FALSE;
}

/**
 * Helper function for array_map purposes.
 */
function _taxonomy_get_tid_from_term($term) {
  return $term->tid;
}

/**
 * Implodes a list of tags of a certain vocabulary into a string.
 *
 * @see drupal_explode_tags()
 */
function taxonomy_implode_tags($tags, $vid = NULL) {
  $typed_tags = array();
  foreach ($tags as $tag) {
    // Extract terms belonging to the vocabulary in question.
    if (!isset($vid) || $tag->vid == $vid) {
      // Make sure we have a completed loaded taxonomy term.
      if (isset($tag->name)) {
        // Commas and quotes in tag names are special cases, so encode 'em.
        if (strpos($tag->name, ',') !== FALSE || strpos($tag->name, '"') !== FALSE) {
          $tag->name = '"' . str_replace('"', '""', $tag->name) . '"';
        }

        $typed_tags[] = $tag->name;
      }
    }
  }
  return implode(', ', $typed_tags);
}

/**
 * Implements hook_field_info().
 *
 * Field settings:
 * - allowed_values: a list array of one or more vocabulary trees:
 *   - vocabulary: a vocabulary machine name.
 *   - parent: a term ID of a term whose children are allowed. This should be
 *     '0' if all terms in a vocabulary are allowed. The allowed values do not
 *     include the parent term.
 *
 */
function taxonomy_field_info() {
  return array(
    'taxonomy_term_reference' => array(
      'label' => t('Term reference'),
      'description' => t('This field stores a reference to a taxonomy term.'),
      'default_widget' => 'options_select',
      'default_formatter' => 'taxonomy_term_reference_link',
      'settings' => array(
        'allowed_values' => array(
          array(
            'vocabulary' => '',
            'parent' => '0',
          ),
        ),
      ),
    ),
  );
}

/**
 * Implements hook_field_widget_info().
 */
function taxonomy_field_widget_info() {
  return array(
    'taxonomy_autocomplete' => array(
      'label' => t('Autocomplete term widget (tagging)'),
      'field types' => array('taxonomy_term_reference'),
      'settings' => array(
        'size' => 60,
        'autocomplete_path' => 'taxonomy/autocomplete',
      ),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
      ),
    ),
  );
}

/**
 * Implements hook_field_widget_info_alter().
 */
function taxonomy_field_widget_info_alter(&$info) {
  $info['options_select']['field types'][] = 'taxonomy_term_reference';
  $info['options_buttons']['field types'][] = 'taxonomy_term_reference';
}

/**
 * Implements hook_options_list().
 */
function taxonomy_options_list($field) {
  $function = !empty($field['settings']['options_list_callback']) ? $field['settings']['options_list_callback'] : 'taxonomy_allowed_values';
  return $function($field);
}

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

    // Check each existing item to ensure it can be found in the
    // allowed values for this field.
    foreach ($items as $delta => $item) {
      $validate = TRUE;
      if (!empty($item['tid']) && $item['tid'] != 'autocreate') {
        $validate = FALSE;
        foreach ($field['settings']['allowed_values'] as $settings) {
          // If no parent is specified, check if the term is in the vocabulary.
          if (isset($settings['vocabulary']) && empty($settings['parent'])) {
            if ($settings['vocabulary'] == $terms[$item['tid']]->vocabulary_machine_name) {
              $validate = TRUE;
              break;
            }
          }
          // If a parent is specified, then to validate it must appear in the
          // array returned by taxonomy_get_parents_all().
          elseif (!empty($settings['parent'])) {
            $ancestors = taxonomy_get_parents_all($item['tid']);
            foreach ($ancestors as $ancestor) {
              if ($ancestor->tid == $settings['parent']) {
                $validate = TRUE;
                break 2;
              }
            }
          }
        }
      }
      if (!$validate) {
        $errors[$field['field_name']][$langcode][$delta][] = array(
          'error' => 'taxonomy_term_reference_illegal_value',
          'message' => t('%name: illegal value.', array('%name' => t($instance['label']))),
        );
      }
    }
  }
}

/**
 * Implements hook_field_is_empty().
 */
function taxonomy_field_is_empty($item, $field) {
  if (!is_array($item) || (empty($item['tid']) && (string) $item['tid'] !== '0')) {
    return TRUE;
  }
  return FALSE;
}

/**
 * Implements hook_field_formatter_info().
 */
function taxonomy_field_formatter_info() {
  return array(
    'taxonomy_term_reference_link' => array(
      'label' => t('Link'),
      'field types' => array('taxonomy_term_reference'),
    ),
    'taxonomy_term_reference_plain' => array(
      'label' => t('Plain text'),
      'field types' => array('taxonomy_term_reference'),
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function taxonomy_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

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

  switch ($display['type']) {
    case 'taxonomy_term_reference_link':
      foreach ($items as $delta => $item) {
        if ($item['tid'] == 'autocreate') {
          $element[$delta] = array(
            '#markup' => check_plain($item['name']),
          );
        }
        else {
          $term = $item['taxonomy_term'];
          $uri = entity_uri('taxonomy_term', $term);
          $element[$delta] = array(
            '#type' => 'link',
            '#title' => $term->name,
            '#href' => $uri['path'],
            '#options' => $uri['options'],
          );
        }
      }
      break;

    case 'taxonomy_term_reference_plain':
      foreach ($items as $delta => $item) {
        $name = ($item['tid'] != 'autocreate' ? $item['taxonomy_term']->name : $item['name']);
        $element[$delta] = array(
          '#markup' => check_plain($name),
        );
      }
      break;
  }

  return $element;
}

/**
 * Returns the set of valid terms for a taxonomy field.
 *
 * @param $field
 *   The field definition.
 * @return
 *   The array of valid terms for this field, keyed by term id.
 */
function taxonomy_allowed_values($field) {
  $options = array();
  foreach ($field['settings']['allowed_values'] as $tree) {
    if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
      if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'])) {
        foreach ($terms as $term) {
          $options[$term->tid] = str_repeat('-', $term->depth) . $term->name;
        }
      }
    }
  }
  return $options;
}

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

  // Collect every possible term attached to any of the fieldable entities.
  foreach ($entities as $id => $entity) {
    foreach ($items[$id] as $delta => $item) {
      // Force the array key to prevent duplicates.
      if ($item['tid'] != 'autocreate') {
        $tids[$item['tid']] = $item['tid'];
      }
    }
  }
  if ($tids) {
    $terms = taxonomy_term_load_multiple($tids);

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

      foreach ($items[$id] as $delta => $item) {
        // Check whether the taxonomy term field instance value could be loaded.
        if (isset($terms[$item['tid']])) {
          // Replace the instance value with the term data.
          $items[$id][$delta]['taxonomy_term'] = $terms[$item['tid']];
        }
        // Terms to be created are not in $terms, but are still legitimate.
        else if ($item['tid'] == 'autocreate') {
          // Leave the item in place.
        }
        // Otherwise, unset the instance value, since the term does not exist.
        else {
          unset($items[$id][$delta]);
          $rekey = TRUE;
        }
      }

      if ($rekey) {
        // Rekey the items array.
        $items[$id] = array_values($items[$id]);
      }
    }
  }
}

/**
 * Title callback for term pages.
 *
 * @param $term
 *   A term object.
 *
 * @return
 *   The term name to be used as the page title.
 */
function taxonomy_term_title($term) {
  return $term->name;
}

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

  $element += array(
    '#type' => 'textfield',
    '#default_value' => taxonomy_implode_tags($tags),
    '#autocomplete_path' => $instance['widget']['settings']['autocomplete_path'] . '/' . $field['field_name'],
    '#size' => $instance['widget']['settings']['size'],
    '#maxlength' => 1024,
    '#element_validate' => array('taxonomy_autocomplete_validate'),
  );

  return $element;
}

/**
 * Form element validate handler for taxonomy term autocomplete element.
 */
function taxonomy_autocomplete_validate($element, &$form_state) {
  // Autocomplete widgets do not send their tids in the form, so we must detect
  // them here and process them independently.
  $value = array();
  if ($tags = $element['#value']) {
    // Collect candidate vocabularies.
    $field = field_widget_field($element, $form_state);
    $vocabularies = array();
    foreach ($field['settings']['allowed_values'] as $tree) {
      if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
        $vocabularies[$vocabulary->vid] = $vocabulary;
      }
    }

    // Translate term names into actual terms.
    $typed_terms = drupal_explode_tags($tags);
    foreach ($typed_terms as $typed_term) {
      // See if the term exists in the chosen vocabulary and return the tid;
      // otherwise, create a new 'autocreate' term for insert/update.
      if ($possibilities = taxonomy_term_load_multiple(array(), array('name' => trim($typed_term), 'vid' => array_keys($vocabularies)))) {
        $term = array_pop($possibilities);
      }
      else {
        $vocabulary = reset($vocabularies);
        $term = array(
          'tid' => 'autocreate',
          'vid' => $vocabulary->vid,
          'name' => $typed_term,
          'vocabulary_machine_name' => $vocabulary->machine_name,
        );
      }
      $value[] = (array)$term;
    }
  }

  form_set_value($element, $value, $form_state);
}

/**
 * Implements hook_field_widget_error().
 */
function taxonomy_field_widget_error($element, $error, $form, &$form_state) {
  form_error($element, $error['message']);
}
/**
 * Implements hook_field_settings_form().
 */
function taxonomy_field_settings_form($field, $instance, $has_data) {
  // Get proper values for 'allowed_values_function', which is a core setting.
  $vocabularies = taxonomy_get_vocabularies();
  $options = array();
  foreach ($vocabularies as $vocabulary) {
    $options[$vocabulary->machine_name] = $vocabulary->name;
  }
  $form['allowed_values'] = array(
    '#tree' => TRUE,
  );

  foreach ($field['settings']['allowed_values'] as $delta => $tree) {
    $form['allowed_values'][$delta]['vocabulary'] = array(
      '#type' => 'select',
      '#title' => t('Vocabulary'),
      '#default_value' => $tree['vocabulary'],
      '#options' => $options,
      '#required' => TRUE,
      '#description' => t('The vocabulary which supplies the options for this field.'),
      '#disabled' => $has_data,
    );
    $form['allowed_values'][$delta]['parent'] = array(
      '#type' => 'value',
      '#value' => $tree['parent'],
    );
  }

  return $form;
}

/**
 * Implements hook_rdf_mapping().
 *
 * @return array
 *   The rdf mapping for vocabularies and terms.
 */
function taxonomy_rdf_mapping() {
  return array(
    array(
      'type' => 'taxonomy_term',
      'bundle' => RDF_DEFAULT_BUNDLE,
      'mapping' => array(
        'rdftype' => array('skos:Concept'),
        'name'   => array(
          'predicates' => array('rdfs:label', 'skos:prefLabel'),
        ),
        'description'   => array(
          'predicates' => array('skos:definition'),
        ),
        'vid'   => array(
          'predicates' => array('skos:inScheme'),
          'type' => 'rel',
        ),
        'parent'   => array(
          'predicates' => array('skos:broader'),
          'type' => 'rel',
        ),
      ),
    ),
    array(
      'type' => 'taxonomy_vocabulary',
      'bundle' => RDF_DEFAULT_BUNDLE,
      'mapping' => array(
        'rdftype' => array('skos:ConceptScheme'),
        'name'   => array(
          'predicates' => array('dc:title'),
        ),
        'description'   => array(
          'predicates' => array('rdfs:comment'),
        ),
      ),
    ),
  );
}

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

/**
 * Implements hook_field_presave().
 *
 * Create any new terms defined in a freetagging vocabulary.
 */
function taxonomy_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  foreach ($items as $delta => $item) {
    if ($item['tid'] == 'autocreate') {
      $term = (object) $item;
      unset($term->tid);
      taxonomy_term_save($term);
      $items[$delta]['tid'] = $term->tid;
    }
  }
}

/**
 * Implements hook_field_insert().
 */
function taxonomy_field_insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
  // We maintain a denormalized table of term/node relationships, containing
  // only data for current, published nodes.
  if (variable_get('taxonomy_maintain_index_table', TRUE) && $field['storage']['type'] == 'field_sql_storage' && $entity_type == 'node' && $entity->status) {
    $query = db_insert('taxonomy_index')->fields(array('nid', 'tid', 'sticky', 'created', ));
    foreach ($items as $item) {
      $query->values(array(
        'nid' => $entity->nid,
        'tid' => $item['tid'],
        'sticky' => $entity->sticky,
        'created' => $entity->created,
      ));
    }
    $query->execute();
  }
}

/**
 * Implements hook_field_update().
 */
function taxonomy_field_update($entity_type, $entity, $field, $instance, $langcode, &$items) {
  if (variable_get('taxonomy_maintain_index_table', TRUE) && $field['storage']['type'] == 'field_sql_storage' && $entity_type == 'node') {
    $first_call = &drupal_static(__FUNCTION__, array());

    // We don't maintain data for old revisions, so clear all previous values
    // from the table. Since this hook runs once per field, per object, make
    // sure we only wipe values once.
    if (!isset($first_call[$entity->nid])) {
      $first_call[$entity->nid] = FALSE;
      db_delete('taxonomy_index')->condition('nid', $entity->nid)->execute();
    }
    // Only save data to the table if the node is published.
    if ($entity->status) {
      $query = db_insert('taxonomy_index')->fields(array('nid', 'tid', 'sticky', 'created'));
      foreach ($items as $item) {
        $query->values(array(
          'nid' => $entity->nid,
          'tid' => $item['tid'],
          'sticky' => $entity->sticky,
          'created' => $entity->created,
        ));
      }
      $query->execute();
    }
  }
}

/**
 * Implements hook_node_delete().
 */
function taxonomy_node_delete($node) {
  if (variable_get('taxonomy_maintain_index_table', TRUE)) {
    // Clean up the {taxonomy_index} table when nodes are deleted.
    db_delete('taxonomy_index')->condition('nid', $node->nid)->execute();
  }
}

/**
 * Implements hook_taxonomy_term_delete().
 */
function taxonomy_taxonomy_term_delete($term) {
  if (variable_get('taxonomy_maintain_index_table', TRUE)) {
    // Clean up the {taxonomy_index} table when terms are deleted.
    db_delete('taxonomy_index')->condition('tid', $term->tid)->execute();
  }
}

/**
 * @} End of "defgroup taxonomy_index"
 */