summaryrefslogtreecommitdiff
path: root/modules/taxonomy/taxonomy.module
blob: f2cfa376e5412c4bf87d931503b2b1817a984a99 (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
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
<?php
// $Id$

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

/**
 * Implement hook_permission().
 */
function taxonomy_permission() {
  return array(
    'administer taxonomy' => array(
      'title' => t('Administer taxonomy'),
      'description' => t('Manage taxonomy vocabularies and terms.'),
    ),
  );
}

/**
 * Implement hook_fieldable_info().
 */
function taxonomy_fieldable_info() {
  $return = array(
    'taxonomy_term' => array(
      'label' => t('Taxonomy term'),
      'object keys' => array(
        'id' => 'tid',
        'bundle' => 'vocabulary_machine_name',
      ),
      'bundle keys' => array(
        'bundle' => 'machine_name',
      ),
      'bundles' => array(),
    ),
  );
  foreach (taxonomy_get_vocabularies() as $vocabulary) {
    $return['taxonomy_term']['bundles'][$vocabulary->machine_name] = array(
      'label' => $vocabulary->name,
      'admin' => array(
        'path' => 'admin/structure/taxonomy/%taxonomy_vocabulary',
        'real path' => 'admin/structure/taxonomy/' . $vocabulary->vid,
        'bundle argument' => 3,
        'access arguments' => array('administer taxonomy'),
      ),
    );
  }
  return $return;
}

/**
 * Implement hook_field_build_modes();
 *
 * @TODO: build mode for display as a field (when attached to nodes etc.).
 */
function taxonomy_field_build_modes($obj_type) {
  $modes = array();
  if ($obj_type == 'term') {
    $modes = array(
      'full' => t('Taxonomy term page'),
    );
  }
  return $modes;
}

/**
 * Implement hook_field_extra_fields().
 */
function taxonomy_field_extra_fields($bundle) {
  $extra = array();

  if ($type = node_type_get_type($bundle)) {
    if (taxonomy_get_vocabularies($bundle)) {
      $extra['taxonomy'] = array(
        'label' => t('Taxonomy'),
        'description' => t('Taxonomy module element.'),
        'weight' => -3,
      );
    }
  }

  return $extra;
}

/**
 * Implement hook_theme().
 */
function taxonomy_theme() {
  return array(
    'taxonomy_term_select' => array(
      'arguments' => array('element' => NULL),
    ),
    'taxonomy_overview_vocabularies' => array(
      'arguments' => array('form' => array()),
    ),
    'taxonomy_overview_terms' => array(
      'arguments' => array('form' => array()),
    ),
    'field_formatter_taxonomy_term_link' => array(
      'arguments' => array('element' => NULL),
    ),
    'field_formatter_taxonomy_term_plain' => array(
      'arguments' => array('element' => NULL),
    ),
    'taxonomy_autocomplete' => array(
      'arguments' => array('element' => NULL),
    ),
  );
}

/**
 * Implement hook_node_view().
 */
function taxonomy_node_view($node, $build_mode) {
  if (empty($node->taxonomy)) {
    return;
  }

  if ($build_mode == 'rss') {
    // Provide category information for RSS feeds.
    foreach ($node->taxonomy as $term) {
      $node->rss_elements[] = array(
        'key' => 'category',
        'value' => $term->name,
        'attributes' => array('domain' => url(taxonomy_term_path($term), array('absolute' => TRUE))),
      );
    }
  }
  else {
    $links = array();

    // If previewing, the terms must be converted to objects first.
    if (!empty($node->in_preview)) {
      $node->taxonomy = taxonomy_preview_terms($node);
    }

    foreach ($node->taxonomy as $term) {
      // During preview the free tagging terms are in an array unlike the
      // other terms which are objects. So we have to check if a $term
      // is an object or not.
      if (is_object($term)) {
        $links['taxonomy_term_' . $term->tid] = array(
          'title' => $term->name,
          'href' => taxonomy_term_path($term),
          'attributes' => array('rel' => 'tag', 'title' => strip_tags($term->description))
        );
      }
      // Previewing free tagging terms; we don't link them because the
      // term-page might not exist yet.
      else {
        foreach ($term as $free_typed) {
          $typed_terms = drupal_explode_tags($free_typed);
          foreach ($typed_terms as $typed_term) {
            $links['taxonomy_preview_term_' . $typed_term] = array(
              'title' => $typed_term,
            );
          }
        }
      }
    }

    $node->content['links']['terms'] = array(
      '#theme' => 'links',
      '#links' => $links,
      '#attributes' => array('class' => array('links', 'inline')),
      '#sorted' => TRUE,
    );
  }
}

/**
 * For vocabularies not maintained by taxonomy.module, give the maintaining
 * module a chance to provide a path for terms in that vocabulary.
 *
 * @param $term
 *   A term object.
 * @return
 *   An internal Drupal path.
 */
function taxonomy_term_path($term) {
  $vocabulary = taxonomy_vocabulary_load($term->vid);
  if ($vocabulary->module != 'taxonomy' && $path = module_invoke($vocabulary->module, 'term_path', $term)) {
    return $path;
  }
  return 'taxonomy/term/' . $term->tid;
}

/**
 * Implement 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'),
  );

  $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,
  );

  $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'),
    'type' => MENU_CALLBACK,
  );

  $items['taxonomy/term/%taxonomy_term/view'] = array(
    'title' => 'View',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  $items['taxonomy/term/%taxonomy_term/edit'] = array(
    'title' => 'Edit term',
    'page callback' => 'taxonomy_term_edit',
    'page arguments' => array(2),
    'access arguments' => array('administer taxonomy'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
  );
  $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,
  );
  $items['taxonomy/autocomplete'] = array(
    'title' => 'Autocomplete taxonomy',
    'page callback' => 'taxonomy_autocomplete',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  // TODO: remove with taxonomy_term_node_*
  $items['taxonomy/autocomplete/legacy'] = array(
    'title' => 'Autocomplete taxonomy',
    'page callback' => 'taxonomy_autocomplete_legacy',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  $items['admin/structure/taxonomy/%taxonomy_vocabulary'] = array(
    'title' => 'Vocabulary', // this is replaced by callback
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_form_vocabulary', 3),
    'title callback' => 'taxonomy_admin_vocabulary_title_callback',
    'title arguments' => array(3),
    'access arguments' => array('administer taxonomy'),
    'type' => MENU_CALLBACK,
  );

  $items['admin/structure/taxonomy/%taxonomy_vocabulary/edit'] = array(
    'title' => 'Edit vocabulary',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -20,
  );

  $items['admin/structure/taxonomy/%taxonomy_vocabulary/list'] = array(
    'title' => 'List terms',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('taxonomy_overview_terms', 3),
    'access arguments' => array('administer taxonomy'),
    'type' => MENU_LOCAL_TASK,
    'weight' => -10,
  );

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

  return $items;
}

/**
 * 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) {
  if (empty($vocabulary->nodes)) {
    $vocabulary->nodes = array();
  }

  if (!empty($vocabulary->name)) {
    // Prevent leading and trailing spaces in vocabulary names.
    $vocabulary->name = trim($vocabulary->name);
  }

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

  if (!empty($vocabulary->vid) && !empty($vocabulary->name)) {
    $status = drupal_write_record('taxonomy_vocabulary', $vocabulary, 'vid');
    db_delete('taxonomy_vocabulary_node_type')
      ->condition('vid', $vocabulary->vid)
      ->execute();

    if (!empty($vocabulary->nodes)) {
      $query = db_insert('taxonomy_vocabulary_node_type')
        ->fields(array('vid', 'type'));
      foreach ($vocabulary->nodes as $type => $selected) {
        $query->values(array(
          'vid' => $vocabulary->vid,
          'type' => $type,
        ));
      }
      $query->execute();
    }
    module_invoke_all('taxonomy_vocabulary_update', $vocabulary);
  }
  elseif (empty($vocabulary->vid)) {
    $status = drupal_write_record('taxonomy_vocabulary', $vocabulary);

    if (!empty($vocabulary->nodes)) {
      $query = db_insert('taxonomy_vocabulary_node_type')
        ->fields(array('vid', 'type'));
      foreach ($vocabulary->nodes as $type => $selected) {
        $query->values(array(
          'vid' => $vocabulary->vid,
          'type' => $type,
        ));
      }
      $query->execute();
    }
    field_attach_create_bundle($vocabulary->machine_name);
    module_invoke_all('taxonomy_vocabulary_insert', $vocabulary);
  }

  cache_clear_all();
  drupal_static_reset('taxonomy_vocabulary_load_multiple');

  return $status;
}

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

  db_delete('taxonomy_vocabulary')
    ->condition('vid', $vid)
    ->execute();
  db_delete('taxonomy_vocabulary_node_type')
    ->condition('vid', $vid)
    ->execute();
  $result = db_query('SELECT tid FROM {taxonomy_term_data} WHERE vid = :vid', array(':vid' => $vid))->fetchCol();
  foreach ($result as $tid) {
    taxonomy_term_delete($tid);
  }

  field_attach_delete_bundle($vocabulary['machine_name']);
  module_invoke_all('taxonomy', 'delete', 'vocabulary', $vocabulary);

  cache_clear_all();
  drupal_static_reset('taxonomy_vocabulary_load_multiple');

  return SAVED_DELETED;
}

/**
 * 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) {
  if ($term->name) {
    // 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;
  }

  field_attach_presave('taxonomy_term', $term);

  if (!empty($term->tid) && $term->name) {
    $status = drupal_write_record('taxonomy_term_data', $term, 'tid');
    field_attach_update('taxonomy_term', $term);
    module_invoke_all('taxonomy_term_update', $term);
  }
  else {
    $status = drupal_write_record('taxonomy_term_data', $term);
    _taxonomy_clean_field_cache($term);
    field_attach_insert('taxonomy_term', $term);
    module_invoke_all('taxonomy_term_insert', $term);
  }

  db_delete('taxonomy_term_hierarchy')
    ->condition('tid', $term->tid)
    ->execute();

  if (!isset($term->parent) || empty($term->parent)) {
    $term->parent = array(0);
  }
  $query = db_insert('taxonomy_term_hierarchy')
    ->fields(array('tid', 'parent'));
  if (is_array($term->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
        ));
      }
    }
  }
  else {
    $query->values(array(
     'tid' => $term->tid,
     'parent' => $parent
    ));
  }
  $query->execute();

  db_delete('taxonomy_term_synonym')
    ->condition('tid', $term->tid)
    ->execute();
  if (!empty($term->synonyms)) {
    $query = db_insert('taxonomy_term_synonym')
      ->fields(array('tid', 'name'));
    foreach (explode ("\n", str_replace("\r", '', $term->synonyms)) as $synonym) {
      if ($synonym) {
        $query->values(array(
          'tid' => $term->tid,
          'name' => rtrim($synonym)
        ));
      }
    }
    $query->execute();
  }

  cache_clear_all();
  taxonomy_terms_static_reset();

  return $status;
}

/**
 * Delete a term.
 *
 * @param $tid
 *   The term ID.
 * @return
 *   Status constant indicating deletion.
 */
function taxonomy_term_delete($tid) {
  $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;
          }
        }
      }

      $term = taxonomy_term_load($tid);

      db_delete('taxonomy_term_data')
        ->condition('tid', $tid)
        ->execute();
      db_delete('taxonomy_term_hierarchy')
        ->condition('tid', $tid)
        ->execute();
      db_delete('taxonomy_term_synonym')
        ->condition('tid', $tid)
        ->execute();
      db_delete('taxonomy_term_node')
        ->condition('tid', $tid)
        ->execute();

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

    $tids = $orphans;
  }

  cache_clear_all();
  taxonomy_terms_static_reset();

  return SAVED_DELETED;
}

