annotate core/modules/node/src/Plugin/Search/NodeSearch.php @ 19:fa3358dc1485 tip

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