<?php

/**
 * Displays a search page.
 *
 * @param $id
 *   The search page's machine name.
 * @param $keys
 *   The keys to search for.
 */
function search_api_page_view($id, $keys = NULL) {
  $page = search_api_page_load($id);
  if (!$page) {
    return MENU_NOT_FOUND;
  }

  // Override per_page setting with GET parameter.
  if (!empty($_GET['per_page']) && !empty($page->options['get_per_page']) && ((int) $_GET['per_page']) > 0) {
    // Remember and later restore the true setting value so we don't
    // accidentally permanently save the altered one.
    $page->options['original_per_page'] = $page->options['per_page'];
    $page->options['per_page'] = (int) $_GET['per_page'];
  }

  if (isset($page->options['result_page_search_form']) && $page->options['result_page_search_form']) {
    $ret['form'] = drupal_get_form('search_api_page_search_form', $page, $keys);
  }

  if ($keys) {
    try {
      $results = search_api_page_search_execute($page, $keys);
    }
    catch (SearchApiException $e) {
      $ret['message'] = t('An error occurred while executing the search. Please try again or contact the site administrator if the problem persists.');
      watchdog('search_api_page', 'An error occurred while executing a search: !msg.', array('!msg' => $e->getMessage()), WATCHDOG_ERROR, l(t('search page'), $_GET['q']));
    }

    // Load spellcheck.
    if (isset($results['search_api_spellcheck'])) {
      $ret['results']['#spellcheck'] = array(
        '#theme' => 'search_api_spellcheck',
        '#spellcheck' => $results['search_api_spellcheck'],
      // Let the theme function know where the key is stored by passing its arg
      // number. We can work this out from the number of args in the page path.
        '#options' => array(
          'arg' => array(count(arg(NULL, $page->path))),
        ),
        '#prefix' => '<p class="search-api-spellcheck suggestion">',
        '#suffix' => '</p>',
      );
    }

    $ret['results']['#theme'] = 'search_api_page_results';
    $ret['results']['#index'] = search_api_index_load($page->index_id);
    $ret['results']['#results'] = $results;
    $ret['results']['#view_mode'] = isset($page->options['view_mode']) ? $page->options['view_mode'] : 'search_api_page_result';
    $ret['results']['#keys'] = $keys;
    $ret['results']['#page_machine_name'] = $page->machine_name;

    // Load pager.
    if ($results['result count'] > $page->options['per_page']) {
      pager_default_initialize($results['result count'], $page->options['per_page']);
      $ret['results']['#pager'] = theme('pager');
    }

    if (!empty($results['ignored'])) {
      drupal_set_message(t('The following search keys are too short or too common and were therefore ignored: "@list".', array('@list' => implode(t('", "'), $results['ignored']))), 'warning');
    }
    if (!empty($results['warnings'])) {
      foreach ($results['warnings'] as $warning) {
        drupal_set_message($warning, 'warning');
      }
    }
  }

  if (isset($page->options['original_per_page'])) {
    $page->options['per_page'] = $page->options['original_per_page'];
    unset($page->options['original_per_page']);
  }

  return $ret;
}

/**
 * Executes a search.
 *
 * @param Entity $page
 *   The page for which a search should be executed.
 * @param $keys
 *   The keywords to search for.
 *
 * @return array
 *   The search results as returned by SearchApiQueryInterface::execute().
 */
function search_api_page_search_execute(Entity $page, $keys) {
  $limit = $page->options['per_page'];
  $offset = pager_find_page() * $limit;
  $options = array(
    'search id' => 'search_api_page:' . $page->path,
    'parse mode' => $page->options['mode'],
  );

  if (!empty($page->options['search_api_spellcheck'])) {
    $options['search_api_spellcheck'] = TRUE;
  }

  $query = search_api_query($page->index_id, $options)
    ->keys($keys)
    ->range($offset, $limit);
  if (!empty($page->options['fields'])) {
    $query->fields($page->options['fields']);
  }
  return $query->execute();
}