/**
 * 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_synonym_root');
  drupal_static_reset('taxonomy_term_load_multiple');
}

/**
 * Generate a form element for selecting terms from a vocabulary.
 *
 * @param $vid
 *   The vocabulary ID to generate a form element for
 * @param $value
 *   The existing value of the term(s) in this vocabulary to use by default.
 * @param $help
 *   Optional help text to use for the form element. If specified, this value
 *   MUST be properly sanitized and filtered (e.g. with filter_xss_admin() or
 *   check_plain() if it is user-supplied) to prevent XSS vulnerabilities. If
 *   omitted, the help text stored with the vocaulary (if any) will be used.
 * @return
 *   An array describing a form element to select terms for a vocabulary.
 *
 * @see _taxonomy_term_select()
 * @see filter_xss_admin()
 */
function taxonomy_form($vid, $value = 0, $help = NULL) {
  $vocabulary = taxonomy_vocabulary_load($vid);
  $help = ($help) ? $help : filter_xss_admin($vocabulary->help);

  if (!$vocabulary->multiple) {
    $blank = ($vocabulary->required) ? t('- Please choose -') : t('- None selected -');
  }
  else {
    $blank = ($vocabulary->required) ? 0 : t('- None -');
  }

  return _taxonomy_term_select(check_plain($vocabulary->name), $value, $vid, $help, intval($vocabulary->multiple), $blank);
}

/**
 * Generate a set of options for selecting a term from all vocabularies.
 */
function taxonomy_form_all($free_tags = 0) {
  $vocabularies = taxonomy_get_vocabularies();
  $options = array();
  foreach ($vocabularies as $vid => $vocabulary) {
    if ($vocabulary->tags && !$free_tags) {
      continue;
    }
    $tree = taxonomy_get_tree($vid);
    if ($tree && (count($tree) > 0)) {
      $options[$vocabulary->name] = array();
      foreach ($tree as $term) {
        $options[$vocabulary->name][$term->tid] = str_repeat('-', $term->depth) . $term->name;
      }
    }
  }
  return $options;
}

/**
 * Return an array of all vocabulary objects.
 *
 * @param $type
 *   If set, return only those vocabularies associated with this node type.
 */
function taxonomy_get_vocabularies($type = NULL) {
  $conditions = !empty($type) ? array('type' => $type) : NULL;
  return taxonomy_vocabulary_load_multiple(array(), $conditions);
}

/**
 * Get names for all taxonomy vocabularies.
 *
 * @return
 *   An array of vocabulary names in the format 'machine_name' => 'name'.
 */
function taxonomy_vocabulary_get_names() {
  $names = array();
  $vocabularies = taxonomy_get_vocabularies();
  foreach ($vocabularies as $vocabulary) {
    $names[$vocabulary->machine_name] = $vocabulary->name;
  }
  return $names;
}

/**
 * Implement hook_form_alter().
 * Generate a form for selecting terms to associate with a node.
 * We check for taxonomy_override_selector before loading the full
 * vocabulary, so contrib modules can intercept before hook_form_alter
 *  and provide scalable alternatives.
 */
