synonyms.module 57 KB

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