synonyms.pages.inc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. <?php
  2. /**
  3. * @file
  4. * Menu page callbacks of Synonyms module.
  5. */
  6. /**
  7. * Page callback: Outputs JSON for taxonomy autocomplete suggestions.
  8. *
  9. * This callback outputs term name suggestions in response to Ajax requests
  10. * made by the synonyms autocomplete widget for taxonomy term reference
  11. * fields. The output is a JSON object of plain-text term suggestions,
  12. * keyed by the user-entered value with the completed term name appended.
  13. * Term names containing commas are wrapped in quotes. The search is made
  14. * with consideration of synonyms.
  15. *
  16. * @param string $field_name
  17. * The name of the term reference field.
  18. * @param string $entity_type
  19. * Entity type to which the supplied $field_name is attached to
  20. * @param string $bundle
  21. * Bundle name to which the supplied $field_name is attached to
  22. * @param string $tags_typed
  23. * (optional) A comma-separated list of term names entered in the
  24. * autocomplete form element. Only the last term is used for autocompletion.
  25. * Defaults to '' (an empty string).
  26. */
  27. function synonyms_autocomplete($field_name, $entity_type, $bundle, $tags_typed = '') {
  28. // If the request has a '/' in the search text, then the menu system will have
  29. // split it into multiple arguments, recover the intended $tags_typed.
  30. $args = func_get_args();
  31. // Shift off the $field_name argument.
  32. array_shift($args);
  33. // Shift off the $entity_type argument.
  34. array_shift($args);
  35. // Shift off the $bundle argument.
  36. array_shift($args);
  37. $tags_typed = implode('/', $args);
  38. // Make sure the field exists and is a taxonomy field.
  39. if (!($field = field_info_field($field_name)) || $field['type'] != 'taxonomy_term_reference') {
  40. // Error string. The JavaScript handler will realize this is not JSON and
  41. // will display it as debugging information.
  42. print t('Taxonomy field @field_name not found.', array('@field_name' => $field_name));
  43. exit;
  44. }
  45. if (!($instance = field_info_instance($entity_type, $field['field_name'], $bundle))) {
  46. // Error string. The JavaScript handler will realize this is not JSON and
  47. // will display it as debugging information.
  48. print t('There was not found an instance of @field_name in @entity_type.', array(
  49. '@field_name' => $field_name,
  50. '@entity_type' => $entity_type,
  51. ));
  52. exit;
  53. }
  54. // How many suggestions maximum we are able to output.
  55. $max_suggestions = $instance['widget']['settings']['suggestion_size'];
  56. // Whether we are allowed to suggest more than one entry per term, shall that
  57. // entry be either term name itself or one of its synonyms.
  58. $suggest_only_unique = $instance['widget']['settings']['suggest_only_unique'];
  59. // The user enters a comma-separated list of tags. We only autocomplete the
  60. // last tag.
  61. $tags_typed = drupal_explode_tags($tags_typed);
  62. $tag_last = drupal_strtolower(array_pop($tags_typed));
  63. $term_matches = array();
  64. if ($tag_last != '') {
  65. // Part of the criteria for the query come from the field's own settings.
  66. $vocabularies = array();
  67. $tmp = taxonomy_vocabulary_get_names();
  68. foreach ($field['settings']['allowed_values'] as $tree) {
  69. $vocabularies[$tmp[$tree['vocabulary']]->vid] = $tree['vocabulary'];
  70. }
  71. $vocabularies = taxonomy_vocabulary_load_multiple(array_keys($vocabularies));
  72. // Array of found suggestions. Each subarray of this array will represent
  73. // a single suggestion entry. The sub array must at least contain the
  74. // following keys:
  75. // tid - tid of the suggested term
  76. // name - name of the suggested term
  77. // And optionally, if the term is suggested based on its synonym, the sub
  78. // array should also include the additional key:
  79. // synonym - string representation of the synonym based on which the
  80. // suggested term was included.
  81. $tags_return = array();
  82. // Firstly getting a list of tids that match by $term->name.
  83. $query = db_select('taxonomy_term_data', 't');
  84. $query->addTag('translatable');
  85. $query->addTag('term_access');
  86. // Do not select already entered terms.
  87. if (!empty($tags_typed)) {
  88. $query->condition('t.name', $tags_typed, 'NOT IN');
  89. }
  90. // Select rows that match by term name.
  91. $result = $query
  92. ->fields('t', array('tid', 'name'))
  93. ->condition('t.vid', array_keys($vocabularies))
  94. ->condition('t.name', '%' . db_like($tag_last) . '%', 'LIKE')
  95. ->range(0, $max_suggestions)
  96. ->execute()
  97. ->fetchAllKeyed();
  98. // Converting results into another format.
  99. foreach ($result as $tid => $name) {
  100. $tags_return[] = array(
  101. 'name' => $name,
  102. 'tid' => $tid,
  103. );
  104. }
  105. $synonym_tids = array();
  106. // Now we go vocabulary by vocabulary looking through synonym fields.
  107. foreach ($vocabularies as $vocabulary) {
  108. // Now we go a synonym field by synonym field gathering suggestions.
  109. // Since officially EntityFieldQuery doesn't support OR conditions
  110. // we are enforced to go a field by field querying multiple times the DB.
  111. $bundle = field_extract_bundle('taxonomy_term', $vocabulary);
  112. foreach (synonyms_synonyms_fields($vocabulary) as $field) {
  113. $field = field_info_field($field);
  114. $instance = field_info_instance('taxonomy_term', $field['field_name'], $bundle);
  115. $query = new EntityFieldQuery();
  116. $query->entityCondition('entity_type', 'taxonomy_term')
  117. ->entityCondition('bundle', $bundle);
  118. // We let the class that defines this field type as a source of synonyms
  119. // filter out and provide its suggestions based on this field.
  120. $class = synonyms_extractor_info($field['type']);
  121. call_user_func(array($class, 'processEntityFieldQuery'), $tag_last, $query, $field, $instance);
  122. if (!empty($tags_typed)) {
  123. $query->propertyCondition('name', $tags_typed, 'NOT IN');
  124. }
  125. if ($suggest_only_unique && !empty($tags_return)) {
  126. $tmp = array();
  127. foreach ($tags_return as $tag_return) {
  128. $tmp[] = $tag_return['tid'];
  129. }
  130. // We don't want to search among the terms already found by term name.
  131. $query->entityCondition('entity_id', $tmp, 'NOT IN');
  132. }
  133. if ($suggest_only_unique && !empty($synonym_tids)) {
  134. // We also don't want to search among the terms already matched by
  135. // previous synonym fields.
  136. $query->entityCondition('entity_id', $synonym_tids, 'NOT IN');
  137. }
  138. $tmp = $query->execute();
  139. if (!empty($tmp)) {
  140. // Merging the results.
  141. $tmp = array_keys($tmp['taxonomy_term']);
  142. $synonym_tids = array_merge($synonym_tids, $tmp);
  143. }
  144. }
  145. }
  146. if (!empty($synonym_tids)) {
  147. foreach (taxonomy_term_load_multiple($synonym_tids) as $synonym_term) {
  148. $tmp = array(
  149. 'name' => $synonym_term->name,
  150. 'tid' => $synonym_term->tid,
  151. );
  152. // Additionally we have to find out which synonym triggered inclusion of
  153. // this term.
  154. foreach (synonyms_get_sanitized($synonym_term) as $item) {
  155. if (strpos(mb_strtoupper($item, 'UTF-8'), mb_strtoupper($tag_last, 'UTF-8')) !== FALSE) {
  156. $tags_return[] = array('synonym' => $item) + $tmp;
  157. if ($suggest_only_unique) {
  158. // We just want to output 1 single suggestion entry per term, so
  159. // one synonym is enough.
  160. break;
  161. }
  162. }
  163. }
  164. }
  165. }
  166. $prefix = empty($tags_typed) ? '' : drupal_implode_tags($tags_typed) . ', ';
  167. if (count($tags_return) > $max_suggestions) {
  168. $tags_return = array_slice($tags_return, 0, $max_suggestions);
  169. }
  170. // Now formatting the results.
  171. foreach ($tags_return as $info) {
  172. $n = $info['name'];
  173. // Term names containing commas or quotes must be wrapped in quotes.
  174. if (strpos($info['name'], ',') !== FALSE || strpos($info['name'], '"') !== FALSE) {
  175. $n = '"' . str_replace('"', '""', $info['name']) . '"';
  176. }
  177. if (isset($info['synonym'])) {
  178. $display_name = t('@synonym, synonym of %term', array('@synonym' => $info['synonym'], '%term' => $info['name']));
  179. }
  180. else {
  181. $display_name = check_plain($info['name']);
  182. }
  183. while (isset($term_matches[$prefix . $n])) {
  184. $n .= ' ';
  185. }
  186. $term_matches[$prefix . $n] = $display_name;
  187. }
  188. }
  189. drupal_json_output($term_matches);
  190. }
  191. /**
  192. * Mark nodes that reference specific terms for search re-indexing.
  193. *
  194. * This is particularly useful, when the terms in question have been changed.
  195. *
  196. * @param $tids array
  197. * Array of tids of the terms
  198. */
  199. function synonyms_reindex_nodes_by_terms($tids) {
  200. // In order to speed up the process, we will query DB for nid's that reference
  201. // handled to us tids, and at the end we'll trigger their re-indexing in just
  202. // a single SQL query. Probably it is better to use search_touch_node(), but
  203. // that would imply a big amount of SQL queries on some websites.
  204. $found_nids = array();
  205. foreach (field_info_field_map() as $field_name => $v) {
  206. if ($v['type'] == 'taxonomy_term_reference' && isset($v['bundles']['node'])) {
  207. // This field is taxonomy term reference and it is attached to nodes, so
  208. // we will run EntityFieldQuery on it.
  209. $query = new EntityFieldQuery();
  210. $result = $query->entityCondition('entity_type', 'node')
  211. ->fieldCondition($field_name, 'tid', $tids, 'IN')
  212. ->execute();
  213. if (isset($result['node'])) {
  214. $found_nids = array_merge($found_nids, array_keys($result['node']));
  215. }
  216. }
  217. }
  218. if (!empty($found_nids)) {
  219. db_update('search_dataset')
  220. ->fields(array('reindex' => REQUEST_TIME))
  221. ->condition('type', 'node')
  222. ->condition('sid', $found_nids, 'IN')
  223. ->execute();
  224. }
  225. }
  226. /**
  227. * Mark nodes that reference terms from a vocabulary for search re-indexing.
  228. *
  229. * @param $vocabulary object
  230. * Fully loaded vocabulary object
  231. */
  232. function synonyms_reindex_nodes_by_vocabulary($vocabulary) {
  233. $tids = db_select('taxonomy_term_data', 't')
  234. ->fields('t', array('tid'))
  235. ->condition('vid', $vocabulary->vid)
  236. ->execute()
  237. ->fetchCol();
  238. if (!empty($tids)) {
  239. synonyms_reindex_nodes_by_terms($tids);
  240. }
  241. }
  242. /**
  243. * Submit handler for Taxonomy vocabulary edit form.
  244. *
  245. * Store extra values attached to form in this module.
  246. */
  247. function synonyms_taxonomy_form_vocabulary_submit($form, &$form_state) {
  248. $values = $form_state['values'];
  249. if ($values['op'] == $form['actions']['submit']['#value']) {
  250. if (isset($form['#vocabulary']->vid)) {
  251. $vocabulary = taxonomy_vocabulary_load($form['#vocabulary']->vid);
  252. }
  253. else {
  254. // As a fallback, if this is a just created vocabulary, we try to pull it
  255. // up by the just submitted machine name.
  256. $vocabulary = taxonomy_vocabulary_machine_name_load($values['machine_name']);
  257. }
  258. // Preprocessing values keeping only field names of the checked fields.
  259. $values['synonyms']['synonyms'] = array_values(array_filter($values['synonyms']['synonyms']));
  260. $settings = synonyms_vocabulary_settings($vocabulary);
  261. $settings = $values['synonyms'] + $settings;
  262. synonyms_vocabulary_settings_save($vocabulary, $settings);
  263. }
  264. }