synonyms.module 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  1. <?php
  2. /**
  3. * @file
  4. * Provide synonyms feature for Drupal Taxonomy.
  5. */
  6. /**
  7. * Implements hook_menu().
  8. */
  9. function synonyms_menu() {
  10. $items = array();
  11. $items['synonyms/autocomplete/%/%/%'] = array(
  12. 'title' => 'Autocomplete Synonyms',
  13. 'page callback' => 'synonyms_autocomplete',
  14. 'page arguments' => array(2, 3, 4),
  15. 'access arguments' => array('access content'),
  16. 'file' => 'synonyms.pages.inc',
  17. 'type' => MENU_CALLBACK,
  18. );
  19. return $items;
  20. }
  21. /**
  22. * Implements hook_ctools_plugin_type().
  23. */
  24. function synonyms_ctools_plugin_type() {
  25. $plugins = array();
  26. $plugins['behavior'] = array(
  27. 'defaults' => array(
  28. 'title' => NULL,
  29. 'description' => NULL,
  30. 'settings form callback' => NULL,
  31. 'interface' => NULL,
  32. 'enabled callback' => NULL,
  33. 'disabled callback' => NULL,
  34. ),
  35. );
  36. return $plugins;
  37. }
  38. /**
  39. * Implements hook_ctools_plugin_directory().
  40. */
  41. function synonyms_ctools_plugin_directory($owner, $plugin_type) {
  42. switch ($owner) {
  43. case 'synonyms':
  44. switch ($plugin_type) {
  45. case 'behavior':
  46. return 'plugins/' . $plugin_type;
  47. }
  48. break;
  49. case 'ctools':
  50. switch ($plugin_type) {
  51. case 'arguments':
  52. return 'plugins/' . $plugin_type;
  53. }
  54. break;
  55. }
  56. }
  57. /**
  58. * Implements hook_theme().
  59. */
  60. function synonyms_theme() {
  61. return array(
  62. 'synonyms_behaviors_settings' => array(
  63. 'render element' => 'element',
  64. 'file' => 'synonyms.pages.inc',
  65. ),
  66. );
  67. }
  68. /**
  69. * Implements hook_entity_property_info().
  70. */
  71. function synonyms_entity_property_info() {
  72. $info = array();
  73. $properties = &$info['taxonomy_term']['properties'];
  74. $properties['synonyms'] = array(
  75. 'label' => t('Synonyms'),
  76. 'description' => t('Synonyms of entity.'),
  77. 'type' => 'list<text>',
  78. 'getter callback' => 'synonyms_get_sanitized',
  79. 'computed' => TRUE,
  80. 'sanitized' => TRUE,
  81. 'raw getter callback' => 'synonyms_get_raw',
  82. );
  83. return $info;
  84. }
  85. /**
  86. * Implements hook_field_delete_instance().
  87. */
  88. function synonyms_field_delete_instance($instance) {
  89. // Remove, if necessary, any synonyms behaviors enabled on this instance.
  90. $result = db_select('synonyms_settings', 's')
  91. ->fields('s', array('behavior'))
  92. ->condition('s.instance_id', $instance['id'])
  93. ->execute();
  94. foreach ($result as $row) {
  95. synonyms_behavior_settings_delete($instance['id'], $row->behavior);
  96. }
  97. }
  98. /**
  99. * Implements hook_synonyms_behavior_implementation_info().
  100. */
  101. function synonyms_synonyms_behavior_implementation_info($behavior) {
  102. switch ($behavior) {
  103. case 'autocomplete':
  104. case 'select':
  105. case 'synonyms':
  106. return array(
  107. 'number_integer' => 'TextSynonymsBehavior',
  108. 'number_decimal' => 'TextSynonymsBehavior',
  109. 'number_float' => 'TextSynonymsBehavior',
  110. 'text' => 'TextSynonymsBehavior',
  111. 'taxonomy_term_reference' => 'TaxonomySynonymsBehavior',
  112. 'entityreference' => 'EntityReferenceSynonymsBehavior',
  113. );
  114. break;
  115. }
  116. return array();
  117. }
  118. /**
  119. * Implements hook_form_FORM_ID_alter().
  120. */
  121. function synonyms_form_taxonomy_form_vocabulary_alter(&$form, &$form_state) {
  122. if (isset($form_state['confirm_delete']) && $form_state['confirm_delete']) {
  123. return;
  124. }
  125. if (!isset($form['#vocabulary']->vid) || !$form['#vocabulary']->vid) {
  126. return;
  127. }
  128. $form['synonyms'] = array(
  129. '#type' => 'fieldset',
  130. '#title' => t('Synonyms'),
  131. '#collapsible' => TRUE,
  132. '#tree' => TRUE,
  133. );
  134. $behaviors = synonyms_behaviors();
  135. $bundle = field_extract_bundle('taxonomy_term', $form['#vocabulary']);
  136. $form['synonyms']['behaviors'] = array(
  137. '#theme' => 'synonyms_behaviors_settings',
  138. '#id' => 'synonyms-behaviors-settings-wrapper',
  139. );
  140. foreach ($behaviors as $behavior => $behavior_info) {
  141. $form['synonyms']['behaviors'][$behavior] = array(
  142. '#title' => $behavior_info['title'],
  143. );
  144. $behavior_implementations = synonyms_behavior_get($behavior, 'taxonomy_term', $bundle);
  145. foreach ($behavior_implementations as $implementation) {
  146. $instance = field_info_instance($implementation['entity_type'], $implementation['field_name'], $implementation['bundle']);
  147. $form['synonyms']['behaviors'][$behavior][$implementation['instance_id']]['#title'] = $instance['label'];
  148. if (isset($form_state['values']['synonyms']['behaviors'][$behavior][$implementation['instance_id']])) {
  149. $behavior_settings = (bool) $form_state['values']['synonyms']['behaviors'][$behavior][$implementation['instance_id']]['enabled'];
  150. }
  151. else {
  152. $behavior_settings = !is_null($implementation['settings']);
  153. }
  154. if ($behavior_settings) {
  155. if (isset($form_state['values']['synonyms']['behaviors'][$behavior][$implementation['instance_id']]['settings'])) {
  156. $behavior_settings = $form_state['values']['synonyms']['behaviors'][$behavior][$implementation['instance_id']]['settings'];
  157. }
  158. elseif ($implementation['settings']) {
  159. $behavior_settings = $implementation['settings'];
  160. }
  161. else {
  162. $behavior_settings = array();
  163. }
  164. }
  165. $form['synonyms']['behaviors'][$behavior][$implementation['instance_id']]['enabled'] = array(
  166. '#type' => 'checkbox',
  167. '#title' => t('Enable'),
  168. '#default_value' => $behavior_settings !== FALSE,
  169. );
  170. $settings_form = ctools_plugin_get_function($behavior_info, 'settings form callback');
  171. if ($settings_form) {
  172. $form['synonyms']['behaviors'][$behavior][$implementation['instance_id']]['enabled']['#ajax'] = array(
  173. 'callback' => 'synonyms_behaviors_settings_form_ajax',
  174. 'wrapper' => $form['synonyms']['behaviors']['#id'],
  175. );
  176. if ($behavior_settings !== FALSE) {
  177. $form['synonyms']['behaviors'][$behavior][$implementation['instance_id']]['settings'] = $settings_form($form, $form_state, $behavior_settings);
  178. }
  179. }
  180. }
  181. }
  182. $form['#submit'][] = 'synonyms_taxonomy_form_vocabulary_submit';
  183. }
  184. /**
  185. * Submit handler for Taxonomy vocabulary edit form.
  186. *
  187. * Store synonyms behavior settings.
  188. */
  189. function synonyms_taxonomy_form_vocabulary_submit($form, &$form_state) {
  190. $values = $form_state['values'];
  191. if ($values['op'] == $form['actions']['submit']['#value']) {
  192. foreach ($values['synonyms']['behaviors'] as $behavior => $settings) {
  193. foreach ($settings as $instance_id => $behavior_settings) {
  194. if ($behavior_settings['enabled']) {
  195. synonyms_behavior_settings_save(array(
  196. 'instance_id' => $instance_id,
  197. 'behavior' => $behavior,
  198. 'settings' => isset($behavior_settings['settings']) ? $behavior_settings['settings'] : NULL,
  199. ));
  200. }
  201. else {
  202. synonyms_behavior_settings_delete($instance_id, $behavior);
  203. }
  204. }
  205. }
  206. }
  207. }
  208. /**
  209. * Ajax callback function for synonyms behavior settings form.
  210. */
  211. function synonyms_behaviors_settings_form_ajax($form, &$form_state) {
  212. return $form['synonyms']['behaviors'];
  213. }
  214. /**
  215. * Implements hook_field_widget_info().
  216. */
  217. function synonyms_field_widget_info() {
  218. return array(
  219. 'synonyms_autocomplete' => array(
  220. 'label' => t('Synonyms friendly autocomplete term widget'),
  221. 'field types' => array('taxonomy_term_reference'),
  222. 'settings' => array(
  223. 'size' => 60,
  224. 'synonyms_autocomplete_path' => 'synonyms/autocomplete',
  225. 'suggestion_size' => 10,
  226. 'suggest_only_unique' => FALSE,
  227. 'auto_creation' => 1,
  228. ),
  229. 'behaviors' => array(
  230. 'multiple values' => FIELD_BEHAVIOR_CUSTOM,
  231. ),
  232. ),
  233. 'synonyms_select' => array(
  234. 'label' => t('Synonyms friendly select list'),
  235. 'field types' => array('taxonomy_term_reference'),
  236. 'settings' => array(
  237. 'sort' => 'weight',
  238. ),
  239. 'behaviors' => array(
  240. 'multiple values' => FIELD_BEHAVIOR_CUSTOM,
  241. ),
  242. ),
  243. );
  244. }
  245. /**
  246. * Implements hook_field_widget_settings_form().
  247. */
  248. function synonyms_field_widget_settings_form($field, $instance) {
  249. $widget = $instance['widget'];
  250. $settings = $widget['settings'] + field_info_widget_settings($widget['type']);
  251. $form = array();
  252. switch ($widget['type']) {
  253. case 'synonyms_autocomplete':
  254. $form['auto_creation'] = array(
  255. '#type' => 'checkbox',
  256. '#title' => t('Allow auto-creation?'),
  257. '#description' => t('Whether users may create a new term by typing in a non-existing name into this field.'),
  258. '#default_value' => $settings['auto_creation'],
  259. );
  260. $form['suggestion_size'] = array(
  261. '#type' => 'textfield',
  262. '#title' => t('Suggestions Size'),
  263. '#description' => t('Please, enter how many suggested entities to show in the autocomplete textfield.'),
  264. '#required' => TRUE,
  265. '#element_validate' => array('element_validate_integer_positive'),
  266. '#default_value' => $settings['suggestion_size'],
  267. );
  268. $form['suggest_only_unique'] = array(
  269. '#type' => 'checkbox',
  270. '#title' => t('Suggest only one entry per term'),
  271. '#description' => t('If you want to include only term name or a single synonym, suggesting a particular term, while disregarding all ongoing ones, please, tick this checkbox on.'),
  272. '#default_value' => $settings['suggest_only_unique'],
  273. );
  274. break;
  275. case 'synonyms_select':
  276. $form['sort'] = array(
  277. '#type' => 'radios',
  278. '#title' => t('Sort'),
  279. '#description' => t('Choose by what criterion the items within select should be sorted.'),
  280. '#options' => array(
  281. 'weight' => t('As in taxonomy vocabulary (by weight)'),
  282. 'name' => t('By name of terms and their synonyms'),
  283. ),
  284. '#default_value' => $settings['sort'],
  285. );
  286. break;
  287. }
  288. return $form;
  289. }
  290. /**
  291. * Implements hook_field_widget_form().
  292. */
  293. function synonyms_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  294. $default_value = array();
  295. foreach ($items as $item) {
  296. $default_value[] = $item['tid'];
  297. }
  298. switch ($instance['widget']['type']) {
  299. case 'synonyms_autocomplete':
  300. $tags = taxonomy_term_load_multiple($default_value);
  301. $element += array(
  302. '#type' => 'textfield',
  303. '#default_value' => taxonomy_implode_tags($tags),
  304. '#autocomplete_path' => $instance['widget']['settings']['synonyms_autocomplete_path'] . '/' . $field['field_name'] . '/' . $instance['entity_type'] . '/' . $instance['bundle'],
  305. '#size' => $instance['widget']['settings']['size'],
  306. '#maxlength' => 1024,
  307. '#element_validate' => array('taxonomy_autocomplete_validate', 'synonyms_autocomplete_validate'),
  308. '#auto_creation' => $instance['widget']['settings']['auto_creation'],
  309. '#attached' => array(
  310. 'js' => array(
  311. drupal_get_path('module', 'synonyms') . '/js/synonyms-autocomplete.js' => array(),
  312. ),
  313. ),
  314. '#attributes' => array(
  315. 'class' => array('synonyms-autocomplete'),
  316. ),
  317. );
  318. break;
  319. case 'synonyms_select':
  320. $multiple = $field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED;
  321. $options = array();
  322. foreach ($field['settings']['allowed_values'] as $tree) {
  323. if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
  324. switch ($instance['widget']['settings']['sort']) {
  325. case 'weight':
  326. if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'], NULL, TRUE)) {
  327. $behavior_implementations = synonyms_behavior_get('select', 'taxonomy_term', field_extract_bundle('taxonomy_term', $vocabulary), TRUE);
  328. foreach ($terms as $term) {
  329. $options[] = synonyms_select_option($term);
  330. foreach ($behavior_implementations as $implementation) {
  331. foreach (synonyms_extract_synonyms($term, $implementation) as $synonym) {
  332. $options[] = synonyms_select_option($term, $synonym, $implementation);
  333. }
  334. }
  335. }
  336. }
  337. break;
  338. case 'name':
  339. // TODO: is there any way to leverage DB for the sorting routine?
  340. $options = synonyms_select_sort_name_options_recursive($vocabulary, $tree['parent']);
  341. break;
  342. }
  343. }
  344. }
  345. if (!$multiple && !$element['#required']) {
  346. $options = array('' => t('- None -')) + $options;
  347. }
  348. $element += array(
  349. '#type' => 'select',
  350. '#multiple' => $multiple,
  351. '#options' => $options,
  352. '#default_value' => $default_value,
  353. '#element_validate' => array('synonyms_select_form_to_storage'),
  354. );
  355. break;
  356. }
  357. return $element;
  358. }
  359. /**
  360. * Implements hook_field_widget_error().
  361. */
  362. function synonyms_field_widget_error($element, $error, $form, &$form_state) {
  363. form_error($element, $error['message']);
  364. }
  365. /**
  366. * Form element validate handler.
  367. *
  368. * Handle validation for taxonomy term synonym-friendly autocomplete element.
  369. */
  370. function synonyms_autocomplete_validate($element, &$form_state) {
  371. // After taxonomy_autocomplete_validate() has finished its job any terms it
  372. // didn't find have been set for autocreation. We need to:
  373. // (a) Double-check that those terms are not synonyms.
  374. // (b) Check that synonyms' configurable auto-creation option is enabled.
  375. $value = drupal_array_get_nested_value($form_state['values'], $element['#parents']);
  376. $field = field_widget_field($element, $form_state);
  377. foreach ($value as $delta => $term) {
  378. if ($term['tid'] == 'autocreate') {
  379. $synonym_tid = 0;
  380. foreach ($field['settings']['allowed_values'] as $tree) {
  381. $behavior_implementations = synonyms_behavior_get('autocomplete', 'taxonomy_term', $tree['vocabulary'], TRUE);
  382. foreach ($behavior_implementations as $behavior_implementation) {
  383. $synonyms = synonyms_synonyms_find_behavior(db_and()->condition(AbstractSynonymsSynonymsBehavior::COLUMN_PLACEHOLDER, $term['name']), $behavior_implementation);
  384. foreach ($synonyms as $synonym) {
  385. $synonym_tid = $synonym->entity_id;
  386. break(2);
  387. }
  388. }
  389. }
  390. if ($synonym_tid != 0) {
  391. $value[$delta]['tid'] = $synonym_tid;
  392. }
  393. elseif (!$element['#auto_creation']) {
  394. unset($value[$delta]);
  395. }
  396. }
  397. }
  398. $value = array_values($value);
  399. form_set_value($element, $value, $form_state);
  400. }
  401. /**
  402. * Try to find a term by its name or synonym.
  403. *
  404. * @param string $name
  405. * The string to be searched for its {taxonomy_term_data}.tid
  406. * @param object $vocabulary
  407. * Fully loaded vocabulary object in which you wish to search
  408. * @param int $parent
  409. * Optional. In case you want to narrow your search scope, this parameter
  410. * takes in the {taxonomy_term_data}.tid of the parent term, letting you
  411. * search only among its children
  412. *
  413. * @return int
  414. * If the look up was successful returns the {taxonomy_term_data}.tid of the
  415. * found term, otherwise returns 0
  416. */
  417. function synonyms_get_term_by_synonym($name, $vocabulary, $parent = 0) {
  418. $name = trim($name);
  419. $terms = taxonomy_get_term_by_name($name, $vocabulary->machine_name);
  420. foreach ($terms as $term) {
  421. if (!$parent || synonyms_taxonomy_term_is_child_of($term->tid, $parent)) {
  422. // TODO: actually it could be so that there is more than 1 term that
  423. // satisfies the search query, i.e. the name and parent constraints. At
  424. // the moment we are going to return the first one we encounter, though
  425. // something better could be thought of in the future.
  426. return $term->tid;
  427. }
  428. }
  429. // We have failed to find a term with the provided $name. So let's search now
  430. // among the term synonyms.
  431. $bundle = field_extract_bundle('taxonomy_term', $vocabulary);
  432. $synonyms = synonyms_synonyms_find(db_and()->condition(AbstractSynonymsSynonymsBehavior::COLUMN_PLACEHOLDER, $name), 'taxonomy_term', $bundle);
  433. foreach ($synonyms as $synonym) {
  434. if (!$parent || synonyms_taxonomy_term_is_child_of($synonym->entity_id, $parent)) {
  435. // TODO: similarly here, as above, we could have more than 1 match, but
  436. // for now we will simply return the first one encountered.
  437. return $synonym->entity_id;
  438. }
  439. }
  440. // If we have reached down here, this means we haven't got any match
  441. // as fallback we return 0.
  442. return 0;
  443. }
  444. /**
  445. * Look up a term considering synonyms and if nothing is found add one.
  446. *
  447. * This function is useful for automated creation of new terms as it won't
  448. * generate the same terms over and over again.
  449. *
  450. * @param string $name
  451. * The string to be searched for its {taxonomy_term_data}.tid
  452. * @param object $vocabulary
  453. * Fully loaded vocabulary object in which you wish to search
  454. * @param int $parent
  455. * Optional. In case you want to narrow your search scope, this parameter
  456. * takes in the {taxonomy_term_data}.tid of the parent term, letting you
  457. * search only among its children
  458. *
  459. * @return int
  460. * If a term already exists, its {taxonomy_term_data}.tid is returned,
  461. * otherwise it creates a new term and returns its {taxonomy_term_data}.tid
  462. */
  463. function synonyms_add_term_by_synonym($name, $vocabulary, $parent = 0) {
  464. $tid = synonyms_get_term_by_synonym($name, $vocabulary, $parent);
  465. if ($tid) {
  466. // We found some term, returning its tid.
  467. return $tid;
  468. }
  469. // We haven't found any term, so we create one.
  470. $term = (object) array(
  471. 'name' => $name,
  472. 'vid' => $vocabulary->vid,
  473. 'parent' => array($parent),
  474. );
  475. taxonomy_term_save($term);
  476. if (isset($term->tid)) {
  477. return $term->tid;
  478. }
  479. // Normally we shouldn't reach up to here, because a term would have got
  480. // created and the just created tid would have been returned. Nevertheless,
  481. // as a fallback in case of any error we return 0.
  482. return 0;
  483. }
  484. /**
  485. * Retrieve a list of sanitized synonyms of a taxonomy term.
  486. *
  487. * @param $item object
  488. * Fully loaded taxonomy term
  489. *
  490. * @return array
  491. * List of sanitized synonyms of a taxonomy term
  492. */
  493. function synonyms_get_sanitized($item) {
  494. $synonyms = array();
  495. foreach (synonyms_get_term_synonyms($item) as $synonym) {
  496. $synonyms[] = $synonym['safe_value'];
  497. }
  498. return $synonyms;
  499. }
  500. /**
  501. * Retrieve a list of raw synonyms of a taxonomy term.
  502. *
  503. * @param $item object
  504. * Fully loaded taxonomy term
  505. *
  506. * @return array
  507. * List of raw synonyms of a taxonomy term
  508. */
  509. function synonyms_get_raw($item) {
  510. $synonyms = array();
  511. foreach (synonyms_get_term_synonyms($item) as $synonym) {
  512. $synonyms[] = $synonym['value'];
  513. }
  514. return $synonyms;
  515. }
  516. /**
  517. * Public function for retrieving synonyms of a taxonomy term.
  518. *
  519. * You are encouraged to use synonyms_get_sanitized() or synonyms_get_raw()
  520. * instead. This function soon will be removed from the source code.
  521. *
  522. * @param object $term
  523. * Fully loaded taxonomy term for which the synonyms are desired
  524. *
  525. * @return array
  526. * Array of synonyms, if synonyms are disabled for the taxonomy term's
  527. * vocabulary, an empty array is returned. Each synonym subarray consists of
  528. * the following keys:
  529. * - value: (string) the value of a synonym as it was input by user
  530. * - safe_value: (string) a sanitized value of a synonym
  531. *
  532. * @deprecated
  533. */
  534. function synonyms_get_term_synonyms($term) {
  535. $synonyms = array();
  536. $vocabulary = taxonomy_vocabulary_load($term->vid);
  537. $bundle = field_extract_bundle('taxonomy_term', $vocabulary);
  538. $behavior_implementations = synonyms_behavior_get('synonyms', 'taxonomy_term', $bundle, TRUE);
  539. foreach ($behavior_implementations as $implementation) {
  540. foreach (synonyms_extract_synonyms($term, $implementation) as $synonym) {
  541. $synonyms[] = array(
  542. 'value' => $synonym,
  543. 'safe_value' => check_plain($synonym),
  544. );
  545. }
  546. }
  547. return $synonyms;
  548. }
  549. /**
  550. * Extract synonyms of an entity within a certain field and behavior.
  551. *
  552. * Do not use this function, if you want to get synonyms of an entity, unless
  553. * you know what you are doing. This function extracts the synonyms from a field
  554. * that is specified by $behavior_implementation parameter. The behavior may not
  555. * necessarily be of 'synonyms' type, so it's not 100% valid to say that the
  556. * entity has the returned array as its synonyms. However, this function is very
  557. * useful for behaviors that "extend" the basic synonyms behavior.
  558. *
  559. * @param object $entity
  560. * Fully loaded entity, synonyms from which should be extracted
  561. * @param array $behavior_implementation
  562. * Fully loaded behavior implementation. Supply here one of the values from
  563. * the return of synonyms_behavior_get() function
  564. *
  565. * @return array
  566. * Array of synonyms that reside in the field dictated by
  567. * $behavior_implementation parameter
  568. */
  569. function synonyms_extract_synonyms($entity, $behavior_implementation) {
  570. $synonyms = array();
  571. $field = field_info_field($behavior_implementation['field_name']);
  572. $instance = field_info_instance($behavior_implementation['entity_type'], $behavior_implementation['field_name'], $behavior_implementation['bundle']);
  573. $items = field_get_items($behavior_implementation['entity_type'], $entity, $field['field_name']);
  574. if (is_array($items) && !empty($items)) {
  575. $object = synonyms_behavior_implementation_class($behavior_implementation['behavior'], $field);
  576. $object = new $object();
  577. $synonyms = array_merge($synonyms, $object->extractSynonyms($items, $field, $instance, $entity, $behavior_implementation['entity_type']));
  578. }
  579. return $synonyms;
  580. }
  581. /**
  582. * Look up entities by their synonyms.
  583. *
  584. * @param QueryConditionInterface $condition
  585. * Object of QueryConditionInterface that specifies conditions by which you
  586. * want to find synonyms. When building this condition object, use
  587. * AbstractSynonymsSynonymsBehavior::COLUMN_PLACEHOLDER as a placeholder for
  588. * real column name that contains synonym as text. For example, if you were to
  589. * find all entities with synonyms that begin with "synonym-come-here"
  590. * substring, case insensitive and replacing all spaces in original synonym
  591. * string by a dash sign, then you would have to create the following
  592. * condition object:
  593. * db_and()
  594. * ->where("LOWER(REPLACE(" . AbstractSynonymsSynonymsBehavior::COLUMN_PLACEHOLDER . ", ' ', '-')) LIKE 'synonym-come-here%'")
  595. * And then just supply this object as an input parameter to this function
  596. * @param string $entity_type
  597. * Among synonyms of what entity type to search
  598. * @param string $bundle
  599. * Among synonyms of what bundle to search
  600. *
  601. * @return array
  602. * Array of found synonyms and entity IDs to which those belong. Each element
  603. * in the array will be an object and will have the following structure:
  604. * - synonym: (string) Synonym that was found and which satisfies the
  605. * $condition you specified
  606. * - entity_id: (int) ID of the entity to which the found synonym belongs
  607. */
  608. function synonyms_synonyms_find(QueryConditionInterface $condition, $entity_type, $bundle) {
  609. $rows = array();
  610. $behavior_implementations = synonyms_behavior_get('synonyms', $entity_type, $bundle, TRUE);
  611. foreach ($behavior_implementations as $behavior_implementation) {
  612. foreach (synonyms_synonyms_find_behavior($condition, $behavior_implementation) as $row) {
  613. $rows[] = $row;
  614. }
  615. }
  616. return $rows;
  617. }
  618. /**
  619. * Find entities with a provided synonym within certain behavior implementation.
  620. *
  621. * Do not use this function, if you want to find entities that have specific
  622. * synonyms, unless you know what you are doing. This function searches for the
  623. * entities with synonyms from a field that is specified by
  624. * $behavior_implementation parameter. The behavior may not necessarily be of
  625. * 'synonyms' type, so it's not 100% valid to say that the returned entities
  626. * have the specified synonyms. However, this function is very useful for
  627. * behaviors that "extend" the basic synonyms behavior.
  628. *
  629. * You have full SQL flexibility to specify parameters of how to search for
  630. * synonyms. You can create arbitrary set of SQL conditions that will be plugged
  631. * into specific SELECT queries by behavior implementations.
  632. *
  633. * @param QueryConditionInterface $condition
  634. * Object of QueryConditionInterface that specifies conditions by which you
  635. * want to find synonyms. When building this condition object, use
  636. * AbstractSynonymsSynonymsBehavior::COLUMN_PLACEHOLDER as a placeholder for
  637. * real column name that contains synonym as text. For example, if you were to
  638. * find all entities with synonyms that begin with "synonym-come-here"
  639. * substring, case insensitive and replacing all spaces in original synonym
  640. * string by a dash sign, then you would have to create the following
  641. * condition object:
  642. * db_and()
  643. * ->where("LOWER(REPLACE(" . AbstractSynonymsSynonymsBehavior::COLUMN_PLACEHOLDER . ", ' ', '-')) LIKE 'synonym-come-here%'")
  644. * And then just supply this object as an input parameter to this function
  645. * @param array $behavior_implementation
  646. * Fully loaded behavior implementation. Supply here one of the values from
  647. * the return of synonyms_behavior_get() function
  648. *
  649. * @return Traversable
  650. * Traversable result set of found synonyms and entity IDs to which those
  651. * belong. Each element in the result set will be an object and will have the
  652. * following structure:
  653. * - synonym: (string) Synonym that was found and which satisfies the
  654. * $condition you specified
  655. * - entity_id: (int) ID of the entity to which the found synonym belongs
  656. */
  657. function synonyms_synonyms_find_behavior(QueryConditionInterface $condition, $behavior_implementation) {
  658. $field = field_info_field($behavior_implementation['field_name']);
  659. $instance = field_info_instance($behavior_implementation['entity_type'], $behavior_implementation['field_name'], $behavior_implementation['bundle']);
  660. $object = synonyms_behavior_implementation_class($behavior_implementation['behavior'], $field);
  661. $object = new $object();
  662. return $object->synonymsFind($condition, $field, $instance);
  663. }
  664. /**
  665. * Allow to merge $synonym_entity as a synonym into $trunk_entity.
  666. *
  667. * Helpful function during various merging operations. It allows you to add a
  668. * synonym (where possible) into one entity, which will represent another entity
  669. * in the format expected by the field in which the synonym is being added.
  670. * Important note: if the cardinality limit of the field into which you are
  671. * adding synonym has been reached, calling to this function will take no
  672. * effect.
  673. *
  674. * @param object $trunk_entity
  675. * Fully loaded entity object in which the synonym is being added
  676. * @param string $trunk_entity_type
  677. * Entity type of $trunk_entity
  678. * @param string $field
  679. * Field name that should exist in $trunk_entity and have enabled the
  680. * "synonyms" behavior. Into this field synonym will be added
  681. * @param object $synonym_entity
  682. * Fully loaded entity object which will be added as a synonym
  683. * @param string $synonym_entity_type
  684. * Entity type of $synonym_entity
  685. *
  686. * @return bool
  687. * Whether synonym has been successfully added
  688. */
  689. function synonyms_add_entity_as_synonym($trunk_entity, $trunk_entity_type, $field, $synonym_entity, $synonym_entity_type) {
  690. if ($trunk_entity_type != 'taxonomy_term') {
  691. // Currently synonyms module only operates on taxonomy terms.
  692. return FALSE;
  693. }
  694. $bundle = entity_extract_ids($trunk_entity_type, $trunk_entity);
  695. $bundle = $bundle[2];
  696. $behavior_implementations = synonyms_behavior_get('synonyms', $trunk_entity_type, $bundle, TRUE);
  697. $field = field_info_field($field);
  698. $instance = field_info_instance($trunk_entity_type, $field['field_name'], $bundle);
  699. if (!isset($behavior_implementations[$instance['id']])) {
  700. // $field either doesn't exist in the $trunk_entity or it does not have
  701. // enabled the behavior of synonyms.
  702. return FALSE;
  703. }
  704. $items = field_get_items($trunk_entity_type, $trunk_entity, $field['field_name']);
  705. $items = is_array($items) ? $items : array();
  706. $object = synonyms_behavior_implementation_class('synonyms', $field);
  707. $object = new $object();
  708. $extra_items = $object->mergeEntityAsSynonym($items, $field, $instance, $synonym_entity, $synonym_entity_type);
  709. if (empty($extra_items)) {
  710. // For some reason the behavior implementation couldn't merge it. Otherwise
  711. // it would have not returned an empty array.
  712. return FALSE;
  713. }
  714. // Merging extracted synonym items into the values of the field that already
  715. // exist.
  716. // @todo: Currently we hardcode to LANGUAGE_NONE, but in future it would be
  717. // nice to have multilanguage support.
  718. $items = array_merge($items, $extra_items);
  719. // Now we want to keep only unique values of the $items. Since we know nothing
  720. // about what determines uniqueness of an item, we will ask the synonym
  721. // behavior to hash each of them and then will compare hashes.
  722. $unique_items = array();
  723. foreach ($items as $item) {
  724. $unique_items[$object->synonymItemHash($item, $field, $instance)] = $item;
  725. }
  726. $items = array_values($unique_items);
  727. $trunk_entity->{$field['field_name']}[LANGUAGE_NONE] = $items;
  728. // In future if this module eventually becomes a gateway for synonyms for any
  729. // entity types, we'll substitute it with entity_save().
  730. taxonomy_term_save($trunk_entity);
  731. return TRUE;
  732. }
  733. /**
  734. * Return array of field names that are sources of synonyms.
  735. *
  736. * Return array of field names that are currently have enabled the synonyms
  737. * behavior in the supplied vocabulary. This function is deprecated and shortly
  738. * will be removed from the code. All clients of this function are encourage to
  739. * use synonyms_behavior_get() function, which provides a richer set of
  740. * functionality than this one.
  741. *
  742. * @param object $vocabulary
  743. * Fully loaded taxonomy vocabulary object
  744. *
  745. * @return array
  746. * Array of field names
  747. *
  748. * @deprecated
  749. */
  750. function synonyms_synonyms_fields($vocabulary) {
  751. $fields = array();
  752. $bundle = field_extract_bundle('taxonomy_term', $vocabulary);
  753. $behavior_implementations = synonyms_behavior_get('synonyms', 'taxonomy_term', $bundle, TRUE);
  754. foreach ($behavior_implementations as $v) {
  755. $fields[] = $v['field_name'];
  756. }
  757. return $fields;
  758. }
  759. /**
  760. * Implements hook_views_api().
  761. */
  762. function synonyms_views_api() {
  763. return array(
  764. 'api' => 3,
  765. 'path' => drupal_get_path('module', 'synonyms') . '/views',
  766. );
  767. }
  768. /**
  769. * Load function for existing implementations of synonyms behaviors.
  770. *
  771. * @param string $behavior
  772. * Name of the synonyms behavior whose existing implementations should be
  773. * loaded. Basically it has to be name of a ctools plugin of "behavior" type.
  774. * @param string $entity_type
  775. * Optional filter to limit the search for existing implementations only to
  776. * those that apply to the provided entity type
  777. * @param string $bundle
  778. * Optional filter to limit the search for existing implementations only to
  779. * those that apply to the provided bundle and entity type (the $entity_type
  780. * argument)
  781. * @param bool $only_enabled
  782. * Optional filter to limit the search for existing implementations only to
  783. * those that are currently enabled
  784. * @param bool $include_deleted
  785. * Optional filter to include the behaviors from deleted instances
  786. *
  787. * @return array
  788. * Array of loaded existing synonyms behavior implementations. It is keyed
  789. * by ID of the field instance to which the behavior implementation applies.
  790. * The underlying array will have the following structure:
  791. * - behavior: (string) Behavior name of this behavior implementation, i.e.
  792. * name of a ctools plugin of "behavior" type
  793. * - settings: (mixed) Behavior settings, its internal structure depends on
  794. * the type of behavior. If this value is NULL, it means the behavior
  795. * implementation is currently disabled for the field instance
  796. * - entity_type: (string) Entity type to which this behavior implementation
  797. * applies
  798. * - bundle: (string) Bundle name to which this behavior implementation
  799. * applies
  800. * - field_name: (string) Name of a field to which this behavior
  801. * implementation applies
  802. * - instance_id: (int) ID of the instance to which this behavior
  803. * implementation applies
  804. */
  805. function synonyms_behavior_get($behavior, $entity_type = NULL, $bundle = NULL, $only_enabled = FALSE, $include_deleted = FALSE) {
  806. $behavior_implementation_info = synonyms_behavior_implementation_info($behavior);
  807. $supported_field_types = array_keys($behavior_implementation_info);
  808. if (empty($supported_field_types)) {
  809. return array();
  810. }
  811. $query = db_select('field_config_instance', 'i');
  812. $field_alias = $query->innerJoin('field_config', 'f', 'f.id = i.field_id');
  813. $query->condition($field_alias . '.type', $supported_field_types);
  814. if ($entity_type) {
  815. $query->condition('i.entity_type', $entity_type);
  816. }
  817. if ($bundle) {
  818. $query->condition('i.bundle', $bundle);
  819. }
  820. if (!$include_deleted) {
  821. $query->condition('i.deleted', 0);
  822. }
  823. $settings_alias = $query->addJoin($only_enabled ? 'INNER' : 'LEFT OUTER', 'synonyms_settings', 's', 's.instance_id = i.id AND s.behavior = :behavior', array(
  824. ':behavior' => $behavior,
  825. ));
  826. $query->fields($settings_alias, array('behavior', 'settings_serialized'));
  827. $query->fields('i', array('entity_type', 'bundle', 'field_name'));
  828. $query->addField('i', 'id', 'instance_id');
  829. $result = $query->execute();
  830. $result = $result->fetchAllAssoc('instance_id', PDO::FETCH_ASSOC);
  831. return synonyms_behavior_settings_unpack($result);
  832. }
  833. /**
  834. * Retrieve information about all ctools plugins of type 'synonyms behavior'.
  835. *
  836. * @return array
  837. * Array of information on all available synonyms behavior plugins
  838. */
  839. function synonyms_behaviors() {
  840. ctools_include('plugins');
  841. return ctools_get_plugins('synonyms', 'behavior');
  842. }
  843. /**
  844. * Fetch information about synonyms behaviors implementations per field type.
  845. *
  846. * Fetch the map between field types and the PHP classes that implement synonyms
  847. * behaviors for them.
  848. *
  849. * @param string $behavior
  850. * What specific behavior is queried. Supply here keys from the return of
  851. * synonyms_behaviors() function
  852. *
  853. * @return array
  854. * Array of information about what field types implement the provided behavior
  855. * through what PHP classes. Keys of this array are field types, whereas their
  856. * values are names of PHP classes that implement the provided behavior for
  857. * that particular field type
  858. */
  859. function synonyms_behavior_implementation_info($behavior) {
  860. $info = module_invoke_all('synonyms_behavior_implementation_info', $behavior);
  861. drupal_alter('synonyms_behavior_implementation_info', $info, $behavior);
  862. return $info;
  863. }
  864. /**
  865. * Determine what PHP class implements specific behavior for specific field.
  866. *
  867. * @param string $behavior
  868. * Name of the behavior, implementation of which is requested. It should be
  869. * one of the keys of the return of synonyms_behaviors() function.
  870. * @param array $field
  871. * Field definition array for which PHP class implementing $behavior is
  872. * requested
  873. *
  874. * @return string
  875. * Name of the PHP class that implements $behavior for $field field
  876. */
  877. function synonyms_behavior_implementation_class($behavior, $field) {
  878. $map = synonyms_behavior_implementation_info($behavior);
  879. return $map[$field['type']];
  880. }
  881. /**
  882. * Execute unpacking operation on the just loaded synonyms behavior settings.
  883. *
  884. * @param array $settings
  885. * Array of the just loaded settings. Each sub array should contain the
  886. * following keys:
  887. * - instance_id: (int) ID of the instance to which it applies
  888. * - behavior: (string) name of the synonyms behavior to which these settings
  889. * apply
  890. * - settings_serialized: (string) serialized content of the settings
  891. *
  892. * @return array
  893. * Unpacked version of the provided $settings
  894. */
  895. function synonyms_behavior_settings_unpack($settings) {
  896. foreach ($settings as &$setting) {
  897. $setting['settings'] = $setting['settings_serialized'] ? unserialize($setting['settings_serialized']) : NULL;
  898. }
  899. return $settings;
  900. }
  901. /**
  902. * Save the provided synonyms behavior settings into the database.
  903. *
  904. * @param array $settings
  905. * Array of settings. It must have the following structure:
  906. * - instance_id: (int) ID of the instance to which it applies
  907. * - behavior: (string) name of the synonyms behavior to which it applies
  908. * - settings: (mixed) the content of settings themselves
  909. */
  910. function synonyms_behavior_settings_save($settings) {
  911. if (!isset($settings['settings'])) {
  912. $settings['settings'] = array();
  913. }
  914. $settings['settings_serialized'] = serialize($settings['settings']);
  915. $result = db_merge('synonyms_settings')
  916. ->key(array(
  917. 'instance_id' => $settings['instance_id'],
  918. 'behavior' => $settings['behavior'],
  919. ))
  920. ->fields(array(
  921. 'instance_id' => $settings['instance_id'],
  922. 'behavior' => $settings['behavior'],
  923. 'settings_serialized' => $settings['settings_serialized'],
  924. ))
  925. ->execute();
  926. switch ($result) {
  927. case MergeQuery::STATUS_INSERT:
  928. $behavior_definition = synonyms_behaviors();
  929. $behavior_definition = $behavior_definition[$settings['behavior']];
  930. $enabled_callback = ctools_plugin_get_function($behavior_definition, 'enabled callback');
  931. if ($enabled_callback) {
  932. $enabled_callback($behavior_definition, $settings['settings'], synonyms_instance_id_load($settings['instance_id']));
  933. }
  934. break;
  935. }
  936. }
  937. /**
  938. * Delete settings for specific behavior and field instance.
  939. *
  940. * @param int $instance_id
  941. * ID of the instance for which settings should be removed
  942. * @param string $behavior
  943. * Name of behavior for which settings should be removed
  944. */
  945. function synonyms_behavior_settings_delete($instance_id, $behavior) {
  946. $behavior_definition = synonyms_behaviors();
  947. $behavior_definition = $behavior_definition[$behavior];
  948. $disabled_callback = ctools_plugin_get_function($behavior_definition, 'disabled callback');
  949. if ($disabled_callback) {
  950. $instance = synonyms_instance_id_load($instance_id);
  951. $behavior_implementation = synonyms_behavior_get($behavior, $instance['entity_type'], $instance['bundle'], FALSE, TRUE);
  952. $behavior_implementation = $behavior_implementation[$instance_id];
  953. $disabled_callback($behavior_definition, $behavior_implementation, $instance);
  954. }
  955. db_delete('synonyms_settings')
  956. ->condition('instance_id', $instance_id)
  957. ->condition('behavior', $behavior)
  958. ->execute();
  959. }
  960. /**
  961. * Supportive function to load a field instance by its ID.
  962. *
  963. * @param int $instance_id
  964. * ID of the instance that should be loaded
  965. *
  966. * @return array
  967. * Instance definition array
  968. */
  969. function synonyms_instance_id_load($instance_id) {
  970. $result = db_select('field_config_instance', 'i')
  971. ->fields('i', array('entity_type', 'bundle', 'field_name'))
  972. ->condition('id', $instance_id)
  973. ->execute()
  974. ->fetchAssoc();
  975. return field_info_instance($result['entity_type'], $result['field_name'], $result['bundle']);
  976. }
  977. /**
  978. * Convert synonyms friendly select widget values for storage friendly format.
  979. *
  980. * It acts similar to what the _options_form_to_storage() function does -
  981. * bridges between how values are returned from form API to how they are
  982. * expected by Field module.
  983. */
  984. function synonyms_select_form_to_storage($element, &$form_state) {
  985. $value = array();
  986. if ($element['#multiple']) {
  987. $value = $element['#value'];
  988. }
  989. else {
  990. $value[] = $element['#value'];
  991. }
  992. foreach ($value as $k => $v) {
  993. // For the cases when a synonym was selected and not a term option, we
  994. // process the selected values stripping everything that goes after
  995. // semicolon.
  996. if (!is_numeric($v)) {
  997. $tid = explode(':', $v);
  998. $value[$k] = $tid[0];
  999. }
  1000. }
  1001. // The user also might have selected multiple times the same term, given that
  1002. // a term can be represented by more than 1 option (a term and its synonym),
  1003. // then it's possible in theory, so we should be ready for this scenario.
  1004. $value = array_unique($value);
  1005. $form_state_value = array();
  1006. foreach ($value as $tid) {
  1007. $form_state_value[] = array('tid' => $tid);
  1008. }
  1009. form_set_value($element, $form_state_value, $form_state);
  1010. }
  1011. /**
  1012. * Check whether a taxonomy term $tid is a child of a taxonomy term $parent_tid.
  1013. *
  1014. * Supportive function, used throughout this module for parent constrains.
  1015. *
  1016. * @param int $tid
  1017. * {taxonomy_term}.tid of the term that is tested for being a child of the
  1018. * $parent_tid term
  1019. * @param int $parent_tid
  1020. * {taxonomy_term}.tid of the term that is tested for being parent of the $tid
  1021. * term
  1022. *
  1023. * @return bool
  1024. * Whether $tid is a child of $parent_tid
  1025. */
  1026. function synonyms_taxonomy_term_is_child_of($tid, $parent_tid) {
  1027. $term_parents = taxonomy_get_parents_all($tid);
  1028. // Dropping out the term itself from its array of parents.
  1029. array_shift($term_parents);
  1030. foreach ($term_parents as $term_parent) {
  1031. if ($term_parent->tid == $parent_tid) {
  1032. return TRUE;
  1033. }
  1034. }
  1035. return FALSE;
  1036. }
  1037. /**
  1038. * Format an option for select form element.
  1039. *
  1040. * @param object $term
  1041. * Fully loaded taxonomy term which is represented by this option
  1042. * @param string $synonym
  1043. * If the provided term is represented in this option by a synonym, then
  1044. * provide it here
  1045. * @param array $behavior_implementation
  1046. * Behavior implementation array from which the $synonym comes from
  1047. *
  1048. * @return object
  1049. * An option for select form element
  1050. */
  1051. function synonyms_select_option($term, $synonym = NULL, $behavior_implementation = NULL) {
  1052. $key = $synonym ? $term->tid . ':' . drupal_html_class($synonym) : $term->tid;
  1053. $wording = $term->name;
  1054. if ($synonym) {
  1055. $instance = field_info_instance($behavior_implementation['entity_type'], $behavior_implementation['field_name'], $behavior_implementation['bundle']);
  1056. $wording = format_string($behavior_implementation['settings']['wording'], array(
  1057. '@synonym' => $synonym,
  1058. '@term' => $term->name,
  1059. '@field_name' => drupal_strtolower($instance['label']),
  1060. ));
  1061. }
  1062. return (object) array(
  1063. 'option' => array($key => str_repeat('-', $term->depth) . $wording),
  1064. );
  1065. }
  1066. /**
  1067. * Supportive function to build options array with sorting by name logic.
  1068. *
  1069. * The function starts from the 0-depth level and starts to recursively build
  1070. * the options and to sort the labels on each level, then it merges the bottom
  1071. * to up all the levels maintaining correct order within the final options
  1072. * array.
  1073. *
  1074. * @param object $vocabulary
  1075. * Within which vocabulary to execute the function. Supply here the fully
  1076. * loaded taxonomy vocabulary object
  1077. * @param int $parent
  1078. * Only children of this term will be included in the output. You can supply
  1079. * 0 which means to include all the terms from the vocabulary
  1080. * @param int $depth
  1081. * Used for internal purposes. Clients of this function should supply here 0,
  1082. * unless they know what they are doing. It is used internally to keep track
  1083. * of the nesting level
  1084. *
  1085. * @return array
  1086. * Array of options that can be inserted directly into 'select' form element.
  1087. * The options will be sorted by name (term or synonym), respecting the
  1088. * hierarchy restrictions
  1089. */
  1090. function synonyms_select_sort_name_options_recursive($vocabulary, $parent = 0, $depth = 0) {
  1091. // We statically cache behavior implementations in order to not DDOS the data
  1092. // base.
  1093. $behavior_implementations = drupal_static(__FUNCTION__, array());
  1094. $bundle = field_extract_bundle('taxonomy_term', $vocabulary);
  1095. if (!isset($behavior_implementations[$bundle])) {
  1096. $behavior_implementations[$bundle] = synonyms_behavior_get('select', 'taxonomy_term', $bundle, TRUE);
  1097. }
  1098. $options = array();
  1099. if ($terms = taxonomy_get_tree($vocabulary->vid, $parent, 1, TRUE)) {
  1100. $options = array();
  1101. foreach ($terms as $term) {
  1102. $term->depth = $depth;
  1103. $options[] = synonyms_select_option($term);
  1104. foreach ($behavior_implementations[$bundle] as $implementation) {
  1105. foreach (synonyms_extract_synonyms($term, $implementation) as $synonym) {
  1106. $options[] = synonyms_select_option($term, $synonym, $implementation);
  1107. }
  1108. }
  1109. }
  1110. usort($options, 'synonyms_select_sort_name');
  1111. // Now recursively go one level nested into each of the terms that we have
  1112. // on this level.
  1113. $options_copy = $options;
  1114. $i = 0;
  1115. foreach ($options_copy as $v) {
  1116. $i++;
  1117. $tid = array_keys($v->option);
  1118. $tid = $tid[0];
  1119. if (is_numeric($tid)) {
  1120. $nested_options = synonyms_select_sort_name_options_recursive($vocabulary, $tid, $depth + 1);
  1121. $options = array_merge(array_slice($options, 0, $i), $nested_options, array_slice($options, $i));
  1122. }
  1123. }
  1124. }
  1125. return $options;
  1126. }
  1127. /**
  1128. * Supportive function.
  1129. *
  1130. * It is used for string comparison within synonyms friendly select widget.
  1131. */
  1132. function synonyms_select_sort_name($a, $b) {
  1133. return strcasecmp(reset($a->option), reset($b->option));
  1134. }