search.module 40.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
<?php

/**
 * @file
 * Enables site-wide keyword searching.
 */

use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Matches all 'N' Unicode character classes (numbers)
 */
define('PREG_CLASS_NUMBERS',
  '\x{30}-\x{39}\x{b2}\x{b3}\x{b9}\x{bc}-\x{be}\x{660}-\x{669}\x{6f0}-\x{6f9}' .
  '\x{966}-\x{96f}\x{9e6}-\x{9ef}\x{9f4}-\x{9f9}\x{a66}-\x{a6f}\x{ae6}-\x{aef}' .
  '\x{b66}-\x{b6f}\x{be7}-\x{bf2}\x{c66}-\x{c6f}\x{ce6}-\x{cef}\x{d66}-\x{d6f}' .
  '\x{e50}-\x{e59}\x{ed0}-\x{ed9}\x{f20}-\x{f33}\x{1040}-\x{1049}\x{1369}-' .
  '\x{137c}\x{16ee}-\x{16f0}\x{17e0}-\x{17e9}\x{17f0}-\x{17f9}\x{1810}-\x{1819}' .
  '\x{1946}-\x{194f}\x{2070}\x{2074}-\x{2079}\x{2080}-\x{2089}\x{2153}-\x{2183}' .
  '\x{2460}-\x{249b}\x{24ea}-\x{24ff}\x{2776}-\x{2793}\x{3007}\x{3021}-\x{3029}' .
  '\x{3038}-\x{303a}\x{3192}-\x{3195}\x{3220}-\x{3229}\x{3251}-\x{325f}\x{3280}-' .
  '\x{3289}\x{32b1}-\x{32bf}\x{ff10}-\x{ff19}');

/**
 * Matches all 'P' Unicode character classes (punctuation)
 */
define('PREG_CLASS_PUNCTUATION',
  '\x{21}-\x{23}\x{25}-\x{2a}\x{2c}-\x{2f}\x{3a}\x{3b}\x{3f}\x{40}\x{5b}-\x{5d}' .
  '\x{5f}\x{7b}\x{7d}\x{a1}\x{ab}\x{b7}\x{bb}\x{bf}\x{37e}\x{387}\x{55a}-\x{55f}' .
  '\x{589}\x{58a}\x{5be}\x{5c0}\x{5c3}\x{5f3}\x{5f4}\x{60c}\x{60d}\x{61b}\x{61f}' .
  '\x{66a}-\x{66d}\x{6d4}\x{700}-\x{70d}\x{964}\x{965}\x{970}\x{df4}\x{e4f}' .
  '\x{e5a}\x{e5b}\x{f04}-\x{f12}\x{f3a}-\x{f3d}\x{f85}\x{104a}-\x{104f}\x{10fb}' .
  '\x{1361}-\x{1368}\x{166d}\x{166e}\x{169b}\x{169c}\x{16eb}-\x{16ed}\x{1735}' .
  '\x{1736}\x{17d4}-\x{17d6}\x{17d8}-\x{17da}\x{1800}-\x{180a}\x{1944}\x{1945}' .
  '\x{2010}-\x{2027}\x{2030}-\x{2043}\x{2045}-\x{2051}\x{2053}\x{2054}\x{2057}' .
  '\x{207d}\x{207e}\x{208d}\x{208e}\x{2329}\x{232a}\x{23b4}-\x{23b6}\x{2768}-' .
  '\x{2775}\x{27e6}-\x{27eb}\x{2983}-\x{2998}\x{29d8}-\x{29db}\x{29fc}\x{29fd}' .
  '\x{3001}-\x{3003}\x{3008}-\x{3011}\x{3014}-\x{301f}\x{3030}\x{303d}\x{30a0}' .
  '\x{30fb}\x{fd3e}\x{fd3f}\x{fe30}-\x{fe52}\x{fe54}-\x{fe61}\x{fe63}\x{fe68}' .
  '\x{fe6a}\x{fe6b}\x{ff01}-\x{ff03}\x{ff05}-\x{ff0a}\x{ff0c}-\x{ff0f}\x{ff1a}' .
  '\x{ff1b}\x{ff1f}\x{ff20}\x{ff3b}-\x{ff3d}\x{ff3f}\x{ff5b}\x{ff5d}\x{ff5f}-' .
  '\x{ff65}');

/**
 * Matches CJK (Chinese, Japanese, Korean) letter-like characters.
 *
 * This list is derived from the "East Asian Scripts" section of
 * http://www.unicode.org/charts/index.html, as well as a comment on
 * http://unicode.org/reports/tr11/tr11-11.html listing some character
 * ranges that are reserved for additional CJK ideographs.
 *
 * The character ranges do not include numbers, punctuation, or symbols, since
 * these are handled separately in search. Note that radicals and strokes are
 * considered symbols. (See
 * http://www.unicode.org/Public/UNIDATA/extracted/DerivedGeneralCategory.txt)
 *
 * @see search_expand_cjk()
 */
