SearchPageListBuilder.php 12.8 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\search\SearchPageListBuilder.
6 7 8 9
 */

namespace Drupal\search;

10
use Drupal\Core\Config\ConfigFactoryInterface;
11
use Drupal\Core\Config\Entity\DraggableListBuilder;
12
use Drupal\Core\Entity\EntityInterface;
13
use Drupal\Core\Entity\EntityStorageInterface;
14 15 16 17 18
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Form\FormInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
19 20 21
 * Defines a class to build a listing of search page entities.
 *
 * @see \Drupal\search\Entity\SearchPage
22
 */
23
class SearchPageListBuilder extends DraggableListBuilder implements FormInterface {
24 25 26 27 28 29 30 31 32 33 34

  /**
   * The entities being listed.
   *
   * @var \Drupal\search\SearchPageInterface[]
   */
  protected $entities = array();

  /**
   * Stores the configuration factory.
   *
35
   * @var \Drupal\Core\Config\ConfigFactoryInterface
36 37 38 39 40 41 42 43 44 45 46
   */
  protected $configFactory;

  /**
   * The search manager.
   *
   * @var \Drupal\search\SearchPluginManager
   */
  protected $searchManager;

  /**
47
   * Constructs a new SearchPageListBuilder object.
48
   *
49 50
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
51 52
   * @param \Drupal\Core\Entity\EntityStorageInterface $storage
   *   The entity storage class.
53 54
   * @param \Drupal\search\SearchPluginManager $search_manager
   *   The search plugin manager.
55
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
56 57
   *   The factory for configuration objects.
   */
58
  public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, SearchPluginManager $search_manager, ConfigFactoryInterface $config_factory) {
59
    parent::__construct($entity_type, $storage);
60 61 62 63 64 65 66
    $this->configFactory = $config_factory;
    $this->searchManager = $search_manager;
  }

  /**
   * {@inheritdoc}
   */
