annotate core/modules/node/src/Plugin/Search/NodeSearch.php @ 4:a9cd425dd02b

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