define('PREG_CLASS_CJK', '\x{1100}-\x{11FF}\x{3040}-\x{309F}\x{30A1}-\x{318E}' .
  '\x{31A0}-\x{31B7}\x{31F0}-\x{31FF}\x{3400}-\x{4DBF}\x{4E00}-\x{9FCF}' .
  '\x{A000}-\x{A48F}\x{A4D0}-\x{A4FD}\x{A960}-\x{A97F}\x{AC00}-\x{D7FF}' .
  '\x{F900}-\x{FAFF}\x{FF21}-\x{FF3A}\x{FF41}-\x{FF5A}\x{FF66}-\x{FFDC}' .
  '\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}');

/**
 * Implements hook_help().
 */
function search_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.search':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The Search module provides the ability to set up search pages based on plugins provided by other modules. In Drupal core, there are two page-type plugins: the Content page type provides keyword searching for content managed by the Node module, and the Users page type provides keyword searching for registered users. Contributed modules may provide other page-type plugins. For more information, see the <a href=":search-module">online documentation for the Search module</a>.', array(':search-module' => 'https://www.drupal.org/documentation/modules/search')) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Configuring search pages') . '</dt>';
      $output .= '<dd>' . t('To configure search pages, visit the <a href=":search-settings">Search pages page</a>. In the Search pages section, you can add a new search page, edit the configuration of existing search pages, enable and disable search pages, and choose the default search page. Each enabled search page has a URL path starting with <em>search</em>, and each will appear as a tab or local task link on the <a href=":search-url">search page</a>; you can configure the text that is shown in the tab. In addition, some search page plugins have additional settings that you can configure for each search page.', array(':search-settings' => \Drupal::url('entity.search_page.collection'), ':search-url' => \Drupal::url('search.view'))) . '</dd>';
      $output .= '<dt>' . t('Managing the search index') . '</dt>';
      $output .= '<dd>' . t('Some search page plugins, such as the core Content search page, index searchable text using the Drupal core search index, and will not work unless content is indexed. Indexing is done during <em>cron</em> runs, so it requires a <a href=":cron">cron maintenance task</a> to be set up. There are also several settings affecting indexing that can be configured on the <a href=":search-settings">Search pages page</a>: the number of items to index per cron run, the minimum word length to index, and how to handle Chinese, Japanese, and Korean characters.', array(':cron' => \Drupal::url('system.cron_settings'), ':search-settings' => \Drupal::url('entity.search_page.collection'))) . '</dd>';
      $output .= '<dd>' . t('Modules providing search page plugins generally ensure that content-related actions on your site (creating, editing, or deleting content and comments) automatically cause affected content items to be marked for indexing or reindexing at the next cron run. When content is marked for reindexing, the previous content remains in the index until cron runs, at which time it is replaced by the new content. However, there are some actions related to the structure of your site that do not cause affected content to be marked for reindexing. Examples of structure-related actions that affect content include deleting or editing taxonomy terms, enabling or disabling modules that add text to content (such as Taxonomy, Comment, and field-providing modules), and modifying the fields or display parameters of your content types. If you take one of these actions and you want to ensure that the search index is updated to reflect your changed site structure, you can mark all content for reindexing by clicking the "Re-index site" button on the <a href=":search-settings">Search pages page</a>. If you have a lot of content on your site, it may take several cron runs for the content to be reindexed.', array(':search-settings' => \Drupal::url('entity.search_page.collection'))) . '</dd>';
      $output .= '<dt>' . t('Displaying the Search block') . '</dt>';
      $output .= '<dd>' . t('The Search module includes a block, which can be enabled and configured on the <a href=":blocks">Block layout page</a>, if you have the Block module enabled; the default block title is Search, and it is the Search form block in the Forms category, if you wish to add another instance. The block is available to users with the <a href=":search_permission">Use search</a> permission, and it performs a search using the configured default search page.', array(':blocks' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#', ':search_permission' => \Drupal::url('user.admin_permissions', array(), array('fragment' => 'module-search')))) . '</dd>';
      $output .= '<dt>' . t('Searching your site') . '</dt>';
      $output .= '<dd>' . t('Users with <a href=":search_permission">Use search</a> permission can use the Search block and <a href=":search">Search page</a>. Users with the <a href=":node_permission">View published content</a> permission can use configured search pages of type <em>Content</em> to search for content containing exact keywords; in addition, users with <a href=":search_permission">Use advanced search</a> permission can use more complex search filtering. Users with the <a href=":user_permission">View user information</a> permission can use configured search pages of type <em>Users</em> to search for active users containing the keyword anywhere in the username, and users with the <a href=":user_permission">Administer users</a> permission can search for active and blocked users, by email address or username keyword.', array(':search' => \Drupal::url('search.view'), ':search_permission' => \Drupal::url('user.admin_permissions', array(), array('fragment' => 'module-search')), ':node_permission' => \Drupal::url('user.admin_permissions', array(), array('fragment' => 'module-node')), ':user_permission' => \Drupal::url('user.admin_permissions', array(), array('fragment' => 'module-user')))) . '</dd>';
      $output .= '<dt>' . t('Extending the Search module') . '</dt>';
      $output .= '<dd>' . t('By default, the Search module only supports exact keyword matching in content searches. You can modify this behavior by installing a language-specific stemming module for your language (such as <a href=":porterstemmer_url">Porter Stemmer</a> for American English), which allows words such as walk, walking, and walked to be matched in the Search module. Another approach is to use a third-party search technology with stemming or partial word matching features built in, such as <a href=":solr_url">Apache Solr</a> or <a href=":sphinx_url">Sphinx</a>. There are also contributed modules that provide additional search pages. These and other <a href=":contrib-search">search-related contributed modules</a> can be downloaded by visiting Drupal.org.', array(':contrib-search' => 'https://www.drupal.org/project/project_module?f[2]=im_vid_3%3A105', ':porterstemmer_url' => 'https://www.drupal.org/project/porterstemmer', ':solr_url' => 'https://www.drupal.org/project/apachesolr', ':sphinx_url' => 'https://www.drupal.org/project/sphinx')) . '</dd>';
      $output .= '</dl>';
      return $output;
  }
}