function taxonomy_form_alter(&$form, $form_state, $form_id) {
  if (!variable_get('taxonomy_override_selector', FALSE) && !empty($form['#node_edit_form'])) {
    $node = $form['#node'];

    if (!isset($node->taxonomy)) {
      $terms = empty($node->nid) ? array() : taxonomy_node_get_terms($node);
    }
    else {
      // After preview the terms must be converted to objects.
      if (isset($form_state['node_preview'])) {
        $node->taxonomy = taxonomy_preview_terms($node);
      }
      $terms = $node->taxonomy;
    }
    $query = db_select('taxonomy_vocabulary', 'v');
    $query->join('taxonomy_vocabulary_node_type', 'n', 'v.vid = n.vid');
    $query->addTag('term_access');

    $result = $query
      ->fields('v')
      ->condition('n.type', $node->type)
      ->orderBy('v.weight')
      ->orderBy('v.name')
      ->execute();

    foreach ($result as $vocabulary) {
      if ($vocabulary->tags) {
        if (isset($form_state['node_preview'])) {
          // Typed string can be changed by the user before preview,
          // so we just insert the tags directly as provided in the form.
          $typed_string = $node->taxonomy['tags'][$vocabulary->vid];
        }
        else {
          $typed_string = taxonomy_implode_tags($terms, $vocabulary->vid) . (array_key_exists('tags', $terms) ? $terms['tags'][$vocabulary->vid] : NULL);
        }
        if ($vocabulary->help) {
          $help = filter_xss_admin($vocabulary->help);
        }
        else {
          $help = t('A comma-separated list of terms describing this content. Example: funny, bungee jumping, "Company, Inc."');
        }
        $form['taxonomy']['tags'][$vocabulary->vid] = array('#type' => 'textfield',
          '#title' => $vocabulary->name,
          '#description' => $help,
          '#required' => $vocabulary->required,
          '#default_value' => $typed_string,
          '#autocomplete_path' => 'taxonomy/autocomplete/legacy/' . $vocabulary->vid,
          '#weight' => $vocabulary->weight,
          '#maxlength' => 1024,
        );
      }
      else {
        // Extract terms belonging to the vocabulary in question.
        $default_terms = array();
        foreach ($terms as $term) {
          // Free tagging has no default terms and also no vid after preview.
          if (isset($term->vid) && $term->vid == $vocabulary->vid) {
            $default_terms[$term->tid] = $term;
          }
        }
        $form['taxonomy'][$vocabulary->vid] = taxonomy_form($vocabulary->vid, array_keys($default_terms), filter_xss_admin($vocabulary->help));
        $form['taxonomy'][$vocabulary->vid]['#weight'] = $vocabulary->weight;
        $form['taxonomy'][$vocabulary->vid]['#required'] = $vocabulary->required;
      }
    }
    if (!empty($form['taxonomy']) && is_array($form['taxonomy'])) {
      if (count($form['taxonomy']) > 1) {
        // Add fieldset only if form has more than 1 element.
        $form['taxonomy'] += array(
          '#type' => 'fieldset',
          '#title' => t('Vocabularies'),
          '#collapsible' => TRUE,
          '#collapsed' => FALSE,
        );
      }
      $form['taxonomy']['#weight'] = -3;
      $form['taxonomy']['#tree'] = TRUE;
    }
  }
}

/**
 * Helper function to convert terms after a preview.
 *
 * After preview the tags are an array instead of proper objects. This function
 * converts them back to objects with the exception of 'free tagging' terms,
 * because new tags can be added by the user before preview and those do not
 * yet exist in the database. We therefore save those tags as a string so
 * we can fill the form again after the preview.
 */
function taxonomy_preview_terms($node) {
  $taxonomy = array();
  if (isset($node->taxonomy)) {
    foreach ($node->taxonomy as $key => $term) {
      unset($node->taxonomy[$key]);
      // A 'Multiple select' and a 'Free tagging' field returns an array.
      if (is_array($term)) {
        foreach ($term as $tid) {
          if ($key == 'tags') {
            // Free tagging; the values will be saved for later as strings
            // instead of objects to fill the form again.
            $taxonomy['tags'] = $term;
          }
          else {
            $taxonomy[$tid] = taxonomy_term_load($tid);
          }
        }
      }
      // A 'Single select' field returns the term id.
      elseif ($term) {
        $taxonomy[$term] = taxonomy_term_load($term);
      }
    }
  }
  return $taxonomy;
}

/**
 * Find all terms associated with the given node, within one vocabulary.
 */
function taxonomy_node_get_terms_by_vocabulary($node, $vid, $key = 'tid') {
  $query = db_select('taxonomy_term_data', 't');
  $query->join('taxonomy_term_node', 'r', 'r.tid = t.tid');
  $query->addTag('term_access');

  $result = $query
    ->fields('t')
    ->condition('t.vid', $vid)
    ->condition('r.vid', $node->vid)
    ->orderBy('weight')
    ->execute();

  $terms = array();
  foreach ($result as $term) {
    $terms[$term->$key] = $term;
  }
  return $terms;
}

/**
 * Find all term IDs associated with a set of nodes.
 *
 * @param $nodes
 *  An array of node objects.
 *
 * @return
 *  An array of term and node IDs ordered by vocabulary and term weight.
 */
function taxonomy_get_tids_from_nodes($nodes) {
  $node_vids = array();
  foreach ($nodes as $node) {
    $node_vids[] = $node->vid;
  }
  $query = db_select('taxonomy_term_node', 'r');
  $query->join('taxonomy_term_data', 't', 'r.tid = t.tid');
  $query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');
  $query->addTag('term_access');

  return $query
    ->fields('r', array('tid', 'nid', 'vid'))
    ->condition('r.vid', $node_vids, 'IN')
    ->orderBy('v.weight')
    ->orderBy('t.weight')
    ->orderBy('t.name')
    ->execute()
    ->fetchAll();
}

/**
 * Find all terms associated with the given node, ordered by vocabulary and term weight.
 */
function taxonomy_node_get_terms($node, $key = 'tid') {
  $terms = &drupal_static(__FUNCTION__);

  if (!isset($terms[$node->vid][$key])) {
    $query = db_select('taxonomy_term_node', 'r');
    $query->join('taxonomy_term_data', 't', 'r.tid = t.tid');
    $query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');
    $query->addTag('term_access');

    $result = $query
      ->fields('r', array('tid', 'nid', 'vid'))
      ->condition('r.vid', $node->vid)
      ->orderBy('v.weight')
      ->orderBy('t.weight')
      ->orderBy('t.name')
      ->execute();
    $terms[$node->vid][$key] = array();
    foreach ($result as $term) {
      $terms[$node->vid][$key][$term->$key] = $term;
    }
  }
  return $terms[$node->vid][$key];
}

/**
 * Save term associations for a given node.
 */
function taxonomy_node_save($node, $terms) {

  taxonomy_node_delete_revision($node);

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

    foreach ($typed_input as $vid => $vid_value) {
      $vocabulary = taxonomy_vocabulary_load($vid);
      $typed_terms = drupal_explode_tags($vid_value);

      $inserted = array();
      foreach ($typed_terms as $typed_term) {
        // See if the term exists in the chosen vocabulary
        // and return the tid; otherwise, add a new record.
        $possibilities = taxonomy_get_term_by_name($typed_term);
        $typed_term_tid = NULL; // tid match, if any.
        foreach ($possibilities as $possibility) {
          if ($possibility->vid == $vid) {
            $typed_term_tid = $possibility->tid;
          }
        }

        if (!$typed_term_tid) {
          $edit = array(
            'vid' => $vid,
            'name' => $typed_term,
            'vocabulary_machine_name' => $vocabulary->machine_name,
          );
          $term = (object)$edit;
          $status = taxonomy_term_save($term);
          $typed_term_tid = $term->tid;
        }

        // Defend against duplicate, differently cased tags
        if (!isset($inserted[$typed_term_tid])) {
          db_insert('taxonomy_term_node')
            ->fields(array(
              'nid' => $node->nid,
              'vid' => $node->vid,
              'tid' => $typed_term_tid
            ))
            ->execute();
          $inserted[$typed_term_tid] = TRUE;
        }
      }
    }
  }

  if (is_array($terms) && !empty($terms)) {
    $query = db_insert('taxonomy_term_node')
      ->fields(array('nid', 'vid', 'tid'));

    foreach ($terms as $term) {
      if (is_array($term)) {
        foreach ($term as $tid) {
          if ($tid) {
            $query->values(array(
              'nid' => $node->nid,
              'vid' => $node->vid,
              'tid' => $tid,
            ));
          }
        }
      }
      elseif (is_object($term)) {
        $query->values(array(
          'nid' => $node->nid,
          'vid' => $node->vid,
          'tid' => $term->tid,
        ));
      }
      elseif ($term) {
        $query->values(array(
          'nid' => $node->nid,
          'vid' => $node->vid,
          'tid' => $term,
        ));
      }
    }
    $query->execute();
  }
}

