taxonomy.module 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941
  1. <?php
  2. /**
  3. * @file
  4. * Enables the organization of content into categories.
  5. */
  6. /**
  7. * Users can create new terms in a free-tagging vocabulary when
  8. * submitting a taxonomy_autocomplete_widget. We store a term object
  9. * whose tid is 'autocreate' as a field data item during widget
  10. * validation and then actually create the term if/when that field
  11. * data item makes it to taxonomy_field_insert/update().
  12. */
  13. /**
  14. * Implements hook_help().
  15. */
  16. function taxonomy_help($path, $arg) {
  17. switch ($path) {
  18. case 'admin/help#taxonomy':
  19. $output = '';
  20. $output .= '<h3>' . t('About') . '</h3>';
  21. $output .= '<p>' . t('The Taxonomy module allows you to classify the content of your website. To classify content, you define <em>vocabularies</em> that contain related <em>terms</em>, and then assign the vocabularies to content types. For more information, see the online handbook entry for the <a href="@taxonomy">Taxonomy module</a>.', array('@taxonomy' => 'http://drupal.org/documentation/modules/taxonomy/')) . '</p>';
  22. $output .= '<h3>' . t('Uses') . '</h3>';
  23. $output .= '<dl>';
  24. $output .= '<dt>' . t('Creating vocabularies') . '</dt>';
  25. $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'))));
  26. $output .= '<ul><li>' . t('<em>vocabulary</em>: Music') . '</li>';
  27. $output .= '<ul><li>' . t('<em>term</em>: Jazz') . '</li>';
  28. $output .= '<ul><li>' . t('<em>sub-term</em>: Swing') . '</li>';
  29. $output .= '<li>' . t('<em>sub-term</em>: Fusion') . '</li></ul></ul>';
  30. $output .= '<ul><li>' . t('<em>term</em>: Rock') . '</li>';
  31. $output .= '<ul><li>' . t('<em>sub-term</em>: Country rock') . '</li>';
  32. $output .= '<li>' . t('<em>sub-term</em>: Hard rock') . '</li></ul></ul></ul>';
  33. $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>';
  34. $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>';
  35. $output .= '<dt>' . t('Assigning vocabularies to content types') . '</dt>';
  36. $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>';
  37. $output .= '<dt>' . t('Classifying content') . '</dt>';
  38. $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>';
  39. $output .= '<dt>' . t('Viewing listings and RSS feeds by term') . '</dt>';
  40. $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>';
  41. $output .= '<dt>' . t('Extending Taxonomy module') . '</dt>';
  42. $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'));
  43. $output .= '</dl>';
  44. return $output;
  45. case 'admin/structure/taxonomy':
  46. $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>';
  47. return $output;
  48. case 'admin/structure/taxonomy/%':
  49. $vocabulary = taxonomy_vocabulary_machine_name_load($arg[3]);
  50. switch ($vocabulary->hierarchy) {
  51. case 0:
  52. 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>';
  53. case 1:
  54. 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>';
  55. case 2:
  56. 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>';
  57. }
  58. }
  59. }
  60. /**
  61. * Implements hook_permission().
  62. */
  63. function taxonomy_permission() {
  64. $permissions = array(
  65. 'administer taxonomy' => array(
  66. 'title' => t('Administer vocabularies and terms'),
  67. ),
  68. );
  69. foreach (taxonomy_get_vocabularies() as $vocabulary) {
  70. $permissions += array(
  71. 'edit terms in ' . $vocabulary->vid => array(
  72. 'title' => t('Edit terms in %vocabulary', array('%vocabulary' => $vocabulary->name)),
  73. ),
  74. );
  75. $permissions += array(
  76. 'delete terms in ' . $vocabulary->vid => array(
  77. 'title' => t('Delete terms from %vocabulary', array('%vocabulary' => $vocabulary->name)),
  78. ),
  79. );
  80. }
  81. return $permissions;
  82. }
  83. /**
  84. * Implements hook_entity_info().
  85. */
  86. function taxonomy_entity_info() {
  87. $return = array(
  88. 'taxonomy_term' => array(
  89. 'label' => t('Taxonomy term'),
  90. 'controller class' => 'TaxonomyTermController',
  91. 'base table' => 'taxonomy_term_data',
  92. 'uri callback' => 'taxonomy_term_uri',
  93. 'fieldable' => TRUE,
  94. 'entity keys' => array(
  95. 'id' => 'tid',
  96. 'bundle' => 'vocabulary_machine_name',
  97. 'label' => 'name',
  98. ),
  99. 'bundle keys' => array(
  100. 'bundle' => 'machine_name',
  101. ),
  102. 'bundles' => array(),
  103. 'view modes' => array(
  104. // @todo View mode for display as a field (when attached to nodes etc).
  105. 'full' => array(
  106. 'label' => t('Taxonomy term page'),
  107. 'custom settings' => FALSE,
  108. ),
  109. ),
  110. ),
  111. );
  112. foreach (taxonomy_vocabulary_get_names() as $machine_name => $vocabulary) {
  113. $return['taxonomy_term']['bundles'][$machine_name] = array(
  114. 'label' => $vocabulary->name,
  115. 'admin' => array(
  116. 'path' => 'admin/structure/taxonomy/%taxonomy_vocabulary_machine_name',
  117. 'real path' => 'admin/structure/taxonomy/' . $machine_name,
  118. 'bundle argument' => 3,
  119. 'access arguments' => array('administer taxonomy'),
  120. ),
  121. );
  122. }
  123. $return['taxonomy_vocabulary'] = array(
  124. 'label' => t('Taxonomy vocabulary'),
  125. 'controller class' => 'TaxonomyVocabularyController',
  126. 'base table' => 'taxonomy_vocabulary',
  127. 'entity keys' => array(
  128. 'id' => 'vid',
  129. 'label' => 'name',
  130. ),
  131. 'fieldable' => FALSE,
  132. );
  133. return $return;
  134. }
  135. /**
  136. * Entity uri callback.
  137. */
  138. function taxonomy_term_uri($term) {
  139. return array(
  140. 'path' => 'taxonomy/term/' . $term->tid,
  141. );
  142. }
  143. /**
  144. * Implements hook_field_extra_fields().
  145. */
  146. function taxonomy_field_extra_fields() {
  147. $return = array();
  148. $info = entity_get_info('taxonomy_term');
  149. foreach (array_keys($info['bundles']) as $bundle) {
  150. $return['taxonomy_term'][$bundle] = array(
  151. 'form' => array(
  152. 'name' => array(
  153. 'label' => t('Name'),
  154. 'description' => t('Term name textfield'),
  155. 'weight' => -5,
  156. ),
  157. 'description' => array(
  158. 'label' => t('Description'),
  159. 'description' => t('Term description textarea'),
  160. 'weight' => 0,
  161. ),
  162. ),
  163. 'display' => array(
  164. 'description' => array(
  165. 'label' => t('Description'),
  166. 'description' => t('Term description'),
  167. 'weight' => 0,
  168. ),
  169. ),
  170. );
  171. }
  172. return $return;
  173. }
  174. /**
  175. * Return nodes attached to a term across all field instances.
  176. *
  177. * This function requires taxonomy module to be maintaining its own tables,
  178. * and will return an empty array if it is not. If using other field storage
  179. * methods alternatives methods for listing terms will need to be used.
  180. *
  181. * @param $tid
  182. * The term ID.
  183. * @param $pager
  184. * Boolean to indicate whether a pager should be used.
  185. * @param $limit
  186. * Integer. The maximum number of nodes to find.
  187. * Set to FALSE for no limit.
  188. * @param $order
  189. * An array of fields and directions.
  190. *
  191. * @return
  192. * An array of nids matching the query.
  193. */
  194. function taxonomy_select_nodes($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC')) {
  195. if (!variable_get('taxonomy_maintain_index_table', TRUE)) {
  196. return array();
  197. }
  198. $query = db_select('taxonomy_index', 't');
  199. $query->addTag('node_access');
  200. $query->condition('tid', $tid);
  201. if ($pager) {
  202. $count_query = clone $query;
  203. $count_query->addExpression('COUNT(t.nid)');
  204. $query = $query->extend('PagerDefault');
  205. if ($limit !== FALSE) {
  206. $query = $query->limit($limit);
  207. }
  208. $query->setCountQuery($count_query);
  209. }
  210. else {
  211. if ($limit !== FALSE) {
  212. $query->range(0, $limit);
  213. }
  214. }
  215. $query->addField('t', 'nid');
  216. $query->addField('t', 'tid');
  217. foreach ($order as $field => $direction) {
  218. $query->orderBy($field, $direction);
  219. // ORDER BY fields need to be loaded too, assume they are in the form
  220. // table_alias.name
  221. list($table_alias, $name) = explode('.', $field);
  222. $query->addField($table_alias, $name);
  223. }
  224. return $query->execute()->fetchCol();
  225. }
  226. /**
  227. * Implements hook_theme().
  228. */
  229. function taxonomy_theme() {
  230. return array(
  231. 'taxonomy_overview_vocabularies' => array(
  232. 'render element' => 'form',
  233. ),
  234. 'taxonomy_overview_terms' => array(
  235. 'render element' => 'form',
  236. ),
  237. 'taxonomy_term' => array(
  238. 'render element' => 'elements',
  239. 'template' => 'taxonomy-term',
  240. ),
  241. );
  242. }
  243. /**
  244. * Implements hook_menu().
  245. */
  246. function taxonomy_menu() {
  247. $items['admin/structure/taxonomy'] = array(
  248. 'title' => 'Taxonomy',
  249. 'description' => 'Manage tagging, categorization, and classification of your content.',
  250. 'page callback' => 'drupal_get_form',
  251. 'page arguments' => array('taxonomy_overview_vocabularies'),
  252. 'access arguments' => array('administer taxonomy'),
  253. 'file' => 'taxonomy.admin.inc',
  254. );
  255. $items['admin/structure/taxonomy/list'] = array(
  256. 'title' => 'List',
  257. 'type' => MENU_DEFAULT_LOCAL_TASK,
  258. 'weight' => -10,
  259. );
  260. $items['admin/structure/taxonomy/add'] = array(
  261. 'title' => 'Add vocabulary',
  262. 'page callback' => 'drupal_get_form',
  263. 'page arguments' => array('taxonomy_form_vocabulary'),
  264. 'access arguments' => array('administer taxonomy'),
  265. 'type' => MENU_LOCAL_ACTION,
  266. 'file' => 'taxonomy.admin.inc',
  267. );
  268. $items['taxonomy/term/%taxonomy_term'] = array(
  269. 'title' => 'Taxonomy term',
  270. 'title callback' => 'taxonomy_term_title',
  271. 'title arguments' => array(2),
  272. 'page callback' => 'taxonomy_term_page',
  273. 'page arguments' => array(2),
  274. 'access arguments' => array('access content'),
  275. 'file' => 'taxonomy.pages.inc',
  276. );
  277. $items['taxonomy/term/%taxonomy_term/view'] = array(
  278. 'title' => 'View',
  279. 'type' => MENU_DEFAULT_LOCAL_TASK,
  280. );
  281. $items['taxonomy/term/%taxonomy_term/edit'] = array(
  282. 'title' => 'Edit',
  283. 'page callback' => 'drupal_get_form',
  284. // Pass a NULL argument to ensure that additional path components are not
  285. // passed to taxonomy_form_term() as the vocabulary machine name argument.
  286. 'page arguments' => array('taxonomy_form_term', 2, NULL),
  287. 'access callback' => 'taxonomy_term_edit_access',
  288. 'access arguments' => array(2),
  289. 'type' => MENU_LOCAL_TASK,
  290. 'weight' => 10,
  291. 'file' => 'taxonomy.admin.inc',
  292. );
  293. $items['taxonomy/term/%taxonomy_term/feed'] = array(
  294. 'title' => 'Taxonomy term',
  295. 'title callback' => 'taxonomy_term_title',
  296. 'title arguments' => array(2),
  297. 'page callback' => 'taxonomy_term_feed',
  298. 'page arguments' => array(2),
  299. 'access arguments' => array('access content'),
  300. 'type' => MENU_CALLBACK,
  301. 'file' => 'taxonomy.pages.inc',
  302. );
  303. $items['taxonomy/autocomplete'] = array(
  304. 'title' => 'Autocomplete taxonomy',
  305. 'page callback' => 'taxonomy_autocomplete',
  306. 'access arguments' => array('access content'),
  307. 'type' => MENU_CALLBACK,
  308. 'file' => 'taxonomy.pages.inc',
  309. );
  310. $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name'] = array(
  311. 'title callback' => 'taxonomy_admin_vocabulary_title_callback',
  312. 'title arguments' => array(3),
  313. 'page callback' => 'drupal_get_form',
  314. 'page arguments' => array('taxonomy_overview_terms', 3),
  315. 'access arguments' => array('administer taxonomy'),
  316. 'file' => 'taxonomy.admin.inc',
  317. );
  318. $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/list'] = array(
  319. 'title' => 'List',
  320. 'type' => MENU_DEFAULT_LOCAL_TASK,
  321. 'weight' => -20,
  322. );
  323. $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/edit'] = array(
  324. 'title' => 'Edit',
  325. 'page callback' => 'drupal_get_form',
  326. 'page arguments' => array('taxonomy_form_vocabulary', 3),
  327. 'access arguments' => array('administer taxonomy'),
  328. 'type' => MENU_LOCAL_TASK,
  329. 'weight' => -10,
  330. 'file' => 'taxonomy.admin.inc',
  331. );
  332. $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/add'] = array(
  333. 'title' => 'Add term',
  334. 'page callback' => 'drupal_get_form',
  335. 'page arguments' => array('taxonomy_form_term', array(), 3),
  336. 'access arguments' => array('administer taxonomy'),
  337. 'type' => MENU_LOCAL_ACTION,
  338. 'file' => 'taxonomy.admin.inc',
  339. );
  340. return $items;
  341. }
  342. /**
  343. * Implements hook_admin_paths().
  344. */
  345. function taxonomy_admin_paths() {
  346. $paths = array(
  347. 'taxonomy/term/*/edit' => TRUE,
  348. );
  349. return $paths;
  350. }
  351. /**
  352. * Return edit access for a given term.
  353. */
  354. function taxonomy_term_edit_access($term) {
  355. return user_access("edit terms in $term->vid") || user_access('administer taxonomy');
  356. }
  357. /**
  358. * Return the vocabulary name given the vocabulary object.
  359. */
  360. function taxonomy_admin_vocabulary_title_callback($vocabulary) {
  361. return check_plain($vocabulary->name);
  362. }
  363. /**
  364. * Saves a vocabulary.
  365. *
  366. * @param $vocabulary
  367. * A vocabulary object with the following properties:
  368. * - vid: The ID of the vocabulary.
  369. * - name: The human-readable name of the vocabulary.
  370. * - machine_name: The machine name of the vocabulary.
  371. * - description: (optional) The vocabulary's description.
  372. * - hierarchy: The hierarchy level of the vocabulary.
  373. * - module: (optional) The module altering the vocabulary.
  374. * - weight: (optional) The weight of this vocabulary in relation to other
  375. * vocabularies.
  376. * - original: (optional) The original vocabulary object before any changes
  377. * are applied.
  378. * - old_machine_name: (optional) The original machine name of the
  379. * vocabulary.
  380. *
  381. * @return
  382. * Status constant indicating whether the vocabulary was inserted (SAVED_NEW)
  383. * or updated(SAVED_UPDATED).
  384. */
  385. function taxonomy_vocabulary_save($vocabulary) {
  386. // Prevent leading and trailing spaces in vocabulary names.
  387. if (!empty($vocabulary->name)) {
  388. $vocabulary->name = trim($vocabulary->name);
  389. }
  390. // Load the stored entity, if any.
  391. if (!empty($vocabulary->vid)) {
  392. if (!isset($vocabulary->original)) {
  393. $vocabulary->original = entity_load_unchanged('taxonomy_vocabulary', $vocabulary->vid);
  394. }
  395. // Make sure machine name changes are easily detected.
  396. // @todo: Remove in Drupal 8, as it is deprecated by directly reading from
  397. // $vocabulary->original.
  398. $vocabulary->old_machine_name = $vocabulary->original->machine_name;
  399. }
  400. if (!isset($vocabulary->module)) {
  401. $vocabulary->module = 'taxonomy';
  402. }
  403. module_invoke_all('taxonomy_vocabulary_presave', $vocabulary);
  404. module_invoke_all('entity_presave', $vocabulary, 'taxonomy_vocabulary');
  405. if (!empty($vocabulary->vid) && !empty($vocabulary->name)) {
  406. $status = drupal_write_record('taxonomy_vocabulary', $vocabulary, 'vid');
  407. taxonomy_vocabulary_static_reset(array($vocabulary->vid));
  408. if ($vocabulary->old_machine_name != $vocabulary->machine_name) {
  409. field_attach_rename_bundle('taxonomy_term', $vocabulary->old_machine_name, $vocabulary->machine_name);
  410. }
  411. module_invoke_all('taxonomy_vocabulary_update', $vocabulary);
  412. module_invoke_all('entity_update', $vocabulary, 'taxonomy_vocabulary');
  413. }
  414. elseif (empty($vocabulary->vid)) {
  415. $status = drupal_write_record('taxonomy_vocabulary', $vocabulary);
  416. taxonomy_vocabulary_static_reset();
  417. field_attach_create_bundle('taxonomy_term', $vocabulary->machine_name);
  418. module_invoke_all('taxonomy_vocabulary_insert', $vocabulary);
  419. module_invoke_all('entity_insert', $vocabulary, 'taxonomy_vocabulary');
  420. }
  421. unset($vocabulary->original);
  422. cache_clear_all();
  423. return $status;
  424. }
  425. /**
  426. * Delete a vocabulary.
  427. *
  428. * @param $vid
  429. * A vocabulary ID.
  430. * @return
  431. * Constant indicating items were deleted.
  432. */
  433. function taxonomy_vocabulary_delete($vid) {
  434. $vocabulary = taxonomy_vocabulary_load($vid);
  435. $transaction = db_transaction();
  436. try {
  437. // Only load terms without a parent, child terms will get deleted too.
  438. $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();
  439. foreach ($result as $tid) {
  440. taxonomy_term_delete($tid);
  441. }
  442. db_delete('taxonomy_vocabulary')
  443. ->condition('vid', $vid)
  444. ->execute();
  445. field_attach_delete_bundle('taxonomy_term', $vocabulary->machine_name);
  446. module_invoke_all('taxonomy_vocabulary_delete', $vocabulary);
  447. module_invoke_all('entity_delete', $vocabulary, 'taxonomy_vocabulary');
  448. // Load all Taxonomy module fields and delete those which use only this
  449. // vocabulary.
  450. $taxonomy_fields = field_read_fields(array('module' => 'taxonomy'));
  451. foreach ($taxonomy_fields as $field_name => $taxonomy_field) {
  452. $modified_field = FALSE;
  453. // Term reference fields may reference terms from more than one
  454. // vocabulary.
  455. foreach ($taxonomy_field['settings']['allowed_values'] as $key => $allowed_value) {
  456. if ($allowed_value['vocabulary'] == $vocabulary->machine_name) {
  457. unset($taxonomy_field['settings']['allowed_values'][$key]);
  458. $modified_field = TRUE;
  459. }
  460. }
  461. if ($modified_field) {
  462. if (empty($taxonomy_field['settings']['allowed_values'])) {
  463. field_delete_field($field_name);
  464. }
  465. else {
  466. // Update the field definition with the new allowed values.
  467. field_update_field($taxonomy_field);
  468. }
  469. }
  470. }
  471. cache_clear_all();
  472. taxonomy_vocabulary_static_reset();
  473. return SAVED_DELETED;
  474. }
  475. catch (Exception $e) {
  476. $transaction->rollback();
  477. watchdog_exception('taxonomy', $e);
  478. throw $e;
  479. }
  480. }
  481. /**
  482. * Implements hook_taxonomy_vocabulary_update().
  483. */
  484. function taxonomy_taxonomy_vocabulary_update($vocabulary) {
  485. // Reflect machine name changes in the definitions of existing 'taxonomy'
  486. // fields.
  487. if (!empty($vocabulary->old_machine_name) && $vocabulary->old_machine_name != $vocabulary->machine_name) {
  488. $fields = field_read_fields();
  489. foreach ($fields as $field_name => $field) {
  490. $update = FALSE;
  491. if ($field['type'] == 'taxonomy_term_reference') {
  492. foreach ($field['settings']['allowed_values'] as $key => &$value) {
  493. if ($value['vocabulary'] == $vocabulary->old_machine_name) {
  494. $value['vocabulary'] = $vocabulary->machine_name;
  495. $update = TRUE;
  496. }
  497. }
  498. if ($update) {
  499. field_update_field($field);
  500. }
  501. }
  502. }
  503. }
  504. }
  505. /**
  506. * Checks and updates the hierarchy flag of a vocabulary.
  507. *
  508. * Checks the current parents of all terms in a vocabulary and updates the
  509. * vocabulary's hierarchy setting to the lowest possible level. If no term
  510. * has parent terms then the vocabulary will be given a hierarchy of 0.
  511. * If any term has a single parent then the vocabulary will be given a
  512. * hierarchy of 1. If any term has multiple parents then the vocabulary
  513. * will be given a hierarchy of 2.
  514. *
  515. * @param $vocabulary
  516. * A vocabulary object.
  517. * @param $changed_term
  518. * An array of the term structure that was updated.
  519. *
  520. * @return
  521. * An integer that represents the level of the vocabulary's hierarchy.
  522. */
  523. function taxonomy_check_vocabulary_hierarchy($vocabulary, $changed_term) {
  524. $tree = taxonomy_get_tree($vocabulary->vid);
  525. $hierarchy = 0;
  526. foreach ($tree as $term) {
  527. // Update the changed term with the new parent value before comparison.
  528. if ($term->tid == $changed_term['tid']) {
  529. $term = (object) $changed_term;
  530. $term->parents = $term->parent;
  531. }
  532. // Check this term's parent count.
  533. if (count($term->parents) > 1) {
  534. $hierarchy = 2;
  535. break;
  536. }
  537. elseif (count($term->parents) == 1 && !isset($term->parents[0])) {
  538. $hierarchy = 1;
  539. }
  540. }
  541. if ($hierarchy != $vocabulary->hierarchy) {
  542. $vocabulary->hierarchy = $hierarchy;
  543. taxonomy_vocabulary_save($vocabulary);
  544. }
  545. return $hierarchy;
  546. }
  547. /**
  548. * Saves a term object to the database.
  549. *
  550. * @param $term
  551. * The taxonomy term object with the following properties:
  552. * - vid: The ID of the vocabulary the term is assigned to.
  553. * - name: The name of the term.
  554. * - tid: (optional) The unique ID for the term being saved. If $term->tid is
  555. * empty or omitted, a new term will be inserted.
  556. * - description: (optional) The term's description.
  557. * - format: (optional) The text format for the term's description.
  558. * - weight: (optional) The weight of this term in relation to other terms
  559. * within the same vocabulary.
  560. * - parent: (optional) The parent term(s) for this term. This can be a single
  561. * term ID or an array of term IDs. A value of 0 means this term does not
  562. * have any parents. When omitting this variable during an update, the
  563. * existing hierarchy for the term remains unchanged.
  564. * - vocabulary_machine_name: (optional) The machine name of the vocabulary
  565. * the term is assigned to. If not given, this value will be set
  566. * automatically by loading the vocabulary based on $term->vid.
  567. * - original: (optional) The original taxonomy term object before any changes
  568. * were applied. When omitted, the unchanged taxonomy term object is
  569. * loaded from the database and stored in this property.
  570. * Since a taxonomy term is an entity, any fields contained in the term object
  571. * are saved alongside the term object.
  572. *
  573. * @return
  574. * Status constant indicating whether term was inserted (SAVED_NEW) or updated
  575. * (SAVED_UPDATED). When inserting a new term, $term->tid will contain the
  576. * term ID of the newly created term.
  577. */
  578. function taxonomy_term_save($term) {
  579. // Prevent leading and trailing spaces in term names.
  580. $term->name = trim($term->name);
  581. if (!isset($term->vocabulary_machine_name)) {
  582. $vocabulary = taxonomy_vocabulary_load($term->vid);
  583. $term->vocabulary_machine_name = $vocabulary->machine_name;
  584. }
  585. // Load the stored entity, if any.
  586. if (!empty($term->tid) && !isset($term->original)) {
  587. $term->original = entity_load_unchanged('taxonomy_term', $term->tid);
  588. }
  589. field_attach_presave('taxonomy_term', $term);
  590. module_invoke_all('taxonomy_term_presave', $term);
  591. module_invoke_all('entity_presave', $term, 'taxonomy_term');
  592. if (empty($term->tid)) {
  593. $op = 'insert';
  594. $status = drupal_write_record('taxonomy_term_data', $term);
  595. field_attach_insert('taxonomy_term', $term);
  596. if (!isset($term->parent)) {
  597. $term->parent = array(0);
  598. }
  599. }
  600. else {
  601. $op = 'update';
  602. $status = drupal_write_record('taxonomy_term_data', $term, 'tid');
  603. field_attach_update('taxonomy_term', $term);
  604. if (isset($term->parent)) {
  605. db_delete('taxonomy_term_hierarchy')
  606. ->condition('tid', $term->tid)
  607. ->execute();
  608. }
  609. }
  610. if (isset($term->parent)) {
  611. if (!is_array($term->parent)) {
  612. $term->parent = array($term->parent);
  613. }
  614. $query = db_insert('taxonomy_term_hierarchy')
  615. ->fields(array('tid', 'parent'));
  616. foreach ($term->parent as $parent) {
  617. if (is_array($parent)) {
  618. foreach ($parent as $tid) {
  619. $query->values(array(
  620. 'tid' => $term->tid,
  621. 'parent' => $tid
  622. ));
  623. }
  624. }
  625. else {
  626. $query->values(array(
  627. 'tid' => $term->tid,
  628. 'parent' => $parent
  629. ));
  630. }
  631. }
  632. $query->execute();
  633. }
  634. // Reset the taxonomy term static variables.
  635. taxonomy_terms_static_reset();
  636. // Invoke the taxonomy hooks.
  637. module_invoke_all("taxonomy_term_$op", $term);
  638. module_invoke_all("entity_$op", $term, 'taxonomy_term');
  639. unset($term->original);
  640. return $status;
  641. }
  642. /**
  643. * Delete a term.
  644. *
  645. * @param $tid
  646. * The term ID.
  647. * @return
  648. * Status constant indicating deletion.
  649. */
  650. function taxonomy_term_delete($tid) {
  651. $transaction = db_transaction();
  652. try {
  653. $tids = array($tid);
  654. while ($tids) {
  655. $children_tids = $orphans = array();
  656. foreach ($tids as $tid) {
  657. // See if any of the term's children are about to be become orphans:
  658. if ($children = taxonomy_get_children($tid)) {
  659. foreach ($children as $child) {
  660. // If the term has multiple parents, we don't delete it.
  661. $parents = taxonomy_get_parents($child->tid);
  662. if (count($parents) == 1) {
  663. $orphans[] = $child->tid;
  664. }
  665. }
  666. }
  667. if ($term = taxonomy_term_load($tid)) {
  668. db_delete('taxonomy_term_data')
  669. ->condition('tid', $tid)
  670. ->execute();
  671. db_delete('taxonomy_term_hierarchy')
  672. ->condition('tid', $tid)
  673. ->execute();
  674. field_attach_delete('taxonomy_term', $term);
  675. module_invoke_all('taxonomy_term_delete', $term);
  676. module_invoke_all('entity_delete', $term, 'taxonomy_term');
  677. taxonomy_terms_static_reset();
  678. }
  679. }
  680. $tids = $orphans;
  681. }
  682. return SAVED_DELETED;
  683. }
  684. catch (Exception $e) {
  685. $transaction->rollback();
  686. watchdog_exception('taxonomy', $e);
  687. throw $e;
  688. }
  689. }
  690. /**
  691. * Generate an array for rendering the given term.
  692. *
  693. * @param $term
  694. * A term object.
  695. * @param $view_mode
  696. * View mode, e.g. 'full', 'teaser'...
  697. * @param $langcode
  698. * (optional) A language code to use for rendering. Defaults to the global
  699. * content language of the current request.
  700. *
  701. * @return
  702. * An array as expected by drupal_render().
  703. */
  704. function taxonomy_term_view($term, $view_mode = 'full', $langcode = NULL) {
  705. if (!isset($langcode)) {
  706. $langcode = $GLOBALS['language_content']->language;
  707. }
  708. field_attach_prepare_view('taxonomy_term', array($term->tid => $term), $view_mode, $langcode);
  709. entity_prepare_view('taxonomy_term', array($term->tid => $term), $langcode);
  710. $build = array(
  711. '#theme' => 'taxonomy_term',
  712. '#term' => $term,
  713. '#view_mode' => $view_mode,
  714. '#language' => $langcode,
  715. );
  716. $build += field_attach_view('taxonomy_term', $term, $view_mode, $langcode);
  717. // Add term description if the term has one.
  718. if (!empty($term->description)) {
  719. $build['description'] = array(
  720. '#markup' => check_markup($term->description, $term->format, '', TRUE),
  721. '#weight' => 0,
  722. '#prefix' => '<div class="taxonomy-term-description">',
  723. '#suffix' => '</div>',
  724. );
  725. }
  726. $build['#attached']['css'][] = drupal_get_path('module', 'taxonomy') . '/taxonomy.css';
  727. // Allow modules to modify the structured term.
  728. $type = 'taxonomy_term';
  729. drupal_alter(array('taxonomy_term_view', 'entity_view'), $build, $type);
  730. return $build;
  731. }
  732. /**
  733. * Process variables for taxonomy-term.tpl.php.
  734. */
  735. function template_preprocess_taxonomy_term(&$variables) {
  736. $variables['view_mode'] = $variables['elements']['#view_mode'];
  737. $variables['term'] = $variables['elements']['#term'];
  738. $term = $variables['term'];
  739. $uri = entity_uri('taxonomy_term', $term);
  740. $variables['term_url'] = url($uri['path'], $uri['options']);
  741. $variables['term_name'] = check_plain($term->name);
  742. $variables['page'] = $variables['view_mode'] == 'full' && taxonomy_term_is_page($term);
  743. // Flatten the term object's member fields.
  744. $variables = array_merge((array) $term, $variables);
  745. // Helpful $content variable for templates.
  746. $variables['content'] = array();
  747. foreach (element_children($variables['elements']) as $key) {
  748. $variables['content'][$key] = $variables['elements'][$key];
  749. }
  750. // field_attach_preprocess() overwrites the $[field_name] variables with the
  751. // values of the field in the language that was selected for display, instead
  752. // of the raw values in $term->[field_name], which contain all values in all
  753. // languages.
  754. field_attach_preprocess('taxonomy_term', $term, $variables['content'], $variables);
  755. // Gather classes, and clean up name so there are no underscores.
  756. $vocabulary_name_css = str_replace('_', '-', $term->vocabulary_machine_name);
  757. $variables['classes_array'][] = 'vocabulary-' . $vocabulary_name_css;
  758. $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->vocabulary_machine_name;
  759. $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->tid;
  760. }
  761. /**
  762. * Returns whether the current page is the page of the passed-in term.
  763. *
  764. * @param $term
  765. * A term object.
  766. */
  767. function taxonomy_term_is_page($term) {
  768. $page_term = menu_get_object('taxonomy_term', 2);
  769. return (!empty($page_term) ? $page_term->tid == $term->tid : FALSE);
  770. }
  771. /**
  772. * Clear all static cache variables for terms.
  773. */
  774. function taxonomy_terms_static_reset() {
  775. drupal_static_reset('taxonomy_term_count_nodes');
  776. drupal_static_reset('taxonomy_get_tree');
  777. drupal_static_reset('taxonomy_get_tree:parents');
  778. drupal_static_reset('taxonomy_get_tree:terms');
  779. drupal_static_reset('taxonomy_get_parents');
  780. drupal_static_reset('taxonomy_get_parents_all');
  781. drupal_static_reset('taxonomy_get_children');
  782. entity_get_controller('taxonomy_term')->resetCache();
  783. }
  784. /**
  785. * Clear all static cache variables for vocabularies.
  786. *
  787. * @param $ids
  788. * An array of ids to reset in entity controller cache.
  789. */
  790. function taxonomy_vocabulary_static_reset($ids = NULL) {
  791. drupal_static_reset('taxonomy_vocabulary_get_names');
  792. entity_get_controller('taxonomy_vocabulary')->resetCache($ids);
  793. }
  794. /**
  795. * Return an array of all vocabulary objects.
  796. *
  797. * @return
  798. * An array of all vocabulary objects, indexed by vid.
  799. */
  800. function taxonomy_get_vocabularies() {
  801. return taxonomy_vocabulary_load_multiple(FALSE, array());
  802. }
  803. /**
  804. * Get names for all taxonomy vocabularies.
  805. *
  806. * @return
  807. * An associative array of objects keyed by vocabulary machine name with
  808. * information about taxonomy vocabularies. Each object has properties:
  809. * - name: The vocabulary name.
  810. * - machine_name: The machine name.
  811. * - vid: The vocabulary ID.
  812. */
  813. function taxonomy_vocabulary_get_names() {
  814. $names = &drupal_static(__FUNCTION__);
  815. if (!isset($names)) {
  816. $names = db_query('SELECT name, machine_name, vid FROM {taxonomy_vocabulary}')->fetchAllAssoc('machine_name');
  817. }
  818. return $names;
  819. }
  820. /**
  821. * Finds all parents of a given term ID.
  822. *
  823. * @param $tid
  824. * A taxonomy term ID.
  825. *
  826. * @return
  827. * An array of term objects which are the parents of the term $tid, or an
  828. * empty array if parents are not found.
  829. */
  830. function taxonomy_get_parents($tid) {
  831. $parents = &drupal_static(__FUNCTION__, array());
  832. if ($tid && !isset($parents[$tid])) {
  833. $query = db_select('taxonomy_term_data', 't');
  834. $query->join('taxonomy_term_hierarchy', 'h', 'h.parent = t.tid');
  835. $query->addField('t', 'tid');
  836. $query->condition('h.tid', $tid);
  837. $query->addTag('term_access');
  838. $query->orderBy('t.weight');
  839. $query->orderBy('t.name');
  840. $tids = $query->execute()->fetchCol();
  841. $parents[$tid] = taxonomy_term_load_multiple($tids);
  842. }
  843. return isset($parents[$tid]) ? $parents[$tid] : array();
  844. }
  845. /**
  846. * Find all ancestors of a given term ID.
  847. */
  848. function taxonomy_get_parents_all($tid) {
  849. $cache = &drupal_static(__FUNCTION__, array());
  850. if (isset($cache[$tid])) {
  851. return $cache[$tid];
  852. }
  853. $parents = array();
  854. if ($term = taxonomy_term_load($tid)) {
  855. $parents[] = $term;
  856. $n = 0;
  857. while ($parent = taxonomy_get_parents($parents[$n]->tid)) {
  858. $parents = array_merge($parents, $parent);
  859. $n++;
  860. }
  861. }
  862. $cache[$tid] = $parents;
  863. return $parents;
  864. }
  865. /**
  866. * Finds all children of a term ID.
  867. *
  868. * @param $tid
  869. * A taxonomy term ID.
  870. * @param $vid
  871. * An optional vocabulary ID to restrict the child search.
  872. *
  873. * @return
  874. * An array of term objects that are the children of the term $tid, or an
  875. * empty array when no children exist.
  876. */
  877. function taxonomy_get_children($tid, $vid = 0) {
  878. $children = &drupal_static(__FUNCTION__, array());
  879. if ($tid && !isset($children[$tid])) {
  880. $query = db_select('taxonomy_term_data', 't');
  881. $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
  882. $query->addField('t', 'tid');
  883. $query->condition('h.parent', $tid);
  884. if ($vid) {
  885. $query->condition('t.vid', $vid);
  886. }
  887. $query->addTag('term_access');
  888. $query->orderBy('t.weight');
  889. $query->orderBy('t.name');
  890. $tids = $query->execute()->fetchCol();
  891. $children[$tid] = taxonomy_term_load_multiple($tids);
  892. }
  893. return isset($children[$tid]) ? $children[$tid] : array();
  894. }
  895. /**
  896. * Create a hierarchical representation of a vocabulary.
  897. *
  898. * @param $vid
  899. * Which vocabulary to generate the tree for.
  900. * @param $parent
  901. * The term ID under which to generate the tree. If 0, generate the tree
  902. * for the entire vocabulary.
  903. * @param $max_depth
  904. * The number of levels of the tree to return. Leave NULL to return all levels.
  905. * @param $load_entities
  906. * If TRUE, a full entity load will occur on the term objects. Otherwise they
  907. * are partial objects queried directly from the {taxonomy_term_data} table to
  908. * save execution time and memory consumption when listing large numbers of
  909. * terms. Defaults to FALSE.
  910. *
  911. * @return
  912. * An array of all term objects in the tree. Each term object is extended
  913. * to have "depth" and "parents" attributes in addition to its normal ones.
  914. * Results are statically cached. Term objects will be partial or complete
  915. * depending on the $load_entities parameter.
  916. */
  917. function taxonomy_get_tree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE) {
  918. $children = &drupal_static(__FUNCTION__, array());
  919. $parents = &drupal_static(__FUNCTION__ . ':parents', array());
  920. $terms = &drupal_static(__FUNCTION__ . ':terms', array());
  921. // We cache trees, so it's not CPU-intensive to call get_tree() on a term
  922. // and its children, too.
  923. if (!isset($children[$vid])) {
  924. $children[$vid] = array();
  925. $parents[$vid] = array();
  926. $terms[$vid] = array();
  927. $query = db_select('taxonomy_term_data', 't');
  928. $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
  929. $result = $query
  930. ->addTag('translatable')
  931. ->addTag('term_access')
  932. ->fields('t')
  933. ->fields('h', array('parent'))
  934. ->condition('t.vid', $vid)
  935. ->orderBy('t.weight')
  936. ->orderBy('t.name')
  937. ->execute();
  938. foreach ($result as $term) {
  939. $children[$vid][$term->parent][] = $term->tid;
  940. $parents[$vid][$term->tid][] = $term->parent;
  941. $terms[$vid][$term->tid] = $term;
  942. }
  943. }
  944. // Load full entities, if necessary. The entity controller statically
  945. // caches the results.
  946. if ($load_entities) {
  947. $term_entities = taxonomy_term_load_multiple(array_keys($terms[$vid]));
  948. }
  949. $max_depth = (!isset($max_depth)) ? count($children[$vid]) : $max_depth;
  950. $tree = array();
  951. // Keeps track of the parents we have to process, the last entry is used
  952. // for the next processing step.
  953. $process_parents = array();
  954. $process_parents[] = $parent;
  955. // Loops over the parent terms and adds its children to the tree array.
  956. // Uses a loop instead of a recursion, because it's more efficient.
  957. while (count($process_parents)) {
  958. $parent = array_pop($process_parents);
  959. // The number of parents determines the current depth.
  960. $depth = count($process_parents);
  961. if ($max_depth > $depth && !empty($children[$vid][$parent])) {
  962. $has_children = FALSE;
  963. $child = current($children[$vid][$parent]);
  964. do {
  965. if (empty($child)) {
  966. break;
  967. }
  968. $term = $load_entities ? $term_entities[$child] : $terms[$vid][$child];
  969. if (isset($parents[$vid][$term->tid])) {
  970. // Clone the term so that the depth attribute remains correct
  971. // in the event of multiple parents.
  972. $term = clone $term;
  973. }
  974. $term->depth = $depth;
  975. unset($term->parent);
  976. $term->parents = $parents[$vid][$term->tid];
  977. $tree[] = $term;
  978. if (!empty($children[$vid][$term->tid])) {
  979. $has_children = TRUE;
  980. // We have to continue with this parent later.
  981. $process_parents[] = $parent;
  982. // Use the current term as parent for the next iteration.
  983. $process_parents[] = $term->tid;
  984. // Reset pointers for child lists because we step in there more often
  985. // with multi parents.
  986. reset($children[$vid][$term->tid]);
  987. // Move pointer so that we get the correct term the next time.
  988. next($children[$vid][$parent]);
  989. break;
  990. }
  991. } while ($child = next($children[$vid][$parent]));
  992. if (!$has_children) {
  993. // We processed all terms in this hierarchy-level, reset pointer
  994. // so that this function works the next time it gets called.
  995. reset($children[$vid][$parent]);
  996. }
  997. }
  998. }
  999. return $tree;
  1000. }
  1001. /**
  1002. * Try to map a string to an existing term, as for glossary use.
  1003. *
  1004. * Provides a case-insensitive and trimmed mapping, to maximize the
  1005. * likelihood of a successful match.
  1006. *
  1007. * @param $name
  1008. * Name of the term to search for.
  1009. * @param $vocabulary
  1010. * (optional) Vocabulary machine name to limit the search. Defaults to NULL.
  1011. *
  1012. * @return
  1013. * An array of matching term objects.
  1014. */
  1015. function taxonomy_get_term_by_name($name, $vocabulary = NULL) {
  1016. $conditions = array('name' => trim($name));
  1017. if (isset($vocabulary)) {
  1018. $vocabularies = taxonomy_vocabulary_get_names();
  1019. if (isset($vocabularies[$vocabulary])) {
  1020. $conditions['vid'] = $vocabularies[$vocabulary]->vid;
  1021. }
  1022. else {
  1023. // Return an empty array when filtering by a non-existing vocabulary.
  1024. return array();
  1025. }
  1026. }
  1027. return taxonomy_term_load_multiple(array(), $conditions);
  1028. }
  1029. /**
  1030. * Controller class for taxonomy terms.
  1031. *
  1032. * This extends the DrupalDefaultEntityController class. Only alteration is
  1033. * that we match the condition on term name case-independently.
  1034. */
  1035. class TaxonomyTermController extends DrupalDefaultEntityController {
  1036. protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
  1037. $query = parent::buildQuery($ids, $conditions, $revision_id);
  1038. $query->addTag('translatable');
  1039. $query->addTag('term_access');
  1040. // When name is passed as a condition use LIKE.
  1041. if (isset($conditions['name'])) {
  1042. $query_conditions = &$query->conditions();
  1043. foreach ($query_conditions as $key => $condition) {
  1044. if (is_array($condition) && $condition['field'] == 'base.name') {
  1045. $query_conditions[$key]['operator'] = 'LIKE';
  1046. $query_conditions[$key]['value'] = db_like($query_conditions[$key]['value']);
  1047. }
  1048. }
  1049. }
  1050. // Add the machine name field from the {taxonomy_vocabulary} table.
  1051. $query->innerJoin('taxonomy_vocabulary', 'v', 'base.vid = v.vid');
  1052. $query->addField('v', 'machine_name', 'vocabulary_machine_name');
  1053. return $query;
  1054. }
  1055. protected function cacheGet($ids, $conditions = array()) {
  1056. $terms = parent::cacheGet($ids, $conditions);
  1057. // Name matching is case insensitive, note that with some collations
  1058. // LOWER() and drupal_strtolower() may return different results.
  1059. foreach ($terms as $term) {
  1060. $term_values = (array) $term;
  1061. if (isset($conditions['name']) && drupal_strtolower($conditions['name'] != drupal_strtolower($term_values['name']))) {
  1062. unset($terms[$term->tid]);
  1063. }
  1064. }
  1065. return $terms;
  1066. }
  1067. }
  1068. /**
  1069. * Controller class for taxonomy vocabularies.
  1070. *
  1071. * This extends the DrupalDefaultEntityController class, adding required
  1072. * special handling for taxonomy vocabulary objects.
  1073. */
  1074. class TaxonomyVocabularyController extends DrupalDefaultEntityController {
  1075. protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
  1076. $query = parent::buildQuery($ids, $conditions, $revision_id);
  1077. $query->addTag('translatable');
  1078. $query->orderBy('base.weight');
  1079. $query->orderBy('base.name');
  1080. return $query;
  1081. }
  1082. }
  1083. /**
  1084. * Load multiple taxonomy terms based on certain conditions.
  1085. *
  1086. * This function should be used whenever you need to load more than one term
  1087. * from the database. Terms are loaded into memory and will not require
  1088. * database access if loaded again during the same page request.
  1089. *
  1090. * @see entity_load()
  1091. * @see EntityFieldQuery
  1092. *
  1093. * @param $tids
  1094. * An array of taxonomy term IDs.
  1095. * @param $conditions
  1096. * (deprecated) An associative array of conditions on the {taxonomy_term}
  1097. * table, where the keys are the database fields and the values are the
  1098. * values those fields must have. Instead, it is preferable to use
  1099. * EntityFieldQuery to retrieve a list of entity IDs loadable by
  1100. * this function.
  1101. *
  1102. * @return
  1103. * An array of term objects, indexed by tid. When no results are found, an
  1104. * empty array is returned.
  1105. *
  1106. * @todo Remove $conditions in Drupal 8.
  1107. */
  1108. function taxonomy_term_load_multiple($tids = array(), $conditions = array()) {
  1109. return entity_load('taxonomy_term', $tids, $conditions);
  1110. }
  1111. /**
  1112. * Load multiple taxonomy vocabularies based on certain conditions.
  1113. *
  1114. * This function should be used whenever you need to load more than one
  1115. * vocabulary from the database. Terms are loaded into memory and will not
  1116. * require database access if loaded again during the same page request.
  1117. *
  1118. * @see entity_load()
  1119. *
  1120. * @param $vids
  1121. * An array of taxonomy vocabulary IDs, or FALSE to load all vocabularies.
  1122. * @param $conditions
  1123. * An array of conditions to add to the query.
  1124. *
  1125. * @return
  1126. * An array of vocabulary objects, indexed by vid.
  1127. */
  1128. function taxonomy_vocabulary_load_multiple($vids = array(), $conditions = array()) {
  1129. return entity_load('taxonomy_vocabulary', $vids, $conditions);
  1130. }
  1131. /**
  1132. * Return the vocabulary object matching a vocabulary ID.
  1133. *
  1134. * @param $vid
  1135. * The vocabulary's ID.
  1136. *
  1137. * @return
  1138. * The vocabulary object with all of its metadata, if exists, FALSE otherwise.
  1139. * Results are statically cached.
  1140. *
  1141. * @see taxonomy_vocabulary_machine_name_load()
  1142. */
  1143. function taxonomy_vocabulary_load($vid) {
  1144. $vocabularies = taxonomy_vocabulary_load_multiple(array($vid));
  1145. return reset($vocabularies);
  1146. }
  1147. /**
  1148. * Return the vocabulary object matching a vocabulary machine name.
  1149. *
  1150. * @param $name
  1151. * The vocabulary's machine name.
  1152. *
  1153. * @return
  1154. * The vocabulary object with all of its metadata, if exists, FALSE otherwise.
  1155. * Results are statically cached.
  1156. *
  1157. * @see taxonomy_vocabulary_load()
  1158. */
  1159. function taxonomy_vocabulary_machine_name_load($name) {
  1160. $vocabularies = taxonomy_vocabulary_load_multiple(NULL, array('machine_name' => $name));
  1161. return reset($vocabularies);
  1162. }
  1163. /**
  1164. * Return the term object matching a term ID.
  1165. *
  1166. * @param $tid
  1167. * A term's ID
  1168. *
  1169. * @return
  1170. * A taxonomy term object, or FALSE if the term was not found. Results are
  1171. * statically cached.
  1172. */
  1173. function taxonomy_term_load($tid) {
  1174. if (!is_numeric($tid)) {
  1175. return FALSE;
  1176. }
  1177. $term = taxonomy_term_load_multiple(array($tid), array());
  1178. return $term ? $term[$tid] : FALSE;
  1179. }
  1180. /**
  1181. * Helper function for array_map purposes.
  1182. */
  1183. function _taxonomy_get_tid_from_term($term) {
  1184. return $term->tid;
  1185. }
  1186. /**
  1187. * Implodes a list of tags of a certain vocabulary into a string.
  1188. *
  1189. * @see drupal_explode_tags()
  1190. */
  1191. function taxonomy_implode_tags($tags, $vid = NULL) {
  1192. $typed_tags = array();
  1193. foreach ($tags as $tag) {
  1194. // Extract terms belonging to the vocabulary in question.
  1195. if (!isset($vid) || $tag->vid == $vid) {
  1196. // Make sure we have a completed loaded taxonomy term.
  1197. if (isset($tag->name)) {
  1198. // Commas and quotes in tag names are special cases, so encode 'em.
  1199. if (strpos($tag->name, ',') !== FALSE || strpos($tag->name, '"') !== FALSE) {
  1200. $typed_tags[] = '"' . str_replace('"', '""', $tag->name) . '"';
  1201. }
  1202. else {
  1203. $typed_tags[] = $tag->name;
  1204. }
  1205. }
  1206. }
  1207. }
  1208. return implode(', ', $typed_tags);
  1209. }
  1210. /**
  1211. * Implements hook_field_info().
  1212. *
  1213. * Field settings:
  1214. * - allowed_values: a list array of one or more vocabulary trees:
  1215. * - vocabulary: a vocabulary machine name.
  1216. * - parent: a term ID of a term whose children are allowed. This should be
  1217. * '0' if all terms in a vocabulary are allowed. The allowed values do not
  1218. * include the parent term.
  1219. *
  1220. */
  1221. function taxonomy_field_info() {
  1222. return array(
  1223. 'taxonomy_term_reference' => array(
  1224. 'label' => t('Term reference'),
  1225. 'description' => t('This field stores a reference to a taxonomy term.'),
  1226. 'default_widget' => 'options_select',
  1227. 'default_formatter' => 'taxonomy_term_reference_link',
  1228. 'settings' => array(
  1229. 'allowed_values' => array(
  1230. array(
  1231. 'vocabulary' => '',
  1232. 'parent' => '0',
  1233. ),
  1234. ),
  1235. ),
  1236. ),
  1237. );
  1238. }
  1239. /**
  1240. * Implements hook_field_widget_info().
  1241. */
  1242. function taxonomy_field_widget_info() {
  1243. return array(
  1244. 'taxonomy_autocomplete' => array(
  1245. 'label' => t('Autocomplete term widget (tagging)'),
  1246. 'field types' => array('taxonomy_term_reference'),
  1247. 'settings' => array(
  1248. 'size' => 60,
  1249. 'autocomplete_path' => 'taxonomy/autocomplete',
  1250. ),
  1251. 'behaviors' => array(
  1252. 'multiple values' => FIELD_BEHAVIOR_CUSTOM,
  1253. ),
  1254. ),
  1255. );
  1256. }
  1257. /**
  1258. * Implements hook_field_widget_info_alter().
  1259. */
  1260. function taxonomy_field_widget_info_alter(&$info) {
  1261. $info['options_select']['field types'][] = 'taxonomy_term_reference';
  1262. $info['options_buttons']['field types'][] = 'taxonomy_term_reference';
  1263. }
  1264. /**
  1265. * Implements hook_options_list().
  1266. */
  1267. function taxonomy_options_list($field, $instance, $entity_type, $entity) {
  1268. $function = !empty($field['settings']['options_list_callback']) ? $field['settings']['options_list_callback'] : 'taxonomy_allowed_values';
  1269. return $function($field);
  1270. }
  1271. /**
  1272. * Implements hook_field_validate().
  1273. *
  1274. * Taxonomy field settings allow for either a single vocabulary ID, multiple
  1275. * vocabulary IDs, or sub-trees of a vocabulary to be specified as allowed
  1276. * values, although only the first of these is supported via the field UI.
  1277. * Confirm that terms entered as values meet at least one of these conditions.
  1278. *
  1279. * Possible error codes:
  1280. * - 'taxonomy_term_illegal_value': The value is not part of the list of allowed values.
  1281. */
  1282. function taxonomy_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  1283. // Build an array of existing term IDs so they can be loaded with
  1284. // taxonomy_term_load_multiple();
  1285. foreach ($items as $delta => $item) {
  1286. if (!empty($item['tid']) && $item['tid'] != 'autocreate') {
  1287. $tids[] = $item['tid'];
  1288. }
  1289. }
  1290. if (!empty($tids)) {
  1291. $terms = taxonomy_term_load_multiple($tids);
  1292. // Check each existing item to ensure it can be found in the
  1293. // allowed values for this field.
  1294. foreach ($items as $delta => $item) {
  1295. $validate = TRUE;
  1296. if (!empty($item['tid']) && $item['tid'] != 'autocreate') {
  1297. $validate = FALSE;
  1298. foreach ($field['settings']['allowed_values'] as $settings) {
  1299. // If no parent is specified, check if the term is in the vocabulary.
  1300. if (isset($settings['vocabulary']) && empty($settings['parent'])) {
  1301. if ($settings['vocabulary'] == $terms[$item['tid']]->vocabulary_machine_name) {
  1302. $validate = TRUE;
  1303. break;
  1304. }
  1305. }
  1306. // If a parent is specified, then to validate it must appear in the
  1307. // array returned by taxonomy_get_parents_all().
  1308. elseif (!empty($settings['parent'])) {
  1309. $ancestors = taxonomy_get_parents_all($item['tid']);
  1310. foreach ($ancestors as $ancestor) {
  1311. if ($ancestor->tid == $settings['parent']) {
  1312. $validate = TRUE;
  1313. break 2;
  1314. }
  1315. }
  1316. }
  1317. }
  1318. }
  1319. if (!$validate) {
  1320. $errors[$field['field_name']][$langcode][$delta][] = array(
  1321. 'error' => 'taxonomy_term_reference_illegal_value',
  1322. 'message' => t('%name: illegal value.', array('%name' => $instance['label'])),
  1323. );
  1324. }
  1325. }
  1326. }
  1327. }
  1328. /**
  1329. * Implements hook_field_is_empty().
  1330. */
  1331. function taxonomy_field_is_empty($item, $field) {
  1332. if (!is_array($item) || (empty($item['tid']) && (string) $item['tid'] !== '0')) {
  1333. return TRUE;
  1334. }
  1335. return FALSE;
  1336. }
  1337. /**
  1338. * Implements hook_field_formatter_info().
  1339. */
  1340. function taxonomy_field_formatter_info() {
  1341. return array(
  1342. 'taxonomy_term_reference_link' => array(
  1343. 'label' => t('Link'),
  1344. 'field types' => array('taxonomy_term_reference'),
  1345. ),
  1346. 'taxonomy_term_reference_plain' => array(
  1347. 'label' => t('Plain text'),
  1348. 'field types' => array('taxonomy_term_reference'),
  1349. ),
  1350. 'taxonomy_term_reference_rss_category' => array(
  1351. 'label' => t('RSS category'),
  1352. 'field types' => array('taxonomy_term_reference'),
  1353. ),
  1354. );
  1355. }
  1356. /**
  1357. * Implements hook_field_formatter_view().
  1358. */
  1359. function taxonomy_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  1360. $element = array();
  1361. // Terms whose tid is 'autocreate' do not exist
  1362. // yet and $item['taxonomy_term'] is not set. Theme such terms as
  1363. // just their name.
  1364. switch ($display['type']) {
  1365. case 'taxonomy_term_reference_link':
  1366. foreach ($items as $delta => $item) {
  1367. if ($item['tid'] == 'autocreate') {
  1368. $element[$delta] = array(
  1369. '#markup' => check_plain($item['name']),
  1370. );
  1371. }
  1372. else {
  1373. $term = $item['taxonomy_term'];
  1374. $uri = entity_uri('taxonomy_term', $term);
  1375. $element[$delta] = array(
  1376. '#type' => 'link',
  1377. '#title' => $term->name,
  1378. '#href' => $uri['path'],
  1379. '#options' => $uri['options'],
  1380. );
  1381. }
  1382. }
  1383. break;
  1384. case 'taxonomy_term_reference_plain':
  1385. foreach ($items as $delta => $item) {
  1386. $name = ($item['tid'] != 'autocreate' ? $item['taxonomy_term']->name : $item['name']);
  1387. $element[$delta] = array(
  1388. '#markup' => check_plain($name),
  1389. );
  1390. }
  1391. break;
  1392. case 'taxonomy_term_reference_rss_category':
  1393. foreach ($items as $delta => $item) {
  1394. $entity->rss_elements[] = array(
  1395. 'key' => 'category',
  1396. 'value' => $item['tid'] != 'autocreate' ? $item['taxonomy_term']->name : $item['name'],
  1397. 'attributes' => array(
  1398. 'domain' => $item['tid'] != 'autocreate' ? url('taxonomy/term/' . $item['tid'], array('absolute' => TRUE)) : '',
  1399. ),
  1400. );
  1401. }
  1402. break;
  1403. }
  1404. return $element;
  1405. }
  1406. /**
  1407. * Returns the set of valid terms for a taxonomy field.
  1408. *
  1409. * @param $field
  1410. * The field definition.
  1411. * @return
  1412. * The array of valid terms for this field, keyed by term id.
  1413. */
  1414. function taxonomy_allowed_values($field) {
  1415. $options = array();
  1416. foreach ($field['settings']['allowed_values'] as $tree) {
  1417. if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
  1418. if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'])) {
  1419. foreach ($terms as $term) {
  1420. $options[$term->tid] = str_repeat('-', $term->depth) . $term->name;
  1421. }
  1422. }
  1423. }
  1424. }
  1425. return $options;
  1426. }
  1427. /**
  1428. * Implements hook_field_formatter_prepare_view().
  1429. *
  1430. * This preloads all taxonomy terms for multiple loaded objects at once and
  1431. * unsets values for invalid terms that do not exist.
  1432. */
  1433. function taxonomy_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays) {
  1434. $tids = array();
  1435. // Collect every possible term attached to any of the fieldable entities.
  1436. foreach ($entities as $id => $entity) {
  1437. foreach ($items[$id] as $delta => $item) {
  1438. // Force the array key to prevent duplicates.
  1439. if ($item['tid'] != 'autocreate') {
  1440. $tids[$item['tid']] = $item['tid'];
  1441. }
  1442. }
  1443. }
  1444. if ($tids) {
  1445. $terms = taxonomy_term_load_multiple($tids);
  1446. // Iterate through the fieldable entities again to attach the loaded term data.
  1447. foreach ($entities as $id => $entity) {
  1448. $rekey = FALSE;
  1449. foreach ($items[$id] as $delta => $item) {
  1450. // Check whether the taxonomy term field instance value could be loaded.
  1451. if (isset($terms[$item['tid']])) {
  1452. // Replace the instance value with the term data.
  1453. $items[$id][$delta]['taxonomy_term'] = $terms[$item['tid']];
  1454. }
  1455. // Terms to be created are not in $terms, but are still legitimate.
  1456. elseif ($item['tid'] == 'autocreate') {
  1457. // Leave the item in place.
  1458. }
  1459. // Otherwise, unset the instance value, since the term does not exist.
  1460. else {
  1461. unset($items[$id][$delta]);
  1462. $rekey = TRUE;
  1463. }
  1464. }
  1465. if ($rekey) {
  1466. // Rekey the items array.
  1467. $items[$id] = array_values($items[$id]);
  1468. }
  1469. }
  1470. }
  1471. }
  1472. /**
  1473. * Title callback for term pages.
  1474. *
  1475. * @param $term
  1476. * A term object.
  1477. *
  1478. * @return
  1479. * The term name to be used as the page title.
  1480. */
  1481. function taxonomy_term_title($term) {
  1482. return $term->name;
  1483. }
  1484. /**
  1485. * Implements hook_field_widget_form().
  1486. */
  1487. function taxonomy_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  1488. $tags = array();
  1489. foreach ($items as $item) {
  1490. $tags[$item['tid']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
  1491. }
  1492. $element += array(
  1493. '#type' => 'textfield',
  1494. '#default_value' => taxonomy_implode_tags($tags),
  1495. '#autocomplete_path' => $instance['widget']['settings']['autocomplete_path'] . '/' . $field['field_name'],
  1496. '#size' => $instance['widget']['settings']['size'],
  1497. '#maxlength' => 1024,
  1498. '#element_validate' => array('taxonomy_autocomplete_validate'),
  1499. );
  1500. return $element;
  1501. }
  1502. /**
  1503. * Form element validate handler for taxonomy term autocomplete element.
  1504. */
  1505. function taxonomy_autocomplete_validate($element, &$form_state) {
  1506. // Autocomplete widgets do not send their tids in the form, so we must detect
  1507. // them here and process them independently.
  1508. $value = array();
  1509. if ($tags = $element['#value']) {
  1510. // Collect candidate vocabularies.
  1511. $field = field_widget_field($element, $form_state);
  1512. $vocabularies = array();
  1513. foreach ($field['settings']['allowed_values'] as $tree) {
  1514. if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
  1515. $vocabularies[$vocabulary->vid] = $vocabulary;
  1516. }
  1517. }
  1518. // Translate term names into actual terms.
  1519. $typed_terms = drupal_explode_tags($tags);
  1520. foreach ($typed_terms as $typed_term) {
  1521. // See if the term exists in the chosen vocabulary and return the tid;
  1522. // otherwise, create a new 'autocreate' term for insert/update.
  1523. if ($possibilities = taxonomy_term_load_multiple(array(), array('name' => trim($typed_term), 'vid' => array_keys($vocabularies)))) {
  1524. $term = array_pop($possibilities);
  1525. }
  1526. else {
  1527. $vocabulary = reset($vocabularies);
  1528. $term = array(
  1529. 'tid' => 'autocreate',
  1530. 'vid' => $vocabulary->vid,
  1531. 'name' => $typed_term,
  1532. 'vocabulary_machine_name' => $vocabulary->machine_name,
  1533. );
  1534. }
  1535. $value[] = (array)$term;
  1536. }
  1537. }
  1538. form_set_value($element, $value, $form_state);
  1539. }
  1540. /**
  1541. * Implements hook_field_widget_error().
  1542. */
  1543. function taxonomy_field_widget_error($element, $error, $form, &$form_state) {
  1544. form_error($element, $error['message']);
  1545. }
  1546. /**
  1547. * Implements hook_field_settings_form().
  1548. */
  1549. function taxonomy_field_settings_form($field, $instance, $has_data) {
  1550. // Get proper values for 'allowed_values_function', which is a core setting.
  1551. $vocabularies = taxonomy_get_vocabularies();
  1552. $options = array();
  1553. foreach ($vocabularies as $vocabulary) {
  1554. $options[$vocabulary->machine_name] = $vocabulary->name;
  1555. }
  1556. $form['allowed_values'] = array(
  1557. '#tree' => TRUE,
  1558. );
  1559. foreach ($field['settings']['allowed_values'] as $delta => $tree) {
  1560. $form['allowed_values'][$delta]['vocabulary'] = array(
  1561. '#type' => 'select',
  1562. '#title' => t('Vocabulary'),
  1563. '#default_value' => $tree['vocabulary'],
  1564. '#options' => $options,
  1565. '#required' => TRUE,
  1566. '#description' => t('The vocabulary which supplies the options for this field.'),
  1567. '#disabled' => $has_data,
  1568. );
  1569. $form['allowed_values'][$delta]['parent'] = array(
  1570. '#type' => 'value',
  1571. '#value' => $tree['parent'],
  1572. );
  1573. }
  1574. return $form;
  1575. }
  1576. /**
  1577. * Implements hook_rdf_mapping().
  1578. *
  1579. * @return array
  1580. * The rdf mapping for vocabularies and terms.
  1581. */
  1582. function taxonomy_rdf_mapping() {
  1583. return array(
  1584. array(
  1585. 'type' => 'taxonomy_term',
  1586. 'bundle' => RDF_DEFAULT_BUNDLE,
  1587. 'mapping' => array(
  1588. 'rdftype' => array('skos:Concept'),
  1589. 'name' => array(
  1590. 'predicates' => array('rdfs:label', 'skos:prefLabel'),
  1591. ),
  1592. 'description' => array(
  1593. 'predicates' => array('skos:definition'),
  1594. ),
  1595. 'vid' => array(
  1596. 'predicates' => array('skos:inScheme'),
  1597. 'type' => 'rel',
  1598. ),
  1599. 'parent' => array(
  1600. 'predicates' => array('skos:broader'),
  1601. 'type' => 'rel',
  1602. ),
  1603. ),
  1604. ),
  1605. array(
  1606. 'type' => 'taxonomy_vocabulary',
  1607. 'bundle' => RDF_DEFAULT_BUNDLE,
  1608. 'mapping' => array(
  1609. 'rdftype' => array('skos:ConceptScheme'),
  1610. 'name' => array(
  1611. 'predicates' => array('dc:title'),
  1612. ),
  1613. 'description' => array(
  1614. 'predicates' => array('rdfs:comment'),
  1615. ),
  1616. ),
  1617. ),
  1618. );
  1619. }
  1620. /**
  1621. * @defgroup taxonomy_index Taxonomy indexing
  1622. * @{
  1623. * Functions to maintain taxonomy indexing.
  1624. *
  1625. * Taxonomy uses default field storage to store canonical relationships
  1626. * between terms and fieldable entities. However its most common use case
  1627. * requires listing all content associated with a term or group of terms
  1628. * sorted by creation date. To avoid slow queries due to joining across
  1629. * multiple node and field tables with various conditions and order by criteria,
  1630. * we maintain a denormalized table with all relationships between terms,
  1631. * published nodes and common sort criteria such as sticky and created.
  1632. * This is used as a lookup table by taxonomy_select_nodes(). When using other
  1633. * field storage engines or alternative methods of denormalizing this data
  1634. * you should set the variable 'taxonomy_maintain_index_table' to FALSE
  1635. * to avoid unnecessary writes in SQL.
  1636. */
  1637. /**
  1638. * Implements hook_field_presave().
  1639. *
  1640. * Create any new terms defined in a freetagging vocabulary.
  1641. */
  1642. function taxonomy_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  1643. foreach ($items as $delta => $item) {
  1644. if ($item['tid'] == 'autocreate') {
  1645. $term = (object) $item;
  1646. unset($term->tid);
  1647. taxonomy_term_save($term);
  1648. $items[$delta]['tid'] = $term->tid;
  1649. }
  1650. }
  1651. }
  1652. /**
  1653. * Implements hook_node_insert().
  1654. */
  1655. function taxonomy_node_insert($node) {
  1656. // Add taxonomy index entries for the node.
  1657. taxonomy_build_node_index($node);
  1658. }
  1659. /**
  1660. * Builds and inserts taxonomy index entries for a given node.
  1661. *
  1662. * The index lists all terms that are related to a given node entity, and is
  1663. * therefore maintained at the entity level.
  1664. *
  1665. * @param $node
  1666. * The node object.
  1667. */
  1668. function taxonomy_build_node_index($node) {
  1669. // We maintain a denormalized table of term/node relationships, containing
  1670. // only data for current, published nodes.
  1671. $status = NULL;
  1672. if (variable_get('taxonomy_maintain_index_table', TRUE)) {
  1673. // If a node property is not set in the node object when node_save() is
  1674. // called, the old value from $node->original is used.
  1675. if (!empty($node->original)) {
  1676. $status = (int)(!empty($node->status) || (!isset($node->status) && !empty($node->original->status)));
  1677. $sticky = (int)(!empty($node->sticky) || (!isset($node->sticky) && !empty($node->original->sticky)));
  1678. }
  1679. else {
  1680. $status = (int)(!empty($node->status));
  1681. $sticky = (int)(!empty($node->sticky));
  1682. }
  1683. }
  1684. // We only maintain the taxonomy index for published nodes.
  1685. if ($status) {
  1686. // Collect a unique list of all the term IDs from all node fields.
  1687. $tid_all = array();
  1688. foreach (field_info_instances('node', $node->type) as $instance) {
  1689. $field_name = $instance['field_name'];
  1690. $field = field_info_field($field_name);
  1691. if ($field['module'] == 'taxonomy' && $field['storage']['type'] == 'field_sql_storage') {
  1692. // If a field value is not set in the node object when node_save() is
  1693. // called, the old value from $node->original is used.
  1694. if (isset($node->{$field_name})) {
  1695. $items = $node->{$field_name};
  1696. }
  1697. elseif (isset($node->original->{$field_name})) {
  1698. $items = $node->original->{$field_name};
  1699. }
  1700. else {
  1701. continue;
  1702. }
  1703. foreach (field_available_languages('node', $field) as $langcode) {
  1704. if (!empty($items[$langcode])) {
  1705. foreach ($items[$langcode] as $item) {
  1706. $tid_all[$item['tid']] = $item['tid'];
  1707. }
  1708. }
  1709. }
  1710. }
  1711. }
  1712. // Insert index entries for all the node's terms.
  1713. if (!empty($tid_all)) {
  1714. $query = db_insert('taxonomy_index')->fields(array('nid', 'tid', 'sticky', 'created'));
  1715. foreach ($tid_all as $tid) {
  1716. $query->values(array(
  1717. 'nid' => $node->nid,
  1718. 'tid' => $tid,
  1719. 'sticky' => $sticky,
  1720. 'created' => $node->created,
  1721. ));
  1722. }
  1723. $query->execute();
  1724. }
  1725. }
  1726. }
  1727. /**
  1728. * Implements hook_node_update().
  1729. */
  1730. function taxonomy_node_update($node) {
  1731. // Always rebuild the node's taxonomy index entries on node save.
  1732. taxonomy_delete_node_index($node);
  1733. taxonomy_build_node_index($node);
  1734. }
  1735. /**
  1736. * Implements hook_node_delete().
  1737. */
  1738. function taxonomy_node_delete($node) {
  1739. // Clean up the {taxonomy_index} table when nodes are deleted.
  1740. taxonomy_delete_node_index($node);
  1741. }
  1742. /**
  1743. * Deletes taxonomy index entries for a given node.
  1744. *
  1745. * @param $node
  1746. * The node object.
  1747. */
  1748. function taxonomy_delete_node_index($node) {
  1749. if (variable_get('taxonomy_maintain_index_table', TRUE)) {
  1750. db_delete('taxonomy_index')->condition('nid', $node->nid)->execute();
  1751. }
  1752. }
  1753. /**
  1754. * Implements hook_taxonomy_term_delete().
  1755. */
  1756. function taxonomy_taxonomy_term_delete($term) {
  1757. if (variable_get('taxonomy_maintain_index_table', TRUE)) {
  1758. // Clean up the {taxonomy_index} table when terms are deleted.
  1759. db_delete('taxonomy_index')->condition('tid', $term->tid)->execute();
  1760. }
  1761. }
  1762. /**
  1763. * @} End of "defgroup taxonomy_index".
  1764. */
  1765. /**
  1766. * Implements hook_entity_query_alter().
  1767. *
  1768. * Converts EntityFieldQuery instances on taxonomy terms that have an entity
  1769. * condition on term bundles (vocabulary machine names). Since the vocabulary
  1770. * machine name is not present in the {taxonomy_term_data} table itself, we have
  1771. * to convert the bundle condition into a proprety condition of vocabulary IDs
  1772. * to match against {taxonomy_term_data}.vid.
  1773. */
  1774. function taxonomy_entity_query_alter($query) {
  1775. $conditions = &$query->entityConditions;
  1776. // Alter only taxonomy term queries with bundle conditions.
  1777. if (isset($conditions['entity_type']) && $conditions['entity_type']['value'] == 'taxonomy_term' && isset($conditions['bundle'])) {
  1778. // Convert vocabulary machine names to vocabulary IDs.
  1779. $vocabulary_data = taxonomy_vocabulary_get_names();
  1780. $vids = array();
  1781. if (is_array($conditions['bundle']['value'])) {
  1782. foreach ($conditions['bundle']['value'] as $vocabulary_machine_name) {
  1783. $vids[] = $vocabulary_data[$vocabulary_machine_name]->vid;
  1784. }
  1785. }
  1786. else {
  1787. $vocabulary_machine_name = $conditions['bundle']['value'];
  1788. $vids = $vocabulary_data[$vocabulary_machine_name]->vid;
  1789. }
  1790. $query->propertyCondition('vid', $vids, $conditions['bundle']['operator']);
  1791. unset($conditions['bundle']);
  1792. }
  1793. }