materio_search_api.pages.inc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. <?php
  2. /**
  3. * materiobase_search_autocomplete_dbselect()
  4. *
  5. * inspired by taxonomy_autocomplete()
  6. *
  7. * OBSOLETE : this fonction use a direct dbselect request to provide results forautocomplete
  8. *
  9. */
  10. function materio_search_api_autocomplete_dbselect($typed = ''){
  11. // If the request has a '/' in the search text, then the menu system will have
  12. // split it into multiple arguments, recover the intended $tags_typed.
  13. $args = func_get_args();
  14. $typed = implode('/', $args);
  15. /*
  16. TODO riche serach engine + \\ etc gmail like
  17. */
  18. if ($typed != '') {
  19. // Part of the criteria for the query come from the field's own settings.
  20. $vids = array();
  21. $vocabularies = taxonomy_vocabulary_get_names();
  22. foreach ($vocabularies as $voc) {
  23. $vids[] = $voc->vid;
  24. }
  25. $query = db_select('taxonomy_term_data', 't');
  26. $query->addTag('translatable');
  27. $query->addTag('term_access');
  28. // Select rows that match by term name.
  29. $tags_return = $query
  30. ->fields('t', array('tid', 'name'))
  31. ->condition('t.vid', $vids)
  32. ->condition('t.name', '%' . db_like($typed) . '%', 'LIKE')
  33. ->range(0, 10)
  34. ->execute()
  35. ->fetchAllKeyed();
  36. $term_matches = array();
  37. foreach ($tags_return as $tid => $name) {
  38. $n = $name;
  39. // Term names containing commas or quotes must be wrapped in quotes.
  40. // if (strpos($name, ',') !== FALSE || strpos($name, '"') !== FALSE) {
  41. // $n = '"' . str_replace('"', '""', $name) . '"';
  42. // }
  43. $term_matches[$n] = check_plain($name);
  44. }
  45. }
  46. drupal_json_output($term_matches);
  47. }
  48. /**
  49. * materio_search_api_autocomplete_searchapi($typed = '')
  50. *
  51. * GOOD one using searchapi (SOLR)
  52. */
  53. function materio_search_api_autocomplete_searchapi($typed = ''){
  54. // If the request has a '/' in the search text, then the menu system will have
  55. // split it into multiple arguments, recover the intended $tags_typed.
  56. $args = func_get_args();
  57. $typed = implode('/', $args);
  58. // dsm($typed, 'typed');
  59. if ($typed != '') {
  60. // search for patterns like key -another key +lastkey
  61. // and provide auto completion for the last key
  62. preg_match_all('/\s?[\+|-]?[^\s]+/', $typed, $adv_search_q);
  63. preg_match('/^(\+|-)?(.*)$/', trim(array_pop($adv_search_q[0])), $last);
  64. $tosearch = isset($last[2]) ? $last[2] : $typed;
  65. // build the query
  66. $index_machine_name = variable_get('autocompletesearchindex', -1);
  67. $query = search_api_query($index_machine_name);
  68. // $query_filter = $query->createFilter();
  69. // $query_filter->condition('name', $tosearch);
  70. // $query_filter->condition('type', 'article');
  71. // $query->filter($query_filter);
  72. $query->keys($tosearch);
  73. $tags_return = $query->execute();
  74. // dsm($tags_return, '$tags_return');
  75. if($tags_return['result count']){
  76. $term_matches = array();
  77. $index = search_api_index_load($index_machine_name);
  78. $delta = 0;
  79. foreach ($index->loadItems(array_keys($tags_return['results'])) as $item) {
  80. //dsm($item, '$item');
  81. //$term_matches[$item->tid] = check_plain($item->name);
  82. // $term_matches[check_plain($item->name)] = check_plain($item->name);
  83. // TODO: leave tags with nodes
  84. $term_matches[ trim(implode(' ', $adv_search_q[0]).' '.$last[1].$item->name)] = check_plain($item->name);
  85. $delta++;
  86. if($delta > 7)
  87. break;
  88. }
  89. drupal_json_output($term_matches);
  90. }else{
  91. drupal_json_output(array());
  92. }
  93. }else{
  94. return;
  95. }
  96. // dsm($term_matches, 'term_matches');
  97. // return 'debug mode of materio_search_api_autocomplete_searchapi';
  98. }
  99. /**
  100. * materio_search_api_results_search()
  101. *
  102. *
  103. */
  104. function materio_search_api_results_search(){
  105. global $user;
  106. //dsm("materio_search_api_results_search");
  107. $args = func_get_args();
  108. $typed = implode('/', $args);
  109. // dsm($typed, 'typed');
  110. preg_match_all('/\?page=([0-9]+)/', $typed, $pages);
  111. //dsm($pages, '$pages');
  112. if($pages[0]){
  113. $typed = str_replace($pages[0][0], '', $typed);
  114. // $page = $pages[1][0];
  115. }
  116. // else{
  117. // $page = 0;
  118. // }
  119. preg_match_all('/\s?[^\s]+\s?/', $typed, $words);
  120. // dsm($words, "words");
  121. // $match = array('\\', '+', '-', '&', '|', '!', '(', ')', '{', '}', '[', ']', '^', '~', '*', '?', ':', '"', ';', ' ');
  122. // $replace = array('\\\\', '\\+', '\\-', '\\&', '\\|', '\\!', '\\(', '\\)', '\\{', '\\}', '\\[', '\\]', '\\^', '\\~', '\\*', '\\?', '\\:', '\\"', '\\;', '\\ ');
  123. foreach ($words[0] as $word) {
  124. // dsm($word);
  125. $word = trim($word);
  126. // $word = str_replace($match, $replace, $word);
  127. // dsm($word, 'word');
  128. $keys[] = $word;
  129. }
  130. // dsm($keys, 'keys');
  131. $index_machine_name = variable_get('mainsearchindex', -1);
  132. $index = search_api_index_load($index_machine_name);
  133. $indexed_bundles = $index->options['data_alter_callbacks']['search_api_alter_bundle_filter']['settings']['bundles'];
  134. foreach ($indexed_bundles as $bundle) {
  135. $default_bundles[] = $bundle;
  136. }
  137. $bundles_filter = isset($user->data['materiosearchapi_bundlesfilter']) ? $user->data['materiosearchapi_bundlesfilter'] : $default_bundles;
  138. // dsm($bundles_filter, 'bundles_filter');
  139. $viewmode = isset($user->data['materiosearchapi_viewmode']) ? $user->data['materiosearchapi_viewmode'] : variable_get('defaultviewmode', 'full');
  140. if ($keys) {
  141. // TODO: cache the results with cache graceful : http://drupal.org/project/cache_graceful
  142. try {
  143. $limit = variable_get($viewmode.'_limite', '10');
  144. $offset = pager_find_page() * $limit; //$page*$limit;//
  145. $query = search_api_query($index_machine_name, array('conjunction'=>'OR', 'parse mode'=>'direct'))
  146. ->keys(implode(' ', $keys))
  147. ->range($offset, $limit);
  148. $filter = $query->createFilter('OR');
  149. foreach ($bundles_filter as $type) {
  150. $filter->condition('type', $type, '=');
  151. }
  152. // dsm($filter, 'filter');
  153. $query->filter($filter);
  154. $results = $query->execute();
  155. }
  156. catch (SearchApiException $e) {
  157. $ret['message'] = t('An error occurred while executing the search. Please try again or contact the site administrator if the problem persists.');
  158. watchdog('materiobasemod', 'An error occurred while executing a search: !msg.', array('!msg' => $e->getMessage()), WATCHDOG_ERROR, l(t('search page'), $_GET['q']));
  159. }
  160. // dsm($results, 'results');
  161. // $accessible_results = array();
  162. // foreach ($results['results'] as $nid => $entity) {
  163. // if(node_access('view', node_load($nid)))
  164. // $accessible_results[$nid] = $entity;
  165. // }
  166. // $results['results'] = $accessible_results;
  167. // $results['result count'] = count($accessible_results);
  168. # Load spellcheck.
  169. // if (isset($results['search_api_spellcheck'])) {
  170. // $ret['results']['#spellcheck'] = array(
  171. // '#theme' => 'search_api_spellcheck',
  172. // '#spellcheck' => $results['search_api_spellcheck'],
  173. // // Let the theme function know where the key is stored by passing its arg
  174. // // number. We can work this out from the number of args in the page path.
  175. // '#options' => array(
  176. // 'arg' => array(count(arg(NULL, $page->path))),
  177. // ),
  178. // '#prefix' => '<p class="search-api-spellcheck suggestion">',
  179. // '#suffix' => '</p>',
  180. // );
  181. // }
  182. $ret['results']['#theme'] = 'materio_search_api_results';
  183. /*
  184. TODO choose index in module settings
  185. */
  186. $ret['results']['#index'] = search_api_index_load('materiaux_breves');
  187. $ret['results']['#results'] = $results;
  188. $ret['results']['#view_mode'] = $viewmode;
  189. $ret['results']['#keys'] = $keys;
  190. drupal_set_title('<i class="icon-materio-search"></i>'.check_plain($typed), PASS_THROUGH);
  191. // Load pager.
  192. // if ($results['result count'] > $page->options['per_page']) {
  193. pager_default_initialize($results['result count'], $limit);
  194. $ret['results']['#pager'] = theme('pager');
  195. // }
  196. if (!empty($results['ignored'])) {
  197. drupal_set_message(
  198. t('The following search keys are too short or too common and were therefore ignored: "@list".',
  199. array( '@list' => implode(t('", "'), $results['ignored']) ) ),
  200. 'warning'
  201. );
  202. }
  203. if (!empty($results['warnings'])) {
  204. foreach ($results['warnings'] as $warning) {
  205. drupal_set_message($warning, 'warning');
  206. }
  207. }
  208. }
  209. return $ret;
  210. }
  211. /**
  212. * materio_search_api_actuality()
  213. *
  214. */
  215. function materio_search_api_actuality(){
  216. global $user;
  217. if(!user_access('use materio search api')){
  218. $date = strtotime('-6 month');
  219. // dsm($date);
  220. }
  221. $viewmode = isset($user->data['materiosearchapi_viewmode']) ? $user->data['materiosearchapi_viewmode'] : variable_get('defaultviewmode', 'full');
  222. $limit = 10;//variable_get($viewmode.'_limite', '10');
  223. $offset = pager_find_page() * $limit;
  224. // dsm($offset);
  225. $query = new EntityFieldQuery;
  226. $query
  227. ->entityCondition('entity_type', 'node')
  228. ->propertyCondition('status', 1)
  229. ->entityCondition('bundle', array('breve'))
  230. ->propertyOrderBy('created', 'DESC')
  231. ->range($offset,$limit);
  232. if(!user_access('use materio search api')){
  233. $query->propertyCondition('created', $date, '>');
  234. }
  235. $result = $query->execute();
  236. // dsm($result, '$result');
  237. $count_query = new EntityFieldQuery;
  238. $count_query
  239. ->entityCondition('entity_type', 'node')
  240. ->propertyCondition('status', 1)
  241. ->entityCondition('bundle', array('breve'));
  242. // dsm($count, 'count');
  243. if(!user_access('use materio search api')){
  244. $count_query->propertyCondition('created', $date, '>');
  245. }
  246. $count = $count_query->count()->execute();
  247. pager_default_initialize($count, $limit);
  248. foreach ($result['node'] as $nid => $n) {
  249. $breve = node_load($nid);
  250. if(!node_access('view', $breve))
  251. continue;
  252. $items[] = $breve;
  253. $materiaux = field_get_items('node',$breve,'field_materiau_ref');
  254. // dsm($materiaux, 'materiaux');
  255. if($materiaux){
  256. foreach ($materiaux as $value) {
  257. $materiau = node_load($value['target_id']);
  258. if(node_access('view', $materiau))
  259. $items[] = $materiau;
  260. }
  261. }
  262. }
  263. // drupal_set_title(t('Actualities'));
  264. drupal_set_title(t(''));
  265. return theme('materio_search_api_actuality', array(
  266. 'items' => $items,
  267. 'view_mode' => $viewmode,
  268. 'count' => $count,
  269. 'pager' => theme('pager'),
  270. ));
  271. }
  272. function materio_search_api_viewmode_change($vm){
  273. //dsm($vm, 'materio_search_api_viewmode_change');
  274. $rep = _materio_search_api_change_viewmode($vm);
  275. //return 'debug mode for materio_search_api_viewmode_change';
  276. // drupal_json_output($rep);
  277. drupal_goto();
  278. }