/**
 * Implement hook_node_type_insert().
 */
function taxonomy_node_type_insert($info) {
  drupal_static_reset('taxonomy_term_count_nodes');
}

/**
 * Implement hook_node_type_update().
 */
function taxonomy_node_type_update($info) {
  if (!empty($info->old_type) && $info->type != $info->old_type) {
    db_update('taxonomy_vocabulary_node_type')
      ->fields(array(
        'type' => $info->type,
      ))
      ->condition('type', $info->old_type)
      ->execute();
  }
  drupal_static_reset('taxonomy_term_count_nodes');
}

/**
 * Implement hook_node_type_delete().
 */
function taxonomy_node_type_delete($info) {
  db_delete('taxonomy_vocabulary_node_type')
    ->condition('type', $info->type)
    ->execute();

  drupal_static_reset('taxonomy_term_count_nodes');
}

/**
 * Find all parents of a given term ID.
 */
function taxonomy_get_parents($tid, $key = 'tid') {
  if ($tid) {
    $query = db_select('taxonomy_term_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.parent = t.tid');
    $query->addTag('term_access');

    $result = $query
      ->fields('t')
      ->condition('h.tid', $tid)
      ->orderBy('weight')
      ->orderBy('name')
      ->execute();
    $parents = array();
    foreach ($result as $parent) {
      $parents[$parent->$key] = $parent;
    }
    return $parents;
  }
  else {
    return array();
  }
}

/**
 * Find all ancestors of a given term ID.
 */
function taxonomy_get_parents_all($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++;
    }
  }
  return $parents;
}

/**
 * Find all children of a term ID.
 */
function taxonomy_get_children($tid, $vid = 0, $key = 'tid') {
  $query = db_select('taxonomy_term_data', 't');
  $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
  $query->addTag('term_access');

  $query
    ->fields('t')
    ->condition('parent', $tid)
    ->orderBy('weight')
    ->orderBy('name');
  if ($vid) {
    $query->condition('t.vid', $vid);
  }
  $result = $query->execute();

  $children = array();
  foreach ($result as $term) {
    $children[$term->$key] = $term;
  }
  return $children;
}

/**
 * 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 $depth
 *   Internal use only.
 *
 * @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.
 */
function taxonomy_get_tree($vid, $parent = 0, $max_depth = NULL, $depth = -1) {
  $children = &drupal_static(__FUNCTION__, array());
  $parents = &drupal_static(__FUNCTION__ . 'parents', array());
  $terms = &drupal_static(__FUNCTION__ . 'terms', array());

  $depth++;

  // 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');
    $query->addTag('term_access');

    $result = $query
      ->fields('t')
      ->fields('h', array('parent'))
      ->condition('t.vid', $vid)
      ->orderBy('weight')
      ->orderBy('name')
      ->execute();
    foreach ($result as $term) {
      $children[$vid][$term->parent][] = $term->tid;
      $parents[$vid][$term->tid][] = $term->parent;
      $terms[$vid][$term->tid] = $term;
    }
  }

  $max_depth = (is_null($max_depth)) ? count($children[$vid]) : $max_depth;
  $tree = array();
  if ($max_depth > $depth && !empty($children[$vid][$parent])) {
    foreach ($children[$vid][$parent] as $child) {
      $term = clone $terms[$vid][$child];
      $term->depth = $depth;
      // The "parent" attribute is not useful, as it would show one parent only.
      unset($term->parent);
      $term->parents = $parents[$vid][$child];
      $tree[] = $term;
      if (!empty($children[$vid][$child])) {
        $tree = array_merge($tree, taxonomy_get_tree($vid, $child, $max_depth, $depth));
      }
    }
  }

  return $tree;
}

/**
 * Return an array of synonyms of the given term ID.
 */
function taxonomy_get_synonyms($tid) {
  if ($tid) {
    $synonyms = array();
    return db_query('SELECT name FROM {taxonomy_term_synonym} WHERE tid = :tid', array(':tid' => $tid))->fetchCol();
  }
  else {
    return array();
  }
}

/**
 * Return the term object that has the given string as a synonym.
 *
 * @param $synonym
 *   The string to compare against.
 * @return
 *   A term object, or FALSE if no matching term is found.
 */
function taxonomy_get_synonym_root($synonym) {
  $synonyms = &drupal_static(__FUNCTION__, array());

  if (!isset($synonyms[$synonym])) {
    $synonyms[$synonym] = db_query("SELECT * FROM {taxonomy_term_synonym} s, {taxonomy_term_data} t WHERE t.tid = s.tid AND s.name = :name", array(':name' => $synonym))->fetch();
  }
  return $synonyms[$synonym];
}

/**
 * Count the number of published nodes classified by a term.
 *
 * @param $tid
 *   The term ID
 * @param $type
 *   (Optional) The $node->type. If given, taxonomy_term_count_nodes only counts
 *   nodes of $type that are classified with the term $tid.
 *
 * @return
 *   An integer representing a number of nodes.
 *   Results are statically cached.
 */
function taxonomy_term_count_nodes($tid, $type = NULL) {
  $count = &drupal_static(__FUNCTION__, array());
  // Reset the taxonomy tree when first called (or if reset).
  if (empty($count)) {
    drupal_static_reset('taxonomy_get_tree');
  }
  // If $type is NULL, change it to 0 to allow it to be used as an array key
  // for the static cache.
  $type = empty($type) ? 0 : $type;

  if (!isset($count[$type][$tid])) {
    $term = taxonomy_term_load($tid);
    $tree = taxonomy_get_tree($term->vid, $tid, NULL);
    $tids = array($tid);
    foreach ($tree as $descendent) {
      $tids[] = $descendent->tid;
    }

    $query = db_select('taxonomy_term_node', 't');
    $query->addExpression('COUNT(DISTINCT(n.nid))', 'nid_count');
    $query->join('node', 'n', 't.vid = n.vid');
    $query->condition('t.tid', $tids, 'IN');
    $query->condition('n.status', 1);
    if (!is_numeric($type)) {
      $query->condition('n.type', $type);
    }
    $query->addTag('term_access');
    $count[$type][$tid] = $query->execute()->fetchField();
  }
  return $count[$type][$tid];
}

