<?php
/**
 * @file
 * search_api_stats.module
 */

/**
 * Implements hook_search_api_query_alter($query).
 *
 * @param SearchApiQueryInterface $query
 *  The SearchApiQueryInterface object representing the search query.
 */
function search_api_stats_search_api_query_alter(SearchApiQueryInterface $query) {

  global $user;

  // Assign some object variables to avoid chained member access.
  $index = $query->getIndex();
  if (!empty($index)) {
    $server = $index->server();
  }

  // Fail out if there's no valid index or server objects to work from.
  if (empty($index) || empty($server)) {
    return;
  }

  $log = array(
    's_name' => $server->machine_name,
    'i_name' => $index->machine_name,
    'timestamp' => REQUEST_TIME,
    'uid' => $user->uid,
    'sid' => session_id(),
    'keywords' => trim(drupal_strtolower($query->getOriginalKeys())),
    'filters' => '',
    'sort' => '',
  );

  drupal_write_record('search_api_stats', $log);
}