synonyms.pages.inc 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. $widget = $instance['widget']['type'] == 'synonyms_autocomplete' ? $instance['widget']['settings'] : field_info_widget_settings('synonyms_autocomplete');
  55. // How many suggestions maximum we are able to output.
  56. $max_suggestions = $widget['suggestion_size'];
  57. // Whether we are allowed to suggest more than one entry per term, shall that
  58. // entry be either term name itself or one of its synonyms.
  59. $suggest_only_unique = $widget['suggest_only_unique'];
  60. // The user enters a comma-separated list of tags. We only autocomplete the
  61. // last tag.
  62. $tags_typed = drupal_explode_tags($tags_typed);
  63. $tag_last = drupal_strtolower(array_pop($tags_typed));
  64. $tags_typed_tids = array();
  65. if (!empty($tags_typed)) {
  66. $efq = new EntityFieldQuery();
  67. $efq->entityCondition('entity_type', 'taxonomy_term');
  68. $efq->propertyCondition('name', $tags_typed);
  69. $tags_typed_tids = $efq->execute();
  70. if (isset($tags_typed_tids['taxonomy_term'])) {
  71. $tags_typed_tids = array_keys($tags_typed_tids['taxonomy_term']);
  72. }
  73. }
  74. $term_matches = array();
  75. if ($tag_last != '') {
  76. // Part of the criteria for the query come from the field's own settings.
  77. $vocabularies = array();
  78. $tmp = taxonomy_vocabulary_get_names();
  79. foreach ($field['settings']['allowed_values'] as $tree) {
  80. $vocabularies[$tmp[$tree['vocabulary']]->vid] = $tree['vocabulary'];
  81. }
  82. $vocabularies = taxonomy_vocabulary_load_multiple(array_keys($vocabularies));
  83. // Array of found suggestions. Each subarray of this array will represent
  84. // a single suggestion entry. The sub array must contain the following keys:
  85. // - tid: (int) tid of the suggested term
  86. // - name: (string) name of the suggested term
  87. // - wording: (string) human friendly XSS escaped text of the suggestion
  88. // entry
  89. $tags_return = array();
  90. // Firstly getting a list of tids that match by $term->name.
  91. $query = db_select('taxonomy_term_data', 't');
  92. $query->addTag('translatable');
  93. $query->addTag('term_access');
  94. // Do not select already entered terms.
  95. if (!empty($tags_typed_tids)) {
  96. $query->condition('t.tid', $tags_typed_tids, 'NOT IN');
  97. }
  98. // Select rows that match by term name.
  99. $result = $query
  100. ->fields('t', array('tid', 'name'))
  101. ->condition('t.vid', array_keys($vocabularies))
  102. ->condition('t.name', '%' . db_like($tag_last) . '%', 'LIKE')
  103. ->range(0, $max_suggestions)
  104. ->execute();
  105. foreach ($result as $v) {
  106. $v = (array) $v;
  107. $v['wording'] = check_plain($v['name']);
  108. $tags_return[] = $v;
  109. }
  110. // Now we go vocabulary by vocabulary looking through synonym fields.
  111. foreach ($vocabularies as $vocabulary) {
  112. // Now we go a synonym field by synonym field gathering suggestions.
  113. $bundle = field_extract_bundle('taxonomy_term', $vocabulary);
  114. $behavior_implementations = synonyms_behavior_get('autocomplete', 'taxonomy_term', $bundle, TRUE);
  115. foreach ($behavior_implementations as $implementation) {
  116. $condition = db_and();
  117. $condition->condition(AbstractSynonymsSynonymsBehavior::COLUMN_PLACEHOLDER, '%' . db_like($tag_last) . '%', 'LIKE');
  118. if (!empty($tags_typed_tids)) {
  119. $condition->condition('entity_id', $tags_typed_tids, 'NOT IN');
  120. }
  121. if ($suggest_only_unique && !empty($tags_return)) {
  122. $tmp = array();
  123. foreach ($tags_return as $tag_return) {
  124. $tmp[] = $tag_return['tid'];
  125. }
  126. $condition->condition('entity_id', $tmp, 'NOT IN');
  127. }
  128. $new_tids = array();
  129. foreach (synonyms_synonyms_find_behavior($condition, $implementation) as $synonym) {
  130. if (!$suggest_only_unique || !in_array($synonym->entity_id, $new_tids)) {
  131. $tags_return[] = array(
  132. 'tid' => $synonym->entity_id,
  133. 'name' => '',
  134. 'synonym' => $synonym->synonym,
  135. 'implementation' => $implementation,
  136. );
  137. $new_tids[] = $synonym->entity_id;
  138. }
  139. }
  140. }
  141. }
  142. $synonym_terms = array();
  143. foreach ($tags_return as $v) {
  144. if (isset($v['synonym'])) {
  145. $synonym_terms[] = $v['tid'];
  146. }
  147. }
  148. if (!empty($synonym_terms)) {
  149. $synonym_terms = taxonomy_term_load_multiple($synonym_terms);
  150. foreach ($tags_return as &$v) {
  151. if (isset($v['synonym'])) {
  152. $instance = field_info_instance($v['implementation']['entity_type'], $v['implementation']['field_name'], $v['implementation']['bundle']);
  153. $v['name'] = $synonym_terms[$v['tid']]->name;
  154. $v['wording'] = format_string(filter_xss($v['implementation']['settings']['wording']), array(
  155. '@synonym' => $v['synonym'],
  156. '@term' => $v['name'],
  157. '@field_name' => drupal_strtolower($instance['label']),
  158. ));
  159. }
  160. }
  161. }
  162. $prefix = empty($tags_typed) ? '' : drupal_implode_tags($tags_typed) . ', ';
  163. if (count($tags_return) > $max_suggestions) {
  164. $tags_return = array_slice($tags_return, 0, $max_suggestions);
  165. }
  166. // Now formatting the results.
  167. foreach ($tags_return as $info) {
  168. $n = $info['name'];
  169. // Term names containing commas or quotes must be wrapped in quotes.
  170. if (strpos($info['name'], ',') !== FALSE || strpos($info['name'], '"') !== FALSE) {
  171. $n = '"' . str_replace('"', '""', $info['name']) . '"';
  172. }
  173. while (isset($term_matches[$prefix . $n])) {
  174. $n .= ' ';
  175. }
  176. $term_matches[$prefix . $n] = $info['wording'];
  177. }
  178. }
  179. drupal_json_output($term_matches);
  180. }
  181. /**
  182. * Default theme implementation for behavior settings form element.
  183. */
  184. function theme_synonyms_behaviors_settings($variables) {
  185. drupal_add_css(drupal_get_path('module', 'synonyms') . '/synonyms.css');
  186. $element = &$variables['element'];
  187. $table = array(
  188. 'header' => array(t('Field')),
  189. 'rows' => array(),
  190. 'empty' => t('Seems like there are no fields for which synonyms functionality is available. Try adding a text field to get started.'),
  191. );
  192. $instance_ids = array();
  193. foreach (element_children($element) as $behavior) {
  194. $table['header'][] = check_plain($element[$behavior]['#title']);
  195. $instance_ids = array_unique(array_merge($instance_ids, element_children($element[$behavior])));
  196. }
  197. foreach ($instance_ids as $instance_id) {
  198. $row = array();
  199. $row_title = '';
  200. foreach (element_children($element) as $behavior) {
  201. if (isset($element[$behavior][$instance_id]['#title']) && !$row_title) {
  202. $row_title = check_plain($element[$behavior][$instance_id]['#title']);
  203. }
  204. $row[] = array(
  205. 'data' => isset($element[$behavior][$instance_id]) ? drupal_render($element[$behavior][$instance_id]) : t('Not implemented'),
  206. 'class' => array('synonyms-behavior-settings', 'synonyms-behavior-settings-' . $behavior),
  207. );
  208. }
  209. array_unshift($row, $row_title);
  210. $table['rows'][] = $row;
  211. }
  212. return '<div id="' . $element['#id'] . '">' . theme('table', $table) . drupal_render_children($element) . '</div>';
  213. }