/**
 * 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)));
}

/**
 * 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.
 *
 * @param $vids
 *  An array of taxonomy vocabulary IDs.
 * @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()) {
  $vocabulary_cache = &drupal_static(__FUNCTION__, array());
  // Node type associations are not stored in the vocabulary table, so remove
  // this from conditions into it's own variable.
  if (isset($conditions['type'])) {
    $type = $conditions['type'];
    unset($conditions['type']);
  }

  $vocabularies = array();

  // Create a new variable which is either a prepared version of the $vids
  // array for later comparison with the term cache, or FALSE if no $vids were
  // passed. The $vids array is reduced as items are loaded from cache, and we
  // need to know if it's empty for this reason to avoid querying the database
  // when all requested items are loaded from cache.
  $passed_vids = !empty($vids) ? array_flip($vids) : FALSE;

  // Load any available items from the internal cache.
  if ($vocabulary_cache) {
    if ($vids) {
      $vocabularies += array_intersect_key($vocabulary_cache, $passed_vids);
      // If any items were loaded, remove them from the $vids still to load.
      $vids = array_keys(array_diff_key($passed_vids, $vocabularies));
    }
    // If only conditions is passed, load all items from the cache. Items
    // which don't match conditions will be removed later.
    elseif ($conditions) {
      $vocabularies = $vocabulary_cache;
    }
  }

  // Remove any loaded terms from the array if they don't match $conditions.
  if ($conditions || isset($type)) {
    foreach ($vocabularies as $vocabulary) {
      $vocabulary_values = (array) $vocabulary;
      if (array_diff_assoc($conditions, $vocabulary_values)) {
        unset($vocabularies[$vocabulary->vid]);
      }
      if (isset($type) && !in_array($type, $vocabulary->nodes)) {
        unset($vocabularies[$vocabulary->vid]);
      }
    }
  }

  // Load any remaining vocabularies from the database, this is necessary if
  // we have $vids still to load, or if no $vids were passed.
  if ($vids || !$passed_vids) {
    $query = db_select('taxonomy_vocabulary', 'v');
    $query->addField('n', 'type');
    $query
      ->fields('v')
      ->orderBy('v.weight')
      ->orderBy('v.name')
      ->addTag('vocabulary_access');

    if (!empty($type)) {
      $query->join('taxonomy_vocabulary_node_type', 'n', 'v.vid = n.vid AND n.type = :type', array(':type' => $type));
    }
    else {
      $query->leftJoin('taxonomy_vocabulary_node_type', 'n', 'v.vid = n.vid');
    }

    // If the $vids array is populated, add those to the query.
    if ($vids) {
      $query->condition('v.vid', $vids, 'IN');
    }

    // If the conditions array is populated, add those to the query.
    if ($conditions) {
      foreach ($conditions as $field => $value) {
        $query->condition('v.' . $field, $value);
      }
    }
    $result = $query->execute();

    $queried_vocabularies = array();
    $node_types = array();
    foreach ($result as $record) {
      // If no node types are associated with a vocabulary, the LEFT JOIN will
      // return a NULL value for type.
      if (isset($record->type)) {
        $node_types[$record->vid][$record->type] = $record->type;
        unset($record->type);
        $record->nodes = $node_types[$record->vid];
      }
      elseif (!isset($record->nodes)) {
        $record->nodes = array();
      }
      $queried_vocabularies[$record->vid] = $record;
    }

    // Invoke hook_taxonomy_vocabulary_load() on the vocabularies loaded from
    // the database and add them to the static cache.
    if (!empty($queried_vocabularies)) {
      foreach (module_implements('taxonomy_vocabulary_load') as $module) {
        $function = $module . '_taxonomy_vocabulary_load';
        $function($queried_vocabularies);
      }
      $vocabularies += $queried_vocabularies;
      $vocabulary_cache += $queried_vocabularies;
    }
  }

  // Ensure that the returned array is ordered the same as the original $vids
  // array if this was passed in and remove any invalid vids.
  if ($passed_vids) {
    // Remove any invalid vids from the array.
    $passed_vids = array_intersect_key($passed_vids, $vocabularies);
    foreach ($vocabularies as $vocabulary) {
      $passed_vids[$vocabulary->vid] = $vocabulary;
    }
    $vocabularies = $passed_vids;
  }

  return $vocabularies;
}

/**
 * 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) {
  return reset(taxonomy_vocabulary_load_multiple(array($vid), array()));
}

/**
 * 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.
 *
 * @param $tids
 *  An array of taxonomy term IDs.
 * @param $conditions
 *  An array of conditions to add to the query.
 *
 * @return
 *  An array of term objects, indexed by tid.
 */
function taxonomy_term_load_multiple($tids = array(), $conditions = array()) {
  $term_cache = &drupal_static(__FUNCTION__, array());

  // Node type associations are not stored in the taxonomy_term_data table, so
  // remove this from conditions into it's own variable.
  if (isset($conditions['type'])) {
    $type = $conditions['type'];
    unset($conditions['type']);
  }

  $terms = array();

  // Create a new variable which is either a prepared version of the $tids
  // array for later comparison with the term cache, or FALSE if no $tids were
  // passed. The $tids array is reduced as items are loaded from cache, and we
  // need to know if it's empty for this reason to avoid querying the database
  // when all requested terms are loaded from cache.
  $passed_tids = !empty($tids) ? array_flip($tids) : FALSE;

  // Load any available terms from the internal cache.
  if ($term_cache) {
    if ($tids) {
      $terms += array_intersect_key($term_cache, $passed_tids);
      // If any terms were loaded, remove them from the $tids still to load.
      $tids = array_keys(array_diff_key($passed_tids, $terms));
    }
    // If only conditions is passed, load all terms from the cache. Terms
    // which don't match conditions will be removed later.
    elseif ($conditions) {
      $terms = $term_cache;
    }
  }

  // Remove any loaded terms from the array if they don't match $conditions.
  if ($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]);
      }
      elseif (array_diff_assoc($conditions, $term_values)) {
        unset($terms[$term->tid]);
      }
    }
  }

  // Load any remaining terms from the database, this is necessary if we have
  // $tids still to load, or if $conditions was passed without $tids.
  if ($tids || ($conditions && !$passed_tids)) {
    $query = db_select('taxonomy_term_data', 't');
    $query->addTag('term_access');
    $query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');
    $taxonomy_term_data = drupal_schema_fields_sql('taxonomy_term_data');
    $query->addField('v', 'machine_name', 'vocabulary_machine_name');
    $query
      ->fields('t', $taxonomy_term_data)
      ->addTag('term_access');

    // If the $tids array is populated, add those to the query.
    if ($tids) {
      $query->condition('t.tid', $tids, 'IN');
    }

    if (!empty($type)) {
      $query->join('taxonomy_vocabulary_node_type', 'n', 't.vid = n.vid AND n.type = :type', array(':type' => $type));
    }

    // If the conditions array is populated, add those to the query.
    if ($conditions) {
      // When name is passed as a condition use LIKE.
      if (isset($conditions['name'])) {
        $query->condition('t.name', $conditions['name'], 'LIKE');
        unset($conditions['name']);
      }
      foreach ($conditions as $field => $value) {
        $query->condition('t.' . $field, $value);
      }
    }
    $queried_terms = $query->execute()->fetchAllAssoc('tid');

    if (!empty($queried_terms)) {

      // Attach fields.
      field_attach_load('taxonomy_term', $queried_terms);

      // Invoke hook_taxonomy_term_load() and add the term objects to the
      // static cache.
      foreach (module_implements('taxonomy_term_load') as $module) {
        $function = $module . '_taxonomy_term_load';
        $function($queried_terms);
      }
      $terms += $queried_terms;
      $term_cache += $queried_terms;
    }
  }

  // Ensure that the returned array is ordered the same as the original $tids
  // array if this was passed in and remove any invalid tids.
  if ($passed_tids) {
    // Remove any invalid tids from the array.
    $passed_tids = array_intersect_key($passed_tids, $terms);
    foreach ($terms as $term) {
      $passed_tids[$term->tid] = $term;
    }
    $terms = $passed_tids;
  }

  return $terms;
}

/**
 * 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;
}

/**
 * Create a select form element for a given taxonomy vocabulary.
 *
 * NOTE: This function expects input that has already been sanitized and is
 * safe for display. Callers must properly sanitize the $title and
 * $description arguments to prevent XSS vulnerabilities.
 *
 * @param $title
 *   The title of the vocabulary. This MUST be sanitized by the caller.
 * @param $value
 *   The currently selected terms from this vocabulary, if any.
 * @param $vocabulary_id
 *   The vocabulary ID to build the form element for.
 * @param $description
 *   Help text for the form element. This MUST be sanitized by the caller.
 * @param $multiple
 *   Boolean to control if the form should use a single or multiple select.
 * @param $blank
 *   Optional form choice to use when no value has been selected.
 * @param $exclude
 *   Optional array of term ids to exclude in the selector.
 * @return
 *   A FAPI form array to select terms from the given vocabulary.
 *
 * @see taxonomy_form()
 * @see taxonomy_form_term()
 */
