search_api.module 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. <?php
  2. /**
  3. * @file
  4. * Provides a rich framework for creating searches.
  5. */
  6. use Drupal\comment\Entity\Comment;
  7. use Drupal\Core\Config\ConfigImporter;
  8. use Drupal\Core\Entity\ContentEntityInterface;
  9. use Drupal\Core\Entity\EntityInterface;
  10. use Drupal\Core\Form\FormStateInterface;
  11. use Drupal\Core\Url;
  12. use Drupal\node\NodeInterface;
  13. use Drupal\search_api\Entity\Index;
  14. use Drupal\search_api\IndexInterface;
  15. use Drupal\search_api\Plugin\search_api\datasource\ContentEntity;
  16. use Drupal\search_api\Plugin\search_api\datasource\ContentEntityTaskManager;
  17. use Drupal\search_api\Plugin\search_api\datasource\EntityDatasourceInterface;
  18. use Drupal\search_api\Plugin\views\argument\SearchApiTerm as TermArgument;
  19. use Drupal\search_api\Plugin\views\filter\SearchApiTerm as TermFilter;
  20. use Drupal\search_api\Plugin\views\query\SearchApiQuery;
  21. use Drupal\search_api\SearchApiException;
  22. use Drupal\search_api\Task\IndexTaskManager;
  23. use Drupal\views\ViewEntityInterface;
  24. /**
  25. * Implements hook_help().
  26. */
  27. function search_api_help($route_name) {
  28. switch ($route_name) {
  29. case 'search_api.overview':
  30. $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).');
  31. $search_module_warning = _search_api_search_module_warning();
  32. if ($search_module_warning) {
  33. $message = "<p>$message</p><p>$search_module_warning</p>";
  34. }
  35. return $message;
  36. }
  37. return NULL;
  38. }
  39. /**
  40. * Implements hook_cron().
  41. *
  42. * This will first execute pending tasks (if there are any). After that, items
  43. * will be indexed on all enabled indexes with a non-zero cron limit. Indexing
  44. * will run for the time set in the cron_worker_runtime config setting
  45. * (defaulting to 15 seconds), but will at least index one batch of items on
  46. * each index.
  47. */
  48. function search_api_cron() {
  49. // Execute pending server tasks.
  50. \Drupal::getContainer()->get('search_api.server_task_manager')->execute();
  51. // Load all enabled, not read-only indexes.
  52. $conditions = [
  53. 'status' => TRUE,
  54. ];
  55. $index_storage = \Drupal::entityTypeManager()->getStorage('search_api_index');
  56. /** @var \Drupal\search_api\IndexInterface[] $indexes */
  57. $indexes = $index_storage->loadByProperties($conditions);
  58. if (!$indexes) {
  59. return;
  60. }
  61. // Add items to the tracking system for all indexes for which this hasn't
  62. // happened yet.
  63. $task_manager = \Drupal::getContainer()->get('search_api.task_manager');
  64. foreach ($indexes as $index_id => $index) {
  65. $conditions = [
  66. 'type' => IndexTaskManager::TRACK_ITEMS_TASK_TYPE,
  67. 'index_id' => $index_id,
  68. ];
  69. $task_manager->executeSingleTask($conditions);
  70. // Filter out read-only indexes here, since we want to have tracking but not
  71. // index items for them.
  72. if ($index->isReadOnly()) {
  73. unset($indexes[$index_id]);
  74. }
  75. }
  76. // Now index items.
  77. // Remember servers which threw an exception.
  78. $ignored_servers = [];
  79. // Continue indexing, one batch from each index, until the time is up, but at
  80. // least index one batch per index.
  81. $settings = \Drupal::config('search_api.settings');
  82. $default_cron_limit = $settings->get('default_cron_limit');
  83. $end = time() + $settings->get('cron_worker_runtime');
  84. $first_pass = TRUE;
  85. while (TRUE) {
  86. if (!$indexes) {
  87. break;
  88. }
  89. foreach ($indexes as $id => $index) {
  90. if (!$first_pass && time() >= $end) {
  91. break 2;
  92. }
  93. if (!empty($ignored_servers[$index->getServerId()])) {
  94. continue;
  95. }
  96. $limit = $index->getOption('cron_limit', $default_cron_limit);
  97. $num = 0;
  98. if ($limit) {
  99. try {
  100. $num = $index->indexItems($limit);
  101. if ($num) {
  102. $variables = [
  103. '@num' => $num,
  104. '%name' => $index->label(),
  105. ];
  106. \Drupal::service('logger.channel.search_api')->info('Indexed @num items for index %name.', $variables);
  107. }
  108. }
  109. catch (SearchApiException $e) {
  110. // Exceptions will probably be caused by the server in most cases.
  111. // Therefore, don't index for any index on this server.
  112. $ignored_servers[$index->getServerId()] = TRUE;
  113. $vars['%index'] = $index->label();
  114. watchdog_exception('search_api', $e, '%type while trying to index items on %index: @message in %function (line %line of %file).', $vars);
  115. }
  116. }
  117. if (!$num) {
  118. // Couldn't index any items => stop indexing for this index in this
  119. // cron run.
  120. unset($indexes[$id]);
  121. }
  122. }
  123. $first_pass = FALSE;
  124. }
  125. }
  126. /**
  127. * Implements hook_hook_info().
  128. */
  129. function search_api_hook_info() {
  130. $hooks = [
  131. 'search_api_backend_info_alter',
  132. 'search_api_server_features_alter',
  133. 'search_api_datasource_info_alter',
  134. 'search_api_processor_info_alter',
  135. 'search_api_data_type_info_alter',
  136. 'search_api_parse_mode_info_alter',
  137. 'search_api_tracker_info_alter',
  138. 'search_api_displays_alter',
  139. 'search_api_field_type_mapping_alter',
  140. 'search_api_views_handler_mapping_alter',
  141. 'search_api_views_field_handler_mapping_alter',
  142. 'search_api_index_items_alter',
  143. 'search_api_items_indexed',
  144. 'search_api_query_alter',
  145. // Unfortunately, it's not possible to add hook infos for hooks with
  146. // "wildcards".
  147. // 'search_api_query_TAG_alter',
  148. 'search_api_results_alter',
  149. // 'search_api_results_TAG_alter',
  150. 'search_api_index_reindex',
  151. ];
  152. $info = [
  153. 'group' => 'search_api',
  154. ];
  155. return array_fill_keys($hooks, $info);
  156. }
  157. /**
  158. * Implements hook_config_import_steps_alter().
  159. */
  160. function search_api_config_import_steps_alter(&$sync_steps, ConfigImporter $config_importer) {
  161. $new = $config_importer->getUnprocessedConfiguration('create');
  162. $changed = $config_importer->getUnprocessedConfiguration('update');
  163. $new_or_changed = array_merge($new, $changed);
  164. $prefix = \Drupal::entityTypeManager()->getDefinition('search_api_index')->getConfigPrefix() . '.';
  165. $prefix_length = strlen($prefix);
  166. foreach ($new_or_changed as $config_id) {
  167. if (substr($config_id, 0, $prefix_length) === $prefix) {
  168. $sync_steps[] = ['Drupal\search_api\Task\IndexTaskManager', 'processIndexTasks'];
  169. }
  170. }
  171. }
  172. /**
  173. * Implements hook_entity_insert().
  174. *
  175. * Adds entries for all languages of the new entity to the tracking table for
  176. * each index that tracks entities of this type.
  177. *
  178. * By setting the $entity->search_api_skip_tracking property to a true-like
  179. * value before this hook is invoked, you can prevent this behavior and make the
  180. * Search API ignore this new entity.
  181. *
  182. * Note that this function implements tracking only on behalf of the "Content
  183. * Entity" datasource defined in this module, not for entity-based datasources
  184. * in general. Datasources defined by other modules still have to implement
  185. * their own mechanism for tracking new/updated/deleted entities.
  186. *
  187. * @see \Drupal\search_api\Plugin\search_api\datasource\ContentEntity
  188. */
  189. function search_api_entity_insert(EntityInterface $entity) {
  190. // Check if the entity is a content entity.
  191. if (!($entity instanceof ContentEntityInterface) || $entity->search_api_skip_tracking) {
  192. return;
  193. }
  194. $indexes = ContentEntity::getIndexesForEntity($entity);
  195. if (!$indexes) {
  196. return;
  197. }
  198. // Compute the item IDs for all languages of the entity.
  199. $item_ids = [];
  200. $entity_id = $entity->id();
  201. foreach (array_keys($entity->getTranslationLanguages()) as $langcode) {
  202. $item_ids[] = $entity_id . ':' . $langcode;
  203. }
  204. $datasource_id = 'entity:' . $entity->getEntityTypeId();
  205. foreach ($indexes as $index) {
  206. $filtered_item_ids = ContentEntity::filterValidItemIds($index, $datasource_id, $item_ids);
  207. $index->trackItemsInserted($datasource_id, $filtered_item_ids);
  208. }
  209. }
  210. /**
  211. * Implements hook_entity_update().
  212. *
  213. * Updates the corresponding tracking table entries for each index that tracks
  214. * this entity.
  215. *
  216. * Also takes care of new or deleted translations.
  217. *
  218. * By setting the $entity->search_api_skip_tracking property to a true-like
  219. * value before this hook is invoked, you can prevent this behavior and make the
  220. * Search API ignore this update.
  221. *
  222. * Note that this function implements tracking only on behalf of the "Content
  223. * Entity" datasource defined in this module, not for entity-based datasources
  224. * in general. Datasources defined by other modules still have to implement
  225. * their own mechanism for tracking new/updated/deleted entities.
  226. *
  227. * @see \Drupal\search_api\Plugin\search_api\datasource\ContentEntity
  228. */
  229. function search_api_entity_update(EntityInterface $entity) {
  230. // Check if the entity is a content entity.
  231. if (!($entity instanceof ContentEntityInterface) || $entity->search_api_skip_tracking) {
  232. return;
  233. }
  234. $indexes = ContentEntity::getIndexesForEntity($entity);
  235. if (!$indexes) {
  236. return;
  237. }
  238. // Compare old and new languages for the entity to identify inserted,
  239. // updated and deleted translations (and, therefore, search items).
  240. $entity_id = $entity->id();
  241. $inserted_item_ids = [];
  242. $updated_item_ids = $entity->getTranslationLanguages();
  243. $deleted_item_ids = [];
  244. $old_translations = $entity->original->getTranslationLanguages();
  245. foreach ($old_translations as $langcode => $language) {
  246. if (!isset($updated_item_ids[$langcode])) {
  247. $deleted_item_ids[] = $langcode;
  248. }
  249. }
  250. foreach ($updated_item_ids as $langcode => $language) {
  251. if (!isset($old_translations[$langcode])) {
  252. unset($updated_item_ids[$langcode]);
  253. $inserted_item_ids[] = $langcode;
  254. }
  255. }
  256. $datasource_id = 'entity:' . $entity->getEntityTypeId();
  257. $combine_id = function ($langcode) use ($entity_id) {
  258. return $entity_id . ':' . $langcode;
  259. };
  260. $inserted_item_ids = array_map($combine_id, $inserted_item_ids);
  261. $updated_item_ids = array_map($combine_id, array_keys($updated_item_ids));
  262. $deleted_item_ids = array_map($combine_id, $deleted_item_ids);
  263. foreach ($indexes as $index) {
  264. if ($inserted_item_ids) {
  265. $filtered_item_ids = ContentEntity::filterValidItemIds($index, $datasource_id, $inserted_item_ids);
  266. $index->trackItemsInserted($datasource_id, $filtered_item_ids);
  267. }
  268. if ($updated_item_ids) {
  269. $index->trackItemsUpdated($datasource_id, $updated_item_ids);
  270. }
  271. if ($deleted_item_ids) {
  272. $index->trackItemsDeleted($datasource_id, $deleted_item_ids);
  273. }
  274. }
  275. }
  276. /**
  277. * Implements hook_entity_delete().
  278. *
  279. * Deletes all entries for this entity from the tracking table for each index
  280. * that tracks this entity type.
  281. *
  282. * By setting the $entity->search_api_skip_tracking property to a true-like
  283. * value before this hook is invoked, you can prevent this behavior and make the
  284. * Search API ignore this deletion. (Note that this might lead to stale data in
  285. * the tracking table or on the server, since the item will not removed from
  286. * there (if it has been added before).)
  287. *
  288. * Note that this function implements tracking only on behalf of the "Content
  289. * Entity" datasource defined in this module, not for entity-based datasources
  290. * in general. Datasources defined by other modules still have to implement
  291. * their own mechanism for tracking new/updated/deleted entities.
  292. *
  293. * @see \Drupal\search_api\Plugin\search_api\datasource\ContentEntity
  294. */
  295. function search_api_entity_delete(EntityInterface $entity) {
  296. // Check if the entity is a content entity.
  297. if (!($entity instanceof ContentEntityInterface) || $entity->search_api_skip_tracking) {
  298. return;
  299. }
  300. $indexes = ContentEntity::getIndexesForEntity($entity);
  301. if (!$indexes) {
  302. return;
  303. }
  304. // Remove the search items for all the entity's translations.
  305. $item_ids = [];
  306. $entity_id = $entity->id();
  307. foreach (array_keys($entity->getTranslationLanguages()) as $langcode) {
  308. $item_ids[] = $entity_id . ':' . $langcode;
  309. }
  310. $datasource_id = 'entity:' . $entity->getEntityTypeId();
  311. foreach ($indexes as $index) {
  312. $index->trackItemsDeleted($datasource_id, $item_ids);
  313. }
  314. }
  315. /**
  316. * Implements hook_node_access_records_alter().
  317. *
  318. * Marks the node and its comments changed for indexes that use the "Content
  319. * access" processor.
  320. */
  321. function search_api_node_access_records_alter(array &$grants, NodeInterface $node) {
  322. /** @var \Drupal\search_api\IndexInterface $index */
  323. foreach (Index::loadMultiple() as $index) {
  324. if (!$index->hasValidTracker() || !$index->status()) {
  325. continue;
  326. }
  327. if (!$index->isValidProcessor('content_access')) {
  328. continue;
  329. }
  330. foreach ($index->getDatasources() as $datasource_id => $datasource) {
  331. switch ($datasource->getEntityTypeId()) {
  332. case 'node':
  333. // Don't index the node if search_api_skip_tracking is set on it.
  334. if ($node->search_api_skip_tracking) {
  335. continue 2;
  336. }
  337. $item_id = $datasource->getItemId($node->getTypedData());
  338. if ($item_id !== NULL) {
  339. $index->trackItemsUpdated($datasource_id, [$item_id]);
  340. }
  341. break;
  342. case 'comment':
  343. if (!isset($comments)) {
  344. $entity_query = \Drupal::entityQuery('comment');
  345. $entity_query->condition('entity_id', (int) $node->id());
  346. $entity_query->condition('entity_type', 'node');
  347. $comment_ids = $entity_query->execute();
  348. /** @var \Drupal\comment\CommentInterface[] $comments */
  349. $comments = Comment::loadMultiple($comment_ids);
  350. }
  351. $item_ids = [];
  352. foreach ($comments as $comment) {
  353. $item_id = $datasource->getItemId($comment->getTypedData());
  354. if ($item_id !== NULL) {
  355. $item_ids[] = $item_id;
  356. }
  357. }
  358. if ($item_ids) {
  359. $index->trackItemsUpdated($datasource_id, $item_ids);
  360. }
  361. break;
  362. }
  363. }
  364. }
  365. }
  366. /**
  367. * Implements hook_theme().
  368. */
  369. function search_api_theme() {
  370. return [
  371. 'search_api_admin_fields_table' => [
  372. 'render element' => 'element',
  373. 'function' => 'theme_search_api_admin_fields_table',
  374. 'file' => 'search_api.theme.inc',
  375. ],
  376. 'search_api_admin_data_type_table' => [
  377. 'variables' => [
  378. 'data_types' => [],
  379. 'fallback_mapping' => []
  380. ],
  381. 'function' => 'theme_search_api_admin_data_type_table',
  382. 'file' => 'search_api.theme.inc',
  383. ],
  384. 'search_api_form_item_list' => [
  385. 'render element' => 'element',
  386. 'function' => 'theme_search_api_form_item_list',
  387. 'file' => 'search_api.theme.inc',
  388. ],
  389. 'search_api_server' => [
  390. 'variables' => ['server' => NULL],
  391. 'function' => 'theme_search_api_server',
  392. 'file' => 'search_api.theme.inc',
  393. ],
  394. 'search_api_index' => [
  395. 'variables' => [
  396. 'index' => NULL,
  397. 'server_count' => NULL,
  398. 'server_count_error' => NULL,
  399. ],
  400. 'function' => 'theme_search_api_index',
  401. 'file' => 'search_api.theme.inc',
  402. ],
  403. ];
  404. }
  405. /**
  406. * Implements hook_ENTITY_TYPE_update() for type "search_api_index".
  407. *
  408. * Implemented on behalf of the "entity" datasource plugin.
  409. *
  410. * @see \Drupal\search_api\Plugin\search_api\datasource\ContentEntity
  411. */
  412. function search_api_search_api_index_update(IndexInterface $index) {
  413. if (!$index->status() || empty($index->original)) {
  414. return;
  415. }
  416. /** @var \Drupal\search_api\IndexInterface $original */
  417. $original = $index->original;
  418. if (!$original->status()) {
  419. return;
  420. }
  421. foreach ($index->getDatasources() as $datasource_id => $datasource) {
  422. if ($datasource->getBaseId() != 'entity'
  423. || !($datasource instanceof EntityDatasourceInterface)
  424. || !$original->isValidDatasource($datasource_id)) {
  425. continue;
  426. }
  427. $old_datasource = $original->getDatasource($datasource_id);
  428. $old_config = $old_datasource->getConfiguration();
  429. $new_config = $datasource->getConfiguration();
  430. if ($old_config != $new_config) {
  431. // Bundles and languages share the same structure, so changes can be
  432. // processed in a unified way.
  433. $tasks = [];
  434. $insert_task = ContentEntityTaskManager::INSERT_ITEMS_TASK_TYPE;
  435. $delete_task = ContentEntityTaskManager::DELETE_ITEMS_TASK_TYPE;
  436. $settings = [];
  437. $entity_type = \Drupal::entityTypeManager()
  438. ->getDefinition($datasource->getEntityTypeId());
  439. if ($entity_type->hasKey('bundle')) {
  440. $settings['bundles'] = $datasource->getBundles();
  441. }
  442. if ($entity_type->isTranslatable()) {
  443. $settings['languages'] = \Drupal::languageManager()->getLanguages();
  444. }
  445. // Determine which bundles/languages have been newly selected or
  446. // deselected and then assign them to the appropriate actions depending
  447. // on the current "default" setting.
  448. foreach ($settings as $setting => $all) {
  449. $old_selected = array_flip($old_config[$setting]['selected']);
  450. $new_selected = array_flip($new_config[$setting]['selected']);
  451. // First, check if the "default" setting changed and invert the checked
  452. // items for the old config, so the following comparison makes sense.
  453. if ($old_config[$setting]['default'] != $new_config[$setting]['default']) {
  454. $old_selected = array_diff_key($all, $old_selected);
  455. }
  456. $newly_selected = array_keys(array_diff_key($new_selected, $old_selected));
  457. $newly_unselected = array_keys(array_diff_key($old_selected, $new_selected));
  458. if ($new_config[$setting]['default']) {
  459. $tasks[$insert_task][$setting] = $newly_unselected;
  460. $tasks[$delete_task][$setting] = $newly_selected;
  461. }
  462. else {
  463. $tasks[$insert_task][$setting] = $newly_selected;
  464. $tasks[$delete_task][$setting] = $newly_unselected;
  465. }
  466. }
  467. // This will keep only those tasks where at least one of "bundles" or
  468. // "languages" is non-empty.
  469. $tasks = array_filter($tasks, 'array_filter');
  470. $task_manager = \Drupal::getContainer()
  471. ->get('search_api.task_manager');
  472. foreach ($tasks as $task => $data) {
  473. $data += [
  474. 'datasource' => $datasource_id,
  475. 'page' => 0,
  476. ];
  477. $task_manager->addTask($task, NULL, $index, $data);
  478. }
  479. // If we added any new tasks, set a batch for them. (If we aren't in a
  480. // form submission, this will just be ignored.)
  481. if ($tasks) {
  482. $task_manager->setTasksBatch([
  483. 'index_id' => $index->id(),
  484. 'type' => array_keys($tasks),
  485. ]);
  486. }
  487. }
  488. }
  489. }
  490. /**
  491. * Implements hook_views_plugins_argument_alter().
  492. */
  493. function search_api_views_plugins_argument_alter(array &$plugins) {
  494. // We have to include the term argument handler like this, since adding it
  495. // directly (i.e., with an annotation) would cause fatal errors on sites
  496. // without the Taxonomy module.
  497. if (\Drupal::moduleHandler()->moduleExists('taxonomy')) {
  498. $plugins['search_api_term'] = [
  499. 'plugin_type' => 'argument',
  500. 'id' => 'search_api_term',
  501. 'class' => TermArgument::class,
  502. 'provider' => 'search_api',
  503. ];
  504. }
  505. }
  506. /**
  507. * Implements hook_views_plugins_filter_alter().
  508. */
  509. function search_api_views_plugins_filter_alter(array &$plugins) {
  510. // We have to include the term filter handler like this, since adding it
  511. // directly (i.e., with an annotation) would cause fatal errors on sites
  512. // without the Taxonomy module.
  513. if (\Drupal::moduleHandler()->moduleExists('taxonomy')) {
  514. $plugins['search_api_term'] = [
  515. 'plugin_type' => 'filter',
  516. 'id' => 'search_api_term',
  517. 'class' => TermFilter::class,
  518. 'provider' => 'search_api',
  519. ];
  520. }
  521. }
  522. /**
  523. * Implements hook_ENTITY_TYPE_insert() for type "view".
  524. */
  525. function search_api_view_insert(ViewEntityInterface $view) {
  526. _search_api_view_crud_event($view);
  527. // Disable Views' default caching mechanisms on Search API views.
  528. $displays = $view->get('display');
  529. if ($displays['default']['display_options']['query']['type'] === 'search_api_query') {
  530. $change = FALSE;
  531. foreach ($displays as $id => $display) {
  532. if (isset($display['display_options']['cache']['type']) && in_array($display['display_options']['cache']['type'], ['tag', 'time'])) {
  533. $displays[$id]['display_options']['cache']['type'] = 'none';
  534. $change = TRUE;
  535. }
  536. }
  537. if ($change) {
  538. drupal_set_message(\Drupal::translation()->translate('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.'), 'warning');
  539. $view->set('display', $displays);
  540. $view->save();
  541. }
  542. }
  543. }
  544. /**
  545. * Implements hook_ENTITY_TYPE_update() for type "view".
  546. */
  547. function search_api_view_update(ViewEntityInterface $view) {
  548. _search_api_view_crud_event($view);
  549. }
  550. /**
  551. * Implements hook_ENTITY_TYPE_delete() for type "view".
  552. */
  553. function search_api_view_delete(ViewEntityInterface $view) {
  554. _search_api_view_crud_event($view);
  555. }
  556. /**
  557. * Reacts to a view CRUD event.
  558. *
  559. * @param \Drupal\views\ViewEntityInterface $view
  560. * The view that was created, changed or deleted.
  561. */
  562. function _search_api_view_crud_event(ViewEntityInterface $view) {
  563. // Whenever a view is created, updated (displays might have been added or
  564. // removed) or deleted, we need to clear our cached display definitions.
  565. if (SearchApiQuery::getIndexFromTable($view->get('base_table'))) {
  566. \Drupal::getContainer()
  567. ->get('plugin.manager.search_api.display')
  568. ->clearCachedDefinitions();
  569. }
  570. }
  571. /**
  572. * Retrieves the allowed values for a list field instance.
  573. *
  574. * @param string $entity_type
  575. * The entity type to which the field is attached.
  576. * @param string $bundle
  577. * The bundle to which the field is attached.
  578. * @param string $field_name
  579. * The field's field name.
  580. *
  581. * @return array|null
  582. * An array of allowed values in the form key => label, or NULL.
  583. *
  584. * @see _search_api_views_handler_adjustments()
  585. */
  586. function _search_api_views_get_allowed_values($entity_type, $bundle, $field_name) {
  587. $field_manager = \Drupal::getContainer()->get('entity_field.manager');
  588. $field_definitions = $field_manager->getFieldDefinitions($entity_type, $bundle);
  589. if (!empty($field_definitions[$field_name])) {
  590. /** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
  591. $field_definition = $field_definitions[$field_name];
  592. $options = $field_definition->getSetting('allowed_values');
  593. if ($options) {
  594. return $options;
  595. }
  596. }
  597. return NULL;
  598. }
  599. /**
  600. * Implements hook_form_FORM_ID_alter() for form "views_ui_edit_display_form".
  601. */
  602. function search_api_form_views_ui_edit_display_form_alter(&$form, FormStateInterface $form_state) {
  603. // Disable Views' default caching mechanisms on Search API views.
  604. $displays = $form_state->getStorage()['view']->get('display');
  605. if ($displays['default']['display_options']['query']['type'] === 'search_api_query') {
  606. unset($form['options']['cache']['type']['#options']['tag']);
  607. unset($form['options']['cache']['type']['#options']['time']);
  608. }
  609. }
  610. /**
  611. * Returns a warning message if the Core Search module is enabled.
  612. *
  613. * @return string|null
  614. * A warning message if needed, NULL otherwise.
  615. *
  616. * @see search_api_install()
  617. * @see search_api_requirements()
  618. */
  619. function _search_api_search_module_warning() {
  620. if (\Drupal::moduleHandler()->moduleExists('search')) {
  621. $args = [
  622. ':url' => Url::fromRoute('system.modules_uninstall')->toString(),
  623. ':documentation' => 'https://www.drupal.org/node/2010146#core-search',
  624. ];
  625. 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);
  626. }
  627. return NULL;
  628. }