taxonomy.module 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053
  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. * Implements callback_entity_info_uri().
  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' => 'entity_label',
  312. 'title arguments' => array('taxonomy_vocabulary', 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. * Returns the sanitized name of a vocabulary.
  359. *
  360. * Deprecated. This function was previously used as a menu item title callback
  361. * but has been replaced by using entity_label() (which does not
  362. * sanitize the title, since the menu system does that automatically). In
  363. * Drupal 7, use that function for title callbacks, and call check_plain()
  364. * directly if you need a sanitized title.
  365. */
  366. function taxonomy_admin_vocabulary_title_callback($vocabulary) {
  367. return check_plain($vocabulary->name);
  368. }
  369. /**
  370. * Saves a vocabulary.
  371. *
  372. * @param $vocabulary
  373. * A vocabulary object with the following properties:
  374. * - vid: (optional) The ID of the vocabulary (omit if creating a new
  375. * vocabulary; only use to update an existing vocabulary).
  376. * - name: The human-readable name of the vocabulary.
  377. * - machine_name: The machine name of the vocabulary.
  378. * - description: (optional) The vocabulary's description.
  379. * - hierarchy: The hierarchy level of the vocabulary.
  380. * - module: (optional) The module altering the vocabulary.
  381. * - weight: (optional) The weight of this vocabulary in relation to other
  382. * vocabularies.
  383. * - original: (optional) The original vocabulary object before any changes
  384. * are applied.
  385. * - old_machine_name: (optional) The original machine name of the
  386. * vocabulary.
  387. *
  388. * @return
  389. * Status constant indicating whether the vocabulary was inserted (SAVED_NEW)
  390. * or updated (SAVED_UPDATED).
  391. */
  392. function taxonomy_vocabulary_save($vocabulary) {
  393. // Prevent leading and trailing spaces in vocabulary names.
  394. if (!empty($vocabulary->name)) {
  395. $vocabulary->name = trim($vocabulary->name);
  396. }
  397. // Load the stored entity, if any.
  398. if (!empty($vocabulary->vid)) {
  399. if (!isset($vocabulary->original)) {
  400. $vocabulary->original = entity_load_unchanged('taxonomy_vocabulary', $vocabulary->vid);
  401. }
  402. // Make sure machine name changes are easily detected.
  403. // @todo: Remove in Drupal 8, as it is deprecated by directly reading from
  404. // $vocabulary->original.
  405. $vocabulary->old_machine_name = $vocabulary->original->machine_name;
  406. }
  407. if (!isset($vocabulary->module)) {
  408. $vocabulary->module = 'taxonomy';
  409. }
  410. module_invoke_all('taxonomy_vocabulary_presave', $vocabulary);
  411. module_invoke_all('entity_presave', $vocabulary, 'taxonomy_vocabulary');
  412. if (!empty($vocabulary->vid) && !empty($vocabulary->name)) {
  413. $status = drupal_write_record('taxonomy_vocabulary', $vocabulary, 'vid');
  414. taxonomy_vocabulary_static_reset(array($vocabulary->vid));
  415. if ($vocabulary->old_machine_name != $vocabulary->machine_name) {
  416. field_attach_rename_bundle('taxonomy_term', $vocabulary->old_machine_name, $vocabulary->machine_name);
  417. }
  418. module_invoke_all('taxonomy_vocabulary_update', $vocabulary);
  419. module_invoke_all('entity_update', $vocabulary, 'taxonomy_vocabulary');
  420. }
  421. elseif (empty($vocabulary->vid)) {
  422. $status = drupal_write_record('taxonomy_vocabulary', $vocabulary);
  423. taxonomy_vocabulary_static_reset();
  424. field_attach_create_bundle('taxonomy_term', $vocabulary->machine_name);
  425. module_invoke_all('taxonomy_vocabulary_insert', $vocabulary);
  426. module_invoke_all('entity_insert', $vocabulary, 'taxonomy_vocabulary');
  427. }
  428. unset($vocabulary->original);
  429. cache_clear_all();
  430. return $status;
  431. }
  432. /**
  433. * Deletes a vocabulary.
  434. *
  435. * This will update all Taxonomy fields so that they don't reference the
  436. * deleted vocabulary. It also will delete fields that have no remaining
  437. * vocabulary references. All taxonomy terms of the deleted vocabulary
  438. * will be deleted as well.
  439. *
  440. * @param $vid
  441. * A vocabulary ID.
  442. * @return
  443. * Constant indicating items were deleted.
  444. */
  445. function taxonomy_vocabulary_delete($vid) {
  446. $vocabulary = taxonomy_vocabulary_load($vid);
  447. $transaction = db_transaction();
  448. try {
  449. // Only load terms without a parent, child terms will get deleted too.
  450. $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();
  451. foreach ($result as $tid) {
  452. taxonomy_term_delete($tid);
  453. }
  454. db_delete('taxonomy_vocabulary')
  455. ->condition('vid', $vid)
  456. ->execute();
  457. field_attach_delete_bundle('taxonomy_term', $vocabulary->machine_name);
  458. module_invoke_all('taxonomy_vocabulary_delete', $vocabulary);
  459. module_invoke_all('entity_delete', $vocabulary, 'taxonomy_vocabulary');
  460. // Load all Taxonomy module fields and delete those which use only this
  461. // vocabulary.
  462. $taxonomy_fields = field_read_fields(array('module' => 'taxonomy'));
  463. foreach ($taxonomy_fields as $field_name => $taxonomy_field) {
  464. $modified_field = FALSE;
  465. // Term reference fields may reference terms from more than one
  466. // vocabulary.
  467. foreach ($taxonomy_field['settings']['allowed_values'] as $key => $allowed_value) {
  468. if ($allowed_value['vocabulary'] == $vocabulary->machine_name) {
  469. unset($taxonomy_field['settings']['allowed_values'][$key]);
  470. $modified_field = TRUE;
  471. }
  472. }
  473. if ($modified_field) {
  474. if (empty($taxonomy_field['settings']['allowed_values'])) {
  475. field_delete_field($field_name);
  476. }
  477. else {
  478. // Update the field definition with the new allowed values.
  479. field_update_field($taxonomy_field);
  480. }
  481. }
  482. }
  483. cache_clear_all();
  484. taxonomy_vocabulary_static_reset();
  485. return SAVED_DELETED;
  486. }
  487. catch (Exception $e) {
  488. $transaction->rollback();
  489. watchdog_exception('taxonomy', $e);
  490. throw $e;
  491. }
  492. }
  493. /**
  494. * Implements hook_taxonomy_vocabulary_update().
  495. */
  496. function taxonomy_taxonomy_vocabulary_update($vocabulary) {
  497. // Reflect machine name changes in the definitions of existing 'taxonomy'
  498. // fields.
  499. if (!empty($vocabulary->old_machine_name) && $vocabulary->old_machine_name != $vocabulary->machine_name) {
  500. $fields = field_read_fields();
  501. foreach ($fields as $field_name => $field) {
  502. $update = FALSE;
  503. if ($field['type'] == 'taxonomy_term_reference') {
  504. foreach ($field['settings']['allowed_values'] as $key => &$value) {
  505. if ($value['vocabulary'] == $vocabulary->old_machine_name) {
  506. $value['vocabulary'] = $vocabulary->machine_name;
  507. $update = TRUE;
  508. }
  509. }
  510. if ($update) {
  511. field_update_field($field);
  512. }
  513. }
  514. }
  515. }
  516. }
  517. /**
  518. * Checks and updates the hierarchy flag of a vocabulary.
  519. *
  520. * Checks the current parents of all terms in a vocabulary and updates the
  521. * vocabulary's hierarchy setting to the lowest possible level. If no term
  522. * has parent terms then the vocabulary will be given a hierarchy of 0.
  523. * If any term has a single parent then the vocabulary will be given a
  524. * hierarchy of 1. If any term has multiple parents then the vocabulary
  525. * will be given a hierarchy of 2.
  526. *
  527. * @param $vocabulary
  528. * A vocabulary object.
  529. * @param $changed_term
  530. * An array of the term structure that was updated.
  531. *
  532. * @return
  533. * An integer that represents the level of the vocabulary's hierarchy.
  534. */
  535. function taxonomy_check_vocabulary_hierarchy($vocabulary, $changed_term) {
  536. $tree = taxonomy_get_tree($vocabulary->vid);
  537. $hierarchy = 0;
  538. foreach ($tree as $term) {
  539. // Update the changed term with the new parent value before comparison.
  540. if ($term->tid == $changed_term['tid']) {
  541. $term = (object) $changed_term;
  542. $term->parents = $term->parent;
  543. }
  544. // Check this term's parent count.
  545. if (count($term->parents) > 1) {
  546. $hierarchy = 2;
  547. break;
  548. }
  549. elseif (count($term->parents) == 1 && !isset($term->parents[0])) {
  550. $hierarchy = 1;
  551. }
  552. }
  553. if ($hierarchy != $vocabulary->hierarchy) {
  554. $vocabulary->hierarchy = $hierarchy;
  555. taxonomy_vocabulary_save($vocabulary);
  556. }
  557. return $hierarchy;
  558. }
  559. /**
  560. * Saves a term object to the database.
  561. *
  562. * @param $term
  563. * The taxonomy term object with the following properties:
  564. * - vid: The ID of the vocabulary the term is assigned to.
  565. * - name: The name of the term.
  566. * - tid: (optional) The unique ID for the term being saved. If $term->tid is
  567. * empty or omitted, a new term will be inserted.
  568. * - description: (optional) The term's description.
  569. * - format: (optional) The text format for the term's description.
  570. * - weight: (optional) The weight of this term in relation to other terms
  571. * within the same vocabulary.
  572. * - parent: (optional) The parent term(s) for this term. This can be a single
  573. * term ID or an array of term IDs. A value of 0 means this term does not
  574. * have any parents. When omitting this variable during an update, the
  575. * existing hierarchy for the term remains unchanged.
  576. * - vocabulary_machine_name: (optional) The machine name of the vocabulary
  577. * the term is assigned to. If not given, this value will be set
  578. * automatically by loading the vocabulary based on $term->vid.
  579. * - original: (optional) The original taxonomy term object before any changes
  580. * were applied. When omitted, the unchanged taxonomy term object is
  581. * loaded from the database and stored in this property.
  582. * Since a taxonomy term is an entity, any fields contained in the term object
  583. * are saved alongside the term object.
  584. *
  585. * @return
  586. * Status constant indicating whether term was inserted (SAVED_NEW) or updated
  587. * (SAVED_UPDATED). When inserting a new term, $term->tid will contain the
  588. * term ID of the newly created term.
  589. */
  590. function taxonomy_term_save($term) {
  591. // Prevent leading and trailing spaces in term names.
  592. $term->name = trim($term->name);
  593. if (!isset($term->vocabulary_machine_name)) {
  594. $vocabulary = taxonomy_vocabulary_load($term->vid);
  595. $term->vocabulary_machine_name = $vocabulary->machine_name;
  596. }
  597. // Load the stored entity, if any.
  598. if (!empty($term->tid) && !isset($term->original)) {
  599. $term->original = entity_load_unchanged('taxonomy_term', $term->tid);
  600. }
  601. field_attach_presave('taxonomy_term', $term);
  602. module_invoke_all('taxonomy_term_presave', $term);
  603. module_invoke_all('entity_presave', $term, 'taxonomy_term');
  604. if (empty($term->tid)) {
  605. $op = 'insert';
  606. $status = drupal_write_record('taxonomy_term_data', $term);
  607. field_attach_insert('taxonomy_term', $term);
  608. if (!isset($term->parent)) {
  609. $term->parent = array(0);
  610. }
  611. }
  612. else {
  613. $op = 'update';
  614. $status = drupal_write_record('taxonomy_term_data', $term, 'tid');
  615. field_attach_update('taxonomy_term', $term);
  616. if (isset($term->parent)) {
  617. db_delete('taxonomy_term_hierarchy')
  618. ->condition('tid', $term->tid)
  619. ->execute();
  620. }
  621. }
  622. if (isset($term->parent)) {
  623. if (!is_array($term->parent)) {
  624. $term->parent = array($term->parent);
  625. }
  626. $query = db_insert('taxonomy_term_hierarchy')
  627. ->fields(array('tid', 'parent'));
  628. foreach ($term->parent as $parent) {
  629. if (is_array($parent)) {
  630. foreach ($parent as $tid) {
  631. $query->values(array(
  632. 'tid' => $term->tid,
  633. 'parent' => $tid
  634. ));
  635. }
  636. }
  637. else {
  638. $query->values(array(
  639. 'tid' => $term->tid,
  640. 'parent' => $parent
  641. ));
  642. }
  643. }
  644. $query->execute();
  645. }
  646. // Reset the taxonomy term static variables.
  647. taxonomy_terms_static_reset();
  648. // Invoke the taxonomy hooks.
  649. module_invoke_all("taxonomy_term_$op", $term);
  650. module_invoke_all("entity_$op", $term, 'taxonomy_term');
  651. unset($term->original);
  652. return $status;
  653. }
  654. /**
  655. * Delete a term.
  656. *
  657. * @param $tid
  658. * The term ID.
  659. * @return
  660. * Status constant indicating deletion.
  661. */
  662. function taxonomy_term_delete($tid) {
  663. $transaction = db_transaction();
  664. try {
  665. $tids = array($tid);
  666. while ($tids) {
  667. $children_tids = $orphans = array();
  668. foreach ($tids as $tid) {
  669. // See if any of the term's children are about to be become orphans:
  670. if ($children = taxonomy_get_children($tid)) {
  671. foreach ($children as $child) {
  672. // If the term has multiple parents, we don't delete it.
  673. $parents = taxonomy_get_parents($child->tid);
  674. if (count($parents) == 1) {
  675. $orphans[] = $child->tid;
  676. }
  677. }
  678. }
  679. if ($term = taxonomy_term_load($tid)) {
  680. db_delete('taxonomy_term_data')
  681. ->condition('tid', $tid)
  682. ->execute();
  683. db_delete('taxonomy_term_hierarchy')
  684. ->condition('tid', $tid)
  685. ->execute();
  686. field_attach_delete('taxonomy_term', $term);
  687. module_invoke_all('taxonomy_term_delete', $term);
  688. module_invoke_all('entity_delete', $term, 'taxonomy_term');
  689. taxonomy_terms_static_reset();
  690. }
  691. }
  692. $tids = $orphans;
  693. }
  694. return SAVED_DELETED;
  695. }
  696. catch (Exception $e) {
  697. $transaction->rollback();
  698. watchdog_exception('taxonomy', $e);
  699. throw $e;
  700. }
  701. }
  702. /**
  703. * Generates an array which displays a term detail page.
  704. *
  705. * @param term
  706. * A taxonomy term object.
  707. * @return
  708. * A $page element suitable for use by drupal_render().
  709. */
  710. function taxonomy_term_show($term) {
  711. return taxonomy_term_view_multiple(array($term->tid => $term), 'full');
  712. }
  713. /**
  714. * Constructs a drupal_render() style array from an array of loaded terms.
  715. *
  716. * @param $terms
  717. * An array of taxonomy terms as returned by taxonomy_term_load_multiple().
  718. * @param $view_mode
  719. * View mode, e.g. 'full', 'teaser'...
  720. * @param $weight
  721. * An integer representing the weight of the first taxonomy term in the list.
  722. * @param $langcode
  723. * (optional) A language code to use for rendering. Defaults to the global
  724. * content language of the current request.
  725. *
  726. * @return
  727. * An array in the format expected by drupal_render().
  728. */
  729. function taxonomy_term_view_multiple($terms, $view_mode = 'teaser', $weight = 0, $langcode = NULL) {
  730. field_attach_prepare_view('taxonomy_term', $terms, $view_mode, $langcode);
  731. entity_prepare_view('taxonomy_term', $terms, $langcode);
  732. $build = array();
  733. foreach ($terms as $term) {
  734. $build['taxonomy_terms'][$term->tid] = taxonomy_term_view($term, $view_mode, $langcode);
  735. $build['taxonomy_terms'][$term->tid]['#weight'] = $weight;
  736. $weight++;
  737. }
  738. $build['taxonomy_terms']['#sorted'] = TRUE;
  739. return $build;
  740. }
  741. /**
  742. * Builds a structured array representing the term's content.
  743. *
  744. * The content built for the taxonomy term (field values, file attachments or
  745. * other term components) will vary depending on the $view_mode parameter.
  746. *
  747. * Drupal core defines the following view modes for terms, with the following
  748. * default use cases:
  749. * - full (default): term is displayed on its own page (taxonomy/term/123)
  750. * Contributed modules might define additional view modes, or use existing
  751. * view modes in additional contexts.
  752. *
  753. * @param $term
  754. * A taxonomy term object.
  755. * @param $view_mode
  756. * View mode, e.g. 'full', 'teaser'...
  757. * @param $langcode
  758. * (optional) A language code to use for rendering. Defaults to the global
  759. * content language of the current request.
  760. */
  761. function taxonomy_term_build_content($term, $view_mode = 'full', $langcode = NULL) {
  762. if (!isset($langcode)) {
  763. $langcode = $GLOBALS['language_content']->language;
  764. }
  765. // Remove previously built content, if exists.
  766. $term->content = array();
  767. // Allow modules to change the view mode.
  768. $context = array(
  769. 'entity_type' => 'taxonomy_term',
  770. 'entity' => $term,
  771. 'langcode' => $langcode,
  772. );
  773. drupal_alter('entity_view_mode', $view_mode, $context);
  774. // Add the term description if the term has one and it is visible.
  775. $type = 'taxonomy_term';
  776. $entity_ids = entity_extract_ids($type, $term);
  777. $settings = field_view_mode_settings($type, $entity_ids[2]);
  778. $fields = field_extra_fields_get_display($type, $entity_ids[2], $view_mode);
  779. if (!empty($term->description) && isset($fields['description']) && $fields['description']['visible']) {
  780. $term->content['description'] = array(
  781. '#markup' => check_markup($term->description, $term->format, '', TRUE),
  782. '#weight' => $fields['description']['weight'],
  783. '#prefix' => '<div class="taxonomy-term-description">',
  784. '#suffix' => '</div>',
  785. );
  786. }
  787. // Build fields content.
  788. // In case of a multiple view, taxonomy_term_view_multiple() already ran the
  789. // 'prepare_view' step. An internal flag prevents the operation from running
  790. // twice.
  791. field_attach_prepare_view('taxonomy_term', array($term->tid => $term), $view_mode, $langcode);
  792. entity_prepare_view('taxonomy_term', array($term->tid => $term), $langcode);
  793. $term->content += field_attach_view('taxonomy_term', $term, $view_mode, $langcode);
  794. // Allow modules to make their own additions to the taxonomy term.
  795. module_invoke_all('taxonomy_term_view', $term, $view_mode, $langcode);
  796. module_invoke_all('entity_view', $term, 'taxonomy_term', $view_mode, $langcode);
  797. // Make sure the current view mode is stored if no module has already
  798. // populated the related key.
  799. $term->content += array('#view_mode' => $view_mode);
  800. }
  801. /**
  802. * Generate an array for rendering the given term.
  803. *
  804. * @param $term
  805. * A term object.
  806. * @param $view_mode
  807. * View mode, e.g. 'full', 'teaser'...
  808. * @param $langcode
  809. * (optional) A language code to use for rendering. Defaults to the global
  810. * content language of the current request.
  811. *
  812. * @return
  813. * An array as expected by drupal_render().
  814. */
  815. function taxonomy_term_view($term, $view_mode = 'full', $langcode = NULL) {
  816. if (!isset($langcode)) {
  817. $langcode = $GLOBALS['language_content']->language;
  818. }
  819. // Populate $term->content with a render() array.
  820. taxonomy_term_build_content($term, $view_mode, $langcode);
  821. $build = $term->content;
  822. // We don't need duplicate rendering info in $term->content.
  823. unset($term->content);
  824. $build += array(
  825. '#theme' => 'taxonomy_term',
  826. '#term' => $term,
  827. '#view_mode' => $view_mode,
  828. '#language' => $langcode,
  829. );
  830. $build['#attached']['css'][] = drupal_get_path('module', 'taxonomy') . '/taxonomy.css';
  831. // Allow modules to modify the structured taxonomy term.
  832. $type = 'taxonomy_term';
  833. drupal_alter(array('taxonomy_term_view', 'entity_view'), $build, $type);
  834. return $build;
  835. }
  836. /**
  837. * Process variables for taxonomy-term.tpl.php.
  838. */
  839. function template_preprocess_taxonomy_term(&$variables) {
  840. $variables['view_mode'] = $variables['elements']['#view_mode'];
  841. $variables['term'] = $variables['elements']['#term'];
  842. $term = $variables['term'];
  843. $uri = entity_uri('taxonomy_term', $term);
  844. $variables['term_url'] = url($uri['path'], $uri['options']);
  845. $variables['term_name'] = check_plain($term->name);
  846. $variables['page'] = $variables['view_mode'] == 'full' && taxonomy_term_is_page($term);
  847. // Flatten the term object's member fields.
  848. $variables = array_merge((array) $term, $variables);
  849. // Helpful $content variable for templates.
  850. $variables['content'] = array();
  851. foreach (element_children($variables['elements']) as $key) {
  852. $variables['content'][$key] = $variables['elements'][$key];
  853. }
  854. // field_attach_preprocess() overwrites the $[field_name] variables with the
  855. // values of the field in the language that was selected for display, instead
  856. // of the raw values in $term->[field_name], which contain all values in all
  857. // languages.
  858. field_attach_preprocess('taxonomy_term', $term, $variables['content'], $variables);
  859. // Gather classes, and clean up name so there are no underscores.
  860. $vocabulary_name_css = str_replace('_', '-', $term->vocabulary_machine_name);
  861. $variables['classes_array'][] = 'vocabulary-' . $vocabulary_name_css;
  862. $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->vocabulary_machine_name;
  863. $variables['theme_hook_suggestions'][] = 'taxonomy_term__' . $term->tid;
  864. }
  865. /**
  866. * Returns whether the current page is the page of the passed-in term.
  867. *
  868. * @param $term
  869. * A term object.
  870. */
  871. function taxonomy_term_is_page($term) {
  872. $page_term = menu_get_object('taxonomy_term', 2);
  873. return (!empty($page_term) ? $page_term->tid == $term->tid : FALSE);
  874. }
  875. /**
  876. * Clear all static cache variables for terms.
  877. */
  878. function taxonomy_terms_static_reset() {
  879. drupal_static_reset('taxonomy_term_count_nodes');
  880. drupal_static_reset('taxonomy_get_tree');
  881. drupal_static_reset('taxonomy_get_tree:parents');
  882. drupal_static_reset('taxonomy_get_tree:terms');
  883. drupal_static_reset('taxonomy_get_parents');
  884. drupal_static_reset('taxonomy_get_parents_all');
  885. drupal_static_reset('taxonomy_get_children');
  886. entity_get_controller('taxonomy_term')->resetCache();
  887. }
  888. /**
  889. * Clear all static cache variables for vocabularies.
  890. *
  891. * @param $ids
  892. * An array of ids to reset in entity controller cache.
  893. */
  894. function taxonomy_vocabulary_static_reset($ids = NULL) {
  895. drupal_static_reset('taxonomy_vocabulary_get_names');
  896. entity_get_controller('taxonomy_vocabulary')->resetCache($ids);
  897. }
  898. /**
  899. * Return an array of all vocabulary objects.
  900. *
  901. * @return
  902. * An array of all vocabulary objects, indexed by vid.
  903. */
  904. function taxonomy_get_vocabularies() {
  905. return taxonomy_vocabulary_load_multiple(FALSE, array());
  906. }
  907. /**
  908. * Get names for all taxonomy vocabularies.
  909. *
  910. * @return
  911. * An associative array of objects keyed by vocabulary machine name with
  912. * information about taxonomy vocabularies. Each object has properties:
  913. * - name: The vocabulary name.
  914. * - machine_name: The machine name.
  915. * - vid: The vocabulary ID.
  916. */
  917. function taxonomy_vocabulary_get_names() {
  918. $names = &drupal_static(__FUNCTION__);
  919. if (!isset($names)) {
  920. $names = db_query('SELECT name, machine_name, vid FROM {taxonomy_vocabulary}')->fetchAllAssoc('machine_name');
  921. }
  922. return $names;
  923. }
  924. /**
  925. * Finds all parents of a given term ID.
  926. *
  927. * @param $tid
  928. * A taxonomy term ID.
  929. *
  930. * @return
  931. * An array of term objects which are the parents of the term $tid, or an
  932. * empty array if parents are not found.
  933. */
  934. function taxonomy_get_parents($tid) {
  935. $parents = &drupal_static(__FUNCTION__, array());
  936. if ($tid && !isset($parents[$tid])) {
  937. $query = db_select('taxonomy_term_data', 't');
  938. $query->join('taxonomy_term_hierarchy', 'h', 'h.parent = t.tid');
  939. $query->addField('t', 'tid');
  940. $query->condition('h.tid', $tid);
  941. $query->addTag('term_access');
  942. $query->orderBy('t.weight');
  943. $query->orderBy('t.name');
  944. $tids = $query->execute()->fetchCol();
  945. $parents[$tid] = taxonomy_term_load_multiple($tids);
  946. }
  947. return isset($parents[$tid]) ? $parents[$tid] : array();
  948. }
  949. /**
  950. * Find all ancestors of a given term ID.
  951. */
  952. function taxonomy_get_parents_all($tid) {
  953. $cache = &drupal_static(__FUNCTION__, array());
  954. if (isset($cache[$tid])) {
  955. return $cache[$tid];
  956. }
  957. $parents = array();
  958. if ($term = taxonomy_term_load($tid)) {
  959. $parents[] = $term;
  960. $n = 0;
  961. while ($parent = taxonomy_get_parents($parents[$n]->tid)) {
  962. $parents = array_merge($parents, $parent);
  963. $n++;
  964. }
  965. }
  966. $cache[$tid] = $parents;
  967. return $parents;
  968. }
  969. /**
  970. * Finds all children of a term ID.
  971. *
  972. * @param $tid
  973. * A taxonomy term ID.
  974. * @param $vid
  975. * An optional vocabulary ID to restrict the child search.
  976. *
  977. * @return
  978. * An array of term objects that are the children of the term $tid, or an
  979. * empty array when no children exist.
  980. */
  981. function taxonomy_get_children($tid, $vid = 0) {
  982. $children = &drupal_static(__FUNCTION__, array());
  983. if ($tid && !isset($children[$tid])) {
  984. $query = db_select('taxonomy_term_data', 't');
  985. $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
  986. $query->addField('t', 'tid');
  987. $query->condition('h.parent', $tid);
  988. if ($vid) {
  989. $query->condition('t.vid', $vid);
  990. }
  991. $query->addTag('term_access');
  992. $query->orderBy('t.weight');
  993. $query->orderBy('t.name');
  994. $tids = $query->execute()->fetchCol();
  995. $children[$tid] = taxonomy_term_load_multiple($tids);
  996. }
  997. return isset($children[$tid]) ? $children[$tid] : array();
  998. }
  999. /**
  1000. * Create a hierarchical representation of a vocabulary.
  1001. *
  1002. * @param $vid
  1003. * Which vocabulary to generate the tree for.
  1004. * @param $parent
  1005. * The term ID under which to generate the tree. If 0, generate the tree
  1006. * for the entire vocabulary.
  1007. * @param $max_depth
  1008. * The number of levels of the tree to return. Leave NULL to return all levels.
  1009. * @param $load_entities
  1010. * If TRUE, a full entity load will occur on the term objects. Otherwise they
  1011. * are partial objects queried directly from the {taxonomy_term_data} table to
  1012. * save execution time and memory consumption when listing large numbers of
  1013. * terms. Defaults to FALSE.
  1014. *
  1015. * @return
  1016. * An array of all term objects in the tree. Each term object is extended
  1017. * to have "depth" and "parents" attributes in addition to its normal ones.
  1018. * Results are statically cached. Term objects will be partial or complete
  1019. * depending on the $load_entities parameter.
  1020. */
  1021. function taxonomy_get_tree($vid, $parent = 0, $max_depth = NULL, $load_entities = FALSE) {
  1022. $children = &drupal_static(__FUNCTION__, array());
  1023. $parents = &drupal_static(__FUNCTION__ . ':parents', array());
  1024. $terms = &drupal_static(__FUNCTION__ . ':terms', array());
  1025. // We cache trees, so it's not CPU-intensive to call taxonomy_get_tree() on a
  1026. // term and its children, too.
  1027. if (!isset($children[$vid])) {
  1028. $children[$vid] = array();
  1029. $parents[$vid] = array();
  1030. $terms[$vid] = array();
  1031. $query = db_select('taxonomy_term_data', 't');
  1032. $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
  1033. $result = $query
  1034. ->addTag('translatable')
  1035. ->addTag('term_access')
  1036. ->fields('t')
  1037. ->fields('h', array('parent'))
  1038. ->condition('t.vid', $vid)
  1039. ->orderBy('t.weight')
  1040. ->orderBy('t.name')
  1041. ->execute();
  1042. foreach ($result as $term) {
  1043. $children[$vid][$term->parent][] = $term->tid;
  1044. $parents[$vid][$term->tid][] = $term->parent;
  1045. $terms[$vid][$term->tid] = $term;
  1046. }
  1047. }
  1048. // Load full entities, if necessary. The entity controller statically
  1049. // caches the results.
  1050. if ($load_entities) {
  1051. $term_entities = taxonomy_term_load_multiple(array_keys($terms[$vid]));
  1052. }
  1053. $max_depth = (!isset($max_depth)) ? count($children[$vid]) : $max_depth;
  1054. $tree = array();
  1055. // Keeps track of the parents we have to process, the last entry is used
  1056. // for the next processing step.
  1057. $process_parents = array();
  1058. $process_parents[] = $parent;
  1059. // Loops over the parent terms and adds its children to the tree array.
  1060. // Uses a loop instead of a recursion, because it's more efficient.
  1061. while (count($process_parents)) {
  1062. $parent = array_pop($process_parents);
  1063. // The number of parents determines the current depth.
  1064. $depth = count($process_parents);
  1065. if ($max_depth > $depth && !empty($children[$vid][$parent])) {
  1066. $has_children = FALSE;
  1067. $child = current($children[$vid][$parent]);
  1068. do {
  1069. if (empty($child)) {
  1070. break;
  1071. }
  1072. $term = $load_entities ? $term_entities[$child] : $terms[$vid][$child];
  1073. if (isset($parents[$vid][$term->tid])) {
  1074. // Clone the term so that the depth attribute remains correct
  1075. // in the event of multiple parents.
  1076. $term = clone $term;
  1077. }
  1078. $term->depth = $depth;
  1079. unset($term->parent);
  1080. $term->parents = $parents[$vid][$term->tid];
  1081. $tree[] = $term;
  1082. if (!empty($children[$vid][$term->tid])) {
  1083. $has_children = TRUE;
  1084. // We have to continue with this parent later.
  1085. $process_parents[] = $parent;
  1086. // Use the current term as parent for the next iteration.
  1087. $process_parents[] = $term->tid;
  1088. // Reset pointers for child lists because we step in there more often
  1089. // with multi parents.
  1090. reset($children[$vid][$term->tid]);
  1091. // Move pointer so that we get the correct term the next time.
  1092. next($children[$vid][$parent]);
  1093. break;
  1094. }
  1095. } while ($child = next($children[$vid][$parent]));
  1096. if (!$has_children) {
  1097. // We processed all terms in this hierarchy-level, reset pointer
  1098. // so that this function works the next time it gets called.
  1099. reset($children[$vid][$parent]);
  1100. }
  1101. }
  1102. }
  1103. return $tree;
  1104. }
  1105. /**
  1106. * Try to map a string to an existing term, as for glossary use.
  1107. *
  1108. * Provides a case-insensitive and trimmed mapping, to maximize the
  1109. * likelihood of a successful match.
  1110. *
  1111. * @param $name
  1112. * Name of the term to search for.
  1113. * @param $vocabulary
  1114. * (optional) Vocabulary machine name to limit the search. Defaults to NULL.
  1115. *
  1116. * @return
  1117. * An array of matching term objects.
  1118. */
  1119. function taxonomy_get_term_by_name($name, $vocabulary = NULL) {
  1120. $conditions = array('name' => trim($name));
  1121. if (isset($vocabulary)) {
  1122. $vocabularies = taxonomy_vocabulary_get_names();
  1123. if (isset($vocabularies[$vocabulary])) {
  1124. $conditions['vid'] = $vocabularies[$vocabulary]->vid;
  1125. }
  1126. else {
  1127. // Return an empty array when filtering by a non-existing vocabulary.
  1128. return array();
  1129. }
  1130. }
  1131. return taxonomy_term_load_multiple(array(), $conditions);
  1132. }
  1133. /**
  1134. * Controller class for taxonomy terms.
  1135. *
  1136. * This extends the DrupalDefaultEntityController class. Only alteration is
  1137. * that we match the condition on term name case-independently.
  1138. */
  1139. class TaxonomyTermController extends DrupalDefaultEntityController {
  1140. protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
  1141. $query = parent::buildQuery($ids, $conditions, $revision_id);
  1142. $query->addTag('translatable');
  1143. $query->addTag('term_access');
  1144. // When name is passed as a condition use LIKE.
  1145. if (isset($conditions['name'])) {
  1146. $query_conditions = &$query->conditions();
  1147. foreach ($query_conditions as $key => $condition) {
  1148. if (is_array($condition) && $condition['field'] == 'base.name') {
  1149. $query_conditions[$key]['operator'] = 'LIKE';
  1150. $query_conditions[$key]['value'] = db_like($query_conditions[$key]['value']);
  1151. }
  1152. }
  1153. }
  1154. // Add the machine name field from the {taxonomy_vocabulary} table.
  1155. $query->innerJoin('taxonomy_vocabulary', 'v', 'base.vid = v.vid');
  1156. $query->addField('v', 'machine_name', 'vocabulary_machine_name');
  1157. return $query;
  1158. }
  1159. protected function cacheGet($ids, $conditions = array()) {
  1160. $terms = parent::cacheGet($ids, $conditions);
  1161. // Name matching is case insensitive, note that with some collations
  1162. // LOWER() and drupal_strtolower() may return different results.
  1163. foreach ($terms as $term) {
  1164. $term_values = (array) $term;
  1165. if (isset($conditions['name']) && drupal_strtolower($conditions['name'] != drupal_strtolower($term_values['name']))) {
  1166. unset($terms[$term->tid]);
  1167. }
  1168. }
  1169. return $terms;
  1170. }
  1171. }
  1172. /**
  1173. * Controller class for taxonomy vocabularies.
  1174. *
  1175. * This extends the DrupalDefaultEntityController class, adding required
  1176. * special handling for taxonomy vocabulary objects.
  1177. */
  1178. class TaxonomyVocabularyController extends DrupalDefaultEntityController {
  1179. protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
  1180. $query = parent::buildQuery($ids, $conditions, $revision_id);
  1181. $query->addTag('translatable');
  1182. $query->orderBy('base.weight');
  1183. $query->orderBy('base.name');
  1184. return $query;
  1185. }
  1186. }
  1187. /**
  1188. * Load multiple taxonomy terms based on certain conditions.
  1189. *
  1190. * This function should be used whenever you need to load more than one term
  1191. * from the database. Terms are loaded into memory and will not require
  1192. * database access if loaded again during the same page request.
  1193. *
  1194. * @see entity_load()
  1195. * @see EntityFieldQuery
  1196. *
  1197. * @param $tids
  1198. * An array of taxonomy term IDs.
  1199. * @param $conditions
  1200. * (deprecated) An associative array of conditions on the {taxonomy_term}
  1201. * table, where the keys are the database fields and the values are the
  1202. * values those fields must have. Instead, it is preferable to use
  1203. * EntityFieldQuery to retrieve a list of entity IDs loadable by
  1204. * this function.
  1205. *
  1206. * @return
  1207. * An array of term objects, indexed by tid. When no results are found, an
  1208. * empty array is returned.
  1209. *
  1210. * @todo Remove $conditions in Drupal 8.
  1211. */
  1212. function taxonomy_term_load_multiple($tids = array(), $conditions = array()) {
  1213. return entity_load('taxonomy_term', $tids, $conditions);
  1214. }
  1215. /**
  1216. * Load multiple taxonomy vocabularies based on certain conditions.
  1217. *
  1218. * This function should be used whenever you need to load more than one
  1219. * vocabulary from the database. Terms are loaded into memory and will not
  1220. * require database access if loaded again during the same page request.
  1221. *
  1222. * @see entity_load()
  1223. *
  1224. * @param $vids
  1225. * An array of taxonomy vocabulary IDs, or FALSE to load all vocabularies.
  1226. * @param $conditions
  1227. * An array of conditions to add to the query.
  1228. *
  1229. * @return
  1230. * An array of vocabulary objects, indexed by vid.
  1231. */
  1232. function taxonomy_vocabulary_load_multiple($vids = array(), $conditions = array()) {
  1233. return entity_load('taxonomy_vocabulary', $vids, $conditions);
  1234. }
  1235. /**
  1236. * Return the vocabulary object matching a vocabulary ID.
  1237. *
  1238. * @param $vid
  1239. * The vocabulary's ID.
  1240. *
  1241. * @return
  1242. * The vocabulary object with all of its metadata, if exists, FALSE otherwise.
  1243. * Results are statically cached.
  1244. *
  1245. * @see taxonomy_vocabulary_machine_name_load()
  1246. */
  1247. function taxonomy_vocabulary_load($vid) {
  1248. $vocabularies = taxonomy_vocabulary_load_multiple(array($vid));
  1249. return reset($vocabularies);
  1250. }
  1251. /**
  1252. * Return the vocabulary object matching a vocabulary machine name.
  1253. *
  1254. * @param $name
  1255. * The vocabulary's machine name.
  1256. *
  1257. * @return
  1258. * The vocabulary object with all of its metadata, if exists, FALSE otherwise.
  1259. * Results are statically cached.
  1260. *
  1261. * @see taxonomy_vocabulary_load()
  1262. */
  1263. function taxonomy_vocabulary_machine_name_load($name) {
  1264. $vocabularies = taxonomy_vocabulary_load_multiple(NULL, array('machine_name' => $name));
  1265. return reset($vocabularies);
  1266. }
  1267. /**
  1268. * Return the term object matching a term ID.
  1269. *
  1270. * @param $tid
  1271. * A term's ID
  1272. *
  1273. * @return
  1274. * A taxonomy term object, or FALSE if the term was not found. Results are
  1275. * statically cached.
  1276. */
  1277. function taxonomy_term_load($tid) {
  1278. if (!is_numeric($tid)) {
  1279. return FALSE;
  1280. }
  1281. $term = taxonomy_term_load_multiple(array($tid), array());
  1282. return $term ? $term[$tid] : FALSE;
  1283. }
  1284. /**
  1285. * Helper function for array_map purposes.
  1286. */
  1287. function _taxonomy_get_tid_from_term($term) {
  1288. return $term->tid;
  1289. }
  1290. /**
  1291. * Implodes a list of tags of a certain vocabulary into a string.
  1292. *
  1293. * @see drupal_explode_tags()
  1294. */
  1295. function taxonomy_implode_tags($tags, $vid = NULL) {
  1296. $typed_tags = array();
  1297. foreach ($tags as $tag) {
  1298. // Extract terms belonging to the vocabulary in question.
  1299. if (!isset($vid) || $tag->vid == $vid) {
  1300. // Make sure we have a completed loaded taxonomy term.
  1301. if (isset($tag->name)) {
  1302. // Commas and quotes in tag names are special cases, so encode 'em.
  1303. if (strpos($tag->name, ',') !== FALSE || strpos($tag->name, '"') !== FALSE) {
  1304. $typed_tags[] = '"' . str_replace('"', '""', $tag->name) . '"';
  1305. }
  1306. else {
  1307. $typed_tags[] = $tag->name;
  1308. }
  1309. }
  1310. }
  1311. }
  1312. return implode(', ', $typed_tags);
  1313. }
  1314. /**
  1315. * Implements hook_field_info().
  1316. *
  1317. * Field settings:
  1318. * - allowed_values: a list array of one or more vocabulary trees:
  1319. * - vocabulary: a vocabulary machine name.
  1320. * - parent: a term ID of a term whose children are allowed. This should be
  1321. * '0' if all terms in a vocabulary are allowed. The allowed values do not
  1322. * include the parent term.
  1323. *
  1324. */
  1325. function taxonomy_field_info() {
  1326. return array(
  1327. 'taxonomy_term_reference' => array(
  1328. 'label' => t('Term reference'),
  1329. 'description' => t('This field stores a reference to a taxonomy term.'),
  1330. 'default_widget' => 'options_select',
  1331. 'default_formatter' => 'taxonomy_term_reference_link',
  1332. 'settings' => array(
  1333. 'allowed_values' => array(
  1334. array(
  1335. 'vocabulary' => '',
  1336. 'parent' => '0',
  1337. ),
  1338. ),
  1339. ),
  1340. ),
  1341. );
  1342. }
  1343. /**
  1344. * Implements hook_field_widget_info().
  1345. */
  1346. function taxonomy_field_widget_info() {
  1347. return array(
  1348. 'taxonomy_autocomplete' => array(
  1349. 'label' => t('Autocomplete term widget (tagging)'),
  1350. 'field types' => array('taxonomy_term_reference'),
  1351. 'settings' => array(
  1352. 'size' => 60,
  1353. 'autocomplete_path' => 'taxonomy/autocomplete',
  1354. ),
  1355. 'behaviors' => array(
  1356. 'multiple values' => FIELD_BEHAVIOR_CUSTOM,
  1357. ),
  1358. ),
  1359. );
  1360. }
  1361. /**
  1362. * Implements hook_field_widget_info_alter().
  1363. */
  1364. function taxonomy_field_widget_info_alter(&$info) {
  1365. $info['options_select']['field types'][] = 'taxonomy_term_reference';
  1366. $info['options_buttons']['field types'][] = 'taxonomy_term_reference';
  1367. }
  1368. /**
  1369. * Implements hook_options_list().
  1370. */
  1371. function taxonomy_options_list($field, $instance, $entity_type, $entity) {
  1372. $function = !empty($field['settings']['options_list_callback']) ? $field['settings']['options_list_callback'] : 'taxonomy_allowed_values';
  1373. return $function($field);
  1374. }
  1375. /**
  1376. * Implements hook_field_validate().
  1377. *
  1378. * Taxonomy field settings allow for either a single vocabulary ID, multiple
  1379. * vocabulary IDs, or sub-trees of a vocabulary to be specified as allowed
  1380. * values, although only the first of these is supported via the field UI.
  1381. * Confirm that terms entered as values meet at least one of these conditions.
  1382. *
  1383. * Possible error codes:
  1384. * - 'taxonomy_term_illegal_value': The value is not part of the list of allowed values.
  1385. */
  1386. function taxonomy_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  1387. // Build an array of existing term IDs so they can be loaded with
  1388. // taxonomy_term_load_multiple();
  1389. foreach ($items as $delta => $item) {
  1390. if (!empty($item['tid']) && $item['tid'] != 'autocreate') {
  1391. $tids[] = $item['tid'];
  1392. }
  1393. }
  1394. if (!empty($tids)) {
  1395. $terms = taxonomy_term_load_multiple($tids);
  1396. // Check each existing item to ensure it can be found in the
  1397. // allowed values for this field.
  1398. foreach ($items as $delta => $item) {
  1399. $validate = TRUE;
  1400. if (!empty($item['tid']) && $item['tid'] != 'autocreate') {
  1401. $validate = FALSE;
  1402. foreach ($field['settings']['allowed_values'] as $settings) {
  1403. // If no parent is specified, check if the term is in the vocabulary.
  1404. if (isset($settings['vocabulary']) && empty($settings['parent'])) {
  1405. if ($settings['vocabulary'] == $terms[$item['tid']]->vocabulary_machine_name) {
  1406. $validate = TRUE;
  1407. break;
  1408. }
  1409. }
  1410. // If a parent is specified, then to validate it must appear in the
  1411. // array returned by taxonomy_get_parents_all().
  1412. elseif (!empty($settings['parent'])) {
  1413. $ancestors = taxonomy_get_parents_all($item['tid']);
  1414. foreach ($ancestors as $ancestor) {
  1415. if ($ancestor->tid == $settings['parent']) {
  1416. $validate = TRUE;
  1417. break 2;
  1418. }
  1419. }
  1420. }
  1421. }
  1422. }
  1423. if (!$validate) {
  1424. $errors[$field['field_name']][$langcode][$delta][] = array(
  1425. 'error' => 'taxonomy_term_reference_illegal_value',
  1426. 'message' => t('%name: illegal value.', array('%name' => $instance['label'])),
  1427. );
  1428. }
  1429. }
  1430. }
  1431. }
  1432. /**
  1433. * Implements hook_field_is_empty().
  1434. */
  1435. function taxonomy_field_is_empty($item, $field) {
  1436. if (!is_array($item) || (empty($item['tid']) && (string) $item['tid'] !== '0')) {
  1437. return TRUE;
  1438. }
  1439. return FALSE;
  1440. }
  1441. /**
  1442. * Implements hook_field_formatter_info().
  1443. */
  1444. function taxonomy_field_formatter_info() {
  1445. return array(
  1446. 'taxonomy_term_reference_link' => array(
  1447. 'label' => t('Link'),
  1448. 'field types' => array('taxonomy_term_reference'),
  1449. ),
  1450. 'taxonomy_term_reference_plain' => array(
  1451. 'label' => t('Plain text'),
  1452. 'field types' => array('taxonomy_term_reference'),
  1453. ),
  1454. 'taxonomy_term_reference_rss_category' => array(
  1455. 'label' => t('RSS category'),
  1456. 'field types' => array('taxonomy_term_reference'),
  1457. ),
  1458. );
  1459. }
  1460. /**
  1461. * Implements hook_field_formatter_view().
  1462. */
  1463. function taxonomy_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  1464. $element = array();
  1465. // Terms whose tid is 'autocreate' do not exist
  1466. // yet and $item['taxonomy_term'] is not set. Theme such terms as
  1467. // just their name.
  1468. switch ($display['type']) {
  1469. case 'taxonomy_term_reference_link':
  1470. foreach ($items as $delta => $item) {
  1471. if ($item['tid'] == 'autocreate') {
  1472. $element[$delta] = array(
  1473. '#markup' => check_plain($item['name']),
  1474. );
  1475. }
  1476. else {
  1477. $term = $item['taxonomy_term'];
  1478. $uri = entity_uri('taxonomy_term', $term);
  1479. $element[$delta] = array(
  1480. '#type' => 'link',
  1481. '#title' => $term->name,
  1482. '#href' => $uri['path'],
  1483. '#options' => $uri['options'],
  1484. );
  1485. }
  1486. }
  1487. break;
  1488. case 'taxonomy_term_reference_plain':
  1489. foreach ($items as $delta => $item) {
  1490. $name = ($item['tid'] != 'autocreate' ? $item['taxonomy_term']->name : $item['name']);
  1491. $element[$delta] = array(
  1492. '#markup' => check_plain($name),
  1493. );
  1494. }
  1495. break;
  1496. case 'taxonomy_term_reference_rss_category':
  1497. foreach ($items as $delta => $item) {
  1498. $entity->rss_elements[] = array(
  1499. 'key' => 'category',
  1500. 'value' => $item['tid'] != 'autocreate' ? $item['taxonomy_term']->name : $item['name'],
  1501. 'attributes' => array(
  1502. 'domain' => $item['tid'] != 'autocreate' ? url('taxonomy/term/' . $item['tid'], array('absolute' => TRUE)) : '',
  1503. ),
  1504. );
  1505. }
  1506. break;
  1507. }
  1508. return $element;
  1509. }
  1510. /**
  1511. * Returns the set of valid terms for a taxonomy field.
  1512. *
  1513. * @param $field
  1514. * The field definition.
  1515. * @return
  1516. * The array of valid terms for this field, keyed by term id.
  1517. */
  1518. function taxonomy_allowed_values($field) {
  1519. $options = array();
  1520. foreach ($field['settings']['allowed_values'] as $tree) {
  1521. if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
  1522. if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'])) {
  1523. foreach ($terms as $term) {
  1524. $options[$term->tid] = str_repeat('-', $term->depth) . $term->name;
  1525. }
  1526. }
  1527. }
  1528. }
  1529. return $options;
  1530. }
  1531. /**
  1532. * Implements hook_field_formatter_prepare_view().
  1533. *
  1534. * This preloads all taxonomy terms for multiple loaded objects at once and
  1535. * unsets values for invalid terms that do not exist.
  1536. */
  1537. function taxonomy_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays) {
  1538. $tids = array();
  1539. // Collect every possible term attached to any of the fieldable entities.
  1540. foreach ($entities as $id => $entity) {
  1541. foreach ($items[$id] as $delta => $item) {
  1542. // Force the array key to prevent duplicates.
  1543. if ($item['tid'] != 'autocreate') {
  1544. $tids[$item['tid']] = $item['tid'];
  1545. }
  1546. }
  1547. }
  1548. if ($tids) {
  1549. $terms = taxonomy_term_load_multiple($tids);
  1550. // Iterate through the fieldable entities again to attach the loaded term data.
  1551. foreach ($entities as $id => $entity) {
  1552. $rekey = FALSE;
  1553. foreach ($items[$id] as $delta => $item) {
  1554. // Check whether the taxonomy term field instance value could be loaded.
  1555. if (isset($terms[$item['tid']])) {
  1556. // Replace the instance value with the term data.
  1557. $items[$id][$delta]['taxonomy_term'] = $terms[$item['tid']];
  1558. }
  1559. // Terms to be created are not in $terms, but are still legitimate.
  1560. elseif ($item['tid'] == 'autocreate') {
  1561. // Leave the item in place.
  1562. }
  1563. // Otherwise, unset the instance value, since the term does not exist.
  1564. else {
  1565. unset($items[$id][$delta]);
  1566. $rekey = TRUE;
  1567. }
  1568. }
  1569. if ($rekey) {
  1570. // Rekey the items array.
  1571. $items[$id] = array_values($items[$id]);
  1572. }
  1573. }
  1574. }
  1575. }
  1576. /**
  1577. * Title callback for term pages.
  1578. *
  1579. * @param $term
  1580. * A term object.
  1581. *
  1582. * @return
  1583. * The term name to be used as the page title.
  1584. */
  1585. function taxonomy_term_title($term) {
  1586. return $term->name;
  1587. }
  1588. /**
  1589. * Implements hook_field_widget_form().
  1590. */
  1591. function taxonomy_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  1592. $tags = array();
  1593. foreach ($items as $item) {
  1594. $tags[$item['tid']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
  1595. }
  1596. $element += array(
  1597. '#type' => 'textfield',
  1598. '#default_value' => taxonomy_implode_tags($tags),
  1599. '#autocomplete_path' => $instance['widget']['settings']['autocomplete_path'] . '/' . $field['field_name'],
  1600. '#size' => $instance['widget']['settings']['size'],
  1601. '#maxlength' => 1024,
  1602. '#element_validate' => array('taxonomy_autocomplete_validate'),
  1603. );
  1604. return $element;
  1605. }
  1606. /**
  1607. * Form element validate handler for taxonomy term autocomplete element.
  1608. */
  1609. function taxonomy_autocomplete_validate($element, &$form_state) {
  1610. // Autocomplete widgets do not send their tids in the form, so we must detect
  1611. // them here and process them independently.
  1612. $value = array();
  1613. if ($tags = $element['#value']) {
  1614. // Collect candidate vocabularies.
  1615. $field = field_widget_field($element, $form_state);
  1616. $vocabularies = array();
  1617. foreach ($field['settings']['allowed_values'] as $tree) {
  1618. if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
  1619. $vocabularies[$vocabulary->vid] = $vocabulary;
  1620. }
  1621. }
  1622. // Translate term names into actual terms.
  1623. $typed_terms = drupal_explode_tags($tags);
  1624. foreach ($typed_terms as $typed_term) {
  1625. // See if the term exists in the chosen vocabulary and return the tid;
  1626. // otherwise, create a new 'autocreate' term for insert/update.
  1627. if ($possibilities = taxonomy_term_load_multiple(array(), array('name' => trim($typed_term), 'vid' => array_keys($vocabularies)))) {
  1628. $term = array_pop($possibilities);
  1629. }
  1630. else {
  1631. $vocabulary = reset($vocabularies);
  1632. $term = array(
  1633. 'tid' => 'autocreate',
  1634. 'vid' => $vocabulary->vid,
  1635. 'name' => $typed_term,
  1636. 'vocabulary_machine_name' => $vocabulary->machine_name,
  1637. );
  1638. }
  1639. $value[] = (array)$term;
  1640. }
  1641. }
  1642. form_set_value($element, $value, $form_state);
  1643. }
  1644. /**
  1645. * Implements hook_field_widget_error().
  1646. */
  1647. function taxonomy_field_widget_error($element, $error, $form, &$form_state) {
  1648. form_error($element, $error['message']);
  1649. }
  1650. /**
  1651. * Implements hook_field_settings_form().
  1652. */
  1653. function taxonomy_field_settings_form($field, $instance, $has_data) {
  1654. // Get proper values for 'allowed_values_function', which is a core setting.
  1655. $vocabularies = taxonomy_get_vocabularies();
  1656. $options = array();
  1657. foreach ($vocabularies as $vocabulary) {
  1658. $options[$vocabulary->machine_name] = $vocabulary->name;
  1659. }
  1660. $form['allowed_values'] = array(
  1661. '#tree' => TRUE,
  1662. );
  1663. foreach ($field['settings']['allowed_values'] as $delta => $tree) {
  1664. $form['allowed_values'][$delta]['vocabulary'] = array(
  1665. '#type' => 'select',
  1666. '#title' => t('Vocabulary'),
  1667. '#default_value' => $tree['vocabulary'],
  1668. '#options' => $options,
  1669. '#required' => TRUE,
  1670. '#description' => t('The vocabulary which supplies the options for this field.'),
  1671. '#disabled' => $has_data,
  1672. );
  1673. $form['allowed_values'][$delta]['parent'] = array(
  1674. '#type' => 'value',
  1675. '#value' => $tree['parent'],
  1676. );
  1677. }
  1678. return $form;
  1679. }
  1680. /**
  1681. * Implements hook_rdf_mapping().
  1682. *
  1683. * @return array
  1684. * The rdf mapping for vocabularies and terms.
  1685. */
  1686. function taxonomy_rdf_mapping() {
  1687. return array(
  1688. array(
  1689. 'type' => 'taxonomy_term',
  1690. 'bundle' => RDF_DEFAULT_BUNDLE,
  1691. 'mapping' => array(
  1692. 'rdftype' => array('skos:Concept'),
  1693. 'name' => array(
  1694. 'predicates' => array('rdfs:label', 'skos:prefLabel'),
  1695. ),
  1696. 'description' => array(
  1697. 'predicates' => array('skos:definition'),
  1698. ),
  1699. 'vid' => array(
  1700. 'predicates' => array('skos:inScheme'),
  1701. 'type' => 'rel',
  1702. ),
  1703. 'parent' => array(
  1704. 'predicates' => array('skos:broader'),
  1705. 'type' => 'rel',
  1706. ),
  1707. ),
  1708. ),
  1709. array(
  1710. 'type' => 'taxonomy_vocabulary',
  1711. 'bundle' => RDF_DEFAULT_BUNDLE,
  1712. 'mapping' => array(
  1713. 'rdftype' => array('skos:ConceptScheme'),
  1714. 'name' => array(
  1715. 'predicates' => array('dc:title'),
  1716. ),
  1717. 'description' => array(
  1718. 'predicates' => array('rdfs:comment'),
  1719. ),
  1720. ),
  1721. ),
  1722. );
  1723. }
  1724. /**
  1725. * @defgroup taxonomy_index Taxonomy indexing
  1726. * @{
  1727. * Functions to maintain taxonomy indexing.
  1728. *
  1729. * Taxonomy uses default field storage to store canonical relationships
  1730. * between terms and fieldable entities. However its most common use case
  1731. * requires listing all content associated with a term or group of terms
  1732. * sorted by creation date. To avoid slow queries due to joining across
  1733. * multiple node and field tables with various conditions and order by criteria,
  1734. * we maintain a denormalized table with all relationships between terms,
  1735. * published nodes and common sort criteria such as sticky and created.
  1736. * This is used as a lookup table by taxonomy_select_nodes(). When using other
  1737. * field storage engines or alternative methods of denormalizing this data
  1738. * you should set the variable 'taxonomy_maintain_index_table' to FALSE
  1739. * to avoid unnecessary writes in SQL.
  1740. */
  1741. /**
  1742. * Implements hook_field_presave().
  1743. *
  1744. * Create any new terms defined in a freetagging vocabulary.
  1745. */
  1746. function taxonomy_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  1747. foreach ($items as $delta => $item) {
  1748. if ($item['tid'] == 'autocreate') {
  1749. $term = (object) $item;
  1750. unset($term->tid);
  1751. taxonomy_term_save($term);
  1752. $items[$delta]['tid'] = $term->tid;
  1753. }
  1754. }
  1755. }
  1756. /**
  1757. * Implements hook_node_insert().
  1758. */
  1759. function taxonomy_node_insert($node) {
  1760. // Add taxonomy index entries for the node.
  1761. taxonomy_build_node_index($node);
  1762. }
  1763. /**
  1764. * Builds and inserts taxonomy index entries for a given node.
  1765. *
  1766. * The index lists all terms that are related to a given node entity, and is
  1767. * therefore maintained at the entity level.
  1768. *
  1769. * @param $node
  1770. * The node object.
  1771. */
  1772. function taxonomy_build_node_index($node) {
  1773. // We maintain a denormalized table of term/node relationships, containing
  1774. // only data for current, published nodes.
  1775. $status = NULL;
  1776. if (variable_get('taxonomy_maintain_index_table', TRUE)) {
  1777. // If a node property is not set in the node object when node_save() is
  1778. // called, the old value from $node->original is used.
  1779. if (!empty($node->original)) {
  1780. $status = (int)(!empty($node->status) || (!isset($node->status) && !empty($node->original->status)));
  1781. $sticky = (int)(!empty($node->sticky) || (!isset($node->sticky) && !empty($node->original->sticky)));
  1782. }
  1783. else {
  1784. $status = (int)(!empty($node->status));
  1785. $sticky = (int)(!empty($node->sticky));
  1786. }
  1787. }
  1788. // We only maintain the taxonomy index for published nodes.
  1789. if ($status) {
  1790. // Collect a unique list of all the term IDs from all node fields.
  1791. $tid_all = array();
  1792. foreach (field_info_instances('node', $node->type) as $instance) {
  1793. $field_name = $instance['field_name'];
  1794. $field = field_info_field($field_name);
  1795. if ($field['module'] == 'taxonomy' && $field['storage']['type'] == 'field_sql_storage') {
  1796. // If a field value is not set in the node object when node_save() is
  1797. // called, the old value from $node->original is used.
  1798. if (isset($node->{$field_name})) {
  1799. $items = $node->{$field_name};
  1800. }
  1801. elseif (isset($node->original->{$field_name})) {
  1802. $items = $node->original->{$field_name};
  1803. }
  1804. else {
  1805. continue;
  1806. }
  1807. foreach (field_available_languages('node', $field) as $langcode) {
  1808. if (!empty($items[$langcode])) {
  1809. foreach ($items[$langcode] as $item) {
  1810. $tid_all[$item['tid']] = $item['tid'];
  1811. }
  1812. }
  1813. }
  1814. }
  1815. }
  1816. // Insert index entries for all the node's terms.
  1817. if (!empty($tid_all)) {
  1818. $query = db_insert('taxonomy_index')->fields(array('nid', 'tid', 'sticky', 'created'));
  1819. foreach ($tid_all as $tid) {
  1820. $query->values(array(
  1821. 'nid' => $node->nid,
  1822. 'tid' => $tid,
  1823. 'sticky' => $sticky,
  1824. 'created' => $node->created,
  1825. ));
  1826. }
  1827. $query->execute();
  1828. }
  1829. }
  1830. }
  1831. /**
  1832. * Implements hook_node_update().
  1833. */
  1834. function taxonomy_node_update($node) {
  1835. // Always rebuild the node's taxonomy index entries on node save.
  1836. taxonomy_delete_node_index($node);
  1837. taxonomy_build_node_index($node);
  1838. }
  1839. /**
  1840. * Implements hook_node_delete().
  1841. */
  1842. function taxonomy_node_delete($node) {
  1843. // Clean up the {taxonomy_index} table when nodes are deleted.
  1844. taxonomy_delete_node_index($node);
  1845. }
  1846. /**
  1847. * Deletes taxonomy index entries for a given node.
  1848. *
  1849. * @param $node
  1850. * The node object.
  1851. */
  1852. function taxonomy_delete_node_index($node) {
  1853. if (variable_get('taxonomy_maintain_index_table', TRUE)) {
  1854. db_delete('taxonomy_index')->condition('nid', $node->nid)->execute();
  1855. }
  1856. }
  1857. /**
  1858. * Implements hook_taxonomy_term_delete().
  1859. */
  1860. function taxonomy_taxonomy_term_delete($term) {
  1861. if (variable_get('taxonomy_maintain_index_table', TRUE)) {
  1862. // Clean up the {taxonomy_index} table when terms are deleted.
  1863. db_delete('taxonomy_index')->condition('tid', $term->tid)->execute();
  1864. }
  1865. }
  1866. /**
  1867. * @} End of "defgroup taxonomy_index".
  1868. */
  1869. /**
  1870. * Implements hook_entity_query_alter().
  1871. *
  1872. * Converts EntityFieldQuery instances on taxonomy terms that have an entity
  1873. * condition on term bundles (vocabulary machine names). Since the vocabulary
  1874. * machine name is not present in the {taxonomy_term_data} table itself, we have
  1875. * to convert the bundle condition into a property condition of vocabulary IDs
  1876. * to match against {taxonomy_term_data}.vid.
  1877. */
  1878. function taxonomy_entity_query_alter($query) {
  1879. $conditions = &$query->entityConditions;
  1880. // Alter only taxonomy term queries with bundle conditions.
  1881. if (isset($conditions['entity_type']) && $conditions['entity_type']['value'] == 'taxonomy_term' && isset($conditions['bundle'])) {
  1882. // Convert vocabulary machine names to vocabulary IDs.
  1883. $vocabulary_data = taxonomy_vocabulary_get_names();
  1884. $vids = array();
  1885. if (is_array($conditions['bundle']['value'])) {
  1886. foreach ($conditions['bundle']['value'] as $vocabulary_machine_name) {
  1887. $vids[] = $vocabulary_data[$vocabulary_machine_name]->vid;
  1888. }
  1889. }
  1890. else {
  1891. $vocabulary_machine_name = $conditions['bundle']['value'];
  1892. $vids = $vocabulary_data[$vocabulary_machine_name]->vid;
  1893. }
  1894. $query->propertyCondition('vid', $vids, $conditions['bundle']['operator']);
  1895. unset($conditions['bundle']);
  1896. }
  1897. }