taxonomy.module 70 KB

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