synonyms.module 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. <?php
  2. /**
  3. * @file
  4. * Provide synonyms feature for Drupal Taxonomy.
  5. */
  6. /**
  7. * The default field name to be used as a source of synonyms for a term.
  8. */
  9. define('SYNONYMS_DEFAULT_FIELD_NAME', 'synonyms_synonyms');
  10. /**
  11. * Implements hook_menu().
  12. */
  13. function synonyms_menu() {
  14. $items = array();
  15. $items['synonyms/autocomplete'] = array(
  16. 'title' => 'Autocomplete Synonyms',
  17. 'page callback' => 'synonyms_autocomplete',
  18. 'access arguments' => array('access content'),
  19. 'type' => MENU_CALLBACK,
  20. );
  21. return $items;
  22. }
  23. /**
  24. * Implements hook_synonyms_extractor_info().
  25. */
  26. function synonyms_synonyms_extractor_info() {
  27. // Here we provide synonyms extractors that come along with Synonyms module.
  28. return array(
  29. 'SynonymsSynonymsExtractor',
  30. 'TaxonomySynonymsExtractor',
  31. 'EntityReferenceSynonymsExtractor',
  32. );
  33. }
  34. /**
  35. * Public function.
  36. *
  37. * Provide info about what class reports ability to extract synonyms from
  38. * which field type. The output information of this function is collected via
  39. * hook_synonyms_extractor_info().
  40. *
  41. * @param string $field_type
  42. * Optionally you may specify to get a class responsible for a specific field
  43. * type only. If nothing is supplied, array of field_type => class_extractor
  44. * relation is returned
  45. * @param bool $reset
  46. * Whether collect all the info again from hooks, or cached info is fine
  47. *
  48. * @return array
  49. * Key of this array denote the field type while value of the array denotes
  50. * which class reports ability to extract synonyms from such field type.
  51. */
  52. function synonyms_extractor_info($field_type = NULL, $reset = FALSE) {
  53. $cache = &drupal_static(__FUNCTION__);
  54. // Trying static cache.
  55. if (!is_array($cache) || $reset) {
  56. // Trying Drupal DB cache layer.
  57. $cid = 'synonyms_extractor_info';
  58. $cache = cache_get($cid);
  59. if (!isset($cache->data) || $reset) {
  60. // No cache has been found at all. So we call hooks and collect data.
  61. $info = array();
  62. $extractor_classes = module_invoke_all('synonyms_extractor_info');
  63. if (is_array($extractor_classes)) {
  64. foreach ($extractor_classes as $class) {
  65. if (class_exists($class) && is_subclass_of($class, 'AbstractSynonymsExtractor')) {
  66. foreach ($class::fieldTypesSupported() as $_field_type) {
  67. $info[$_field_type] = $class;
  68. }
  69. }
  70. }
  71. }
  72. // Letting whoever wants to implement any changes after preprocessing the
  73. // data.
  74. drupal_alter('synonyms_extractor_info', $info);
  75. // Validating that any changes made to $info do not break class hierarchy.
  76. foreach ($info as $k => $v) {
  77. if (!class_exists($v) || !is_subclass_of($v, 'AbstractSynonymsExtractor')) {
  78. unset($info[$k]);
  79. }
  80. }
  81. $cache = $info;
  82. cache_set($cid, $cache, 'cache', CACHE_TEMPORARY);
  83. }
  84. else {
  85. $cache = $cache->data;
  86. }
  87. }
  88. if (!is_null($field_type) && isset($cache[$field_type])) {
  89. return $cache[$field_type];
  90. }
  91. return $cache;
  92. }
  93. /**
  94. * Implements hook_node_update_index().
  95. */
  96. function synonyms_node_update_index($node) {
  97. $output = '';
  98. foreach (field_info_instances('node', $node->type) as $instance) {
  99. // We go a field by field looking for taxonomy term reference and
  100. // if that vocabulary has enabled synonyms, we add term's synonyms
  101. // to the search index.
  102. $field_info = field_info_field($instance['field_name']);
  103. if ($field_info['type'] == 'taxonomy_term_reference') {
  104. // For each term referenced in this node we have to add synonyms.
  105. $_terms = field_get_items('node', $node, $instance['field_name']);
  106. if (is_array($_terms) && !empty($_terms)) {
  107. $terms = array();
  108. foreach ($_terms as $v) {
  109. $terms[] = $v['tid'];
  110. }
  111. $terms = taxonomy_term_load_multiple($terms);
  112. foreach ($terms as $term) {
  113. $synonyms = synonyms_get_term_synonyms($term);
  114. if (!empty($synonyms)) {
  115. $safe_synonyms = array();
  116. foreach ($synonyms as $synonym) {
  117. $safe_synonyms[] = $synonym['safe_value'];
  118. }
  119. $output .= '<strong>' . implode(', ', $safe_synonyms) . '</strong>';
  120. }
  121. }
  122. }
  123. }
  124. }
  125. return $output;
  126. }
  127. /**
  128. * Implements hook_form_FORM_ID_alter().
  129. */
  130. function synonyms_form_taxonomy_form_vocabulary_alter(&$form, &$form_state) {
  131. if (isset($form_state['confirm_delete']) && $form_state['confirm_delete']) {
  132. return;
  133. }
  134. $form['synonyms'] = array(
  135. '#type' => 'fieldset',
  136. '#title' => t('Synonyms'),
  137. '#collapsible' => TRUE,
  138. '#tree' => TRUE,
  139. );
  140. $options = array(
  141. SYNONYMS_DEFAULT_FIELD_NAME => t('Default synonyms field'),
  142. );
  143. if (isset($form['#vocabulary']->vid)) {
  144. $instances = synonyms_instances_extract_applicapable($form['#vocabulary']);
  145. foreach ($instances as $instance) {
  146. // Here we prefer some informative text for the default synonyms field
  147. // rather its label.
  148. if ($instance['field_name'] != SYNONYMS_DEFAULT_FIELD_NAME) {
  149. $options[$instance['field_name']] = $instance['label'];
  150. }
  151. }
  152. }
  153. $form['synonyms']['synonyms'] = array(
  154. '#type' => 'checkboxes',
  155. '#title' => t('Synonyms Fields'),
  156. '#options' => $options,
  157. '#description' => t('<p>This option allows you to assign synonym fields for each term of the vocabulary, allowing to reduce the amount of duplicates.</p><p><b>Important note:</b> unticking %default_field on a production website will result in loss of your synonyms.</p>', array('%default_field' => $options[SYNONYMS_DEFAULT_FIELD_NAME])),
  158. '#default_value' => synonyms_synonyms_fields($form['#vocabulary']),
  159. );
  160. // Adding out own submit handler.
  161. $form['#submit'][] = 'synonyms_taxonomy_form_vocabulary_submit';
  162. }
  163. /**
  164. * Implements hook_field_widget_info().
  165. */
  166. function synonyms_field_widget_info() {
  167. return array(
  168. 'synonyms_autocomplete' => array(
  169. 'label' => t('Synonyms friendly autocomplete term widget'),
  170. 'field types' => array('taxonomy_term_reference'),
  171. 'settings' => array(
  172. 'size' => 60,
  173. 'autocomplete_path' => 'synonyms/autocomplete',
  174. ),
  175. 'behaviors' => array(
  176. 'multiple values' => FIELD_BEHAVIOR_CUSTOM,
  177. ),
  178. ),
  179. );
  180. }
  181. /**
  182. * Implements hook_field_widget_settings_form().
  183. */
  184. function synonyms_field_widget_settings_form($field, $instance) {
  185. $widget = $instance['widget'];
  186. $settings = $widget['settings'];
  187. $form = array();
  188. $form['auto_creation'] = array(
  189. '#type' => 'checkbox',
  190. '#title' => t('Allow auto-creation?'),
  191. '#description' => t('Whether users may create a new term by typing in a non-existing name into this field.'),
  192. '#default_value' => isset($settings['auto_creation']) ? $settings['auto_creation'] : 0,
  193. );
  194. return $form;
  195. }
  196. /**
  197. * Implements hook_field_widget_form().
  198. */
  199. function synonyms_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  200. $tags = array();
  201. foreach ($items as $item) {
  202. $tags[$item['tid']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
  203. }
  204. $element += array(
  205. '#type' => 'textfield',
  206. '#default_value' => taxonomy_implode_tags($tags),
  207. '#autocomplete_path' => $instance['widget']['settings']['autocomplete_path'] . '/' . $field['field_name'],
  208. '#size' => $instance['widget']['settings']['size'],
  209. '#maxlength' => 1024,
  210. '#element_validate' => array('taxonomy_autocomplete_validate', 'synonyms_autocomplete_validate'),
  211. '#auto_creation' => isset($instance['widget']['settings']['auto_creation']) ? $instance['widget']['settings']['auto_creation'] : 0,
  212. );
  213. return $element;
  214. }
  215. /**
  216. * Implements hook_field_widget_error().
  217. */
  218. function synonyms_field_widget_error($element, $error, $form, &$form_state) {
  219. form_error($element, $error['message']);
  220. }
  221. /**
  222. * Form element validate handler.
  223. *
  224. * Handle validation for taxonomy term synonym-friendly autocomplete element.
  225. */
  226. function synonyms_autocomplete_validate($element, &$form_state) {
  227. // After taxonomy_autocomplete_validate() has finished its job
  228. // it might left terms in the format for autocreation. Since our field
  229. // supports auto creation as a configurable option, we have to make sure
  230. // auto creation terms are allowed.
  231. $value = drupal_array_get_nested_value($form_state['values'], $element['#parents']);
  232. if (!$element['#auto_creation']) {
  233. // Deleting all the terms meant to be auto-created.
  234. foreach ($value as $delta => $term) {
  235. if ($term['tid'] == 'autocreate') {
  236. unset($value[$delta]);
  237. }
  238. }
  239. $value = array_values($value);
  240. }
  241. form_set_value($element, $value, $form_state);
  242. }
  243. /**
  244. * Submit hanlder for Taxonomy vocabulary edit form.
  245. *
  246. * Store extra values attached to form in this module.
  247. */
  248. function synonyms_taxonomy_form_vocabulary_submit($form, &$form_state) {
  249. $values = $form_state['values'];
  250. if ($values['op'] == $form['actions']['submit']['#value']) {
  251. if (isset($form['#vocabulary']->vid)) {
  252. $vocabulary = taxonomy_vocabulary_load($form['#vocabulary']->vid);
  253. }
  254. else {
  255. // As a fallback, if this is a just created vocabulary, we try to pull it
  256. // up by the just submitted machine name.
  257. $vocabulary = taxonomy_vocabulary_machine_name_load($values['machine_name']);
  258. }
  259. // Preprocessing values keeping only field names of the checked fields.
  260. foreach ($values['synonyms']['synonyms'] as $k => $v) {
  261. if (!$v) {
  262. unset($values['synonyms']['synonyms'][$k]);
  263. }
  264. }
  265. $values['synonyms']['synonyms'] = array_values($values['synonyms']['synonyms']);
  266. $settings = synonyms_vocabulary_settings($vocabulary);
  267. $settings = $values['synonyms'] + $settings;
  268. synonyms_vocabulary_settings_save($vocabulary, $settings);
  269. }
  270. }
  271. /**
  272. * Page callback: Outputs JSON for taxonomy autocomplete suggestions.
  273. *
  274. * This callback outputs term name suggestions in response to Ajax requests
  275. * made by the synonyms autocomplete widget for taxonomy term reference
  276. * fields. The output is a JSON object of plain-text term suggestions,
  277. * keyed by the user-entered value with the completed term name appended.
  278. * Term names containing commas are wrapped in quotes. The search is made
  279. * with consideration of synonyms.
  280. *
  281. * @param string $field_name
  282. * The name of the term reference field.
  283. * @param string $tags_typed
  284. * (optional) A comma-separated list of term names entered in the
  285. * autocomplete form element. Only the last term is used for autocompletion.
  286. * Defaults to '' (an empty string).
  287. */
  288. function synonyms_autocomplete($field_name, $tags_typed = '') {
  289. // How many suggestions maximum we are able to output.
  290. $max_suggestions = 10;
  291. // If the request has a '/' in the search text, then the menu system will have
  292. // split it into multiple arguments, recover the intended $tags_typed.
  293. $args = func_get_args();
  294. // Shift off the $field_name argument.
  295. array_shift($args);
  296. $tags_typed = implode('/', $args);
  297. // Make sure the field exists and is a taxonomy field.
  298. if (!($field = field_info_field($field_name)) || $field['type'] != 'taxonomy_term_reference') {
  299. // Error string. The JavaScript handler will realize this is not JSON and
  300. // will display it as debugging information.
  301. print t('Taxonomy field @field_name not found.', array('@field_name' => $field_name));
  302. exit;
  303. }
  304. // The user enters a comma-separated list of tags. We only autocomplete the
  305. // last tag.
  306. $tags_typed = drupal_explode_tags($tags_typed);
  307. $tag_last = drupal_strtolower(array_pop($tags_typed));
  308. $term_matches = array();
  309. if ($tag_last != '') {
  310. // Part of the criteria for the query come from the field's own settings.
  311. $vocabularies = array();
  312. $tmp = taxonomy_vocabulary_get_names();
  313. foreach ($field['settings']['allowed_values'] as $tree) {
  314. $vocabularies[$tmp[$tree['vocabulary']]->vid] = $tree['vocabulary'];
  315. }
  316. $vocabularies = taxonomy_vocabulary_load_multiple(array_keys($vocabularies));
  317. // Firstly getting a list of tids that match by $term->name.
  318. $query = db_select('taxonomy_term_data', 't');
  319. $query->addTag('translatable');
  320. $query->addTag('term_access');
  321. // Do not select already entered terms.
  322. if (!empty($tags_typed)) {
  323. $query->condition('t.name', $tags_typed, 'NOT IN');
  324. }
  325. // Select rows that match by term name.
  326. $tags_return = $query
  327. ->fields('t', array('tid', 'name'))
  328. ->condition('t.vid', array_keys($vocabularies))
  329. ->condition('t.name', '%' . db_like($tag_last) . '%', 'LIKE')
  330. ->range(0, $max_suggestions)
  331. ->execute()
  332. ->fetchAllKeyed();
  333. // Converting results into another format.
  334. foreach ($tags_return as $tid => $name) {
  335. $tags_return[$tid] = array('name' => $name);
  336. }
  337. $synonym_tids = array();
  338. // Now we go vocabulary by vocabulary looking through synonym fields.
  339. foreach ($vocabularies as $vocabulary) {
  340. // Now we go a synonym field by synonym field gathering suggestions.
  341. // Since officially EntityFieldQuery doesn't support OR conditions
  342. // we are enforced to go a field by field querying multiple times the DB.
  343. $bundle = field_extract_bundle('taxonomy_term', $vocabulary);
  344. foreach (synonyms_synonyms_fields($vocabulary) as $field) {
  345. $field = field_info_field($field);
  346. $instance = field_info_instance('taxonomy_term', $field['field_name'], $bundle);
  347. if (count($tags_return) + count($synonym_tids) > $max_suggestions) {
  348. // We have collected enough suggestions and the ongoing queries
  349. // will be just a waste of time.
  350. break;
  351. }
  352. $query = new EntityFieldQuery();
  353. $query->entityCondition('entity_type', 'taxonomy_term')
  354. ->entityCondition('bundle', $vocabulary->machine_name);
  355. // We let the class that defines this field type as a source of synonyms
  356. // filter our and provide its suggestions based on this field.
  357. $class = synonyms_extractor_info($field['type']);
  358. $class::processEntityFieldQuery($tag_last, $query, $field, $instance);
  359. if (!empty($tags_typed)) {
  360. $query->propertyCondition('name', $tags_typed, 'NOT IN');
  361. }
  362. if (!empty($tags_return)) {
  363. // We don't want to search among the terms already found by term name.
  364. $query->entityCondition('entity_id', array_keys($tags_return), 'NOT IN');
  365. }
  366. if (!empty($synonym_tids)) {
  367. // Nor we want to search among the terms already mached by previous
  368. // synonym fields.
  369. $query->entityCondition('entity_id', $synonym_tids, 'NOT IN');
  370. }
  371. $tmp = $query->execute();
  372. if (!empty($tmp)) {
  373. // Merging the results.
  374. $tmp = array_keys($tmp['taxonomy_term']);
  375. $synonym_tids = array_merge($synonym_tids, $tmp);
  376. }
  377. }
  378. }
  379. if (!empty($synonym_tids)) {
  380. $synonym_tids = array_slice($synonym_tids, 0, $max_suggestions - count($tags_return));
  381. foreach (taxonomy_term_load_multiple($synonym_tids) as $synonym_term) {
  382. $tags_return[$synonym_term->tid] = array('name' => $synonym_term->name);
  383. // Additionally we have to find out which synonym triggered inclusion
  384. // of this term.
  385. $synonyms = synonyms_get_term_synonyms($synonym_term);
  386. foreach ($synonyms as $item) {
  387. if (strpos(mb_strtoupper($item['value'], 'UTF-8'), mb_strtoupper($tag_last, 'UTF-8')) !== FALSE) {
  388. $tags_return[$synonym_term->tid]['synonym'] = $item['value'];
  389. break;
  390. }
  391. }
  392. }
  393. }
  394. $prefix = count($tags_typed) ? drupal_implode_tags($tags_typed) . ', ' : '';
  395. // Now formatting the results.
  396. foreach ($tags_return as $tid => $info) {
  397. $n = $info['name'];
  398. // Term names containing commas or quotes must be wrapped in quotes.
  399. if (strpos($info['name'], ',') !== FALSE || strpos($info['name'], '"') !== FALSE) {
  400. $n = '"' . str_replace('"', '""', $info['name']) . '"';
  401. }
  402. if (isset($info['synonym'])) {
  403. $display_name = t('@synonym, synonym of %term', array('@synonym' => $info['synonym'], '%term' => $info['name']));
  404. }
  405. else {
  406. $display_name = check_plain($info['name']);
  407. }
  408. $term_matches[$prefix . $n] = $display_name;
  409. }
  410. }
  411. drupal_json_output($term_matches);
  412. }
  413. /**
  414. * Try to find a term by its name or synonym.
  415. *
  416. * To maximize the match trimming and case-insensetive comparison is used.
  417. *
  418. * @param string $name
  419. * The string to be searched for its {taxonomy_term}.tid
  420. * @param object $vocabulary
  421. * Fully loaded vocabulary object in which you wish to search
  422. * @param int $parent
  423. * Optional. In case you want to narrow your search scope, this parameter
  424. * takes in the {taxonomy_term}.tid of the parent term, letting you search
  425. * only among its children
  426. *
  427. * @return int
  428. * If the look up was successfull returns the {taxonomy_term}.tid of the
  429. * found term, otherwise returns 0
  430. */
  431. function synonyms_get_term_by_synonym($name, $vocabulary, $parent = 0) {
  432. $name = mb_strtoupper(trim($name), 'UTF-8');
  433. $tree = taxonomy_get_tree($vocabulary->vid, $parent, NULL, TRUE);
  434. foreach ($tree as $term) {
  435. if (mb_strtoupper($term->name, 'UTF-8') == $name) {
  436. return $term->tid;
  437. }
  438. // We additionally scan through the synonyms.
  439. $synonyms = synonyms_get_term_synonyms($term);
  440. foreach ($synonyms as $item) {
  441. if (mb_strtoupper($item['safe_value'], 'UTF-8') == $name) {
  442. return $term->tid;
  443. }
  444. }
  445. }
  446. // If we have reached down here, this means we haven't got any match
  447. // as fallback we return 0.
  448. return 0;
  449. }
  450. /**
  451. * Look up a term considering synonyms and if nothing found add one.
  452. *
  453. * This function is useful for automated creation of new terms
  454. * as it won't generate the same terms over and over again.
  455. *
  456. * @param string $name
  457. * The string to be searched for its {taxonomy_term}.tid
  458. * @param object $vocabulary
  459. * Fully loaded vocabulary object in which you wish to search
  460. * @param int $parent
  461. * Optional. In case you want to narrow your search scope, this parameter
  462. * takes in the {taxonomy_term}.tid of the parent term, letting you search
  463. * only among its children
  464. *
  465. * @return int
  466. * If a term already exists, its {taxonomy_term}.tid is returned,
  467. * otherwise it creates a new term and returns its {taxonomy_term}.tid
  468. */
  469. function synonyms_add_term_by_synonym($name, $vocabulary, $parent = 0) {
  470. $tid = synonyms_get_term_by_synonym($name, $vocabulary, $parent);
  471. if ($tid) {
  472. // We found some term, returning its tid.
  473. return $tid;
  474. }
  475. // We haven't found any term, so we create one.
  476. $term = (object) array(
  477. 'name' => $name,
  478. 'vid' => $vocabulary->vid,
  479. 'parent' => array($parent),
  480. );
  481. taxonomy_term_save($term);
  482. if (isset($term->tid)) {
  483. return $term->tid;
  484. }
  485. // Normally we shouldn't reach up to here, because a term would have got
  486. // created and the just created tid would have been returned. Nevertheless,
  487. // as a fallback in case of any error we return 0.
  488. return 0;
  489. }
  490. /**
  491. * Public function for retrieving synonyms of a taxonomy term.
  492. *
  493. * @param object $term
  494. * Fully loaded taxonomy term for which the synonyms are desired
  495. *
  496. * @return array
  497. * Array of synonyms, if synonyms are disabled for the taxonomy term's
  498. * vocabulary, an empty array is returned. Each synonyms array consists of the
  499. * following keys:
  500. * value - the value of a synonym as it was input by user
  501. * safe_value - a sanitized value of a synonym
  502. */
  503. function synonyms_get_term_synonyms($term) {
  504. $synonyms = array();
  505. $vocabulary = taxonomy_vocabulary_load($term->vid);
  506. foreach (synonyms_synonyms_fields($vocabulary) as $field) {
  507. $bundle = field_extract_bundle('taxonomy_term', $vocabulary);
  508. $instance = field_info_instance('taxonomy_term', $field, $bundle);
  509. $field = field_info_field($field);
  510. $items = field_get_items('taxonomy_term', $term, $field['field_name']);
  511. if (is_array($items) && !empty($items)) {
  512. $class = synonyms_extractor_info($field['type']);
  513. $synonyms = array_merge($synonyms, $class::synonymsExtract($items, $field, $instance, $term, 'taxonomy_term'));
  514. }
  515. }
  516. // Applying sanitization to the extracted synonyms.
  517. foreach ($synonyms as $k => $v) {
  518. $synonyms[$k] = array(
  519. 'value' => $v,
  520. 'safe_value' => check_plain($v),
  521. );
  522. }
  523. return $synonyms;
  524. }
  525. /**
  526. * Allow to merge $synonym_entity as a synonym into $trunk_entity.
  527. *
  528. * Helpful function during various merging operations. It allows you to add a
  529. * synonym (where possible) into one entity, which will represent another entity
  530. * in the format expected by the field in which the synonym is being added.
  531. * Important note: if the cardinality limit of the field into which you are
  532. * adding synonym has been reached, calling to this function will take no
  533. * effect.
  534. *
  535. * @param object $trunk_entity
  536. * Fully loaded entity object in which the synonym is being added
  537. * @param string $trunk_entity_type
  538. * Entity type of $trunk_entity
  539. * @param string $field
  540. * Field name that should exist in $trunk_entity and be enabled as a synonym
  541. * source. Into this field synonym will be added
  542. * @param object $synonym_entity
  543. * Fully loaded entity object which will be added as a synonym
  544. * @param string $synonym_entity_type
  545. * Entity type of $synonym_entity
  546. *
  547. * @return bool
  548. * Whether synonym has been successfully added
  549. */
  550. function synonyms_add_entity_as_synonym($trunk_entity, $trunk_entity_type, $field, $synonym_entity, $synonym_entity_type) {
  551. if ($trunk_entity_type != 'taxonomy_term') {
  552. // Currently synonyms module only operates on taxonomy terms.
  553. return FALSE;
  554. }
  555. if (!in_array($field, synonyms_synonyms_fields(taxonomy_vocabulary_load($trunk_entity->vid)))) {
  556. // $field either doesn't exist in the $trunk_entity or it's not enabled as
  557. // a source of synonyms.
  558. return FALSE;
  559. }
  560. // Preparing arguments for calling a method of Extractor class.
  561. $field = field_info_field($field);
  562. $extractor = synonyms_extractor_info($field['type']);
  563. $items = field_get_items($trunk_entity_type, $trunk_entity, $field['field_name']);
  564. $items = is_array($items) ? $items : array();
  565. $trunk_entity_ids = entity_extract_ids($trunk_entity_type, $trunk_entity);
  566. $instance = field_info_instance($trunk_entity_type, $field['field_name'], $trunk_entity_ids[2]);
  567. $extra_items = $extractor::mergeEntityAsSynonym($items, $field, $instance, $synonym_entity, $synonym_entity_type);
  568. // Merging extracted synonym items into the values of the field that already
  569. // exist.
  570. // @todo: Currently we hardcode to LANGUAGE_NONE, but in future it would be
  571. // nice to have multilanguage support.
  572. $items = array_merge($items, $extra_items);
  573. $trunk_entity->{$field['field_name']}[LANGUAGE_NONE] = $items;
  574. // In future if this module eventually becomes a gateway for synonyms for any
  575. // entity types, we'll substitute it with entity_save().
  576. taxonomy_term_save($trunk_entity);
  577. return TRUE;
  578. }
  579. /**
  580. * Return array of field names that are sources of synonyms.
  581. *
  582. * Return array of field names that are currently enabled as source of
  583. * synonyms in the supplied vocabulary.
  584. *
  585. * @param object $vocabulary
  586. * Fully loaded taxonomy vocabulary object
  587. *
  588. * @return array
  589. * Array of field names
  590. */
  591. function synonyms_synonyms_fields($vocabulary) {
  592. $settings = synonyms_vocabulary_settings($vocabulary);
  593. if (!isset($settings['synonyms']) || !is_array($settings['synonyms'])) {
  594. // Wierd as normally we expect to see here at least an empty array but
  595. // no problem. We simply initialize it.
  596. $settings['synonyms'] = array();
  597. }
  598. // It's not just as easy as pulling up already saved value. After this
  599. // we have to make sure that all the fields are still present and have not
  600. // been deleted from the vocabulary.
  601. $bundle = field_extract_bundle('taxonomy_term', $vocabulary);
  602. $instances = field_info_instances('taxonomy_term', $bundle);
  603. $settings['synonyms'] = array_intersect($settings['synonyms'], array_keys($instances));
  604. return $settings['synonyms'];
  605. }
  606. /**
  607. * Enforce the setting "synonyms".
  608. *
  609. * @param object $vocabulary
  610. * Fully loaded entity of a taxonomy vocabulary
  611. * @param array $fields
  612. * Array of fields that are enabled as a source of synonyms
  613. */
  614. function synonyms_synonyms_enforce($vocabulary, $fields) {
  615. $bundle = field_extract_bundle('taxonomy_term', $vocabulary);
  616. // Normally all the fields already exist, we just need to assure that
  617. // default synonyms field exists if it is enabled as a source of synonyms.
  618. // Otherwise we make sure we delete instance of the default field in the
  619. // vocabulary.
  620. $instance = field_info_instance('taxonomy_term', SYNONYMS_DEFAULT_FIELD_NAME, $bundle);
  621. if (in_array(SYNONYMS_DEFAULT_FIELD_NAME, $fields)) {
  622. if (is_null($instance)) {
  623. // Make sure the field exists.
  624. synonyms_default_field_ensure();
  625. field_create_instance(array(
  626. 'field_name' => SYNONYMS_DEFAULT_FIELD_NAME,
  627. 'entity_type' => 'taxonomy_term',
  628. 'bundle' => $bundle,
  629. 'label' => t('Synonyms'),
  630. 'description' => t('Please, enter the synonyms which should be related to this term.'),
  631. ));
  632. }
  633. }
  634. elseif (!is_null($instance)) {
  635. // Deleting the instance, we will delete the field separately when the
  636. // module gets uninstalled.
  637. field_delete_instance($instance, FALSE);
  638. }
  639. }
  640. /**
  641. * Return the current settings for the supplied $vocabulary.
  642. *
  643. * @param object $vocabulary
  644. * Fully loaded entity of a taxonomy vocabulary
  645. *
  646. * @return array
  647. * Array of current synonyms settings for the supplied vocabulary.
  648. * Should include the following keys:
  649. * synonyms - array of field names that are enabled as source of synonyms
  650. */
  651. function synonyms_vocabulary_settings($vocabulary) {
  652. $settings = array();
  653. if (isset($vocabulary->vid)) {
  654. $settings = variable_get('synonyms_settings_' . $vocabulary->vid, array());
  655. }
  656. return $settings;
  657. }
  658. /**
  659. * Save the current settings for the supplied $vocabulary.
  660. *
  661. * @param object $vocabulary
  662. * Fully loaded entity of a taxonomy vocabulary
  663. * @param array $settings
  664. * Settings the have to be stored. The structure of this array has to be
  665. * identical to the output array of the function
  666. * synonyms_vocabulary_settings()
  667. */
  668. function synonyms_vocabulary_settings_save($vocabulary, $settings) {
  669. variable_set('synonyms_settings_' . $vocabulary->vid, $settings);
  670. // Now enforcing each setting.
  671. foreach ($settings as $k => $v) {
  672. switch ($k) {
  673. case 'synonyms':
  674. synonyms_synonyms_enforce($vocabulary, $v);
  675. break;
  676. }
  677. }
  678. }
  679. /**
  680. * Make sure the default synonyms field exists.
  681. *
  682. * If the field doesn't exist function creates one, if the field exists,
  683. * the function does nothing.
  684. */
  685. function synonyms_default_field_ensure() {
  686. $field = field_info_field(SYNONYMS_DEFAULT_FIELD_NAME);
  687. if (is_null($field)) {
  688. $field = array(
  689. 'field_name' => SYNONYMS_DEFAULT_FIELD_NAME,
  690. 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
  691. 'locked' => TRUE,
  692. 'type' => 'text',
  693. );
  694. field_create_field($field);
  695. }
  696. }
  697. /**
  698. * Extract instances that are applicapable for being source of synonyms.
  699. *
  700. * Walk through all instances of a vocabulary and extract only valid candidates
  701. * for becoming a source of synonyms for the vocabulary terms.
  702. *
  703. * @param object $vocabulary
  704. * Fully loaded vocabulary object
  705. *
  706. * @return array
  707. * Array of instance arrays
  708. */
  709. function synonyms_instances_extract_applicapable($vocabulary) {
  710. $applicapable_field_types = array_keys(synonyms_extractor_info());
  711. $applicapable = array();
  712. $bundle = field_extract_bundle('taxonomy_term', $vocabulary);
  713. foreach (field_info_instances('taxonomy_term', $bundle) as $instance) {
  714. $field = field_info_field($instance['field_name']);
  715. if (in_array($field['type'], $applicapable_field_types)) {
  716. $applicapable[] = $instance;
  717. }
  718. }
  719. return $applicapable;
  720. }