function _taxonomy_term_select($title, $value, $vocabulary_id, $description, $multiple, $blank, $exclude = array()) {
  $tree = taxonomy_get_tree($vocabulary_id);
  $options = array();

  if ($blank) {
    $options[0] = $blank;
  }
  if ($tree) {
    foreach ($tree as $term) {
      if (!in_array($term->tid, $exclude)) {
        $choice = new stdClass();
        $choice->option = array($term->tid => str_repeat('-', $term->depth) . $term->name);
        $options[] = $choice;
      }
    }
  }

  return array('#type' => 'select',
    '#title' => $title,
    '#default_value' => $value,
    '#options' => $options,
    '#description' => $description,
    '#multiple' => $multiple,
    '#size' => $multiple ? min(9, count($options)) : 0,
    '#weight' => -15,
    '#theme' => 'taxonomy_term_select',
  );
}

/**
 * Format the selection field for choosing terms
 * (by default the default selection field is used).
 *
 * @ingroup themeable
 */
function theme_taxonomy_term_select($element) {
  return theme('select', $element);
}

/**
 * Finds all nodes that match selected taxonomy conditions.
 *
 * @param $tids
 *   An array of term IDs to match.
 * @param $operator
 *   How to interpret multiple IDs in the array. Can be "or" or "and".
 * @param $depth
 *   How many levels deep to traverse the taxonomy tree. Can be a non-negative
 *   integer or "all".
 * @param $pager
 *   Whether the nodes are to be used with a pager (the case on most Drupal
 *   pages) or not (in an XML feed, for example).
 * @param $order
 *   The order clause for the query that retrieve the nodes.
 *   It is important to specifc the table alias (n).
 *
 *   Example:
 *   array('table_alias.field_name' = 'DESC');
 * @return
 *   An array of node IDs.
 */
function taxonomy_select_nodes($tids = array(), $operator = 'or', $depth = 0, $pager = TRUE, $order = array('n.sticky' => 'DESC', 'n.created' =>  'DESC')) {
  if (count($tids) <= 0) {
    return array();
  }
  // For each term ID, generate an array of descendant term IDs to the right depth.
  $descendant_tids = array();
  if ($depth === 'all') {
    $depth = NULL;
  }
  $terms = taxonomy_term_load_multiple($tids);
  foreach ($terms as $term) {
    $tree = taxonomy_get_tree($term->vid, $term->tid, $depth);
    $descendant_tids[] = array_merge(array($term->tid), array_map('_taxonomy_get_tid_from_term', $tree));
  }

  $query = db_select('node', 'n');
  $query->addTag('node_access');
  $query->condition('n.status', 1);

  if ($operator == 'or') {
      $args = call_user_func_array('array_merge', $descendant_tids);
      $query->join('taxonomy_term_node', 'tn', 'n.vid = tn.vid');
      $query->condition('tn.tid', $args, 'IN');
  }
  else {
    foreach ($descendant_tids as $tids) {
      $alias = $query->join('taxonomy_term_node', 'tn', 'n.vid = tn.vid');
      $query->condition($alias . '.tid', $tids, 'IN');
    }
  }

  if ($pager) {
    $count_query = clone $query;
    $count_query->addExpression('COUNT(DISTINCT n.nid)');

    $query = $query
      ->extend('PagerDefault')
      ->limit(variable_get('default_nodes_main', 10));
    $query->setCountQuery($count_query);
  }
  else {
    $query->range(0, variable_get('feed_default_items', 10));
  }

  $query->distinct(TRUE);
  $query->addField('n', 'nid');
  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();
}

/**
 * Implement hook_node_load().
 */
function taxonomy_node_load($nodes) {
  // Get an array of tid, vid associations ordered by vocabulary and term
  // weight.
  $tids = taxonomy_get_tids_from_nodes($nodes);

  // Extract the tids only from this array.
  $term_ids = array();
  foreach ($tids as $term) {
    $term_ids[$term->tid] = $term->tid;
  }

  // Load the full term objects for these tids.
  $terms = taxonomy_term_load_multiple($term_ids);
  foreach ($tids as $term) {
    $nodes[$term->nid]->taxonomy[$term->tid] = $terms[$term->tid];
  }
  foreach ($nodes as $node) {
    if (!isset($nodes[$node->nid]->taxonomy)) {
      $node->taxonomy = array();
    }
  }
}

/**
 * Implement hook_node_insert().
 */
function taxonomy_node_insert($node) {
  if (!empty($node->taxonomy)) {
    taxonomy_node_save($node, $node->taxonomy);
  }
}

/**
 * Implement hook_node_update().
 */
function taxonomy_node_update($node) {
  if (!empty($node->taxonomy)) {
    taxonomy_node_save($node, $node->taxonomy);
  }
}

/**
 * Implement hook_node_delete().
 *
 * Remove associations of a node to its terms.
 */
function taxonomy_node_delete($node) {
  db_delete('taxonomy_term_node')
    ->condition('nid', $node->nid)
    ->execute();
  drupal_static_reset('taxonomy_term_count_nodes');
}

/**
 * Implement hook_node_delete_revision().
 *
 * Remove associations of a node to its terms.
 */
function taxonomy_node_delete_revision($node) {
  db_delete('taxonomy_term_node')
    ->condition('vid', $node->vid)
    ->execute();
  drupal_static_reset('taxonomy_term_count_nodes');
}

/**
 * Implement hook_node_validate().
 *
 * Make sure incoming vids are free tagging enabled.
 */
function taxonomy_node_validate($node, $form) {
  if (!empty($node->taxonomy)) {
    $terms = $node->taxonomy;
    if (!empty($terms['tags'])) {
      foreach ($terms['tags'] as $vid => $vid_value) {
        $vocabulary = taxonomy_vocabulary_load($vid);
        if (empty($vocabulary->tags)) {
          // see form_get_error $key = implode('][', $element['#parents']);
          // on why this is the key
          form_set_error("taxonomy][tags][$vid", t('The %name vocabulary can not be modified in this way.', array('%name' => $vocabulary->name)));
        }
      }
    }
  }
}

/**
 * Implement hook_node_update_index().
 */
function taxonomy_node_update_index($node) {
  $output = array();
  foreach ($node->taxonomy as $term) {
    $output[] = $term->name;
  }
  if (count($output)) {
    return '<strong>(' . implode(', ', $output) . ')</strong>';
  }
}

/**
 * Implement hook_help().
 */
