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 list terms for a vocabulary
taxonomy_admin_vocabulary_editPage to add or edit a vocabulary
taxonomy_autocompleteHelper function for autocompletion
taxonomy_del_term
taxonomy_del_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. Can be passed to form_select.
taxonomy_form_alterGenerate 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 to the given node, ordered by vocabulary and term weight.
taxonomy_node_get_terms_by_vocabularyFind all terms associated to the given node, within one vocabulary.
taxonomy_node_saveSave term associations for a given node.
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_term
taxonomy_save_vocabulary
taxonomy_select_nodesFinds all nodes that match selected taxonomy conditions.
taxonomy_term_confirm_delete_submit
taxonomy_term_count_nodesGiven a term id, count the number of published nodes in it.
taxonomy_term_pageMenu callback; displays all nodes associated with a term.
taxonomy_term_path
taxonomy_vocabulary_confirm_delete_submit
theme_taxonomy_term_select
_taxonomy_confirm_del_term
_taxonomy_confirm_del_vocabulary
_taxonomy_depth
_taxonomy_get_tid_from_termHelper function for array_map purposes.
_taxonomy_term_childrenHelper for taxonomy_term_count_nodes().
_taxonomy_term_select

File

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