You are here

search_api.module in Search API 8

Same filename and directory in other branches
  1. 7 search_api.module

Provides a rich framework for creating searches.

File

search_api.module
View source
<?php

/**
 * @file
 * Provides a rich framework for creating searches.
 */
use Drupal\comment\Entity\Comment;
use Drupal\Core\Config\ConfigImporter;
use Drupal\Core\Entity\ContentEntityType;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\node\NodeInterface;
use Drupal\search_api\Entity\Index;
use Drupal\search_api\IndexInterface;
use Drupal\search_api\Plugin\views\argument\SearchApiAllTerms;
use Drupal\search_api\Plugin\views\argument\SearchApiTerm as TermArgument;
use Drupal\search_api\Plugin\views\filter\SearchApiTerm as TermFilter;
use Drupal\search_api\Plugin\views\query\SearchApiQuery;
use Drupal\search_api\SearchApiException;
use Drupal\search_api\Task\IndexTaskManager;
use Drupal\views\ViewEntityInterface;
use Drupal\views\ViewExecutable;

/*
 * Load all theme functions.
 */
require_once __DIR__ . '/search_api.theme.inc';

/**
 * Implements hook_help().
 */
function search_api_help($route_name) {
  switch ($route_name) {
    case 'search_api.overview':
      $message = t('Below is a list of indexes grouped by the server they are associated with. A server is the definition of the actual indexing, querying and storage engine (for example, an Apache Solr server, the database, …). An index defines the indexed content (for example, all content and all comments on "Article" posts).');
      $search_module_warning = _search_api_search_module_warning();
      if ($search_module_warning) {
        $message = "<p>{$message}</p><p>{$search_module_warning}</p>";
      }
      return $message;
  }
  return NULL;
}

/**
 * Implements hook_cron().
 *
 * This will first execute pending tasks (if there are any). After that, items
 * will be indexed on all enabled indexes with a non-zero cron limit. Indexing
 * will run for the time set in the cron_worker_runtime config setting
 * (defaulting to 15 seconds), but will at least index one batch of items on
 * each index.
 */
function search_api_cron() {

  // Execute pending server tasks.
  \Drupal::getContainer()
    ->get('search_api.server_task_manager')
    ->execute();

  // Load all enabled, not read-only indexes.
  $conditions = [
    'status' => TRUE,
  ];
  $index_storage = \Drupal::entityTypeManager()
    ->getStorage('search_api_index');

  /** @var \Drupal\search_api\IndexInterface[] $indexes */
  $indexes = $index_storage
    ->loadByProperties($conditions);
  if (!$indexes) {
    return;
  }

  // Add items to the tracking system for all indexes for which this hasn't
  // happened yet.
  $task_manager = \Drupal::getContainer()
    ->get('search_api.task_manager');
  foreach ($indexes as $index_id => $index) {
    $conditions = [
      'type' => IndexTaskManager::TRACK_ITEMS_TASK_TYPE,
      'index_id' => $index_id,
    ];
    $task_manager
      ->executeSingleTask($conditions);

    // Filter out read-only indexes here, since we want to have tracking but not
    // index items for them.
    if ($index
      ->isReadOnly()) {
      unset($indexes[$index_id]);
    }
  }

  // Now index items.
  // Remember servers which threw an exception.
  $ignored_servers = [];

  // Continue indexing, one batch from each index, until the time is up, but at
  // least index one batch per index.
  $settings = \Drupal::config('search_api.settings');
  $default_cron_limit = $settings
    ->get('default_cron_limit');
  $end = time() + $settings
    ->get('cron_worker_runtime');
  $first_pass = TRUE;
  while (TRUE) {
    if (!$indexes) {
      break;
    }
    foreach ($indexes as $id => $index) {
      if (!$first_pass && time() >= $end) {
        break 2;
      }
      if (!empty($ignored_servers[$index
        ->getServerId()])) {
        continue;
      }
      $limit = $index
        ->getOption('cron_limit', $default_cron_limit);
      $num = 0;
      if ($limit) {
        try {
          $num = $index
            ->indexItems($limit);
          if ($num) {
            $variables = [
              '@num' => $num,
              '%name' => $index
                ->label(),
            ];
            \Drupal::service('logger.channel.search_api')
              ->info('Indexed @num items for index %name.', $variables);
          }
        } catch (SearchApiException $e) {

          // Exceptions will probably be caused by the server in most cases.
          // Therefore, don't index for any index on this server.
          $ignored_servers[$index
            ->getServerId()] = TRUE;
          $vars['%index'] = $index
            ->label();
          watchdog_exception('search_api', $e, '%type while trying to index items on %index: @message in %function (line %line of %file).', $vars);
        }
      }
      if (!$num) {

        // Couldn't index any items => stop indexing for this index in this
        // cron run.
        unset($indexes[$id]);
      }
    }
    $first_pass = FALSE;
  }
}

