taxonomy.module

  1. drupal
    1. 4.6 modules/taxonomy.module
    2. 4.7 modules/taxonomy.module
    3. 5 modules/taxonomy/taxonomy.module
    4. 6 modules/taxonomy/taxonomy.module
    5. 7 modules/taxonomy/taxonomy.module
    6. 8 core/modules/taxonomy/taxonomy.module

Enables the organization of content into categories.

Functions & methods

NameDescription
taxonomy_admin_term_editPage to edit a vocabulary term.
taxonomy_admin_vocabulary_editPage to edit a vocabulary.
taxonomy_autocompleteHelper function for autocompletion
taxonomy_del_termDelete a term.
taxonomy_del_vocabularyDelete a vocabulary.
taxonomy_formGenerate a form element for selecting terms from a vocabulary.
taxonomy_form_allGenerate a set of options for selecting a term from all vocabularies.
taxonomy_form_alterImplementation of hook_form_alter(). Generate a form for selecting terms to associate with a node.
taxonomy_form_term
taxonomy_form_term_submitAccept the form submission for a taxonomy term and save the result.
taxonomy_form_vocabularyDisplay form for adding and editing vocabularies.
taxonomy_form_vocabulary_submitAccept the form submission for a vocabulary and save the results.
taxonomy_get_childrenFind all children of a term ID.
taxonomy_get_parentsFind all parents of a given term ID.
taxonomy_get_parents_allFind all ancestors of a given term ID.
taxonomy_get_relatedFind all term objects related to a given term ID.
taxonomy_get_synonymsReturn an array of synonyms of the given term ID.
taxonomy_get_synonym_rootReturn the term object that has the given string as a synonym.
taxonomy_get_termReturn the term object matching a term ID.
taxonomy_get_term_by_nameTry to map a string to an existing term, as for glossary use.
taxonomy_get_treeCreate a hierarchical representation of a vocabulary.
taxonomy_get_vocabulariesReturn an array of all vocabulary objects.
taxonomy_get_vocabularyReturn the vocabulary object matching a vocabulary ID.
taxonomy_helpImplementation of hook_help().
taxonomy_linkImplementation of hook_link().
taxonomy_menuImplementation of hook_menu().
taxonomy_nodeapiImplementation of hook_nodeapi().
taxonomy_node_deleteRemove associations of a node to its terms.
taxonomy_node_get_termsFind all terms associated with the given node, ordered by vocabulary and term weight.
taxonomy_node_get_terms_by_vocabularyFind all terms associated with the given node, within one vocabulary.
taxonomy_node_saveSave term associations for a given node.
taxonomy_node_typeImplementation of hook_node_type().
taxonomy_node_update_indexImplementation of hook_nodeapi('update_index').
taxonomy_node_validateMake sure incoming vids are free tagging enabled.
taxonomy_overview_termsDisplay a tree of all the terms in a vocabulary, with options to edit each one.
taxonomy_overview_vocabulariesList and manage vocabularies.
taxonomy_permImplementation of hook_perm().
taxonomy_render_nodesAccepts the result of a pager_query() call, such as that performed by taxonomy_select_nodes(), and formats each node along with a pager.
taxonomy_rss_itemProvides category information for RSS feeds.
taxonomy_save_termHelper function for taxonomy_form_term_submit().
taxonomy_save_vocabulary
taxonomy_select_nodesFinds all nodes that match selected taxonomy conditions.
taxonomy_terms_parse_stringParses a comma or plus separated string of term IDs.
taxonomy_term_confirm_delete
taxonomy_term_confirm_delete_submit
taxonomy_term_count_nodesCount the number of published nodes classified by a term.
taxonomy_term_pageMenu callback; displays all nodes associated with a term.
taxonomy_term_pathFor vocabularies not maintained by taxonomy.module, give the maintaining module a chance to provide a path for terms in that vocabulary.
taxonomy_vocabulary_confirm_delete
taxonomy_vocabulary_confirm_delete_submit
theme_taxonomy_term_selectWe use the default selection field for choosing terms.
_taxonomy_get_tid_from_termHelper function for array_map purposes.
_taxonomy_term_childrenHelper for taxonomy_term_count_nodes(). Used to find out which terms are children of a parent term.
_taxonomy_term_selectCreate a select form element for a given taxonomy vocabulary.

File

