comparison sites/all/modules/custom/solrsearch/solrsearch_search.module @ 0:015d06b10d37 default tip

initial
author dwinter
date Wed, 31 Jul 2013 13:49:13 +0200
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:015d06b10d37
1 <?php
2
3 include('solrsearch_search_blocks.inc');
4 include('solrsearch_search_author_block.inc');
5 include('solrsearch_search_title_block.inc');
6 include('solrsearch_terms.inc');
7
8 /**
9 * @file
10 * Provides a content search implementation for node content for use with the
11 * Apache Solr search application.
12 */
13
14 #todo loesche diese funktoe finde nicht von wo aus dieaufgerufen wird!!
15 function solrsearch_index_delete_entity_from_index($env_id, $entity_type, $entity_id) {
16
17 return true;
18 }
19 /**
20 * Implements hook_init().
21 *
22 * Checks if we should run an empty facet query so the facet blocks can be
23 * displayed.
24 */
25 function solrsearch_search_init() {
26 // Useless without facetapi
27 //dpm("solrserch_init");
28 if (!module_exists('facetapi')) {
29 return NULL;
30 }
31
32 // Using a simple query we will figure out if we have to execute this snippet
33 // on every page or exit as fast as possible.
34 $query = "SELECT count(env_id)
35 FROM {solrsearch_environment_variable}
36 WHERE name = 'solrsearch_search_show_facets'";
37 $count = db_query($query)->fetchField();
38
39 //dpm($query);
40 //dpm($count);
41 if ($count == 0) {
42 return NULL;
43 }
44
45 // Load the default search page, we only support facets to link to this
46 // search page due to complexity and slow downs
47 //dpm("SEARCH PAGE I");
48
49 $search_page_id = solrsearch_search_default_search_page();
50 //dpm("SP".$search_page_id);
51 $search_page = solrsearch_search_page_load($search_page_id);
52 // Do not continue if our search page is not valid
53 if (empty($search_page)) {
54 return NULL;
55 }
56 //dpm("SEARCH PAGE II");
57 //dpm($search_page);
58 $show_facets = solrsearch_environment_variable_get($search_page['env_id'], 'solrsearch_search_show_facets', 0);
59 //dpm($show_facets);
60 if ($show_facets) {
61
62 // Converts current path to lowercase for case insensitive matching.
63 $paths = array();
64 $paths[] = drupal_strtolower(drupal_get_path_alias(current_path()));
65 $paths[] = drupal_strtolower(current_path());
66
67 $facet_pages = solrsearch_environment_variable_get($search_page['env_id'], 'solrsearch_search_facet_pages', '');
68 //dpm("FACET_PAGES");
69 //dpm($facet_pages);
70 //dpm($paths);
71 //dpm("FACET_PAGES_PATJS");
72 // Iterates over each environment to check if an empty query should be run.
73 if (!empty($facet_pages)) {
74 // Compares path with settings, runs query if there is a match.
75 $patterns = drupal_strtolower($facet_pages);
76 foreach ($paths as $path) {
77 //dpm($path."===".$patterns);
78 if (drupal_match_path($path, $patterns)) {
79 //dpm("MATCH");
80 try {
81 if (!empty($search_page['search_path'])) {
82
83 $solr = solrsearch_get_solr($search_page['env_id']);
84 // Initializes params for empty query.
85 //dpm("solr");
86 //dpm($solr);
87 $params = array(
88 'spellcheck' => 'false',
89 'fq' => array(),
90 'rows' => 1,
91 );
92 $context['page_id'] = $search_page_id;
93 $context['search_type'] = 'solrsearch_search_show_facets';
94 solrsearch_search_run_empty('solrsearch', $params, $search_page['search_path'], $solr, $context);
95 }
96 }
97 catch (Exception $e) {
98 watchdog('Apache Solr', nl2br(check_plain($e->getMessage())), NULL, WATCHDOG_ERROR);
99 }
100 }
101 }
102 }
103 }
104 }
105
106 /**
107 * Implements hook_menu().
108 */
109 function solrsearch_search_menu() {
110 $items['admin/config/search/solrsearch/search-pages'] = array(
111 'title' => 'Pages/Blocks',
112 'description' => 'Configure search pages',
113 'page callback' => 'solrsearch_search_page_list_all',
114 'access arguments' => array('administer search'),
115 'type' => MENU_LOCAL_TASK,
116 'file' => 'solrsearch_search.admin.inc',
117 );
118 $items['admin/config/search/solrsearch/search-pages/add'] = array(
119 'title' => 'Add search page',
120 'page callback' => 'drupal_get_form',
121 'page arguments' => array('solrsearch_search_page_settings_form'),
122 'access arguments' => array('administer search'),
123 'type' => MENU_LOCAL_ACTION,
124 'weight' => 1,
125 'file' => 'solrsearch_search.admin.inc',
126 );
127 $items['admin/config/search/solrsearch/search-pages/%solrsearch_search_page/edit'] = array(
128 'title' => 'Edit search page',
129 'page callback' => 'drupal_get_form',
130 'page arguments' => array('solrsearch_search_page_settings_form', 5),
131 'access arguments' => array('administer search'),
132 'file' => 'solrsearch_search.admin.inc',
133 );
134 $items['admin/config/search/solrsearch/search-pages/%solrsearch_search_page/delete'] = array(
135 'title' => 'Delete search page',
136 'page callback' => 'drupal_get_form',
137 'page arguments' => array('solrsearch_search_delete_search_page_confirm', 5),
138 'access arguments' => array('administer search'),
139 'file' => 'solrsearch_search.admin.inc',
140 );
141 $items['admin/config/search/solrsearch/search-pages/%solrsearch_search_page/clone'] = array(
142 'title' => 'Clone search page',
143 'page callback' => 'drupal_get_form',
144 'page arguments' => array('solrsearch_search_clone_search_page_confirm', 5),
145 'access arguments' => array('administer search'),
146 'file' => 'solrsearch_search.admin.inc',
147 );
148 $items['admin/config/search/solrsearch/search-pages/addblock'] = array(
149 'title' => 'Add search block "More Like This"',
150 'page callback' => 'drupal_get_form',
151 'page arguments' => array('solrsearch_search_mlt_add_block_form'),
152 'access arguments' => array('administer search'),
153 'type' => MENU_LOCAL_ACTION,
154 'weight' => 2,
155 'file' => 'solrsearch_search.admin.inc',
156 );
157
158
159 return $items;
160 }
161
162 function UNUSED_solrsearch_search_menu_alter(&$items) {
163 // Gets default search information.
164 $default_info = search_get_default_module_info();
165 $search_types = solrsearch_search_load_all_search_types();
166 $search_pages = solrsearch_search_load_all_search_pages();
167
168 // Iterates over search pages, builds menu items.
169 foreach ($search_pages as $search_page) {
170 // Validate the environemnt ID in case of import or missed deletion.
171 $environment = solrsearch_environment_load($search_page['env_id']);
172 if (!$environment) {
173 continue;
174 }
175
176 // Parses search path into it's various parts, builds menu items dependent
177 // on whether %keys is in the path.
178 $parts = explode('/', $search_page['search_path']);
179 $keys_pos = count($parts);
180 // Tests whether we are simulating a core search tab.
181 $core_solr_search = ($parts[0] == 'search');
182 $position = array_search('%', $parts);
183 $page_title = isset($search_page['page_title']) ? $search_page['page_title'] : 'Search Results';
184
185
186 // Replace possible tokens [term:tid], [node:nid], [user:uid] with their
187 // menu-specific variant
188 $items[$search_page['search_path']] = array(
189 'title' => $page_title,
190 'page callback' => 'solrsearch_search_custom_page',
191 'page arguments' => array($search_page['page_id'], '', $position),
192 'access arguments' => array('search content'),
193 'type' => ($core_solr_search) ? MENU_LOCAL_TASK : MENU_SUGGESTED_ITEM,
194 'file' => 'solrsearch_search.pages.inc',
195 'file path' => drupal_get_path('module', 'solrsearch_search'),
196 );
197
198 // Not using menu tail because of inflexibility with clean urls
199 $items[$search_page['search_path'] . '/%'] = array(
200 'title' => $page_title,
201 'page callback' => 'solrsearch_search_custom_page',
202 'page arguments' => array($search_page['page_id'], $keys_pos, $position),
203 'access arguments' => array('search content'),
204 'type' => !($core_solr_search) ? MENU_CALLBACK : MENU_LOCAL_TASK,
205 'file' => 'solrsearch_search.pages.inc',
206 'file path' => drupal_get_path('module', 'solrsearch_search'),
207 );
208
209 // If title has a certain callback for the selected type we use it
210 $search_type_id = !empty($search_page['settings']['solrsearch_search_search_type']) ? $search_page['settings']['solrsearch_search_search_type'] : FALSE;
211 $search_type = !empty($search_types[$search_type_id]) ? $search_types[$search_type_id] : FALSE;
212
213 if ($search_type && !empty($position)) {
214 $title_callback = $search_type['title callback'];
215 $items[$search_page['search_path']]['title callback'] = $title_callback;
216 $items[$search_page['search_path']]['title arguments'] = array($search_page['page_id'], $position);
217 $items[$search_page['search_path'] . '/%']['title callback'] = $title_callback;
218 $items[$search_page['search_path'] . '/%']['title arguments'] = array($search_page['page_id'], $position);
219 }
220 // If we have additional searches in the search/* path
221 if ($core_solr_search) {
222 $items[$search_page['search_path'] . '/%']['tab_root'] = 'search/' . $default_info['path'] . '/%';
223 $items[$search_page['search_path'] . '/%']['tab_parent'] = 'search/' . $default_info['path'];
224 }
225 }
226 }
227
228 /**
229 * Function that loads all the search types
230 *
231 * @return array $search_types
232 */
233 function solrsearch_search_load_all_search_types() {
234 $search_types = &drupal_static(__FUNCTION__);
235
236 if (isset($search_types)) {
237 return $search_types;
238 }
239 // Use cache_get to avoid DB when using memcache, etc.
240 $cache = cache_get('solrsearch_search:search_types', 'cache_solrsearch');
241 if (isset($cache->data)) {
242 $search_types = $cache->data;
243 }
244 else {
245 $search_types = array(
246 'bundle' => array(
247 'name' => solrsearch_field_name_map('bundle'),
248 'default menu' => 'search/type/%',
249 'title callback' => 'solrsearch_search_get_value_title',
250 ),
251 );
252 drupal_alter('solrsearch_search_types', $search_types);
253 cache_set('solrsearch_search:search_types', $search_types, 'cache_solrsearch');
254 }
255 return $search_types;
256 }
257
258
259
260 /**
261 * Used as a callback function to generate a title for a node/page depending
262 * on the input in the configuration screen
263 * @param integer $search_page_id
264 * @param integer $value
265 * @return String
266 */
267 /*
268 function solrsearch_search_get_value_title($search_page_id = NULL, $value = NULL) {
269 $page_title = 'Search results for %value';
270 if (isset($value) && isset($search_page_id)) {
271 $search_page = solrsearch_search_page_load($search_page_id);
272 $page_title = str_replace('%value', '!value', $search_page['page_title']);
273 $title = $value;
274 }
275 return t($page_title, array('!value' => $title));
276 }
277 */
278
279 /**
280 * Get or set the default search page id for the current page.
281 */
282 function solrsearch_search_default_search_page($page_id = NULL) {
283 $default_page_id = &drupal_static(__FUNCTION__, NULL);
284
285 if (isset($page_id)) {
286 $default_page_id = $page_id;
287 }
288 if (empty($default_page_id)) {
289 $default_page_id = variable_get('solrsearch_search_default_search_page', 'core_solr_search');
290 }
291 return $default_page_id;
292 }
293
294 /**
295 * Implements hook_solrsearch_default_environment()
296 *
297 * Make sure the core search page is using the default environment.
298 */
299 function solrsearch_search_solrsearch_default_environment($env_id, $old_env_id) {
300 $page = solrsearch_search_page_load('core_solr_search');
301 if ($page && $page['env_id'] != $env_id) {
302 $page['env_id'] = $env_id;
303 solrsearch_search_page_save($page);
304 }
305 }
306
307 /**
308 * Load a search page
309 * @param string $page_id
310 * @return array
311 */
312 function solrsearch_search_page_load($page_id) {
313 //dpm(" solrsearch_search_page_load");
314
315 $search_pages = solrsearch_search_load_all_search_pages();
316 //dpm($search_pages);
317 if (!empty($search_pages[$page_id])) {
318 return $search_pages[$page_id];
319 }
320 return FALSE;
321 }
322
323 function solrsearch_search_page_save($search_page) {
324 if (!empty($search_page)) {
325 db_merge('solrsearch_search_page')
326 ->key(array('page_id' => $search_page['page_id']))
327 ->fields(array(
328 'label' => $search_page['label'],
329 'page_id' => $search_page['page_id'],
330 'description' => $search_page['description'],
331 'env_id' => $search_page['env_id'],
332 'search_path' => $search_page['search_path'],
333 'page_title' => $search_page['page_title'],
334 'settings' => serialize($search_page['settings']),
335 ))
336 ->execute();
337 }
338 }
339
340 /**
341 * Function that clones a search page
342 *
343 * @param $page_id
344 * The page identifier it needs to clone.
345 *
346 */
347 function solrsearch_search_page_clone($page_id) {
348 $search_page = solrsearch_search_page_load($page_id);
349 // Get all search_pages
350 $search_pages = solrsearch_search_load_all_search_pages();
351 // Create an unique ID
352 $new_search_page_id = solrsearch_create_unique_id($search_pages, $search_page['page_id']);
353 // Set this id to the new search page
354 $search_page['page_id'] = $new_search_page_id;
355 $search_page['label'] = $search_page['label'] . ' [cloned]';
356 // All cloned search pages should be removable
357 if (isset($search_page['settings']['solrsearch_search_not_removable'])) {
358 unset($search_page['settings']['solrsearch_search_not_removable']);
359 }
360 // Save our new search page in the database
361 solrsearch_search_page_save($search_page);
362 }
363
364 /**
365 * Implements hook_block_info().
366 */
367 function solrsearch_search_block_info() {
368 // Get all of the moreLikeThis blocks that the user has created
369 $blocks = solrsearch_search_load_all_mlt_blocks();
370 foreach ($blocks as $delta => $settings) {
371 $blocks[$delta] += array('info' => t('Solr Search recommendations: !name', array('!name' => $settings['name'])) , 'cache' => DRUPAL_CACHE_PER_PAGE);
372 }
373 // Add the sort block.
374 $blocks['sort'] = array(
375 'info' => t('Solr Search Core: Sorting'),
376 'cache' => DRUPAL_CACHE_CUSTOM,
377 );
378
379 $blocks['solrsearch'] = array(
380 'info' => t('Solr Search Core: Search'),
381 'cache' => DRUPAL_CACHE_CUSTOM,
382 );
383
384
385 $blocks['solrsearch_author'] = array(
386 'info' => t('Solr Search Core: Search - author'),
387 'cache' => DRUPAL_CACHE_CUSTOM,
388 );
389
390 $blocks['solrsearch_title'] = array(
391 'info' => t('Solr Search Core: Search - title'),
392 'cache' => DRUPAL_CACHE_CUSTOM,
393 );
394
395
396
397 return $blocks;
398 }
399
400 /**
401 * Implements hook_block_view().
402 */
403 function solrsearch_search_block_view($delta = '') {
404
405 if ($delta == 'sort') {
406 $environments = solrsearch_load_all_environments();
407 foreach ($environments as $env_id => $environment) {
408 if (solrsearch_has_searched($env_id) && !solrsearch_suppress_blocks($env_id) && $delta == 'sort') {
409 $response = NULL;
410 $query = solrsearch_current_query($env_id);
411 $solrsort = NULL;
412 if ($query) {
413 // Get the query and response. Without these no blocks make sense.
414 $response = solrsearch_static_response_cache($query->getSearcher());
415 }
416
417 // If there are less than two results, do not return the sort block
418 if (empty($response) || ($response->response->numFound < 2)) {
419 return NULL;
420 }
421
422 // Check if we have to return a cached version of this block
423 if ($query) {
424 // Get the URI without any query parameter.
425 $uri = parse_url(request_uri());
426 // Get the current sort as an array.
427 $solrsort = $query->getSolrsort();
428 $cache_id = $uri['path'] . ':' . implode(':', $solrsort);
429 // Do we have something in cache ?
430 if ($cache = cache_get($cache_id, 'cache_block')) {
431 $block = $cache->data;
432 return $block;
433 }
434 }
435
436 $sorts = $query->getAvailableSorts();
437 $sort_links = array();
438 $path = $query->getPath();
439 $new_query = clone $query;
440 $toggle = array('asc' => 'desc', 'desc' => 'asc');
441 foreach ($sorts as $name => $sort) {
442 $active = $solrsort['#name'] == $name;
443 if ($name == 'score') {
444 $direction = '';
445 $new_direction = 'desc'; // We only sort by descending score.
446 }
447 elseif ($active) {
448 $direction = $toggle[$solrsort['#direction']];
449 $new_direction = $toggle[$solrsort['#direction']];
450 }
451 else {
452 $direction = '';
453 $new_direction = $sort['default'];
454 }
455 $new_query->setSolrsort($name, $new_direction);
456 $sort_links[$name] = array(
457 'text' => $sort['title'],
458 'path' => $path,
459 'options' => array('query' => $new_query->getSolrsortUrlQuery()),
460 'active' => $active,
461 'direction' => $direction,
462 );
463 }
464 foreach ($sort_links as $name => $link) {
465 $themed_links[$name] = theme('solrsearch_sort_link', $link);
466 }
467 $block = array(
468 'subject' => t('Sort by'),
469 'content' => theme('solrsearch_sort_list', array('items' => $themed_links))
470 );
471 // Cache the block
472 cache_set($cache_id, $block, 'cache_block');
473 return $block;
474 }
475 }
476 }
477 elseif ($delta == 'solrsearch') {
478
479 return solrsearch_search_block();
480 }
481
482 elseif($delta == 'solrsearch_author'){
483
484 return solrsearch_search_author_block();
485 }
486
487 elseif($delta == 'solrsearch_title'){
488
489 return solrsearch_search_title_block();
490 }
491
492
493
494 elseif (($node = menu_get_object()) && (!arg(2) || arg(2) == 'view')) {
495 $suggestions = array();
496 // Determine whether the user can view the current node. Probably not necessary.
497 $block = solrsearch_search_mlt_block_load($delta);
498 if ($block && node_access('view', $node)) {
499 // Get our specific environment for the MLT block
500 $env_id = (!empty($block['mlt_env_id'])) ? $block['mlt_env_id'] : '';
501 try {
502 $solr = solrsearch_get_solr($env_id);
503 $context['search_type'] = 'solrsearch_search_mlt';
504 $context['block_id'] = $delta;
505 $docs = solrsearch_search_mlt_suggestions($block, solrsearch_document_id($node->nid), $solr, $context);
506 if (!empty($docs)) {
507 $suggestions['subject'] = check_plain($block['name']);
508 $suggestions['content'] = array(
509 '#theme' => 'solrsearch_search_mlt_recommendation_block',
510 '#docs' => $docs,
511 '#delta' => $delta
512 );
513 }
514 }
515 catch (Exception $e) {
516 watchdog('Apache Solr', nl2br(check_plain($e->getMessage())), NULL, WATCHDOG_ERROR);
517 }
518 }
519 return $suggestions;
520 }
521 }
522
523 /**
524 * Implements hook_form_[form_id]_alter().
525 */
526 function solrsearch_search_form_block_admin_display_form_alter(&$form) {
527 foreach ($form['blocks'] as $key => $block) {
528 if ((strpos($key, "solrsearch_search_mlt-") === 0) && $block['module']['#value'] == 'solrsearch_search') {
529 $form['blocks'][$key]['delete'] = array(
530 '#type' => 'link',
531 '#title' => 'delete',
532 '#href' => 'admin/config/search/solrsearch/search-pages/block/' . $block['delta']['#value'] . '/delete',
533 );
534 }
535 }
536 }
537
538 /**
539 * Implements hook_block_configure().
540 */
541 function solrsearch_search_block_configure($delta = '') {
542 if ($delta != 'sort') {
543 require_once(drupal_get_path('module', 'solrsearch') . '/solrsearch_search.admin.inc');
544 return solrsearch_search_mlt_block_form($delta);
545 }
546 }
547
548 /**
549 * Implements hook_block_save().
550 */
551 function solrsearch_search_block_save($delta = '', $edit = array()) {
552 if ($delta != 'sort') {
553 require_once(drupal_get_path('module', 'solrsearch') . '/solrsearch_search.admin.inc');
554 solrsearch_search_mlt_save_block($edit, $delta);
555 }
556 }
557
558
559 /**
560 * Return all the saved search pages
561 * @return array $search_pages
562 * Array of all search pages
563 */
564 function solrsearch_search_load_all_search_pages() {
565 $search_pages = &drupal_static(__FUNCTION__, array());
566 //dpm("solrsearch_search_load_all_search_pages");
567 if (!empty($search_pages)) {
568 return $search_pages;
569 }
570
571 // If ctools module is enabled, add search pages from code, e.g. from a
572 // feature module.
573 if (module_exists('ctools')) {
574 ctools_include('export');
575 $defaults = ctools_export_load_object('solrsearch_search_page', 'all');
576 foreach ($defaults as $page_id => $default) {
577 $search_pages[$page_id] = (array) $default;
578 }
579 }
580
581 // Get all search_pages and their id
582 $search_pages_db = db_query('SELECT * FROM {solrsearch_search_page}')->fetchAllAssoc('page_id', PDO::FETCH_ASSOC);
583 //$search_pages_db = db_query('SELECT * FROM {apachesolr_search_page}')->fetchAllAssoc('page_id', PDO::FETCH_ASSOC);
584 //dpm($search_pages);
585 //dpm("QUERY");
586 $search_pages = $search_pages + $search_pages_db;
587
588 // Ensure that the core search page uses the default environment. In some
589 // instances, for example when unit testing, this search page isn't defined.
590 if (isset($search_pages['core_solr_search'])) {
591 $search_pages['core_solr_search']['env_id'] = solrsearch_default_environment();
592 }
593
594 // convert settings to an array
595 foreach ($search_pages as $id => $search_page) {
596 if (is_string($search_pages[$id]['settings'])) {
597 $search_pages[$id]['settings'] = unserialize($search_pages[$id]['settings']);
598 // Prevent false outcomes for the following search page
599 $settings = 0;
600 }
601 }
602 //dpm($search_pages);
603 //dpm("QUERY II");
604 return $search_pages;
605 }
606
607 function solrsearch_search_load_all_mlt_blocks() {
608 $search_blocks = variable_get('solrsearch_search_mlt_blocks', array());
609 return $search_blocks;
610 }
611
612 function solrsearch_search_mlt_block_load($block_id) {
613 $search_blocks = variable_get('solrsearch_search_mlt_blocks', array());
614 return isset($search_blocks[$block_id]) ? $search_blocks[$block_id] : FALSE;
615 }
616
617 /**
618 * Performs a moreLikeThis query using the settings and retrieves documents.
619 *
620 * @param $settings
621 * An array of settings.
622 * @param $id
623 * The Solr ID of the document for which you want related content.
624 * For a node that is solrsearch_document_id($node->nid)
625 * @param $solr
626 * The solr environment you want to query against
627 *
628 * @return An array of response documents, or NULL
629 */
630 function solrsearch_search_mlt_suggestions($settings, $id, $solr = NULL, $context = array()) {
631
632 try {
633 $fields = array(
634 'mlt_mintf' => 'mlt.mintf',
635 'mlt_mindf' => 'mlt.mindf',
636 'mlt_minwl' => 'mlt.minwl',
637 'mlt_maxwl' => 'mlt.maxwl',
638 'mlt_maxqt' => 'mlt.maxqt',
639 'mlt_boost' => 'mlt.boost',
640 'mlt_qf' => 'mlt.qf',
641 );
642 $params = array(
643 'q' => 'id:' . $id,
644 'qt' => 'mlt',
645 'fl' => array('entity_id', 'entity_type', 'label', 'path', 'url'),
646 'mlt.fl' => $settings['mlt_fl'],
647 'start' => 0,
648 'rows' => $settings['num_results'],
649 );
650 // We can optionally specify a Solr object.
651 $query = solrsearch_drupal_query('solrsearch_mlt', $params, '', '', $solr, $context);
652
653 foreach ($fields as $form_key => $name) {
654 if (!empty($settings[$form_key])) {
655 $query->addParam($name, $settings[$form_key]);
656 }
657 }
658
659 $type_filters = array();
660 if (is_array($settings['mlt_type_filters']) && !empty($settings['mlt_type_filters'])) {
661 $query->addFilter('bundle', '(' . implode(' OR ', $settings['mlt_type_filters']) . ') ');
662 }
663
664 if ($custom_filters = $settings['mlt_custom_filters']) {
665 // @todo - fix the settings form to take a comma-delimited set of filters.
666 $query->addFilter('', $custom_filters);
667 }
668
669 // This hook allows modules to modify the query object.
670 drupal_alter('solrsearch_query', $query);
671 if ($query->abort_search) {
672 return NULL;
673 }
674
675 $response = $query->search();
676
677 if (isset($response->response->docs)) {
678 return (array) $response->response->docs;
679 }
680 }
681 catch (Exception $e) {
682 watchdog('Apache Solr', nl2br(check_plain($e->getMessage())), NULL, WATCHDOG_ERROR);
683 }
684 }
685
686 function theme_solrsearch_search_mlt_recommendation_block($vars) {
687 $docs = $vars['docs'];
688 $links = array();
689 foreach ($docs as $result) {
690 // Suitable for single-site mode. Label is already safe.
691 $links[] = l($result->label, $result->path, array('html' => TRUE));
692 }
693 $links = array(
694 '#theme' => 'item_list',
695 '#items' => $links,
696 );
697 return render($links);
698 }
699
700 /**
701 * Implements hook_search_info().
702 */
703 function UNUSED_solrsearch_search_search_info() {
704 // Load our core search page
705 // This core search page is assumed to always be there. It cannot be deleted.
706 $search_page = solrsearch_search_page_load('core_solr_search');
707
708 // This can happen during install, or if the DB was manually changed.
709 if (empty($search_page)) {
710 $search_page = array();
711 $search_page['page_title'] = 'echo';
712 $search_page['search_path'] = 'solrsearch/site';
713 }
714
715 return array(
716 'title' => $search_page['page_title'],
717 'path' => str_replace('solrsearch/', '', $search_page['search_path']),
718 'conditions_callback' => variable_get('solrsearch_search_conditions_callback', 'solrsearch_search_conditions'),
719 );
720 }
721
722 /**
723 * Implements hook_search_reset().
724 */
725 function UNUSED_solrsearch_search_search_reset() {
726 module_load_include('inc', 'solrsearch', 'solrsearch.index');
727 $env_id = solrsearch_default_environment();
728 solrsearch_index_mark_for_reindex($env_id);
729 }
730
731 /**
732 * Implements hook_search_status().
733 */
734 function UNUSED_solrsearch_search_search_status() {
735 module_load_include('inc', 'solrsearch', 'solrsearch.index');
736 $env_id = solrsearch_default_environment();
737 return solrsearch_index_status($env_id);
738 }
739
740 /**
741 * Implements hook_search_execute().
742 * @param $keys
743 * The keys that are available after the path that is defined in
744 * hook_search_info
745 * @param $conditions
746 * Conditions that are coming from solrsearch_search_conditions
747 */
748 function solrsearch_search_search_execute($keys = NULL, $conditions = NULL) {
749
750 $search_page = solrsearch_search_page_load('core_solr_search');
751 $results = solrsearch_search_search_results($keys, $conditions, $search_page);
752 return $results;
753 }
754
755 /**
756 * Implementation of a search_view() conditions callback.
757 */
758 function solrsearch_search_conditions() {
759 //get default conditions from the core_solr_search
760 $search_page = solrsearch_search_page_load('core_solr_search');
761 $conditions = solrsearch_search_conditions_default($search_page);
762 return $conditions;
763 }
764
765 /**
766 * Implements hook_search_page().
767 * @param $results
768 * The results that came from apache solr
769 */
770 function solrsearch_search_search_page($results) {
771 $search_page = solrsearch_search_page_load('core_solr_search');
772 $build = solrsearch_search_search_page_custom($results, $search_page);
773 return $build;
774 }
775
776 /**
777 * Mimics solrsearch_search_search_page() but is used for custom search pages
778 * We prefer to keep them seperate so we are not dependent from core search
779 * when someone tries to disable the core search
780 * @param $results
781 * The results that came from apache solr
782 * @param $build
783 * the build array from where this function was called. Good to append output
784 * to the build array
785 * @param $search_page
786 * the search page that is requesting an output
787 */
788 function solrsearch_search_search_page_custom($results, $search_page, $build = array()) {
789 if (!empty($search_page['settings']['solrsearch_search_spellcheck'])) {
790 // Retrieve suggestion
791 $suggestions = solrsearch_search_get_search_suggestions($search_page['env_id']);
792 if ($search_page && !empty($suggestions)) {
793 $build['suggestions'] = array(
794 '#theme' => 'solrsearch_search_suggestions',
795 '#links' => array(l($suggestions[0], $search_page['search_path'] . '/' . $suggestions[0])),
796 );
797 }
798 }
799 // Retrieve expected results from searching
800 if (!empty($results['solrsearch_search_browse'])) {
801 // Show facet browsing blocks.
802 $build['search_results'] = solrsearch_search_page_browse($results['solrsearch_search_browse'], $search_page['env_id']);
803 }
804 elseif ($results) {
805
806 $build['search_results'] = array(
807 '#theme' => 'solrsearch_results',
808 '#results' => $results,
809 '#module' => 'solrsearch_search',
810 '#search_page' => $search_page,
811 );
812 }
813 else {
814 // Give the user some custom help text.
815 $build['search_results'] = array('#markup' => theme('solrsearch_search_noresults'));
816 }
817
818 // Allows modules to alter the render array before returning.
819 drupal_alter('solrsearch_search_page', $build, $search_page);
820
821 return $build;
822 }
823
824 /**
825 * Executes search depending on the conditions given.
826 * See solrsearch_search.pages.inc for another use of this function
827 */
828 function solrsearch_search_search_results($keys = NULL, $conditions = NULL, $search_page = NULL) {
829
830 $params = array();
831 $results = array();
832 // Process the search form. Note that if there is $_POST data,
833 // search_form_submit() will cause a redirect to search/[module path]/[keys],
834 // which will get us back to this page callback. In other words, the search
835 // form submits with POST but redirects to GET. This way we can keep
836 // the search query URL clean as a whistle.
837 if (empty($_POST['form_id'])
838 || ($_POST['form_id'] != 'solrsearch_search_custom_page_search_form')
839 && ($_POST['form_id'] != 'search_form')
840 && ($_POST['form_id'] != 'search_block_form') ) {
841
842 // Check input variables
843 if (empty($search_page)) {
844 $search_page = solrsearch_search_page_load('core_solr_search');
845 // Verify if it actually loaded
846 if (empty($search_page)) {
847 // Something must have been really messed up.
848 solrsearch_failure(t('Solr search'), $keys);
849 return array();
850 }
851 }
852 if (empty($conditions)) {
853 $conditions = solrsearch_search_conditions_default($search_page);
854 }
855
856 // Sort options from the conditions array.
857 // @see solrsearch_search_conditions_default()
858 // See This condition callback to find out how.
859 $solrsort = isset($conditions['solrsearch_search_sort']) ? $conditions['solrsearch_search_sort'] : '';
860 // What to do when we have an initial empty search
861 $empty_search_behavior = isset($search_page['settings']['solrsearch_search_browse']) ? $search_page['settings']['solrsearch_search_browse'] : '';
862
863 try {
864
865 $solr = solrsearch_get_solr($search_page['env_id']);
866 // Default parameters
867 $params['fq'] = isset($conditions['fq']) ? $conditions['fq'] : array();
868 $params['rows'] = $search_page['settings']['solrsearch_search_per_page'];
869
870 if (empty($search_page['settings']['solrsearch_search_spellcheck'])) {
871 // Spellcheck needs to have a string as false/true
872 $params['spellcheck'] = 'false';
873 }
874 else {
875 $params['spellcheck'] = 'true';
876 }
877
878 // Empty text Behavior
879 if (!$keys && !isset($conditions['f']) && ($empty_search_behavior == 'browse' || $empty_search_behavior == 'blocks')) {
880 // Pass empty search behavior as string on to solrsearch_search_search_page()
881 // Hardcoded solrsearch name since we rely on this for the facets
882
883 $context['page_id'] = $search_page['page_id'];
884 $context['search_type'] = 'solrsearch_search_browse';
885 solrsearch_search_run_empty('solrsearch', $params, $search_page['search_path'], $solr, $context);
886 $results['solrsearch_search_browse'] = $empty_search_behavior;
887
888 if ($empty_search_behavior == 'browse') {
889 // Hide sidebar blocks for content-area browsing instead.
890 solrsearch_suppress_blocks($search_page['env_id'], TRUE);
891 }
892 }
893 // Full text behavior. Triggers with a text search or a facet
894 elseif (($keys || isset($conditions['f'])) || ($empty_search_behavior == 'results')) {
895
896 $params['q'] = $keys;
897 // Hardcoded solrsearch name since we rely on this for the facets
898 $context['page_id'] = $search_page['page_id'];
899 $context['search_type'] = 'solrsearch_search_results';
900 $results = solrsearch_search_run('solrsearch', $params, $solrsort, $search_page['search_path'], pager_find_page(), $solr, $context);
901 }
902 }
903 catch (Exception $e) {
904 watchdog('Apache Solr', nl2br(check_plain($e->getMessage())), NULL, WATCHDOG_ERROR);
905 solrsearch_failure(t('Solr search'), $keys);
906 }
907 }
908 return $results;
909 }
910
911 function solrsearch_search_conditions_default($search_page) {
912 $conditions = array();
913 $search_type = isset($search_page['settings']['solrsearch_search_search_type']) ? $search_page['settings']['solrsearch_search_search_type'] : '';
914 $allow_user_input = isset($search_page['settings']['solrsearch_search_allow_user_input']) ? $search_page['settings']['solrsearch_search_allow_user_input'] : FALSE;
915 $path_replacer = isset($search_page['settings']['solrsearch_search_path_replacer']) ? $search_page['settings']['solrsearch_search_path_replacer'] : '';
916 $set_custom_filter = isset($search_page['settings']['solrsearch_search_custom_enable']) ? $search_page['settings']['solrsearch_search_custom_enable'] : '';
917 $search_page_fq = !empty($search_page['settings']['fq']) ? $search_page['settings']['fq'] : '';
918
919
920
921
922
923 $conditions['fq'] = array();
924 // We only allow this to happen if the search page explicitely allows it
925 if ($allow_user_input) {
926 // Get the filterQueries from the url
927 if (!empty($_GET['fq']) && is_array($_GET['fq'])) {
928 // Reset the array so that we have one level lower to go through
929 $conditions['fq'] = $_GET['fq'];
930 }
931 foreach($conditions['fq'] as $condition_id => $condition) {
932 // If the user input does not pass our validation we do not allow
933 // it to query solr
934 $test_query = solrsearch_drupal_subquery('Test');
935 if (!$test_query->validFilterValue($condition)) {
936 unset($conditions['fq'][$condition_id]);
937 }
938 }
939 }
940
941 // Custom filters added in search pages
942 if (!empty($search_page_fq) && !empty($set_custom_filter)) {
943 if (!empty($path_replacer)) {
944 // If the manual filter has a % in it, replace it with $value
945 $conditions['fq'][] = str_replace('%', $path_replacer, $search_page_fq);
946 }
947 else {
948 // Put the complete filter in the filter query
949 $conditions['fq'][] = $search_page_fq;
950 }
951 }
952
953 // Search type filters (such as taxonomy)
954 if (!empty($path_replacer) && !empty($search_type) && $search_type != 'custom') {
955 $conditions['fq'][] = $search_type . ':' . $path_replacer;
956 }
957
958 // We may also have filters added by facet API module. The 'f'
959 // is determined by variable FacetapiUrlProcessor::$filterKey. Hard
960 // coded here to avoid extra class loading.
961 if (!empty($_GET['f']) && is_array($_GET['f'])) {
962 if (module_exists('facetapi')) {
963 $conditions['f'] = $_GET['f'];
964 }
965 }
966 // Add the sort from the page to our conditions
967 $sort = isset($_GET['solrsort']) ? $_GET['solrsort'] : '';
968 $conditions['solrsearch_search_sort'] = $sort;
969
970
971 $conditions['fq'][] = "doc-type:indexMeta";
972 return $conditions;
973 }
974
975 /**
976 * Handle browse results for empty searches.
977 */
978 function solrsearch_search_page_browse($empty_search_behavior, $env_id) {
979 $build = array();
980 //dpm("solrsearch_search_page_browse");
981 //dpm($empty_search_behavior);
982
983 // Switch in case we come up with new flags.
984 switch ($empty_search_behavior) {
985 case 'browse':
986 if (module_exists('facetapi') && $query = solrsearch_current_query($env_id)) {
987 module_load_include('inc', 'facetapi', 'facetapi.block');
988 // Get facet render elements.
989 $searcher = $query->getSearcher();
990 $elements = facetapi_build_realm($searcher, 'block');
991 $build = array();
992 //dpm($searcher);
993 //dpm($elements);
994 foreach (element_children($elements) as $key) {
995 $delta = "facetapi_{$key}";
996 // @todo: order/filter these pseudo-blocks according to block.module weight, visibility (see 7.x-1beta4)
997 $block = new stdClass();
998 $block->visibility = TRUE;
999 $block->enabled = TRUE;
1000 $block->module = 'facetapi';
1001 $block->subject = theme('facetapi_title', array('title' => $elements[$key]['#title']));
1002 $build[$delta] = $elements[$key];
1003 $block->region = NULL;
1004 $block->delta = 'solrsearch-' . $key;
1005 // @todo: the final themed block's div id attribute does not coincide with "real" block's id (see facetapi_get_delta_map())
1006 $build[$delta]['#block'] = $block;
1007 $build[$delta]['#theme_wrappers'][] = 'block';
1008 $build['#sorted'] = TRUE;
1009 }
1010 $build['#theme_wrappers'][] = 'solrsearch_search_browse_blocks';
1011 }
1012 break;
1013 }
1014 return $build;
1015 }
1016
1017 /**
1018 * Shows a groups of blocks for starting a search from a filter.
1019 */
1020 function theme_solrsearch_search_browse_blocks($vars) {
1021 $result = '';
1022 if ($vars['content']['#children']) {
1023 $result .= "<div class='solrsearch-browse-blocks'>\n<h2>" . t('Browse available categories') . "</h2>\n";
1024 $result .= '<p>' . t('Pick a category to launch a search.') . "</p>\n";
1025 $result .= $vars['content']['#children'] . "\n</div>\n";
1026 }
1027
1028 return $result;
1029 }
1030
1031 /**
1032 * Execute a search with zero results rows so as to populate facets.
1033 */
1034 function solrsearch_search_run_empty($name, array $params = array(), $base_path = '', $solr = NULL, $context = array()) {
1035 $query = solrsearch_drupal_query($name, $params, '', $base_path, $solr, $context);
1036 $query->addParam('rows', '0');
1037 $solr_id = $query->solr('getId');
1038 list($final_query, $response) = solrsearch_do_query($query);
1039 solrsearch_has_searched($solr_id, TRUE);
1040 }
1041
1042 /**
1043 * Execute a search results based on keyword, filter, and sort strings.
1044 *
1045 * @param $name
1046 * @param $params
1047 * Array - 'q' is the keywords to search.
1048 * @param $solrsort
1049 * @param $base_path
1050 * For constructing filter and sort links. Leave empty unless the links need to point somewhere
1051 * other than the base path of the current request.
1052 * @param integer $page
1053 * For pagination.
1054 * @param DrupalApacheSolrServiceInterface $solr
1055 * The solr server resource to execute the search on.
1056 *
1057 * @return stdClass $response
1058 *
1059 * @throws Exception
1060 */
1061 function solrsearch_search_run($name, array $params = array(), $solrsort = '', $base_path = '', $page = 0, DrupalApacheSolrServiceInterface $solr = NULL, $context = array()) {
1062 // Merge the default params into the params sent in.
1063
1064 $params += solrsearch_search_basic_params();
1065 // This is the object that knows about the query coming from the user.
1066 $query = solrsearch_drupal_query($name, $params, $solrsort, $base_path, $solr, $context);
1067
1068 if ($query->getParam('q')) {
1069 solrsearch_search_add_spellcheck_params($query);
1070 }
1071
1072 // Add the paging parameters
1073 $query->page = $page;
1074
1075 solrsearch_search_add_boost_params($query);
1076 if ($query->getParam('q')) {
1077 solrsearch_search_highlighting_params($query);
1078 if (!$query->getParam('hl.fl')) {
1079 $qf = array();
1080 foreach ($query->getParam('qf') as $field) {
1081 // Truncate off any boost so we get the simple field name.
1082 $parts = explode('^', $field, 2);
1083 $qf[$parts[0]] = TRUE;
1084 }
1085 foreach (array('content', 'ts_comments') as $field) {
1086 if (isset($qf[$field])) {
1087 $query->addParam('hl.fl', $field);
1088 }
1089 }
1090 }
1091 }
1092 else {
1093 // No highlighting, use the teaser as a snippet.
1094 $query->addParam('fl', 'teaser');
1095 }
1096
1097
1098 list($final_query, $response) = solrsearch_do_query($query);
1099
1100 $env_id = $query->solr('getId');
1101 solrsearch_has_searched($env_id, TRUE);
1102 $process_response_callback = solrsearch_environment_variable_get($env_id, 'process_response_callback', 'solrsearch_search_process_response');
1103 if (function_exists($process_response_callback)) {
1104 return call_user_func($process_response_callback, $response, $final_query);
1105 }
1106 else {
1107 return solrsearch_search_process_response($response, $final_query);
1108 }
1109 }
1110
1111 function solrsearch_search_basic_params(DrupalSolrQueryInterface $query = NULL) {
1112 $params = array(
1113 'fl' => array(
1114 'id',
1115 'entity_type',
1116 'author_c',
1117 'author',
1118 'title',
1119 'title_s',
1120 'keyword',
1121 'year',
1122 'IM_date',
1123 'IM_signature',
1124 'archive-path',
1125 'doc-type',
1126 'mpiwg-dri',
1127 'access-type',
1128 ),
1129 'mm' => 1,
1130 'rows' => 10,
1131 'pf' => 'title^2.0 author^1.0',
1132 'ps' => 15,
1133 'hl' => 'true',
1134 'hl.fl' => 'title',
1135 'hl.snippets' => 3,
1136 'hl.mergeContigious' => 'true',
1137 'f.content.hl.alternateField' => 'teaser',
1138 'f.content.hl.maxAlternateFieldLength' => 256,
1139 );
1140 if ($query) {
1141 $query->addParams($params);
1142 }
1143 return $params;
1144 }
1145
1146 /**
1147 * Add highlighting settings to the search params.
1148 *
1149 * These settings are set in solrconfig.xml.
1150 * See the defaults there.
1151 * If you wish to override them, you can via settings.php or drush
1152 */
1153 function solrsearch_search_highlighting_params(DrupalSolrQueryInterface $query = NULL) {
1154 $params['hl'] = variable_get('solrsearch_hl_active', NULL);
1155 $params['hl.fragsize']= variable_get('solrsearch_hl_textsnippetlength', NULL);
1156 $params['hl.simple.pre'] = variable_get('solrsearch_hl_pretag', NULL);
1157 $params['hl.simple.post'] = variable_get('solrsearch_hl_posttag', NULL);
1158 $params['hl.snippets'] = variable_get('solrsearch_hl_numsnippets', NULL);
1159 // This should be an array of possible field names.
1160 $params['hl.fl'] = variable_get('solrsearch_hl_fieldtohighlight', NULL);
1161 $params = array_filter($params);
1162 if ($query) {
1163 $query->addParams($params);
1164 }
1165 return $params;
1166 }
1167
1168 function solrsearch_search_add_spellcheck_params(DrupalSolrQueryInterface $query) {
1169 $params = array();
1170
1171 // Add new parameter to the search request
1172 $params['spellcheck.q'] = $query->getParam('q');
1173 $params['spellcheck'] = 'true';
1174 $query->addParams($params);
1175 }
1176
1177 function solrsearch_search_add_boost_params(DrupalSolrQueryInterface $query) {
1178 $env_id = $query->solr('getId');
1179 $params = array();
1180
1181 $defaults = array(
1182 'content' => '1.0',
1183 'ts_comments' => '0.5',
1184 'tos_content_extra' => '0.1',
1185 'label' => '5.0',
1186 'tos_name' => '3.0',
1187 'taxonomy_names' => '2.0',
1188 'tags_h1' => '5.0',
1189 'tags_h2_h3' => '3.0',
1190 'tags_h4_h5_h6' => '2.0',
1191 'tags_inline' => '1.0',
1192 'tags_a' => '0',
1193 );
1194 $qf = solrsearch_environment_variable_get($env_id, 'field_bias', $defaults);
1195 $fields = $query->solr('getFields');
1196 if ($qf && $fields) {
1197 foreach ($fields as $field_name => $field) {
1198 if (!empty($qf[$field_name])) {
1199 $prefix = substr($field_name, 0, 3);
1200 if ($field_name == 'content' || $prefix == 'IM_' || $prefix == 'TT_') {
1201 // Normed fields tend to have a lower score. Multiplying by 40 is
1202 // a rough attempt to bring the score in line with fields that are
1203 // not normed.
1204 $qf[$field_name] *= 40.0;
1205 }
1206 $params['qf'][$field_name] = $field_name . '^' . $qf[$field_name];
1207 }
1208 }
1209 }
1210
1211 $date_settings = solrsearch_environment_variable_get($env_id, 'solrsearch_search_date_boost', '0:0');
1212 $comment_settings = solrsearch_environment_variable_get($env_id, 'solrsearch_search_comment_boost', '0:0');
1213 $changed_settings = solrsearch_environment_variable_get($env_id, 'solrsearch_search_changed_boost', '0:0');
1214 $sticky_boost = solrsearch_environment_variable_get($env_id, 'solrsearch_search_sticky_boost', '0');
1215 $promote_boost = solrsearch_environment_variable_get($env_id, 'solrsearch_search_promote_boost', '0');
1216 // For the boost functions for the created timestamp, etc we use the
1217 // standard date-biasing function, as suggested (but steeper) at
1218 // http://wiki.apache.org/solr/SolrRelevancyFAQ#How_can_I_boost_the_score_of_newer_documents
1219 // ms() returns the time difference in ms between now and the date
1220 // The function is thus: $ab/(ms(NOW,date)*$steepness + $ab).
1221 list($date_steepness, $date_boost) = explode(':', $date_settings);
1222 if ($date_boost) {
1223 $ab = 4 / $date_steepness;
1224 $params['bf'][] = "recip(ms(NOW,ds_created),3.16e-11,$ab,$ab)^$date_boost";
1225 }
1226 // Boost on comment count.
1227 list($comment_steepness, $comment_boost) = explode(':', $comment_settings);
1228 if ($comment_boost) {
1229 $params['bf'][] = "recip(div(1,max(is_comment_count,1)),$comment_steepness,10,10)^$comment_boost";
1230 }
1231 // Boost for a more recent comment or node edit.
1232 list($changed_steepness, $changed_boost) = explode(':', $changed_settings);
1233 if ($changed_boost) {
1234 $ab = 4 / $changed_steepness;
1235 $params['bf'][] = "recip(ms(NOW,ds_created),3.16e-11,$ab,$ab)^$changed_boost";
1236 }
1237 // Boost for nodes with sticky bit set.
1238 if ($sticky_boost) {
1239 $params['bq'][] = "bs_sticky:true^$sticky_boost";
1240 }
1241 // Boost for nodes with promoted bit set.
1242 if ($promote_boost) {
1243 $params['bq'][] = "bs_promote:true^$promote_boost";
1244 }
1245 // Modify the weight of results according to the node types.
1246 $type_boosts = solrsearch_environment_variable_get($env_id, 'solrsearch_search_type_boosts', array());
1247 if (!empty($type_boosts)) {
1248 foreach ($type_boosts as $type => $boost) {
1249 // Only add a param if the boost is != 0 (i.e. > "Normal").
1250 if ($boost) {
1251 $params['bq'][] = "bundle:$type^$boost";
1252 }
1253 }
1254 }
1255 $query->addParams($params);
1256 }
1257
1258 function solrsearch_search_process_response($response, DrupalSolrQueryInterface $query) {
1259 $results = array();
1260 // We default to getting snippets from the body content and comments.
1261 $hl_fl = $query->getParam('hl.fl');
1262 if (!$hl_fl) {
1263 //TODO: make highlighitn configurabel
1264 $hl_fl = array('title','author');
1265 }
1266 $total = $response->response->numFound;
1267
1268
1269 pager_default_initialize($total, $query->getParam('rows'));
1270 if ($total > 0) {
1271 $fl = $query->getParam('fl');
1272 // 'id' and 'entity_type' are the only required fields in the schema, and
1273 // 'score' is generated by solr.
1274
1275
1276 foreach ($response->response->docs as $doc) {
1277 $extra = array();
1278 // Allow modules to alter each document and its extra information.
1279 drupal_alter('solrsearch_search_result', $doc, $extra, $query);
1280
1281 // Start with an empty snippets array.
1282 $snippets = array();
1283
1284 //TODO mappe das irgendwo allgemein?
1285 $doc->id=$doc->{'archive-path'};
1286
1287 // Find the nicest available snippet.
1288 foreach ($hl_fl as $hl_param) {
1289 if (isset($response->highlighting->{$doc->id}->$hl_param)) {
1290 // Merge arrays preserving keys.
1291 foreach ($response->highlighting->{$doc->id}->$hl_param as $value) {
1292 $snippets[$hl_param][] = $value;
1293 }
1294 }
1295 }
1296 // If there's no snippet at this point, add the teaser.
1297 if (!$snippets) {
1298 if (isset($doc->teaser)) {
1299 $snippets[] = truncate_utf8($doc->teaser, 256, TRUE);
1300 }
1301 }
1302
1303 $hook = 'solrsearch_search_snippets__' . $doc->{'doc-type'};
1304 /*$bundle = !empty($doc->bundle) ? $doc->bundle : NULL;
1305 if ($bundle) {
1306 $hook .= '__' . $bundle;
1307 }*/
1308 $snippet = theme($hook, array('doc' => $doc, 'snippets' => $snippets));
1309
1310 if (!isset($doc->content)) {
1311 $doc->content = $snippet;
1312 }
1313
1314 /*
1315 // Normalize common dates so that we can use Drupal's normal date and
1316 // time handling.
1317 if (isset($doc->ds_created)) {
1318 $doc->created = strtotime($doc->ds_created);
1319 }
1320 else {
1321 $doc->created = NULL;
1322 }
1323
1324 if (isset($doc->ds_changed)) {
1325 $doc->changed = strtotime($doc->ds_changed);
1326 }
1327 else {
1328 $doc->changed = NULL;
1329 }
1330
1331 if (isset($doc->tos_name)) {
1332 $doc->name = $doc->tos_name;
1333 }
1334 else {
1335 $doc->name = NULL;
1336 }
1337 */
1338 // Set all expected fields from fl to NULL if they are missing so
1339 // as to prevent Notice: Undefined property.
1340 $fl = array_merge($fl, array('path', 'label', 'score'));
1341 foreach ($fl as $field) {
1342 if (!isset($doc->{$field})) {
1343 $doc->{$field} = NULL;
1344 }
1345 }
1346
1347 $fields = (array) $doc;
1348
1349 // a path is not a requirement of entity (see entity_uri() ), so we check if we
1350 // can show it and fallback to the main page of the site if we don't
1351 // have it.
1352 if (!isset($doc->url)) {
1353 $path = '';
1354 }
1355 else {
1356 $path = $doc->url;
1357 }
1358
1359 $result = array(
1360
1361 // template_preprocess_search_result() runs check_plain() on the title
1362 // again. Decode to correct the display.
1363 'title' => htmlspecialchars_decode($doc->title[0], ENT_QUOTES),
1364 'author' => htmlspecialchars_decode($doc->author[0], ENT_QUOTES),
1365 // These values are not required by the search module but are provided
1366 // to give entity callbacks and themers more flexibility.
1367 'score' => $doc->score,
1368 'snippets' => $snippets,
1369 'snippet' => $snippet,
1370 'fields' => $fields,
1371 'doc-type' => $doc->{'doc-type'},
1372 'mpiwg-dri' => $doc->{'mpiwg-dri'},
1373 'access-type'=> $doc->{'access-type'},
1374 'year' => $doc->{'year'},
1375 );
1376
1377 if (isset($doc->{'IM_date'})){
1378 $result['date']=$doc->{'IM_date'};
1379 }
1380 if (isset($doc->{'IM_signature'})){
1381 $result['signature']=$doc->{'IM_signature'};
1382 }
1383
1384
1385 // Call entity-type-specific callbacks for extra handling.
1386 /*$function = solrsearch_entity_get_callback($doc->{'doc-type'}, 'result callback', '');
1387 if (is_callable($function)) {
1388 $function($doc, $result, $extra);
1389 }
1390 */
1391 $result['extra'] = $extra;
1392
1393 $results[] = $result;
1394 }
1395 }
1396 // Hook to allow modifications of the retrieved results
1397 foreach (module_implements('solrsearch_process_results') as $module) {
1398 $function = $module . '_solrsearch_process_results';
1399 $function($results, $query);
1400 }
1401 return $results;
1402 }
1403
1404 /**
1405 * Used as a callback function to generate a title for a node/page depending
1406 * on the input in the configuration screen
1407 * @param integer $search_page_id
1408 * @param integer $value
1409 * @return String
1410 */
1411 function searchsolr_search_get_value_title($search_page_id = NULL, $value = NULL) {
1412 $page_title = 'Search results for %value';
1413 if (isset($value) && isset($search_page_id)) {
1414 $search_page = apachesolr_search_page_load($search_page_id);
1415 $page_title = str_replace('%value', '!value', $search_page['page_title']);
1416 $title = $value;
1417 }
1418 return t($page_title, array('!value' => $title));
1419 }
1420
1421 /**
1422 * Retrieve all of the suggestions that were given after a certain search
1423 * @return array()
1424 */
1425 function solrsearch_search_get_search_suggestions($env_id) {
1426 $suggestions_output = array();
1427 if (solrsearch_has_searched($env_id)) {
1428 $query = solrsearch_current_query($env_id);
1429 $keyword = $query->getParam('q');
1430 $searcher = $query->getSearcher();
1431 $response = solrsearch_static_response_cache($searcher);
1432 // Get spellchecker suggestions into an array.
1433 if (!empty($response->spellcheck->suggestions)) {
1434 $suggestions = get_object_vars($response->spellcheck->suggestions);
1435 if ($suggestions) {
1436 $replacements = array();
1437 // Get the original query and retrieve all words with suggestions.
1438 foreach ($suggestions as $word => $value) {
1439 $replacements[$word] = $value->suggestion[0];
1440 }
1441 // Replace the keyword with the suggested keyword.
1442 $suggested_keyword = strtr($keyword, $replacements);
1443 // Show only if suggestion is different than current query.
1444 if ($keyword != $suggested_keyword) {
1445 $suggestions_output[] = $suggested_keyword;
1446 }
1447 }
1448 }
1449 }
1450 return $suggestions_output;
1451 }
1452
1453 /**
1454 * Implements hook_solrsearch_entity_info_alter().
1455 */
1456 function solrsearch_search_solrsearch_entity_info_alter(&$entity_info) {
1457 // First set defaults so that we don't need to worry about NULL keys.
1458 foreach (array_keys($entity_info) as $type) {
1459 $entity_info[$type]['result callback'] = '';
1460 }
1461 // Now set those values that we know. Other modules can do so
1462 // for their own entities if they want.
1463 $entity_info['node']['result callback'] = 'solrsearch_search_node_result';
1464 }
1465
1466 /**
1467 * Callback function for node search results.
1468 *
1469 * @param stdClass $doc
1470 * The result document from Apache Solr.
1471 * @param array $result
1472 * The result array for this record to which to add.
1473 */
1474 function solrsearch_search_node_result($doc, &$result, &$extra) {
1475 $doc->uid = $doc->is_uid;
1476 $result += array(
1477 'type' => node_type_get_name($doc->bundle),
1478 'user' => theme('username', array('account' => $doc)),
1479 'date' => isset($doc->changed) ? $doc->changed : 0,
1480 'node' => $doc,
1481 'uid' => $doc->is_uid,
1482 );
1483
1484 if (isset($doc->is_comment_count)) {
1485 $extra['comments'] = format_plural($doc->is_comment_count, '1 comment', '@count comments');
1486 }
1487 }
1488
1489 /**
1490 * Returns whether a search page exists.
1491 */
1492 function solrsearch_search_page_exists($search_page_id) {
1493 return db_query('SELECT 1 FROM {solrsearch_search_page} WHERE page_id = :page_id', array(':page_id' => $search_page_id))->fetchField();
1494 }
1495
1496 /**
1497 * Template preprocess for solrsearch search results.
1498 *
1499 * We need to add additional entity/bundle-based templates
1500 */
1501 function solrsearch_search_preprocess_search_result(&$variables) {
1502 // If this search result is coming from our module, we want to improve the
1503 // template potential to make life easier for themers.
1504
1505
1506 if ($variables['module'] == 'solrsearch_search') {
1507 $result = $variables['result'];
1508
1509 //info in display should display the author.
1510 $variables['info']=$result['author'];
1511 if (!empty($result['entity_type'])) {
1512 $variables['theme_hook_suggestions'][] = 'search_result__' . $variables['module'] . '__' . $result['entity_type'];
1513 if (!empty($result['bundle'])) {
1514 $variables['theme_hook_suggestions'][] = 'search_result__' . $variables['module'] . '__' . $result['entity_type'] . '__' . $result['bundle'];
1515 }
1516 }
1517 }
1518 }
1519
1520 function solrsearch_search_preprocess_search_results(&$variables) {
1521 // Initialize variables
1522 $env_id = NULL;
1523
1524 // If this is a solr search, expose more data to themes to play with.
1525 if ($variables['module'] == 'solrsearch_search') {
1526 // Fetch our current query
1527 if (!empty($variables['search_page']['env_id'])) {
1528 $env_id = $variables['search_page']['env_id'];
1529 }
1530 $query = solrsearch_current_query($env_id);
1531
1532 if ($query) {
1533 $variables['query'] = $query;
1534 $variables['response'] = solrsearch_static_response_cache($query->getSearcher());
1535 }
1536 if (empty($variables['response'])) {
1537 $variables['description'] = '';
1538 return NULL;
1539 }
1540 $total = $variables['response']->response->numFound;
1541 $params = $variables['query']->getParams();
1542
1543 $variables['description'] = t('Showing items @start through @end of @total.', array(
1544 '@start' => $params['start'] + 1,
1545 '@end' => $params['start'] + $params['rows'] - 1,
1546 '@total' => $total,
1547 ));
1548 // Redefine the pager if it was missing
1549 pager_default_initialize($total, $params['rows']);
1550 $variables['pager'] = theme('pager', array('tags' => NULL));
1551
1552 // Add template hints for environments
1553 if (!empty($env_id)) {
1554 $variables['theme_hook_suggestions'][] = 'search_results__' . $variables['module'] . '__' . $env_id;
1555 // Add template hints for search pages
1556 if (!empty($variables['search_page']['page_id'])) {
1557 $variables['theme_hook_suggestions'][] = 'search_results__' . $variables['module'] . '__' . $variables['search_page']['page_id'];
1558 // Add template hints for both
1559 $variables['theme_hook_suggestions'][] = 'search_results__' . $variables['module'] . '__' . $env_id . '__' . $variables['search_page']['page_id'];
1560 }
1561 }
1562 }
1563 }
1564
1565 /**
1566 * Implements hook_solrsearch_environment_delete().
1567 */
1568 function solrsearch_search_solrsearch_environment_delete($server) {
1569 db_update('solrsearch_search_page')
1570 ->fields(array(
1571 'env_id' => '',
1572 ))
1573 ->condition('env_id', $server['env_id'])
1574 ->execute();
1575 solrsearch_environment_variable_del($server['env_id'], 'solrsearch_search_show_facets');
1576 solrsearch_environment_variable_del($server['env_id'], 'solrsearch_search_facet_pages');
1577 menu_rebuild();
1578 }
1579
1580 /*function solrsearch_search_form_search_block_form_alter(&$form, $form_state) {
1581 if (variable_get('search_default_module') == 'solrsearch_search') {
1582 $form['#submit'][] = 'solrsearch_search_form_search_submit';
1583 }
1584 }
1585 */
1586
1587 /**
1588 * Default theme function for spelling suggestions.
1589 */
1590 function theme_solrsearch_search_suggestions($variables) {
1591 $output = '<div class="spelling-suggestions">';
1592 $output .= '<dl class="form-item"><dt><strong>' . t('Did you mean') . '</strong></dt>';
1593 foreach ((array) $variables['links'] as $link) {
1594 $output .= '<dd>' . $link . '</dd>';
1595 }
1596 $output .= '</dl></div>';
1597 return $output;
1598 }
1599
1600 /**
1601 * Added form submit function to retain filters.
1602 *
1603 * @see solrsearch_search_form_search_form_alter()
1604 */
1605 function solrsearch_search_form_search_submit($form, &$form_state) {
1606 $fv = $form_state['values'];
1607 // Replace keys with their rawurlencoded value
1608 if (isset($fv['search_block_form'])) {
1609 $raw_keys = str_replace("/","%2f",$fv['search_block_form']);
1610 $form_state['redirect'] = str_replace($fv['search_block_form'], $raw_keys, $form_state['redirect']);
1611 }
1612 }
1613
1614
1615 /**
1616 * submit function for the delete_index form.
1617 *
1618 */
1619 function solrsearch_search_build_spellcheck($form, &$form_state) {
1620 try {
1621 $solr = solrsearch_get_solr();
1622 $params['spellcheck'] = 'true';
1623 $params['spellcheck.build'] = 'true';
1624 $response = $solr->search('solr', 0, 0, $params);
1625 }
1626 catch (Exception $e) {
1627 watchdog('Apache Solr', nl2br(check_plain($e->getMessage())), NULL, WATCHDOG_ERROR);
1628 }
1629 }
1630
1631 /**
1632 * Implements hook_form_[form_id]_alter().
1633 *
1634 * Adds settings to show facet blocks on non-search pages.
1635 */
1636 function solrsearch_search_form_facetapi_realm_settings_form_alter(&$form, &$form_state) {
1637
1638 if ('solrsearch' == $form['#facetapi']['adapter']->getId() && 'block' == $form['#facetapi']['realm']['name']) {
1639 // Gets the environment ID from the searcher, stores in #facetapi property.
1640 $env_id = ltrim(strstr($form['#facetapi']['adapter']->getSearcher(), '@'), '@');
1641
1642 $show_facets = solrsearch_environment_variable_get($env_id, 'solrsearch_search_show_facets', 0);
1643 $facet_pages = solrsearch_environment_variable_get($env_id, 'solrsearch_search_facet_pages', '');
1644
1645 $form['#facetapi']['env_id'] = $env_id;
1646
1647 $form['solrsearch_search_show_facets'] = array(
1648 '#type' => 'checkbox',
1649 '#title' => t('Show facets on non-search pages.'),
1650 '#default_value' => $show_facets,
1651 '#weight' => '-10',
1652 );
1653
1654 $form['solrsearch_search_facet_pages'] = array(
1655 '#title' => t('Non-search paths'),
1656 '#type' => 'textarea',
1657 '#default_value' => $facet_pages,
1658 '#weight' => '-10',
1659 '#dependency' => array(
1660 'edit-solrsearch-search-show-facets' => array(1),
1661 ),
1662 );
1663
1664 $form['#submit'][] = 'solrsearch_search_facetapi_realm_settings_form_submit';
1665 }
1666 }
1667
1668 /**
1669 * Form submission handler for facetapi_realm_settings_form().
1670 */
1671 function solrsearch_search_facetapi_realm_settings_form_submit(&$form, &$form_state) {
1672 $env_id = $form['#facetapi']['env_id'];
1673
1674 // Adds the settings to the array keyed by environment ID, saves variables.
1675 $show_facets = $form_state['values']['solrsearch_search_show_facets'];
1676 $facet_pages = $form_state['values']['solrsearch_search_facet_pages'];
1677 if ($show_facets) {
1678 solrsearch_environment_variable_set($env_id, 'solrsearch_search_show_facets', $show_facets);
1679 }
1680 else {
1681 // Due to performance reasons, we delete it from the vars so that our init
1682 // process can react on environments that hae it set and not unset.
1683 // See solrsearch_search_init().
1684 solrsearch_environment_variable_del($env_id, 'solrsearch_search_show_facets');
1685 }
1686 solrsearch_environment_variable_set($env_id, 'solrsearch_search_facet_pages', $facet_pages);
1687 }
1688
1689 /**
1690 * Implements hook_theme().
1691 */
1692 function solrsearch_search_theme() {
1693 return array(
1694 /**
1695 * Shows the facets in blocks in the search result area
1696 */
1697 'solrsearch_search_browse_blocks' => array(
1698 'render element' => 'content',
1699 ),
1700 /**
1701 * Shows the search snippet
1702 */
1703 'solrsearch_search_snippets' => array(
1704 'variables' => array('doc' => NULL, 'snippets' => array()),
1705 ),
1706 /**
1707 * Shows a message when the search does not return any result
1708 */
1709 'solrsearch_search_noresults' => array(
1710 'variables' => array(),
1711 ),
1712 /**
1713 * Shows a list of suggestions
1714 */
1715 'solrsearch_search_suggestions' => array(
1716 'variables' => array('links' => NULL),
1717 ),
1718 /**
1719 * Shows a list of results (docs) in content recommendation block
1720 */
1721 'solrsearch_search_mlt_recommendation_block' => array(
1722 'variables' => array('docs' => NULL, 'delta' => NULL),
1723 ),
1724 'solrsearch_search_block_form' => array(
1725 'render element' => 'form',
1726 'template' => 'solrsearch-block-form',
1727 ),
1728
1729 'solrsearch_search_author_block_form' => array(
1730 'render element' => 'form',
1731 'template' => 'solrsearch-author-block-form',
1732 ),
1733
1734 'solrsearch_search_title_block_form' => array(
1735 'render element' => 'form',
1736 'template' => 'solrsearch-title-block-form',
1737 ),
1738 );
1739 }
1740
1741
1742
1743 /**
1744 * Implements hook_theme_registry_alter().
1745 */
1746 function solrsearch_search_theme_registry_alter(&$theme_registry) {
1747
1748 if (isset($theme_registry['search_results'])) {
1749 $theme_registry['search_results']['variables']['search_page'] = NULL;
1750 }
1751 }
1752
1753 /**
1754 * Theme the highlighted snippet text for a search entry.
1755 *
1756 * @param array $vars
1757 *
1758 */
1759 function theme_solrsearch_search_snippets($vars) {
1760 $result = '';
1761 if (is_array($vars['snippets'])) {
1762 $snippets = $vars['snippets'];
1763 if (isset($snippets['content'])) {
1764 $result .= implode(' ... ', $snippets['content']);
1765 unset($snippets['content']);
1766 }
1767 if (isset($snippets['teaser'])) {
1768 $result .= (strlen($result) > 0) ? ' ... ' : '';
1769 $result .= implode(' ... ', $snippets['teaser']);
1770 unset($snippets['teaser']);
1771 }
1772 if (count($snippets)) {
1773 $result .= (strlen($result) > 0) ? ' ... ' : '';
1774 foreach ($snippets as $snippet) {
1775 $result .= implode(' ... ', $snippet);
1776 }
1777 }
1778 }
1779 return $result . ' ...';
1780 }
1781
1782 /**
1783 * Brief message to display when no results match the query.
1784 *
1785 * @see search_help()
1786 */
1787 function theme_solrsearch_search_noresults() {
1788 return t('<ul>
1789 <li>Check if your spelling is correct, or try removing filters.</li>
1790 <li>Remove quotes around phrases to match each word individually: <em>"blue drop"</em> will match less than <em>blue drop</em>.</li>
1791 <li>You can require or exclude terms using + and -: <em>big +blue drop</em> will require a match on <em>blue</em> while <em>big blue -drop</em> will exclude results that contain <em>drop</em>.</li>
1792 </ul>');
1793 }
1794
1795
1796
1797
1798 /**
1799 * Implements hook_forms().
1800 */
1801 function solrsearch_search_forms() {
1802 $forms['solrsearch_search_block_form']= array(
1803 'callback' => 'solrsearch_search_box',
1804 'callback arguments' => array('solrsearch_search_block_form'),
1805 );
1806
1807 $forms['solrsearch_search_author_block_form']= array(
1808 'callback' => 'solrsearch_search_author_box',
1809 'callback arguments' => array('solrsearch_search_author_block_form'),
1810 );
1811
1812 $forms['solrsearch_search_title_block_form']= array(
1813 'callback' => 'solrsearch_search_title_box',
1814 'callback arguments' => array('solrsearch_search_title_block_form'),
1815 );
1816 return $forms;
1817 }
1818
1819
1820
1821
1822
1823
1824