function taxonomy_help($path, $arg) {
  switch ($path) {
    case 'admin/help#taxonomy':
      $output = '<p>' . t('The taxonomy module allows you to categorize content using various systems of classification. Free-tagging vocabularies are created by users on the fly when they submit posts (as commonly found in blogs and social bookmarking applications). Controlled vocabularies allow for administrator-defined short lists of terms as well as complex hierarchies with multiple relationships between different terms. These methods can be applied to different content types and combined together to create a powerful and flexible method of classifying and presenting your content.') . '</p>';
      $output .= '<p>' . t('For example, when creating a recipe site, you might want to classify posts by both the type of meal and preparation time. A vocabulary for each allows you to categorize using each criteria independently instead of creating a tag for every possible combination.') . '</p>';
      $output .= '<p>' . t('Type of Meal: <em>Appetizer, Main Course, Salad, Dessert</em>') . '</p>';
      $output .= '<p>' . t('Preparation Time: <em>0-30mins, 30-60mins, 1-2 hrs, 2hrs+</em>') . '</p>';
      $output .= '<p>' . t("Each taxonomy term (often called a 'category' or 'tag' in other systems) automatically provides lists of posts and a corresponding RSS feed. These taxonomy/term URLs can be manipulated to generate AND and OR lists of posts classified with terms. In our recipe site example, it then becomes easy to create pages displaying 'Main courses', '30 minute recipes', or '30 minute main courses and appetizers' by using terms on their own or in combination with others. There are a significant number of contributed modules which you to alter and extend the behavior of the core module for both display and organization of terms.") . '</p>';
      $output .= '<p>' . t("Terms can also be organized in parent/child relationships from the admin interface. An example would be a vocabulary grouping countries under their parent geo-political regions. The taxonomy module also enables advanced implementations of hierarchy, for example placing Turkey in both the 'Middle East' and 'Europe'.") . '</p>';
      $output .= '<p>' . t('The taxonomy module supports the use of both synonyms and related terms, but does not directly use this functionality. However, optional contributed or custom modules may make full use of these advanced features.') . '</p>';
      $output .= '<p>' . t('For more information, see the online handbook entry for <a href="@taxonomy">Taxonomy module</a>.', array('@taxonomy' => 'http://drupal.org/handbook/modules/taxonomy/')) . '</p>';
      return $output;
    case 'admin/structure/taxonomy':
      $output = '<p>' . t("The taxonomy module allows you to categorize your content using both tags and administrator defined terms. It is a flexible tool for classifying content with many advanced features. To begin, create a 'Vocabulary' to hold one set of terms or tags. You can create one free-tagging vocabulary for everything, or separate controlled vocabularies to define the various properties of your content, for example 'Countries' or 'Colors'.") . '</p>';
      $output .= '<p>' . t('Use the list below to configure and review the vocabularies defined on your site, or to list and manage the terms (tags) they contain. A vocabulary may (optionally) be tied to specific content types as shown in the <em>Type</em> column and, if so, will be displayed when creating or editing posts of that type. Multiple vocabularies tied to the same content type will be displayed in the order shown below. Remember that your changes will not be saved until you click the <em>Save</em> button at the bottom of the page.') . '</p>';
      return $output;
    case 'admin/structure/taxonomy/%/list':
      $vocabulary = taxonomy_vocabulary_load($arg[3]);
      if ($vocabulary->tags) {
        return '<p>' . t('%capital_name is a free-tagging vocabulary. To change the name or description of a term, click the <em>edit</em> link next to the term.', array('%capital_name' => drupal_ucfirst($vocabulary->name))) . '</p>';
      }
      switch ($vocabulary->hierarchy) {
        case 0:
          return '<p>' . t('%capital_name is a flat vocabulary. You may organize the terms in the %name vocabulary by using the handles on the left side of the table. To change the name or description of a term, click the <em>edit</em> link next to the term.', array('%capital_name' => drupal_ucfirst($vocabulary->name), '%name' => $vocabulary->name)) . '</p>';
        case 1:
          return '<p>' . t('%capital_name is a single hierarchy vocabulary. You may organize the terms in the %name vocabulary by using the handles on the left side of the table. To change the name or description of a term, click the <em>edit</em> link next to the term.', array('%capital_name' => drupal_ucfirst($vocabulary->name), '%name' => $vocabulary->name)) . '</p>';
        case 2:
          return '<p>' . t('%capital_name is a multiple hierarchy vocabulary. To change the name or description of a term, click the <em>edit</em> link next to the term. Drag and drop of multiple hierarchies 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>';
      }
    case 'admin/structure/taxonomy/add':
      return '<p>' . t('Define how your vocabulary will be presented to administrators and users, and which content types to categorize with it. Tags allows users to create terms when submitting posts by typing a comma separated list. Otherwise terms are chosen from a select list and can only be created by users with the "administer taxonomy" permission.') . '</p>';
  }
}

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

/**
 * Implode a list of tags of a certain vocabulary into a string.
 */
function taxonomy_implode_tags($tags, $vid = NULL) {
  $typed_tags = array();
  foreach ($tags as $tag) {
    // Extract terms belonging to the vocabulary in question.
    if (is_null($vid) || $tag->vid == $vid) {

      // 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);
}

/**
 * Implement hook_hook_info().
 */
function taxonomy_hook_info() {
  return array(
    'taxonomy' => array(
      'taxonomy' => array(
        'insert' => array(
          'runs when' => t('After saving a new term to the database'),
        ),
        'update' => array(
          'runs when' => t('After saving an updated term to the database'),
        ),
        'delete' => array(
          'runs when' => t('After deleting a term')
        ),
      ),
    ),
  );
}

/**
 * Implement hook_field_info().
 *
 * Field settings:
 * - allowed_values: a list array of one or more vocabulary trees:
 *   - vid: a vocabulary ID.
 *   - 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' => array(
      'label' => t('Taxonomy term'),
      'description' => t('This field stores a reference to a taxonomy term.'),
      'default_widget' => 'options_select',
      'default_formatter' => 'taxonomy_term_link',
      'settings' => array(
        'allowed_values' => array(
          array(
            'vid' => '0',
            'parent' => '0',
          ),
        ),
      ),
    ),
  );
}

/**
 * Implement hook_field_widget_info().
 *
 * We need custom handling of multiple values because we need
 * to combine them into a options list rather than display
 * cardinality elements. We will use the field module's default
 * handling for default values.
 *
 * Callbacks can be omitted if default handing is used.
 * They're included here just so this module can be used
 * as an example for custom modules that might do things
 * differently.
 */
function taxonomy_field_widget_info() {
  return array(
    'taxonomy_autocomplete' => array(
      'label' => t('Autocomplete term widget (tagging)'),
      'field types' => array('taxonomy_term'),
      'settings' => array(
        'size' => 60,
        'autocomplete_path' => 'taxonomy/autocomplete',
      ),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
      ),
    ),
  );
}

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

/**
 * Implement hook_field_schema().
 */
function taxonomy_field_schema($field) {
  return array(
    'columns' => array(
      'value' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => FALSE,
      ),
    ),
    'indexes' => array(
      'value' => array('value'),
    ),
  );
}

/**
 * Implement hook_field_validate().
 *
 * Possible error codes:
 * - 'taxonomy_term_illegal_value': The value is not part of the list of allowed values.
 */
function taxonomy_field_validate($obj_type, $object, $field, $instance, $langcode, $items, &$errors) {
  $allowed_values = taxonomy_allowed_values($field);
  $widget = field_info_widget_types($instance['widget']['type']);
  
  // Check we don't exceed the allowed number of values for widgets with custom
  // behavior for multiple values (taxonomy_autocomplete widget).
  if ($widget['behaviors']['multiple values'] == FIELD_BEHAVIOR_CUSTOM && $field['cardinality'] >= 2) {
    if (count($items) > $field['cardinality']) {
      $errors[$field['field_name']][0][] = array(
        'error' => 'taxonomy_term_illegal_value',
        'message' => t('%name: this field cannot hold more that @count values.', array('%name' => t($instance['label']), '@count' => $field['cardinality'])),
      );
    }
  }

  foreach ($items as $delta => $item) {
    if (!empty($item['value'])) {
      if (!isset($allowed_values[$item['value']])) {
        $errors[$field['field_name']][$delta][] = array(
          'error' => 'taxonomy_term_illegal_value',
          'message' => t('%name: illegal value.', array('%name' => t($instance['label']))),
        );
      }
    }
  }
}

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

/**
 * Implement hook_field_formatter_info().
 */
function taxonomy_field_formatter_info() {
  return array(
    'taxonomy_term_link' => array(
      'label' => t('Link'),
      'field types' => array('taxonomy_term'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
    'taxonomy_term_plain' => array(
      'label' => t('Plain text'),
      'field types' => array('taxonomy_term'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
  );
}

/**
 * Theme function for 'link' term field formatter.
 */
function theme_field_formatter_taxonomy_term_link($element) {
  $term = $element['#item']['taxonomy_term'];
  return l($term->name, taxonomy_term_path($term));
}

/**
 * Theme function for 'plain' term field formatter.
 */
function theme_field_formatter_taxonomy_term_plain($element) {
  $term = $element['#item']['taxonomy_term'];
  return $term->name;
}

/**
 * Create an array of the allowed values for this field.
 *
 * Call the field's allowed_values function to retrieve the allowed
 * values array.
 *
 * @see _taxonomy_term_select()
 */
function taxonomy_allowed_values($field) {
  $options = array();
  foreach ($field['settings']['allowed_values'] as $tree) {
    $terms = taxonomy_get_tree($tree['vid'], $tree['parent']);
    if ($terms) {
      foreach ($terms as $term) {
        $options[$term->tid] = str_repeat('-', $term->depth) . $term->name;
      }
    }
  }
  return $options;
}

/**
 * Implement hook_field_load().
 *
 * This preloads all taxonomy terms for multiple loaded objects at once and
 * unsets values for invalid terms that do not exist.
 */
function taxonomy_field_load($obj_type, $objects, $field, $instances, $langcode, &$items, $age) {
  $tids = array();

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

    // Avoid calling taxonomy_term_load_multiple because it could lead to
    // circular references.
    $query = db_select('taxonomy_term_data', 't');
    $query->fields('t');
    $query->condition('t.tid', $tids, 'IN');
    $query->addTag('term_access');
    $terms = $query->execute()->fetchAllAssoc('tid');

    // Iterate through the fieldable entities again to attach the loaded term data.
    foreach ($objects as $id => $object) {
      foreach ($items[$id] as $delta => $item) {
        // Check whether the taxonomy term field instance value could be loaded.
        if (isset($terms[$item['value']])) {
          // Replace the instance value with the term data.
          $items[$id][$delta]['taxonomy_term'] = $terms[$item['value']];
        }
        // Otherwise, unset the instance value, since the term does not exist.
        else {
          unset($items[$id][$delta]);
        }
      }
    }
  }
}

/**
 * Helper function that clears field cache when terms are updated or deleted
 */
function _taxonomy_clean_field_cache($term) {
  $cids = array();

  // Determine object types that are not cacheable.
  $obj_types = array();
  foreach (field_info_fieldable_types() as $obj_type => $info) {
    if (!$info['cacheable']) {
      $obj_types[] = $obj_type;
    }
  }

  // Load info for all taxonomy term fields.
  $fields = field_read_fields(array('type' => 'taxonomy_term'));
  foreach ($fields as $field_name => $field) {

    // Assemble an array of vocabulary IDs that are used in this field.
    foreach ($field['settings']['allowed_values'] as $tree) {
      $vids[$tree['vid']] = $tree['vid'];
    }
    
    // Check this term's vocabulary against those used for the field's options.
    if (in_array($term->vid, $vids)) {
      $conditions = array(array('value', $term->tid));
      if ($obj_types) {
        $conditions[] = array('type', $obj_types, 'NOT IN');
      }
      $results = field_attach_query($field['id'], $conditions, FIELD_QUERY_NO_LIMIT);
      foreach ($results as $obj_type => $objects) {
        foreach (array_keys($objects) as $id) {
          $cids[] = "field:$obj_type:$id";
        }
      }
    }
  }
  if ($cids) {
    cache_clear_all($cids, 'cache_field');
  }
}

/**
 * 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 check_plain($term->name);
}

/**
 * Implement hook_field_widget().
 */
function taxonomy_field_widget(&$form, &$form_state, $field, $instance, $items, $delta = NULL) {
  $element = array(
    '#type' => $instance['widget']['type'],
    '#default_value' => !empty($items) ? $items : array(),
  );
  return $element;
}

/**
 * Implement hook_field_widget_error().
 */
function taxonomy_field_widget_error($element, $error) {
  $field_key = $element['#columns'][0];
  form_error($element[$field_key], $error['message']);
}

/**
 * Process an individual autocomplete widget element.
 *
 * Build the form element. When creating a form using FAPI #process, note that
 * $element['#value'] is already set.
 *
 * The $field and $instance arrays are in $form['#fields'][$element['#field_name']].
 *
 * @todo For widgets to be actual FAPI 'elements', reusable outside of a 'field'
 * context, they shoudn't rely on $field and $instance. The bits of information
 * needed to adjust the behavior of the 'element' should be extracted in
 * hook_field_widget() above.
 */
function taxonomy_autocomplete_elements_process($element, &$form_state, $form) {
  $field = $form['#fields'][$element['#field_name']]['field'];
  $instance = $form['#fields'][$element['#field_name']]['instance'];
  $field_key = $element['#columns'][0];

  // See if this element is in the database format or the transformed format,
  // and transform it if necessary.
  if (is_array($element['#value']) && !array_key_exists($field_key, $element['#value'])) {
    $tags = array();
    foreach ($element['#default_value'] as $item) {
      $tags[$item['value']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['value']);
    }
    $element['#value'] = taxonomy_implode_tags($tags);
  }
  $typed_string = $element['#value'];

  $value = array();
  $element[$field_key] = array(
    '#type' => 'textfield',
    '#default_value' => $typed_string,
    '#autocomplete_path' => 'taxonomy/autocomplete/'. $element['#field_name'] .'/'. $element['#bundle'],
    '#size' => $instance['widget']['settings']['size'],
    '#attributes' => array('class' => array('text')),
    '#title' => $element['#title'],
    '#description' => $element['#description'],
    '#required' => $element['#required'],
  );
  $element[$field_key]['#maxlength'] = !empty($field['settings']['max_length']) ? $field['settings']['max_length'] : NULL;

  // Set #element_validate in a way that it will not wipe out other validation
  // functions already set by other modules.
  if (empty($element['#element_validate'])) {
    $element['#element_validate'] = array();
  }
  array_unshift($element['#element_validate'], 'taxonomy_autocomplete_validate');

  // Make sure field info will be available to the validator which does not get
  // the values in $form.
  $form_state['#fields'][$element['#field_name']] = $form['#fields'][$element['#field_name']];
  return $element;
}

/**
 * FAPI function to validate 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.
  if ($form_state['values'][$element['#field_name']]['value']) {

    // @see taxonomy_node_save
    $field = $form_state['#fields'][$element['#field_name']]['field'];
    $field_key = $element['#columns'][0];
    $vids = array();
    foreach ($field['settings']['allowed_values'] as $tree) {
      $vids[] = $tree['vid'];
    }
    $typed_terms = drupal_explode_tags($form_state['values'][$element['#field_name']]['value']);
    $values = array();

    foreach ($typed_terms as $typed_term) {

      // See if the term exists in the chosen vocabulary and return the tid;
      // otherwise, add a new record.
      $possibilities = taxonomy_term_load_multiple(array(), array('name' => trim($typed_term), 'vid' => $vids));
      $typed_term_tid = NULL;

      // tid match, if any.
      foreach ($possibilities as $possibility) {
        $typed_term_tid = $possibility->tid;
        break;
      }
      if (!$typed_term_tid) {
        $vocabulary = taxonomy_vocabulary_load($vids[0]);
        $edit = array(
          'vid' => $vids[0],
          'name' => $typed_term,
          'vocabulary_machine_name' => $vocabulary->machine_name,
        );
        $term = (object) $edit;
        if ($status = taxonomy_term_save($term)) {
          $typed_term_tid = $term->tid;
        }
      }
      $values[$typed_term_tid] = $typed_term_tid;
    }
    $results = options_transpose_array_rows_cols(array($field_key => $values));
    form_set_value($element, $results, $form_state);
  }
}

/**
 * Implement FAPI hook_elements().
 *
 * Any FAPI callbacks needed for individual widgets can be declared here,
 * and the element will be passed to those callbacks for processing.
 *
 * Drupal will automatically theme the element using a theme with
 * the same name as the hook_elements key.
 */
function taxonomy_elements() {
  return array(
    'taxonomy_autocomplete' => array(
      '#input' => TRUE,
      '#columns' => array('value'),
      '#delta' => 0,
      '#process' => array('taxonomy_autocomplete_elements_process'),
    ),
  );
}

/**
 * Implement hook_field_settings_form().
 */
function taxonomy_field_settings_form($field, $instance) {
  // Get proper values for 'allowed_values_function', which is a core setting.
  $vocabularies = taxonomy_get_vocabularies();
  $options = array();
  foreach ($vocabularies as $vocabulary) {
    $options[$vocabulary->vid] = $vocabulary->name;
  }
  $form['allowed_values'] = array(
    '#tree' => TRUE,
  );

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

  return $form;
}