67
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
68
    return new static(
69
      $entity_type,
70
      $container->get('entity.manager')->getStorage($entity_type->id()),
71
      $container->get('plugin.manager.search'),
72
      $container->get('config.factory')
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormID() {
    return 'search_admin_settings';
  }

  /**
   * {@inheritdoc}
   */
  public function buildHeader() {
    $header['label'] = array(
      'data' => $this->t('Label'),
    );
    $header['url'] = array(
      'data' => $this->t('URL'),
      'class' => array(RESPONSIVE_PRIORITY_LOW),
    );
    $header['plugin'] = array(
      'data' => $this->t('Type'),
      'class' => array(RESPONSIVE_PRIORITY_LOW),
    );
    $header['status'] = array(
      'data' => $this->t('Status'),
100 101 102 103
    );
    $header['progress'] = array(
      'data' => $this->t('Indexing progress'),
      'class' => array(RESPONSIVE_PRIORITY_MEDIUM),
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    );
    return $header + parent::buildHeader();
  }

  /**
   * {@inheritdoc}
   */
  public function buildRow(EntityInterface $entity) {
    /** @var $entity \Drupal\search\SearchPageInterface */
    $row['label'] = $this->getLabel($entity);
    $row['url']['#markup'] = 'search/' . $entity->getPath();
    // If the search page is active, link to it.
    if ($entity->status()) {
      $row['url'] = array(
        '#type' => 'link',
        '#title' => $row['url'],
        '#route_name' => 'search.view_' . $entity->id(),
      );
    }

    $definition = $entity->getPlugin()->getPluginDefinition();
    $row['plugin']['#markup'] = $definition['title'];

    if ($entity->isDefaultSearch()) {
      $status = $this->t('Default');
    }
    elseif ($entity->status()) {
      $status = $this->t('Enabled');
    }
    else {
      $status = $this->t('Disabled');
    }
    $row['status']['#markup'] = $status;
137 138 139 140 141 142 143 144 145 146 147 148

    if ($entity->isIndexable()) {
      $status = $entity->getPlugin()->indexStatus();
      $row['progress']['#markup'] = $this->t('%num_indexed of %num_total indexed', array(
        '%num_indexed' => $status['total'] - $status['remaining'],
        '%num_total' => $status['total']
      ));
    }
    else {
      $row['progress']['#markup'] = $this->t('Does not use index');
    }

149 150 151 152 153 154 155 156
    return $row + parent::buildRow($entity);
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, array &$form_state) {
    $form = parent::buildForm($form, $form_state);
157 158 159
    $old_state = $this->configFactory->getOverrideState();
    $search_settings = $this->configFactory->setOverrideState(FALSE)->get('search.settings');
    $this->configFactory->setOverrideState($old_state);
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    // Collect some stats.
    $remaining = 0;
    $total = 0;
    foreach ($this->entities as $entity) {
      if ($entity->isIndexable() && $status = $entity->getPlugin()->indexStatus()) {
        $remaining += $status['remaining'];
        $total += $status['total'];
      }
    }

    $this->moduleHandler->loadAllIncludes('admin.inc');
    $count = format_plural($remaining, 'There is 1 item left to index.', 'There are @count items left to index.');
    $percentage = ((int) min(100, 100 * ($total - $remaining) / max(1, $total))) . '%';
    $status = '<p><strong>' . $this->t('%percentage of the site has been indexed.', array('%percentage' => $percentage)) . ' ' . $count . '</strong></p>';
    $form['status'] = array(
      '#type' => 'details',
176
      '#title' => $this->t('Indexing progress'),
177
      '#open' => TRUE,
178 179 180 181 182 183 184 185
    );
    $form['status']['status'] = array('#markup' => $status);
    $form['status']['wipe'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Re-index site'),
      '#submit' => array(array($this, 'searchAdminReindexSubmit')),
    );

186 187
    $items = array(10, 20, 50, 100, 200, 500);
    $items = array_combine($items, $items);
188 189 190 191

    // Indexing throttle:
    $form['indexing_throttle'] = array(
      '#type' => 'details',
192 193
      '#title' => $this->t('Indexing throttle'),
      '#open' => TRUE,
194 195 196 197 198 199 200 201 202 203 204
    );
    $form['indexing_throttle']['cron_limit'] = array(
      '#type' => 'select',
      '#title' => $this->t('Number of items to index per cron run'),
      '#default_value' => $search_settings->get('index.cron_limit'),
      '#options' => $items,
      '#description' => $this->t('The maximum number of items indexed in each pass of a <a href="@cron">cron maintenance task</a>. If necessary, reduce the number of items to prevent timeouts and memory errors while indexing.', array('@cron' => url('admin/reports/status'))),
    );
    // Indexing settings:
    $form['indexing_settings'] = array(
      '#type' => 'details',
205 206
      '#title' => $this->t('Indexing settings'),
      '#open' => TRUE,
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
    );
    $form['indexing_settings']['info'] = array(
      '#markup' => $this->t('<p><em>Changing the settings below will cause the site index to be rebuilt. The search index is not cleared but systematically updated to reflect the new settings. Searching will continue to work 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>')
    );
    $form['indexing_settings']['minimum_word_size'] = array(
      '#type' => 'number',
      '#title' => $this->t('Minimum word length to index'),
      '#default_value' => $search_settings->get('index.minimum_word_size'),
      '#min' => 1,
      '#max' => 1000,
      '#description' => $this->t('The number of characters a word has to be to be indexed. A lower setting means better search result ranking, but also a larger database. Each search query must contain at least one keyword that is this size (or longer).')
    );
    $form['indexing_settings']['overlap_cjk'] = array(
      '#type' => 'checkbox',
      '#title' => $this->t('Simple CJK handling'),
      '#default_value' => $search_settings->get('index.overlap_cjk'),
      '#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.')
    );

226 227 228 229 230 231 232 233 234 235 236 237 238 239
    // Indexing settings:
    $form['logging'] = array(
      '#type' => 'details',
      '#title' => $this->t('Logging'),
      '#open' => TRUE,
    );

    $form['logging']['logging'] = array(
      '#type' => 'checkbox',
      '#title' => $this->t('Log searches'),
      '#default_value' => $search_settings->get('logging'),
      '#description' => $this->t('If checked, all searches will be logged. Uncheck to skip logging. Logging may affect performance.'),
    );

240 241 242
    $form['search_pages'] = array(
      '#type' => 'details',
      '#title' => $this->t('Search pages'),
243
      '#open' => TRUE,
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
    );
    $form['search_pages']['add_page'] = array(
      '#type' => 'container',
      '#attributes' => array(
        'class' => array('container-inline'),
      ),
      '#attached' => array(
        'css' => array(
          drupal_get_path('module', 'search') . '/css/search.admin.css',
        ),
      ),
    );
    // In order to prevent validation errors for the parent form, this cannot be
    // required, see self::validateAddSearchPage().
    $form['search_pages']['add_page']['search_type'] = array(
      '#type' => 'select',
      '#title' => $this->t('Search page type'),
      '#empty_option' => $this->t('- Choose page type -'),
      '#options' => array_map(function ($definition) {
        return $definition['title'];
      }, $this->searchManager->getDefinitions()),
    );
    $form['search_pages']['add_page']['add_search_submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Add new page'),
      '#validate' => array(array($this, 'validateAddSearchPage')),
      '#submit' => array(array($this, 'submitAddSearchPage')),
      '#limit_validation_errors' => array(array('search_type')),
    );

    // Move the listing into the search_pages element.
    $form['search_pages'][$this->entitiesKey] = $form[$this->entitiesKey];
    $form['search_pages'][$this->entitiesKey]['#empty'] = $this->t('No search pages have been configured.');
    unset($form[$this->entitiesKey]);

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Save configuration'),
      '#button_type' => 'primary',
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
292
  public function getDefaultOperations(EntityInterface $entity) {
293
    /** @var $entity \Drupal\search\SearchPageInterface */
294
    $operations = parent::getDefaultOperations($entity);
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336

    // Prevent the default search from being disabled or deleted.
    if ($entity->isDefaultSearch()) {
      unset($operations['disable'], $operations['delete']);
    }
    else {
      $operations['default'] = array(
        'title' => $this->t('Set as default'),
        'route_name' => 'search.set_default',
        'route_parameters' => array(
          'search_page' => $entity->id(),
        ),
        'weight' => 50,
      );
    }

    return $operations;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, array &$form_state) {
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, array &$form_state) {
    parent::submitForm($form, $form_state);

    $search_settings = $this->configFactory->get('search.settings');
    // If these settings change, the index needs to be rebuilt.
    if (($search_settings->get('index.minimum_word_size') != $form_state['values']['minimum_word_size']) || ($search_settings->get('index.overlap_cjk') != $form_state['values']['overlap_cjk'])) {
      $search_settings->set('index.minimum_word_size', $form_state['values']['minimum_word_size']);
      $search_settings->set('index.overlap_cjk', $form_state['values']['overlap_cjk']);
      drupal_set_message($this->t('The index will be rebuilt.'));
      search_reindex();
    }

    $search_settings
      ->set('index.cron_limit', $form_state['values']['cron_limit'])
337
      ->set('logging', $form_state['values']['logging'])
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
      ->save();

    drupal_set_message($this->t('The configuration options have been saved.'));
  }

  /**
   * Form submission handler for the reindex button on the search admin settings
   * form.
   */
  public function searchAdminReindexSubmit(array &$form, array &$form_state) {
    // Send the user to the confirmation page.
    $form_state['redirect_route']['route_name'] = 'search.reindex_confirm';
  }

  /**
   * Form validation handler for adding a new search page.
   */
  public function validateAddSearchPage(array &$form, array &$form_state) {
    if (empty($form_state['values']['search_type'])) {
      $this->formBuilder()->setErrorByName('search_type', $form_state, $this->t('You must select the new search page type.'));
    }
  }

  /**
   * Form submission handler for adding a new search page.
   */
  public function submitAddSearchPage(array &$form, array &$form_state) {
    $form_state['redirect_route'] = array(
      'route_name' => 'search.add_type',
      'route_parameters' => array(
        'search_plugin_id' => $form_state['values']['search_type'],
      ),
    );
  }

}