bde195ec638edc3c33abbf7a773ad9bcfd9db971
[yaffs-website] / web / core / modules / search / src / SearchPageListBuilder.php
1 <?php
2
3 namespace Drupal\search;
4
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;
14 use Drupal\Core\Url;
15 use Symfony\Component\DependencyInjection\ContainerInterface;
16
17 /**
18  * Defines a class to build a listing of search page entities.
19  *
20  * @see \Drupal\search\Entity\SearchPage
21  */
22 class SearchPageListBuilder extends DraggableListBuilder implements FormInterface {
23   use ConfigFormBaseTrait;
24
25   /**
26    * The entities being listed.
27    *
28    * @var \Drupal\search\SearchPageInterface[]
29    */
30   protected $entities = [];
31
32   /**
33    * Stores the configuration factory.
34    *
35    * @var \Drupal\Core\Config\ConfigFactoryInterface
36    */
37   protected $configFactory;
38
39   /**
40    * The search manager.
41    *
42    * @var \Drupal\search\SearchPluginManager
43    */
44   protected $searchManager;
45
46   /**
47    * The messenger.
48    *
49    * @var \Drupal\Core\Messenger\MessengerInterface
50    */
51   protected $messenger;
52
53   /**
54    * Constructs a new SearchPageListBuilder object.
55    *
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
65    *   The messenger.
66    */
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;
72   }
73
74   /**
75    * {@inheritdoc}
76    */
77   public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
78     return new static(
79       $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')
84     );
85   }
86
87   /**
88    * {@inheritdoc}
89    */
90   public function getFormId() {
91     return 'search_admin_settings';
92   }
93
94   /**
95    * {@inheritdoc}
96    */
97   protected function getEditableConfigNames() {
98     return ['search.settings'];
99   }
100
101   /**
102    * {@inheritdoc}
103    */
104   public function buildHeader() {
105     $header['label'] = [
106       'data' => $this->t('Label'),
107     ];
108     $header['url'] = [
109       'data' => $this->t('URL'),
110       'class' => [RESPONSIVE_PRIORITY_LOW],
111     ];
112     $header['plugin'] = [
113       'data' => $this->t('Type'),
114       'class' => [RESPONSIVE_PRIORITY_LOW],
115     ];
116     $header['status'] = [
117       'data' => $this->t('Status'),
118     ];
119     $header['progress'] = [
120       'data' => $this->t('Indexing progress'),
121       'class' => [RESPONSIVE_PRIORITY_MEDIUM],
122     ];
123     return $header + parent::buildHeader();
124   }
125
126   /**
127    * {@inheritdoc}
128    */
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()) {
135       $row['url'] = [
136         '#type' => 'link',
137         '#title' => $row['url'],
138         '#url' => Url::fromRoute('search.view_' . $entity->id()),
139       ];
140     }
141
142     $definition = $entity->getPlugin()->getPluginDefinition();
143     $row['plugin']['#markup'] = $definition['title'];
144
145     if ($entity->isDefaultSearch()) {
146       $status = $this->t('Default');
147     }
148     elseif ($entity->status()) {
149       $status = $this->t('Enabled');
150     }
151     else {
152       $status = $this->t('Disabled');
153     }
154     $row['status']['#markup'] = $status;
155
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'],
161       ]);
162     }
163     else {
164       $row['progress']['#markup'] = $this->t('Does not use index');
165     }
166
167     return $row + parent::buildRow($entity);
168   }
169
170   /**
171    * {@inheritdoc}
172    */
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.
177     $remaining = 0;
178     $total = 0;
179     foreach ($this->entities as $entity) {
180       if ($entity->isIndexable() && $status = $entity->getPlugin()->indexStatus()) {
181         $remaining += $status['remaining'];
182         $total += $status['total'];
183       }
184     }
185
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;
192     $percentage .= '%';
193     $status = '<p><strong>' . $this->t('%percentage of the site has been indexed.', ['%percentage' => $percentage]) . ' ' . $count . '</strong></p>';
194     $form['status'] = [
195       '#type' => 'details',
196       '#title' => $this->t('Indexing progress'),
197       '#open' => TRUE,
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')]),
199     ];
200     $form['status']['status'] = ['#markup' => $status];
201     $form['status']['wipe'] = [
202       '#type' => 'submit',
203       '#value' => $this->t('Re-index site'),
204       '#submit' => ['::searchAdminReindexSubmit'],
205     ];
206
207     $items = [10, 20, 50, 100, 200, 500];
208     $items = array_combine($items, $items);
209
210     // Indexing throttle:
211     $form['indexing_throttle'] = [
212       '#type' => 'details',
213       '#title' => $this->t('Indexing throttle'),
214       '#open' => TRUE,
215     ];
216     $form['indexing_throttle']['cron_limit'] = [
217       '#type' => 'select',
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')]),
222     ];
223     // Indexing settings:
224     $form['indexing_settings'] = [
225       '#type' => 'details',
226       '#title' => $this->t('Default indexing settings'),
227       '#open' => TRUE,
228     ];
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>"),
231     ];
232     $form['indexing_settings']['minimum_word_size'] = [
233       '#type' => 'number',
234       '#title' => $this->t('Minimum word length to index'),
235       '#default_value' => $search_settings->get('index.minimum_word_size'),
236       '#min' => 1,
237       '#max' => 1000,
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.'),
239     ];
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.'),
245     ];
246
247     // Indexing settings:
248     $form['logging'] = [
249       '#type' => 'details',
250       '#title' => $this->t('Logging'),
251       '#open' => TRUE,
252     ];
253
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.'),
259     ];
260
261     $form['search_pages'] = [
262       '#type' => 'details',
263       '#title' => $this->t('Search pages'),
264       '#open' => TRUE,
265     ];
266     $form['search_pages']['add_page'] = [
267       '#type' => 'container',
268       '#attributes' => [
269         'class' => ['container-inline'],
270       ],
271     ];
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'] = [
275       '#type' => 'select',
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()),
281     ];
282     $form['search_pages']['add_page']['add_search_submit'] = [
283       '#type' => 'submit',
284       '#value' => $this->t('Add search page'),
285       '#validate' => ['::validateAddSearchPage'],
286       '#submit' => ['::submitAddSearchPage'],
287       '#limit_validation_errors' => [['search_type']],
288     ];
289
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]);
294
295     $form['actions']['#type'] = 'actions';
296     $form['actions']['submit'] = [
297       '#type' => 'submit',
298       '#value' => $this->t('Save configuration'),
299       '#button_type' => 'primary',
300     ];
301
302     return $form;
303   }
304
305   /**
306    * {@inheritdoc}
307    */
308   public function getDefaultOperations(EntityInterface $entity) {
309     /** @var $entity \Drupal\search\SearchPageInterface */
310     $operations = parent::getDefaultOperations($entity);
311
312     // Prevent the default search from being disabled or deleted.
313     if ($entity->isDefaultSearch()) {
314       unset($operations['disable'], $operations['delete']);
315     }
316     else {
317       $operations['default'] = [
318         'title' => $this->t('Set as default'),
319         'url' => Url::fromRoute('entity.search_page.set_default', [
320           'search_page' => $entity->id(),
321         ]),
322         'weight' => 50,
323       ];
324     }
325
326     return $operations;
327   }
328
329   /**
330    * {@inheritdoc}
331    */
332   public function validateForm(array &$form, FormStateInterface $form_state) {
333   }
334
335   /**
336    * {@inheritdoc}
337    */
338   public function submitForm(array &$form, FormStateInterface $form_state) {
339     parent::submitForm($form, $form_state);
340
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();
350     }
351
352     $search_settings
353       ->set('index.cron_limit', $form_state->getValue('cron_limit'))
354       ->set('logging', $form_state->getValue('logging'))
355       ->save();
356
357     $this->messenger->addStatus($this->t('The configuration options have been saved.'));
358   }
359
360   /**
361    * Form submission handler for the reindex button on the search admin settings
362    * form.
363    */
364   public function searchAdminReindexSubmit(array &$form, FormStateInterface $form_state) {
365     // Send the user to the confirmation page.
366     $form_state->setRedirect('search.reindex_confirm');
367   }
368
369   /**
370    * Form validation handler for adding a new search page.
371    */
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.'));
375     }
376   }
377
378   /**
379    * Form submission handler for adding a new search page.
380    */
381   public function submitAddSearchPage(array &$form, FormStateInterface $form_state) {
382     $form_state->setRedirect(
383       'search.add_type',
384       ['search_plugin_id' => $form_state->getValue('search_type')]
385     );
386   }
387
388 }