Security update to Drupal 8.4.6
[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\Url;
14 use Symfony\Component\DependencyInjection\ContainerInterface;
15
16 /**
17  * Defines a class to build a listing of search page entities.
18  *
19  * @see \Drupal\search\Entity\SearchPage
20  */
21 class SearchPageListBuilder extends DraggableListBuilder implements FormInterface {
22   use ConfigFormBaseTrait;
23
24   /**
25    * The entities being listed.
26    *
27    * @var \Drupal\search\SearchPageInterface[]
28    */
29   protected $entities = [];
30
31   /**
32    * Stores the configuration factory.
33    *
34    * @var \Drupal\Core\Config\ConfigFactoryInterface
35    */
36   protected $configFactory;
37
38   /**
39    * The search manager.
40    *
41    * @var \Drupal\search\SearchPluginManager
42    */
43   protected $searchManager;
44
45   /**
46    * Constructs a new SearchPageListBuilder object.
47    *
48    * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
49    *   The entity type definition.
50    * @param \Drupal\Core\Entity\EntityStorageInterface $storage
51    *   The entity storage class.
52    * @param \Drupal\search\SearchPluginManager $search_manager
53    *   The search plugin manager.
54    * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
55    *   The factory for configuration objects.
56    */
57   public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, SearchPluginManager $search_manager, ConfigFactoryInterface $config_factory) {
58     parent::__construct($entity_type, $storage);
59     $this->configFactory = $config_factory;
60     $this->searchManager = $search_manager;
61   }
62
63   /**
64    * {@inheritdoc}
65    */
66   public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
67     return new static(
68       $entity_type,
69       $container->get('entity.manager')->getStorage($entity_type->id()),
70       $container->get('plugin.manager.search'),
71       $container->get('config.factory')
72     );
73   }
74
75   /**
76    * {@inheritdoc}
77    */
78   public function getFormId() {
79     return 'search_admin_settings';
80   }
81
82   /**
83    * {@inheritdoc}
84    */
85   protected function getEditableConfigNames() {
86     return ['search.settings'];
87   }
88
89   /**
90    * {@inheritdoc}
91    */
92   public function buildHeader() {
93     $header['label'] = [
94       'data' => $this->t('Label'),
95     ];
96     $header['url'] = [
97       'data' => $this->t('URL'),
98       'class' => [RESPONSIVE_PRIORITY_LOW],
99     ];
100     $header['plugin'] = [
101       'data' => $this->t('Type'),
102       'class' => [RESPONSIVE_PRIORITY_LOW],
103     ];
104     $header['status'] = [
105       'data' => $this->t('Status'),
106     ];
107     $header['progress'] = [
108       'data' => $this->t('Indexing progress'),
109       'class' => [RESPONSIVE_PRIORITY_MEDIUM],
110     ];
111     return $header + parent::buildHeader();
112   }
113
114   /**
115    * {@inheritdoc}
116    */
117   public function buildRow(EntityInterface $entity) {
118     /** @var $entity \Drupal\search\SearchPageInterface */
119     $row['label'] = $entity->label();
120     $row['url']['#markup'] = 'search/' . $entity->getPath();
121     // If the search page is active, link to it.
122     if ($entity->status()) {
123       $row['url'] = [
124         '#type' => 'link',
125         '#title' => $row['url'],
126         '#url' => Url::fromRoute('search.view_' . $entity->id()),
127       ];
128     }
129
130     $definition = $entity->getPlugin()->getPluginDefinition();
131     $row['plugin']['#markup'] = $definition['title'];
132
133     if ($entity->isDefaultSearch()) {
134       $status = $this->t('Default');
135     }
136     elseif ($entity->status()) {
137       $status = $this->t('Enabled');
138     }
139     else {
140       $status = $this->t('Disabled');
141     }
142     $row['status']['#markup'] = $status;
143
144     if ($entity->isIndexable()) {
145       $status = $entity->getPlugin()->indexStatus();
146       $row['progress']['#markup'] = $this->t('%num_indexed of %num_total indexed', [
147         '%num_indexed' => $status['total'] - $status['remaining'],
148         '%num_total' => $status['total']
149       ]);
150     }
151     else {
152       $row['progress']['#markup'] = $this->t('Does not use index');
153     }
154
155     return $row + parent::buildRow($entity);
156   }
157
158   /**
159    * {@inheritdoc}
160    */
161   public function buildForm(array $form, FormStateInterface $form_state) {
162     $form = parent::buildForm($form, $form_state);
163     $search_settings = $this->config('search.settings');
164     // Collect some stats.
165     $remaining = 0;
166     $total = 0;
167     foreach ($this->entities as $entity) {
168       if ($entity->isIndexable() && $status = $entity->getPlugin()->indexStatus()) {
169         $remaining += $status['remaining'];
170         $total += $status['total'];
171       }
172     }
173
174     $this->moduleHandler->loadAllIncludes('admin.inc');
175     $count = $this->formatPlural($remaining, 'There is 1 item left to index.', 'There are @count items left to index.');
176     $done = $total - $remaining;
177     // Use floor() to calculate the percentage, so if it is not quite 100%, it
178     // will show as 99%, to indicate "almost done".
179     $percentage = $total > 0 ? floor(100 * $done / $total) : 100;
180     $percentage .= '%';
181     $status = '<p><strong>' . $this->t('%percentage of the site has been indexed.', ['%percentage' => $percentage]) . ' ' . $count . '</strong></p>';
182     $form['status'] = [
183       '#type' => 'details',
184       '#title' => $this->t('Indexing progress'),
185       '#open' => TRUE,
186       '#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')]),
187     ];
188     $form['status']['status'] = ['#markup' => $status];
189     $form['status']['wipe'] = [
190       '#type' => 'submit',
191       '#value' => $this->t('Re-index site'),
192       '#submit' => ['::searchAdminReindexSubmit'],
193     ];
194
195     $items = [10, 20, 50, 100, 200, 500];
196     $items = array_combine($items, $items);
197
198     // Indexing throttle:
199     $form['indexing_throttle'] = [
200       '#type' => 'details',
201       '#title' => $this->t('Indexing throttle'),
202       '#open' => TRUE,
203     ];
204     $form['indexing_throttle']['cron_limit'] = [
205       '#type' => 'select',
206       '#title' => $this->t('Number of items to index per cron run'),
207       '#default_value' => $search_settings->get('index.cron_limit'),
208       '#options' => $items,
209       '#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')]),
210     ];
211     // Indexing settings:
212     $form['indexing_settings'] = [
213       '#type' => 'details',
214       '#title' => $this->t('Default indexing settings'),
215       '#open' => TRUE,
216     ];
217     $form['indexing_settings']['info'] = [
218       '#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>")
219     ];
220     $form['indexing_settings']['minimum_word_size'] = [
221       '#type' => 'number',
222       '#title' => $this->t('Minimum word length to index'),
223       '#default_value' => $search_settings->get('index.minimum_word_size'),
224       '#min' => 1,
225       '#max' => 1000,
226       '#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.'),
227     ];
228     $form['indexing_settings']['overlap_cjk'] = [
229       '#type' => 'checkbox',
230       '#title' => $this->t('Simple CJK handling'),
231       '#default_value' => $search_settings->get('index.overlap_cjk'),
232       '#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.')
233     ];
234
235     // Indexing settings:
236     $form['logging'] = [
237       '#type' => 'details',
238       '#title' => $this->t('Logging'),
239       '#open' => TRUE,
240     ];
241
242     $form['logging']['logging'] = [
243       '#type' => 'checkbox',
244       '#title' => $this->t('Log searches'),
245       '#default_value' => $search_settings->get('logging'),
246       '#description' => $this->t('If checked, all searches will be logged. Uncheck to skip logging. Logging may affect performance.'),
247     ];
248
249     $form['search_pages'] = [
250       '#type' => 'details',
251       '#title' => $this->t('Search pages'),
252       '#open' => TRUE,
253     ];
254     $form['search_pages']['add_page'] = [
255       '#type' => 'container',
256       '#attributes' => [
257         'class' => ['container-inline'],
258       ],
259     ];
260     // In order to prevent validation errors for the parent form, this cannot be
261     // required, see self::validateAddSearchPage().
262     $form['search_pages']['add_page']['search_type'] = [
263       '#type' => 'select',
264       '#title' => $this->t('Search page type'),
265       '#empty_option' => $this->t('- Choose page type -'),
266       '#options' => array_map(function ($definition) {
267         return $definition['title'];
268       }, $this->searchManager->getDefinitions()),
269     ];
270     $form['search_pages']['add_page']['add_search_submit'] = [
271       '#type' => 'submit',
272       '#value' => $this->t('Add search page'),
273       '#validate' => ['::validateAddSearchPage'],
274       '#submit' => ['::submitAddSearchPage'],
275       '#limit_validation_errors' => [['search_type']],
276     ];
277
278     // Move the listing into the search_pages element.
279     $form['search_pages'][$this->entitiesKey] = $form[$this->entitiesKey];
280     $form['search_pages'][$this->entitiesKey]['#empty'] = $this->t('No search pages have been configured.');
281     unset($form[$this->entitiesKey]);
282
283     $form['actions']['#type'] = 'actions';
284     $form['actions']['submit'] = [
285       '#type' => 'submit',
286       '#value' => $this->t('Save configuration'),
287       '#button_type' => 'primary',
288     ];
289
290     return $form;
291   }
292
293   /**
294    * {@inheritdoc}
295    */
296   public function getDefaultOperations(EntityInterface $entity) {
297     /** @var $entity \Drupal\search\SearchPageInterface */
298     $operations = parent::getDefaultOperations($entity);
299
300     // Prevent the default search from being disabled or deleted.
301     if ($entity->isDefaultSearch()) {
302       unset($operations['disable'], $operations['delete']);
303     }
304     else {
305       $operations['default'] = [
306         'title' => $this->t('Set as default'),
307         'url' => Url::fromRoute('entity.search_page.set_default', [
308           'search_page' => $entity->id(),
309         ]),
310         'weight' => 50,
311       ];
312     }
313
314     return $operations;
315   }
316
317   /**
318    * {@inheritdoc}
319    */
320   public function validateForm(array &$form, FormStateInterface $form_state) {
321   }
322
323   /**
324    * {@inheritdoc}
325    */
326   public function submitForm(array &$form, FormStateInterface $form_state) {
327     parent::submitForm($form, $form_state);
328
329     $search_settings = $this->config('search.settings');
330     // If these settings change, the default index needs to be rebuilt.
331     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'))) {
332       $search_settings->set('index.minimum_word_size', $form_state->getValue('minimum_word_size'));
333       $search_settings->set('index.overlap_cjk', $form_state->getValue('overlap_cjk'));
334       // Specifically mark items in the default index for reindexing, since
335       // these settings are used in the search_index() function.
336       drupal_set_message($this->t('The default search index will be rebuilt.'));
337       search_mark_for_reindex();
338     }
339
340     $search_settings
341       ->set('index.cron_limit', $form_state->getValue('cron_limit'))
342       ->set('logging', $form_state->getValue('logging'))
343       ->save();
344
345     drupal_set_message($this->t('The configuration options have been saved.'));
346   }
347
348   /**
349    * Form submission handler for the reindex button on the search admin settings
350    * form.
351    */
352   public function searchAdminReindexSubmit(array &$form, FormStateInterface $form_state) {
353     // Send the user to the confirmation page.
354     $form_state->setRedirect('search.reindex_confirm');
355   }
356
357   /**
358    * Form validation handler for adding a new search page.
359    */
360   public function validateAddSearchPage(array &$form, FormStateInterface $form_state) {
361     if ($form_state->isValueEmpty('search_type')) {
362       $form_state->setErrorByName('search_type', $this->t('You must select the new search page type.'));
363     }
364   }
365
366   /**
367    * Form submission handler for adding a new search page.
368    */
369   public function submitAddSearchPage(array &$form, FormStateInterface $form_state) {
370     $form_state->setRedirect(
371       'search.add_type',
372       ['search_plugin_id' => $form_state->getValue('search_type')]
373     );
374   }
375
376 }