materio_search_api.pages.inc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  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. // dsm($adv_search_q, "adv_search_q");
  64. preg_match('/^(\+|-)?(.*)$/', trim(array_pop($adv_search_q[0])), $last);
  65. // dsm($last, "last");
  66. $tosearch = isset($last[2]) ? $last[2] : $typed;
  67. // build the query
  68. global $language;
  69. $index_machine_name = variable_get('autocompletesearchindex_'.$language->language, -1);
  70. $query = search_api_query($index_machine_name);
  71. // $query_filter = $query->createFilter();
  72. // $query_filter->condition('name', $tosearch);
  73. // $query_filter->condition('type', 'article');
  74. // $query->filter($query_filter);
  75. $query->keys($tosearch);
  76. $tags_return = $query->execute();
  77. // dsm($tags_return, '$tags_return');
  78. if($tags_return['result count']){
  79. $term_matches = array();
  80. $index = search_api_index_load($index_machine_name);
  81. $delta = 0;
  82. foreach ($index->loadItems(array_keys($tags_return['results'])) as $item) {
  83. //dsm($item, '$item');
  84. //$term_matches[$item->tid] = check_plain($item->name);
  85. // $term_matches[check_plain($item->name)] = check_plain($item->name);
  86. // TODO: leave tags with nodes
  87. $itemname = $item->name;
  88. $term_matches[trim(implode(' ', $adv_search_q[0]).' "'.$last[1].$itemname).'"'] = check_plain($itemname);
  89. $delta++;
  90. if($delta > 15)
  91. break;
  92. }
  93. drupal_json_output($term_matches);
  94. }else{
  95. drupal_json_output(array());
  96. }
  97. }else{
  98. return;
  99. }
  100. // dsm($term_matches, 'term_matches');
  101. // return 'debug mode of materio_search_api_autocomplete_searchapi';
  102. }
  103. /**
  104. * materio_search_api_results_search()
  105. *
  106. *
  107. */
  108. function materio_search_api_results_search(){
  109. //dsm("materio_search_api_results_search");
  110. // retreive typed words separated by slashes as a sentence
  111. $args = func_get_args();
  112. // dsm($args, 'materio_search_api_results_search :: args');
  113. $filters_search = false;
  114. if(isset($args[0]) && $args[0] == "filters"){
  115. $filters_search = array_shift($args);
  116. }
  117. $keys = $args;
  118. // $keys = explode(' ',implode(' ',$args));
  119. // dsm($keys, 'keys');
  120. $typed = implode(' ', $keys);
  121. // dsm($typed, 'typed');
  122. # with parse mode terms we use a single string of words seperated by spaces wich will be OR or AND regarding the conjunction query option
  123. # had to add q.op = OR on solr requesthandler on solrconfig.xml
  124. // remove query page params
  125. preg_match_all('/\?page=([0-9]+)/', $typed, $pages);
  126. //dsm($pages, '$pages');
  127. if($pages[0]){
  128. $typed = str_replace($pages[0][0], '', $typed);
  129. }
  130. // dsm($typed, 'typed');
  131. if ($typed) {
  132. global $language;
  133. global $user;
  134. # retrieve viewmode and then use it to define the query range
  135. $viewmode = isset($user->data['materiosearchapi_viewmode'])
  136. ? $user->data['materiosearchapi_viewmode']
  137. : variable_get('defaultviewmode', 'full');
  138. $limit = variable_get($viewmode.'_limite', '10');
  139. // dsm($limit, "limit");
  140. $offset = pager_find_page() * $limit; //$page*$limit;//
  141. // dsm($offset, "offset");
  142. # Normal search
  143. if(user_access('use materio search api')){
  144. // dsm('normal search');
  145. // TODO: this two following functions calls should be merged, it's not clean as it is
  146. if(!$filters_search){
  147. $results = msa_solrquery_materiauxbreves($typed, $language, $user, $offset, $limit);
  148. }else{
  149. $results = msa_solrquery_filterssearch($typed, $language, $user, $offset, $limit);
  150. }
  151. }
  152. # only breves search (+ related materials)
  153. # not used anymore as free users not exists anymore
  154. else if(user_access('use materio search api for breves')){
  155. // dsm('limited search');
  156. $results = msa_solrquery_breves($typed, $language, $user, $offset, $limit);
  157. }
  158. // for all case
  159. $ret['results']['#results'] = $results;
  160. $ret['results']['#items'] = $results['items'];
  161. // $ret['results']['#index'] = $results['index'];
  162. $ret['results']['#theme'] = 'materio_search_api_results';
  163. $ret['results']['#keys'] = $typed;
  164. $ret['results']['#view_mode'] = $viewmode;
  165. // page title
  166. $page_title = $typed;
  167. drupal_set_title('<i class="icon-materio-search"></i>'.check_plain($page_title), PASS_THROUGH);
  168. // render results
  169. if(isset($results)){
  170. // Load pager.
  171. // if ($results['result count'] > $page->options['per_page']) {
  172. pager_default_initialize($results['result count'], $limit);
  173. $ret['results']['#pager'] = theme('pager');
  174. // }
  175. if (!empty($results['ignored'])) {
  176. drupal_set_message(
  177. t('The following search keys are too short or too common and were therefore ignored: "@list".',
  178. array( '@list' => implode(t('", "'), $results['ignored']) ) ),
  179. 'warning'
  180. );
  181. }
  182. if (!empty($results['warnings'])) {
  183. foreach ($results['warnings'] as $warning) {
  184. drupal_set_message($warning, 'warning');
  185. }
  186. }
  187. }
  188. }
  189. // dsm($ret, 'ret');
  190. return $ret;
  191. }
  192. function msa_solrquery_materiauxbreves($keys, $language, $user, $offset, $limit){
  193. // dsm($offset, 'offset');
  194. // dsm($limit, 'limit');
  195. // -- communs --//
  196. # define default bundle option (materiaux, breves)
  197. $default_bundles = array();
  198. // TODO: this can't work as $taxo_index is not defined yet
  199. if(isset($taxo_index->options['data_alter_callbacks']['search_api_alter_bundle_filter']['settings']['bundles'])){
  200. $indexed_bundles = $taxo_index->options['data_alter_callbacks']['search_api_alter_bundle_filter']['settings']['bundles'];
  201. foreach ($indexed_bundles as $bundle) { $default_bundles[] = $bundle; }
  202. }
  203. # choose solr query bundle option
  204. $bundles_filter = isset($user->data['materiosearchapi_bundlesfilter'])
  205. ? $user->data['materiosearchapi_bundlesfilter']
  206. : $default_bundles;
  207. // -- -- taxo search AND -- -- //
  208. # define search api solr index
  209. $taxo_index_machine_name = variable_get('taxonomysearchindex_'.$language->language, -1);
  210. $taxo_index = search_api_index_load($taxo_index_machine_name);
  211. # choose solr query options
  212. $query_options = array('conjunction'=>'AND', 'parse mode'=>'terms');
  213. #create the solr query for taxonomy search
  214. $taxo_query = search_api_query($taxo_index_machine_name, $query_options)
  215. ->keys($keys);
  216. # apply bundle options to solr query if usefull
  217. if(count($bundles_filter)){
  218. $filter = $taxo_query->createFilter('OR');
  219. foreach ($bundles_filter as $type)
  220. $filter->condition('type', $type, '=');
  221. $taxo_query->filter($filter);
  222. }
  223. // $query->setOption('search_api_bypass_access', true);
  224. # add user access solr query option
  225. $taxo_query->setOption('search_api_access_account', $user);
  226. // $taxo_query->setOption('q.op', 'OR');
  227. #execute first time to get the all items, to be able to filter the full text research
  228. $taxo_total_results = $taxo_query->execute();
  229. // dsm($taxo_total_results, "taxo total results");
  230. $return = array(
  231. "results" => $taxo_total_results['results']
  232. );
  233. // -- -- full text search -- -- //
  234. #define search api solr index
  235. $fulltxt_index_machine_name = variable_get('fulltextsearchindex_'.$language->language, -1);
  236. $fulltxt_index = search_api_index_load($fulltxt_index_machine_name);
  237. # choose solr query options
  238. $query_options = array('conjunction'=>'OR', 'parse mode'=>'terms');
  239. #create the solr query for taxonomy search
  240. $fulltxt_query = search_api_query($fulltxt_index_machine_name, $query_options)
  241. ->keys($keys);
  242. # apply bundle options to solr query if usefull
  243. if(count($bundles_filter)){
  244. $filter = $fulltxt_query->createFilter('OR');
  245. foreach ($bundles_filter as $type)
  246. $filter->condition('type', $type, '=');
  247. $fulltxt_query->filter($filter);
  248. }
  249. # filter to remove precedent search query
  250. $nid_filter = $fulltxt_query->createFilter('AND');
  251. foreach ($results['results'] as $nid => $item)
  252. $nid_filter->condition('nid', $nid, '<>');
  253. $fulltxt_query->filter($nid_filter);
  254. # add user access solr query option
  255. $fulltxt_query->setOption('search_api_access_account', $user);
  256. # execute solr query and record results
  257. $fulltxt_results = $fulltxt_query->execute();
  258. // dsm($fulltxt_results, "fulltxt_results");
  259. // -- -- merge taxo and full text search -- -- //
  260. # add the fulltext search results to the global results
  261. $return['results'] += $fulltxt_results['results'];
  262. # count global results
  263. $return['result count'] = count($return['results']);
  264. # create items array with the good range
  265. $return['items'] = array();
  266. $o = -1;
  267. foreach ($return['results'] as $nid => $value) {
  268. $o++;
  269. if( $o < $offset ) continue;
  270. if ($o >= $offset+$limit) break;
  271. $return['items'][$nid] = node_load($nid);
  272. }
  273. # TODO: cache the results with cache graceful : http://drupal.org/project/cache_graceful
  274. // dsm($return, 'return');
  275. return $return;
  276. }
  277. function msa_solrquery_filterssearch($keys, $language, $user, $offset, $limit){
  278. // dsm($keys, "keys");
  279. $keys = explode("+", $keys);
  280. foreach ($keys as $value) {
  281. $tids[] = intval($value);
  282. }
  283. // dsm($tids, "tids");
  284. // dsm($offset, 'offset');
  285. // dsm($limit, 'limit');
  286. // init empty results array in wich we will concaten different queries
  287. $return = array(
  288. "results" => array()
  289. );
  290. # define search api solr index
  291. $advancedsearch_index_machine_name = variable_get('advancedsearchindex_'.$language->language, -1);
  292. // dsm($advancedsearch_index_machine_name);
  293. $taxo_index = search_api_index_load($advancedsearch_index_machine_name);
  294. # choose solr query options
  295. $query_options = array('conjunction'=>'AND');
  296. // get searchable field names and run one by one the search
  297. // eventualy concat all results
  298. $fields = msa_get_custom_onto_taxo_searchable_fields();
  299. // run a search for each tag (results will be intersected later)
  300. foreach ($tids as $i => $tid) {
  301. $tmps_results[$i] = array();
  302. // run a search for a tag for each field
  303. foreach ($fields['tid'] as $field) {
  304. # create the solr query for taxonomy search
  305. $query = search_api_query($advancedsearch_index_machine_name, $query_options);
  306. // ->keys("*:*");
  307. // ->range($offset, $limit);
  308. // https://www.drupal.org/node/2596523
  309. $filter = $query->createFilter('AND');
  310. $filter->condition($field['name'], $tid);
  311. $query->filter($filter);
  312. # add user access solr query option
  313. $query->setOption('search_api_access_account', $user);
  314. // $query->setOption('search_api_bypass_access', true);
  315. # execute
  316. $results = $query->execute();
  317. // dsm($results, "results");
  318. // concat each field results for one tag
  319. $tmps_results[$i] += $results['results'];
  320. }
  321. }
  322. // dsm($tmps_results, "tmp_resuslts");
  323. // do the intersect and score routine
  324. if (count($tmps_results) > 1) {
  325. // if we have more than one tag
  326. $results_intersected = array_intersect_key($tmps_results[0], $tmps_results[1]);
  327. if(count($tmps_results > 2)){
  328. // if we have more than 2 tags
  329. for ($i=2; $i < count($tmps_results); $i++) {
  330. $results_intersected = array_intersect_key($results_intersected, $tmps_results[$i]);
  331. }
  332. }
  333. // dsm($results_intersected, 'results_intersected');
  334. foreach ($results_intersected as $tid => $v) {
  335. $scores = array();
  336. for ($j=0; $j < count($tmps_results); $j++) {
  337. $i = 0;
  338. foreach ($tmps_results[$j] as $key => $vv) {
  339. if ($tid === $key) {
  340. $scores[] = $i;
  341. break;
  342. }
  343. $i++;
  344. }
  345. }
  346. $results_intersected[$tid]['score'] = array_sum($scores) / count($scores);
  347. }
  348. uasort($results_intersected, "msa_cmp_filtered_results");
  349. // dsm($results_intersected, 'results_intersected scored');
  350. }
  351. $return['results'] = $results_intersected;
  352. # count global results
  353. $return['result count'] = count($results_intersected);
  354. # create items array with the good range
  355. $return['items'] = array();
  356. $o = -1;
  357. foreach ($return['results'] as $nid => $value) {
  358. $o++;
  359. if( $o < $offset ) continue;
  360. if ($o >= $offset+$limit) break;
  361. $return['items'][$nid] = node_load($nid);
  362. }
  363. # TODO: cache the results with cache graceful : http://drupal.org/project/cache_graceful
  364. // dsm($return, 'return');
  365. return $return;
  366. }
  367. function msa_cmp_filtered_results($a, $b){
  368. // dsm($a, "a");
  369. // dsm($b, "b");
  370. if ($a['score'] == $b['score']) {
  371. return 0;
  372. }
  373. return ($a['score'] < $b['score']) ? -1 : 1;
  374. }
  375. # not used anymore as free users not exists anymore
  376. function msa_solrquery_breves($typed, $language, $user, $offset, $limit){
  377. $index_machine_name = variable_get('brevessearchindex_'.$language->language, -1);
  378. // dsm($index_machine_name, '$index_machine_name');
  379. $index = search_api_index_load($index_machine_name);
  380. # choose solr query options
  381. $query_options = array('conjunction'=>'OR', 'parse mode'=>'direct');
  382. #create the solr query
  383. $query = search_api_query($index_machine_name, $query_options)
  384. ->keys($typed)
  385. ->range($offset, $limit);
  386. // $query->setOption('search_api_bypass_access', true);
  387. # add user access solr query option
  388. $query->setOption('search_api_access_account', $user);
  389. # execute solr query and record results
  390. $results = $query->execute();
  391. // dsm($results, 'results');
  392. $results['index'] = $index;//search_api_index_load($index_machine_name);
  393. #could
  394. $could_index_machine_name = variable_get('fulltextsearchindex_'.$language->language, -1);
  395. $could_index = search_api_index_load($could_index_machine_name);
  396. # in case of free user search, run a real search to indicate how much items you could find
  397. $could_query = search_api_query($could_index_machine_name, array('conjunction'=>'OR', 'parse mode'=>'direct'))
  398. ->keys($typed);
  399. $could_results = $could_query->execute();
  400. // dsm($could_results, 'could_results');
  401. $results['could results'] = $could_results;
  402. # add items : breve + materials wich are in the could result
  403. $items = array();
  404. $breves = $index->loadItems(array_keys($results['results']));
  405. foreach ($breves as $nid => $breve) {
  406. if(!node_access('view', $breve))
  407. continue;
  408. $items[] = $breve;
  409. $materiaux = field_get_items('node',$breve,'field_materiau_ref');
  410. // dsm($materiaux, 'materiaux');
  411. if($materiaux){
  412. foreach ($materiaux as $value) {
  413. if(!isset($could_results['results'][$value['target_id']]))
  414. continue;
  415. $materiau = node_load($value['target_id']);
  416. if(node_access('view', $materiau))
  417. $items[] = $materiau;
  418. }
  419. }
  420. }
  421. $results['items'] = $items;
  422. $results['breves count'] = $results['result count'];
  423. $results['result count'] = count($items);
  424. // dsm($results, "results");
  425. # TODO: cache the results with cache graceful : http://drupal.org/project/cache_graceful
  426. return $results;
  427. }
  428. /**
  429. * materio_search_api_actuality()
  430. *
  431. */
  432. # only breves search (+ related materials)
  433. # NOT USED ANYMORE as free users not exists anymore
  434. function materio_search_api_actuality(){
  435. global $user;
  436. $useraccess = !isset($user->roles[10]) // student
  437. && !isset($user->roles[11]) // alphatesteur
  438. && !isset($user->roles[6]) // adherent
  439. && !isset($user->roles[8]) // premium
  440. && !isset($user->roles[12]) // translator
  441. && !isset($user->roles[13]) // admin showroom
  442. && !isset($user->roles[3]) // admin
  443. && !isset($user->roles[4]); // root
  444. if($useraccess){
  445. $date_limit = strtotime('-4 month');
  446. // dsm(date('d m y', $date_limit));
  447. }
  448. # retrieve viewmode and then use it to define the query range
  449. $viewmode = user_access('access to materio database')
  450. ? isset($user->data['materiosearchapi_viewmode'])
  451. ? $user->data['materiosearchapi_viewmode']
  452. : variable_get('defaultviewmode', 'cardmedium')
  453. : 'cardbig';
  454. $limit = 10;//variable_get($viewmode.'_limite', '10');
  455. $offset = pager_find_page() * $limit;
  456. // dsm($offset);
  457. $query = new EntityFieldQuery;
  458. $query
  459. ->entityCondition('entity_type', 'node')
  460. ->propertyCondition('status', 1)
  461. ->entityCondition('bundle', array('breve'))
  462. ->propertyOrderBy('created', 'DESC')
  463. ->range($offset,$limit);
  464. if($useraccess){
  465. $query->propertyCondition('created', $date_limit, '>');
  466. }
  467. $result = $query->execute();
  468. // dsm($result, '$result');
  469. $count_query = new EntityFieldQuery;
  470. $count_query
  471. ->entityCondition('entity_type', 'node')
  472. ->propertyCondition('status', 1)
  473. ->entityCondition('bundle', array('breve'));
  474. // dsm($count, 'count');
  475. if($useraccess){
  476. $count_query->propertyCondition('created', $date_limit, '>');
  477. }
  478. $count = $count_query->count()->execute();
  479. pager_default_initialize($count, $limit);
  480. $items = array();
  481. if(isset($result['node'])){
  482. foreach ($result['node'] as $nid => $n) {
  483. $breve = node_load($nid);
  484. if(!node_access('view', $breve))
  485. continue;
  486. $items[] = $breve;
  487. // if(user_access('access to materio database')){
  488. $materiaux = field_get_items('node',$breve,'field_materiau_ref');
  489. // dsm($materiaux, 'materiaux');
  490. if($materiaux){
  491. foreach ($materiaux as $value) {
  492. $materiau = node_load($value['target_id']);
  493. if(node_access('view', $materiau))
  494. $items[] = $materiau;
  495. }
  496. }
  497. // }
  498. }
  499. }
  500. // drupal_set_title(t('Actualities'));
  501. drupal_set_title(t(''));
  502. return theme('materio_search_api_actuality', array(
  503. 'items' => $items,
  504. 'view_mode' => $viewmode,
  505. 'count' => $count,
  506. 'pager' => theme('pager'),
  507. ));
  508. }
  509. function materio_search_api_viewmode_change($vm){
  510. //dsm($vm, 'materio_search_api_viewmode_change');
  511. $rep = _materio_search_api_change_viewmode($vm);
  512. //return 'debug mode for materio_search_api_viewmode_change';
  513. // drupal_json_output($rep);
  514. drupal_goto();
  515. }