6d7c8eb7d47e56d1a6f7079225fcfc7ce37738ef
[yaffs-website] / web / core / modules / node / src / Plugin / Search / NodeSearch.php
1 <?php
2
3 namespace Drupal\node\Plugin\Search;
4
5 use Drupal\Core\Access\AccessResult;
6 use Drupal\Core\Cache\CacheableMetadata;
7 use Drupal\Core\Config\Config;
8 use Drupal\Core\Database\Connection;
9 use Drupal\Core\Database\Query\SelectExtender;
10 use Drupal\Core\Database\StatementInterface;
11 use Drupal\Core\Entity\EntityManagerInterface;
12 use Drupal\Core\Extension\ModuleHandlerInterface;
13 use Drupal\Core\Form\FormStateInterface;
14 use Drupal\Core\Language\LanguageInterface;
15 use Drupal\Core\Language\LanguageManagerInterface;
16 use Drupal\Core\Session\AccountInterface;
17 use Drupal\Core\Access\AccessibleInterface;
18 use Drupal\Core\Database\Query\Condition;
19 use Drupal\Core\Render\RendererInterface;
20 use Drupal\node\NodeInterface;
21 use Drupal\search\Plugin\ConfigurableSearchPluginBase;
22 use Drupal\search\Plugin\SearchIndexingInterface;
23 use Drupal\Search\SearchQuery;
24 use Symfony\Component\DependencyInjection\ContainerInterface;
25
26 /**
27  * Handles searching for node entities using the Search module index.
28  *
29  * @SearchPlugin(
30  *   id = "node_search",
31  *   title = @Translation("Content")
32  * )
33  */
34 class NodeSearch extends ConfigurableSearchPluginBase implements AccessibleInterface, SearchIndexingInterface {
35
36   /**
37    * A database connection object.
38    *
39    * @var \Drupal\Core\Database\Connection
40    */
41   protected $database;
42
43   /**
44    * An entity manager object.
45    *
46    * @var \Drupal\Core\Entity\EntityManagerInterface
47    */
48   protected $entityManager;
49
50   /**
51    * A module manager object.
52    *
53    * @var \Drupal\Core\Extension\ModuleHandlerInterface
54    */
55   protected $moduleHandler;
56
57   /**
58    * A config object for 'search.settings'.
59    *
60    * @var \Drupal\Core\Config\Config
61    */
62   protected $searchSettings;
63
64   /**
65    * The language manager.
66    *
67    * @var \Drupal\Core\Language\LanguageManagerInterface
68    */
69   protected $languageManager;
70
71   /**
72    * The Drupal account to use for checking for access to advanced search.
73    *
74    * @var \Drupal\Core\Session\AccountInterface
75    */
76   protected $account;
77
78   /**
79    * The Renderer service to format the username and node.
80    *
81    * @var \Drupal\Core\Render\RendererInterface
82    */
83   protected $renderer;
84
85   /**
86    * An array of additional rankings from hook_ranking().
87    *
88    * @var array
89    */
90   protected $rankings;
91
92   /**
93    * The list of options and info for advanced search filters.
94    *
95    * Each entry in the array has the option as the key and for its value, an
96    * array that determines how the value is matched in the database query. The
97    * possible keys in that array are:
98    * - column: (required) Name of the database column to match against.
99    * - join: (optional) Information on a table to join. By default the data is
100    *   matched against the {node_field_data} table.
101    * - operator: (optional) OR or AND, defaults to OR.
102    *
103    * @var array
104    */
105   protected $advanced = [
106     'type' => ['column' => 'n.type'],
107     'language' => ['column' => 'i.langcode'],
108     'author' => ['column' => 'n.uid'],
109     'term' => ['column' => 'ti.tid', 'join' => ['table' => 'taxonomy_index', 'alias' => 'ti', 'condition' => 'n.nid = ti.nid']],
110   ];
111
112   /**
113    * A constant for setting and checking the query string.
114    */
115   const ADVANCED_FORM = 'advanced-form';
116
117   /**
118    * {@inheritdoc}
119    */
120   static public function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
121     return new static(
122       $configuration,
123       $plugin_id,
124       $plugin_definition,
125       $container->get('database'),
126       $container->get('entity.manager'),
127       $container->get('module_handler'),
128       $container->get('config.factory')->get('search.settings'),
129       $container->get('language_manager'),
130       $container->get('renderer'),
131       $container->get('current_user')
132     );
133   }
134
135   /**
136    * Constructs a \Drupal\node\Plugin\Search\NodeSearch object.
137    *
138    * @param array $configuration
139    *   A configuration array containing information about the plugin instance.
140    * @param string $plugin_id
141    *   The plugin_id for the plugin instance.
142    * @param mixed $plugin_definition
143    *   The plugin implementation definition.
144    * @param \Drupal\Core\Database\Connection $database
145    *   A database connection object.
146    * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
147    *   An entity manager object.
148    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
149    *   A module manager object.
150    * @param \Drupal\Core\Config\Config $search_settings
151    *   A config object for 'search.settings'.
152    * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
153    *   The language manager.
154    * @param \Drupal\Core\Render\RendererInterface $renderer
155    *   The renderer.
156    * @param \Drupal\Core\Session\AccountInterface $account
157    *   The $account object to use for checking for access to advanced search.
158    */
159   public function __construct(array $configuration, $plugin_id, $plugin_definition, Connection $database, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler, Config $search_settings, LanguageManagerInterface $language_manager, RendererInterface $renderer, AccountInterface $account = NULL) {
160     $this->database = $database;
161     $this->entityManager = $entity_manager;
162     $this->moduleHandler = $module_handler;
163     $this->searchSettings = $search_settings;
164     $this->languageManager = $language_manager;
165     $this->renderer = $renderer;
166     $this->account = $account;
167     parent::__construct($configuration, $plugin_id, $plugin_definition);
168
169     $this->addCacheTags(['node_list']);
170   }
171
172   /**
173    * {@inheritdoc}
174    */
175   public function access($operation = 'view', AccountInterface $account = NULL, $return_as_object = FALSE) {
176     $result = AccessResult::allowedIfHasPermission($account, 'access content');
177     return $return_as_object ? $result : $result->isAllowed();
178   }
179
180   /**
181    * {@inheritdoc}
182    */
183   public function isSearchExecutable() {
184     // Node search is executable if we have keywords or an advanced parameter.
185     // At least, we should parse out the parameters and see if there are any
186     // keyword matches in that case, rather than just printing out the
187     // "Please enter keywords" message.
188     return !empty($this->keywords) || (isset($this->searchParameters['f']) && count($this->searchParameters['f']));
189   }
190
191   /**
192    * {@inheritdoc}
193    */
194   public function getType() {
195     return $this->getPluginId();
196   }
197
198   /**
199    * {@inheritdoc}
200    */
201   public function execute() {
202     if ($this->isSearchExecutable()) {
203       $results = $this->findResults();
204
205       if ($results) {
206         return $this->prepareResults($results);
207       }
208     }
209
210     return [];
211   }
212
213   /**
214    * Queries to find search results, and sets status messages.
215    *
216    * This method can assume that $this->isSearchExecutable() has already been
217    * checked and returned TRUE.
218    *
219    * @return \Drupal\Core\Database\StatementInterface|null
220    *   Results from search query execute() method, or NULL if the search
221    *   failed.
222    */
223   protected function findResults() {
224     $keys = $this->keywords;
225
226     // Build matching conditions.
227     $query = $this->database
228       ->select('search_index', 'i', ['target' => 'replica'])
229       ->extend('Drupal\search\SearchQuery')
230       ->extend('Drupal\Core\Database\Query\PagerSelectExtender');
231     $query->join('node_field_data', 'n', 'n.nid = i.sid AND n.langcode = i.langcode');
232     $query->condition('n.status', 1)
233       ->addTag('node_access')
234       ->searchExpression($keys, $this->getPluginId());
235
236     // Handle advanced search filters in the f query string.
237     // \Drupal::request()->query->get('f') is an array that looks like this in
238     // the URL: ?f[]=type:page&f[]=term:27&f[]=term:13&f[]=langcode:en
239     // So $parameters['f'] looks like:
240     // array('type:page', 'term:27', 'term:13', 'langcode:en');
241     // We need to parse this out into query conditions, some of which go into
242     // the keywords string, and some of which are separate conditions.
243     $parameters = $this->getParameters();
244     if (!empty($parameters['f']) && is_array($parameters['f'])) {
245       $filters = [];
246       // Match any query value that is an expected option and a value
247       // separated by ':' like 'term:27'.
248       $pattern = '/^(' . implode('|', array_keys($this->advanced)) . '):([^ ]*)/i';
249       foreach ($parameters['f'] as $item) {
250         if (preg_match($pattern, $item, $m)) {
251           // Use the matched value as the array key to eliminate duplicates.
252           $filters[$m[1]][$m[2]] = $m[2];
253         }
254       }
255
256       // Now turn these into query conditions. This assumes that everything in
257       // $filters is a known type of advanced search.
258       foreach ($filters as $option => $matched) {
259         $info = $this->advanced[$option];
260         // Insert additional conditions. By default, all use the OR operator.
261         $operator = empty($info['operator']) ? 'OR' : $info['operator'];
262         $where = new Condition($operator);
263         foreach ($matched as $value) {
264           $where->condition($info['column'], $value);
265         }
266         $query->condition($where);
267         if (!empty($info['join'])) {
268           $query->join($info['join']['table'], $info['join']['alias'], $info['join']['condition']);
269         }
270       }
271     }
272
273     // Add the ranking expressions.
274     $this->addNodeRankings($query);
275
276     // Run the query.
277     $find = $query
278       // Add the language code of the indexed item to the result of the query,
279       // since the node will be rendered using the respective language.
280       ->fields('i', ['langcode'])
281       // And since SearchQuery makes these into GROUP BY queries, if we add
282       // a field, for PostgreSQL we also need to make it an aggregate or a
283       // GROUP BY. In this case, we want GROUP BY.
284       ->groupBy('i.langcode')
285       ->limit(10)
286       ->execute();
287
288     // Check query status and set messages if needed.
289     $status = $query->getStatus();
290
291     if ($status & SearchQuery::EXPRESSIONS_IGNORED) {
292       drupal_set_message($this->t('Your search used too many AND/OR expressions. Only the first @count terms were included in this search.', ['@count' => $this->searchSettings->get('and_or_limit')]), 'warning');
293     }
294
295     if ($status & SearchQuery::LOWER_CASE_OR) {
296       drupal_set_message($this->t('Search for either of the two terms with uppercase <strong>OR</strong>. For example, <strong>cats OR dogs</strong>.'), 'warning');
297     }
298
299     if ($status & SearchQuery::NO_POSITIVE_KEYWORDS) {
300       drupal_set_message($this->formatPlural($this->searchSettings->get('index.minimum_word_size'), 'You must include at least one keyword to match in the content, and punctuation is ignored.', 'You must include at least one keyword to match in the content. Keywords must be at least @count characters, and punctuation is ignored.'), 'warning');
301     }
302
303     return $find;
304   }
305
306   /**
307    * Prepares search results for rendering.
308    *
309    * @param \Drupal\Core\Database\StatementInterface $found
310    *   Results found from a successful search query execute() method.
311    *
312    * @return array
313    *   Array of search result item render arrays (empty array if no results).
314    */
315   protected function prepareResults(StatementInterface $found) {
316     $results = [];
317
318     $node_storage = $this->entityManager->getStorage('node');
319     $node_render = $this->entityManager->getViewBuilder('node');
320     $keys = $this->keywords;
321
322     foreach ($found as $item) {
323       // Render the node.
324       /** @var \Drupal\node\NodeInterface $node */
325       $node = $node_storage->load($item->sid)->getTranslation($item->langcode);
326       $build = $node_render->view($node, 'search_result', $item->langcode);
327
328       /** @var \Drupal\node\NodeTypeInterface $type*/
329       $type = $this->entityManager->getStorage('node_type')->load($node->bundle());
330
331       unset($build['#theme']);
332       $build['#pre_render'][] = [$this, 'removeSubmittedInfo'];
333
334       // Fetch comments for snippet.
335       $rendered = $this->renderer->renderPlain($build);
336       $this->addCacheableDependency(CacheableMetadata::createFromRenderArray($build));
337       $rendered .= ' ' . $this->moduleHandler->invoke('comment', 'node_update_index', [$node]);
338
339       $extra = $this->moduleHandler->invokeAll('node_search_result', [$node]);
340
341       $language = $this->languageManager->getLanguage($item->langcode);
342       $username = [
343         '#theme' => 'username',
344         '#account' => $node->getOwner(),
345       ];
346
347       $result = [
348         'link' => $node->url('canonical', ['absolute' => TRUE, 'language' => $language]),
349         'type' => $type->label(),
350         'title' => $node->label(),
351         'node' => $node,
352         'extra' => $extra,
353         'score' => $item->calculated_score,
354         'snippet' => search_excerpt($keys, $rendered, $item->langcode),
355         'langcode' => $node->language()->getId(),
356       ];
357
358       $this->addCacheableDependency($node);
359
360       // We have to separately add the node owner's cache tags because search
361       // module doesn't use the rendering system, it does its own rendering
362       // without taking cacheability metadata into account. So we have to do it
363       // explicitly here.
364       $this->addCacheableDependency($node->getOwner());
365
366       if ($type->displaySubmitted()) {
367         $result += [
368           'user' => $this->renderer->renderPlain($username),
369           'date' => $node->getChangedTime(),
370         ];
371       }
372
373       $results[] = $result;
374
375     }
376     return $results;
377   }
378
379   /**
380    * Removes the submitted by information from the build array.
381    *
382    * This information is being removed from the rendered node that is used to
383    * build the search result snippet. It just doesn't make sense to have it
384    * displayed in the snippet.
385    *
386    * @param array $build
387    *   The build array.
388    *
389    * @return array
390    *   The modified build array.
391    */
392   public function removeSubmittedInfo(array $build) {
393     unset($build['created']);
394     unset($build['uid']);
395     return $build;
396   }
397
398   /**
399    * Adds the configured rankings to the search query.
400    *
401    * @param $query
402    *   A query object that has been extended with the Search DB Extender.
403    */
404   protected function addNodeRankings(SelectExtender $query) {
405     if ($ranking = $this->getRankings()) {
406       $tables = &$query->getTables();
407       foreach ($ranking as $rank => $values) {
408         if (isset($this->configuration['rankings'][$rank]) && !empty($this->configuration['rankings'][$rank])) {
409           $node_rank = $this->configuration['rankings'][$rank];
410           // If the table defined in the ranking isn't already joined, then add it.
411           if (isset($values['join']) && !isset($tables[$values['join']['alias']])) {
412             $query->addJoin($values['join']['type'], $values['join']['table'], $values['join']['alias'], $values['join']['on']);
413           }
414           $arguments = isset($values['arguments']) ? $values['arguments'] : [];
415           $query->addScore($values['score'], $arguments, $node_rank);
416         }
417       }
418     }
419   }
420
421   /**
422    * {@inheritdoc}
423    */
424   public function updateIndex() {
425     // Interpret the cron limit setting as the maximum number of nodes to index
426     // per cron run.
427     $limit = (int) $this->searchSettings->get('index.cron_limit');
428
429     $query = db_select('node', 'n', ['target' => 'replica']);
430     $query->addField('n', 'nid');
431     $query->leftJoin('search_dataset', 'sd', 'sd.sid = n.nid AND sd.type = :type', [':type' => $this->getPluginId()]);
432     $query->addExpression('CASE MAX(sd.reindex) WHEN NULL THEN 0 ELSE 1 END', 'ex');
433     $query->addExpression('MAX(sd.reindex)', 'ex2');
434     $query->condition(
435         $query->orConditionGroup()
436           ->where('sd.sid IS NULL')
437           ->condition('sd.reindex', 0, '<>')
438       );
439     $query->orderBy('ex', 'DESC')
440       ->orderBy('ex2')
441       ->orderBy('n.nid')
442       ->groupBy('n.nid')
443       ->range(0, $limit);
444
445     $nids = $query->execute()->fetchCol();
446     if (!$nids) {
447       return;
448     }
449
450     $node_storage = $this->entityManager->getStorage('node');
451     foreach ($node_storage->loadMultiple($nids) as $node) {
452       $this->indexNode($node);
453     }
454   }
455
456   /**
457    * Indexes a single node.
458    *
459    * @param \Drupal\node\NodeInterface $node
460    *   The node to index.
461    */
462   protected function indexNode(NodeInterface $node) {
463     $languages = $node->getTranslationLanguages();
464     $node_render = $this->entityManager->getViewBuilder('node');
465
466     foreach ($languages as $language) {
467       $node = $node->getTranslation($language->getId());
468       // Render the node.
469       $build = $node_render->view($node, 'search_index', $language->getId());
470
471       unset($build['#theme']);
472
473       // Add the title to text so it is searchable.
474       $build['search_title'] = [
475         '#prefix' => '<h1>',
476         '#plain_text' => $node->label(),
477         '#suffix' => '</h1>',
478         '#weight' => -1000
479       ];
480       $text = $this->renderer->renderPlain($build);
481
482       // Fetch extra data normally not visible.
483       $extra = $this->moduleHandler->invokeAll('node_update_index', [$node]);
484       foreach ($extra as $t) {
485         $text .= $t;
486       }
487
488       // Update index, using search index "type" equal to the plugin ID.
489       search_index($this->getPluginId(), $node->id(), $language->getId(), $text);
490     }
491   }
492
493   /**
494    * {@inheritdoc}
495    */
496   public function indexClear() {
497     // All NodeSearch pages share a common search index "type" equal to
498     // the plugin ID.
499     search_index_clear($this->getPluginId());
500   }
501
502   /**
503    * {@inheritdoc}
504    */
505   public function markForReindex() {
506     // All NodeSearch pages share a common search index "type" equal to
507     // the plugin ID.
508     search_mark_for_reindex($this->getPluginId());
509   }
510
511   /**
512    * {@inheritdoc}
513    */
514   public function indexStatus() {
515     $total = $this->database->query('SELECT COUNT(*) FROM {node}')->fetchField();
516     $remaining = $this->database->query("SELECT COUNT(DISTINCT n.nid) FROM {node} n LEFT JOIN {search_dataset} sd ON sd.sid = n.nid AND sd.type = :type WHERE sd.sid IS NULL OR sd.reindex <> 0", [':type' => $this->getPluginId()])->fetchField();
517
518     return ['remaining' => $remaining, 'total' => $total];
519   }
520
521   /**
522    * {@inheritdoc}
523    */
524   public function searchFormAlter(array &$form, FormStateInterface $form_state) {
525     $parameters = $this->getParameters();
526     $keys = $this->getKeywords();
527     $used_advanced = !empty($parameters[self::ADVANCED_FORM]);
528     if ($used_advanced) {
529       $f = isset($parameters['f']) ? (array) $parameters['f'] : [];
530       $defaults = $this->parseAdvancedDefaults($f, $keys);
531     }
532     else {
533       $defaults = ['keys' => $keys];
534     }
535
536     $form['basic']['keys']['#default_value'] = $defaults['keys'];
537
538     // Add advanced search keyword-related boxes.
539     $form['advanced'] = [
540       '#type' => 'details',
541       '#title' => t('Advanced search'),
542       '#attributes' => ['class' => ['search-advanced']],
543       '#access' => $this->account && $this->account->hasPermission('use advanced search'),
544       '#open' => $used_advanced,
545     ];
546     $form['advanced']['keywords-fieldset'] = [
547       '#type' => 'fieldset',
548       '#title' => t('Keywords'),
549     ];
550
551     $form['advanced']['keywords'] = [
552       '#prefix' => '<div class="criterion">',
553       '#suffix' => '</div>',
554     ];
555
556     $form['advanced']['keywords-fieldset']['keywords']['or'] = [
557       '#type' => 'textfield',
558       '#title' => t('Containing any of the words'),
559       '#size' => 30,
560       '#maxlength' => 255,
561       '#default_value' => isset($defaults['or']) ? $defaults['or'] : '',
562     ];
563
564     $form['advanced']['keywords-fieldset']['keywords']['phrase'] = [
565       '#type' => 'textfield',
566       '#title' => t('Containing the phrase'),
567       '#size' => 30,
568       '#maxlength' => 255,
569       '#default_value' => isset($defaults['phrase']) ? $defaults['phrase'] : '',
570     ];
571
572     $form['advanced']['keywords-fieldset']['keywords']['negative'] = [
573       '#type' => 'textfield',
574       '#title' => t('Containing none of the words'),
575       '#size' => 30,
576       '#maxlength' => 255,
577       '#default_value' => isset($defaults['negative']) ? $defaults['negative'] : '',
578     ];
579
580     // Add node types.
581     $types = array_map(['\Drupal\Component\Utility\Html', 'escape'], node_type_get_names());
582     $form['advanced']['types-fieldset'] = [
583       '#type' => 'fieldset',
584       '#title' => t('Types'),
585     ];
586     $form['advanced']['types-fieldset']['type'] = [
587       '#type' => 'checkboxes',
588       '#title' => t('Only of the type(s)'),
589       '#prefix' => '<div class="criterion">',
590       '#suffix' => '</div>',
591       '#options' => $types,
592       '#default_value' => isset($defaults['type']) ? $defaults['type'] : [],
593     ];
594
595     $form['advanced']['submit'] = [
596       '#type' => 'submit',
597       '#value' => t('Advanced search'),
598       '#prefix' => '<div class="action">',
599       '#suffix' => '</div>',
600       '#weight' => 100,
601     ];
602
603     // Add languages.
604     $language_options = [];
605     $language_list = $this->languageManager->getLanguages(LanguageInterface::STATE_ALL);
606     foreach ($language_list as $langcode => $language) {
607       // Make locked languages appear special in the list.
608       $language_options[$langcode] = $language->isLocked() ? t('- @name -', ['@name' => $language->getName()]) : $language->getName();
609     }
610     if (count($language_options) > 1) {
611       $form['advanced']['lang-fieldset'] = [
612         '#type' => 'fieldset',
613         '#title' => t('Languages'),
614       ];
615       $form['advanced']['lang-fieldset']['language'] = [
616         '#type' => 'checkboxes',
617         '#title' => t('Languages'),
618         '#prefix' => '<div class="criterion">',
619         '#suffix' => '</div>',
620         '#options' => $language_options,
621         '#default_value' => isset($defaults['language']) ? $defaults['language'] : [],
622       ];
623     }
624   }
625
626   /**
627    * {@inheritdoc}
628    */
629   public function buildSearchUrlQuery(FormStateInterface $form_state) {
630     // Read keyword and advanced search information from the form values,
631     // and put these into the GET parameters.
632     $keys = trim($form_state->getValue('keys'));
633     $advanced = FALSE;
634
635     // Collect extra filters.
636     $filters = [];
637     if ($form_state->hasValue('type') && is_array($form_state->getValue('type'))) {
638       // Retrieve selected types - Form API sets the value of unselected
639       // checkboxes to 0.
640       foreach ($form_state->getValue('type') as $type) {
641         if ($type) {
642           $advanced = TRUE;
643           $filters[] = 'type:' . $type;
644         }
645       }
646     }
647
648     if ($form_state->hasValue('term') && is_array($form_state->getValue('term'))) {
649       foreach ($form_state->getValue('term') as $term) {
650         $filters[] = 'term:' . $term;
651         $advanced = TRUE;
652       }
653     }
654     if ($form_state->hasValue('language') && is_array($form_state->getValue('language'))) {
655       foreach ($form_state->getValue('language') as $language) {
656         if ($language) {
657           $advanced = TRUE;
658           $filters[] = 'language:' . $language;
659         }
660       }
661     }
662     if ($form_state->getValue('or') != '') {
663       if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state->getValue('or'), $matches)) {
664         $keys .= ' ' . implode(' OR ', $matches[1]);
665         $advanced = TRUE;
666       }
667     }
668     if ($form_state->getValue('negative') != '') {
669       if (preg_match_all('/ ("[^"]+"|[^" ]+)/i', ' ' . $form_state->getValue('negative'), $matches)) {
670         $keys .= ' -' . implode(' -', $matches[1]);
671         $advanced = TRUE;
672       }
673     }
674     if ($form_state->getValue('phrase') != '') {
675       $keys .= ' "' . str_replace('"', ' ', $form_state->getValue('phrase')) . '"';
676       $advanced = TRUE;
677     }
678     $keys = trim($keys);
679
680     // Put the keywords and advanced parameters into GET parameters. Make sure
681     // to put keywords into the query even if it is empty, because the page
682     // controller uses that to decide it's time to check for search results.
683     $query = ['keys' => $keys];
684     if ($filters) {
685       $query['f'] = $filters;
686     }
687     // Record that the person used the advanced search form, if they did.
688     if ($advanced) {
689       $query[self::ADVANCED_FORM] = '1';
690     }
691
692     return $query;
693   }
694
695   /**
696    * Parses the advanced search form default values.
697    *
698    * @param array $f
699    *   The 'f' query parameter set up in self::buildUrlSearchQuery(), which
700    *   contains the advanced query values.
701    * @param string $keys
702    *   The search keywords string, which contains some information from the
703    *   advanced search form.
704    *
705    * @return array
706    *   Array of default form values for the advanced search form, including
707    *   a modified 'keys' element for the bare search keywords.
708    */
709   protected function parseAdvancedDefaults($f, $keys) {
710     $defaults = [];
711
712     // Split out the advanced search parameters.
713     foreach ($f as $advanced) {
714       list($key, $value) = explode(':', $advanced, 2);
715       if (!isset($defaults[$key])) {
716         $defaults[$key] = [];
717       }
718       $defaults[$key][] = $value;
719     }
720
721     // Split out the negative, phrase, and OR parts of keywords.
722
723     // For phrases, the form only supports one phrase.
724     $matches = [];
725     $keys = ' ' . $keys . ' ';
726     if (preg_match('/ "([^"]+)" /', $keys, $matches)) {
727       $keys = str_replace($matches[0], ' ', $keys);
728       $defaults['phrase'] = $matches[1];
729     }
730
731     // Negative keywords: pull all of them out.
732     if (preg_match_all('/ -([^ ]+)/', $keys, $matches)) {
733       $keys = str_replace($matches[0], ' ', $keys);
734       $defaults['negative'] = implode(' ', $matches[1]);
735     }
736
737     // OR keywords: pull up to one set of them out of the query.
738     if (preg_match('/ [^ ]+( OR [^ ]+)+ /', $keys, $matches)) {
739       $keys = str_replace($matches[0], ' ', $keys);
740       $words = explode(' OR ', trim($matches[0]));
741       $defaults['or'] = implode(' ', $words);
742     }
743
744     // Put remaining keywords string back into keywords.
745     $defaults['keys'] = trim($keys);
746
747     return $defaults;
748   }
749
750   /**
751    * Gathers ranking definitions from hook_ranking().
752    *
753    * @return array
754    *   An array of ranking definitions.
755    */
756   protected function getRankings() {
757     if (!$this->rankings) {
758       $this->rankings = $this->moduleHandler->invokeAll('ranking');
759     }
760     return $this->rankings;
761   }
762
763   /**
764    * {@inheritdoc}
765    */
766   public function defaultConfiguration() {
767     $configuration = [
768       'rankings' => [],
769     ];
770     return $configuration;
771   }
772
773   /**
774    * {@inheritdoc}
775    */
776   public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
777     // Output form for defining rank factor weights.
778     $form['content_ranking'] = [
779       '#type' => 'details',
780       '#title' => t('Content ranking'),
781       '#open' => TRUE,
782     ];
783     $form['content_ranking']['info'] = [
784       '#markup' => '<p><em>' . $this->t('Influence is a numeric multiplier used in ordering search results. A higher number means the corresponding factor has more influence on search results; zero means the factor is ignored. Changing these numbers does not require the search index to be rebuilt. Changes take effect immediately.') . '</em></p>'
785     ];
786     // Prepare table.
787     $header = [$this->t('Factor'), $this->t('Influence')];
788     $form['content_ranking']['rankings'] = [
789       '#type' => 'table',
790       '#header' => $header,
791     ];
792
793     // Note: reversed to reflect that higher number = higher ranking.
794     $range = range(0, 10);
795     $options = array_combine($range, $range);
796     foreach ($this->getRankings() as $var => $values) {
797       $form['content_ranking']['rankings'][$var]['name'] = [
798         '#markup' => $values['title'],
799       ];
800       $form['content_ranking']['rankings'][$var]['value'] = [
801         '#type' => 'select',
802         '#options' => $options,
803         '#attributes' => ['aria-label' => $this->t("Influence of '@title'", ['@title' => $values['title']])],
804         '#default_value' => isset($this->configuration['rankings'][$var]) ? $this->configuration['rankings'][$var] : 0,
805       ];
806     }
807     return $form;
808   }
809
810   /**
811    * {@inheritdoc}
812    */
813   public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
814     foreach ($this->getRankings() as $var => $values) {
815       if (!$form_state->isValueEmpty(['rankings', $var, 'value'])) {
816         $this->configuration['rankings'][$var] = $form_state->getValue(['rankings', $var, 'value']);
817       }
818       else {
819         unset($this->configuration['rankings'][$var]);
820       }
821     }
822   }
823
824 }