modules/taxonomy/taxonomy.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * Enables the organization of content into categories.
  5. */
  6. /**
  7. * Implementation of hook_perm().
  8. */
  9. function taxonomy_perm() {
  10. return array('administer taxonomy');
  11. }
  12. /**
  13. * Implementation of hook_link().
  14. *
  15. * This hook is extended with $type = 'taxonomy terms' to allow themes to
  16. * print lists of terms associated with a node. Themes can print taxonomy
  17. * links with:
  18. *
  19. * if (module_exists('taxonomy')) {
  20. * $terms = taxonomy_link('taxonomy terms', $node);
  21. * print theme('links', $terms);
  22. * }
  23. */
  24. function taxonomy_link($type, $node = NULL) {
  25. if ($type == 'taxonomy terms' && $node != NULL) {
  26. $links = array();
  27. if (array_key_exists('taxonomy', $node)) {
  28. foreach ($node->taxonomy as $term) {
  29. $links['taxonomy_term_'. $term->tid] = array(
  30. 'title' => $term->name,
  31. 'href' => taxonomy_term_path($term),
  32. 'attributes' => array('rel' => 'tag', 'title' => strip_tags($term->description))
  33. );
  34. }
  35. }
  36. // We call this hook again because some modules and themes call taxonomy_link('taxonomy terms') directly
  37. foreach (module_implements('link_alter') as $module) {
  38. $function = $module .'_link_alter';
  39. $function($node, $links);
  40. }
  41. return $links;
  42. }
  43. }
  44. /**
  45. * For vocabularies not maintained by taxonomy.module, give the maintaining
  46. * module a chance to provide a path for terms in that vocabulary.
  47. *
  48. * @param $term
  49. * A term object.
  50. * @return
  51. * An internal Drupal path.
  52. */
  53. function taxonomy_term_path($term) {
  54. $vocabulary = taxonomy_get_vocabulary($term->vid);
  55. if ($vocabulary->module != 'taxonomy' && $path = module_invoke($vocabulary->module, 'term_path', $term)) {
  56. return $path;
  57. }
  58. return 'taxonomy/term/'. $term->tid;
  59. }
  60. /**
  61. * Implementation of hook_menu().
  62. */
  63. function taxonomy_menu($may_cache) {
  64. $items = array();
  65. if ($may_cache) {
  66. $items[] = array('path' => 'admin/content/taxonomy',
  67. 'title' => t('Categories'),
  68. 'description' => t('Create vocabularies and terms to categorize your content.'),
  69. 'callback' => 'taxonomy_overview_vocabularies',
  70. 'access' => user_access('administer taxonomy'));
  71. $items[] = array('path' => 'admin/content/taxonomy/list',
  72. 'title' => t('List'),
  73. 'type' => MENU_DEFAULT_LOCAL_TASK,
  74. 'weight' => -10);
  75. $items[] = array('path' => 'admin/content/taxonomy/add/vocabulary',
  76. 'title' => t('Add vocabulary'),
  77. 'callback' => 'drupal_get_form',
  78. 'callback arguments' => array('taxonomy_form_vocabulary'),
  79. 'access' => user_access('administer taxonomy'),
  80. 'type' => MENU_LOCAL_TASK);
  81. $items[] = array('path' => 'admin/content/taxonomy/edit/vocabulary',
  82. 'title' => t('Edit vocabulary'),
  83. 'callback' => 'taxonomy_admin_vocabulary_edit',
  84. 'access' => user_access('administer taxonomy'),
  85. 'type' => MENU_CALLBACK);
  86. $items[] = array('path' => 'admin/content/taxonomy/edit/term',
  87. 'title' => t('Edit term'),
  88. 'callback' => 'taxonomy_admin_term_edit',
  89. 'access' => user_access('administer taxonomy'),
  90. 'type' => MENU_CALLBACK);
  91. $items[] = array('path' => 'taxonomy/term',
  92. 'title' => t('Taxonomy term'),
  93. 'callback' => 'taxonomy_term_page',
  94. 'access' => user_access('access content'),
  95. 'type' => MENU_CALLBACK);
  96. $items[] = array('path' => 'taxonomy/autocomplete',
  97. 'title' => t('Autocomplete taxonomy'),
  98. 'callback' => 'taxonomy_autocomplete',
  99. 'access' => user_access('access content'),
  100. 'type' => MENU_CALLBACK);
  101. }
  102. else {
  103. if (arg(0) == 'admin' && arg(1) == 'content' && arg(2) == 'taxonomy' && is_numeric(arg(3))) {
  104. $vid = arg(3);
  105. $items[] = array('path' => 'admin/content/taxonomy/'. $vid,
  106. 'title' => t('List terms'),
  107. 'callback' => 'taxonomy_overview_terms',
  108. 'callback arguments' => array($vid),
  109. 'access' => user_access('administer taxonomy'),
  110. 'type' => MENU_CALLBACK);
  111. $items[] = array('path' => 'admin/content/taxonomy/'. $vid .'/list',
  112. 'title' => t('List'),
  113. 'type' => MENU_DEFAULT_LOCAL_TASK,
  114. 'weight' => -10);
  115. $items[] = array('path' => 'admin/content/taxonomy/'. $vid .'/add/term',
  116. 'title' => t('Add term'),
  117. 'callback' => 'drupal_get_form',
  118. 'callback arguments' => array('taxonomy_form_term', $vid),
  119. 'access' => user_access('administer taxonomy'),
  120. 'type' => MENU_LOCAL_TASK);
  121. }
  122. }
  123. return $items;
  124. }
  125. /**
  126. * List and manage vocabularies.
  127. */
  128. function taxonomy_overview_vocabularies() {
  129. $vocabularies = taxonomy_get_vocabularies();
  130. $rows = array();
  131. foreach ($vocabularies as $vocabulary) {
  132. $types = array();
  133. foreach ($vocabulary->nodes as $type) {
  134. $node_type = node_get_types('name', $type);
  135. $types[] = $node_type ? check_plain($node_type) : check_plain($type);
  136. }
  137. $rows[] = array('name' => check_plain($vocabulary->name),
  138. 'type' => implode(', ', $types),
  139. 'edit' => l(t('edit vocabulary'), "admin/content/taxonomy/edit/vocabulary/$vocabulary->vid"),
  140. 'list' => l(t('list terms'), "admin/content/taxonomy/$vocabulary->vid"),
  141. 'add' => l(t('add terms'), "admin/content/taxonomy/$vocabulary->vid/add/term")
  142. );
  143. }
  144. if (empty($rows)) {
  145. $rows[] = array(array('data' => t('No categories available.'), 'colspan' => '5'));
  146. }
  147. $header = array(t('Name'), t('Type'), array('data' => t('Operations'), 'colspan' => '3'));
  148. return theme('table', $header, $rows, array('id' => 'taxonomy'));
  149. }
  150. /**
  151. * Display a tree of all the terms in a vocabulary, with options to edit
  152. * each one.
  153. */
  154. function taxonomy_overview_terms($vid) {
  155. $destination = drupal_get_destination();
  156. $header = array(t('Name'), t('Operations'));
  157. $vocabulary = taxonomy_get_vocabulary($vid);
  158. if (!$vocabulary) {
  159. return drupal_not_found();
  160. }
  161. drupal_set_title(check_plain($vocabulary->name));
  162. $start_from = $_GET['page'] ? $_GET['page'] : 0;
  163. $total_entries = 0; // total count for pager
  164. $page_increment = 25; // number of tids per page
  165. $displayed_count = 0; // number of tids shown
  166. if ($vocabulary->tags) {
  167. // We are not calling taxonomy_get_tree because that might fail with a big
  168. // number of tags in the freetagging vocabulary.
  169. $results = pager_query(db_rewrite_sql('SELECT t.*, h.parent FROM {term_data} t INNER JOIN {term_hierarchy} h ON t.tid = h.tid WHERE t.vid = %d ORDER BY weight, name', 't', 'tid'), $page_increment, 0, NULL, $vid);
  170. while ($term = db_fetch_object($results)) {
  171. $rows[] = array(
  172. l($term->name, "taxonomy/term/$term->tid"),
  173. l(t('edit'), "admin/content/taxonomy/edit/term/$term->tid", array(), $destination),
  174. );
  175. }
  176. }
  177. else {
  178. $tree = taxonomy_get_tree($vocabulary->vid);
  179. foreach ($tree as $term) {
  180. $total_entries++; // we're counting all-totals, not displayed
  181. if (($start_from && ($start_from * $page_increment) >= $total_entries) || ($displayed_count == $page_increment)) {
  182. continue;
  183. }
  184. $rows[] = array(str_repeat('--', $term->depth) .' '. l($term->name, "taxonomy/term/$term->tid"), l(t('edit'), "admin/content/taxonomy/edit/term/$term->tid", array(), $destination));
  185. $displayed_count++; // we're counting tids displayed
  186. }
  187. if (!$rows) {
  188. $rows[] = array(array('data' => t('No terms available.'), 'colspan' => '2'));
  189. }
  190. $GLOBALS['pager_page_array'][] = $start_from; // FIXME
  191. $GLOBALS['pager_total'][] = intval($total_entries / $page_increment) + 1; // FIXME
  192. }
  193. $output .= theme('table', $header, $rows, array('id' => 'taxonomy'));
  194. if ($vocabulary->tags || $total_entries >= $page_increment) {
  195. $output .= theme('pager', NULL, $page_increment);
  196. }
  197. return $output;
  198. }
  199. /**
  200. * Display form for adding and editing vocabularies.
  201. */
  202. function taxonomy_form_vocabulary($edit = array()) {
  203. $form['name'] = array('#type' => 'textfield',
  204. '#title' => t('Vocabulary name'),
  205. '#default_value' => $edit['name'],
  206. '#maxlength' => 255,
  207. '#description' => t('The name for this vocabulary. Example: "Topic".'),
  208. '#required' => TRUE,
  209. );
  210. $form['description'] = array('#type' => 'textarea',
  211. '#title' => t('Description'),
  212. '#default_value' => $edit['description'],
  213. '#description' => t('Description of the vocabulary; can be used by modules.'),
  214. );
  215. $form['help'] = array('#type' => 'textfield',
  216. '#title' => t('Help text'),
  217. '#maxlength' => 255,
  218. '#default_value' => $edit['help'],
  219. '#description' => t('Instructions to present to the user when choosing a term.'),
  220. );
  221. $form['nodes'] = array('#type' => 'checkboxes',
  222. '#title' => t('Types'),
  223. '#default_value' => $edit['nodes'],
  224. '#options' => array_map('check_plain', node_get_types('names')),
  225. '#description' => t('A list of node types you want to associate with this vocabulary.'),
  226. '#required' => TRUE,
  227. );
  228. $form['hierarchy'] = array('#type' => 'radios',
  229. '#title' => t('Hierarchy'),
  230. '#default_value' => $edit['hierarchy'],
  231. '#options' => array(t('Disabled'), t('Single'), t('Multiple')),
  232. '#description' => t('Allows <a href="@help-url">a tree-like hierarchy</a> between terms of this vocabulary.', array('@help-url' => url('admin/help/taxonomy', NULL, NULL, 'hierarchy'))),
  233. );
  234. $form['relations'] = array('#type' => 'checkbox',
  235. '#title' => t('Related terms'),
  236. '#default_value' => $edit['relations'],
  237. '#description' => t('Allows <a href="@help-url">related terms</a> in this vocabulary.', array('@help-url' => url('admin/help/taxonomy', NULL, NULL, 'related-terms'))),
  238. );
  239. $form['tags'] = array('#type' => 'checkbox',
  240. '#title' => t('Free tagging'),
  241. '#default_value' => $edit['tags'],
  242. '#description' => t('Content is categorized by typing terms instead of choosing from a list.'),
  243. );
  244. $form['multiple'] = array('#type' => 'checkbox',
  245. '#title' => t('Multiple select'),
  246. '#default_value' => $edit['multiple'],
  247. '#description' => t('Allows nodes to have more than one term from this vocabulary (always true for free tagging).'),
  248. );
  249. $form['required'] = array('#type' => 'checkbox',
  250. '#title' => t('Required'),
  251. '#default_value' => $edit['required'],
  252. '#description' => t('If enabled, every node <strong>must</strong> have at least one term in this vocabulary.'),
  253. );
  254. $form['weight'] = array('#type' => 'weight',
  255. '#title' => t('Weight'),
  256. '#default_value' => $edit['weight'],
  257. '#description' => t('In listings, the heavier vocabularies will sink and the lighter vocabularies will be positioned nearer the top.'),
  258. );
  259. $form['submit'] = array('#type' => 'submit', '#value' => t('Submit'));
  260. if ($edit['vid']) {
  261. $form['delete'] = array('#type' => 'submit', '#value' => t('Delete'));
  262. $form['vid'] = array('#type' => 'value', '#value' => $edit['vid']);
  263. $form['module'] = array('#type' => 'value', '#value' => $edit['module']);
  264. }
  265. return $form;
  266. }
  267. /**
  268. * Accept the form submission for a vocabulary and save the results.
  269. */
  270. function taxonomy_form_vocabulary_submit($form_id, $form_values) {
  271. // Fix up the nodes array to remove unchecked nodes.
  272. $form_values['nodes'] = array_filter($form_values['nodes']);
  273. switch (taxonomy_save_vocabulary($form_values)) {
  274. case SAVED_NEW:
  275. drupal_set_message(t('Created new vocabulary %name.', array('%name' => $form_values['name'])));
  276. watchdog('taxonomy', t('Created new vocabulary %name.', array('%name' => $form_values['name'])), WATCHDOG_NOTICE, l(t('edit'), 'admin/content/taxonomy/edit/vocabulary/'. $form_values['vid']));
  277. break;
  278. case SAVED_UPDATED:
  279. drupal_set_message(t('Updated vocabulary %name.', array('%name' => $form_values['name'])));
  280. watchdog('taxonomy', t('Updated vocabulary %name.', array('%name' => $form_values['name'])), WATCHDOG_NOTICE, l(t('edit'), 'admin/content/taxonomy/edit/vocabulary/'. $form_values['vid']));
  281. break;
  282. }
  283. return 'admin/content/taxonomy';
  284. }
  285. function taxonomy_save_vocabulary(&$edit) {
  286. $edit['nodes'] = empty($edit['nodes']) ? array() : $edit['nodes'];
  287. if ($edit['vid'] && $edit['name']) {
  288. db_query("UPDATE {vocabulary} SET name = '%s', description = '%s', help = '%s', multiple = %d, required = %d, hierarchy = %d, relations = %d, tags = %d, weight = %d, module = '%s' WHERE vid = %d", $edit['name'], $edit['description'], $edit['help'], $edit['multiple'], $edit['required'], $edit['hierarchy'], $edit['relations'], $edit['tags'], $edit['weight'], isset($edit['module']) ? $edit['module'] : 'taxonomy', $edit['vid']);
  289. db_query("DELETE FROM {vocabulary_node_types} WHERE vid = %d", $edit['vid']);
  290. foreach ($edit['nodes'] as $type => $selected) {
  291. db_query("INSERT INTO {vocabulary_node_types} (vid, type) VALUES (%d, '%s')", $edit['vid'], $type);
  292. }
  293. module_invoke_all('taxonomy', 'update', 'vocabulary', $edit);
  294. $status = SAVED_UPDATED;
  295. }
  296. else if ($edit['vid']) {
  297. $status = taxonomy_del_vocabulary($edit['vid']);
  298. }
  299. else {
  300. $edit['vid'] = db_next_id('{vocabulary}_vid');
  301. db_query("INSERT INTO {vocabulary} (vid, name, description, help, multiple, required, hierarchy, relations, tags, weight, module) VALUES (%d, '%s', '%s', '%s', %d, %d, %d, %d, %d, %d, '%s')", $edit['vid'], $edit['name'], $edit['description'], $edit['help'], $edit['multiple'], $edit['required'], $edit['hierarchy'], $edit['relations'], $edit['tags'], $edit['weight'], isset($edit['module']) ? $edit['module'] : 'taxonomy');
  302. foreach ($edit['nodes'] as $type => $selected) {
  303. db_query("INSERT INTO {vocabulary_node_types} (vid, type) VALUES (%d, '%s')", $edit['vid'], $type);
  304. }
  305. module_invoke_all('taxonomy', 'insert', 'vocabulary', $edit);
  306. $status = SAVED_NEW;
  307. }
  308. cache_clear_all();
  309. return $status;
  310. }
  311. /**
  312. * Delete a vocabulary.
  313. *
  314. * @param $vid
  315. * A vocabulary ID.
  316. * @return
  317. * Constant indicating items were deleted.
  318. */
  319. function taxonomy_del_vocabulary($vid) {
  320. $vocabulary = (array) taxonomy_get_vocabulary($vid);
  321. db_query('DELETE FROM {vocabulary} WHERE vid = %d', $vid);
  322. db_query('DELETE FROM {vocabulary_node_types} WHERE vid = %d', $vid);
  323. $result = db_query('SELECT tid FROM {term_data} WHERE vid = %d', $vid);
  324. while ($term = db_fetch_object($result)) {
  325. taxonomy_del_term($term->tid);
  326. }
  327. module_invoke_all('taxonomy', 'delete', 'vocabulary', $vocabulary);
  328. cache_clear_all();
  329. return SAVED_DELETED;
  330. }
  331. function taxonomy_vocabulary_confirm_delete($vid) {
  332. $vocabulary = taxonomy_get_vocabulary($vid);
  333. $form['type'] = array('#type' => 'value', '#value' => 'vocabulary');
  334. $form['vid'] = array('#type' => 'value', '#value' => $vid);
  335. $form['name'] = array('#type' => 'value', '#value' => $vocabulary->name);
  336. return confirm_form($form,
  337. t('Are you sure you want to delete the vocabulary %title?',
  338. array('%title' => $vocabulary->name)),
  339. 'admin/content/taxonomy',
  340. t('Deleting a vocabulary will delete all the terms in it. This action cannot be undone.'),
  341. t('Delete'),
  342. t('Cancel'));
  343. }
  344. function taxonomy_vocabulary_confirm_delete_submit($form_id, $form_values) {
  345. $status = taxonomy_del_vocabulary($form_values['vid']);
  346. drupal_set_message(t('Deleted vocabulary %name.', array('%name' => $form_values['name'])));
  347. watchdog('taxonomy', t('Deleted vocabulary %name.', array('%name' => $form_values['name'])), WATCHDOG_NOTICE);
  348. return 'admin/content/taxonomy';
  349. }
  350. function taxonomy_form_term($vocabulary_id, $edit = array()) {
  351. $vocabulary = taxonomy_get_vocabulary($vocabulary_id);
  352. drupal_set_title(check_plain($vocabulary->name));
  353. $form['name'] = array(
  354. '#type' => 'textfield',
  355. '#title' => t('Term name'),
  356. '#default_value' => $edit['name'],
  357. '#maxlength' => 255,
  358. '#description' => t('The name of this term.'),
  359. '#required' => TRUE);
  360. $form['description'] = array(
  361. '#type' => 'textarea',
  362. '#title' => t('Description'),
  363. '#default_value' => $edit['description'],
  364. '#description' => t('A description of the term.'));
  365. if ($vocabulary->hierarchy) {
  366. $parent = array_keys(taxonomy_get_parents($edit['tid']));
  367. $children = taxonomy_get_tree($vocabulary_id, $edit['tid']);
  368. // A term can't be the child of itself, nor of its children.
  369. foreach ($children as $child) {
  370. $exclude[] = $child->tid;
  371. }
  372. $exclude[] = $edit['tid'];
  373. if ($vocabulary->hierarchy == 1) {
  374. $form['parent'] = _taxonomy_term_select(t('Parent'), 'parent', $parent, $vocabulary_id, l(t('Parent term'), 'admin/help/taxonomy', NULL, NULL, 'parent') .'.', 0, '<'. t('root') .'>', $exclude);
  375. }
  376. elseif ($vocabulary->hierarchy == 2) {
  377. $form['parent'] = _taxonomy_term_select(t('Parents'), 'parent', $parent, $vocabulary_id, l(t('Parent terms'), 'admin/help/taxonomy', NULL, NULL, 'parent') .'.', 1, '<'. t('root') .'>', $exclude);
  378. }
  379. }
  380. if ($vocabulary->relations) {
  381. $form['relations'] = _taxonomy_term_select(t('Related terms'), 'relations', array_keys(taxonomy_get_related($edit['tid'])), $vocabulary_id, NULL, 1, '<'. t('none') .'>', array($edit['tid']));
  382. }
  383. $form['synonyms'] = array(
  384. '#type' => 'textarea',
  385. '#title' => t('Synonyms'),
  386. '#default_value' => implode("\n", taxonomy_get_synonyms($edit['tid'])),
  387. '#description' => t('<a href="@help-url">Synonyms</a> of this term, one synonym per line.', array('@help-url' => url('admin/help/taxonomy', NULL, NULL, 'synonyms'))));
  388. $form['weight'] = array(
  389. '#type' => 'weight',
  390. '#title' => t('Weight'),
  391. '#default_value' => $edit['weight'],
  392. '#description' => t('In listings, the heavier terms will sink and the lighter terms will be positioned nearer the top.'));
  393. $form['vid'] = array(
  394. '#type' => 'value',
  395. '#value' => $vocabulary->vid);
  396. $form['submit'] = array(
  397. '#type' => 'submit',
  398. '#value' => t('Submit'));
  399. if ($edit['tid']) {
  400. $form['delete'] = array(
  401. '#type' => 'submit',
  402. '#value' => t('Delete'));
  403. $form['tid'] = array(
  404. '#type' => 'value',
  405. '#value' => $edit['tid']);
  406. }
  407. else {
  408. $form['destination'] = array('#type' => 'hidden', '#value' => $_GET['q']);
  409. }
  410. return $form;
  411. }
  412. /**
  413. * Accept the form submission for a taxonomy term and save the result.
  414. */
  415. function taxonomy_form_term_submit($form_id, $form_values) {
  416. switch (taxonomy_save_term($form_values)) {
  417. case SAVED_NEW:
  418. drupal_set_message(t('Created new term %term.', array('%term' => $form_values['name'])));
  419. watchdog('taxonomy', t('Created new term %term.', array('%term' => $form_values['name'])), WATCHDOG_NOTICE, l(t('edit'), 'admin/content/taxonomy/edit/term/'. $form_values['tid']));
  420. break;
  421. case SAVED_UPDATED:
  422. drupal_set_message(t('Updated term %term.', array('%term' => $form_values['name'])));
  423. watchdog('taxonomy', t('Updated term %term.', array('%term' => $form_values['name'])), WATCHDOG_NOTICE, l(t('edit'), 'admin/content/taxonomy/edit/term/'. $form_values['tid']));
  424. break;
  425. }
  426. return 'admin/content/taxonomy';
  427. }
  428. /**
  429. * Helper function for taxonomy_form_term_submit().
  430. *
  431. * @param $form_values
  432. * @return
  433. * Status constant indicating if term was inserted or updated.
  434. */
  435. function taxonomy_save_term(&$form_values) {
  436. if ($form_values['tid'] && $form_values['name']) {
  437. db_query("UPDATE {term_data} SET name = '%s', description = '%s', weight = %d WHERE tid = %d", $form_values['name'], $form_values['description'], $form_values['weight'], $form_values['tid']);
  438. $hook = 'update';
  439. $status = SAVED_UPDATED;
  440. }
  441. else if ($form_values['tid']) {
  442. return taxonomy_del_term($form_values['tid']);
  443. }
  444. else {
  445. $form_values['tid'] = db_next_id('{term_data}_tid');
  446. db_query("INSERT INTO {term_data} (tid, name, description, vid, weight) VALUES (%d, '%s', '%s', %d, %d)", $form_values['tid'], $form_values['name'], $form_values['description'], $form_values['vid'], $form_values['weight']);
  447. $hook = 'insert';
  448. $status = SAVED_NEW;
  449. }
  450. db_query('DELETE FROM {term_relation} WHERE tid1 = %d OR tid2 = %d', $form_values['tid'], $form_values['tid']);
  451. if ($form_values['relations']) {
  452. foreach ($form_values['relations'] as $related_id) {
  453. if ($related_id != 0) {
  454. db_query('INSERT INTO {term_relation} (tid1, tid2) VALUES (%d, %d)', $form_values['tid'], $related_id);
  455. }
  456. }
  457. }
  458. db_query('DELETE FROM {term_hierarchy} WHERE tid = %d', $form_values['tid']);
  459. if (!isset($form_values['parent']) || empty($form_values['parent'])) {
  460. $form_values['parent'] = array(0);
  461. }
  462. if (is_array($form_values['parent'])) {
  463. foreach ($form_values['parent'] as $parent) {
  464. if (is_array($parent)) {
  465. foreach ($parent as $tid) {
  466. db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $form_values['tid'], $tid);
  467. }
  468. }
  469. else {
  470. db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $form_values['tid'], $parent);
  471. }
  472. }
  473. }
  474. else {
  475. db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $form_values['tid'], $form_values['parent']);
  476. }
  477. db_query('DELETE FROM {term_synonym} WHERE tid = %d', $form_values['tid']);
  478. if ($form_values['synonyms']) {
  479. foreach (explode ("\n", str_replace("\r", '', $form_values['synonyms'])) as $synonym) {
  480. if ($synonym) {
  481. db_query("INSERT INTO {term_synonym} (tid, name) VALUES (%d, '%s')", $form_values['tid'], chop($synonym));
  482. }
  483. }
  484. }
  485. if (isset($hook)) {
  486. module_invoke_all('taxonomy', $hook, 'term', $form_values);
  487. }
  488. cache_clear_all();
  489. return $status;
  490. }
  491. /**
  492. * Delete a term.
  493. *
  494. * @param $tid
  495. * The term ID.
  496. * @return
  497. * Status constant indicating deletion.
  498. */
  499. function taxonomy_del_term($tid) {
  500. $tids = array($tid);
  501. while ($tids) {
  502. $children_tids = $orphans = array();
  503. foreach ($tids as $tid) {
  504. // See if any of the term's children are about to be become orphans:
  505. if ($children = taxonomy_get_children($tid)) {
  506. foreach ($children as $child) {
  507. // If the term has multiple parents, we don't delete it.
  508. $parents = taxonomy_get_parents($child->tid);
  509. if (count($parents) == 1) {
  510. $orphans[] = $child->tid;
  511. }
  512. }
  513. }
  514. $term = (array) taxonomy_get_term($tid);
  515. db_query('DELETE FROM {term_data} WHERE tid = %d', $tid);
  516. db_query('DELETE FROM {term_hierarchy} WHERE tid = %d', $tid);
  517. db_query('DELETE FROM {term_relation} WHERE tid1 = %d OR tid2 = %d', $tid, $tid);
  518. db_query('DELETE FROM {term_synonym} WHERE tid = %d', $tid);
  519. db_query('DELETE FROM {term_node} WHERE tid = %d', $tid);
  520. module_invoke_all('taxonomy', 'delete', 'term', $term);
  521. }
  522. $tids = $orphans;
  523. }
  524. cache_clear_all();
  525. return SAVED_DELETED;
  526. }
  527. function taxonomy_term_confirm_delete($tid) {
  528. $term = taxonomy_get_term($tid);
  529. $form['type'] = array('#type' => 'value', '#value' => 'term');
  530. $form['name'] = array('#type' => 'value', '#value' => $term->name);
  531. $form['tid'] = array('#type' => 'value', '#value' => $tid);
  532. return confirm_form($form,
  533. t('Are you sure you want to delete the term %title?',
  534. array('%title' => $term->name)),
  535. 'admin/content/taxonomy',
  536. t('Deleting a term will delete all its children if there are any. This action cannot be undone.'),
  537. t('Delete'),
  538. t('Cancel'));
  539. }
  540. function taxonomy_term_confirm_delete_submit($form_id, $form_values) {
  541. taxonomy_del_term($form_values['tid']);
  542. drupal_set_message(t('Deleted term %name.', array('%name' => $form_values['name'])));
  543. watchdog('taxonomy', t('Deleted term %name.', array('%name' => $form_values['name'])), WATCHDOG_NOTICE);
  544. return 'admin/content/taxonomy';
  545. }
  546. /**
  547. * Generate a form element for selecting terms from a vocabulary.
  548. */
  549. function taxonomy_form($vid, $value = 0, $help = NULL, $name = 'taxonomy') {
  550. $vocabulary = taxonomy_get_vocabulary($vid);
  551. $help = ($help) ? $help : filter_xss_admin($vocabulary->help);
  552. if (!$vocabulary->multiple) {
  553. $blank = ($vocabulary->required) ? t('- Please choose -') : t('- None selected -');
  554. }
  555. else {
  556. $blank = ($vocabulary->required) ? 0 : t('- None -');
  557. }
  558. return _taxonomy_term_select(check_plain($vocabulary->name), $name, $value, $vid, $help, intval($vocabulary->multiple), $blank);
  559. }
  560. /**
  561. * Generate a set of options for selecting a term from all vocabularies.
  562. */
  563. function taxonomy_form_all($free_tags = 0) {
  564. $vocabularies = taxonomy_get_vocabularies();
  565. $options = array();
  566. foreach ($vocabularies as $vid => $vocabulary) {
  567. if ($vocabulary->tags && !$free_tags) { continue; }
  568. $tree = taxonomy_get_tree($vid);
  569. if ($tree && (count($tree) > 0)) {
  570. $options[$vocabulary->name] = array();
  571. foreach ($tree as $term) {
  572. $options[$vocabulary->name][$term->tid] = str_repeat('-', $term->depth) . $term->name;
  573. }
  574. }
  575. }
  576. return $options;
  577. }
  578. /**
  579. * Return an array of all vocabulary objects.
  580. *
  581. * @param $type
  582. * If set, return only those vocabularies associated with this node type.
  583. */
  584. function taxonomy_get_vocabularies($type = NULL) {
  585. if ($type) {
  586. $result = db_query(db_rewrite_sql("SELECT v.vid, v.*, n.type FROM {vocabulary} v LEFT JOIN {vocabulary_node_types} n ON v.vid = n.vid WHERE n.type = '%s' ORDER BY v.weight, v.name", 'v', 'vid'), $type);
  587. }
  588. else {
  589. $result = db_query(db_rewrite_sql('SELECT v.*, n.type FROM {vocabulary} v LEFT JOIN {vocabulary_node_types} n ON v.vid = n.vid ORDER BY v.weight, v.name', 'v', 'vid'));
  590. }
  591. $vocabularies = array();
  592. $node_types = array();
  593. while ($voc = db_fetch_object($result)) {
  594. $node_types[$voc->vid][] = $voc->type;
  595. unset($voc->type);
  596. $voc->nodes = $node_types[$voc->vid];
  597. $vocabularies[$voc->vid] = $voc;
  598. }
  599. return $vocabularies;
  600. }
  601. /**
  602. * Implementation of hook_form_alter().
  603. * Generate a form for selecting terms to associate with a node.
  604. */
  605. function taxonomy_form_alter($form_id, &$form) {
  606. if (isset($form['type']) && $form['type']['#value'] .'_node_form' == $form_id) {
  607. $node = $form['#node'];
  608. if (!isset($node->taxonomy)) {
  609. if ($node->nid) {
  610. $terms = taxonomy_node_get_terms($node->nid);
  611. }
  612. else {
  613. $terms = array();
  614. }
  615. }
  616. else {
  617. $terms = $node->taxonomy;
  618. }
  619. $c = db_query(db_rewrite_sql("SELECT v.* FROM {vocabulary} v INNER JOIN {vocabulary_node_types} n ON v.vid = n.vid WHERE n.type = '%s' ORDER BY v.weight, v.name", 'v', 'vid'), $node->type);
  620. while ($vocabulary = db_fetch_object($c)) {
  621. if ($vocabulary->tags) {
  622. $typed_terms = array();
  623. foreach ($terms as $term) {
  624. // Extract terms belonging to the vocabulary in question.
  625. if ($term->vid == $vocabulary->vid) {
  626. // Commas and quotes in terms are special cases, so encode 'em.
  627. if (strpos($term->name, ',') !== FALSE || strpos($term->name, '"') !== FALSE) {
  628. $term->name = '"'.str_replace('"', '""', $term->name).'"';
  629. }
  630. $typed_terms[] = $term->name;
  631. }
  632. }
  633. $typed_string = implode(', ', $typed_terms) . (array_key_exists('tags', $terms) ? $terms['tags'][$vocabulary->vid] : NULL);
  634. if ($vocabulary->help) {
  635. $help = filter_xss_admin($vocabulary->help);
  636. }
  637. else {
  638. $help = t('A comma-separated list of terms describing this content. Example: funny, bungee jumping, "Company, Inc.".');
  639. }
  640. $form['taxonomy']['tags'][$vocabulary->vid] = array('#type' => 'textfield',
  641. '#title' => $vocabulary->name,
  642. '#description' => $help,
  643. '#required' => $vocabulary->required,
  644. '#default_value' => $typed_string,
  645. '#autocomplete_path' => 'taxonomy/autocomplete/'. $vocabulary->vid,
  646. '#weight' => $vocabulary->weight,
  647. '#maxlength' => 1024,
  648. );
  649. }
  650. else {
  651. // Extract terms belonging to the vocabulary in question.
  652. $default_terms = array();
  653. foreach ($terms as $term) {
  654. if ($term->vid == $vocabulary->vid) {
  655. $default_terms[$term->tid] = $term;
  656. }
  657. }
  658. $form['taxonomy'][$vocabulary->vid] = taxonomy_form($vocabulary->vid, array_keys($default_terms), filter_xss_admin($vocabulary->help));
  659. $form['taxonomy'][$vocabulary->vid]['#weight'] = $vocabulary->weight;
  660. $form['taxonomy'][$vocabulary->vid]['#required'] = $vocabulary->required;
  661. }
  662. }
  663. if (is_array($form['taxonomy']) && !empty($form['taxonomy'])) {
  664. if (count($form['taxonomy']) > 1) { // Add fieldset only if form has more than 1 element.
  665. $form['taxonomy'] += array(
  666. '#type' => 'fieldset',
  667. '#title' => t('Categories'),
  668. '#collapsible' => TRUE,
  669. '#collapsed' => FALSE,
  670. );
  671. }
  672. $form['taxonomy']['#weight'] = -3;
  673. $form['taxonomy']['#tree'] = TRUE;
  674. }
  675. }
  676. }
  677. /**
  678. * Find all terms associated with the given node, within one vocabulary.
  679. */
  680. function taxonomy_node_get_terms_by_vocabulary($nid, $vid, $key = 'tid') {
  681. $result = db_query(db_rewrite_sql('SELECT t.tid, t.* FROM {term_data} t INNER JOIN {term_node} r ON r.tid = t.tid WHERE t.vid = %d AND r.nid = %d ORDER BY weight', 't', 'tid'), $vid, $nid);
  682. $terms = array();
  683. while ($term = db_fetch_object($result)) {
  684. $terms[$term->$key] = $term;
  685. }
  686. return $terms;
  687. }
  688. /**
  689. * Find all terms associated with the given node, ordered by vocabulary and term weight.
  690. */
  691. function taxonomy_node_get_terms($nid, $key = 'tid') {
  692. static $terms;
  693. if (!isset($terms[$nid][$key])) {
  694. $result = db_query(db_rewrite_sql('SELECT t.* FROM {term_node} r INNER JOIN {term_data} t ON r.tid = t.tid INNER JOIN {vocabulary} v ON t.vid = v.vid WHERE r.nid = %d ORDER BY v.weight, t.weight, t.name', 't', 'tid'), $nid);
  695. $terms[$nid][$key] = array();
  696. while ($term = db_fetch_object($result)) {
  697. $terms[$nid][$key][$term->$key] = $term;
  698. }
  699. }
  700. return $terms[$nid][$key];
  701. }
  702. /**
  703. * Make sure incoming vids are free tagging enabled.
  704. */
  705. function taxonomy_node_validate(&$node) {
  706. if ($node->taxonomy) {
  707. $terms = $node->taxonomy;
  708. if ($terms['tags']) {
  709. foreach ($terms['tags'] as $vid => $vid_value) {
  710. $vocabulary = taxonomy_get_vocabulary($vid);
  711. if (!$vocabulary->tags) {
  712. // see form_get_error $key = implode('][', $element['#parents']);
  713. // on why this is the key
  714. form_set_error("taxonomy][tags][$vid", t('The %name vocabulary can not be modified in this way.', array('%name' => $vocabulary->name)));
  715. }
  716. }
  717. }
  718. }
  719. }
  720. /**
  721. * Save term associations for a given node.
  722. */
  723. function taxonomy_node_save($nid, $terms) {
  724. taxonomy_node_delete($nid);
  725. // Free tagging vocabularies do not send their tids in the form,
  726. // so we'll detect them here and process them independently.
  727. if (isset($terms['tags'])) {
  728. $typed_input = $terms['tags'];
  729. unset($terms['tags']);
  730. foreach ($typed_input as $vid => $vid_value) {
  731. // This regexp allows the following types of user input:
  732. // this, "somecmpany, llc", "and ""this"" w,o.rks", foo bar
  733. $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
  734. preg_match_all($regexp, $vid_value, $matches);
  735. $typed_terms = array_unique($matches[1]);
  736. $inserted = array();
  737. foreach ($typed_terms as $typed_term) {
  738. // If a user has escaped a term (to demonstrate that it is a group,
  739. // or includes a comma or quote character), we remove the escape
  740. // formatting so to save the term into the database as the user intends.
  741. $typed_term = str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $typed_term));
  742. $typed_term = trim($typed_term);
  743. if ($typed_term == "") { continue; }
  744. // See if the term exists in the chosen vocabulary
  745. // and return the tid; otherwise, add a new record.
  746. $possibilities = taxonomy_get_term_by_name($typed_term);
  747. $typed_term_tid = NULL; // tid match, if any.
  748. foreach ($possibilities as $possibility) {
  749. if ($possibility->vid == $vid) {
  750. $typed_term_tid = $possibility->tid;
  751. }
  752. }
  753. if (!$typed_term_tid) {
  754. $edit = array('vid' => $vid, 'name' => $typed_term);
  755. $status = taxonomy_save_term($edit);
  756. $typed_term_tid = $edit['tid'];
  757. }
  758. // Defend against duplicate, differently cased tags
  759. if (!isset($inserted[$typed_term_tid])) {
  760. db_query('INSERT INTO {term_node} (nid, tid) VALUES (%d, %d)', $nid, $typed_term_tid);
  761. $inserted[$typed_term_tid] = TRUE;
  762. }
  763. }
  764. }
  765. }
  766. if (is_array($terms)) {
  767. foreach ($terms as $term) {
  768. if (is_array($term)) {
  769. foreach ($term as $tid) {
  770. if ($tid) {
  771. db_query('INSERT INTO {term_node} (nid, tid) VALUES (%d, %d)', $nid, $tid);
  772. }
  773. }
  774. }
  775. else if (is_object($term)) {
  776. db_query('INSERT INTO {term_node} (nid, tid) VALUES (%d, %d)', $nid, $term->tid);
  777. }
  778. else if ($term) {
  779. db_query('INSERT INTO {term_node} (nid, tid) VALUES (%d, %d)', $nid, $term);
  780. }
  781. }
  782. }
  783. }
  784. /**
  785. * Remove associations of a node to its terms.
  786. */
  787. function taxonomy_node_delete($nid) {
  788. db_query('DELETE FROM {term_node} WHERE nid = %d', $nid);
  789. }
  790. /**
  791. * Implementation of hook_node_type().
  792. */
  793. function taxonomy_node_type($op, $info) {
  794. if ($op == 'update' && !empty($info->old_type) && $info->type != $info->old_type) {
  795. db_query("UPDATE {vocabulary_node_types} SET type = '%s' WHERE type = '%s'", $info->type, $info->old_type);
  796. }
  797. elseif ($op == 'delete') {
  798. db_query("DELETE FROM {vocabulary_node_types} WHERE type = '%s'", $info->type);
  799. }
  800. }
  801. /**
  802. * Find all term objects related to a given term ID.
  803. */
  804. function taxonomy_get_related($tid, $key = 'tid') {
  805. if ($tid) {
  806. $result = db_query('SELECT t.*, tid1, tid2 FROM {term_relation}, {term_data} t WHERE (t.tid = tid1 OR t.tid = tid2) AND (tid1 = %d OR tid2 = %d) AND t.tid != %d ORDER BY weight, name', $tid, $tid, $tid);
  807. $related = array();
  808. while ($term = db_fetch_object($result)) {
  809. $related[$term->$key] = $term;
  810. }
  811. return $related;
  812. }
  813. else {
  814. return array();
  815. }
  816. }
  817. /**
  818. * Find all parents of a given term ID.
  819. */
  820. function taxonomy_get_parents($tid, $key = 'tid') {
  821. if ($tid) {
  822. $result = db_query(db_rewrite_sql('SELECT t.tid, t.* FROM {term_data} t INNER JOIN {term_hierarchy} h ON h.parent = t.tid WHERE h.tid = %d ORDER BY weight, name', 't', 'tid'), $tid);
  823. $parents = array();
  824. while ($parent = db_fetch_object($result)) {
  825. $parents[$parent->$key] = $parent;
  826. }
  827. return $parents;
  828. }
  829. else {
  830. return array();
  831. }
  832. }
  833. /**
  834. * Find all ancestors of a given term ID.
  835. */
  836. function taxonomy_get_parents_all($tid) {
  837. $parents = array();
  838. if ($tid) {
  839. $parents[] = taxonomy_get_term($tid);
  840. $n = 0;
  841. while ($parent = taxonomy_get_parents($parents[$n]->tid)) {
  842. $parents = array_merge($parents, $parent);
  843. $n++;
  844. }
  845. }
  846. return $parents;
  847. }
  848. /**
  849. * Find all children of a term ID.
  850. */
  851. function taxonomy_get_children($tid, $vid = 0, $key = 'tid') {
  852. if ($vid) {
  853. $result = db_query(db_rewrite_sql('SELECT t.* FROM {term_data} t INNER JOIN {term_hierarchy} h ON h.tid = t.tid WHERE t.vid = %d AND h.parent = %d ORDER BY weight, name', 't', 'tid'), $vid, $tid);
  854. }
  855. else {
  856. $result = db_query(db_rewrite_sql('SELECT t.* FROM {term_data} t INNER JOIN {term_hierarchy} h ON h.tid = t.tid WHERE parent = %d ORDER BY weight, name', 't', 'tid'), $tid);
  857. }
  858. $children = array();
  859. while ($term = db_fetch_object($result)) {
  860. $children[$term->$key] = $term;
  861. }
  862. return $children;
  863. }
  864. /**
  865. * Create a hierarchical representation of a vocabulary.
  866. *
  867. * @param $vid
  868. * Which vocabulary to generate the tree for.
  869. *
  870. * @param $parent
  871. * The term ID under which to generate the tree. If 0, generate the tree
  872. * for the entire vocabulary.
  873. *
  874. * @param $depth
  875. * Internal use only.
  876. *
  877. * @param $max_depth
  878. * The number of levels of the tree to return. Leave NULL to return all levels.
  879. *
  880. * @return
  881. * An array of all term objects in the tree. Each term object is extended
  882. * to have "depth" and "parents" attributes in addition to its normal ones.
  883. * Results are statically cached.
  884. */
  885. function taxonomy_get_tree($vid, $parent = 0, $depth = -1, $max_depth = NULL) {
  886. static $children, $parents, $terms;
  887. $depth++;
  888. // We cache trees, so it's not CPU-intensive to call get_tree() on a term
  889. // and its children, too.
  890. if (!isset($children[$vid])) {
  891. $children[$vid] = array();
  892. $result = db_query(db_rewrite_sql('SELECT t.tid, t.*, parent FROM {term_data} t INNER JOIN {term_hierarchy} h ON t.tid = h.tid WHERE t.vid = %d ORDER BY weight, name', 't', 'tid'), $vid);
  893. while ($term = db_fetch_object($result)) {
  894. $children[$vid][$term->parent][] = $term->tid;
  895. $parents[$vid][$term->tid][] = $term->parent;
  896. $terms[$vid][$term->tid] = $term;
  897. }
  898. }
  899. $max_depth = (is_null($max_depth)) ? count($children[$vid]) : $max_depth;
  900. if ($children[$vid][$parent]) {
  901. foreach ($children[$vid][$parent] as $child) {
  902. if ($max_depth > $depth) {
  903. $term = drupal_clone($terms[$vid][$child]);
  904. $term->depth = $depth;
  905. // The "parent" attribute is not useful, as it would show one parent only.
  906. unset($term->parent);
  907. $term->parents = $parents[$vid][$child];
  908. $tree[] = $term;
  909. if ($children[$vid][$child]) {
  910. $tree = array_merge($tree, taxonomy_get_tree($vid, $child, $depth, $max_depth));
  911. }
  912. }
  913. }
  914. }
  915. return $tree ? $tree : array();
  916. }
  917. /**
  918. * Return an array of synonyms of the given term ID.
  919. */
  920. function taxonomy_get_synonyms($tid) {
  921. if ($tid) {
  922. $result = db_query('SELECT name FROM {term_synonym} WHERE tid = %d', $tid);
  923. while ($synonym = db_fetch_array($result)) {
  924. $synonyms[] = $synonym['name'];
  925. }
  926. return $synonyms ? $synonyms : array();
  927. }
  928. else {
  929. return array();
  930. }
  931. }
  932. /**
  933. * Return the term object that has the given string as a synonym.
  934. */
  935. function taxonomy_get_synonym_root($synonym) {
  936. return db_fetch_object(db_query("SELECT * FROM {term_synonym} s, {term_data} t WHERE t.tid = s.tid AND s.name = '%s'", $synonym));
  937. }
  938. /**
  939. * Count the number of published nodes classified by a term.
  940. *
  941. * @param $tid
  942. * The term's ID
  943. *
  944. * @param $type
  945. * The $node->type. If given, taxonomy_term_count_nodes only counts
  946. * nodes of $type that are classified with the term $tid.
  947. *
  948. * @return int
  949. * An integer representing a number of nodes.
  950. * Results are statically cached.
  951. */
  952. function taxonomy_term_count_nodes($tid, $type = 0) {
  953. static $count;
  954. if (!isset($count[$type])) {
  955. // $type == 0 always evaluates TRUE if $type is a string
  956. if (is_numeric($type)) {
  957. $result = db_query(db_rewrite_sql('SELECT t.tid, COUNT(n.nid) AS c FROM {term_node} t INNER JOIN {node} n ON t.nid = n.nid WHERE n.status = 1 GROUP BY t.tid'));
  958. }
  959. else {
  960. $result = db_query(db_rewrite_sql("SELECT t.tid, COUNT(n.nid) AS c FROM {term_node} t INNER JOIN {node} n ON t.nid = n.nid WHERE n.status = 1 AND n.type = '%s' GROUP BY t.tid"), $type);
  961. }
  962. $count[$type] = array();
  963. while ($term = db_fetch_object($result)) {
  964. $count[$type][$term->tid] = $term->c;
  965. }
  966. }
  967. foreach (_taxonomy_term_children($tid) as $c) {
  968. $children_count += taxonomy_term_count_nodes($c, $type);
  969. }
  970. return $count[$type][$tid] + $children_count;
  971. }
  972. /**
  973. * Helper for taxonomy_term_count_nodes(). Used to find out
  974. * which terms are children of a parent term.
  975. *
  976. * @param $tid
  977. * The parent term's ID
  978. *
  979. * @return array
  980. * An array of term IDs representing the children of $tid.
  981. * Results are statically cached.
  982. *
  983. */
  984. function _taxonomy_term_children($tid) {
  985. static $children;
  986. if (!isset($children)) {
  987. $result = db_query('SELECT tid, parent FROM {term_hierarchy}');
  988. while ($term = db_fetch_object($result)) {
  989. $children[$term->parent][] = $term->tid;
  990. }
  991. }
  992. return $children[$tid] ? $children[$tid] : array();
  993. }
  994. /**
  995. * Try to map a string to an existing term, as for glossary use.
  996. *
  997. * Provides a case-insensitive and trimmed mapping, to maximize the
  998. * likelihood of a successful match.
  999. *
  1000. * @param name
  1001. * Name of the term to search for.
  1002. *
  1003. * @return
  1004. * An array of matching term objects.
  1005. */
  1006. function taxonomy_get_term_by_name($name) {
  1007. $db_result = db_query(db_rewrite_sql("SELECT t.tid, t.* FROM {term_data} t WHERE LOWER('%s') = LOWER(t.name)", 't', 'tid'), trim($name));
  1008. $result = array();
  1009. while ($term = db_fetch_object($db_result)) {
  1010. $result[] = $term;
  1011. }
  1012. return $result;
  1013. }
  1014. /**
  1015. * Return the vocabulary object matching a vocabulary ID.
  1016. *
  1017. * @param $vid
  1018. * The vocabulary's ID
  1019. *
  1020. * @return Object
  1021. * The vocabulary object with all of its metadata.
  1022. * Results are statically cached.
  1023. */
  1024. function taxonomy_get_vocabulary($vid) {
  1025. static $vocabularies = array();
  1026. if (!array_key_exists($vid, $vocabularies)) {
  1027. $result = db_query('SELECT v.*, n.type FROM {vocabulary} v LEFT JOIN {vocabulary_node_types} n ON v.vid = n.vid WHERE v.vid = %d ORDER BY v.weight, v.name', $vid);
  1028. $node_types = array();
  1029. while ($voc = db_fetch_object($result)) {
  1030. $node_types[] = $voc->type;
  1031. unset($voc->type);
  1032. $voc->nodes = $node_types;
  1033. $vocabularies[$vid] = $voc;
  1034. }
  1035. }
  1036. return $vocabularies[$vid];
  1037. }
  1038. /**
  1039. * Return the term object matching a term ID.
  1040. *
  1041. * @param $tid
  1042. * A term's ID
  1043. *
  1044. * @return Object
  1045. * A term object. Results are statically cached.
  1046. */
  1047. function taxonomy_get_term($tid) {
  1048. static $terms = array();
  1049. if (!isset($terms[$tid])) {
  1050. $terms[$tid] = db_fetch_object(db_query('SELECT * FROM {term_data} WHERE tid = %d', $tid));
  1051. }
  1052. return $terms[$tid];
  1053. }
  1054. /**
  1055. * Create a select form element for a given taxonomy vocabulary.
  1056. *
  1057. * NOTE: This function expects input that has already been sanitized and is
  1058. * safe for display. Callers must properly sanitize the $title and
  1059. * $description arguments to prevent XSS vulnerabilities.
  1060. *
  1061. * @param $title
  1062. * The title of the vocabulary. This MUST be sanitized by the caller.
  1063. * @param $name
  1064. * Ignored.
  1065. * @param $value
  1066. * The currently selected terms from this vocabulary, if any.
  1067. * @param $vocabulary_id
  1068. * The vocabulary ID to build the form element for.
  1069. * @param $description
  1070. * Help text for the form element. This MUST be sanitized by the caller.
  1071. * @param $multiple
  1072. * Boolean to control if the form should use a single or multiple select.
  1073. * @param $blank
  1074. * Optional form choice to use when no value has been selected.
  1075. * @param $exclude
  1076. * Optional array of term ids to exclude in the selector.
  1077. * @return
  1078. * A FAPI form array to select terms from the given vocabulary.
  1079. *
  1080. * @see taxonomy_form()
  1081. * @see taxonomy_form_term()
  1082. */
  1083. function _taxonomy_term_select($title, $name, $value, $vocabulary_id, $description, $multiple, $blank, $exclude = array()) {
  1084. $tree = taxonomy_get_tree($vocabulary_id);
  1085. $options = array();
  1086. if ($blank) {
  1087. $options[''] = $blank;
  1088. }
  1089. if ($tree) {
  1090. foreach ($tree as $term) {
  1091. if (!in_array($term->tid, $exclude)) {
  1092. $choice = new stdClass();
  1093. $choice->option = array($term->tid => str_repeat('-', $term->depth) . $term->name);
  1094. $options[] = $choice;
  1095. }
  1096. }
  1097. }
  1098. return array('#type' => 'select',
  1099. '#title' => $title,
  1100. '#default_value' => $value,
  1101. '#options' => $options,
  1102. '#description' => $description,
  1103. '#multiple' => $multiple,
  1104. '#size' => $multiple ? min(9, count($options)) : 0,
  1105. '#weight' => -15,
  1106. '#theme' => 'taxonomy_term_select',
  1107. );
  1108. }
  1109. /**
  1110. * We use the default selection field for choosing terms.
  1111. */
  1112. function theme_taxonomy_term_select($element) {
  1113. return theme('select', $element);
  1114. }
  1115. /**
  1116. * Finds all nodes that match selected taxonomy conditions.
  1117. *
  1118. * @param $tids
  1119. * An array of term IDs to match.
  1120. * @param $operator
  1121. * How to interpret multiple IDs in the array. Can be "or" or "and".
  1122. * @param $depth
  1123. * How many levels deep to traverse the taxonomy tree. Can be a nonnegative
  1124. * integer or "all".
  1125. * @param $pager
  1126. * Whether the nodes are to be used with a pager (the case on most Drupal
  1127. * pages) or not (in an XML feed, for example).
  1128. * @param $order
  1129. * The order clause for the query that retrieve the nodes.
  1130. * @return
  1131. * A resource identifier pointing to the query results.
  1132. */
  1133. function taxonomy_select_nodes($tids = array(), $operator = 'or', $depth = 0, $pager = TRUE, $order = 'n.sticky DESC, n.created DESC') {
  1134. if (count($tids) > 0) {
  1135. // For each term ID, generate an array of descendant term IDs to the right depth.
  1136. $descendant_tids = array();
  1137. if ($depth === 'all') {
  1138. $depth = NULL;
  1139. }
  1140. foreach ($tids as $index => $tid) {
  1141. $term = taxonomy_get_term($tid);
  1142. $tree = taxonomy_get_tree($term->vid, $tid, -1, $depth);
  1143. $descendant_tids[] = array_merge(array($tid), array_map('_taxonomy_get_tid_from_term', $tree));
  1144. }
  1145. if ($operator == 'or') {
  1146. $args = call_user_func_array('array_merge', $descendant_tids);
  1147. $placeholders = implode(',', array_fill(0, count($args), '%d'));
  1148. $sql = 'SELECT DISTINCT(n.nid), n.sticky, n.title, n.created FROM {node} n INNER JOIN {term_node} tn ON n.nid = tn.nid WHERE tn.tid IN ('. $placeholders .') AND n.status = 1 ORDER BY '. $order;
  1149. $sql_count = 'SELECT COUNT(DISTINCT(n.nid)) FROM {node} n INNER JOIN {term_node} tn ON n.nid = tn.nid WHERE tn.tid IN ('. $placeholders .') AND n.status = 1';
  1150. }
  1151. else {
  1152. $joins = '';
  1153. $wheres = '';
  1154. $args = array();
  1155. foreach ($descendant_tids as $index => $tids) {
  1156. $joins .= ' INNER JOIN {term_node} tn'. $index .' ON n.nid = tn'. $index .'.nid';
  1157. $placeholders = implode(',', array_fill(0, count($tids), '%d'));
  1158. $wheres .= ' AND tn'. $index .'.tid IN ('. $placeholders .')';
  1159. $args = array_merge($args, $tids);
  1160. }
  1161. $sql = 'SELECT DISTINCT(n.nid), n.sticky, n.title, n.created FROM {node} n '. $joins .' WHERE n.status = 1 '. $wheres .' ORDER BY '. $order;
  1162. $sql_count = 'SELECT COUNT(DISTINCT(n.nid)) FROM {node} n '. $joins .' WHERE n.status = 1 '. $wheres;
  1163. }
  1164. $sql = db_rewrite_sql($sql);
  1165. $sql_count = db_rewrite_sql($sql_count);
  1166. if ($pager) {
  1167. $result = pager_query($sql, variable_get('default_nodes_main', 10), 0, $sql_count, $args);
  1168. }
  1169. else {
  1170. $result = db_query_range($sql, $args, 0, variable_get('feed_default_items', 10));
  1171. }
  1172. }
  1173. return $result;
  1174. }
  1175. /**
  1176. * Accepts the result of a pager_query() call, such as that performed by
  1177. * taxonomy_select_nodes(), and formats each node along with a pager.
  1178. */
  1179. function taxonomy_render_nodes($result) {
  1180. $output = '';
  1181. if (db_num_rows($result) > 0) {
  1182. while ($node = db_fetch_object($result)) {
  1183. $output .= node_view(node_load($node->nid), 1);
  1184. }
  1185. $output .= theme('pager', NULL, variable_get('default_nodes_main', 10), 0);
  1186. }
  1187. else {
  1188. $output .= '<p>'. t('There are currently no posts in this category.') .'</p>';
  1189. }
  1190. return $output;
  1191. }
  1192. /**
  1193. * Implementation of hook_nodeapi().
  1194. */
  1195. function taxonomy_nodeapi($node, $op, $arg = 0) {
  1196. switch ($op) {
  1197. case 'load':
  1198. $output['taxonomy'] = taxonomy_node_get_terms($node->nid);
  1199. return $output;
  1200. case 'insert':
  1201. taxonomy_node_save($node->nid, $node->taxonomy);
  1202. break;
  1203. case 'update':
  1204. taxonomy_node_save($node->nid, $node->taxonomy);
  1205. break;
  1206. case 'delete':
  1207. taxonomy_node_delete($node->nid);
  1208. break;
  1209. case 'validate':
  1210. taxonomy_node_validate($node);
  1211. break;
  1212. case 'rss item':
  1213. return taxonomy_rss_item($node);
  1214. case 'update index':
  1215. return taxonomy_node_update_index($node);
  1216. }
  1217. }
  1218. /**
  1219. * Implementation of hook_nodeapi('update_index').
  1220. */
  1221. function taxonomy_node_update_index(&$node) {
  1222. $output = array();
  1223. foreach ($node->taxonomy as $term) {
  1224. $output[] = $term->name;
  1225. }
  1226. if (count($output)) {
  1227. return '<strong>('. implode(', ', $output) .')</strong>';
  1228. }
  1229. }
  1230. /**
  1231. * Parses a comma or plus separated string of term IDs.
  1232. *
  1233. * @param $str_tids
  1234. * A string of term IDs, separated by plus or comma.
  1235. * comma (,) means AND
  1236. * plus (+) means OR
  1237. *
  1238. * @return an associative array with an operator key (either 'and'
  1239. * or 'or') and a tid key containing an array of the term ids.
  1240. */
  1241. function taxonomy_terms_parse_string($str_tids) {
  1242. $terms = array();
  1243. if (preg_match('/^([0-9]+[+ ])+[0-9]+$/', $str_tids)) {
  1244. $terms['operator'] = 'or';
  1245. // The '+' character in a query string may be parsed as ' '.
  1246. $terms['tids'] = preg_split('/[+ ]/', $str_tids);
  1247. }
  1248. else if (preg_match('/^([0-9]+,)*[0-9]+$/', $str_tids)) {
  1249. $terms['operator'] = 'and';
  1250. $terms['tids'] = explode(',', $str_tids);
  1251. }
  1252. return $terms;
  1253. }
  1254. /**
  1255. * Menu callback; displays all nodes associated with a term.
  1256. */
  1257. function taxonomy_term_page($str_tids = '', $depth = 0, $op = 'page') {
  1258. $terms = taxonomy_terms_parse_string($str_tids);
  1259. if ($terms['operator'] != 'and' && $terms['operator'] != 'or') {
  1260. drupal_not_found();
  1261. }
  1262. if ($terms['tids']) {
  1263. $placeholders = implode(',', array_fill(0, count($terms['tids']), '%d'));
  1264. $result = db_query(db_rewrite_sql('SELECT t.tid, t.name FROM {term_data} t WHERE t.tid IN ('. $placeholders .')', 't', 'tid'), $terms['tids']);
  1265. $tids = array(); // we rebuild the $tids-array so it only contains terms the user has access to.
  1266. $names = array();
  1267. while ($term = db_fetch_object($result)) {
  1268. $tids[] = $term->tid;
  1269. $names[] = $term->name;
  1270. }
  1271. if ($names) {
  1272. $title = check_plain(implode(', ', $names));
  1273. drupal_set_title($title);
  1274. switch ($op) {
  1275. case 'page':
  1276. // Build breadcrumb based on first hierarchy of first term:
  1277. $current->tid = $tids[0];
  1278. $breadcrumbs = array(array('path' => $_GET['q'], 'title' => $names[0]));
  1279. while ($parents = taxonomy_get_parents($current->tid)) {
  1280. $current = array_shift($parents);
  1281. $breadcrumbs[] = array('path' => 'taxonomy/term/'. $current->tid, 'title' => $current->name);
  1282. }
  1283. $breadcrumbs = array_reverse($breadcrumbs);
  1284. menu_set_location($breadcrumbs);
  1285. $output = taxonomy_render_nodes(taxonomy_select_nodes($tids, $terms['operator'], $depth, TRUE));
  1286. drupal_add_feed(url('taxonomy/term/'. $str_tids .'/'. $depth .'/feed'), 'RSS - '. $title);
  1287. return $output;
  1288. break;
  1289. case 'feed':
  1290. $term = taxonomy_get_term($tids[0]);
  1291. $channel['link'] = url('taxonomy/term/'. $str_tids .'/'. $depth, NULL, NULL, TRUE);
  1292. $channel['title'] = variable_get('site_name', 'Drupal') .' - '. $title;
  1293. $channel['description'] = $term->description;
  1294. $result = taxonomy_select_nodes($tids, $terms['operator'], $depth, FALSE);
  1295. node_feed($result, $channel);
  1296. break;
  1297. default:
  1298. drupal_not_found();
  1299. }
  1300. }
  1301. else {
  1302. drupal_not_found();
  1303. }
  1304. }
  1305. }
  1306. /**
  1307. * Page to edit a vocabulary.
  1308. */
  1309. function taxonomy_admin_vocabulary_edit($vid = NULL) {
  1310. if ($_POST['op'] == t('Delete') || $_POST['confirm']) {
  1311. return drupal_get_form('taxonomy_vocabulary_confirm_delete', $vid);
  1312. }
  1313. if ($vocabulary = (array)taxonomy_get_vocabulary($vid)) {
  1314. return drupal_get_form('taxonomy_form_vocabulary', $vocabulary);
  1315. }
  1316. return drupal_not_found();
  1317. }
  1318. /**
  1319. * Page to edit a vocabulary term.
  1320. */
  1321. function taxonomy_admin_term_edit($tid) {
  1322. if ($_POST['op'] == t('Delete') || $_POST['confirm']) {
  1323. return drupal_get_form('taxonomy_term_confirm_delete', $tid);
  1324. }
  1325. if ($term = (array)taxonomy_get_term($tid)) {
  1326. return drupal_get_form('taxonomy_form_term', $term['vid'], $term);
  1327. }
  1328. return drupal_not_found();
  1329. }
  1330. /**
  1331. * Provides category information for RSS feeds.
  1332. */
  1333. function taxonomy_rss_item($node) {
  1334. $output = array();
  1335. foreach ($node->taxonomy as $term) {
  1336. $output[] = array('key' => 'category',
  1337. 'value' => check_plain($term->name),
  1338. 'attributes' => array('domain' => url('taxonomy/term/'. $term->tid, NULL, NULL, TRUE)));
  1339. }
  1340. return $output;
  1341. }
  1342. /**
  1343. * Implementation of hook_help().
  1344. */
  1345. function taxonomy_help($section) {
  1346. switch ($section) {
  1347. case 'admin/help#taxonomy':
  1348. $output = '<p>'. t('The taxonomy module is one of the most popular features because users often want to create categories to organize content by type. A simple example would be organizing a list of music reviews by musical genre.') .'</p>';
  1349. $output .= '<p>'. t('Taxonomy is the study of classification. The taxonomy module allows you to define vocabularies (sets of categories) which are used to classify content. The module supports hierarchical classification and association between terms, allowing for truly flexible information retrieval and classification. The taxonomy module allows multiple lists of categories for classification (controlled vocabularies) and offers the possibility of creating thesauri (controlled vocabularies that indicate the relationship of terms) and taxonomies (controlled vocabularies where relationships are indicated hierarchically). To view and manage the terms of each vocabulary, click on the associated <em>list terms</em> link. To delete a vocabulary and all its terms, choose <em>edit vocabulary.</em>') .'</p>';
  1350. $output .= '<p>'. t('A controlled vocabulary is a set of terms to use for describing content (known as descriptors in indexing lingo). Drupal allows you to describe each piece of content (blog, story, etc.) using one or many of these terms. For simple implementations, you might create a set of categories without subcategories, similar to Slashdot\'s sections. For more complex implementations, you might create a hierarchical list of categories.') .'</p>';
  1351. $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="@taxonomy">Taxonomy page</a>.', array('@taxonomy' => 'http://drupal.org/handbook/modules/taxonomy/')) .'</p>';
  1352. return $output;
  1353. case 'admin/content/taxonomy':
  1354. return '<p>'. t('The taxonomy module allows you to classify content into categories and subcategories; it allows multiple lists of categories for classification (controlled vocabularies) and offers the possibility of creating thesauri (controlled vocabularies that indicate the relationship of terms), taxonomies (controlled vocabularies where relationships are indicated hierarchically), and free vocabularies where terms, or tags, are defined during content creation. To view and manage the terms of each vocabulary, click on the associated <em>list terms</em> link. To delete a vocabulary and all its terms, choose "edit vocabulary".') .'</p>';
  1355. case 'admin/content/taxonomy/add/vocabulary':
  1356. return '<p>'. t("When you create a controlled vocabulary you are creating a set of terms to use for describing content (known as descriptors in indexing lingo). Drupal allows you to describe each piece of content (blog, story, etc.) using one or many of these terms. For simple implementations, you might create a set of categories without subcategories. For more complex implementations, you might create a hierarchical list of categories.") .'</p>';
  1357. }
  1358. }
  1359. /**
  1360. * Helper function for array_map purposes.
  1361. */
  1362. function _taxonomy_get_tid_from_term($term) {
  1363. return $term->tid;
  1364. }
  1365. /**
  1366. * Helper function for autocompletion
  1367. */
  1368. function taxonomy_autocomplete($vid, $string = '') {
  1369. // The user enters a comma-separated list of tags. We only autocomplete the last tag.
  1370. // This regexp allows the following types of user input:
  1371. // this, "somecmpany, llc", "and ""this"" w,o.rks", foo bar
  1372. $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
  1373. preg_match_all($regexp, $string, $matches);
  1374. $array = $matches[1];
  1375. // Fetch last tag
  1376. $last_string = trim(array_pop($array));
  1377. if ($last_string != '') {
  1378. $result = db_query_range(db_rewrite_sql("SELECT t.tid, t.name FROM {term_data} t WHERE t.vid = %d AND LOWER(t.name) LIKE LOWER('%%%s%%')", 't', 'tid'), $vid, $last_string, 0, 10);
  1379. $prefix = count($array) ? implode(', ', $array) .', ' : '';
  1380. $matches = array();
  1381. while ($tag = db_fetch_object($result)) {
  1382. $n = $tag->name;
  1383. // Commas and quotes in terms are special cases, so encode 'em.
  1384. if (strpos($tag->name, ',') !== FALSE || strpos($tag->name, '"') !== FALSE) {
  1385. $n = '"'. str_replace('"', '""', $tag->name) .'"';
  1386. }
  1387. $matches[$prefix . $n] = check_plain($tag->name);
  1388. }
  1389. print drupal_to_js($matches);
  1390. exit();
  1391. }
  1392. }
Login or register to post comments