/**
 * Implements hook_theme().
 */
function search_theme() {
  return array(
    'search_result' => array(
      'variables' => array('result' => NULL, 'plugin_id' => NULL),
      'file' => 'search.pages.inc',
    ),
  );
}

/**
 * Implements hook_preprocess_HOOK() for block templates.
 */
function search_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'search_form_block') {
    $variables['attributes']['role'] = 'search';
  }
}

/**
 * Clears either a part of, or the entire search index.
 *
 * This function is meant for use by search page plugins, or for building a
 * user interface that lets users clear all or parts of the search index.
 *
 * @param string|null $type
 *   (optional) The plugin ID or other machine-readable type for the items to
 *   remove from the search index. If omitted, $sid and $langcode are ignored
 *   and the entire search index is cleared.
 * @param string|null $sid
 *   (optional) The ID of the items to remove from the search index. If
 *   omitted, all items matching $type are cleared, and $langcode is ignored.
 * @param string|null $langcode
 *   (optional) Language code of the item to remove from the search index. If
 *   omitted, all items matching $sid and $type are cleared.
 */
function search_index_clear($type = NULL, $sid = NULL, $langcode = NULL) {
  $query_index = db_delete('search_index');
  $query_dataset = db_delete('search_dataset');
  if ($type) {
    $query_index->condition('type', $type);
    $query_dataset->condition('type', $type);
    if ($sid) {
      $query_index->condition('sid', $sid);
      $query_dataset->condition('sid', $sid);
      if ($langcode) {
        $query_index->condition('langcode', $langcode);
        $query_dataset->condition('langcode', $langcode);
      }
    }
  }

  $query_index->execute();
  $query_dataset->execute();

  if ($type) {
    // Invalidate all render cache items that contain data from this index.
    Cache::invalidateTags(['search_index:' . $type]);
  }
  else {
    // Invalidate all render cache items that contain data from any index.
    Cache::invalidateTags(['search_index']);
  }
}

/**
 * Marks a word as "dirty" (changed), or retrieves the list of dirty words.
 *
 * This is used during indexing (cron). Words that are dirty have outdated
 * total counts in the search_total table, and need to be recounted.
 */
function search_dirty($word = NULL) {
  $dirty = &drupal_static(__FUNCTION__, array());
  if ($word !== NULL) {
    $dirty[$word] = TRUE;
  }
  else {
    return $dirty;
  }
}

/**
 * Implements hook_cron().
 *
 * Fires updateIndex() in the plugins for all indexable active search pages,
 * and cleans up dirty words.
 *
 * @see search_dirty()
 */
function search_cron() {
  // We register a shutdown function to ensure that search_total is always up
  // to date.
  drupal_register_shutdown_function('search_update_totals');

  /** @var $search_page_repository \Drupal\search\SearchPageRepositoryInterface */
  $search_page_repository = \Drupal::service('search.search_page_repository');
  foreach ($search_page_repository->getIndexableSearchPages() as $entity) {
    $entity->getPlugin()->updateIndex();
  }
}

/**
 * Updates the {search_total} database table.
 *
 * This function is called on shutdown to ensure that {search_total} is always
 * up to date (even if cron times out or otherwise fails).
 */
function search_update_totals() {
  // Update word IDF (Inverse Document Frequency) counts for new/changed words.
  foreach (search_dirty() as $word => $dummy) {
    // Get total count
    $total = db_query("SELECT SUM(score) FROM {search_index} WHERE word = :word", array(':word' => $word), array('target' => 'replica'))->fetchField();
    // Apply Zipf's law to equalize the probability distribution.
    $total = log10(1 + 1/(max(1, $total)));
    db_merge('search_total')
      ->key('word', $word)
      ->fields(array('count' => $total))
      ->execute();
  }
  // Find words that were deleted from search_index, but are still in
  // search_total. We use a LEFT JOIN between the two tables and keep only the
  // rows which fail to join.
  $result = db_query("SELECT t.word AS realword, i.word FROM {search_total} t LEFT JOIN {search_index} i ON t.word = i.word WHERE i.word IS NULL", array(), array('target' => 'replica'));
  $or = db_or();
  foreach ($result as $word) {
    $or->condition('word', $word->realword);
  }
  if (count($or) > 0) {
    db_delete('search_total')
      ->condition($or)
      ->execute();
  }
}