/**
 * Implements hook_hook_info().
 */
function search_api_hook_info() {
  $hooks = [
    'search_api_backend_info_alter',
    'search_api_server_features_alter',
    'search_api_datasource_info_alter',
    'search_api_processor_info_alter',
    'search_api_data_type_info_alter',
    'search_api_parse_mode_info_alter',
    'search_api_tracker_info_alter',
    'search_api_displays_alter',
    'search_api_field_type_mapping_alter',
    'search_api_views_handler_mapping_alter',
    'search_api_views_field_handler_mapping_alter',
    'search_api_index_items_alter',
    'search_api_items_indexed',
    'search_api_query_alter',
    // Unfortunately, it's not possible to add hook infos for hooks with
    // "wildcards".
    // 'search_api_query_TAG_alter',
    'search_api_results_alter',
    // 'search_api_results_TAG_alter',
    'search_api_index_reindex',
  ];
  $info = [
    'group' => 'search_api',
  ];
  return array_fill_keys($hooks, $info);
}

/**
 * Implements hook_config_import_steps_alter().
 */
function search_api_config_import_steps_alter(&$sync_steps, ConfigImporter $config_importer) {
  $new = $config_importer
    ->getUnprocessedConfiguration('create');
  $changed = $config_importer
    ->getUnprocessedConfiguration('update');
  $new_or_changed = array_merge($new, $changed);
  $prefix = \Drupal::entityTypeManager()
    ->getDefinition('search_api_index')
    ->getConfigPrefix() . '.';
  $prefix_length = strlen($prefix);
  foreach ($new_or_changed as $config_id) {
    if (substr($config_id, 0, $prefix_length) === $prefix) {
      $sync_steps[] = [
        'Drupal\\search_api\\Task\\IndexTaskManager',
        'processIndexTasks',
      ];
    }
  }
}

/**
 * Implements hook_entity_insert().
 *
 * Note that this function implements tracking only on behalf of the "Content
 * Entity" datasource defined in this module, not for entity-based datasources
 * in general. Datasources defined by other modules still have to implement
 * their own mechanism for tracking new/updated/deleted entities.
 *
 * @see \Drupal\search_api\Plugin\search_api\datasource\ContentEntityTrackingManager::entityInsert()
 */
function search_api_entity_insert(EntityInterface $entity) {

  // Call this hook on behalf of the Content Entity datasource.
  \Drupal::getContainer()
    ->get('search_api.entity_datasource.tracking_manager')
    ->entityInsert($entity);
}

/**
 * Implements hook_entity_update().
 *
 * Note that this function implements tracking only on behalf of the "Content
 * Entity" datasource defined in this module, not for entity-based datasources
 * in general. Datasources defined by other modules still have to implement
 * their own mechanism for tracking new/updated/deleted entities.
 *
 * Independent of datasources, however, this will also call
 * \Drupal\search_api\Utility\TrackingHelper::trackReferencedEntityUpdate() to
 * attempt to mark all items for reindexing that indirectly indexed changed
 * fields of this entity.
 *
 * @see \Drupal\search_api\Plugin\search_api\datasource\ContentEntityTrackingManager::entityUpdate()
 * @see \Drupal\search_api\Utility\TrackingHelper::trackReferencedEntityUpdate()
 */
