synonyms.pages.inc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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_taxonomy_term($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_taxonomy_term' ? $instance['widget']['settings'] : field_info_widget_settings('synonyms_autocomplete_taxonomy_term');
  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. // Array of found suggestions. Each subarray of this array will represent a
  75. // single suggestion entry.
  76. // - tid: (int) tid of the suggested term
  77. // - name: (string) name of the suggested term
  78. // - synonym: (string) optional synonym string that matched this entry
  79. // - behavior_implementation: (array) optional behavior implementation that
  80. // provided the synonym
  81. $tags_return = array();
  82. if ($tag_last != '') {
  83. // Part of the criteria for the query come from the field's own settings.
  84. $vocabularies = array();
  85. $tmp = taxonomy_vocabulary_get_names();
  86. foreach ($field['settings']['allowed_values'] as $tree) {
  87. $vocabularies[$tmp[$tree['vocabulary']]->vid] = $tree['vocabulary'];
  88. }
  89. $vocabularies = taxonomy_vocabulary_load_multiple(array_keys($vocabularies));
  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. $tags_return[] = (array) $v;
  107. }
  108. // Now we go vocabulary by vocabulary looking through synonym fields.
  109. foreach ($vocabularies as $vocabulary) {
  110. // Now we go a synonym field by synonym field gathering suggestions.
  111. $bundle = field_extract_bundle('taxonomy_term', $vocabulary);
  112. $behavior_implementations = synonyms_behavior_get('autocomplete', 'taxonomy_term', $bundle, TRUE);
  113. foreach ($behavior_implementations as $implementation) {
  114. $condition = db_and();
  115. $condition->condition(AbstractSynonymsBehavior::COLUMN_SYNONYM_PLACEHOLDER, '%' . db_like($tag_last) . '%', 'LIKE');
  116. if (!empty($tags_typed_tids)) {
  117. $condition->condition(AbstractSynonymsBehavior::COLUMN_ENTITY_ID_PLACEHOLDER, $tags_typed_tids, 'NOT IN');
  118. }
  119. if ($suggest_only_unique && !empty($tags_return)) {
  120. $tmp = array();
  121. foreach ($tags_return as $tag_return) {
  122. $tmp[] = $tag_return['tid'];
  123. }
  124. $condition->condition(AbstractSynonymsBehavior::COLUMN_ENTITY_ID_PLACEHOLDER, $tmp, 'NOT IN');
  125. }
  126. $new_tids = array();
  127. foreach ($implementation['object']->synonymsFind($condition) as $synonym) {
  128. if (!$suggest_only_unique || !in_array($synonym->entity_id, $new_tids)) {
  129. $tags_return[] = array(
  130. 'tid' => $synonym->entity_id,
  131. 'name' => '',
  132. 'synonym' => $synonym->synonym,
  133. 'behavior_implementation' => $implementation,
  134. );
  135. $new_tids[] = $synonym->entity_id;
  136. }
  137. }
  138. }
  139. }
  140. $synonym_terms = array();
  141. foreach ($tags_return as $v) {
  142. if (isset($v['synonym'])) {
  143. $synonym_terms[] = $v['tid'];
  144. }
  145. }
  146. if (!empty($synonym_terms)) {
  147. $synonym_terms = taxonomy_term_load_multiple($synonym_terms);
  148. foreach ($tags_return as &$v) {
  149. if (isset($v['synonym'])) {
  150. $v['name'] = $synonym_terms[$v['tid']]->name;
  151. }
  152. }
  153. }
  154. if (count($tags_return) > $max_suggestions) {
  155. $tags_return = array_slice($tags_return, 0, $max_suggestions);
  156. }
  157. }
  158. $prefix = empty($tags_typed) ? '' : drupal_implode_tags($tags_typed) . ', ';
  159. drupal_json_output(synonyms_autocomplete_format($tags_return, $prefix));
  160. }
  161. /**
  162. * Page callback: Outputs JSON for entity autocomplete suggestions.
  163. *
  164. * This callback outputs entity name suggestions in response to Ajax requests
  165. * made by the synonyms autocomplete widget for entity reference fields. The
  166. * output is a JSON object of plain-text entity suggestions, keyed by the
  167. * user-entered value with the completed entity name appended. Entity names
  168. * containing commas are wrapped in quotes. The search is made with
  169. * consideration of synonyms.
  170. *
  171. * @param string $field_name
  172. * The name of the entity reference field.
  173. * @param string $entity_type
  174. * Entity type to which the supplied $field_name is attached to
  175. * @param string $bundle
  176. * Bundle name to which the supplied $field_name is attached to
  177. * @param string $tags_typed
  178. * (optional) A comma-separated list of entity names entered in the
  179. * autocomplete form element. Only the last term is used for autocompletion.
  180. * Defaults to '' (an empty string).
  181. */
  182. function synonyms_autocomplete_entity($field_name, $entity_type, $bundle, $tags_typed = '') {
  183. // If the request has a '/' in the search text, then the menu system will have
  184. // split it into multiple arguments, recover the intended $tags_typed.
  185. $args = func_get_args();
  186. // Shift off the $field_name argument.
  187. array_shift($args);
  188. // Shift off the $entity_type argument.
  189. array_shift($args);
  190. // Shift off the $bundle argument.
  191. array_shift($args);
  192. $tags_typed = implode('/', $args);
  193. if (!($field = field_info_field($field_name)) || $field['type'] != 'entityreference') {
  194. print t('Entity reference field @field_name not found.', array('@field_name' => $field_name));
  195. exit;
  196. }
  197. if (!($instance = field_info_instance($entity_type, $field['field_name'], $bundle))) {
  198. // Error string. The JavaScript handler will realize this is not JSON and
  199. // will display it as debugging information.
  200. print t('There was not found an instance of @field_name in @entity_type.', array(
  201. '@field_name' => $field_name,
  202. '@entity_type' => $entity_type,
  203. ));
  204. exit;
  205. }
  206. $widget = $instance['widget']['type'] == 'synonyms_autocomplete_entity' ? $instance['widget']['settings'] : field_info_widget_settings('synonyms_autocomplete_entity');
  207. // How many suggestions maximum we are able to output.
  208. $max_suggestions = $widget['suggestion_size'];
  209. // Whether we are allowed to suggest more than one entry per term, shall that
  210. // entry be either term name itself or one of its synonyms.
  211. $suggest_only_unique = $widget['suggest_only_unique'];
  212. $tags_typed = drupal_explode_tags($tags_typed);
  213. $tag_last = drupal_strtolower(array_pop($tags_typed));
  214. $prefix = count($tags_typed) ? drupal_implode_tags($tags_typed) . ', ' : '';
  215. $handler = entityreference_get_selection_handler($field, $instance, $entity_type, NULL);
  216. $tags_typed_entity_ids = array();
  217. if (!empty($tags_typed)) {
  218. foreach ($handler->getReferencableEntities($tags_typed, 'IN') as $target_entity_ids) {
  219. $tags_typed_entity_ids = array_merge($tags_typed_entity_ids, array_keys($target_entity_ids));
  220. }
  221. }
  222. $matches = array();
  223. if ($tag_last) {
  224. foreach ($handler->getReferencableEntities($tag_last) as $target_entity_ids) {
  225. foreach (array_diff_key($target_entity_ids, drupal_map_assoc($tags_typed_entity_ids)) as $target_id => $label) {
  226. $matches[] = array(
  227. 'target_id' => $target_id,
  228. 'name' => $label,
  229. );
  230. if (count($matches) == $max_suggestions) {
  231. break (2);
  232. }
  233. }
  234. }
  235. if (count($matches) < $max_suggestions) {
  236. $behavior_implementations = synonyms_behavior_get('autocomplete', $field['settings']['target_type'], synonyms_field_target_bundles($field), TRUE);
  237. foreach ($behavior_implementations as $implementation) {
  238. $condition = db_and();
  239. $condition->condition(AbstractSynonymsBehavior::COLUMN_SYNONYM_PLACEHOLDER, '%' . db_like($tag_last) . '%', 'LIKE');
  240. if (!empty($tags_typed_entity_ids)) {
  241. $condition->condition(AbstractSynonymsBehavior::COLUMN_ENTITY_ID_PLACEHOLDER, $tags_typed_entity_ids, 'NOT IN');
  242. }
  243. if ($suggest_only_unique && !empty($matches)) {
  244. $tmp = array();
  245. foreach ($matches as $match) {
  246. $tmp[] = $match['target_id'];
  247. }
  248. $condition->condition(AbstractSynonymsBehavior::COLUMN_ENTITY_ID_PLACEHOLDER, $tmp, 'NOT IN');
  249. }
  250. $new_target_ids = array();
  251. foreach ($implementation['object']->synonymsFind($condition) as $synonym) {
  252. if (!$suggest_only_unique || !in_array($synonym->entity_id, $new_target_ids)) {
  253. $matches[] = array(
  254. 'target_id' => $synonym->entity_id,
  255. 'synonym' => $synonym->synonym,
  256. 'behavior_implementation' => $implementation,
  257. );
  258. $new_target_ids[] = $synonym->entity_id;
  259. if (count($matches) == $max_suggestions) {
  260. break (2);
  261. }
  262. }
  263. }
  264. }
  265. }
  266. $synonym_entities = array();
  267. foreach ($matches as $match) {
  268. if (!isset($match['wording']) && isset($match['synonym'])) {
  269. $synonym_entities[] = $match['target_id'];
  270. }
  271. }
  272. if (!empty($synonym_entities)) {
  273. $synonym_entities = entity_load($field['settings']['target_type'], $synonym_entities);
  274. foreach ($matches as $k => $match) {
  275. if (!isset($match['name']) && isset($match['synonym'])) {
  276. if (entity_access('view', $field['settings']['target_type'], $synonym_entities[$match['target_id']])) {
  277. $matches[$k]['name'] = entity_label($field['settings']['target_type'], $synonym_entities[$match['target_id']]);
  278. }
  279. else {
  280. unset($matches[$k]);
  281. }
  282. }
  283. }
  284. $matches = array_values($matches);
  285. }
  286. }
  287. drupal_json_output(synonyms_autocomplete_format($matches, $prefix));
  288. }
  289. /**
  290. * Supportive function to format autocomplete suggestions.
  291. *
  292. * @param array $matches
  293. * Array of matched entries. It should follow this structure:
  294. * - name: (string) String to be inserted into autocomplete textfield if user
  295. * chooses this autocomplete entry
  296. * - synonym: (string) If this entry is matched through a synonym, put that
  297. * synonym here
  298. * - behavior_implementation: (array) If this entry is matched through a
  299. * synonym, put here the behavior implementation array that provided this
  300. * match
  301. * @param string $prefix
  302. * Any prefix to be appended to 'name' property of $matches array when
  303. * inserting into the autocomplete textfield. Normally it is the already
  304. * entered entries in the textfield
  305. *
  306. * @return array
  307. * Array of formatted autocomplete response entries ready to be returned to
  308. * the autocomplete JavaScript
  309. */
  310. function synonyms_autocomplete_format($matches, $prefix) {
  311. $output = array();
  312. foreach ($matches as $match) {
  313. $n = synonyms_autocomplete_escape($match['name']);
  314. while (isset($output[$prefix . $n])) {
  315. $n .= ' ';
  316. }
  317. $wording = check_plain($match['name']);
  318. if (isset($match['synonym'])) {
  319. $wording = format_string(filter_xss($match['behavior_implementation']['settings']['wording']), array(
  320. '@entity' => $match['name'],
  321. '@synonym' => $match['synonym'],
  322. '@field_name' => drupal_strtolower($match['behavior_implementation']['label']),
  323. ));
  324. }
  325. $output[$prefix . $n] = $wording;
  326. }
  327. return $output;
  328. }
  329. /**
  330. * Default theme implementation for behavior settings form element.
  331. */
  332. function theme_synonyms_behaviors_settings($variables) {
  333. drupal_add_css(drupal_get_path('module', 'synonyms') . '/synonyms.css');
  334. $element = &$variables['element'];
  335. $table = array(
  336. 'header' => array(t('Field')),
  337. 'rows' => array(),
  338. 'empty' => t('Seems like there are no fields for which synonyms functionality available. Try adding a text field to get started.'),
  339. );
  340. $instance_ids = array();
  341. foreach (element_children($element) as $behavior) {
  342. $table['header'][] = check_plain($element[$behavior]['#title']);
  343. $instance_ids = array_unique(array_merge($instance_ids, element_children($element[$behavior])));
  344. }
  345. foreach ($instance_ids as $instance_id) {
  346. $row = array();
  347. $row_title = '';
  348. foreach (element_children($element) as $behavior) {
  349. if (isset($element[$behavior][$instance_id]['#title']) && !$row_title) {
  350. $row_title = check_plain($element[$behavior][$instance_id]['#title']);
  351. }
  352. $row[] = array(
  353. 'data' => isset($element[$behavior][$instance_id]) ? drupal_render($element[$behavior][$instance_id]) : t('Not implemented'),
  354. 'class' => array('synonyms-behavior-settings', 'synonyms-behavior-settings-' . $behavior),
  355. );
  356. }
  357. array_unshift($row, $row_title);
  358. $table['rows'][] = $row;
  359. }
  360. return '<div id="' . $element['#id'] . '">' . theme('table', $table) . drupal_render_children($element) . '</div>';
  361. }
  362. /**
  363. * Page menu callback for managing Synonyms settings of entity types.
  364. */
  365. function synonyms_settings_overview() {
  366. $output = array();
  367. $output['table'] = array(
  368. '#theme' => 'table',
  369. '#header' => array(t('Entity type'), t('Bundle'), t('Manage')),
  370. '#rows' => array(),
  371. );
  372. foreach (entity_get_info() as $entity_type => $entity_info) {
  373. if (synonyms_entity_type_load($entity_type)) {
  374. foreach ($entity_info['bundles'] as $bundle => $bundle_info) {
  375. $output['table']['#rows'][] = array(
  376. $entity_info['label'],
  377. $bundle == $entity_type ? '' : $bundle_info['label'],
  378. l(t('Edit'), 'admin/structure/synonyms/' . $entity_type . '/' . $bundle),
  379. );
  380. }
  381. }
  382. }
  383. return $output;
  384. }
  385. /**
  386. * Synonyms settings form for a specific entity type and bundle name.
  387. *
  388. * @param string $entity_type
  389. * Entity type for which to generate synonyms settings form
  390. * @param string $bundle
  391. * Bundle name for which to generate synonyms settings form
  392. */
  393. function synonyms_settings_form($form, &$form_state, $entity_type, $bundle) {
  394. $form['settings'] = array(
  395. '#tree' => TRUE,
  396. '#theme' => 'synonyms_behaviors_settings',
  397. '#id' => 'synonyms-behaviors-settings-wrapper',
  398. '#entity_type' => $entity_type,
  399. '#bundle' => $bundle,
  400. );
  401. $behaviors = synonyms_behaviors();
  402. foreach ($behaviors as $behavior => $behavior_info) {
  403. $form['settings'][$behavior] = array(
  404. '#title' => $behavior_info['title'],
  405. );
  406. $behavior_implementations = synonyms_behavior_get($behavior, $entity_type, $bundle);
  407. foreach ($behavior_implementations as $implementation) {
  408. $form['settings'][$behavior][$implementation['provider']]['#title'] = $implementation['label'];
  409. if (isset($form_state['values']['settings'][$behavior][$implementation['provider']])) {
  410. $behavior_settings = (bool) $form_state['values']['settings'][$behavior][$implementation['provider']]['enabled'];
  411. }
  412. else {
  413. $behavior_settings = isset($implementation['settings']);
  414. }
  415. if ($behavior_settings) {
  416. if (isset($form_state['values']['settings'][$behavior][$implementation['provider']]['settings'])) {
  417. $behavior_settings = $form_state['values']['settings'][$behavior][$implementation['provider']]['settings'];
  418. }
  419. elseif (isset($implementation['settings'])) {
  420. $behavior_settings = $implementation['settings'];
  421. }
  422. else {
  423. $behavior_settings = array();
  424. }
  425. }
  426. $form['settings'][$behavior][$implementation['provider']]['enabled'] = array(
  427. '#type' => 'checkbox',
  428. '#title' => t('Enable'),
  429. '#default_value' => $behavior_settings !== FALSE,
  430. );
  431. $settings_form = ctools_plugin_get_function($behavior_info, 'settings form callback');
  432. if ($settings_form) {
  433. $form['settings'][$behavior][$implementation['provider']]['enabled']['#ajax'] = array(
  434. 'callback' => 'synonyms_settings_form_ajax',
  435. 'wrapper' => $form['settings']['#id'],
  436. );
  437. if ($behavior_settings !== FALSE) {
  438. $form['settings'][$behavior][$implementation['provider']]['settings'] = $settings_form($form, $form_state, $behavior_settings);
  439. }
  440. }
  441. }
  442. }
  443. $form['actions'] = array(
  444. '#type' => '#actions',
  445. );
  446. $form['actions']['submit'] = array(
  447. '#type' => 'submit',
  448. '#value' => t('Save'),
  449. );
  450. return $form;
  451. }
  452. /**
  453. * Submit handler for 'synonyms_settings_form' form.
  454. *
  455. * Store synonyms behavior settings.
  456. */
  457. function synonyms_settings_form_submit($form, &$form_state) {
  458. foreach ($form_state['values']['settings'] as $behavior => $settings) {
  459. foreach ($settings as $provider => $behavior_settings) {
  460. $behavior_implementation = array(
  461. 'entity_type' => $form['settings']['#entity_type'],
  462. 'bundle' => $form['settings']['#bundle'],
  463. 'provider' => $provider,
  464. 'behavior' => $behavior,
  465. 'settings' => isset($behavior_settings['settings']) ? $behavior_settings['settings'] : NULL,
  466. );
  467. if ($behavior_settings['enabled']) {
  468. synonyms_behavior_implementation_save($behavior_implementation);
  469. }
  470. else {
  471. synonyms_behavior_implementation_delete($behavior_implementation);
  472. }
  473. }
  474. }
  475. drupal_set_message(t('Synonyms settings have been successfully saved.'));
  476. $form_state['redirect'] = array('admin/structure/synonyms');
  477. }
  478. /**
  479. * Ajax callback function for synonyms settings form.
  480. */
  481. function synonyms_settings_form_ajax($form, &$form_state) {
  482. return $form['settings'];
  483. }