/**
 * Simplifies and preprocesses text for searching.
 *
 * Processing steps:
 * - Entities are decoded.
 * - Text is lower-cased and diacritics (accents) are removed.
 * - hook_search_preprocess() is invoked.
 * - CJK (Chinese, Japanese, Korean) characters are processed, depending on
 *   the search settings.
 * - Punctuation is processed (removed or replaced with spaces, depending on
 *   where it is; see code for details).
 * - Words are truncated to 50 characters maximum.
 *
 * @param string $text
 *   Text to simplify.
 * @param string|null $langcode
 *   Language code for the language of $text, if known.
 *
 * @return string
 *   Simplified and processed text.
 *
 * @see hook_search_preprocess()
 */
function search_simplify($text, $langcode = NULL) {
  // Decode entities to UTF-8
  $text = Html::decodeEntities($text);

  // Lowercase
  $text = Unicode::strtolower($text);

  // Remove diacritics.
  $text = \Drupal::service('transliteration')->removeDiacritics($text);

  // Call an external processor for word handling.
  search_invoke_preprocess($text, $langcode);

  // Simple CJK handling
  if (\Drupal::config('search.settings')->get('index.overlap_cjk')) {
    $text = preg_replace_callback('/[' . PREG_CLASS_CJK . ']+/u', 'search_expand_cjk', $text);
  }

  // To improve searching for numerical data such as dates, IP addresses
  // or version numbers, we consider a group of numerical characters
  // separated only by punctuation characters to be one piece.
  // This also means that searching for e.g. '20/03/1984' also returns
  // results with '20-03-1984' in them.
  // Readable regexp: ([number]+)[punctuation]+(?=[number])
  $text = preg_replace('/([' . PREG_CLASS_NUMBERS . ']+)[' . PREG_CLASS_PUNCTUATION . ']+(?=[' . PREG_CLASS_NUMBERS . '])/u', '\1', $text);

  // Multiple dot and dash groups are word boundaries and replaced with space.
  // No need to use the unicode modifier here because 0-127 ASCII characters
  // can't match higher UTF-8 characters as the leftmost bit of those are 1.
  $text = preg_replace('/[.-]{2,}/', ' ', $text);

  // The dot, underscore and dash are simply removed. This allows meaningful
  // search behavior with acronyms and URLs. See unicode note directly above.
  $text = preg_replace('/[._-]+/', '', $text);

  // With the exception of the rules above, we consider all punctuation,
  // marks, spacers, etc, to be a word boundary.
  $text = preg_replace('/[' . Unicode::PREG_CLASS_WORD_BOUNDARY . ']+/u', ' ', $text);

  // Truncate everything to 50 characters.
  $words = explode(' ', $text);
  array_walk($words, '_search_index_truncate');
  $text = implode(' ', $words);

  return $text;
}

/**
 * Splits CJK (Chinese, Japanese, Korean) text into tokens.
 *
 * The Search module matches exact words, where a word is defined to be a
 * sequence of characters delimited by spaces or punctuation. CJK languages are
 * written in long strings of characters, though, not split up into words. So
 * in order to allow search matching, we split up CJK text into tokens
 * consisting of consecutive, overlapping sequences of characters whose length
 * is equal to the 'minimum_word_size' variable. This tokenizing is only done
 * if the 'overlap_cjk' variable is TRUE.
 *
 * @param array $matches
 *   This function is a callback for preg_replace_callback(), which is called
 *   from search_simplify(). So, $matches is an array of regular expression
 *   matches, which means that $matches[0] contains the matched text -- a
 *   string of CJK characters to tokenize.
 *
 * @return string
 *   Tokenized text, starting and ending with a space character.
 */
function search_expand_cjk($matches) {
  $min = \Drupal::config('search.settings')->get('index.minimum_word_size');
  $str = $matches[0];
  $length = Unicode::strlen($str);
  // If the text is shorter than the minimum word size, don't tokenize it.
  if ($length <= $min) {
    return ' ' . $str . ' ';
  }
  $tokens = ' ';
  // Build a FIFO queue of characters.
  $chars = array();
  for ($i = 0; $i < $length; $i++) {
    // Add the next character off the beginning of the string to the queue.
    $current = Unicode::substr($str, 0, 1);
    $str = substr($str, strlen($current));
    $chars[] = $current;
    if ($i >= $min - 1) {
      // Make a token of $min characters, and add it to the token string.
      $tokens .= implode('', $chars) . ' ';
      // Shift out the first character in the queue.
      array_shift($chars);
    }
  }
  return $tokens;
}

/**
 * Simplifies and splits a string into words for indexing.
 *
 * @param string $text
 *   Text to process.
 * @param string|null $langcode
 *   Language code for the language of $text, if known.
 *
 * @return array
 *   Array of words in the simplified, preprocessed text.
 *
 * @see search_simplify()
 */