/**
 * Function for preprocessing the variables for the search_api_page_results
 * template.
 *
 * @param array $variables
 *   An associative array containing:
 *   - $index: The index this search was executed on.
 *   - $results: An array of search results, as returned by
 *     SearchApiQueryInterface::execute().
 *   - $keys: The keywords of the executed search.
 *
 * @see search_api_page-results.tpl.php
 */
function template_preprocess_search_api_page_results(array &$variables) {
  $results = $variables['results'];
  $keys = $variables['keys'];

  $variables['items'] = $variables['index']->loadItems(array_keys($variables['results']['results']));
  $variables['result_count'] = $results['result count'];
  $variables['sec'] = round($results['performance']['complete'], 3);
  $variables['search_performance'] = array(
      '#theme' => 'search_performance',
      '#markup' => format_plural(
        $results['result count'],
        'The search found 1 result in @sec seconds.',
        'The search found @count results in @sec seconds.',
        array('@sec' => $variables['sec'])
      ),
      '#prefix' => '<p class="search-performance">',
      '#suffix' => '</p>',
  );

  $variables['search_results'] = array(
    '#theme' => 'search_results_list',
    'results' => $variables['results']['results'],
    'items' => $variables['items'],
    'index' => $variables['index'],
    'type' => 'ul',
  );
}

/**
 * Process variables for search-result.tpl.php.
 *
 * The $variables array contains the following arguments:
 * - $result
 *
 * @see search_api_page-result.tpl.php
 */
function template_preprocess_search_api_page_result(&$variables) {
  $index = $variables['index'];
  $variables['id'] = $variables['result']['id'];
  $variables['excerpt'] = $variables['result']['excerpt'];
  $item = $variables['item'];

  $wrapper = $index->entityWrapper($item, FALSE);

  $variables['url'] = $index->datasource()->getItemUrl($item);
  $variables['title'] = $index->datasource()->getItemLabel($item);

  if (!empty($variables['excerpt'])) {
    $text = $variables['excerpt'];
  }
  else {
    $fields = $index->options['fields'];
    $fields = array_intersect_key($fields, drupal_map_assoc($index->getFulltextFields()));
    $fields = search_api_extract_fields($wrapper, $fields);
    $text = '';
    $length = 0;
    foreach ($fields as $field_name => $field) {
      if (search_api_is_list_type($field['type']) || !isset($field['value'])) {
        continue;
      }
      $val_length = drupal_strlen($field['value']);
      if ($val_length > $length) {
        $text = $field['value'];
        $length = $val_length;

        $format = NULL;
        if (($pos = strrpos($field_name, ':')) && substr($field_name, $pos + 1) == 'value') {
          $tmp = $wrapper;
          try {
            foreach (explode(':', substr($field_name, 0, $pos)) as $part) {
              if (!isset($tmp->$part)) {
                $tmp = NULL;
              }
              $tmp = $tmp->$part;
            }
          }
          catch (EntityMetadataWrapperException $e) {
            $tmp = NULL;
          }
          if ($tmp && $tmp->type() == 'text_formatted' && isset($tmp->format)) {
            $format = $tmp->format->value();
          }
        }
      }
    }
    if ($text && function_exists('text_summary')) {
      $text = text_summary($text, $format);
    }
  }

  // Check for existence. User search does not include snippets.
  $variables['snippet'] = isset($text) ? $text : '';

  // Meta information
  global $language;
  if (isset($item->language) && $item->language != $language->language && $item->language != LANGUAGE_NONE) {
    $variables['title_attributes_array']['xml:lang'] = $item->language;
    $variables['content_attributes_array']['xml:lang'] = $item->language;
  }

  $info = array();
  if (!empty($item->name)) {
    $info['user'] = $item->name;
  }
  if (!empty($item->created)) {
    $info['date'] = format_date($item->created, 'short');
  }
  // Provide separated and grouped meta information..
  $variables['info_split'] = $info;
  $variables['info'] = implode(' - ', $info);
}
