taxonomy.module 69 KB

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