3 namespace Drupal\search;
5 use Drupal\Core\Config\ConfigFactoryInterface;
6 use Drupal\Core\Config\Entity\DraggableListBuilder;
7 use Drupal\Core\Entity\EntityInterface;
8 use Drupal\Core\Entity\EntityStorageInterface;
9 use Drupal\Core\Entity\EntityTypeInterface;
10 use Drupal\Core\Form\ConfigFormBaseTrait;
11 use Drupal\Core\Form\FormInterface;
12 use Drupal\Core\Form\FormStateInterface;
13 use Drupal\Core\Messenger\MessengerInterface;
15 use Symfony\Component\DependencyInjection\ContainerInterface;
18 * Defines a class to build a listing of search page entities.
20 * @see \Drupal\search\Entity\SearchPage
22 class SearchPageListBuilder extends DraggableListBuilder implements FormInterface {
23 use ConfigFormBaseTrait;
26 * The entities being listed.
28 * @var \Drupal\search\SearchPageInterface[]
30 protected $entities = [];
33 * Stores the configuration factory.
35 * @var \Drupal\Core\Config\ConfigFactoryInterface
37 protected $configFactory;
42 * @var \Drupal\search\SearchPluginManager
44 protected $searchManager;
49 * @var \Drupal\Core\Messenger\MessengerInterface
54 * Constructs a new SearchPageListBuilder object.
56 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
57 * The entity type definition.
58 * @param \Drupal\Core\Entity\EntityStorageInterface $storage
59 * The entity storage class.
60 * @param \Drupal\search\SearchPluginManager $search_manager
61 * The search plugin manager.
62 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
63 * The factory for configuration objects.
64 * @param \Drupal\Core\Messenger\MessengerInterface $messenger
67 public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, SearchPluginManager $search_manager, ConfigFactoryInterface $config_factory, MessengerInterface $messenger) {
68 parent::__construct($entity_type, $storage);
69 $this->configFactory = $config_factory;
70 $this->searchManager = $search_manager;
71 $this->messenger = $messenger;
77 public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
80 $container->get('entity.manager')->getStorage($entity_type->id()),
81 $container->get('plugin.manager.search'),
82 $container->get('config.factory'),
83 $container->get('messenger')
90 public function getFormId() {
91 return 'search_admin_settings';
97 protected function getEditableConfigNames() {
98 return ['search.settings'];
104 public function buildHeader() {
106 'data' => $this->t('Label'),
109 'data' => $this->t('URL'),
110 'class' => [RESPONSIVE_PRIORITY_LOW],
112 $header['plugin'] = [
113 'data' => $this->t('Type'),
114 'class' => [RESPONSIVE_PRIORITY_LOW],
116 $header['status'] = [
117 'data' => $this->t('Status'),
119 $header['progress'] = [
120 'data' => $this->t('Indexing progress'),
121 'class' => [RESPONSIVE_PRIORITY_MEDIUM],
123 return $header + parent::buildHeader();
129 public function buildRow(EntityInterface $entity) {
130 /** @var $entity \Drupal\search\SearchPageInterface */
131 $row['label'] = $entity->label();
132 $row['url']['#markup'] = 'search/' . $entity->getPath();
133 // If the search page is active, link to it.
134 if ($entity->status()) {
137 '#title' => $row['url'],
138 '#url' => Url::fromRoute('search.view_' . $entity->id()),
142 $definition = $entity->getPlugin()->getPluginDefinition();
143 $row['plugin']['#markup'] = $definition['title'];
145 if ($entity->isDefaultSearch()) {
146 $status = $this->t('Default');
148 elseif ($entity->status()) {
149 $status = $this->t('Enabled');
152 $status = $this->t('Disabled');
154 $row['status']['#markup'] = $status;
156 if ($entity->isIndexable()) {
157 $status = $entity->getPlugin()->indexStatus();
158 $row['progress']['#markup'] = $this->t('%num_indexed of %num_total indexed', [
159 '%num_indexed' => $status['total'] - $status['remaining'],
160 '%num_total' => $status['total'],
164 $row['progress']['#markup'] = $this->t('Does not use index');
167 return $row + parent::buildRow($entity);
173 public function buildForm(array $form, FormStateInterface $form_state) {
174 $form = parent::buildForm($form, $form_state);
175 $search_settings = $this->config('search.settings');
176 // Collect some stats.
179 foreach ($this->entities as $entity) {
180 if ($entity->isIndexable() && $status = $entity->getPlugin()->indexStatus()) {
181 $remaining += $status['remaining'];
182 $total += $status['total'];
186 $this->moduleHandler->loadAllIncludes('admin.inc');
187 $count = $this->formatPlural($remaining, 'There is 1 item left to index.', 'There are @count items left to index.');
188 $done = $total - $remaining;
189 // Use floor() to calculate the percentage, so if it is not quite 100%, it
190 // will show as 99%, to indicate "almost done".
191 $percentage = $total > 0 ? floor(100 * $done / $total) : 100;
193 $status = '<p><strong>' . $this->t('%percentage of the site has been indexed.', ['%percentage' => $percentage]) . ' ' . $count . '</strong></p>';
195 '#type' => 'details',
196 '#title' => $this->t('Indexing progress'),
198 '#description' => $this->t('Only items in the index will appear in search results. To build and maintain the index, a correctly configured <a href=":cron">cron maintenance task</a> is required.', [':cron' => \Drupal::url('system.cron_settings')]),
200 $form['status']['status'] = ['#markup' => $status];
201 $form['status']['wipe'] = [
203 '#value' => $this->t('Re-index site'),
204 '#submit' => ['::searchAdminReindexSubmit'],
207 $items = [10, 20, 50, 100, 200, 500];
208 $items = array_combine($items, $items);
210 // Indexing throttle:
211 $form['indexing_throttle'] = [
212 '#type' => 'details',
213 '#title' => $this->t('Indexing throttle'),
216 $form['indexing_throttle']['cron_limit'] = [
218 '#title' => $this->t('Number of items to index per cron run'),
219 '#default_value' => $search_settings->get('index.cron_limit'),
220 '#options' => $items,
221 '#description' => $this->t('The maximum number of items indexed in each run of the <a href=":cron">cron maintenance task</a>. If necessary, reduce the number of items to prevent timeouts and memory errors while indexing. Some search page types may have their own setting for this.', [':cron' => \Drupal::url('system.cron_settings')]),
223 // Indexing settings:
224 $form['indexing_settings'] = [
225 '#type' => 'details',
226 '#title' => $this->t('Default indexing settings'),
229 $form['indexing_settings']['info'] = [
230 '#markup' => $this->t("<p>Search pages that use an index may use the default index provided by the Search module, or they may use a different indexing mechanism. These settings are for the default index. <em>Changing these settings will cause the default search index to be rebuilt to reflect the new settings. Searching will continue to work, based on the existing index, but new content won't be indexed until all existing content has been re-indexed.</em></p><p><em>The default settings should be appropriate for the majority of sites.</em></p>"),
232 $form['indexing_settings']['minimum_word_size'] = [
234 '#title' => $this->t('Minimum word length to index'),
235 '#default_value' => $search_settings->get('index.minimum_word_size'),
238 '#description' => $this->t('The minimum character length for a word to be added to the index. Searches must include a keyword of at least this length.'),
240 $form['indexing_settings']['overlap_cjk'] = [
241 '#type' => 'checkbox',
242 '#title' => $this->t('Simple CJK handling'),
243 '#default_value' => $search_settings->get('index.overlap_cjk'),
244 '#description' => $this->t('Whether to apply a simple Chinese/Japanese/Korean tokenizer based on overlapping sequences. Turn this off if you want to use an external preprocessor for this instead. Does not affect other languages.'),
247 // Indexing settings:
249 '#type' => 'details',
250 '#title' => $this->t('Logging'),
254 $form['logging']['logging'] = [
255 '#type' => 'checkbox',
256 '#title' => $this->t('Log searches'),
257 '#default_value' => $search_settings->get('logging'),
258 '#description' => $this->t('If checked, all searches will be logged. Uncheck to skip logging. Logging may affect performance.'),
261 $form['search_pages'] = [
262 '#type' => 'details',
263 '#title' => $this->t('Search pages'),
266 $form['search_pages']['add_page'] = [
267 '#type' => 'container',
269 'class' => ['container-inline'],
272 // In order to prevent validation errors for the parent form, this cannot be
273 // required, see self::validateAddSearchPage().
274 $form['search_pages']['add_page']['search_type'] = [
276 '#title' => $this->t('Search page type'),
277 '#empty_option' => $this->t('- Choose page type -'),
278 '#options' => array_map(function ($definition) {
279 return $definition['title'];
280 }, $this->searchManager->getDefinitions()),
282 $form['search_pages']['add_page']['add_search_submit'] = [
284 '#value' => $this->t('Add search page'),
285 '#validate' => ['::validateAddSearchPage'],
286 '#submit' => ['::submitAddSearchPage'],
287 '#limit_validation_errors' => [['search_type']],
290 // Move the listing into the search_pages element.
291 $form['search_pages'][$this->entitiesKey] = $form[$this->entitiesKey];
292 $form['search_pages'][$this->entitiesKey]['#empty'] = $this->t('No search pages have been configured.');
293 unset($form[$this->entitiesKey]);
295 $form['actions']['#type'] = 'actions';
296 $form['actions']['submit'] = [
298 '#value' => $this->t('Save configuration'),
299 '#button_type' => 'primary',
308 public function getDefaultOperations(EntityInterface $entity) {
309 /** @var $entity \Drupal\search\SearchPageInterface */
310 $operations = parent::getDefaultOperations($entity);
312 // Prevent the default search from being disabled or deleted.
313 if ($entity->isDefaultSearch()) {
314 unset($operations['disable'], $operations['delete']);
317 $operations['default'] = [
318 'title' => $this->t('Set as default'),
319 'url' => Url::fromRoute('entity.search_page.set_default', [
320 'search_page' => $entity->id(),
332 public function validateForm(array &$form, FormStateInterface $form_state) {
338 public function submitForm(array &$form, FormStateInterface $form_state) {
339 parent::submitForm($form, $form_state);
341 $search_settings = $this->config('search.settings');
342 // If these settings change, the default index needs to be rebuilt.
343 if (($search_settings->get('index.minimum_word_size') != $form_state->getValue('minimum_word_size')) || ($search_settings->get('index.overlap_cjk') != $form_state->getValue('overlap_cjk'))) {
344 $search_settings->set('index.minimum_word_size', $form_state->getValue('minimum_word_size'));
345 $search_settings->set('index.overlap_cjk', $form_state->getValue('overlap_cjk'));
346 // Specifically mark items in the default index for reindexing, since
347 // these settings are used in the search_index() function.
348 $this->messenger->addStatus($this->t('The default search index will be rebuilt.'));
349 search_mark_for_reindex();
353 ->set('index.cron_limit', $form_state->getValue('cron_limit'))
354 ->set('logging', $form_state->getValue('logging'))
357 $this->messenger->addStatus($this->t('The configuration options have been saved.'));
361 * Form submission handler for the reindex button on the search admin settings
364 public function searchAdminReindexSubmit(array &$form, FormStateInterface $form_state) {
365 // Send the user to the confirmation page.
366 $form_state->setRedirect('search.reindex_confirm');
370 * Form validation handler for adding a new search page.
372 public function validateAddSearchPage(array &$form, FormStateInterface $form_state) {
373 if ($form_state->isValueEmpty('search_type')) {
374 $form_state->setErrorByName('search_type', $this->t('You must select the new search page type.'));
379 * Form submission handler for adding a new search page.
381 public function submitAddSearchPage(array &$form, FormStateInterface $form_state) {
382 $form_state->setRedirect(
384 ['search_plugin_id' => $form_state->getValue('search_type')]