<?php

/**
 * @file
 * Provides a Solr-based service class for the Search API.
 */

/**
 * Implements hook_menu().
 */
function search_api_solr_menu() {
  $items['admin/config/search/search_api/server/%search_api_server/files'] = array(
    'title' => 'Files',
    'description' => 'View Solr configuration files.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('search_api_solr_solr_config_form', 5),
    'access callback' => 'search_api_solr_access_server_files',
    'access arguments' => array(5),
    'file' => 'search_api_solr.admin.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => -1,
    'context' => MENU_CONTEXT_INLINE | MENU_CONTEXT_PAGE,
  );

  return $items;
}

/**
 * Implements hook_search_api_service_info().
 */
function search_api_solr_search_api_service_info() {
  $variables = array(
    '@solr_wiki_url' => url('http://wiki.apache.org/solr/SolrQuerySyntax'),
    '@readme_url' => url(drupal_get_path('module', 'search_api_solr') . '/README.txt'),
  );
  $services['search_api_solr_service'] = array(
    'name' => t('Solr service'),
    'description' => t('<p>Index items using an Apache Solr search server.</p>
<ul>
  <li>See <a href="@solr_wiki_url">the Solr wiki</a> for information about the "direct" parse mode.</li>
  <li>Will use internal Solr preprocessors, so Search API preprocessors should for the most part be deactivated.</li>
  <li>See the <a href="@readme_url">README.txt</a> file provided with this module for details.</li>
</ul>', $variables),
    'class' => 'SearchApiSolrService',
  );
  return $services;
}

/**
 * Implements hook_help().
 */
function search_api_solr_help($path, array $arg = array()) {
  if ($path == 'admin/config/search/search_api') {
    // Included because we need the REQUIREMENT_* constants.
    include_once(DRUPAL_ROOT . '/includes/install.inc');
    module_load_include('install', 'search_api_solr');
    $reqs = search_api_solr_requirements('runtime');
    foreach ($reqs as $req) {
      if (isset($req['description'])) {
        $type = $req['severity'] == REQUIREMENT_ERROR ? 'error' : ($req['severity'] == REQUIREMENT_WARNING ? 'warning' : 'status');
        drupal_set_message($req['description'], $type);
      }
    }
  }
}

/**
 * Implements hook_cron().
 *
 * Used to execute an optimization operation on all enabled Solr servers once a
 * day.
 */
function search_api_solr_cron() {
  if (REQUEST_TIME - variable_get('search_api_solr_last_optimize', 0) > 86400) {
    variable_set('search_api_solr_last_optimize', REQUEST_TIME);
    $conditions = array('class' => 'search_api_solr_service', 'enabled' => TRUE);
    foreach (search_api_server_load_multiple(FALSE, $conditions) as $server) {
      try {
        $server->getSolrConnection()->optimize(FALSE);
      }
      catch(Exception $e) {
        watchdog_exception('search_api_solr', $e, '%type while optimizing Solr server @server: !message in %function (line %line of %file).', array('@server' => $server->name));
      }
    }
  }
}

/**
 * Implements hook_flush_caches().
 */
function search_api_solr_flush_caches() {
  return array('cache_search_api_solr');
}


/**
 * Implements hook_search_api_server_update().
 */
function search_api_solr_search_api_server_update(SearchApiServer $server) {
  if ($server->class === 'search_api_solr_service') {
    $server->getSolrConnection()->clearCache();
  }
}

/**
 * Implements hook_views_api().
 */
function search_api_solr_views_api() {
  if (module_exists('search_api_views')) {
    return array(
      'api' => 3,
    );
  }
}

/**
 * Retrieves Solr-specific data for available data types.
 *
 * Returns the data type information for both the default Search API data types
 * and custom data types defined by hook_search_api_data_type_info(). Names for
 * default data types are not included, since they are not relevant to the Solr
 * service class.
 *
 * We're adding some extra Solr field information for the default search api
 * data types (as well as on behalf of a couple contrib field types). The
 * extra information we're adding is documented in
 * search_api_solr_hook_search_api_data_type_info(). You can use the same
 * additional keys in hook_search_api_data_type_info() to support custom
 * dynamic fields in your indexes with Solr.
 *
 * @param string|null $type
 *   (optional) A specific type for which the information should be returned.
 *   Defaults to returning all information.
 *
 * @return array|null
 *   If $type was given, information about that type or NULL if it is unknown.
 *   Otherwise, an array of all types. The format in both cases is the same as
 *   for search_api_get_data_type_info().
 *
 * @see search_api_get_data_type_info()
 * @see search_api_solr_hook_search_api_data_type_info()
 */
function search_api_solr_get_data_type_info($type = NULL) {
  $types = &drupal_static(__FUNCTION__);

  if (!isset($types)) {
    // Grab the stock search_api data types.
    $types = search_api_get_data_type_info();

    // Add our extras for the default search api fields.
    $types += array(
      'text' => array(
        'prefix' => 'tm',
        'always multiValued' => TRUE,
      ),
      'string' => array(
        'prefix' => 's',
      ),
      'integer' => array(
        'prefix' => 'i',
      ),
      'decimal' => array(
        'prefix' => 'f',
      ),
      'date' => array(
        'prefix' => 'd',
      ),
      'duration' => array(
        'prefix' => 'i',
      ),
      'boolean' => array(
        'prefix' => 'b',
      ),
      'uri' => array(
        'prefix' => 's',
      ),
      'tokens' => array(
        'prefix' => 'tm',
        'always multiValued' => TRUE,
      ),
    );

    // Extra data type info.
    $extra_types_info = array(
      'location' => array(
        'prefix' => 'loc',
      ),
      'geohash' => array(
        'prefix' => 'geo',
      ),
    );

    // For the extra types, only add our extra info if it's already been defined.
    foreach ($extra_types_info as $key => $info) {
      if (array_key_exists($key, $types)) {
        // Merge our extras into the data type info
        $types[$key] += $info;
      }
    }
  }

  // Return the info.
  if (isset($type)) {
    return isset($types[$type]) ? $types[$type] : NULL;
  }
  return $types;
}

/**
 * Retrieves a list of all config files of a server.
 *
 * @param SearchApiServer $server
 *   The Solr server whose files should be retrieved.
 * @param string $dir_name
 *   (optional) The directory that should be searched for files. Defaults to the
 *   root config directory.
 *
 * @return array
 *   An associative array of all config files in the given directory. The keys
 *   are the file names, values are arrays with information about the file. The
 *   files are returned in alphabetical order and breadth-first.
 *
 * @throws SearchApiException
 *   If a problem occurred while retrieving the files.
 */
function search_api_solr_server_get_files(SearchApiServer $server, $dir_name = NULL) {
  $response = $server->getFile($dir_name);

  // Search for directories and recursively merge directory files.
  $files_data = json_decode($response->data, TRUE);
  $files_list = $files_data['files'];
  $result = array('' => array());

  foreach ($files_list as $file_name => $file_info) {
    if (empty($file_info['directory'])) {
      $result[''][$file_name] = $file_info;
    }
    else {
      $result[$file_name] = search_api_solr_server_get_files($server, $file_name);
    }
  }

  ksort($result);
  ksort($result['']);
  return array_reduce($result, 'array_merge', array());
}

/**
 * @deprecated
 *
 * @see search_api_solr_access_server_files()
 */
function search_api_access_server_files(SearchApiServer $server) {
  return search_api_solr_access_server_files($server);
}

/**
 * Access callback for a server's "Files" tab.
 *
 * Grants access if the user has the "administer search_api" permission and the
 * server is a Solr server.
 *
 * @param SearchApiServer $server
 *   The server for which access should be tested.
 *
 * @return bool
 *   TRUE if access should be granted, FALSE otherwise.
 */
function search_api_solr_access_server_files(SearchApiServer $server) {
  if (!user_access('administer search_api')) {
    return FALSE;
  }
  $service_info = search_api_get_service_info($server->class);
  $service_class = $service_info['class'];

  if (empty($service_class) || !class_exists($service_class)) {
    // Service class not found.
    return FALSE;
  }
  if ($service_class == 'SearchApiSolrService' || in_array('SearchApiSolrService', class_parents($service_class))) {
    // It's an SearchApiSolrService based connection class.
    return TRUE;
  }

  return FALSE;
}

/**
 * Switches a server to use clean identifiers.
 *
 * Used as a submit callback in SearchApiSolrService::configurationForm().
 */
function _search_api_solr_switch_to_clean_ids(array $form, array &$form_state) {
  $server = $form_state['server'];
  $server->options['clean_ids'] = TRUE;
  $server->save();
  drupal_set_message(t('The Solr server was successfully switched to use clean field identifiers.'));

  $count = 0;
  $conditions['server'] = $server->machine_name;
  $conditions['enabled'] = 1;
  foreach (search_api_index_load_multiple(FALSE, $conditions) as $index) {
    if (!empty($index->options['fields'])) {
      foreach ($index->options['fields'] as $key => $field) {
        if (strpos($key, ':') !== FALSE) {
          $index->reindex();
          ++$count;
          break;
        }
      }
    }
  }
  if ($count) {
    $msg = format_plural($count, '1 index was scheduled for re-indexing.', '@count indexes were scheduled for re-indexing.');
    drupal_set_message($msg);
  }
}