function search_api_entity_update(EntityInterface $entity) {

  // Call this hook on behalf of the Content Entity datasource.
  \Drupal::getContainer()
    ->get('search_api.entity_datasource.tracking_manager')
    ->entityUpdate($entity);

  // Attempt to track all items as changed that indexed updated data indirectly.
  \Drupal::getContainer()
    ->get('search_api.tracking_helper')
    ->trackReferencedEntityUpdate($entity);
}

/**
 * Implements hook_entity_delete().
 *
 * Note that this function implements tracking only on behalf of the "Content
 * Entity" datasource defined in this module, not for entity-based datasources
 * in general. Datasources defined by other modules still have to implement
 * their own mechanism for tracking new/updated/deleted entities.
 *
 * Independent of datasources, however, this will also call
 * \Drupal\search_api\Utility\TrackingHelper::trackReferencedEntityUpdate() to
 * attempt to mark all items for reindexing that indirectly indexed any fields
 * of this entity.
 *
 * @see \Drupal\search_api\Plugin\search_api\datasource\ContentEntityTrackingManager::entityDelete()
 */
function search_api_entity_delete(EntityInterface $entity) {

  // Call this hook on behalf of the Content Entity datasource.
  \Drupal::getContainer()
    ->get('search_api.entity_datasource.tracking_manager')
    ->entityDelete($entity);

  // Attempt to track all items as changed that indexed the entity indirectly.
  \Drupal::getContainer()
    ->get('search_api.tracking_helper')
    ->trackReferencedEntityUpdate($entity, TRUE);
}

/**
 * Implements hook_node_access_records_alter().
 *
 * Marks the node and its comments changed for indexes that use the "Content
 * access" processor.
 */
function search_api_node_access_records_alter(array &$grants, NodeInterface $node) {

  /** @var \Drupal\search_api\IndexInterface $index */
  foreach (Index::loadMultiple() as $index) {
    if (!$index
      ->hasValidTracker() || !$index
      ->status()) {
      continue;
    }
    if (!$index
      ->isValidProcessor('content_access')) {
      continue;
    }
    foreach ($index
      ->getDatasources() as $datasource_id => $datasource) {
      switch ($datasource
        ->getEntityTypeId()) {
        case 'node':

          // Don't index the node if search_api_skip_tracking is set on it.
          if ($node->search_api_skip_tracking) {
            continue 2;
          }
          $item_id = $datasource
            ->getItemId($node
            ->getTypedData());
          if ($item_id !== NULL) {
            $index
              ->trackItemsUpdated($datasource_id, [
              $item_id,
            ]);
          }
          break;
        case 'comment':
          if (!isset($comments)) {
            $comment_ids = \Drupal::entityQuery('comment')
              ->accessCheck(FALSE)
              ->condition('entity_id', (int) $node
              ->id())
              ->condition('entity_type', 'node')
              ->execute();

            /** @var \Drupal\comment\CommentInterface[] $comments */
            $comments = Comment::loadMultiple($comment_ids);
          }
          $item_ids = [];
          foreach ($comments as $comment) {
            $item_id = $datasource
              ->getItemId($comment
              ->getTypedData());
            if ($item_id !== NULL) {
              $item_ids[] = $item_id;
            }
          }
          if ($item_ids) {
            $index
              ->trackItemsUpdated($datasource_id, $item_ids);
          }
          break;
      }
    }
  }
}

/**
 * Implements hook_theme().
 */
function search_api_theme() {
  return [
    'search_api_admin_fields_table' => [
      'render element' => 'element',
    ],
    'search_api_admin_data_type_table' => [
      'variables' => [
        'data_types' => [],
        'fallback_mapping' => [],
        'table' => NULL,
      ],
    ],
    'search_api_form_item_list' => [
      'render element' => 'element',
    ],
    'search_api_server' => [
      'variables' => [
        'server' => NULL,
        'server_info_table' => NULL,
        'description' => NULL,
      ],
    ],
    'search_api_index' => [
      'variables' => [
        'index' => NULL,
        'server_count' => NULL,
        'server_count_error' => NULL,
        'index_process' => NULL,
        'description' => NULL,
        'table' => NULL,
      ],
    ],
  ];
}

/**
 * Implements hook_ENTITY_TYPE_insert() for type "search_api_index".
 *
 * Clears the Views row plugin cache, so our row plugin will become available
 * for new indexes right away.
 *
 * @see search_api_views_plugins_row_alter()
 */