function search_index_split($text, $langcode = NULL) {
  $last = &drupal_static(__FUNCTION__);
  $lastsplit = &drupal_static(__FUNCTION__ . ':lastsplit');

  if ($last == $text) {
    return $lastsplit;
  }
  // Process words
  $text = search_simplify($text, $langcode);
  $words = explode(' ', $text);

  // Save last keyword result
  $last = $text;
  $lastsplit = $words;

  return $words;
}

/**
 * Helper function for array_walk in search_index_split.
 */
function _search_index_truncate(&$text) {
  // Use a static array to avoid re-truncating text we've done before.
  // The same words may often be passed in during excerpt generation.
  static $truncated = array();
  if (isset($truncated[$text])) {
    $text = $truncated[$text];
    return;
  }

  // If we didn't find it in the static array, perform the operation.
  $original = $text;
  if (is_numeric($text)) {
    $text = ltrim($text, '0');
  }
  $text = Unicode::truncate($text, 50);
  // Save it for the next time.
  $truncated[$original] = $text;
}

/**
 * Invokes hook_search_preprocess() to simplify text.
 *
 * @param string $text
 *   Text to preprocess, passed by reference and altered in place.
 * @param string|null $langcode
 *   Language code for the language of $text, if known.
 */
function search_invoke_preprocess(&$text, $langcode = NULL) {
  foreach (\Drupal::moduleHandler()->getImplementations('search_preprocess') as $module) {
    $text = \Drupal::moduleHandler()->invoke($module, 'search_preprocess', array($text, $langcode));
  }
}

/**
 * Updates the full-text search index for a particular item.
 *
 * @param string $type
 *   The plugin ID or other machine-readable type of this item,
 *   which should be less than 64 bytes.
 * @param int $sid
 *   An ID number identifying this particular item (e.g., node ID).
 * @param string $langcode
 *   Language code for the language of the text being indexed.
 * @param string $text
 *   The content of this item. Must be a piece of HTML or plain text.
 *
 * @ingroup search
 */
