You are here

function search_api_saved_searches_query_search_api_saved_search_access_alter in Search API Saved Searches 8

Implements hook_query_TAG_alter() for "search_api_saved_search_access".

File

./search_api_saved_searches.module, line 34
Allows visitors to bookmark searches and get notifications for new results.

Code

function search_api_saved_searches_query_search_api_saved_search_access_alter(AlterableInterface $query) {

  // Read the account to use from the query, if provided.
  $account = $query
    ->getMetaData('account') ?: \Drupal::currentUser();
  $admin_permission = SavedSearchAccessControlHandler::ADMIN_PERMISSION;
  if ($account
    ->hasPermission($admin_permission)) {
    return;
  }

  // Non-admins can only see their own saved searches, anonymous users can't see
  // any saved search listing (only individual searches, using an access token).
  $uid = $account
    ->isAnonymous() ? -1 : $account
    ->id();
  if ($query instanceof QueryInterface) {
    $query
      ->condition('uid', $uid);
  }
  elseif ($query instanceof SelectInterface) {
    $search_table = NULL;
    foreach ($query
      ->getTables() as $key => $table_info) {
      if ($table_info['table'] === 'search_api_saved_search') {
        $search_table = $key;
        break;
      }
    }
    if (!$search_table) {
      $query
        ->where('1 <> 1');
      \Drupal::logger('search_api_saved_searches')
        ->error('Could not add access checks to Saved Search query: base table not found');
      return;
    }
    $query
      ->condition("{$search_table}.uid", $uid);
  }
  else {
    $args['@class'] = get_class($query);
    \Drupal::logger('search_api_saved_searches')
      ->error('Could not add access checks to Saved Search query: query is of unknown class @class', $args);
  }
}