function search_api_search_api_index_insert(Index $index) {
  if (\Drupal::hasService('plugin.manager.views.row')) {
    \Drupal::getContainer()
      ->get('plugin.manager.views.row')
      ->clearCachedDefinitions();
  }
}

/**
 * Implements hook_ENTITY_TYPE_update() for type "search_api_index".
 *
 * Implemented on behalf of the "entity" datasource plugin.
 *
 * @see \Drupal\search_api\Plugin\search_api\datasource\ContentEntityTrackingManager::indexUpdate()
 */
function search_api_search_api_index_update(IndexInterface $index) {
  \Drupal::getContainer()
    ->get('search_api.entity_datasource.tracking_manager')
    ->indexUpdate($index);
}

/**
 * Implements hook_views_plugins_argument_alter().
 */
function search_api_views_plugins_argument_alter(array &$plugins) {

  // We have to include the term argument handler like this, since adding it
  // directly (i.e., with an annotation) would cause fatal errors on sites
  // without the Taxonomy module.
  if (\Drupal::moduleHandler()
    ->moduleExists('taxonomy')) {
    $plugins['search_api_term'] = [
      'plugin_type' => 'argument',
      'id' => 'search_api_term',
      'class' => TermArgument::class,
      'provider' => 'search_api',
    ];
    $plugins['search_api_all_terms'] = [
      'plugin_type' => 'argument',
      'id' => 'search_api_all_terms',
      'class' => SearchApiAllTerms::class,
      'provider' => 'search_api',
    ];
  }
}

/**
 * Implements hook_views_plugins_filter_alter().
 */
function search_api_views_plugins_filter_alter(array &$plugins) {

  // We have to include the term filter handler like this, since adding it
  // directly (i.e., with an annotation) would cause fatal errors on sites
  // without the Taxonomy module.
  if (\Drupal::moduleHandler()
    ->moduleExists('taxonomy')) {
    $plugins['search_api_term'] = [
      'plugin_type' => 'filter',
      'id' => 'search_api_term',
      'class' => TermFilter::class,
      'provider' => 'search_api',
    ];
  }
}

/**
 * Implements hook_ENTITY_TYPE_insert() for type "view".
 */
function search_api_view_insert(ViewEntityInterface $view) {
  _search_api_view_crud_event($view);

  // Disable Views' default caching mechanisms on Search API views.
  $displays = $view
    ->get('display');
  if ($displays['default']['display_options']['query']['type'] === 'search_api_query') {
    $change = FALSE;
    foreach ($displays as $id => $display) {
      if (in_array($display['display_options']['cache']['type'] ?? '', [
        'tag',
        'time',
      ])) {
        $displays[$id]['display_options']['cache']['type'] = 'none';
        $change = TRUE;
      }
    }
    if ($change) {
      $warning = t('The selected caching mechanism does not work with views on Search API indexes. Please either use one of the Search API-specific caching options or "None". Caching was turned off for this view.');
      \Drupal::messenger()
        ->addWarning($warning);
      $view
        ->set('display', $displays);
      $view
        ->save();
    }
  }
}

/**
 * Implements hook_ENTITY_TYPE_update() for type "view".
 */
function search_api_view_update(ViewEntityInterface $view) {
  _search_api_view_crud_event($view);
}

/**
 * Implements hook_ENTITY_TYPE_delete() for type "view".
 */
function search_api_view_delete(ViewEntityInterface $view) {
  _search_api_view_crud_event($view);
}

/**
 * Reacts to a view CRUD event.
 *
 * @param \Drupal\views\ViewEntityInterface $view
 *   The view that was created, changed or deleted.
 */
function _search_api_view_crud_event(ViewEntityInterface $view) {

  // Whenever a view is created, updated (displays might have been added or
  // removed) or deleted, we need to clear our cached display definitions.
  if (SearchApiQuery::getIndexFromTable($view
    ->get('base_table'))) {
    \Drupal::getContainer()
      ->get('plugin.manager.search_api.display')
      ->clearCachedDefinitions();
  }
}