function search_index($type, $sid, $langcode, $text) {
  $minimum_word_size = \Drupal::config('search.settings')->get('index.minimum_word_size');

  // Multipliers for scores of words inside certain HTML tags. The weights are
  // stored in config so that modules can overwrite the default weights.
  // Note: 'a' must be included for link ranking to work.
  $tags = \Drupal::config('search.settings')->get('index.tag_weights');

  // Strip off all ignored tags to speed up processing, but insert space before
  // and after them to keep word boundaries.
  $text = str_replace(array('<', '>'), array(' <', '> '), $text);
  $text = strip_tags($text, '<' . implode('><', array_keys($tags)) . '>');

  // Split HTML tags from plain text.
  $split = preg_split('/\s*<([^>]+?)>\s*/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  // Note: PHP ensures the array consists of alternating delimiters and literals
  // and begins and ends with a literal (inserting $null as required).

  $tag = FALSE; // Odd/even counter. Tag or no tag.
  $score = 1; // Starting score per word
  $accum = ' '; // Accumulator for cleaned up data
  $tagstack = array(); // Stack with open tags
  $tagwords = 0; // Counter for consecutive words
  $focus = 1; // Focus state

  $scored_words = array(); // Accumulator for words for index

  foreach ($split as $value) {
    if ($tag) {
      // Increase or decrease score per word based on tag
      list($tagname) = explode(' ', $value, 2);
      $tagname = Unicode::strtolower($tagname);
      // Closing or opening tag?
      if ($tagname[0] == '/') {
        $tagname = substr($tagname, 1);
        // If we encounter unexpected tags, reset score to avoid incorrect boosting.
        if (!count($tagstack) || $tagstack[0] != $tagname) {
          $tagstack = array();
          $score = 1;
        }
        else {
          // Remove from tag stack and decrement score
          $score = max(1, $score - $tags[array_shift($tagstack)]);
        }
      }
      else {
        if (isset($tagstack[0]) && $tagstack[0] == $tagname) {
          // None of the tags we look for make sense when nested identically.
          // If they are, it's probably broken HTML.
          $tagstack = array();
          $score = 1;
        }
        else {
          // Add to open tag stack and increment score
          array_unshift($tagstack, $tagname);
          $score += $tags[$tagname];
        }
      }
      // A tag change occurred, reset counter.
      $tagwords = 0;
    }
    else {
      // Note: use of PREG_SPLIT_DELIM_CAPTURE above will introduce empty values
      if ($value != '') {
        $words = search_index_split($value, $langcode);
        foreach ($words as $word) {
          // Add word to accumulator
          $accum .= $word . ' ';
          // Check wordlength
          if (is_numeric($word) || Unicode::strlen($word) >= $minimum_word_size) {
            if (!isset($scored_words[$word])) {
              $scored_words[$word] = 0;
            }
            $scored_words[$word] += $score * $focus;
            // Focus is a decaying value in terms of the amount of unique words up to this point.
            // From 100 words and more, it decays, to e.g. 0.5 at 500 words and 0.3 at 1000 words.
            $focus = min(1, .01 + 3.5 / (2 + count($scored_words) * .015));
          }
          $tagwords++;
          // Too many words inside a single tag probably mean a tag was accidentally left open.
          if (count($tagstack) && $tagwords >= 15) {
            $tagstack = array();
            $score = 1;
          }
        }
      }
    }
    $tag = !$tag;
  }

  // Remove the item $sid from the search index, and invalidate the relevant
  // cache tags.
  search_index_clear($type, $sid, $langcode);

  // Insert cleaned up data into dataset
  db_insert('search_dataset')
    ->fields(array(
      'sid' => $sid,
      'langcode' => $langcode,
      'type' => $type,
      'data' => $accum,
      'reindex' => 0,
    ))
    ->execute();

  // Insert results into search index
  foreach ($scored_words as $word => $score) {
    // If a word already exists in the database, its score gets increased
    // appropriately. If not, we create a new record with the appropriate
    // starting score.
    db_merge('search_index')
      ->keys(array(
        'word' => $word,
        'sid' => $sid,
        'langcode' => $langcode,
        'type' => $type,
      ))
      ->fields(array('score' => $score))
      ->expression('score', 'score + :score', array(':score' => $score))
      ->execute();
    search_dirty($word);
  }
}

/**
 * Changes the timestamp on indexed items to 'now' to force reindexing.
 *
 * This function is meant for use by search page plugins, or for building a
 * user interface that lets users mark all or parts of the search index for
 * reindexing.
 *
 * @param string $type
 *   (optional) The plugin ID or other machine-readable type of this item. If
 *   omitted, the entire search index is marked for reindexing, and $sid and
 *   $langcode are ignored.
 * @param int $sid
 *   (optional) An ID number identifying this particular item (e.g., node ID).
 *   If omitted, everything matching $type is marked, and $langcode is ignored.
 * @param string $langcode
 *   (optional) The language code to clear. If omitted, everything matching
 *   $type and $sid is marked.
 */
function search_mark_for_reindex($type = NULL, $sid = NULL, $langcode = NULL) {
  $query = db_update('search_dataset')
    ->fields(array('reindex' => REQUEST_TIME))
    // Only mark items that were not previously marked for reindex, so that
    // marked items maintain their priority by request time.
    ->condition('reindex', 0);

  if ($type) {
    $query->condition('type', $type);
    if ($sid) {
      $query->condition('sid', $sid);
      if ($langcode) {
        $query->condition('langcode', $langcode);
      }
    }
  }

  $query->execute();
}

/**
 * @defgroup search Search interface
 * @{
 * The Drupal search interface manages a global search mechanism.
 *
 * Modules may plug into this system to provide searches of different types of
 * data. Most of the system is handled by the Search module, so this must be
 * enabled for all of the search features to work.
 *
 * There are two ways to interact with the search system:
 * - Specifically for searching nodes, you can implement
 *   hook_node_update_index() and hook_node_search_result(). However, note that
 *   the search system already indexes all visible output of a node; i.e.,
 *   everything displayed normally during node viewing. This is
 *   usually sufficient. You should only use this mechanism if you want
 *   additional, non-visible data to be indexed.
 * - Define a plugin implementing \Drupal\search\Plugin\SearchInterface and
 *   annotated as \Drupal\search\Annotation\SearchPlugin. This will create a
 *   search page type that users can use to set up one or more search pages.
 *   Each of these corresponds to a tab on the /search page, which can be
 *   used to perform searches. You will also need to implement the execute()
 *   method from the interface to perform the search. A base class is provided
 *   in \Drupal\search\Plugin\SearchPluginBase. For more information about
 *   plugins, see the @link plugin_api Plugin API topic. @endlink
 *
 * If your module needs to provide a more complicated search form, then you
 * need to implement it yourself. In that case, you may wish to define it as a
 * local task (tab) under the /search page (e.g. /search/mymodule) so that users
 * can easily find it.
 *
 * @see plugin_api
 * @see annotation
 */

/**
 * Returns snippets from a piece of text, with search keywords highlighted.
 *
 * Used for formatting search results. All HTML tags will be stripped from
 * $text.
 *
 * @param string $keys
 *   A string containing a search query.
 * @param string $text
 *   The text to extract fragments from.
 * @param string|null $langcode
 *   Language code for the language of $text, if known.
 *
 * @return array
 *   A render array containing HTML for the excerpt.
 */
function search_excerpt($keys, $text, $langcode = NULL) {
  // We highlight around non-indexable or CJK characters.
  $boundary_character = '[' . Unicode::PREG_CLASS_WORD_BOUNDARY . PREG_CLASS_CJK . ']';
  $preceded_by_boundary = '(?<=' . $boundary_character . ')';
  $followed_by_boundary = '(?=' . $boundary_character . ')';

  // Extract positive keywords and phrases.
  preg_match_all('/ ("([^"]+)"|(?!OR)([^" ]+))/', ' ' . $keys, $matches);
  $keys = array_merge($matches[2], $matches[3]);

  // Prepare text by stripping HTML tags and decoding HTML entities.
  $text = strip_tags(str_replace(array('<', '>'), array(' <', '> '), $text));
  $text = Html::decodeEntities($text);
  $text_length = strlen($text);

  // Make a list of unique keywords that are actually found in the text,
  // which could be items in $keys or replacements that are equivalent through
  // search_simplify().
  $temp_keys = array();
  foreach ($keys as $key) {
    $key = _search_find_match_with_simplify($key, $text, $boundary_character, $langcode);
    if (isset($key)) {
      // Quote slashes so they can be used in regular expressions.
      $temp_keys[] = preg_quote($key, '/');
    }
  }
  // Several keywords could have simplified down to the same thing, so pick
  // out the unique ones.
  $keys = array_unique($temp_keys);

  // Extract fragments of about 60 characters around keywords, bounded by word
  // boundary characters. Try to reach 256 characters, using second occurrences
  // if necessary.
  $ranges = array();
  $length = 0;
  $look_start = array();
  $remaining_keys = $keys;

  while ($length < 256 && !empty($remaining_keys)) {
    $found_keys = array();
    foreach ($remaining_keys as $key) {
      if ($length >= 256) {
        break;
      }

      // Remember where we last found $key, in case we are coming through a
      // second time.
      if (!isset($look_start[$key])) {
        $look_start[$key] = 0;
      }

      // See if we can find $key after where we found it the last time. Since
      // we are requiring a match on a word boundary, make sure $text starts
      // and ends with a space.
      $matches = array();
      if (preg_match('/' . $preceded_by_boundary . $key . $followed_by_boundary . '/iu', ' ' . $text . ' ', $matches, PREG_OFFSET_CAPTURE, $look_start[$key])) {
        $found_position = $matches[0][1];
        $look_start[$key] = $found_position + 1;
        // Keep track of which keys we found this time, in case we need to
        // pass through again to find more text.
        $found_keys[] = $key;

        // Locate a space before and after this match, leaving about 60
        // characters of context on each end.
        $before = strpos(' ' . $text, ' ', max(0, $found_position - 61));
        if ($before !== FALSE && $before <= $found_position) {
          if ($text_length > $found_position + 60) {
            $after = strrpos(substr($text, 0, $found_position + 60), ' ', $found_position);
          }
          else {
            $after = $text_length;
          }
          if ($after !== FALSE && $after > $found_position) {
            // Account for the spaces we added.
            $before = max($before - 1, 0);
            if ($before < $after) {
              // Save this range.
              $ranges[$before] = $after;
              $length += $after - $before;
            }
          }
        }
      }
    }
    // Next time through this loop, only look for keys we found this time,
    // if any.
    $remaining_keys = $found_keys;
  }

  if (empty($ranges)) {
    // We didn't find any keyword matches, so just return the first part of the
    // text. We also need to re-encode any HTML special characters that we
    // entity-decoded above.
    return [
      '#plain_text' => Unicode::truncate($text, 256, TRUE, TRUE),
    ];
  }

  // Sort the text ranges by starting position.
  ksort($ranges);

  // Collapse overlapping text ranges into one. The sorting makes it O(n).
  $new_ranges = array();
  $max_end = 0;
  foreach ($ranges as $this_from => $this_to) {
    $max_end = max($max_end, $this_to);
    if (!isset($working_from)) {
      // This is the first time through this loop: initialize.
      $working_from = $this_from;
      $working_to = $this_to;
      continue;
    }
    if ($this_from <= $working_to) {
      // The ranges overlap: combine them.
      $working_to = max($working_to, $this_to);
    }
    else {
      // The ranges do not overlap: save the working range and start a new one.
      $new_ranges[$working_from] = $working_to;
      $working_from = $this_from;
      $working_to = $this_to;
    }
  }
  // Save the remaining working range.
  $new_ranges[$working_from] = $working_to;

  // Fetch text within the combined ranges we found.
  $out = array();
  foreach ($new_ranges as $from => $to) {
    $out[] = substr($text, $from, $to - $from);
  }

  // Combine the text chunks with "…" separators. The "…" needs to be
  // translated. Let translators have the … separator text as one chunk.
  $ellipses = explode('@excerpt', t('… @excerpt … @excerpt …'));
  $text = (isset($new_ranges[0]) ? '' : $ellipses[0]) . implode($ellipses[1], $out) . (($max_end < strlen($text) - 1) ? $ellipses[2] : '');
  $text = Html::escape($text);

  // Highlight keywords. Must be done at once to prevent conflicts ('strong'
  // and '<strong>').
  $text = trim(preg_replace('/' . $preceded_by_boundary . '(?:' . implode('|', $keys) . ')' . $followed_by_boundary . '/iu', '<strong>\0</strong>', ' ' . $text . ' '));
  return [
    '#markup' => $text,
    '#allowed_tags' => ['strong']
  ];
}

/**
 * @} End of "defgroup search".
 */

/**
 * Finds an appropriate keyword in text.
 *
 * @param string $key
 *   The keyword to find.
 * @param string $text
 *   The text to search for the keyword.
 * @param string $boundary
 *   Regular expression for the boundary character class (characters that
 *   indicate spaces between words).
 * @param string|null $langcode
 *   Language code for the language of $text, if known.
 *
 * @return string|null
 *   A segment of $text that is between word boundary characters that either
 *   matches $key directly, or matches $key when both this text segment and
 *   $key are processed by search_simplify(). If a matching text segment is
 *   not located, NULL is returned.
 */
function _search_find_match_with_simplify($key, $text, $boundary, $langcode = NULL) {
  $preceded_by_boundary = '(?<=' . $boundary . ')';
  $followed_by_boundary = '(?=' . $boundary . ')';

  // See if $key appears as-is. When testing, make sure $text starts/ends with
  // a space, because we require $key to be surrounded by word boundary
  // characters.
  $temp = trim($key);
  if ($temp == '') {
    return NULL;
  }
  if (preg_match('/' . $preceded_by_boundary . preg_quote($temp, '/') . $followed_by_boundary . '/iu', ' ' . $text . ' ')) {
    return $temp;
  }

  // See if there is a match after lower-casing and removing diacritics in
  // both, which should preserve the string length.
  $new_text = Unicode::strtolower($text);
  $new_text = \Drupal::service('transliteration')->removeDiacritics($new_text);
  $new_key = Unicode::strtolower($temp);
  $new_key = \Drupal::service('transliteration')->removeDiacritics($new_key);
  if (preg_match('/' . $preceded_by_boundary . preg_quote($new_key, '/') . $followed_by_boundary . '/u', ' ' . $new_text . ' ')) {
    $position = Unicode::strpos($new_text, $new_key);
    return Unicode::substr($text, $position, Unicode::strlen($new_key));
  }

  // Run both text and key through search_simplify.
  $simplified_key = trim(search_simplify($key, $langcode));
  $simplified_text = trim(search_simplify($text, $langcode));
  if ($simplified_key == '' || $simplified_text == '' || strpos($simplified_text, $simplified_key) === FALSE) {
    // The simplified keyword and text do not match at all, or are empty.
    return NULL;
  }

  // Split $text into words, keeping track of where the word boundaries are.
  $words = preg_split('/' . $boundary . '+/u', $text, NULL, PREG_SPLIT_OFFSET_CAPTURE);
  // Add an entry pointing to the end of the string, for the loop below.
  $words[] = array('', strlen($text));

  // Using a binary search, find the earliest possible ending position in
  // $text where it will still match the keyword after applying
  // search_simplify().
  $start_index = 0;
  $start_pos = $words[$start_index][1];
  $min_end_index = 1;
  $max_end_index = count($words) - 1;
  while ($max_end_index > $min_end_index) {
    // Check the index half way between min and max. See if we ended there,
    // if we would still have a match.
    $proposed_end_index = floor(($max_end_index + $min_end_index) / 2);
    $proposed_end_pos = $words[$proposed_end_index][1];
    // Since the split was done with preg_split(), the positions are byte counts
    // not character counts, so use substr() not Unicode::substr() here.
    $trial_text = trim(search_simplify(substr($text, $start_pos, $proposed_end_pos - $start_pos), $langcode));
    if (strpos($trial_text, $simplified_key) !== FALSE) {
      // The proposed endpoint is fine, text still matches.
      $max_end_index = $proposed_end_index;
    }
    else {
      // The proposed endpoint index is too early, so the earliest possible
      // OK ending point would be the next index.
      $min_end_index = $proposed_end_index + 1;
    }
  }

  // Now do the same for the starting position: using a binary search, find the
  // latest possible starting position in $text where it will still match the
  // keyword after applying search_simplify().
  $end_index = $min_end_index;
  $end_pos = $words[$end_index][1];
  $min_start_index = 0;
  $max_start_index = $end_index - 1;
  while ($max_start_index > $min_start_index) {
    // Check the index half way between min and max. See if we started there,
    // if we would still have a match.
    $proposed_start_index = ceil(($max_start_index + $min_start_index) / 2);
    $proposed_start_pos = $words[$proposed_start_index][1];
    // Since the split was done with preg_split(), the positions are byte counts
    // not character counts, so use substr() not Unicode::substr() here.
    $trial_text = trim(search_simplify(substr($text, $proposed_start_pos, $end_pos - $proposed_start_pos), $langcode));
    if (strpos($trial_text, $simplified_key) !== FALSE) {
      // The proposed start point is fine, text still matches.
      $min_start_index = $proposed_start_index;
    }
    else {
      // The proposed start point index is too late, so the latest possible
      // OK starting point would be the previous index.
      $max_start_index = $proposed_start_index - 1;
    }
  }
  $start_index = $max_start_index;

  // Return the matching text. We need to use substr() here and not the
  // Unicode::substr() function, because the indices in $words came from
  // preg_split(), so they are Unicode-safe byte positions, not character
  // positions.
  return trim(substr($text, $words[$start_index][1], $words[$end_index][1] - $words[$start_index][1]));
}

/**
 * Implements hook_form_FORM_ID_alter() for the search_block_form form.
 *
 * Since the exposed form is a GET form, we don't want it to send the form
 * tokens. However, you cannot make this happen in the form builder function
 * itself, because the tokens are added to the form after the builder function
 * is called. So, we have to do it in a form_alter.
 *
 * @see \Drupal\search\Form\SearchBlockForm
 */
function search_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
  $form['form_build_id']['#access'] = FALSE;
  $form['form_token']['#access'] = FALSE;
  $form['form_id']['#access'] = FALSE;
}