taxonomy.module

You are here

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

Enables the organization of content into categories.

Functions

Namesort descending Description
taxonomy_check_vocabulary_hierarchy Dynamically check and update the hierarachy flag of a vocabulary. Checks and updates the hierarchy flag of a vocabulary.
taxonomy_del_term Delete a term.
taxonomy_del_vocabulary Delete a vocabulary.
taxonomy_form Generate a form element for selecting terms from a vocabulary.
taxonomy_form_all Generate a set of options for selecting a term from all vocabularies.
taxonomy_form_alter Implementation of hook_form_alter(). Generate a form for selecting terms to associate with a node. We check for taxonomy_override_selector before loading the full vocabulary, so contrib modules can intercept before hook_form_alter and provide scalable…
taxonomy_get_children Find all children of a term ID.
taxonomy_get_parents Find all parents of a given term ID.
taxonomy_get_parents_all Find all ancestors of a given term ID.
taxonomy_get_related Find all term objects related to a given term ID.
taxonomy_get_synonyms Return an array of synonyms of the given term ID.
taxonomy_get_synonym_root Return the term object that has the given string as a synonym.
taxonomy_get_term Return the term object matching a term ID.
taxonomy_get_term_by_name Try to map a string to an existing term, as for glossary use.
taxonomy_get_tree Create a hierarchical representation of a vocabulary.
taxonomy_get_vocabularies Return an array of all vocabulary objects.
taxonomy_help Implementation of hook_help().
taxonomy_hook_info Implementation of hook_hook_info().
taxonomy_implode_tags Implodes a list of tags of a certain vocabulary into a string.
taxonomy_link Implementation of hook_link().
taxonomy_menu Implementation of hook_menu().
taxonomy_nodeapi Implementation of hook_nodeapi().
taxonomy_node_delete Remove associations of a node to its terms.
taxonomy_node_delete_revision Remove associations of a node to its terms.
taxonomy_node_get_terms Find all terms associated with the given node, ordered by vocabulary and term weight.
taxonomy_node_get_terms_by_vocabulary Find all terms associated with the given node, within one vocabulary.
taxonomy_node_save Save term associations for a given node.
taxonomy_node_type Implementation of hook_node_type().
taxonomy_node_update_index Implementation of hook_nodeapi('update_index').
taxonomy_node_validate Make sure incoming vids are free tagging enabled.
taxonomy_perm Implementation of hook_perm().
taxonomy_preview_terms Helper function to convert terms after a preview.
taxonomy_render_nodes Accepts 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_item Provides category information for RSS feeds.
taxonomy_save_term Helper function for taxonomy_form_term_submit().
taxonomy_save_vocabulary
taxonomy_select_nodes Finds all nodes that match selected taxonomy conditions.
taxonomy_terms_parse_string Parses a comma or plus separated string of term IDs.
taxonomy_term_count_nodes Count the number of published nodes classified by a term.
taxonomy_term_path For vocabularies not maintained by taxonomy.module, give the maintaining module a chance to provide a path for terms in that vocabulary.
taxonomy_theme Implementation of hook_theme().
taxonomy_vocabulary_load Return the vocabulary object matching a vocabulary ID.
theme_taxonomy_term_select Format the selection field for choosing terms (by deafult the default selection field is used).
_taxonomy_get_tid_from_term Helper function for array_map purposes.
_taxonomy_term_children Helper for taxonomy_term_count_nodes(). Used to find out which terms are children of a parent term.
_taxonomy_term_select Create 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_theme().
  14. */
  15. function taxonomy_theme() {
  16. return array(
  17. 'taxonomy_term_select' => array(
  18. 'arguments' => array('element' => NULL),
  19. ),
  20. 'taxonomy_term_page' => array(
  21. 'arguments' => array('tids' => array(), 'result' => NULL),
  22. ),
  23. 'taxonomy_overview_vocabularies' => array(
  24. 'arguments' => array('form' => array()),
  25. ),
  26. 'taxonomy_overview_terms' => array(
  27. 'arguments' => array('form' => array()),
  28. ),
  29. );
  30. }
  31. /**
  32. * Implementation of hook_link().
  33. *
  34. * This hook is extended with $type = 'taxonomy terms' to allow themes to
  35. * print lists of terms associated with a node. Themes can print taxonomy
  36. * links with:
  37. *
  38. * if (module_exists('taxonomy')) {
  39. * $terms = taxonomy_link('taxonomy terms', $node);
  40. * print theme('links', $terms);
  41. * }
  42. */
  43. function taxonomy_link($type, $node = NULL) {
  44. if ($type == 'taxonomy terms' && $node != NULL) {
  45. $links = array();
  46. // If previewing, the terms must be converted to objects first.
  47. if (isset($node->build_mode) && $node->build_mode == NODE_BUILD_PREVIEW) {
  48. $node->taxonomy = taxonomy_preview_terms($node);
  49. }
  50. if (!empty($node->taxonomy)) {
  51. foreach ($node->taxonomy as $term) {
  52. // During preview the free tagging terms are in an array unlike the
  53. // other terms which are objects. So we have to check if a $term
  54. // is an object or not.
  55. if (is_object($term)) {
  56. $links['taxonomy_term_'. $term->tid] = array(
  57. 'title' => $term->name,
  58. 'href' => taxonomy_term_path($term),
  59. 'attributes' => array('rel' => 'tag', 'title' => strip_tags($term->description))
  60. );
  61. }
  62. // Previewing free tagging terms; we don't link them because the
  63. // term-page might not exist yet.
  64. else {
  65. foreach ($term as $free_typed) {
  66. $typed_terms = drupal_explode_tags($free_typed);
  67. foreach ($typed_terms as $typed_term) {
  68. $links['taxonomy_preview_term_'. $typed_term] = array(
  69. 'title' => $typed_term,
  70. );
  71. }
  72. }
  73. }
  74. }
  75. }
  76. // We call this hook again because some modules and themes
  77. // call taxonomy_link('taxonomy terms') directly.
  78. drupal_alter('link', $links, $node);
  79. return $links;
  80. }
  81. }
  82. /**
  83. * For vocabularies not maintained by taxonomy.module, give the maintaining
  84. * module a chance to provide a path for terms in that vocabulary.
  85. *
  86. * @param $term
  87. * A term object.
  88. * @return
  89. * An internal Drupal path.
  90. */
  91. function taxonomy_term_path($term) {
  92. $vocabulary = taxonomy_vocabulary_load($term->vid);
  93. if ($vocabulary->module != 'taxonomy' && $path = module_invoke($vocabulary->module, 'term_path', $term)) {
  94. return $path;
  95. }
  96. return 'taxonomy/term/'. $term->tid;
  97. }
  98. /**
  99. * Implementation of hook_menu().
  100. */
  101. function taxonomy_menu() {
  102. $items['admin/content/taxonomy'] = array(
  103. 'title' => 'Taxonomy',
  104. 'description' => 'Manage tagging, categorization, and classification of your content.',
  105. 'page callback' => 'drupal_get_form',
  106. 'page arguments' => array('taxonomy_overview_vocabularies'),
  107. 'access arguments' => array('administer taxonomy'),
  108. 'file' => 'taxonomy.admin.inc',
  109. );
  110. $items['admin/content/taxonomy/list'] = array(
  111. 'title' => 'List',
  112. 'type' => MENU_DEFAULT_LOCAL_TASK,
  113. 'weight' => -10,
  114. );
  115. $items['admin/content/taxonomy/add/vocabulary'] = array(
  116. 'title' => 'Add vocabulary',
  117. 'page callback' => 'drupal_get_form',
  118. 'page arguments' => array('taxonomy_form_vocabulary'),
  119. 'access arguments' => array('administer taxonomy'),
  120. 'type' => MENU_LOCAL_TASK,
  121. 'parent' => 'admin/content/taxonomy',
  122. 'file' => 'taxonomy.admin.inc',
  123. );
  124. $items['admin/content/taxonomy/edit/vocabulary/%taxonomy_vocabulary'] = array(
  125. 'title' => 'Edit vocabulary',
  126. 'page callback' => 'taxonomy_admin_vocabulary_edit',
  127. 'page arguments' => array(5),
  128. 'access arguments' => array('administer taxonomy'),
  129. 'type' => MENU_CALLBACK,
  130. 'file' => 'taxonomy.admin.inc',
  131. );
  132. $items['admin/content/taxonomy/edit/term'] = array(
  133. 'title' => 'Edit term',
  134. 'page callback' => 'taxonomy_admin_term_edit',
  135. 'access arguments' => array('administer taxonomy'),
  136. 'type' => MENU_CALLBACK,
  137. 'file' => 'taxonomy.admin.inc',
  138. );
  139. $items['taxonomy/term/%'] = array(
  140. 'title' => 'Taxonomy term',
  141. 'page callback' => 'taxonomy_term_page',
  142. 'page arguments' => array(2),
  143. 'access arguments' => array('access content'),
  144. 'type' => MENU_CALLBACK,
  145. 'file' => 'taxonomy.pages.inc',
  146. );
  147. $items['taxonomy/autocomplete'] = array(
  148. 'title' => 'Autocomplete taxonomy',
  149. 'page callback' => 'taxonomy_autocomplete',
  150. 'access arguments' => array('access content'),
  151. 'type' => MENU_CALLBACK,
  152. 'file' => 'taxonomy.pages.inc',
  153. );
  154. $items['admin/content/taxonomy/%taxonomy_vocabulary'] = array(
  155. 'title' => 'List terms',
  156. 'page callback' => 'drupal_get_form',
  157. 'page arguments' => array('taxonomy_overview_terms', 3),
  158. 'access arguments' => array('administer taxonomy'),
  159. 'type' => MENU_CALLBACK,
  160. 'file' => 'taxonomy.admin.inc',
  161. );
  162. $items['admin/content/taxonomy/%taxonomy_vocabulary/list'] = array(
  163. 'title' => 'List',
  164. 'type' => MENU_DEFAULT_LOCAL_TASK,
  165. 'weight' => -10,
  166. );
  167. $items['admin/content/taxonomy/%taxonomy_vocabulary/add/term'] = array(
  168. 'title' => 'Add term',
  169. 'page callback' => 'taxonomy_add_term_page',
  170. 'page arguments' => array(3),
  171. 'access arguments' => array('administer taxonomy'),
  172. 'type' => MENU_LOCAL_TASK,
  173. 'parent' => 'admin/content/taxonomy/%taxonomy_vocabulary',
  174. 'file' => 'taxonomy.admin.inc',
  175. );
  176. return $items;
  177. }
  178. function taxonomy_save_vocabulary(&$edit) {
  179. $edit['nodes'] = empty($edit['nodes']) ? array() : $edit['nodes'];
  180. if (!isset($edit['module'])) {
  181. $edit['module'] = 'taxonomy';
  182. }
  183. if (!empty($edit['vid']) && !empty($edit['name'])) {
  184. drupal_write_record('vocabulary', $edit, 'vid');
  185. db_query("DELETE FROM {vocabulary_node_types} WHERE vid = %d", $edit['vid']);
  186. foreach ($edit['nodes'] as $type => $selected) {
  187. db_query("INSERT INTO {vocabulary_node_types} (vid, type) VALUES (%d, '%s')", $edit['vid'], $type);
  188. }
  189. module_invoke_all('taxonomy', 'update', 'vocabulary', $edit);
  190. $status = SAVED_UPDATED;
  191. }
  192. else if (!empty($edit['vid'])) {
  193. $status = taxonomy_del_vocabulary($edit['vid']);
  194. }
  195. else {
  196. drupal_write_record('vocabulary', $edit);
  197. foreach ($edit['nodes'] as $type => $selected) {
  198. db_query("INSERT INTO {vocabulary_node_types} (vid, type) VALUES (%d, '%s')", $edit['vid'], $type);
  199. }
  200. module_invoke_all('taxonomy', 'insert', 'vocabulary', $edit);
  201. $status = SAVED_NEW;
  202. }
  203. cache_clear_all();
  204. return $status;
  205. }
  206. /**
  207. * Delete a vocabulary.
  208. *
  209. * @param $vid
  210. * A vocabulary ID.
  211. * @return
  212. * Constant indicating items were deleted.
  213. */
  214. function taxonomy_del_vocabulary($vid) {
  215. $vocabulary = (array) taxonomy_vocabulary_load($vid);
  216. db_query('DELETE FROM {vocabulary} WHERE vid = %d', $vid);
  217. db_query('DELETE FROM {vocabulary_node_types} WHERE vid = %d', $vid);
  218. $result = db_query('SELECT tid FROM {term_data} WHERE vid = %d', $vid);
  219. while ($term = db_fetch_object($result)) {
  220. taxonomy_del_term($term->tid);
  221. }
  222. module_invoke_all('taxonomy', 'delete', 'vocabulary', $vocabulary);
  223. cache_clear_all();
  224. return SAVED_DELETED;
  225. }
  226. /**
  227. * Dynamically check and update the hierarachy flag of a vocabulary.
  228. * Checks and updates the hierarchy flag of a vocabulary.
  229. *
  230. * Checks the current parents of all terms in a vocabulary and updates the
  231. * vocabulary's hierarchy setting to the lowest possible level. If no term
  232. * has parent terms then the vocabulary will be given a hierarchy of 0.
  233. * If any term has a single parent then the vocabulary will be given a
  234. * hierarchy of 1. If any term has multiple parents then the vocabulary
  235. * will be given a hierarchy of 2.
  236. *
  237. * @param $vocabulary
  238. * An array of the vocabulary structure.
  239. * @param $changed_term
  240. * An array of the term structure that was updated.
  241. *
  242. * @return
  243. * An integer that represents the level of the vocabulary's hierarchy.
  244. */
  245. function taxonomy_check_vocabulary_hierarchy($vocabulary, $changed_term) {
  246. $tree = taxonomy_get_tree($vocabulary['vid']);
  247. $hierarchy = 0;
  248. foreach ($tree as $term) {
  249. // Update the changed term with the new parent value before comparision.
  250. if ($term->tid == $changed_term['tid']) {
  251. $term = (object)$changed_term;
  252. $term->parents = $term->parent;
  253. }
  254. // Check this term's parent count.
  255. if (count($term->parents) > 1) {
  256. $hierarchy = 2;
  257. break;
  258. }
  259. elseif (count($term->parents) == 1 && 0 !== array_shift($term->parents)) {
  260. $hierarchy = 1;
  261. }
  262. }
  263. if ($hierarchy != $vocabulary['hierarchy']) {
  264. $vocabulary['hierarchy'] = $hierarchy;
  265. taxonomy_save_vocabulary($vocabulary);
  266. }
  267. return $hierarchy;
  268. }
  269. /**
  270. * Helper function for taxonomy_form_term_submit().
  271. *
  272. * @param $form_state['values']
  273. * @return
  274. * Status constant indicating if term was inserted or updated.
  275. */
  276. function taxonomy_save_term(&$form_values) {
  277. $form_values += array(
  278. 'description' => '',
  279. 'weight' => 0
  280. );
  281. if (!empty($form_values['tid']) && $form_values['name']) {
  282. drupal_write_record('term_data', $form_values, 'tid');
  283. $hook = 'update';
  284. $status = SAVED_UPDATED;
  285. }
  286. else if (!empty($form_values['tid'])) {
  287. return taxonomy_del_term($form_values['tid']);
  288. }
  289. else {
  290. drupal_write_record('term_data', $form_values);
  291. $hook = 'insert';
  292. $status = SAVED_NEW;
  293. }
  294. db_query('DELETE FROM {term_relation} WHERE tid1 = %d OR tid2 = %d', $form_values['tid'], $form_values['tid']);
  295. if (!empty($form_values['relations'])) {
  296. foreach ($form_values['relations'] as $related_id) {
  297. if ($related_id != 0) {
  298. db_query('INSERT INTO {term_relation} (tid1, tid2) VALUES (%d, %d)', $form_values['tid'], $related_id);
  299. }
  300. }
  301. }
  302. db_query('DELETE FROM {term_hierarchy} WHERE tid = %d', $form_values['tid']);
  303. if (!isset($form_values['parent']) || empty($form_values['parent'])) {
  304. $form_values['parent'] = array(0);
  305. }
  306. if (is_array($form_values['parent'])) {
  307. foreach ($form_values['parent'] as $parent) {
  308. if (is_array($parent)) {
  309. foreach ($parent as $tid) {
  310. db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $form_values['tid'], $tid);
  311. }
  312. }
  313. else {
  314. db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $form_values['tid'], $parent);
  315. }
  316. }
  317. }
  318. else {
  319. db_query('INSERT INTO {term_hierarchy} (tid, parent) VALUES (%d, %d)', $form_values['tid'], $form_values['parent']);
  320. }
  321. db_query('DELETE FROM {term_synonym} WHERE tid = %d', $form_values['tid']);
  322. if (!empty($form_values['synonyms'])) {
  323. foreach (explode ("\n", str_replace("\r", '', $form_values['synonyms'])) as $synonym) {
  324. if ($synonym) {
  325. db_query("INSERT INTO {term_synonym} (tid, name) VALUES (%d, '%s')", $form_values['tid'], chop($synonym));
  326. }
  327. }
  328. }
  329. if (isset($hook)) {
  330. module_invoke_all('taxonomy', $hook, 'term', $form_values);
  331. }
  332. cache_clear_all();
  333. return $status;
  334. }
  335. /**
  336. * Delete a term.
  337. *
  338. * @param $tid
  339. * The term ID.
  340. * @return
  341. * Status constant indicating deletion.
  342. */
  343. function taxonomy_del_term($tid) {
  344. $tids = array($tid);
  345. while ($tids) {
  346. $children_tids = $orphans = array();
  347. foreach ($tids as $tid) {
  348. // See if any of the term's children are about to be become orphans:
  349. if ($children = taxonomy_get_children($tid)) {
  350. foreach ($children as $child) {
  351. // If the term has multiple parents, we don't delete it.
  352. $parents = taxonomy_get_parents($child->tid);
  353. if (count($parents) == 1) {
  354. $orphans[] = $child->tid;
  355. }
  356. }
  357. }
  358. $term = (array) taxonomy_get_term($tid);
  359. db_query('DELETE FROM {term_data} WHERE tid = %d', $tid);
  360. db_query('DELETE FROM {term_hierarchy} WHERE tid = %d', $tid);
  361. db_query('DELETE FROM {term_relation} WHERE tid1 = %d OR tid2 = %d', $tid, $tid);
  362. db_query('DELETE FROM {term_synonym} WHERE tid = %d', $tid);
  363. db_query('DELETE FROM {term_node} WHERE tid = %d', $tid);
  364. module_invoke_all('taxonomy', 'delete', 'term', $term);
  365. }
  366. $tids = $orphans;
  367. }
  368. cache_clear_all();
  369. return SAVED_DELETED;
  370. }
  371. /**
  372. * Generate a form element for selecting terms from a vocabulary.
  373. *
  374. * @param $vid
  375. * The vocabulary ID to generate a form element for.
  376. * @param $value
  377. * The existing value of the term(s) in this vocabulary to use by default.
  378. * @param $help
  379. * Optional help text to use for the form element. If specified, this value
  380. * MUST be properly sanitized and filtered (e.g. with filter_xss_admin() or
  381. * check_plain() if it is user-supplied) to prevent XSS vulnerabilities. If
  382. * omitted, the help text stored with the vocaulary (if any) will be used.
  383. * @return
  384. * An array describing a form element to select terms for a vocabulary.
  385. *
  386. * @see _taxonomy_term_select()
  387. * @see filter_xss_admin()
  388. */
  389. function taxonomy_form($vid, $value = 0, $help = NULL, $name = 'taxonomy') {
  390. $vocabulary = taxonomy_vocabulary_load($vid);
  391. $help = ($help) ? $help : filter_xss_admin($vocabulary->help);
  392. if (!$vocabulary->multiple) {
  393. $blank = ($vocabulary->required) ? t('- Please choose -') : t('- None selected -');
  394. }
  395. else {
  396. $blank = ($vocabulary->required) ? 0 : t('- None -');
  397. }
  398. return _taxonomy_term_select(check_plain($vocabulary->name), $name, $value, $vid, $help, intval($vocabulary->multiple), $blank);
  399. }
  400. /**
  401. * Generate a set of options for selecting a term from all vocabularies.
  402. */
  403. function taxonomy_form_all($free_tags = 0) {
  404. $vocabularies = taxonomy_get_vocabularies();
  405. $options = array();
  406. foreach ($vocabularies as $vid => $vocabulary) {
  407. if ($vocabulary->tags && !$free_tags) { continue; }
  408. $tree = taxonomy_get_tree($vid);
  409. if ($tree && (count($tree) > 0)) {
  410. $options[$vocabulary->name] = array();
  411. foreach ($tree as $term) {
  412. $options[$vocabulary->name][$term->tid] = str_repeat('-', $term->depth) . $term->name;
  413. }
  414. }
  415. }
  416. return $options;
  417. }
  418. /**
  419. * Return an array of all vocabulary objects.
  420. *
  421. * @param $type
  422. * If set, return only those vocabularies associated with this node type.
  423. */
  424. function taxonomy_get_vocabularies($type = NULL) {
  425. if ($type) {
  426. $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);
  427. }
  428. else {
  429. $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'));
  430. }
  431. $vocabularies = array();
  432. $node_types = array();
  433. while ($voc = db_fetch_object($result)) {
  434. // If no node types are associated with a vocabulary, the LEFT JOIN will
  435. // return a NULL value for type.
  436. if (isset($voc->type)) {
  437. $node_types[$voc->vid][$voc->type] = $voc->type;
  438. unset($voc->type);
  439. $voc->nodes = $node_types[$voc->vid];
  440. }
  441. elseif (!isset($voc->nodes)) {
  442. $voc->nodes = array();
  443. }
  444. $vocabularies[$voc->vid] = $voc;
  445. }
  446. return $vocabularies;
  447. }
  448. /**
  449. * Implementation of hook_form_alter().
  450. * Generate a form for selecting terms to associate with a node.
  451. * We check for taxonomy_override_selector before loading the full
  452. * vocabulary, so contrib modules can intercept before hook_form_alter
  453. * and provide scalable alternatives.
  454. */
  455. function taxonomy_form_alter(&$form, $form_state, $form_id) {
  456. if (isset($form['type']) && isset($form['#node']) && (!variable_get('taxonomy_override_selector', FALSE)) && $form['type']['#value'] .'_node_form' == $form_id) {
  457. $node = $form['#node'];
  458. if (!isset($node->taxonomy)) {
  459. $terms = empty($node->nid) ? array() : taxonomy_node_get_terms($node);
  460. }
  461. else {
  462. // After a preview or form reload, the terms must be converted to objects.
  463. reset($node->taxonomy);
  464. if (!is_object(current($node->taxonomy))) {
  465. $node->taxonomy = taxonomy_preview_terms($node);
  466. }
  467. $terms = $node->taxonomy;
  468. }
  469. $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);
  470. while ($vocabulary = db_fetch_object($c)) {
  471. if ($vocabulary->tags) {
  472. if (isset($form_state['node_preview'])) {
  473. // Typed string can be changed by the user before preview,
  474. // so we just insert the tags directly as provided in the form.
  475. $typed_string = $node->taxonomy['tags'][$vocabulary->vid];
  476. }
  477. else {
  478. $typed_string = taxonomy_implode_tags($terms, $vocabulary->vid) . (array_key_exists('tags', $terms) ? $terms['tags'][$vocabulary->vid] : NULL);
  479. }
  480. if ($vocabulary->help) {
  481. $help = filter_xss_admin($vocabulary->help);
  482. }
  483. else {
  484. $help = t('A comma-separated list of terms describing this content. Example: funny, bungee jumping, "Company, Inc.".');
  485. }
  486. $form['taxonomy']['tags'][$vocabulary->vid] = array('#type' => 'textfield',
  487. '#title' => $vocabulary->name,
  488. '#description' => $help,
  489. '#required' => $vocabulary->required,
  490. '#default_value' => $typed_string,
  491. '#autocomplete_path' => 'taxonomy/autocomplete/'. $vocabulary->vid,
  492. '#weight' => $vocabulary->weight,
  493. '#maxlength' => 1024,
  494. );
  495. }
  496. else {
  497. // Extract terms belonging to the vocabulary in question.
  498. $default_terms = array();
  499. foreach ($terms as $term) {
  500. // Free tagging has no default terms and also no vid after preview.
  501. if (isset($term->vid) && $term->vid == $vocabulary->vid) {
  502. $default_terms[$term->tid] = $term;
  503. }
  504. }
  505. $form['taxonomy'][$vocabulary->vid] = taxonomy_form($vocabulary->vid, array_keys($default_terms), filter_xss_admin($vocabulary->help));
  506. $form['taxonomy'][$vocabulary->vid]['#weight'] = $vocabulary->weight;
  507. $form['taxonomy'][$vocabulary->vid]['#required'] = $vocabulary->required;
  508. }
  509. }
  510. if (!empty($form['taxonomy']) && is_array($form['taxonomy'])) {
  511. if (count($form['taxonomy']) > 1) {
  512. // Add fieldset only if form has more than 1 element.
  513. $form['taxonomy'] += array(
  514. '#type' => 'fieldset',
  515. '#title' => t('Vocabularies'),
  516. '#collapsible' => TRUE,
  517. '#collapsed' => FALSE,
  518. );
  519. }
  520. $form['taxonomy']['#weight'] = -3;
  521. $form['taxonomy']['#tree'] = TRUE;
  522. }
  523. }
  524. }
  525. /**
  526. * Helper function to convert terms after a preview.
  527. *
  528. * After preview the tags are an array instead of proper objects. This function
  529. * converts them back to objects with the exception of 'free tagging' terms,
  530. * because new tags can be added by the user before preview and those do not
  531. * yet exist in the database. We therefore save those tags as a string so
  532. * we can fill the form again after the preview.
  533. */
  534. function taxonomy_preview_terms($node) {
  535. $taxonomy = array();
  536. if (isset($node->taxonomy)) {
  537. foreach ($node->taxonomy as $key => $term) {
  538. unset($node->taxonomy[$key]);
  539. // A 'Multiple select' and a 'Free tagging' field returns an array.
  540. if (is_array($term)) {
  541. foreach ($term as $tid) {
  542. if ($key == 'tags') {
  543. // Free tagging; the values will be saved for later as strings
  544. // instead of objects to fill the form again.
  545. $taxonomy['tags'] = $term;
  546. }
  547. else {
  548. $taxonomy[$tid] = taxonomy_get_term($tid);
  549. }
  550. }
  551. }
  552. // A 'Single select' field returns the term id.
  553. elseif ($term) {
  554. $taxonomy[$term] = taxonomy_get_term($term);
  555. }
  556. }
  557. }
  558. return $taxonomy;
  559. }
  560. /**
  561. * Find all terms associated with the given node, within one vocabulary.
  562. */
  563. function taxonomy_node_get_terms_by_vocabulary($node, $vid, $key = 'tid') {
  564. $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.vid = %d ORDER BY weight', 't', 'tid'), $vid, $node->vid);
  565. $terms = array();
  566. while ($term = db_fetch_object($result)) {
  567. $terms[$term->$key] = $term;
  568. }
  569. return $terms;
  570. }
  571. /**
  572. * Find all terms associated with the given node, ordered by vocabulary and term weight.
  573. */
  574. function taxonomy_node_get_terms($node, $key = 'tid', $reset = FALSE) {
  575. static $terms;
  576. if ($reset) {
  577. unset($terms[$node->vid]);
  578. }
  579. if (!isset($terms[$node->vid][$key])) {
  580. $result = db_query(db_rewrite_sql('SELECT t.*,v.weight AS v_weight_unused 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.vid = %d ORDER BY v.weight, t.weight, t.name', 't', 'tid'), $node->vid);
  581. $terms[$node->vid][$key] = array();
  582. while ($term = db_fetch_object($result)) {
  583. $terms[$node->vid][$key][$term->$key] = $term;
  584. }
  585. }
  586. return $terms[$node->vid][$key];
  587. }
  588. /**
  589. * Make sure incoming vids are free tagging enabled.
  590. */
  591. function taxonomy_node_validate(&$node) {
  592. if (!empty($node->taxonomy)) {
  593. $terms = $node->taxonomy;
  594. if (!empty($terms['tags'])) {
  595. foreach ($terms['tags'] as $vid => $vid_value) {
  596. $vocabulary = taxonomy_vocabulary_load($vid);
  597. if (empty($vocabulary->tags)) {
  598. // see form_get_error $key = implode('][', $element['#parents']);
  599. // on why this is the key
  600. form_set_error("taxonomy][tags][$vid", t('The %name vocabulary can not be modified in this way.', array('%name' => $vocabulary->name)));
  601. }
  602. }
  603. }
  604. }
  605. }
  606. /**
  607. * Save term associations for a given node.
  608. */
  609. function taxonomy_node_save(&$node, $terms) {
  610. taxonomy_node_delete_revision($node);
  611. // Free tagging vocabularies do not send their tids in the form,
  612. // so we'll detect them here and process them independently.
  613. if (isset($terms['tags'])) {
  614. $typed_input = $terms['tags'];
  615. unset($terms['tags']);
  616. foreach ($typed_input as $vid => $vid_value) {
  617. $typed_terms = drupal_explode_tags($vid_value);
  618. $inserted = array();
  619. foreach ($typed_terms as $typed_term) {
  620. // See if the term exists in the chosen vocabulary
  621. // and return the tid; otherwise, add a new record.
  622. $possibilities = taxonomy_get_term_by_name($typed_term);
  623. $typed_term_tid = NULL; // tid match, if any.
  624. foreach ($possibilities as $possibility) {
  625. if ($possibility->vid == $vid) {
  626. $typed_term_tid = $possibility->tid;
  627. }
  628. }
  629. if (!$typed_term_tid) {
  630. $edit = array('vid' => $vid, 'name' => $typed_term);
  631. $status = taxonomy_save_term($edit);
  632. $typed_term_tid = $edit['tid'];
  633. }
  634. // Defend against duplicate, differently cased tags
  635. if (!isset($inserted[$typed_term_tid])) {
  636. db_query('INSERT INTO {term_node} (nid, vid, tid) VALUES (%d, %d, %d)', $node->nid, $node->vid, $typed_term_tid);
  637. $inserted[$typed_term_tid] = TRUE;
  638. }
  639. }
  640. }
  641. }
  642. if (is_array($terms)) {
  643. foreach ($terms as $term) {
  644. if (is_array($term)) {
  645. foreach ($term as $tid) {
  646. if ($tid) {
  647. db_query('INSERT INTO {term_node} (nid, vid, tid) VALUES (%d, %d, %d)', $node->nid, $node->vid, $tid);
  648. }
  649. }
  650. }
  651. else if (is_object($term)) {
  652. db_query('INSERT INTO {term_node} (nid, vid, tid) VALUES (%d, %d, %d)', $node->nid, $node->vid, $term->tid);
  653. }
  654. else if ($term) {
  655. db_query('INSERT INTO {term_node} (nid, vid, tid) VALUES (%d, %d, %d)', $node->nid, $node->vid, $term);
  656. }
  657. }
  658. }
  659. // Flush the term "cache" for this node
  660. $node->taxonomy = taxonomy_node_get_terms($node, 'tid', TRUE);
  661. }
  662. /**
  663. * Remove associations of a node to its terms.
  664. */
  665. function taxonomy_node_delete($node) {
  666. db_query('DELETE FROM {term_node} WHERE nid = %d', $node->nid);
  667. }
  668. /**
  669. * Remove associations of a node to its terms.
  670. */
  671. function taxonomy_node_delete_revision($node) {
  672. db_query('DELETE FROM {term_node} WHERE vid = %d', $node->vid);
  673. }
  674. /**
  675. * Implementation of hook_node_type().
  676. */
  677. function taxonomy_node_type($op, $info) {
  678. if ($op == 'update' && !empty($info->old_type) && $info->type != $info->old_type) {
  679. db_query("UPDATE {vocabulary_node_types} SET type = '%s' WHERE type = '%s'", $info->type, $info->old_type);
  680. }
  681. elseif ($op == 'delete') {
  682. db_query("DELETE FROM {vocabulary_node_types} WHERE type = '%s'", $info->type);
  683. }
  684. }
  685. /**
  686. * Find all term objects related to a given term ID.
  687. */
  688. function taxonomy_get_related($tid, $key = 'tid') {
  689. if ($tid) {
  690. $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);
  691. $related = array();
  692. while ($term = db_fetch_object($result)) {
  693. $related[$term->$key] = $term;
  694. }
  695. return $related;
  696. }
  697. else {
  698. return array();
  699. }
  700. }
  701. /**
  702. * Find all parents of a given term ID.
  703. */
  704. function taxonomy_get_parents($tid, $key = 'tid') {
  705. if ($tid) {
  706. $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);
  707. $parents = array();
  708. while ($parent = db_fetch_object($result)) {
  709. $parents[$parent->$key] = $parent;
  710. }
  711. return $parents;
  712. }
  713. else {
  714. return array();
  715. }
  716. }
  717. /**
  718. * Find all ancestors of a given term ID.
  719. */
  720. function taxonomy_get_parents_all($tid) {
  721. $parents = array();
  722. if ($tid) {
  723. $parents[] = taxonomy_get_term($tid);
  724. $n = 0;
  725. while ($parent = taxonomy_get_parents($parents[$n]->tid)) {
  726. $parents = array_merge($parents, $parent);
  727. $n++;
  728. }
  729. }
  730. return $parents;
  731. }
  732. /**
  733. * Find all children of a term ID.
  734. */
  735. function taxonomy_get_children($tid, $vid = 0, $key = 'tid') {
  736. if ($vid) {
  737. $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);
  738. }
  739. else {
  740. $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);
  741. }
  742. $children = array();
  743. while ($term = db_fetch_object($result)) {
  744. $children[$term->$key] = $term;
  745. }
  746. return $children;
  747. }
  748. /**
  749. * Create a hierarchical representation of a vocabulary.
  750. *
  751. * @param $vid
  752. * Which vocabulary to generate the tree for.
  753. *
  754. * @param $parent
  755. * The term ID under which to generate the tree. If 0, generate the tree
  756. * for the entire vocabulary.
  757. *
  758. * @param $depth
  759. * Internal use only. Now deprecated and isn't used. It is left here only
  760. * because of @link http://drupal.org/node/556842 compatibility issues. @endlink
  761. *
  762. * @param $max_depth
  763. * The number of levels of the tree to return. Leave NULL to return all levels.
  764. *
  765. * @return
  766. * An array of all term objects in the tree. Each term object is extended
  767. * to have "depth" and "parents" attributes in addition to its normal ones.
  768. * Results are statically cached.
  769. */
  770. function taxonomy_get_tree($vid, $parent = 0, $depth = -1, $max_depth = NULL) {
  771. static $children, $parents, $terms;
  772. // We cache trees, so it's not CPU-intensive to call get_tree() on a term
  773. // and its children, too.
  774. if (!isset($children[$vid])) {
  775. $children[$vid] = array();
  776. $parents[$vid] = array();
  777. $terms[$vid] = array();
  778. $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);
  779. while ($term = db_fetch_object($result)) {
  780. $children[$vid][$term->parent][] = $term->tid;
  781. $parents[$vid][$term->tid][] = $term->parent;
  782. $terms[$vid][$term->tid] = $term;
  783. }
  784. }
  785. $max_depth = (!isset($max_depth)) ? count($children[$vid]) : $max_depth;
  786. $tree = array();
  787. // Keeps track of the parents we have to process, the last entry is used
  788. // for the next processing step.
  789. $process_parents = array();
  790. $process_parents[] = $parent;
  791. // Loops over the parent terms and adds its children to the tree array.
  792. // Uses a loop instead of a recursion, because it's more efficient.
  793. while (count($process_parents)) {
  794. $parent = array_pop($process_parents);
  795. // The number of parents determines the current depth.
  796. $depth = count($process_parents);
  797. if ($max_depth > $depth && !empty($children[$vid][$parent])) {
  798. $has_children = FALSE;
  799. $child = current($children[$vid][$parent]);
  800. do {
  801. if (empty($child)) {
  802. break;
  803. }
  804. $term = $terms[$vid][$child];
  805. if (count($parents[$vid][$term->tid]) > 1) {
  806. // We have a term with multi parents here. Clone the term,
  807. // so that the depth attribute remains correct.
  808. $term = clone $term;
  809. }
  810. $term->depth = $depth;
  811. unset($term->parent);
  812. $term->parents = $parents[$vid][$term->tid];
  813. $tree[] = $term;
  814. if (!empty($children[$vid][$term->tid])) {
  815. $has_children = TRUE;
  816. // We have to continue with this parent later.
  817. $process_parents[] = $parent;
  818. // Use the current term as parent for the next iteration.
  819. $process_parents[] = $term->tid;
  820. // Reset pointers for child lists because we step in there more often
  821. // with multi parents.
  822. reset($children[$vid][$term->tid]);
  823. // Move pointer so that we get the correct term the next time.
  824. next($children[$vid][$parent]);
  825. break;
  826. }
  827. } while ($child = next($children[$vid][$parent]));
  828. if (!$has_children) {
  829. // We processed all terms in this hierarchy-level, reset pointer
  830. // so that this function works the next time it gets called.
  831. reset($children[$vid][$parent]);
  832. }
  833. }
  834. }
  835. return $tree;
  836. }
  837. /**
  838. * Return an array of synonyms of the given term ID.
  839. */
  840. function taxonomy_get_synonyms($tid) {
  841. if ($tid) {
  842. $synonyms = array();
  843. $result = db_query('SELECT name FROM {term_synonym} WHERE tid = %d', $tid);
  844. while ($synonym = db_fetch_array($result)) {
  845. $synonyms[] = $synonym['name'];
  846. }
  847. return $synonyms;
  848. }
  849. else {
  850. return array();
  851. }
  852. }
  853. /**
  854. * Return the term object that has the given string as a synonym.
  855. */
  856. function taxonomy_get_synonym_root($synonym) {
  857. return db_fetch_object(db_query("SELECT * FROM {term_synonym} s, {term_data} t WHERE t.tid = s.tid AND s.name = '%s'", $synonym));
  858. }
  859. /**
  860. * Count the number of published nodes classified by a term.
  861. *
  862. * @param $tid
  863. * The term's ID
  864. *
  865. * @param $type
  866. * The $node->type. If given, taxonomy_term_count_nodes only counts
  867. * nodes of $type that are classified with the term $tid.
  868. *
  869. * @return int
  870. * An integer representing a number of nodes.
  871. * Results are statically cached.
  872. */
  873. function taxonomy_term_count_nodes($tid, $type = 0) {
  874. static $count;
  875. if (!isset($count[$type])) {
  876. // $type == 0 always evaluates TRUE if $type is a string
  877. if (is_numeric($type)) {
  878. $result = db_query(db_rewrite_sql('SELECT t.tid, COUNT(n.nid) AS c FROM {term_node} t INNER JOIN {node} n ON t.vid = n.vid WHERE n.status = 1 GROUP BY t.tid'));
  879. }
  880. else {
  881. $result = db_query(db_rewrite_sql("SELECT t.tid, COUNT(n.nid) AS c FROM {term_node} t INNER JOIN {node} n ON t.vid = n.vid WHERE n.status = 1 AND n.type = '%s' GROUP BY t.tid"), $type);
  882. }
  883. $count[$type] = array();
  884. while ($term = db_fetch_object($result)) {
  885. $count[$type][$term->tid] = $term->c;
  886. }
  887. }
  888. $children_count = 0;
  889. foreach (_taxonomy_term_children($tid) as $c) {
  890. $children_count += taxonomy_term_count_nodes($c, $type);
  891. }
  892. return $children_count + (isset($count[$type][$tid]) ? $count[$type][$tid] : 0);
  893. }
  894. /**
  895. * Helper for taxonomy_term_count_nodes(). Used to find out
  896. * which terms are children of a parent term.
  897. *
  898. * @param $tid
  899. * The parent term's ID
  900. *
  901. * @return array
  902. * An array of term IDs representing the children of $tid.
  903. * Results are statically cached.
  904. *
  905. */
  906. function _taxonomy_term_children($tid) {
  907. static $children;
  908. if (!isset($children)) {
  909. $result = db_query('SELECT tid, parent FROM {term_hierarchy}');
  910. while ($term = db_fetch_object($result)) {
  911. $children[$term->parent][] = $term->tid;
  912. }
  913. }
  914. return isset($children[$tid]) ? $children[$tid] : array();
  915. }
  916. /**
  917. * Try to map a string to an existing term, as for glossary use.
  918. *
  919. * Provides a case-insensitive and trimmed mapping, to maximize the
  920. * likelihood of a successful match.
  921. *
  922. * @param name
  923. * Name of the term to search for.
  924. *
  925. * @return
  926. * An array of matching term objects.
  927. */
  928. function taxonomy_get_term_by_name($name) {
  929. $db_result = db_query(db_rewrite_sql("SELECT t.tid, t.* FROM {term_data} t WHERE LOWER(t.name) = LOWER('%s')", 't', 'tid'), trim($name));
  930. $result = array();
  931. while ($term = db_fetch_object($db_result)) {
  932. $result[] = $term;
  933. }
  934. return $result;
  935. }
  936. /**
  937. * Return the vocabulary object matching a vocabulary ID.
  938. *
  939. * @param $vid
  940. * The vocabulary's ID
  941. * @param $reset
  942. * Whether to reset the internal taxonomy_vocabulary_load cache.
  943. *
  944. * @return
  945. * The vocabulary object with all of its metadata, if exists, FALSE otherwise.
  946. * Results are statically cached.
  947. */
  948. function taxonomy_vocabulary_load($vid, $reset = FALSE) {
  949. static $vocabularies = array();
  950. if ($reset) {
  951. $vocabularies = array();
  952. }
  953. if (!isset($vocabularies[$vid])) {
  954. // Initialize so if this vocabulary does not exist, we have
  955. // that cached, and we will not try to load this later.
  956. $vocabularies[$vid] = FALSE;
  957. // Try to load the data and fill up the object.
  958. $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', $vid);
  959. $node_types = array();
  960. while ($voc = db_fetch_object($result)) {
  961. if (!empty($voc->type)) {
  962. $node_types[$voc->type] = $voc->type;
  963. }
  964. unset($voc->type);
  965. $voc->nodes = $node_types;
  966. $vocabularies[$vid] = $voc;
  967. }
  968. }
  969. // Return FALSE if this vocabulary does not exist.
  970. return !empty($vocabularies[$vid]) ? $vocabularies[$vid] : FALSE;
  971. }
  972. /**
  973. * Return the term object matching a term ID.
  974. *
  975. * @param $tid
  976. * A term's ID
  977. * @param $reset
  978. * Whether to reset the internal taxonomy_get_term cache.
  979. *
  980. * @return Object
  981. * A term object. Results are statically cached.
  982. */
  983. function taxonomy_get_term($tid, $reset = FALSE) {
  984. static $terms = array();
  985. if ($reset) {
  986. $terms = array();
  987. }
  988. if (!isset($terms[$tid])) {
  989. $terms[$tid] = db_fetch_object(db_query('SELECT * FROM {term_data} WHERE tid = %d', $tid));
  990. }
  991. return $terms[$tid];
  992. }
  993. /**
  994. * Create a select form element for a given taxonomy vocabulary.
  995. *
  996. * NOTE: This function expects input that has already been sanitized and is
  997. * safe for display. Callers must properly sanitize the $title and
  998. * $description arguments to prevent XSS vulnerabilities.
  999. *
  1000. * @param $title
  1001. * The title of the vocabulary. This MUST be sanitized by the caller.
  1002. * @param $name
  1003. * Ignored.
  1004. * @param $value
  1005. * The currently selected terms from this vocabulary, if any.
  1006. * @param $vocabulary_id
  1007. * The vocabulary ID to build the form element for.
  1008. * @param $description
  1009. * Help text for the form element. This MUST be sanitized by the caller.
  1010. * @param $multiple
  1011. * Boolean to control if the form should use a single or multiple select.
  1012. * @param $blank
  1013. * Optional form choice to use when no value has been selected.
  1014. * @param $exclude
  1015. * Optional array of term ids to exclude in the selector.
  1016. * @return
  1017. * A FAPI form array to select terms from the given vocabulary.
  1018. *
  1019. * @see taxonomy_form()
  1020. * @see taxonomy_form_term()
  1021. */
  1022. function _taxonomy_term_select($title, $name, $value, $vocabulary_id, $description, $multiple, $blank, $exclude = array()) {
  1023. $tree = taxonomy_get_tree($vocabulary_id);
  1024. $options = array();
  1025. if ($blank) {
  1026. $options[''] = $blank;
  1027. }
  1028. if ($tree) {
  1029. foreach ($tree as $term) {
  1030. if (!in_array($term->tid, $exclude)) {
  1031. $choice = new stdClass();
  1032. $choice->option = array($term->tid => str_repeat('-', $term->depth) . $term->name);
  1033. $options[] = $choice;
  1034. }
  1035. }
  1036. }
  1037. return array('#type' => 'select',
  1038. '#title' => $title,
  1039. '#default_value' => $value,
  1040. '#options' => $options,
  1041. '#description' => $description,
  1042. '#multiple' => $multiple,
  1043. '#size' => $multiple ? min(9, count($options)) : 0,
  1044. '#weight' => -15,
  1045. '#theme' => 'taxonomy_term_select',
  1046. );
  1047. }
  1048. /**
  1049. * Format the selection field for choosing terms
  1050. * (by deafult the default selection field is used).
  1051. *
  1052. * @ingroup themeable
  1053. */
  1054. function theme_taxonomy_term_select($element) {
  1055. return theme('select', $element);
  1056. }
  1057. /**
  1058. * Finds all nodes that match selected taxonomy conditions.
  1059. *
  1060. * @param $tids
  1061. * An array of term IDs to match.
  1062. * @param $operator
  1063. * How to interpret multiple IDs in the array. Can be "or" or "and".
  1064. * @param $depth
  1065. * How many levels deep to traverse the taxonomy tree. Can be a nonnegative
  1066. * integer or "all".
  1067. * @param $pager
  1068. * Whether the nodes are to be used with a pager (the case on most Drupal
  1069. * pages) or not (in an XML feed, for example).
  1070. * @param $order
  1071. * The order clause for the query that retrieve the nodes.
  1072. * @return
  1073. * A resource identifier pointing to the query results.
  1074. */
  1075. function taxonomy_select_nodes($tids = array(), $operator = 'or', $depth = 0, $pager = TRUE, $order = 'n.sticky DESC, n.created DESC') {
  1076. if (count($tids) > 0) {
  1077. // For each term ID, generate an array of descendant term IDs to the right depth.
  1078. $descendant_tids = array();
  1079. if ($depth === 'all') {
  1080. $depth = NULL;
  1081. }
  1082. foreach ($tids as $index => $tid) {
  1083. $term = taxonomy_get_term($tid);
  1084. $tree = taxonomy_get_tree($term->vid, $tid, -1, $depth);
  1085. $descendant_tids[] = array_merge(array($tid), array_map('_taxonomy_get_tid_from_term', $tree));
  1086. }
  1087. if ($operator == 'or') {
  1088. $args = call_user_func_array('array_merge', $descendant_tids);
  1089. $placeholders = db_placeholders($args, 'int');
  1090. $sql = 'SELECT DISTINCT(n.nid), n.sticky, n.title, n.created FROM {node} n INNER JOIN {term_node} tn ON n.vid = tn.vid WHERE tn.tid IN ('. $placeholders .') AND n.status = 1 ORDER BY '. $order;
  1091. $sql_count = 'SELECT COUNT(DISTINCT(n.nid)) FROM {node} n INNER JOIN {term_node} tn ON n.vid = tn.vid WHERE tn.tid IN ('. $placeholders .') AND n.status = 1';
  1092. }
  1093. else {
  1094. $joins = '';
  1095. $wheres = '';
  1096. $args = array();
  1097. foreach ($descendant_tids as $index => $tids) {
  1098. $joins .= ' INNER JOIN {term_node} tn'. $index .' ON n.vid = tn'. $index .'.vid';
  1099. $wheres .= ' AND tn'. $index .'.tid IN ('. db_placeholders($tids, 'int') .')';
  1100. $args = array_merge($args, $tids);
  1101. }
  1102. $sql = 'SELECT DISTINCT(n.nid), n.sticky, n.title, n.created FROM {node} n '. $joins .' WHERE n.status = 1 '. $wheres .' ORDER BY '. $order;
  1103. $sql_count = 'SELECT COUNT(DISTINCT(n.nid)) FROM {node} n '. $joins .' WHERE n.status = 1 '. $wheres;
  1104. }
  1105. $sql = db_rewrite_sql($sql);
  1106. $sql_count = db_rewrite_sql($sql_count);
  1107. if ($pager) {
  1108. $result = pager_query($sql, variable_get('default_nodes_main', 10), 0, $sql_count, $args);
  1109. }
  1110. else {
  1111. $result = db_query_range($sql, $args, 0, variable_get('feed_default_items', 10));
  1112. }
  1113. }
  1114. return $result;
  1115. }
  1116. /**
  1117. * Accepts the result of a pager_query() call, such as that performed by
  1118. * taxonomy_select_nodes(), and formats each node along with a pager.
  1119. */
  1120. function taxonomy_render_nodes($result) {
  1121. $output = '';
  1122. $has_rows = FALSE;
  1123. while ($node = db_fetch_object($result)) {
  1124. $output .= node_view(node_load($node->nid), 1);
  1125. $has_rows = TRUE;
  1126. }
  1127. if ($has_rows) {
  1128. $output .= theme('pager', NULL, variable_get('default_nodes_main', 10), 0);
  1129. }
  1130. else {
  1131. $output .= '<p>'. t('There are currently no posts in this category.') .'</p>';
  1132. }
  1133. return $output;
  1134. }
  1135. /**
  1136. * Implementation of hook_nodeapi().
  1137. */
  1138. function taxonomy_nodeapi(&$node, $op, $arg = 0) {
  1139. switch ($op) {
  1140. case 'load':
  1141. $output['taxonomy'] = taxonomy_node_get_terms($node);
  1142. return $output;
  1143. case 'insert':
  1144. if (!empty($node->taxonomy)) {
  1145. taxonomy_node_save($node, $node->taxonomy);
  1146. }
  1147. break;
  1148. case 'update':
  1149. if (!empty($node->taxonomy)) {
  1150. taxonomy_node_save($node, $node->taxonomy);
  1151. }
  1152. break;
  1153. case 'delete':
  1154. taxonomy_node_delete($node);
  1155. break;
  1156. case 'delete revision':
  1157. taxonomy_node_delete_revision($node);
  1158. break;
  1159. case 'validate':
  1160. taxonomy_node_validate($node);
  1161. break;
  1162. case 'rss item':
  1163. return taxonomy_rss_item($node);
  1164. case 'update index':
  1165. return taxonomy_node_update_index($node);
  1166. }
  1167. }
  1168. /**
  1169. * Implementation of hook_nodeapi('update_index').
  1170. */
  1171. function taxonomy_node_update_index(&$node) {
  1172. $output = array();
  1173. foreach ($node->taxonomy as $term) {
  1174. $output[] = $term->name;
  1175. }
  1176. if (count($output)) {
  1177. return '<strong>('. implode(', ', $output) .')</strong>';
  1178. }
  1179. }
  1180. /**
  1181. * Parses a comma or plus separated string of term IDs.
  1182. *
  1183. * @param $str_tids
  1184. * A string of term IDs, separated by plus or comma.
  1185. * comma (,) means AND
  1186. * plus (+) means OR
  1187. *
  1188. * @return an associative array with an operator key (either 'and'
  1189. * or 'or') and a tid key containing an array of the term ids.
  1190. */
  1191. function taxonomy_terms_parse_string($str_tids) {
  1192. $terms = array('operator' => '', 'tids' => array());
  1193. if (preg_match('/^([0-9]+[+ ])+[0-9]+$/', $str_tids)) {
  1194. $terms['operator'] = 'or';
  1195. // The '+' character in a query string may be parsed as ' '.
  1196. $terms['tids'] = preg_split('/[+ ]/', $str_tids);
  1197. }
  1198. else if (preg_match('/^([0-9]+,)*[0-9]+$/', $str_tids)) {
  1199. $terms['operator'] = 'and';
  1200. $terms['tids'] = explode(',', $str_tids);
  1201. }
  1202. return $terms;
  1203. }
  1204. /**
  1205. * Provides category information for RSS feeds.
  1206. */
  1207. function taxonomy_rss_item($node) {
  1208. $output = array();
  1209. foreach ($node->taxonomy as $term) {
  1210. $output[] = array('key' => 'category',
  1211. 'value' => $term->name,
  1212. 'attributes' => array('domain' => url('taxonomy/term/'. $term->tid, array('absolute' => TRUE))));
  1213. }
  1214. return $output;
  1215. }
  1216. /**
  1217. * Implementation of hook_help().
  1218. */
  1219. function taxonomy_help($path, $arg) {
  1220. switch ($path) {
  1221. case 'admin/help#taxonomy':
  1222. $output = '<p>'. t('The taxonomy module allows you to categorize content using various systems of classification. Free-tagging vocabularies are created by users on the fly when they submit posts (as commonly found in blogs and social bookmarking applications). Controlled vocabularies allow for administrator-defined short lists of terms as well as complex hierarchies with multiple relationships between different terms. These methods can be applied to different content types and combined together to create a powerful and flexible method of classifying and presenting your content.') .'</p>';
  1223. $output .= '<p>'. t('For example, when creating a recipe site, you might want to classify posts by both the type of meal and preparation time. A vocabulary for each allows you to categorize using each criteria independently instead of creating a tag for every possible combination.') .'</p>';
  1224. $output .= '<p>'. t('Type of Meal: <em>Appetizer, Main Course, Salad, Dessert</em>') .'</p>';
  1225. $output .= '<p>'. t('Preparation Time: <em>0-30mins, 30-60mins, 1-2 hrs, 2hrs+</em>') .'</p>';
  1226. $output .= '<p>'. t("Each taxonomy term (often called a 'category' or 'tag' in other systems) automatically provides lists of posts and a corresponding RSS feed. These taxonomy/term URLs can be manipulated to generate AND and OR lists of posts classified with terms. In our recipe site example, it then becomes easy to create pages displaying 'Main courses', '30 minute recipes', or '30 minute main courses and appetizers' by using terms on their own or in combination with others. There are a significant number of contributed modules which you to alter and extend the behavior of the core module for both display and organization of terms.") .'</p>';
  1227. $output .= '<p>'. t("Terms can also be organized in parent/child relationships from the admin interface. An example would be a vocabulary grouping countries under their parent geo-political regions. The taxonomy module also enables advanced implementations of hierarchy, for example placing Turkey in both the 'Middle East' and 'Europe'.") .'</p>';
  1228. $output .= '<p>'. t('The taxonomy module supports the use of both synonyms and related terms, but does not directly use this functionality. However, optional contributed or custom modules may make full use of these advanced features.') .'</p>';
  1229. $output .= '<p>'. t('For more information, see the online handbook entry for <a href="@taxonomy">Taxonomy module</a>.', array('@taxonomy' => 'http://drupal.org/handbook/modules/taxonomy/')) .'</p>';
  1230. return $output;
  1231. case 'admin/content/taxonomy':
  1232. $output = '<p>'. t("The taxonomy module allows you to categorize your content using both tags and administrator defined terms. It is a flexible tool for classifying content with many advanced features. To begin, create a 'Vocabulary' to hold one set of terms or tags. You can create one free-tagging vocabulary for everything, or separate controlled vocabularies to define the various properties of your content, for example 'Countries' or 'Colors'.") .'</p>';
  1233. $output .= '<p>'. t('Use the list below to configure and review the vocabularies defined on your site, or to list and manage the terms (tags) they contain. A vocabulary may (optionally) be tied to specific content types as shown in the <em>Type</em> column and, if so, will be displayed when creating or editing posts of that type. Multiple vocabularies tied to the same content type will be displayed in the order shown below. To change the order of a vocabulary, grab a drag-and-drop handle under the <em>Name</em> column and drag it to a new location in the list. (Grab a handle by clicking and holding the mouse while hovering over a handle icon.) Remember that your changes will not be saved until you click the <em>Save</em> button at the bottom of the page.') .'</p>';
  1234. return $output;
  1235. case 'admin/content/taxonomy/%':
  1236. $vocabulary = taxonomy_vocabulary_load($arg[3]);
  1237. if ($vocabulary->tags) {
  1238. return '<p>'. t('%capital_name is a free-tagging vocabulary. To change the name or description of a term, click the <em>edit</em> link next to the term.', array('%capital_name' => drupal_ucfirst($vocabulary->name))) .'</p>';
  1239. }
  1240. switch ($vocabulary->hierarchy) {
  1241. case 0:
  1242. return '<p>'. t('%capital_name is a flat vocabulary. You may organize the terms in the %name vocabulary by using the handles on the left side of the table. To change the name or description of a term, click the <em>edit</em> link next to the term.', array('%capital_name' => drupal_ucfirst($vocabulary->name), '%name' => $vocabulary->name)) .'</p>';
  1243. case 1:
  1244. return '<p>'. t('%capital_name is a single hierarchy vocabulary. You may organize the terms in the %name vocabulary by using the handles on the left side of the table. To change the name or description of a term, click the <em>edit</em> link next to the term.', array('%capital_name' => drupal_ucfirst($vocabulary->name), '%name' => $vocabulary->name)) .'</p>';
  1245. case 2:
  1246. return '<p>'. t('%capital_name is a multiple hierarchy vocabulary. To change the name or description of a term, click the <em>edit</em> link next to the term. Drag and drop of multiple hierarchies is not supported, but you can re-enable drag and drop support by editing each term to include only a single parent.', array('%capital_name' => drupal_ucfirst($vocabulary->name))) .'</p>';
  1247. }
  1248. case 'admin/content/taxonomy/add/vocabulary':
  1249. return '<p>'. t('Define how your vocabulary will be presented to administrators and users, and which content types to categorize with it. Tags allows users to create terms when submitting posts by typing a comma separated list. Otherwise terms are chosen from a select list and can only be created by users with the "administer taxonomy" permission.') .'</p>';
  1250. }
  1251. }
  1252. /**
  1253. * Helper function for array_map purposes.
  1254. */
  1255. function _taxonomy_get_tid_from_term($term) {
  1256. return $term->tid;
  1257. }
  1258. /**
  1259. * Implodes a list of tags of a certain vocabulary into a string.
  1260. *
  1261. * @see drupal_explode_tags()
  1262. */
  1263. function taxonomy_implode_tags($tags, $vid = NULL) {
  1264. $typed_tags = array();
  1265. foreach ($tags as $tag) {
  1266. // Extract terms belonging to the vocabulary in question.
  1267. if (is_null($vid) || $tag->vid == $vid) {
  1268. // Commas and quotes in tag names are special cases, so encode 'em.
  1269. if (strpos($tag->name, ',') !== FALSE || strpos($tag->name, '"') !== FALSE) {
  1270. $tag->name = '"'. str_replace('"', '""', $tag->name) .'"';
  1271. }
  1272. $typed_tags[] = $tag->name;
  1273. }
  1274. }
  1275. return implode(', ', $typed_tags);
  1276. }
  1277. /**
  1278. * Implementation of hook_hook_info().
  1279. */
  1280. function taxonomy_hook_info() {
  1281. return array(
  1282. 'taxonomy' => array(
  1283. 'taxonomy' => array(
  1284. 'insert' => array(
  1285. 'runs when' => t('After saving a new term to the database'),
  1286. ),
  1287. 'update' => array(
  1288. 'runs when' => t('After saving an updated term to the database'),
  1289. ),
  1290. 'delete' => array(
  1291. 'runs when' => t('After deleting a term')
  1292. ),
  1293. ),
  1294. ),
  1295. );
  1296. }

Comments

I haven't seen this documented anywhere. Here's a simple way to add a set of free terms to a loaded node.

$node = node_load($nid);
$terms = array('term1', 'term2', 'term3');
// Supply terms as string of comma separated values
$node->taxonomy['tags'][$vocabulary_id] = implode(terms, ",");
node_save($node)

A small correction to typos in the sample code provided above:

$node = node_load($nid);
$terms = array('term1', 'term2', 'term3');
// Supply terms as string of comma separated values
$node->taxonomy['tags'][$vocabulary_id] = implode($terms, ",");
node_save($node);

(It should be "$terms" in the implode, not "terms" and "node_save($node)" ends in a ";")


Also, to find the vocabulary ID for the taxonomy vocabulary and how to do it in a Triggered Rule, you can check here.