/**
 * Retrieves the allowed values for a list field instance.
 *
 * @param string $entity_type
 *   The entity type to which the field is attached.
 * @param string $bundle
 *   The bundle to which the field is attached.
 * @param string $field_name
 *   The field's field name.
 *
 * @return array|null
 *   An array of allowed values in the form key => label, or NULL.
 *
 * @see _search_api_views_handler_adjustments()
 */
function _search_api_views_get_allowed_values($entity_type, $bundle, $field_name) {
  $field_manager = \Drupal::getContainer()
    ->get('entity_field.manager');
  $field_definitions = $field_manager
    ->getFieldDefinitions($entity_type, $bundle);
  if (!empty($field_definitions[$field_name])) {

    /** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
    $field_definition = $field_definitions[$field_name];
    $options = $field_definition
      ->getSetting('allowed_values');
    if ($options) {
      return $options;
    }
  }
  return NULL;
}

/**
 * Returns an options list for bundles of the given entity type.
 *
 * @param string $entity_type_id
 *   The entity type for which to retrieve the bundle names.
 *
 * @return array
 *   An array of allowed values, mapping bundle keys to their (translated)
 *   identifiers.
 *
 * @see _search_api_views_handler_adjustments()
 */
function _search_api_views_get_bundle_names(string $entity_type_id) {
  $bundles = \Drupal::service('entity_type.bundle.info')
    ->getBundleInfo($entity_type_id);
  return array_map(function ($bundle_info) {
    return $bundle_info['label'];
  }, $bundles);
}

/**
 * Implements hook_form_FORM_ID_alter() for form "views_ui_edit_display_form".
 */
function search_api_form_views_ui_edit_display_form_alter(&$form, FormStateInterface $form_state) {

  // Disable Views' default caching mechanisms on Search API views.
  $displays = $form_state
    ->getStorage()['view']
    ->get('display');
  if ($displays['default']['display_options']['query']['type'] === 'search_api_query') {
    unset($form['options']['cache']['type']['#options']['tag']);
    unset($form['options']['cache']['type']['#options']['time']);
  }
}

/**
 * Returns a warning message if the Core Search module is enabled.
 *
 * @return string|null
 *   A warning message if needed, NULL otherwise.
 *
 * @see search_api_install()
 * @see search_api_requirements()
 */
function _search_api_search_module_warning() {
  if (\Drupal::moduleHandler()
    ->moduleExists('search')) {
    $args = [
      ':url' => Url::fromRoute('system.modules_uninstall')
        ->toString(),
      ':documentation' => 'https://www.drupal.org/docs/8/modules/search-api/getting-started/common-pitfalls#core-search',
    ];
    return t('The default Drupal core Search module is still enabled. If you are using Search API, you probably want to <a href=":url">uninstall</a> the Search module for performance reasons. For more information see <a href=":documentation">the Search API handbook</a>.', $args);
  }
  return NULL;
}

/**
 * Implements hook_form_FORM_ID_alter() for views_exposed_form().
 *
 * Custom integration for facets. When a Views exposed filter is modified on a
 * search results page it will lose any facets which have been already selected.
 * This adds hidden fields for each facet so their values are retained.
 */
function search_api_form_views_exposed_form_alter(&$form, FormStateInterface $form_state) {

  // Retrieve the view object and the query plugin.
  $storage = $form_state
    ->getStorage();
  if (!isset($storage['view'])) {
    return;
  }
  $view = $storage['view'];
  if (!$view instanceof ViewExecutable) {
    return;
  }
  $query_plugin = $view
    ->getQuery();

  // Make sure the view is based on Search API and has the "Preserve facets"
  // option enabled, and that the Facets module is installed.
  $preserve_facets = !empty($query_plugin->options['preserve_facet_query_args']) && $query_plugin instanceof SearchApiQuery && \Drupal::moduleHandler()
    ->moduleExists('facets');
  if ($preserve_facets) {
    $filter_key = 'f';

    // Attempt to retrieve the facet source to use the actual facets filter
    // parameter as configured by the admin. (Facet source config entities are
    // not always actually saved in the storage, if the admin didn't change
    // their settings.)
    $query = $query_plugin
      ->getSearchApiQuery();
    $display_id = $query
      ->getSearchId(FALSE);
    $facet_source_id = str_replace(':', '__', 'search_api:' . $display_id);
    $facet_source = \Drupal::entityTypeManager()
      ->getStorage('facets_facet_source')
      ->load($facet_source_id);
    if ($facet_source) {
      $filter_key = $facet_source
        ->getFilterKey() ?: 'f';
    }

    // Get the active facet filters from the query parameters.
    $filters = \Drupal::request()->query
      ->get($filter_key, []);

    // Do not iterate over facet filters if the parameter is not an array.
    if (!is_array($filters)) {
      return;
    }

    // Iterate through the facet filters.
    foreach ($filters as $key => $value) {
      if (!is_string($value)) {
        continue;
      }

      // Add a hidden form field for the facet parameter.
      $form["{$filter_key}[{$key}]"] = [
        '#type' => 'hidden',
        '#value' => $value,
      ];
    }
  }
}

/**
 * Implements hook_entity_extra_field_info().
 */
function search_api_entity_extra_field_info() {
  $extra = [];

  // Add an extra "excerpt" field to every content entity.
  $entity_types = \Drupal::entityTypeManager()
    ->getDefinitions();
  $bundle_info = \Drupal::getContainer()
    ->get('entity_type.bundle.info');
  foreach ($entity_types as $entity_type_id => $entity_type) {
    if ($entity_type instanceof ContentEntityType) {
      $bundles = $bundle_info
        ->getBundleInfo($entity_type_id);
      foreach ($bundles as $bundle => $data) {
        $extra[$entity_type_id][$bundle]['display']['search_api_excerpt'] = [
          'label' => t('Search result excerpt'),
          'description' => t('An excerpt provided by Search API when rendered in a search.'),
          'weight' => 100,
          'visible' => FALSE,
        ];
      }
    }
  }
  return $extra;
}

/**
 * Implements hook_entity_view().
 */
function search_api_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  $excerpt_component = $display
    ->getComponent('search_api_excerpt');
  if ($excerpt_component !== NULL && isset($build['#search_api_excerpt'])) {
    $build['search_api_excerpt'] = [
      '#type' => 'markup',
      '#markup' => $build['#search_api_excerpt'],
      '#cache' => [
        'contexts' => [
          'url.query_args',
        ],
      ],
    ];
  }
}

Functions

Namesort descending Description
search_api_config_import_steps_alter Implements hook_config_import_steps_alter().
search_api_cron Implements hook_cron().
search_api_entity_delete Implements hook_entity_delete().
search_api_entity_extra_field_info Implements hook_entity_extra_field_info().
search_api_entity_insert Implements hook_entity_insert().
search_api_entity_update Implements hook_entity_update().
search_api_entity_view Implements hook_entity_view().
search_api_form_views_exposed_form_alter Implements hook_form_FORM_ID_alter() for views_exposed_form().
search_api_form_views_ui_edit_display_form_alter Implements hook_form_FORM_ID_alter() for form "views_ui_edit_display_form".
search_api_help Implements hook_help().
search_api_hook_info Implements hook_hook_info().
search_api_node_access_records_alter Implements hook_node_access_records_alter().
search_api_search_api_index_insert Implements hook_ENTITY_TYPE_insert() for type "search_api_index".
search_api_search_api_index_update Implements hook_ENTITY_TYPE_update() for type "search_api_index".
search_api_theme Implements hook_theme().
search_api_views_plugins_argument_alter Implements hook_views_plugins_argument_alter().
search_api_views_plugins_filter_alter Implements hook_views_plugins_filter_alter().
search_api_view_delete Implements hook_ENTITY_TYPE_delete() for type "view".
search_api_view_insert Implements hook_ENTITY_TYPE_insert() for type "view".
search_api_view_update Implements hook_ENTITY_TYPE_update() for type "view".
_search_api_search_module_warning Returns a warning message if the Core Search module is enabled.
_search_api_views_get_allowed_values Retrieves the allowed values for a list field instance.
_search_api_views_get_bundle_names Returns an options list for bundles of the given entity type.
_search_api_view_crud_event Reacts to a view CRUD event.