synonyms.module 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566
  1. <?php
  2. /**
  3. * @file
  4. * Provide synonyms feature for Drupal entities.
  5. */
  6. /**
  7. * Implements hook_menu().
  8. */
  9. function synonyms_menu() {
  10. $items = array();
  11. $items['admin/structure/synonyms'] = array(
  12. 'title' => 'Synonyms',
  13. 'description' => 'Manage synonyms settings for all entity types.',
  14. 'page callback' => 'synonyms_settings_overview',
  15. 'access arguments' => array('administer synonyms'),
  16. 'file' => 'synonyms.pages.inc',
  17. 'type' => MENU_NORMAL_ITEM,
  18. );
  19. $items['admin/structure/synonyms/%synonyms_entity_type/%synonyms_bundle'] = array(
  20. 'title' => 'Synonyms settings',
  21. 'title callback' => 'synonyms_settings_title',
  22. 'title arguments' => array(3, 4),
  23. 'description' => 'Manage synonyms settings.',
  24. 'page callback' => 'drupal_get_form',
  25. 'page arguments' => array('synonyms_settings_form', 3, 4),
  26. 'access arguments' => array('administer synonyms'),
  27. 'load arguments' => array(3),
  28. 'file' => 'synonyms.pages.inc',
  29. );
  30. if (module_exists('taxonomy')) {
  31. $items['synonyms/autocomplete-taxonomy-term/%/%/%'] = array(
  32. 'title' => 'Autocomplete Synonyms',
  33. 'page callback' => 'synonyms_autocomplete_taxonomy_term',
  34. 'page arguments' => array(2, 3, 4),
  35. 'access arguments' => array('access content'),
  36. 'file' => 'synonyms.pages.inc',
  37. 'type' => MENU_CALLBACK,
  38. );
  39. }
  40. $items['synonyms/autocomplete-entity/%/%/%'] = array(
  41. 'title' => 'Autocomplete Synonyms',
  42. 'page callback' => 'synonyms_autocomplete_entity',
  43. 'page arguments' => array(2, 3, 4),
  44. 'access callback' => 'entityreference_autocomplete_access_callback',
  45. 'access arguments' => array('tags', 2, 3, 4),
  46. 'file' => 'synonyms.pages.inc',
  47. 'type' => MENU_CALLBACK,
  48. );
  49. return $items;
  50. }
  51. /**
  52. * Implements hook_permission().
  53. */
  54. function synonyms_permission() {
  55. return array(
  56. 'administer synonyms' => array(
  57. 'title' => t('Administer synonyms'),
  58. 'description' => t('Administer synonyms of all entity types.'),
  59. ),
  60. );
  61. }
  62. /**
  63. * Implements hook_ctools_plugin_type().
  64. */
  65. function synonyms_ctools_plugin_type() {
  66. $plugins = array();
  67. $plugins['behavior'] = array(
  68. 'defaults' => array(
  69. 'title' => NULL,
  70. 'description' => NULL,
  71. 'settings form callback' => NULL,
  72. 'interface' => NULL,
  73. 'enabled callback' => NULL,
  74. 'disabled callback' => NULL,
  75. ),
  76. );
  77. return $plugins;
  78. }
  79. /**
  80. * Implements hook_ctools_plugin_directory().
  81. */
  82. function synonyms_ctools_plugin_directory($owner, $plugin_type) {
  83. switch ($owner) {
  84. case 'synonyms':
  85. switch ($plugin_type) {
  86. case 'behavior':
  87. return 'plugins/' . $plugin_type;
  88. }
  89. break;
  90. case 'ctools':
  91. switch ($plugin_type) {
  92. case 'arguments':
  93. return 'plugins/' . $plugin_type;
  94. }
  95. break;
  96. }
  97. }
  98. /**
  99. * Implements hook_theme().
  100. */
  101. function synonyms_theme() {
  102. return array(
  103. 'synonyms_behaviors_settings' => array(
  104. 'render element' => 'element',
  105. 'file' => 'synonyms.pages.inc',
  106. ),
  107. );
  108. }
  109. /**
  110. * Implements hook_entity_property_info().
  111. */
  112. function synonyms_entity_property_info() {
  113. $info = array();
  114. foreach (entity_get_info() as $entity_type => $entity_info) {
  115. $entity_type = synonyms_entity_type_load($entity_type);
  116. if ($entity_type) {
  117. $info[$entity_type]['properties']['synonyms'] = array(
  118. 'label' => t('Synonyms'),
  119. 'description' => t('Synonyms of entity.'),
  120. 'type' => 'list<text>',
  121. 'getter callback' => 'synonyms_get_sanitized',
  122. 'computed' => TRUE,
  123. 'sanitized' => TRUE,
  124. 'raw getter callback' => 'synonyms_get_raw',
  125. );
  126. }
  127. }
  128. return $info;
  129. }
  130. /**
  131. * Implements hook_form_FORM_ID_alter().
  132. */
  133. function synonyms_form_taxonomy_form_vocabulary_alter(&$form, &$form_state) {
  134. // TODO: remove this function after a few releases of Synonyms module, since
  135. // now the module oversees synonyms of all entities, not only taxonomy terms.
  136. if (isset($form_state['confirm_delete']) && $form_state['confirm_delete']) {
  137. return;
  138. }
  139. if (!isset($form['#vocabulary']->vid) || !$form['#vocabulary']->vid) {
  140. return;
  141. }
  142. $form['synonyms'] = array(
  143. '#type' => 'fieldset',
  144. '#title' => t('Synonyms'),
  145. '#collapsible' => TRUE,
  146. );
  147. $form['synonyms']['link'] = array(
  148. '#markup' => t('You can configure synonyms of @vocabulary following <a href="@url">this link</a>.', array(
  149. '@vocabulary' => $form['#vocabulary']->name,
  150. '@url' => url('admin/structure/synonyms/taxonomy_term/' . $form['#vocabulary']->machine_name, array('query' => drupal_get_destination())),
  151. )),
  152. );
  153. }
  154. /**
  155. * Implements hook_field_widget_info().
  156. */
  157. function synonyms_field_widget_info() {
  158. return array(
  159. 'synonyms_autocomplete_taxonomy_term' => array(
  160. 'label' => t('Synonyms friendly autocomplete'),
  161. 'field types' => array('taxonomy_term_reference'),
  162. 'settings' => array(
  163. 'size' => 60,
  164. 'synonyms_autocomplete_path' => 'synonyms/autocomplete-taxonomy-term',
  165. 'suggestion_size' => 10,
  166. 'suggest_only_unique' => FALSE,
  167. 'auto_creation' => 1,
  168. ),
  169. 'behaviors' => array(
  170. 'multiple values' => FIELD_BEHAVIOR_CUSTOM,
  171. ),
  172. ),
  173. 'synonyms_autocomplete_entity' => array(
  174. 'label' => t('Synonyms friendly autocomplete'),
  175. 'field types' => array('entityreference'),
  176. 'settings' => array(
  177. 'size' => 60,
  178. 'synonyms_autocomplete_path' => 'synonyms/autocomplete-entity',
  179. 'suggestion_size' => 10,
  180. 'suggest_only_unique' => FALSE,
  181. ),
  182. 'behaviors' => array(
  183. 'multiple values' => FIELD_BEHAVIOR_CUSTOM,
  184. ),
  185. ),
  186. 'synonyms_select_taxonomy_term' => array(
  187. 'label' => t('Synonyms friendly select list'),
  188. 'field types' => array('taxonomy_term_reference'),
  189. 'settings' => array(
  190. 'sort' => 'weight',
  191. ),
  192. 'behaviors' => array(
  193. 'multiple values' => FIELD_BEHAVIOR_CUSTOM,
  194. ),
  195. ),
  196. 'synonyms_select_entity' => array(
  197. 'label' => t('Synonyms friendly select list'),
  198. 'field types' => array('entityreference'),
  199. 'settings' => array(),
  200. 'behaviors' => array(
  201. 'multiple values' => FIELD_BEHAVIOR_CUSTOM,
  202. ),
  203. ),
  204. );
  205. }
  206. /**
  207. * Implements hook_field_widget_settings_form().
  208. */
  209. function synonyms_field_widget_settings_form($field, $instance) {
  210. $widget = $instance['widget'];
  211. $settings = $widget['settings'] + field_info_widget_settings($widget['type']);
  212. $form = array();
  213. switch ($widget['type']) {
  214. case 'synonyms_autocomplete_taxonomy_term':
  215. case 'synonyms_autocomplete_entity':
  216. if ($widget['type'] == 'synonyms_autocomplete_taxonomy_term') {
  217. $form['auto_creation'] = array(
  218. '#type' => 'checkbox',
  219. '#title' => t('Allow auto-creation?'),
  220. '#description' => t('Whether users may create a new term by typing in a non-existing name into this field.'),
  221. '#default_value' => $settings['auto_creation'],
  222. );
  223. }
  224. $form['suggestion_size'] = array(
  225. '#type' => 'textfield',
  226. '#title' => t('Suggestions Size'),
  227. '#description' => t('Please, enter how many suggested entities to show in the autocomplete textfield.'),
  228. '#required' => TRUE,
  229. '#element_validate' => array('element_validate_integer_positive'),
  230. '#default_value' => $settings['suggestion_size'],
  231. );
  232. $form['suggest_only_unique'] = array(
  233. '#type' => 'checkbox',
  234. '#title' => t('Suggest only one entry per term'),
  235. '#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.'),
  236. '#default_value' => $settings['suggest_only_unique'],
  237. );
  238. break;
  239. case 'synonyms_select_taxonomy_term':
  240. $form['sort'] = array(
  241. '#type' => 'radios',
  242. '#title' => t('Sort'),
  243. '#description' => t('Choose by what criterion the items within select should be sorted.'),
  244. '#options' => array(
  245. 'weight' => t('As in taxonomy vocabulary (by weight)'),
  246. 'name' => t('By name of terms and their synonyms'),
  247. ),
  248. '#default_value' => $settings['sort'],
  249. );
  250. break;
  251. }
  252. return $form;
  253. }
  254. /**
  255. * Implements hook_field_widget_form().
  256. */
  257. function synonyms_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  258. $default_value = synonyms_select_default_value($field, $instance, $items);
  259. switch ($instance['widget']['type']) {
  260. case 'synonyms_autocomplete_taxonomy_term':
  261. case 'synonyms_autocomplete_entity':
  262. switch ($instance['widget']['type']) {
  263. case 'synonyms_autocomplete_taxonomy_term':
  264. $default_value_string = taxonomy_implode_tags(taxonomy_term_load_multiple($default_value));
  265. $element_validate = array('taxonomy_autocomplete_validate', 'synonyms_autocomplete_taxonomy_term_validate');
  266. break;
  267. case 'synonyms_autocomplete_entity':
  268. $default_value_string = array();
  269. $entity = isset($element['#entity']) ? $element['#entity'] : NULL;
  270. $handler = entityreference_get_selection_handler($field, $instance, $instance['entity_type'], $entity);
  271. $target_entities = entity_load($field['settings']['target_type'], $default_value);
  272. foreach ($target_entities as $target_entity_id => $target_entity) {
  273. $default_value_string[] = synonyms_autocomplete_escape($handler->getLabel($target_entity));
  274. }
  275. $default_value_string = drupal_implode_tags($default_value_string);
  276. $element_validate = array('synonyms_autocomplete_entity_validate');
  277. break;
  278. }
  279. $element += array(
  280. '#type' => 'textfield',
  281. '#default_value' => $default_value_string,
  282. '#autocomplete_path' => $instance['widget']['settings']['synonyms_autocomplete_path'] . '/' . $field['field_name'] . '/' . $instance['entity_type'] . '/' . $instance['bundle'],
  283. '#size' => $instance['widget']['settings']['size'],
  284. '#maxlength' => 1024,
  285. '#element_validate' => $element_validate,
  286. '#attached' => array(
  287. 'js' => array(
  288. drupal_get_path('module', 'synonyms') . '/js/synonyms-autocomplete.js' => array(),
  289. ),
  290. ),
  291. '#attributes' => array(
  292. 'class' => array('synonyms-autocomplete'),
  293. ),
  294. );
  295. if (isset($instance['widget']['settings']['auto_creation'])) {
  296. $element['#auto_creation'] = $instance['widget']['settings']['auto_creation'];
  297. }
  298. break;
  299. case 'synonyms_select_taxonomy_term':
  300. $multiple = $field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED;
  301. $options = array();
  302. foreach ($field['settings']['allowed_values'] as $tree) {
  303. if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
  304. switch ($instance['widget']['settings']['sort']) {
  305. case 'weight':
  306. if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'], NULL, TRUE)) {
  307. $behavior_implementations = synonyms_behavior_get('select', 'taxonomy_term', field_extract_bundle('taxonomy_term', $vocabulary), TRUE);
  308. foreach ($terms as $term) {
  309. $options[] = synonyms_select_option_entity($term, 'taxonomy_term', NULL, NULL, array('depth'));
  310. foreach ($behavior_implementations as $implementation) {
  311. foreach ($implementation['object']->extractSynonyms($term) as $synonym) {
  312. $options[] = synonyms_select_option_entity($term, 'taxonomy_term', $synonym, $implementation, array('depth'));
  313. }
  314. }
  315. }
  316. }
  317. break;
  318. case 'name':
  319. // TODO: is there any way to leverage DB for the sorting routine?
  320. $options = synonyms_select_taxonomy_term_sort_name_options_recursive($vocabulary, $tree['parent']);
  321. break;
  322. }
  323. }
  324. }
  325. $element += array(
  326. '#type' => 'select',
  327. '#multiple' => $multiple,
  328. '#options' => $options,
  329. '#default_value' => $default_value,
  330. '#element_validate' => array('synonyms_select_validate', 'synonyms_select_form_to_storage'),
  331. '#empty_option' => t('- None -'),
  332. );
  333. break;
  334. case 'synonyms_select_entity':
  335. $multiple = $field['cardinality'] > 1 || $field['cardinality'] == FIELD_CARDINALITY_UNLIMITED;
  336. $element += array(
  337. '#type' => 'select',
  338. '#multiple' => $multiple,
  339. '#options' => synonyms_select_entity_options($field, $instance, $element['#entity']),
  340. '#default_value' => $default_value,
  341. '#element_validate' => array('synonyms_select_validate', 'synonyms_select_form_to_storage'),
  342. '#empty_option' => t('- None -'),
  343. );
  344. break;
  345. }
  346. return $element;
  347. }
  348. /**
  349. * Implements hook_field_widget_error().
  350. */
  351. function synonyms_field_widget_error($element, $error, $form, &$form_state) {
  352. form_error($element, $error['message']);
  353. }
  354. /**
  355. * Implements hook_features_api().
  356. */
  357. function synonyms_features_api() {
  358. return array(
  359. 'synonyms' => array(
  360. 'name' => t('Synonyms'),
  361. 'file' => drupal_get_path('module', 'synonyms') . '/synonyms.features.inc',
  362. 'default_hook' => 'default_synonyms',
  363. 'feature_source' => TRUE,
  364. ),
  365. );
  366. }
  367. /**
  368. * Implements hook_modules_disabled().
  369. */
  370. function synonyms_modules_disabled($modules) {
  371. foreach ($modules as $module) {
  372. db_delete('synonyms_settings')
  373. ->condition('provider', db_like($module) . '%', 'LIKE')
  374. ->execute();
  375. }
  376. }
  377. /**
  378. * Form element validate handler.
  379. *
  380. * Handle validation for taxonomy term synonym-friendly autocomplete element.
  381. */
  382. function synonyms_autocomplete_taxonomy_term_validate($element, &$form_state) {
  383. // After taxonomy_autocomplete_validate() has finished its job any terms it
  384. // didn't find have been set for autocreation. We need to:
  385. // (a) Double-check that those terms are not synonyms.
  386. // (b) Check that synonyms' configurable auto-creation option is enabled.
  387. $value = drupal_array_get_nested_value($form_state['values'], $element['#parents']);
  388. $tids = array();
  389. $field = field_widget_field($element, $form_state);
  390. foreach ($value as $delta => $term) {
  391. if ($term['tid'] == 'autocreate') {
  392. $synonym_tid = 0;
  393. foreach ($field['settings']['allowed_values'] as $tree) {
  394. $behavior_implementations = synonyms_behavior_get('autocomplete', 'taxonomy_term', $tree['vocabulary'], TRUE);
  395. foreach ($behavior_implementations as $behavior_implementation) {
  396. $synonyms = $behavior_implementation['object']->synonymsFind(db_and()->condition(AbstractSynonymsBehavior::COLUMN_SYNONYM_PLACEHOLDER, $term['name']));
  397. foreach ($synonyms as $synonym) {
  398. $synonym_tid = $synonym->entity_id;
  399. break(2);
  400. }
  401. }
  402. }
  403. if ($synonym_tid != 0 && !in_array($synonym_tid, $tids)) {
  404. $value[$delta]['tid'] = $synonym_tid;
  405. $tids[] = $synonym_tid;
  406. }
  407. elseif (!$element['#auto_creation']) {
  408. unset($value[$delta]);
  409. }
  410. }
  411. else {
  412. $tids[] = $term['tid'];
  413. }
  414. }
  415. $value = array_values($value);
  416. form_set_value($element, $value, $form_state);
  417. }
  418. /**
  419. * Form element validate handler.
  420. *
  421. * Validate entity reference synonyms friendly autocomplete element.
  422. */
  423. function synonyms_autocomplete_entity_validate($element, &$form_state) {
  424. $input = drupal_map_assoc(drupal_explode_tags(drupal_strtolower($element['#value'])));
  425. $value = array();
  426. if (!empty($input)) {
  427. $field = field_info_field($element['#field_name']);
  428. $instance = field_info_instance($element['#entity_type'], $field['field_name'], $element['#bundle']);
  429. $handler = entityreference_get_selection_handler($field, $instance);
  430. $matches = $handler->getReferencableEntities($input, 'IN');
  431. foreach ($matches as $bundle => $entity_ids) {
  432. foreach ($entity_ids as $entity_id => $label) {
  433. $value[] = $entity_id;
  434. unset($input[drupal_strtolower($label)]);
  435. }
  436. }
  437. if (!empty($input)) {
  438. $behavior_implementations = synonyms_behavior_get('autocomplete', $field['settings']['target_type'], synonyms_field_target_bundles($field), TRUE);
  439. foreach ($behavior_implementations as $implementation) {
  440. $condition = db_and();
  441. $condition->condition(AbstractSynonymsBehavior::COLUMN_SYNONYM_PLACEHOLDER, $input, 'IN');
  442. foreach ($implementation['object']->synonymsFind($condition) as $synonym) {
  443. $value[] = $synonym->entity_id;
  444. unset($input[drupal_strtolower($synonym->synonym)]);
  445. if (empty($input)) {
  446. break(2);
  447. }
  448. }
  449. }
  450. }
  451. }
  452. $tmp = array_unique($value);
  453. $value = array();
  454. foreach ($tmp as $target_id) {
  455. $value[] = array('target_id' => $target_id);
  456. }
  457. form_set_value($element, $value, $form_state);
  458. }
  459. /**
  460. * Try finding an entity by its name or synonym.
  461. *
  462. * @param string $entity_type
  463. * What entity type is being searched
  464. * @param string $name
  465. * The look up keyword (the supposed name or synonym)
  466. * @param string $bundle
  467. * Optionally limit the search within a specific bundle name of the provided
  468. * entity type
  469. *
  470. * @return int
  471. * ID of the looked up entity. If such entity was not found, then 0 is
  472. * returned
  473. */
  474. function synonyms_get_entity_by_synonym($entity_type, $name, $bundle = NULL) {
  475. $name = trim($name);
  476. $entity_info = entity_get_info($entity_type);
  477. // This is somewhat hacky, but it's the best we can do: user.module does not
  478. // declare 'label' entity key on 'user' entity type, while there is clearly
  479. // one: the 'name' column. In fact, entityreference.module does about the same
  480. // thing in EntityReference_SelectionHandler_Generic_user class.
  481. if ($entity_type == 'user') {
  482. $entity_info['entity keys']['label'] = 'name';
  483. }
  484. if (isset($entity_info['entity keys']['label'])) {
  485. $efq = new EntityFieldQuery();
  486. $efq->entityCondition('entity_type', $entity_type);
  487. if ($bundle) {
  488. $efq->entityCondition('bundle', $bundle);
  489. }
  490. $efq->propertyCondition($entity_info['entity keys']['label'], $name);
  491. $result = $efq->execute();
  492. if (isset($result[$entity_type])) {
  493. $result = array_keys($result[$entity_type]);
  494. return reset($result);
  495. }
  496. }
  497. $synonyms = synonyms_synonyms_find(db_and()->condition(AbstractSynonymsBehavior::COLUMN_SYNONYM_PLACEHOLDER, $name), $entity_type, $bundle);
  498. if (!empty($synonyms)) {
  499. return reset($synonyms)->entity_id;
  500. }
  501. return 0;
  502. }
  503. /**
  504. * Try to find a term by its name or synonym.
  505. *
  506. * You are advised to use the more general function
  507. * synonyms_get_entity_by_synonym() unless you really need $parent input
  508. * argument from this function for additional filtering by Taxonomy hierarchy.
  509. *
  510. * @param string $name
  511. * The string to be searched for its {taxonomy_term_data}.tid
  512. * @param object $vocabulary
  513. * Fully loaded vocabulary object in which you wish to search
  514. * @param int $parent
  515. * Optional. In case you want to narrow your search scope, this parameter
  516. * takes in the {taxonomy_term_data}.tid of the parent term, letting you
  517. * search only among its children
  518. *
  519. * @return int
  520. * If the look up was successful returns the {taxonomy_term_data}.tid of the
  521. * found term, otherwise returns 0
  522. */
  523. function synonyms_get_term_by_synonym($name, $vocabulary, $parent = 0) {
  524. if (!module_exists('taxonomy')) {
  525. return 0;
  526. }
  527. $name = trim($name);
  528. $terms = taxonomy_get_term_by_name($name, $vocabulary->machine_name);
  529. foreach ($terms as $term) {
  530. if (!$parent || synonyms_taxonomy_term_is_child_of($term->tid, $parent)) {
  531. // TODO: actually it could be so that there is more than 1 term that
  532. // satisfies the search query, i.e. the name and parent constraints. At
  533. // the moment we are going to return the first one we encounter, though
  534. // something better could be thought of in the future.
  535. return $term->tid;
  536. }
  537. }
  538. // We have failed to find a term with the provided $name. So let's search now
  539. // among the term synonyms.
  540. $bundle = field_extract_bundle('taxonomy_term', $vocabulary);
  541. $synonyms = synonyms_synonyms_find(db_and()->condition(AbstractSynonymsBehavior::COLUMN_SYNONYM_PLACEHOLDER, $name), 'taxonomy_term', $bundle);
  542. foreach ($synonyms as $synonym) {
  543. if (!$parent || synonyms_taxonomy_term_is_child_of($synonym->entity_id, $parent)) {
  544. // TODO: similarly here, as above, we could have more than 1 match, but
  545. // for now we will simply return the first one encountered.
  546. return $synonym->entity_id;
  547. }
  548. }
  549. // If we have reached down here, this means we haven't got any match
  550. // as fallback we return 0.
  551. return 0;
  552. }
  553. /**
  554. * Look up a term considering synonyms and if nothing is found add one.
  555. *
  556. * This function is useful for automated creation of new terms as it won't
  557. * generate the same terms over and over again.
  558. *
  559. * @param string $name
  560. * The string to be searched for its {taxonomy_term_data}.tid
  561. * @param object $vocabulary
  562. * Fully loaded vocabulary object in which you wish to search
  563. * @param int $parent
  564. * Optional. In case you want to narrow your search scope, this parameter
  565. * takes in the {taxonomy_term_data}.tid of the parent term, letting you
  566. * search only among its children
  567. *
  568. * @return int
  569. * If a term already exists, its {taxonomy_term_data}.tid is returned,
  570. * otherwise it creates a new term and returns its {taxonomy_term_data}.tid
  571. */
  572. function synonyms_add_term_by_synonym($name, $vocabulary, $parent = 0) {
  573. if (!module_exists('taxonomy')) {
  574. return 0;
  575. }
  576. $tid = synonyms_get_term_by_synonym($name, $vocabulary, $parent);
  577. if ($tid) {
  578. // We found some term, returning its tid.
  579. return $tid;
  580. }
  581. // We haven't found any term, so we create one.
  582. $term = (object) array(
  583. 'name' => $name,
  584. 'vid' => $vocabulary->vid,
  585. 'parent' => array($parent),
  586. );
  587. taxonomy_term_save($term);
  588. if (isset($term->tid)) {
  589. return $term->tid;
  590. }
  591. // Normally we shouldn't reach up to here, because a term would have got
  592. // created and the just created tid would have been returned. Nevertheless,
  593. // as a fallback in case of any error we return 0.
  594. return 0;
  595. }
  596. /**
  597. * Retrieve list of sanitized synonyms of an entity.
  598. *
  599. * @param $entity object
  600. * Fully loaded entity
  601. *
  602. * @return array
  603. * List of sanitized synonyms of an entity
  604. */
  605. function synonyms_get_sanitized($entity, array $options, $name, $entity_type, &$context) {
  606. return array_map('check_plain', synonyms_get_raw($entity, $options, $name, $entity_type, $context));
  607. }
  608. /**
  609. * Retrieve list of raw synonyms of an entity.
  610. *
  611. * @param $entity object
  612. * Fully loaded entity
  613. *
  614. * @return array
  615. * List of raw synonyms of an entity
  616. */
  617. function synonyms_get_raw($entity, array $options, $name, $entity_type, &$context) {
  618. $synonyms = array();
  619. $bundle = entity_extract_ids($entity_type, $entity);
  620. $bundle = $bundle[2];
  621. $behavior_implementations = synonyms_behavior_get_all_enabled($entity_type, $bundle);
  622. $providers = array();
  623. foreach ($behavior_implementations as $implementation) {
  624. if (!in_array($implementation['provider'], $providers)) {
  625. $synonyms = array_merge($synonyms, $implementation['object']->extractSynonyms($entity));
  626. $providers[] = $implementation['provider'];
  627. }
  628. }
  629. return $synonyms;
  630. }
  631. /**
  632. * Public function for retrieving synonyms of a taxonomy term.
  633. *
  634. * You are encouraged to use synonyms_get_sanitized() or synonyms_get_raw()
  635. * instead. This function soon will be removed from the source code.
  636. *
  637. * @param object $term
  638. * Fully loaded taxonomy term for which the synonyms are desired
  639. *
  640. * @return array
  641. * Array of synonyms, if synonyms are disabled for the taxonomy term's
  642. * vocabulary, an empty array is returned. Each synonym subarray consists of
  643. * the following keys:
  644. * - value: (string) the value of a synonym as it was input by user
  645. * - safe_value: (string) a sanitized value of a synonym
  646. *
  647. * @deprecated
  648. */
  649. function synonyms_get_term_synonyms($term) {
  650. if (!module_exists('taxonomy')) {
  651. return array();
  652. }
  653. $synonyms = array();
  654. $vocabulary = taxonomy_vocabulary_load($term->vid);
  655. $bundle = field_extract_bundle('taxonomy_term', $vocabulary);
  656. $behavior_implementations = synonyms_behavior_get_all_enabled('taxonomy_term', $bundle);
  657. foreach ($behavior_implementations as $implementation) {
  658. foreach ($implementation['object']->extractSynonyms($term) as $synonym) {
  659. $synonyms[] = array(
  660. 'value' => $synonym,
  661. 'safe_value' => check_plain($synonym),
  662. );
  663. }
  664. }
  665. return $synonyms;
  666. }
  667. /**
  668. * Look up entities by their synonyms.
  669. *
  670. * @param QueryConditionInterface $condition
  671. * Object of QueryConditionInterface that specifies conditions by which you
  672. * want to find synonyms. When building this condition object, use
  673. * AbstractSynonymsBehavior::COLUMN_PLACEHOLDER as a placeholder for real
  674. * column name that contains synonym as text. For example, if you were to find
  675. * all entities with synonyms that begin with "synonym-come-here" substring,
  676. * case insensitive and replacing all spaces in original synonym string by a
  677. * dash sign, then you would have to create the following condition object:
  678. * db_and()
  679. * ->where("LOWER(REPLACE(" . AbstractSynonymsBehavior::COLUMN_PLACEHOLDER . ", ' ', '-')) LIKE :synonym", array(
  680. * ':synonym' => '%' . db_like($some-var) . '%'
  681. * ))
  682. * And then just supply this object as an input parameter to this function
  683. * @param string $entity_type
  684. * Among synonyms of what entity type to search
  685. * @param string|array $bundle
  686. * Optionally specify among synonyms of what bundle(-s) to search. You can
  687. * specify here a string - bundle name to search within or an array of bundles
  688. * within which to search
  689. *
  690. * @return array
  691. * Array of found synonyms and entity IDs to which those belong. Each element
  692. * in the array will be an object and will have the following structure:
  693. * - synonym: (string) Synonym that was found and which satisfies the
  694. * $condition you specified
  695. * - entity_id: (int) ID of the entity to which the found synonym belongs
  696. */
  697. function synonyms_synonyms_find(QueryConditionInterface $condition, $entity_type, $bundle = NULL) {
  698. $rows = array();
  699. $behavior_implementations = synonyms_behavior_get_all_enabled($entity_type, $bundle);
  700. foreach ($behavior_implementations as $behavior_implementation) {
  701. foreach ($behavior_implementation['object']->synonymsFind($condition) as $row) {
  702. $rows[] = $row;
  703. }
  704. }
  705. return $rows;
  706. }
  707. /**
  708. * Allow to merge $synonym_entity as a synonym into $trunk_entity.
  709. *
  710. * Helpful function during various merging operations. It allows you to add a
  711. * synonym (where possible) into one entity, which will represent another entity
  712. * in the format expected by the field in which the synonym is being added.
  713. * Important note: if the cardinality limit of the field into which you are
  714. * adding synonym has been reached, calling to this function will take no
  715. * effect.
  716. *
  717. * @param object $trunk_entity
  718. * Fully loaded entity object in which the synonym is being added
  719. * @param string $trunk_entity_type
  720. * Entity type of $trunk_entity
  721. * @param string $field
  722. * Field name that should exist in $trunk_entity and have enabled the
  723. * "synonyms" behavior. Into this field synonym will be added
  724. * @param object $synonym_entity
  725. * Fully loaded entity object which will be added as a synonym
  726. * @param string $synonym_entity_type
  727. * Entity type of $synonym_entity
  728. *
  729. * @return bool
  730. * Whether synonym has been successfully added
  731. *
  732. * TODO: This should be shifted into Term Merge module.
  733. */
  734. function synonyms_add_entity_as_synonym($trunk_entity, $trunk_entity_type, $field, $synonym_entity, $synonym_entity_type) {
  735. $bundle = entity_extract_ids($trunk_entity_type, $trunk_entity);
  736. $bundle = $bundle[2];
  737. // TODO: this somehow must be incorporated into synonyms_provider_field
  738. // submodule.
  739. $behavior_implementations = synonyms_behavior_get_all_enabled($trunk_entity_type, $bundle, synonyms_provider_field_provider_name(field_info_field($field)));
  740. if (empty($behavior_implementations)) {
  741. // $field either doesn't exist in the $trunk_entity or it does not have any
  742. // enabled behavior.
  743. return FALSE;
  744. }
  745. $behavior_implementation = reset($behavior_implementations);
  746. $behavior_implementation['object']->mergeEntityAsSynonym($trunk_entity, $synonym_entity, $synonym_entity_type);
  747. entity_save($trunk_entity_type, $trunk_entity);
  748. return TRUE;
  749. }
  750. /**
  751. * Return array of field names that are sources of synonyms.
  752. *
  753. * Return array of field names that are currently have enabled the synonyms
  754. * behavior in the supplied vocabulary. This function is deprecated and shortly
  755. * will be removed from the code. All clients of this function are encourage to
  756. * use synonyms_behavior_get() function, which provides a richer set of
  757. * functionality than this one.
  758. *
  759. * @param object $vocabulary
  760. * Fully loaded taxonomy vocabulary object
  761. *
  762. * @return array
  763. * Array of field names
  764. *
  765. * @deprecated
  766. */
  767. function synonyms_synonyms_fields($vocabulary) {
  768. // TODO: remove this ugly function as soon as possible. It has got hacky since
  769. // now not only fields may be providers of synonyms.
  770. if (!module_exists('taxonomy')) {
  771. return array();
  772. }
  773. $fields = array();
  774. $bundle = field_extract_bundle('taxonomy_term', $vocabulary);
  775. $behavior_implementations = synonyms_behavior_get_all_enabled('taxonomy_term', $bundle);
  776. foreach ($behavior_implementations as $v) {
  777. $field_name = synonyms_provider_field_field_name($v['provider']);
  778. if (field_info_field($field_name)) {
  779. $fields[] = $field_name;
  780. }
  781. }
  782. return $fields;
  783. }
  784. /**
  785. * Implements hook_views_api().
  786. */
  787. function synonyms_views_api() {
  788. return array(
  789. 'api' => 3,
  790. 'path' => drupal_get_path('module', 'synonyms') . '/views',
  791. );
  792. }
  793. /**
  794. * Load function for existing implementations of synonyms behaviors.
  795. *
  796. * @param string $behavior
  797. * Name of the synonyms behavior whose existing implementations should be
  798. * loaded. Basically it has to be name of a ctools plugin of "behavior" type.
  799. * @param string $entity_type
  800. * Behavior implementations of what entity type should be looked up
  801. * @param string|array $bundle
  802. * Behavior implementations of what bundle(-s) should be looked up. If you
  803. * want to look up only a single bundle, provide a string. If you want to
  804. * look up multiple bundles at a time, provide an array of bundles. Empty
  805. * array here would mean to include all bundles that are known within provided
  806. * $entity_type
  807. * @param bool $only_enabled
  808. * Optional filter to limit the search for existing implementations only to
  809. * those that are currently enabled
  810. *
  811. * @return array
  812. * Array of loaded existing synonyms behavior implementations. The underlying
  813. * array will have the following structure:
  814. * - behavior: (string) Behavior name of this behavior implementation, i.e.
  815. * name of a ctools plugin of "behavior" type
  816. * - entity_type: (string) Entity type to which this behavior implementation
  817. * applies
  818. * - bundle: (string) Bundle name to which this behavior implementation
  819. * applies
  820. * - provider: (string) Machine name of this synonyms behavior implementation
  821. * - label: (string) Human friendly name of this synonyms behavior
  822. * implementation
  823. * - class: (string) Name of PHP class that implements behavior interface
  824. * - settings: (mixed) Behavior settings, its internal structure depends on
  825. * the type of behavior. If this value is NULL, it means the behavior
  826. * implementation is currently disabled
  827. * - object: (SynonymsBehavior) If the synonyms behavior implementation is
  828. * enabled, this property will contain a fully initialized object that
  829. * corresponds to this behavior implementation. This object is ready for
  830. * use: to query for synonyms or invoke any other methods behavior interface
  831. * declares
  832. * - module: (string) Name of the module that provides this synonyms behavior
  833. * implementation
  834. */
  835. function synonyms_behavior_get($behavior, $entity_type, $bundle, $only_enabled = FALSE) {
  836. $behavior_implementations = array();
  837. $enabled_behavior_implementations = array();
  838. $query = db_select('synonyms_settings', 's');
  839. $query->fields('s');
  840. $query->condition('behavior', $behavior);
  841. $query->condition('entity_type', $entity_type);
  842. $query->condition('bundle', synonyms_bundle_normalize($entity_type, $bundle));
  843. $result = $query->execute();
  844. foreach ($result as $row) {
  845. $row = (array) $row;
  846. if ($only_enabled) {
  847. $behavior_implementations[] = $row;
  848. }
  849. else {
  850. $enabled_behavior_implementations[$row['bundle']][$row['provider']] = $row;
  851. }
  852. }
  853. if (!$only_enabled) {
  854. foreach (synonyms_bundle_normalize($entity_type, $bundle) as $bundle_name) {
  855. foreach (synonyms_behavior_implementation_info($entity_type, $bundle_name, $behavior) as $provider_info) {
  856. if (isset($enabled_behavior_implementations[$bundle_name][$provider_info['provider']])) {
  857. $provider_info['settings_serialized'] = $enabled_behavior_implementations[$bundle_name][$provider_info['provider']]['settings_serialized'];
  858. }
  859. $behavior_implementations[] = $provider_info;
  860. }
  861. }
  862. }
  863. return synonyms_behavior_settings_unpack($behavior_implementations);
  864. }
  865. /**
  866. * Load all enabled behavior implementations on an entity_type and a bundle.
  867. *
  868. * This is useful when you want to do some operation on all enabled behavior
  869. * implementations for a specific entity_type and a bundle.
  870. *
  871. * @param string $entity_type
  872. * Optionally filter by entity type whose enabled behavior implementations
  873. * should be loaded
  874. * @param string|array $bundle
  875. * Optionally filter by bundle whose enabled behavior implementations should
  876. * be loaded. You can supply here string - single bundle name or an array of
  877. * bundle names. Empty array implies all existing bundle names for a provided
  878. * $entity_type
  879. * @param string $provider
  880. * Optional filter to only return enabled synonyms behavior implementations of
  881. * a specific provider
  882. * @param string $behavior
  883. * Optional filter to only return enabled synonyms behavior implementations of
  884. * a specific behavior
  885. *
  886. * @return array
  887. * Array of enabled behavior implementations for a provided entity type and a
  888. * bundle. Return structure of this function is identical to the return
  889. * structure of synonyms_behavior_get()
  890. */
  891. function synonyms_behavior_get_all_enabled($entity_type = NULL, $bundle = array(), $provider = NULL, $behavior = NULL) {
  892. $query = db_select('synonyms_settings', 's');
  893. $query->fields('s');
  894. if ($entity_type) {
  895. $query->condition('entity_type', $entity_type);
  896. $query->condition('bundle', synonyms_bundle_normalize($entity_type, $bundle));
  897. }
  898. if ($provider) {
  899. $query->condition('provider', $provider);
  900. }
  901. if ($behavior) {
  902. $query->condition('behavior', $behavior);
  903. }
  904. $result = $query->execute();
  905. $behavior_implementations = array();
  906. foreach ($result as $row) {
  907. $behavior_implementations[] = (array) $row;
  908. }
  909. return synonyms_behavior_settings_unpack($behavior_implementations);
  910. }
  911. /**
  912. * Retrieve information about all cTools plugins of type 'synonyms behavior'.
  913. *
  914. * @return array
  915. * Array of information on all available synonyms behavior plugins
  916. */
  917. function synonyms_behaviors() {
  918. ctools_include('plugins');
  919. return ctools_get_plugins('synonyms', 'behavior');
  920. }
  921. /**
  922. * Collect info on available synonyms behavior implementations.
  923. *
  924. * @param string $entity_type
  925. * Entity type whose available synonyms behavior implementations to collect
  926. * @param string $bundle
  927. * Bundle whose available synonyms behavior implementations to collect
  928. * @param string $behavior
  929. * Name of behavior whose available synonyms behavior implementations to
  930. * collect
  931. *
  932. * @return array
  933. * Array of available synonyms behavior implementations. Each synonym behavior
  934. * implementation will be an array with the following structure:
  935. * - provider: (string) Machine name of the synonyms behavior implementation
  936. * - label: (string) Human name of the synonyms behavior implementation
  937. * - class: (string) Name of PHP class that implements behavior interface
  938. * which is stated in cTools behavior plugin definition
  939. * - entity_type: (string) Entity type that corresponds to this synonyms
  940. * behavior implementation
  941. * - bundle: (string) Bundle that corresponds to this synonyms behavior
  942. * implementation
  943. * - behavior: (string) Name of behavior that corresponds to this synonyms
  944. * behavior implementation
  945. * - module: (string) Name of the module that provides this synonyms behavior
  946. * implementation
  947. */
  948. function synonyms_behavior_implementation_info($entity_type, $bundle, $behavior) {
  949. $providers = array();
  950. foreach (module_implements('synonyms_behavior_implementation_info') as $module) {
  951. foreach (module_invoke($module, 'synonyms_behavior_implementation_info', $entity_type, $bundle, $behavior) as $provider) {
  952. $provider['entity_type'] = $entity_type;
  953. $provider['behavior'] = $behavior;
  954. $provider['bundle'] = $bundle;
  955. $provider['module'] = $module;
  956. $providers[$provider['provider']] = $provider;
  957. }
  958. }
  959. return $providers;
  960. }
  961. /**
  962. * Execute unpacking on the just loaded synonyms behavior implementations.
  963. *
  964. * @param array $behavior_implementations
  965. * Array of the just loaded behavior_implementations. Each sub array should
  966. * contain the following keys:
  967. * - entity_type: (string) Entity type that corresponds to this behavior
  968. * implementation
  969. * - bundle: (string) Bundle that corresponds to this behavior implementation
  970. * - provider: (string) Machine name of this synonyms behavior implementation
  971. * - behavior: (string) name of the synonyms behavior to which these settings
  972. * apply
  973. * - settings_serialized: (string) serialized content of the settings
  974. *
  975. * @return array
  976. * Unpacked version of the provided $settings
  977. */
  978. function synonyms_behavior_settings_unpack($behavior_implementations) {
  979. // Array of previously queried synonyms provider info.
  980. $cache = array();
  981. foreach ($behavior_implementations as &$behavior_implementation) {
  982. if (!isset($cache[$behavior_implementation['behavior']][$behavior_implementation['entity_type']][$behavior_implementation['bundle']])) {
  983. $cache[$behavior_implementation['behavior']][$behavior_implementation['entity_type']][$behavior_implementation['bundle']] = synonyms_behavior_implementation_info($behavior_implementation['entity_type'], $behavior_implementation['bundle'], $behavior_implementation['behavior']);
  984. }
  985. // Behavior implementation info may be not available in some rare extreme
  986. // cases. For example, when a field instance is being deleted.
  987. if (isset($cache[$behavior_implementation['behavior']][$behavior_implementation['entity_type']][$behavior_implementation['bundle']][$behavior_implementation['provider']])) {
  988. $behavior_implementation += $cache[$behavior_implementation['behavior']][$behavior_implementation['entity_type']][$behavior_implementation['bundle']][$behavior_implementation['provider']];
  989. }
  990. if (isset($behavior_implementation['settings_serialized'])) {
  991. $behavior_implementation['settings'] = unserialize($behavior_implementation['settings_serialized']);
  992. if (isset($behavior_implementation['class'])) {
  993. $class = $behavior_implementation['class'];
  994. $behavior_implementation['object'] = new $class($behavior_implementation);
  995. }
  996. }
  997. }
  998. unset($behavior_implementation);
  999. return $behavior_implementations;
  1000. }
  1001. /**
  1002. * Save the provided synonyms behavior implementation into the database.
  1003. *
  1004. * @param array $behavior_implementation
  1005. * Behavior implementation array, such as one from synonyms_behavior_get() or
  1006. * alike
  1007. */
  1008. function synonyms_behavior_implementation_save($behavior_implementation) {
  1009. if (!isset($behavior_implementation['settings'])) {
  1010. $behavior_implementation['settings'] = array();
  1011. }
  1012. $behavior_implementation['settings_serialized'] = serialize($behavior_implementation['settings']);
  1013. $result = db_merge('synonyms_settings')
  1014. ->key(array(
  1015. 'entity_type' => $behavior_implementation['entity_type'],
  1016. 'bundle' => $behavior_implementation['bundle'],
  1017. 'provider' => $behavior_implementation['provider'],
  1018. 'behavior' => $behavior_implementation['behavior'],
  1019. ))
  1020. ->fields(array(
  1021. 'entity_type' => $behavior_implementation['entity_type'],
  1022. 'bundle' => $behavior_implementation['bundle'],
  1023. 'provider' => $behavior_implementation['provider'],
  1024. 'behavior' => $behavior_implementation['behavior'],
  1025. 'settings_serialized' => $behavior_implementation['settings_serialized'],
  1026. ))
  1027. ->execute();
  1028. switch ($result) {
  1029. case MergeQuery::STATUS_INSERT:
  1030. $behavior_definition = synonyms_behaviors();
  1031. $behavior_definition = $behavior_definition[$behavior_implementation['behavior']];
  1032. $enabled_callback = ctools_plugin_get_function($behavior_definition, 'enabled callback');
  1033. if ($enabled_callback) {
  1034. $enabled_callback($behavior_definition, $behavior_implementation);
  1035. }
  1036. break;
  1037. }
  1038. }
  1039. /**
  1040. * Delete behavior implementation from database.
  1041. *
  1042. * @param array $behavior_implementation
  1043. * Behavior implementation array, such as one from synonyms_behavior_get() or
  1044. * alike
  1045. */
  1046. function synonyms_behavior_implementation_delete($behavior_implementation) {
  1047. $behavior_definition = synonyms_behaviors();
  1048. $behavior_definition = $behavior_definition[$behavior_implementation['behavior']];
  1049. $disabled_callback = ctools_plugin_get_function($behavior_definition, 'disabled callback');
  1050. if ($disabled_callback) {
  1051. foreach (synonyms_behavior_get($behavior_implementation['behavior'], $behavior_implementation['entity_type'], $behavior_implementation['bundle'], TRUE) as $enabled_behavior_implementation) {
  1052. if ($enabled_behavior_implementation['provider'] == $behavior_implementation['provider']) {
  1053. $disabled_callback($behavior_definition, $behavior_implementation);
  1054. break;
  1055. }
  1056. }
  1057. }
  1058. db_delete('synonyms_settings')
  1059. ->condition('provider', $behavior_implementation['provider'])
  1060. ->condition('entity_type', $behavior_implementation['entity_type'])
  1061. ->condition('bundle', $behavior_implementation['bundle'])
  1062. ->condition('behavior', $behavior_implementation['behavior'])
  1063. ->execute();
  1064. }
  1065. /**
  1066. * Convert synonyms friendly select widget values for storage friendly format.
  1067. *
  1068. * It acts similar to what the _options_form_to_storage() function does -
  1069. * bridges between how values are returned from form API to how they are
  1070. * expected by Field module.
  1071. */
  1072. function synonyms_select_form_to_storage($element, &$form_state) {
  1073. $form_state_value = array();
  1074. foreach (drupal_array_get_nested_value($form_state['values'], $element['#parents']) as $entity_id) {
  1075. $form_state_value[] = array($element['#columns'][0] => $entity_id);
  1076. }
  1077. form_set_value($element, $form_state_value, $form_state);
  1078. }
  1079. /**
  1080. * Element validate handler.
  1081. *
  1082. * Convert selected synonyms into their terms and save the updated data in the
  1083. * value of the form element.
  1084. */
  1085. function synonyms_select_validate($element, &$form_state) {
  1086. $value = array();
  1087. if ($element['#multiple']) {
  1088. $value = $element['#value'];
  1089. }
  1090. else {
  1091. $value[] = $element['#value'];
  1092. }
  1093. foreach ($value as $k => $v) {
  1094. // For the cases when a synonym was selected and not an entity option, we
  1095. // process the selected values stripping everything that goes after
  1096. // semicolon.
  1097. if (!is_numeric($v)) {
  1098. $entity_id = explode(':', $v);
  1099. $value[$k] = $entity_id[0];
  1100. }
  1101. }
  1102. // The user also might have selected multiple times the same entity, given
  1103. // that an entity can be represented by more than 1 option (an entity and its
  1104. // synonym), then it's possible in theory, so we should be ready for this
  1105. // scenario.
  1106. $value = array_unique($value);
  1107. form_set_value($element, $value, $form_state);
  1108. }
  1109. /**
  1110. * Check whether a taxonomy term $tid is a child of a taxonomy term $parent_tid.
  1111. *
  1112. * Supportive function, used throughout this module for parent constrains.
  1113. *
  1114. * @param int $tid
  1115. * {taxonomy_term}.tid of the term that is tested for being a child of the
  1116. * $parent_tid term
  1117. * @param int $parent_tid
  1118. * {taxonomy_term}.tid of the term that is tested for being parent of the $tid
  1119. * term
  1120. *
  1121. * @return bool
  1122. * Whether $tid is a child of $parent_tid
  1123. */
  1124. function synonyms_taxonomy_term_is_child_of($tid, $parent_tid) {
  1125. $term_parents = taxonomy_get_parents_all($tid);
  1126. // Dropping out the term itself from its array of parents.
  1127. array_shift($term_parents);
  1128. foreach ($term_parents as $term_parent) {
  1129. if ($term_parent->tid == $parent_tid) {
  1130. return TRUE;
  1131. }
  1132. }
  1133. return FALSE;
  1134. }
  1135. /**
  1136. * Format an option for entity reference select form element.
  1137. *
  1138. * @param object $entity
  1139. * Fully loaded entity which is represented by this option
  1140. * @param string $entity_type
  1141. * Entity type of the $entity object
  1142. * @param string $synonym
  1143. * If the provided entity is represented in this option by a synonym, then
  1144. * provide it here
  1145. * @param array $behavior_implementation
  1146. * Behavior implementation array from which the $synonym comes from
  1147. * @param array $options
  1148. * Array of additional settings or options that may influence execution of
  1149. * this function. Currently supported options are:
  1150. * - depth: Whether to prefix wording of option labels with depth of the
  1151. * entity. This will work only for taxonomy term entities, as they are the
  1152. * only ones that have notion of depth
  1153. *
  1154. * @return object
  1155. * An option for entity reference select form element
  1156. */
  1157. function synonyms_select_option_entity($entity, $entity_type, $synonym = NULL, $behavior_implementation = NULL, $options = array()) {
  1158. $entity_id = entity_extract_ids($entity_type, $entity);
  1159. $entity_id = $entity_id[0];
  1160. $key = $synonym ? $entity_id . ':' . drupal_html_class($synonym) : $entity_id;
  1161. $wording = entity_label($entity_type, $entity);
  1162. if ($synonym) {
  1163. $wording = format_string($behavior_implementation['settings']['wording'], array(
  1164. '@synonym' => $synonym,
  1165. '@entity' => entity_label($behavior_implementation['entity_type'], $entity),
  1166. '@field_name' => drupal_strtolower($behavior_implementation['label']),
  1167. ));
  1168. }
  1169. if (in_array('depth', $options) && $entity_type == 'taxonomy_term') {
  1170. $depth = count(taxonomy_get_parents_all($entity_id)) - 1;
  1171. $wording = str_repeat('-', $depth) . $wording;
  1172. }
  1173. return (object) array(
  1174. 'option' => array($key => $wording),
  1175. );
  1176. }
  1177. /**
  1178. * Construct options array for entity reference synonyms friendly select list.
  1179. *
  1180. * @param array $field
  1181. * Field definition array of entityreference type for which to construct the
  1182. * options
  1183. * @param array $instance
  1184. * Field instance definition array that corresponds to $field
  1185. * @param object $entity
  1186. * If entity is known for which the options should be generated, provide it
  1187. * here. It is safe to omit this parameter. Frankly, I do not understand well
  1188. * why or how it is used. It is just directly passed into entityreference
  1189. * selection handler class
  1190. *
  1191. * @return array
  1192. * Options array that can be plugged in directly into any #select form element
  1193. */
  1194. function synonyms_select_entity_options($field, $instance, $entity = NULL) {
  1195. $options = entityreference_get_selection_handler($field, $instance, $instance['entity_type'], $entity)->getReferencableEntities();
  1196. $synonyms_options = array();
  1197. $target_entity_info = entity_get_info($field['settings']['target_type']);
  1198. $entity_ids = array();
  1199. foreach ($options as $bundle_entity_ids) {
  1200. $entity_ids = array_merge($entity_ids, array_keys($bundle_entity_ids));
  1201. }
  1202. $entities = entity_load($field['settings']['target_type'], $entity_ids);
  1203. foreach ($options as $bundle => $bundle_entity_ids) {
  1204. $synonyms_options[$target_entity_info['bundles'][$bundle]['label']] = array();
  1205. $behavior_implementations = synonyms_behavior_get('select', $field['settings']['target_type'], $bundle, TRUE);
  1206. foreach ($bundle_entity_ids as $entity_id => $v) {
  1207. $entity = $entities[$entity_id];
  1208. $synonyms_options[$target_entity_info['bundles'][$bundle]['label']][] = synonyms_select_option_entity($entity, $field['settings']['target_type']);
  1209. foreach ($behavior_implementations as $behavior_implementation) {
  1210. foreach ($behavior_implementation['object']->extractSynonyms($entity) as $synonym) {
  1211. $synonyms_options[$target_entity_info['bundles'][$bundle]['label']][] = synonyms_select_option_entity($entity, $field['settings']['target_type'], $synonym, $behavior_implementation);
  1212. }
  1213. }
  1214. }
  1215. usort($synonyms_options[$target_entity_info['bundles'][$bundle]['label']], 'synonyms_select_sort_name');
  1216. }
  1217. if (count($synonyms_options) == 1) {
  1218. $synonyms_options = reset($synonyms_options);
  1219. }
  1220. return $synonyms_options;
  1221. }
  1222. /**
  1223. * Supportive function to build taxonomy term options array sorted by name.
  1224. *
  1225. * The function starts from the 0-depth level and starts to recursively build
  1226. * the options and to sort the labels on each level, then it merges the bottom
  1227. * to up all the levels maintaining correct order within the final options
  1228. * array.
  1229. *
  1230. * @param object $vocabulary
  1231. * Within which vocabulary to execute the function. Supply here the fully
  1232. * loaded taxonomy vocabulary object
  1233. * @param int $parent
  1234. * Only children of this term will be included in the output. You can supply
  1235. * 0 which means to include all the terms from the vocabulary
  1236. * @param int $depth
  1237. * Used for internal purposes. Clients of this function should supply here 0,
  1238. * unless they know what they are doing. It is used internally to keep track
  1239. * of the nesting level
  1240. *
  1241. * @return array
  1242. * Array of options that can be inserted directly into 'select' form element.
  1243. * The options will be sorted by name (term or synonym), respecting the
  1244. * hierarchy restrictions
  1245. */
  1246. function synonyms_select_taxonomy_term_sort_name_options_recursive($vocabulary, $parent = 0, $depth = 0) {
  1247. // We statically cache behavior implementations in order to not DDOS the data
  1248. // base.
  1249. $behavior_implementations = &drupal_static(__FUNCTION__, array());
  1250. $bundle = field_extract_bundle('taxonomy_term', $vocabulary);
  1251. if (!isset($behavior_implementations[$bundle])) {
  1252. $behavior_implementations[$bundle] = synonyms_behavior_get('select', 'taxonomy_term', $bundle, TRUE);
  1253. }
  1254. $options = array();
  1255. if ($terms = taxonomy_get_tree($vocabulary->vid, $parent, 1, TRUE)) {
  1256. $options = array();
  1257. foreach ($terms as $term) {
  1258. $term->depth = $depth;
  1259. $options[] = synonyms_select_option_entity($term, 'taxonomy_term', NULL, NULL, array('depth'));
  1260. foreach ($behavior_implementations[$bundle] as $implementation) {
  1261. foreach ($implementation['object']->extractSynonyms($term) as $synonym) {
  1262. $options[] = synonyms_select_option_entity($term, 'taxonomy_term', $synonym, $implementation, array('depth'));
  1263. }
  1264. }
  1265. }
  1266. usort($options, 'synonyms_select_sort_name');
  1267. // Now recursively go one level nested into each of the terms that we have
  1268. // on this level.
  1269. $options_copy = $options;
  1270. $i = 0;
  1271. foreach ($options_copy as $v) {
  1272. $i++;
  1273. $tid = array_keys($v->option);
  1274. $tid = $tid[0];
  1275. if (is_numeric($tid)) {
  1276. $nested_options = synonyms_select_taxonomy_term_sort_name_options_recursive($vocabulary, $tid, $depth + 1);
  1277. $options = array_merge(array_slice($options, 0, $i), $nested_options, array_slice($options, $i));
  1278. }
  1279. }
  1280. }
  1281. return $options;
  1282. }
  1283. /**
  1284. * Supportive function.
  1285. *
  1286. * It is used for string comparison within synonyms friendly select widget.
  1287. */
  1288. function synonyms_select_sort_name($a, $b) {
  1289. return strcasecmp(reset($a->option), reset($b->option));
  1290. }
  1291. /**
  1292. * Test if entity type is applicable for having synonyms.
  1293. *
  1294. * @param string $entity_type
  1295. * Entity type to test
  1296. *
  1297. * @return bool|string
  1298. * Whether the provided entity type is applicable for having synonyms. If it
  1299. * is applicable, the $entity_type input argument will be returned. Otherwise
  1300. * FALSE is returned
  1301. */
  1302. function synonyms_entity_type_load($entity_type) {
  1303. if (module_exists('synonyms_provider_property')) {
  1304. // If this submodule is enabled, we get into infinite recursion. Moreover,
  1305. // it is very likely all entity types will have at least 1 property on them,
  1306. // so the synonyms_provider_property module will get at least 1 synonym for
  1307. // every entity type. So it is quite safe assumption to say we accept about
  1308. // any entity type.
  1309. return $entity_type;
  1310. }
  1311. $bundles = synonyms_bundle_normalize($entity_type, array());
  1312. foreach (synonyms_behaviors() as $behavior => $behavior_definition) {
  1313. foreach ($bundles as $bundle) {
  1314. $behavior_implementations = synonyms_behavior_implementation_info($entity_type, $bundle, $behavior);
  1315. if (!empty($behavior_implementations)) {
  1316. return $entity_type;
  1317. }
  1318. }
  1319. }
  1320. return FALSE;
  1321. }
  1322. /**
  1323. * Test if provided entity type and bundle are applicable for having synonyms.
  1324. *
  1325. * @param string $bundle
  1326. * Bundle name to test for ability to have synonyms
  1327. * @param string $entity_type
  1328. * Entity type to test for ability to have synonyms
  1329. *
  1330. * @return bool|string
  1331. * Whether the provided entity type and bundle may have synonyms. If they do,
  1332. * the $bundle input argument is returned. Otherwise FALSE is returned
  1333. */
  1334. function synonyms_bundle_load($bundle, $entity_type) {
  1335. foreach (synonyms_behaviors() as $behavior => $behavior_definition) {
  1336. $behavior_implementations = synonyms_behavior_implementation_info($entity_type, $bundle, $behavior);
  1337. if (!empty($behavior_implementations)) {
  1338. return $bundle;
  1339. }
  1340. }
  1341. return FALSE;
  1342. }
  1343. /**
  1344. * Menu title callback function for synonyms settings page.
  1345. *
  1346. * @param string $entity_type
  1347. * Entity type whose synonyms settings are managed
  1348. * @param string $bundle
  1349. * Bundle whose synonyms settings are managed
  1350. *
  1351. * @return string
  1352. * Title of the synonyms settings page
  1353. */
  1354. function synonyms_settings_title($entity_type, $bundle) {
  1355. $entity_info = entity_get_info($entity_type);
  1356. $entity_label = isset($entity_info['plural label']) ? $entity_info['plural label'] : $entity_info['label'];
  1357. if ($entity_type == $bundle) {
  1358. return t('Synonyms settings of @entity_type', array(
  1359. '@entity_type' => $entity_label,
  1360. ));
  1361. }
  1362. return t('Synonyms settings of @bundle @entity_type', array(
  1363. '@bundle' => $entity_info['bundles'][$bundle]['label'],
  1364. '@entity_type' => $entity_label,
  1365. ));
  1366. }
  1367. /**
  1368. * Escape string to safely use in autocomplete text field as default value.
  1369. *
  1370. * @param string $value
  1371. * String to be escaped
  1372. *
  1373. * @return string
  1374. * Escaped string $value
  1375. */
  1376. function synonyms_autocomplete_escape($value) {
  1377. // Commas or quotes must be wrapped in quotes.
  1378. if (strpos($value, ',') !== FALSE || strpos($value, '"') !== FALSE) {
  1379. $value = '"' . str_replace('"', '""', $value) . '"';
  1380. }
  1381. return $value;
  1382. }
  1383. /**
  1384. * Determine a list of target bundles of an entityreference field.
  1385. *
  1386. * @param array $field
  1387. * Field definition array. This field must be of type 'entityreference'
  1388. *
  1389. * @return array|null
  1390. * List of target bundles per the settings of provided field or NULL if the
  1391. * provided field does not expose any limitations on target bundles
  1392. */
  1393. function synonyms_field_target_bundles($field) {
  1394. $target_bundles = isset($field['settings']['handler_settings']['target_bundles']) ? array_values($field['settings']['handler_settings']['target_bundles']) : array();
  1395. if (empty($target_bundles)) {
  1396. $target_bundles = NULL;
  1397. }
  1398. return $target_bundles;
  1399. }
  1400. /**
  1401. * Normalize bundle argument.
  1402. *
  1403. * @param string $entity_type
  1404. * Entity type to define scope of bundles
  1405. * @param string|array $bundle
  1406. * Either a single bundle name or an array of bundle names. Empty array
  1407. * implies all known bundles for $entity_type
  1408. *
  1409. * @return array
  1410. * Normalized array bundle names
  1411. */
  1412. function synonyms_bundle_normalize($entity_type, $bundle) {
  1413. $bundle = (array) $bundle;
  1414. if (empty($bundle)) {
  1415. $bundle = array_keys(field_info_bundles($entity_type));
  1416. }
  1417. return $bundle;
  1418. }
  1419. /**
  1420. * Extract default value for a select widget of Synonyms module.
  1421. *
  1422. * @param array $field
  1423. * Field definition array whose default value should be extracted
  1424. * @param array $instance
  1425. * Field instance definition array whose default value should be extracted
  1426. * @param array $items
  1427. * Array of items that should compose default value
  1428. *
  1429. * @return array
  1430. * Array of default value that can be plugged in into a select widget
  1431. */
  1432. function synonyms_select_default_value($field, $instance, $items) {
  1433. $default_value = array();
  1434. $column = array_keys($field['columns']);
  1435. $column = reset($column);
  1436. foreach ($items as $item) {
  1437. $default_value[] = $item[$column];
  1438. }
  1439. return $default_value;
  1440. }