You are here

function gss_search_results in Google Site Search 6

Same name and namespace in other branches
  1. 7 gss.module \gss_search_results()

Search results page.

1 call to gss_search_results()
gss_search in ./gss.module
Implementation of hook_search().

File

./gss.module, line 128

Code

function gss_search_results($query) {
  global $language;

  // Include dependencies.
  module_load_include('inc', 'gss', 'includes/GoogleSiteSearch');

  // Make query safe.
  $query = check_plain($query);

  // Init GoogleSiteSearch object.
  $gss = new GoogleSiteSearch($query, variable_get('gss_api_key', ''));

  // Get current page.
  $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

  // Init results variable.
  $results = null;

  // Set the number of results per page.
  $gss
    ->SetPageSize(variable_get('gss_page_size', 20));

  // Set the number of pages to show in the pager.
  $gss
    ->SetPagerSize(variable_get('gss_pager_size', 20));

  // Set the search language
  $default_lang = variable_get('gss_default_language', FALSE);
  if ($default_lang) {
    $gss
      ->SetLanguage($language->language);
  }
  else {
    $gss
      ->SetLanguage(variable_get('gss_language', ''));
  }

  // Perform search.
  try {
    $results = $gss
      ->GetSearchResults($page);
  } catch (Exception $e) {
    watchdog('gss', $e, NULL, WATCHDOG_ERROR);
    drupal_set_message(t('Sorry, the search function is unavailable at this time.'));
    exit;
  }

  // Get search summary.
  $total_results = $gss
    ->GetTotalResults();
  $end_pos = $gss
    ->GetCurrentPage() * $gss
    ->GetPageSize();
  $start_pos = $end_pos - $gss
    ->GetPageSize() + 1;
  if ($end_pos > $total_results) {
    $end_pos = $total_results;
  }

  // Build output.
  if (!empty($results)) {
    $output = array();

    // Loop results.
    foreach ($results as $result) {
      $result['thumbnail_url'] = isset($result['thumbnail_url']) ? $result['thumbnail_url'] : '';

      //just to avoid warnings in the log if not set
      $output[] = array(
        'link' => urldecode($result['url']),
        'title' => $result['title'],
        'thumbnail_url' => $result['thumbnail_url'],
        'snippet' => $result['description'],
      );
    }
  }
  else {
    $output[] = array(
      'link' => '',
      'title' => '',
      'snippet' => t('No results'),
    );
  }

  // Get searrch head
  $output['head'] = $gss
    ->GetSearchHead();

  // Get pager
  $output['pager'] = $gss
    ->GetPager();
  return $output;
}