You are here

function search_api_saved_searches_check_updates in Search API Saved Searches 7

Checks for new results for saved searches, and sends a mail if necessary.

Used as a worker callback for the homonymous cron queue.

Parameters

int[] $search_ids: The IDs of the saved searches to check for new results. All of these should have the same mail address and base settings.

Throws

SearchApiException If an error occurred in one of the searches.

See also

search_api_saved_searches_cron_queue_info()

2 string references to 'search_api_saved_searches_check_updates'
search_api_saved_searches_cron in ./search_api_saved_searches.module
Implements hook_cron().
search_api_saved_searches_cron_queue_info in ./search_api_saved_searches.module
Implements hook_cron_queue_info().

File

./search_api_saved_searches.module, line 1279
Offers the ability to save searches and be notified of new results.

Code

function search_api_saved_searches_check_updates(array $search_ids) {
  if (!$search_ids) {
    return;
  }

  // Since in earlier versions this function got the loaded searches passed
  // directly instead of just IDs, and there might still be some such items in
  // the queue when updating to the new style, we have to stay
  // backwards-compatible here. So, when an array of loaded searches is passed,
  // we first replace them with their IDs and only then load them again.
  if (!is_scalar(reset($search_ids))) {

    /** @var SearchApiSavedSearch[] $searches */
    $searches = $search_ids;
    $search_ids = array();
    foreach ($searches as $search) {
      $search_ids[] = $search->id;
    }
  }
  $searches = search_api_saved_search_load_multiple($search_ids, array(
    'enabled' => 1,
  ));
  if (!$searches) {
    return;
  }
  $search = $searches[key($searches)];
  $settings = $search
    ->settings();
  $index = $settings
    ->index();
  $mail_params = array();
  foreach ($searches as $search) {
    $results = search_api_saved_search_fetch_search_results($search);
    if (!$results['result_count']) {
      continue;
    }

    // Load the result items.
    if ($results['results']) {
      $results['results'] = $index
        ->loadItems($results['results']);
    }
    $mail_params['searches'][] = $results;
  }

  // If we set any searches in the mail parameters, send the mail.
  if ($mail_params) {
    $mail_params['user'] = user_load($search->uid);
    $mail_params['settings'] = $settings;
    $message = drupal_mail('search_api_saved_searches', 'notify', $search->mail, user_preferred_language($mail_params['user']), $mail_params);

    // Add a log message that a mail was sent, unless disabled.
    if ($message['result'] && variable_get('search_api_saved_searches_debug_messages', TRUE)) {
      watchdog('search_api_saved_searches', 'A mail with new saved search results was sent to @mail.', array(
        '@mail' => $search->mail,
      ), WATCHDOG_INFO);
    }
  }
}