annotate core/modules/search/search.module @ 0:c75dbcec494b

Initial commit from drush-created site
author Chris Cannam
date Thu, 05 Jul 2018 14:24:15 +0000
parents
children a9cd425dd02b
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 /**
Chris@0 4 * @file
Chris@0 5 * Enables site-wide keyword searching.
Chris@0 6 */
Chris@0 7
Chris@0 8 use Drupal\Component\Utility\Html;
Chris@0 9 use Drupal\Component\Utility\Unicode;
Chris@0 10 use Drupal\Core\Cache\Cache;
Chris@0 11 use Drupal\Core\Database\Query\Condition;
Chris@0 12 use Drupal\Core\Form\FormStateInterface;
Chris@0 13 use Drupal\Core\Routing\RouteMatchInterface;
Chris@0 14
Chris@0 15 /**
Chris@0 16 * Matches all 'N' Unicode character classes (numbers)
Chris@0 17 */
Chris@0 18 define('PREG_CLASS_NUMBERS',
Chris@0 19 '\x{30}-\x{39}\x{b2}\x{b3}\x{b9}\x{bc}-\x{be}\x{660}-\x{669}\x{6f0}-\x{6f9}' .
Chris@0 20 '\x{966}-\x{96f}\x{9e6}-\x{9ef}\x{9f4}-\x{9f9}\x{a66}-\x{a6f}\x{ae6}-\x{aef}' .
Chris@0 21 '\x{b66}-\x{b6f}\x{be7}-\x{bf2}\x{c66}-\x{c6f}\x{ce6}-\x{cef}\x{d66}-\x{d6f}' .
Chris@0 22 '\x{e50}-\x{e59}\x{ed0}-\x{ed9}\x{f20}-\x{f33}\x{1040}-\x{1049}\x{1369}-' .
Chris@0 23 '\x{137c}\x{16ee}-\x{16f0}\x{17e0}-\x{17e9}\x{17f0}-\x{17f9}\x{1810}-\x{1819}' .
Chris@0 24 '\x{1946}-\x{194f}\x{2070}\x{2074}-\x{2079}\x{2080}-\x{2089}\x{2153}-\x{2183}' .
Chris@0 25 '\x{2460}-\x{249b}\x{24ea}-\x{24ff}\x{2776}-\x{2793}\x{3007}\x{3021}-\x{3029}' .
Chris@0 26 '\x{3038}-\x{303a}\x{3192}-\x{3195}\x{3220}-\x{3229}\x{3251}-\x{325f}\x{3280}-' .
Chris@0 27 '\x{3289}\x{32b1}-\x{32bf}\x{ff10}-\x{ff19}');
Chris@0 28
Chris@0 29 /**
Chris@0 30 * Matches all 'P' Unicode character classes (punctuation)
Chris@0 31 */
Chris@0 32 define('PREG_CLASS_PUNCTUATION',
Chris@0 33 '\x{21}-\x{23}\x{25}-\x{2a}\x{2c}-\x{2f}\x{3a}\x{3b}\x{3f}\x{40}\x{5b}-\x{5d}' .
Chris@0 34 '\x{5f}\x{7b}\x{7d}\x{a1}\x{ab}\x{b7}\x{bb}\x{bf}\x{37e}\x{387}\x{55a}-\x{55f}' .
Chris@0 35 '\x{589}\x{58a}\x{5be}\x{5c0}\x{5c3}\x{5f3}\x{5f4}\x{60c}\x{60d}\x{61b}\x{61f}' .
Chris@0 36 '\x{66a}-\x{66d}\x{6d4}\x{700}-\x{70d}\x{964}\x{965}\x{970}\x{df4}\x{e4f}' .
Chris@0 37 '\x{e5a}\x{e5b}\x{f04}-\x{f12}\x{f3a}-\x{f3d}\x{f85}\x{104a}-\x{104f}\x{10fb}' .
Chris@0 38 '\x{1361}-\x{1368}\x{166d}\x{166e}\x{169b}\x{169c}\x{16eb}-\x{16ed}\x{1735}' .
Chris@0 39 '\x{1736}\x{17d4}-\x{17d6}\x{17d8}-\x{17da}\x{1800}-\x{180a}\x{1944}\x{1945}' .
Chris@0 40 '\x{2010}-\x{2027}\x{2030}-\x{2043}\x{2045}-\x{2051}\x{2053}\x{2054}\x{2057}' .
Chris@0 41 '\x{207d}\x{207e}\x{208d}\x{208e}\x{2329}\x{232a}\x{23b4}-\x{23b6}\x{2768}-' .
Chris@0 42 '\x{2775}\x{27e6}-\x{27eb}\x{2983}-\x{2998}\x{29d8}-\x{29db}\x{29fc}\x{29fd}' .
Chris@0 43 '\x{3001}-\x{3003}\x{3008}-\x{3011}\x{3014}-\x{301f}\x{3030}\x{303d}\x{30a0}' .
Chris@0 44 '\x{30fb}\x{fd3e}\x{fd3f}\x{fe30}-\x{fe52}\x{fe54}-\x{fe61}\x{fe63}\x{fe68}' .
Chris@0 45 '\x{fe6a}\x{fe6b}\x{ff01}-\x{ff03}\x{ff05}-\x{ff0a}\x{ff0c}-\x{ff0f}\x{ff1a}' .
Chris@0 46 '\x{ff1b}\x{ff1f}\x{ff20}\x{ff3b}-\x{ff3d}\x{ff3f}\x{ff5b}\x{ff5d}\x{ff5f}-' .
Chris@0 47 '\x{ff65}');
Chris@0 48
Chris@0 49 /**
Chris@0 50 * Matches CJK (Chinese, Japanese, Korean) letter-like characters.
Chris@0 51 *
Chris@0 52 * This list is derived from the "East Asian Scripts" section of
Chris@0 53 * http://www.unicode.org/charts/index.html, as well as a comment on
Chris@0 54 * http://unicode.org/reports/tr11/tr11-11.html listing some character
Chris@0 55 * ranges that are reserved for additional CJK ideographs.
Chris@0 56 *
Chris@0 57 * The character ranges do not include numbers, punctuation, or symbols, since
Chris@0 58 * these are handled separately in search. Note that radicals and strokes are
Chris@0 59 * considered symbols. (See
Chris@0 60 * http://www.unicode.org/Public/UNIDATA/extracted/DerivedGeneralCategory.txt)
Chris@0 61 *
Chris@0 62 * @see search_expand_cjk()
Chris@0 63 */
Chris@0 64 define('PREG_CLASS_CJK', '\x{1100}-\x{11FF}\x{3040}-\x{309F}\x{30A1}-\x{318E}' .
Chris@0 65 '\x{31A0}-\x{31B7}\x{31F0}-\x{31FF}\x{3400}-\x{4DBF}\x{4E00}-\x{9FCF}' .
Chris@0 66 '\x{A000}-\x{A48F}\x{A4D0}-\x{A4FD}\x{A960}-\x{A97F}\x{AC00}-\x{D7FF}' .
Chris@0 67 '\x{F900}-\x{FAFF}\x{FF21}-\x{FF3A}\x{FF41}-\x{FF5A}\x{FF66}-\x{FFDC}' .
Chris@0 68 '\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}');
Chris@0 69
Chris@0 70 /**
Chris@0 71 * Implements hook_help().
Chris@0 72 */
Chris@0 73 function search_help($route_name, RouteMatchInterface $route_match) {
Chris@0 74 switch ($route_name) {
Chris@0 75 case 'help.page.search':
Chris@0 76 $output = '';
Chris@0 77 $output .= '<h3>' . t('About') . '</h3>';
Chris@0 78 $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>.', [':search-module' => 'https://www.drupal.org/documentation/modules/search']) . '</p>';
Chris@0 79 $output .= '<h3>' . t('Uses') . '</h3>';
Chris@0 80 $output .= '<dl>';
Chris@0 81 $output .= '<dt>' . t('Configuring search pages') . '</dt>';
Chris@0 82 $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.', [':search-settings' => \Drupal::url('entity.search_page.collection'), ':search-url' => \Drupal::url('search.view')]) . '</dd>';
Chris@0 83 $output .= '<dt>' . t('Managing the search index') . '</dt>';
Chris@0 84 $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.', [':cron' => \Drupal::url('system.cron_settings'), ':search-settings' => \Drupal::url('entity.search_page.collection')]) . '</dd>';
Chris@0 85 $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.', [':search-settings' => \Drupal::url('entity.search_page.collection')]) . '</dd>';
Chris@0 86 $output .= '<dt>' . t('Displaying the Search block') . '</dt>';
Chris@0 87 $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.', [':blocks' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#', ':search_permission' => \Drupal::url('user.admin_permissions', [], ['fragment' => 'module-search'])]) . '</dd>';
Chris@0 88 $output .= '<dt>' . t('Searching your site') . '</dt>';
Chris@0 89 $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.', [':search' => \Drupal::url('search.view'), ':search_permission' => \Drupal::url('user.admin_permissions', [], ['fragment' => 'module-search']), ':node_permission' => \Drupal::url('user.admin_permissions', [], ['fragment' => 'module-node']), ':user_permission' => \Drupal::url('user.admin_permissions', [], ['fragment' => 'module-user'])]) . '</dd>';
Chris@0 90 $output .= '<dt>' . t('Extending the Search module') . '</dt>';
Chris@0 91 $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.', [':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>';
Chris@0 92 $output .= '</dl>';
Chris@0 93 return $output;
Chris@0 94 }
Chris@0 95 }
Chris@0 96
Chris@0 97 /**
Chris@0 98 * Implements hook_theme().
Chris@0 99 */
Chris@0 100 function search_theme() {
Chris@0 101 return [
Chris@0 102 'search_result' => [
Chris@0 103 'variables' => ['result' => NULL, 'plugin_id' => NULL],
Chris@0 104 'file' => 'search.pages.inc',
Chris@0 105 ],
Chris@0 106 ];
Chris@0 107 }
Chris@0 108
Chris@0 109 /**
Chris@0 110 * Implements hook_theme_suggestions_HOOK().
Chris@0 111 */
Chris@0 112 function search_theme_suggestions_search_result(array $variables) {
Chris@0 113 return ['search_result__' . $variables['plugin_id']];
Chris@0 114 }
Chris@0 115
Chris@0 116 /**
Chris@0 117 * Implements hook_preprocess_HOOK() for block templates.
Chris@0 118 */
Chris@0 119 function search_preprocess_block(&$variables) {
Chris@0 120 if ($variables['plugin_id'] == 'search_form_block') {
Chris@0 121 $variables['attributes']['role'] = 'search';
Chris@0 122 }
Chris@0 123 }
Chris@0 124
Chris@0 125 /**
Chris@0 126 * Clears either a part of, or the entire search index.
Chris@0 127 *
Chris@0 128 * This function is meant for use by search page plugins, or for building a
Chris@0 129 * user interface that lets users clear all or parts of the search index.
Chris@0 130 *
Chris@0 131 * @param string|null $type
Chris@0 132 * (optional) The plugin ID or other machine-readable type for the items to
Chris@0 133 * remove from the search index. If omitted, $sid and $langcode are ignored
Chris@0 134 * and the entire search index is cleared.
Chris@0 135 * @param string|null $sid
Chris@0 136 * (optional) The ID of the items to remove from the search index. If
Chris@0 137 * omitted, all items matching $type are cleared, and $langcode is ignored.
Chris@0 138 * @param string|null $langcode
Chris@0 139 * (optional) Language code of the item to remove from the search index. If
Chris@0 140 * omitted, all items matching $sid and $type are cleared.
Chris@0 141 */
Chris@0 142 function search_index_clear($type = NULL, $sid = NULL, $langcode = NULL) {
Chris@0 143 $query_index = db_delete('search_index');
Chris@0 144 $query_dataset = db_delete('search_dataset');
Chris@0 145 if ($type) {
Chris@0 146 $query_index->condition('type', $type);
Chris@0 147 $query_dataset->condition('type', $type);
Chris@0 148 if ($sid) {
Chris@0 149 $query_index->condition('sid', $sid);
Chris@0 150 $query_dataset->condition('sid', $sid);
Chris@0 151 if ($langcode) {
Chris@0 152 $query_index->condition('langcode', $langcode);
Chris@0 153 $query_dataset->condition('langcode', $langcode);
Chris@0 154 }
Chris@0 155 }
Chris@0 156 }
Chris@0 157
Chris@0 158 $query_index->execute();
Chris@0 159 $query_dataset->execute();
Chris@0 160
Chris@0 161 if ($type) {
Chris@0 162 // Invalidate all render cache items that contain data from this index.
Chris@0 163 Cache::invalidateTags(['search_index:' . $type]);
Chris@0 164 }
Chris@0 165 else {
Chris@0 166 // Invalidate all render cache items that contain data from any index.
Chris@0 167 Cache::invalidateTags(['search_index']);
Chris@0 168 }
Chris@0 169 }
Chris@0 170
Chris@0 171 /**
Chris@0 172 * Marks a word as "dirty" (changed), or retrieves the list of dirty words.
Chris@0 173 *
Chris@0 174 * This is used during indexing (cron). Words that are dirty have outdated
Chris@0 175 * total counts in the search_total table, and need to be recounted.
Chris@0 176 */
Chris@0 177 function search_dirty($word = NULL) {
Chris@0 178 $dirty = &drupal_static(__FUNCTION__, []);
Chris@0 179 if ($word !== NULL) {
Chris@0 180 $dirty[$word] = TRUE;
Chris@0 181 }
Chris@0 182 else {
Chris@0 183 return $dirty;
Chris@0 184 }
Chris@0 185 }
Chris@0 186
Chris@0 187 /**
Chris@0 188 * Implements hook_cron().
Chris@0 189 *
Chris@0 190 * Fires updateIndex() in the plugins for all indexable active search pages,
Chris@0 191 * and cleans up dirty words.
Chris@0 192 *
Chris@0 193 * @see search_dirty()
Chris@0 194 */
Chris@0 195 function search_cron() {
Chris@0 196 // We register a shutdown function to ensure that search_total is always up
Chris@0 197 // to date.
Chris@0 198 drupal_register_shutdown_function('search_update_totals');
Chris@0 199
Chris@0 200 /** @var $search_page_repository \Drupal\search\SearchPageRepositoryInterface */
Chris@0 201 $search_page_repository = \Drupal::service('search.search_page_repository');
Chris@0 202 foreach ($search_page_repository->getIndexableSearchPages() as $entity) {
Chris@0 203 $entity->getPlugin()->updateIndex();
Chris@0 204 }
Chris@0 205 }
Chris@0 206
Chris@0 207 /**
Chris@0 208 * Updates the {search_total} database table.
Chris@0 209 *
Chris@0 210 * This function is called on shutdown to ensure that {search_total} is always
Chris@0 211 * up to date (even if cron times out or otherwise fails).
Chris@0 212 */
Chris@0 213 function search_update_totals() {
Chris@0 214 // Update word IDF (Inverse Document Frequency) counts for new/changed words.
Chris@0 215 foreach (search_dirty() as $word => $dummy) {
Chris@0 216 // Get total count
Chris@0 217 $total = db_query("SELECT SUM(score) FROM {search_index} WHERE word = :word", [':word' => $word], ['target' => 'replica'])->fetchField();
Chris@0 218 // Apply Zipf's law to equalize the probability distribution.
Chris@0 219 $total = log10(1 + 1 / (max(1, $total)));
Chris@0 220 db_merge('search_total')
Chris@0 221 ->key('word', $word)
Chris@0 222 ->fields(['count' => $total])
Chris@0 223 ->execute();
Chris@0 224 }
Chris@0 225 // Find words that were deleted from search_index, but are still in
Chris@0 226 // search_total. We use a LEFT JOIN between the two tables and keep only the
Chris@0 227 // rows which fail to join.
Chris@0 228 $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", [], ['target' => 'replica']);
Chris@0 229 $or = new Condition('OR');
Chris@0 230 foreach ($result as $word) {
Chris@0 231 $or->condition('word', $word->realword);
Chris@0 232 }
Chris@0 233 if (count($or) > 0) {
Chris@0 234 db_delete('search_total')
Chris@0 235 ->condition($or)
Chris@0 236 ->execute();
Chris@0 237 }
Chris@0 238 }
Chris@0 239
Chris@0 240 /**
Chris@0 241 * Simplifies and preprocesses text for searching.
Chris@0 242 *
Chris@0 243 * Processing steps:
Chris@0 244 * - Entities are decoded.
Chris@0 245 * - Text is lower-cased and diacritics (accents) are removed.
Chris@0 246 * - hook_search_preprocess() is invoked.
Chris@0 247 * - CJK (Chinese, Japanese, Korean) characters are processed, depending on
Chris@0 248 * the search settings.
Chris@0 249 * - Punctuation is processed (removed or replaced with spaces, depending on
Chris@0 250 * where it is; see code for details).
Chris@0 251 * - Words are truncated to 50 characters maximum.
Chris@0 252 *
Chris@0 253 * @param string $text
Chris@0 254 * Text to simplify.
Chris@0 255 * @param string|null $langcode
Chris@0 256 * Language code for the language of $text, if known.
Chris@0 257 *
Chris@0 258 * @return string
Chris@0 259 * Simplified and processed text.
Chris@0 260 *
Chris@0 261 * @see hook_search_preprocess()
Chris@0 262 */
Chris@0 263 function search_simplify($text, $langcode = NULL) {
Chris@0 264 // Decode entities to UTF-8
Chris@0 265 $text = Html::decodeEntities($text);
Chris@0 266
Chris@0 267 // Lowercase
Chris@0 268 $text = Unicode::strtolower($text);
Chris@0 269
Chris@0 270 // Remove diacritics.
Chris@0 271 $text = \Drupal::service('transliteration')->removeDiacritics($text);
Chris@0 272
Chris@0 273 // Call an external processor for word handling.
Chris@0 274 search_invoke_preprocess($text, $langcode);
Chris@0 275
Chris@0 276 // Simple CJK handling
Chris@0 277 if (\Drupal::config('search.settings')->get('index.overlap_cjk')) {
Chris@0 278 $text = preg_replace_callback('/[' . PREG_CLASS_CJK . ']+/u', 'search_expand_cjk', $text);
Chris@0 279 }
Chris@0 280
Chris@0 281 // To improve searching for numerical data such as dates, IP addresses
Chris@0 282 // or version numbers, we consider a group of numerical characters
Chris@0 283 // separated only by punctuation characters to be one piece.
Chris@0 284 // This also means that searching for e.g. '20/03/1984' also returns
Chris@0 285 // results with '20-03-1984' in them.
Chris@0 286 // Readable regexp: ([number]+)[punctuation]+(?=[number])
Chris@0 287 $text = preg_replace('/([' . PREG_CLASS_NUMBERS . ']+)[' . PREG_CLASS_PUNCTUATION . ']+(?=[' . PREG_CLASS_NUMBERS . '])/u', '\1', $text);
Chris@0 288
Chris@0 289 // Multiple dot and dash groups are word boundaries and replaced with space.
Chris@0 290 // No need to use the unicode modifier here because 0-127 ASCII characters
Chris@0 291 // can't match higher UTF-8 characters as the leftmost bit of those are 1.
Chris@0 292 $text = preg_replace('/[.-]{2,}/', ' ', $text);
Chris@0 293
Chris@0 294 // The dot, underscore and dash are simply removed. This allows meaningful
Chris@0 295 // search behavior with acronyms and URLs. See unicode note directly above.
Chris@0 296 $text = preg_replace('/[._-]+/', '', $text);
Chris@0 297
Chris@0 298 // With the exception of the rules above, we consider all punctuation,
Chris@0 299 // marks, spacers, etc, to be a word boundary.
Chris@0 300 $text = preg_replace('/[' . Unicode::PREG_CLASS_WORD_BOUNDARY . ']+/u', ' ', $text);
Chris@0 301
Chris@0 302 // Truncate everything to 50 characters.
Chris@0 303 $words = explode(' ', $text);
Chris@0 304 array_walk($words, '_search_index_truncate');
Chris@0 305 $text = implode(' ', $words);
Chris@0 306
Chris@0 307 return $text;
Chris@0 308 }
Chris@0 309
Chris@0 310 /**
Chris@0 311 * Splits CJK (Chinese, Japanese, Korean) text into tokens.
Chris@0 312 *
Chris@0 313 * The Search module matches exact words, where a word is defined to be a
Chris@0 314 * sequence of characters delimited by spaces or punctuation. CJK languages are
Chris@0 315 * written in long strings of characters, though, not split up into words. So
Chris@0 316 * in order to allow search matching, we split up CJK text into tokens
Chris@0 317 * consisting of consecutive, overlapping sequences of characters whose length
Chris@0 318 * is equal to the 'minimum_word_size' variable. This tokenizing is only done
Chris@0 319 * if the 'overlap_cjk' variable is TRUE.
Chris@0 320 *
Chris@0 321 * @param array $matches
Chris@0 322 * This function is a callback for preg_replace_callback(), which is called
Chris@0 323 * from search_simplify(). So, $matches is an array of regular expression
Chris@0 324 * matches, which means that $matches[0] contains the matched text -- a
Chris@0 325 * string of CJK characters to tokenize.
Chris@0 326 *
Chris@0 327 * @return string
Chris@0 328 * Tokenized text, starting and ending with a space character.
Chris@0 329 */
Chris@0 330 function search_expand_cjk($matches) {
Chris@0 331 $min = \Drupal::config('search.settings')->get('index.minimum_word_size');
Chris@0 332 $str = $matches[0];
Chris@0 333 $length = Unicode::strlen($str);
Chris@0 334 // If the text is shorter than the minimum word size, don't tokenize it.
Chris@0 335 if ($length <= $min) {
Chris@0 336 return ' ' . $str . ' ';
Chris@0 337 }
Chris@0 338 $tokens = ' ';
Chris@0 339 // Build a FIFO queue of characters.
Chris@0 340 $chars = [];
Chris@0 341 for ($i = 0; $i < $length; $i++) {
Chris@0 342 // Add the next character off the beginning of the string to the queue.
Chris@0 343 $current = Unicode::substr($str, 0, 1);
Chris@0 344 $str = substr($str, strlen($current));
Chris@0 345 $chars[] = $current;
Chris@0 346 if ($i >= $min - 1) {
Chris@0 347 // Make a token of $min characters, and add it to the token string.
Chris@0 348 $tokens .= implode('', $chars) . ' ';
Chris@0 349 // Shift out the first character in the queue.
Chris@0 350 array_shift($chars);
Chris@0 351 }
Chris@0 352 }
Chris@0 353 return $tokens;
Chris@0 354 }
Chris@0 355
Chris@0 356 /**
Chris@0 357 * Simplifies and splits a string into words for indexing.
Chris@0 358 *
Chris@0 359 * @param string $text
Chris@0 360 * Text to process.
Chris@0 361 * @param string|null $langcode
Chris@0 362 * Language code for the language of $text, if known.
Chris@0 363 *
Chris@0 364 * @return array
Chris@0 365 * Array of words in the simplified, preprocessed text.
Chris@0 366 *
Chris@0 367 * @see search_simplify()
Chris@0 368 */
Chris@0 369 function search_index_split($text, $langcode = NULL) {
Chris@0 370 $last = &drupal_static(__FUNCTION__);
Chris@0 371 $lastsplit = &drupal_static(__FUNCTION__ . ':lastsplit');
Chris@0 372
Chris@0 373 if ($last == $text) {
Chris@0 374 return $lastsplit;
Chris@0 375 }
Chris@0 376 // Process words
Chris@0 377 $text = search_simplify($text, $langcode);
Chris@0 378 $words = explode(' ', $text);
Chris@0 379
Chris@0 380 // Save last keyword result
Chris@0 381 $last = $text;
Chris@0 382 $lastsplit = $words;
Chris@0 383
Chris@0 384 return $words;
Chris@0 385 }
Chris@0 386
Chris@0 387 /**
Chris@0 388 * Helper function for array_walk in search_index_split.
Chris@0 389 */
Chris@0 390 function _search_index_truncate(&$text) {
Chris@0 391 // Use a static array to avoid re-truncating text we've done before.
Chris@0 392 // The same words may often be passed in during excerpt generation.
Chris@0 393 static $truncated = [];
Chris@0 394 if (isset($truncated[$text])) {
Chris@0 395 $text = $truncated[$text];
Chris@0 396 return;
Chris@0 397 }
Chris@0 398
Chris@0 399 // If we didn't find it in the static array, perform the operation.
Chris@0 400 $original = $text;
Chris@0 401 if (is_numeric($text)) {
Chris@0 402 $text = ltrim($text, '0');
Chris@0 403 }
Chris@0 404 $text = Unicode::truncate($text, 50);
Chris@0 405 // Save it for the next time.
Chris@0 406 $truncated[$original] = $text;
Chris@0 407 }
Chris@0 408
Chris@0 409 /**
Chris@0 410 * Invokes hook_search_preprocess() to simplify text.
Chris@0 411 *
Chris@0 412 * @param string $text
Chris@0 413 * Text to preprocess, passed by reference and altered in place.
Chris@0 414 * @param string|null $langcode
Chris@0 415 * Language code for the language of $text, if known.
Chris@0 416 */
Chris@0 417 function search_invoke_preprocess(&$text, $langcode = NULL) {
Chris@0 418 foreach (\Drupal::moduleHandler()->getImplementations('search_preprocess') as $module) {
Chris@0 419 $text = \Drupal::moduleHandler()->invoke($module, 'search_preprocess', [$text, $langcode]);
Chris@0 420 }
Chris@0 421 }
Chris@0 422
Chris@0 423 /**
Chris@0 424 * Updates the full-text search index for a particular item.
Chris@0 425 *
Chris@0 426 * @param string $type
Chris@0 427 * The plugin ID or other machine-readable type of this item,
Chris@0 428 * which should be less than 64 bytes.
Chris@0 429 * @param int $sid
Chris@0 430 * An ID number identifying this particular item (e.g., node ID).
Chris@0 431 * @param string $langcode
Chris@0 432 * Language code for the language of the text being indexed.
Chris@0 433 * @param string $text
Chris@0 434 * The content of this item. Must be a piece of HTML or plain text.
Chris@0 435 *
Chris@0 436 * @ingroup search
Chris@0 437 */
Chris@0 438 function search_index($type, $sid, $langcode, $text) {
Chris@0 439 $minimum_word_size = \Drupal::config('search.settings')->get('index.minimum_word_size');
Chris@0 440
Chris@0 441 // Multipliers for scores of words inside certain HTML tags. The weights are
Chris@0 442 // stored in config so that modules can overwrite the default weights.
Chris@0 443 // Note: 'a' must be included for link ranking to work.
Chris@0 444 $tags = \Drupal::config('search.settings')->get('index.tag_weights');
Chris@0 445
Chris@0 446 // Strip off all ignored tags to speed up processing, but insert space before
Chris@0 447 // and after them to keep word boundaries.
Chris@0 448 $text = str_replace(['<', '>'], [' <', '> '], $text);
Chris@0 449 $text = strip_tags($text, '<' . implode('><', array_keys($tags)) . '>');
Chris@0 450
Chris@0 451 // Split HTML tags from plain text.
Chris@0 452 $split = preg_split('/\s*<([^>]+?)>\s*/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
Chris@0 453 // Note: PHP ensures the array consists of alternating delimiters and literals
Chris@0 454 // and begins and ends with a literal (inserting $null as required).
Chris@0 455
Chris@0 456 // Odd/even counter. Tag or no tag.
Chris@0 457 $tag = FALSE;
Chris@0 458 // Starting score per word.
Chris@0 459 $score = 1;
Chris@0 460 // Accumulator for cleaned up data.
Chris@0 461 $accum = ' ';
Chris@0 462 // Stack with open tags.
Chris@0 463 $tagstack = [];
Chris@0 464 // Counter for consecutive words.
Chris@0 465 $tagwords = 0;
Chris@0 466 // Focus state.
Chris@0 467 $focus = 1;
Chris@0 468
Chris@0 469 // Accumulator for words for index.
Chris@0 470 $scored_words = [];
Chris@0 471
Chris@0 472 foreach ($split as $value) {
Chris@0 473 if ($tag) {
Chris@0 474 // Increase or decrease score per word based on tag
Chris@0 475 list($tagname) = explode(' ', $value, 2);
Chris@0 476 $tagname = Unicode::strtolower($tagname);
Chris@0 477 // Closing or opening tag?
Chris@0 478 if ($tagname[0] == '/') {
Chris@0 479 $tagname = substr($tagname, 1);
Chris@0 480 // If we encounter unexpected tags, reset score to avoid incorrect boosting.
Chris@0 481 if (!count($tagstack) || $tagstack[0] != $tagname) {
Chris@0 482 $tagstack = [];
Chris@0 483 $score = 1;
Chris@0 484 }
Chris@0 485 else {
Chris@0 486 // Remove from tag stack and decrement score
Chris@0 487 $score = max(1, $score - $tags[array_shift($tagstack)]);
Chris@0 488 }
Chris@0 489 }
Chris@0 490 else {
Chris@0 491 if (isset($tagstack[0]) && $tagstack[0] == $tagname) {
Chris@0 492 // None of the tags we look for make sense when nested identically.
Chris@0 493 // If they are, it's probably broken HTML.
Chris@0 494 $tagstack = [];
Chris@0 495 $score = 1;
Chris@0 496 }
Chris@0 497 else {
Chris@0 498 // Add to open tag stack and increment score
Chris@0 499 array_unshift($tagstack, $tagname);
Chris@0 500 $score += $tags[$tagname];
Chris@0 501 }
Chris@0 502 }
Chris@0 503 // A tag change occurred, reset counter.
Chris@0 504 $tagwords = 0;
Chris@0 505 }
Chris@0 506 else {
Chris@0 507 // Note: use of PREG_SPLIT_DELIM_CAPTURE above will introduce empty values
Chris@0 508 if ($value != '') {
Chris@0 509 $words = search_index_split($value, $langcode);
Chris@0 510 foreach ($words as $word) {
Chris@0 511 // Add word to accumulator
Chris@0 512 $accum .= $word . ' ';
Chris@0 513 // Check wordlength
Chris@0 514 if (is_numeric($word) || Unicode::strlen($word) >= $minimum_word_size) {
Chris@0 515 if (!isset($scored_words[$word])) {
Chris@0 516 $scored_words[$word] = 0;
Chris@0 517 }
Chris@0 518 $scored_words[$word] += $score * $focus;
Chris@0 519 // Focus is a decaying value in terms of the amount of unique words up to this point.
Chris@0 520 // From 100 words and more, it decays, to e.g. 0.5 at 500 words and 0.3 at 1000 words.
Chris@0 521 $focus = min(1, .01 + 3.5 / (2 + count($scored_words) * .015));
Chris@0 522 }
Chris@0 523 $tagwords++;
Chris@0 524 // Too many words inside a single tag probably mean a tag was accidentally left open.
Chris@0 525 if (count($tagstack) && $tagwords >= 15) {
Chris@0 526 $tagstack = [];
Chris@0 527 $score = 1;
Chris@0 528 }
Chris@0 529 }
Chris@0 530 }
Chris@0 531 }
Chris@0 532 $tag = !$tag;
Chris@0 533 }
Chris@0 534
Chris@0 535 // Remove the item $sid from the search index, and invalidate the relevant
Chris@0 536 // cache tags.
Chris@0 537 search_index_clear($type, $sid, $langcode);
Chris@0 538
Chris@0 539 // Insert cleaned up data into dataset
Chris@0 540 db_insert('search_dataset')
Chris@0 541 ->fields([
Chris@0 542 'sid' => $sid,
Chris@0 543 'langcode' => $langcode,
Chris@0 544 'type' => $type,
Chris@0 545 'data' => $accum,
Chris@0 546 'reindex' => 0,
Chris@0 547 ])
Chris@0 548 ->execute();
Chris@0 549
Chris@0 550 // Insert results into search index
Chris@0 551 foreach ($scored_words as $word => $score) {
Chris@0 552 // If a word already exists in the database, its score gets increased
Chris@0 553 // appropriately. If not, we create a new record with the appropriate
Chris@0 554 // starting score.
Chris@0 555 db_merge('search_index')
Chris@0 556 ->keys([
Chris@0 557 'word' => $word,
Chris@0 558 'sid' => $sid,
Chris@0 559 'langcode' => $langcode,
Chris@0 560 'type' => $type,
Chris@0 561 ])
Chris@0 562 ->fields(['score' => $score])
Chris@0 563 ->expression('score', 'score + :score', [':score' => $score])
Chris@0 564 ->execute();
Chris@0 565 search_dirty($word);
Chris@0 566 }
Chris@0 567 }
Chris@0 568
Chris@0 569 /**
Chris@0 570 * Changes the timestamp on indexed items to 'now' to force reindexing.
Chris@0 571 *
Chris@0 572 * This function is meant for use by search page plugins, or for building a
Chris@0 573 * user interface that lets users mark all or parts of the search index for
Chris@0 574 * reindexing.
Chris@0 575 *
Chris@0 576 * @param string $type
Chris@0 577 * (optional) The plugin ID or other machine-readable type of this item. If
Chris@0 578 * omitted, the entire search index is marked for reindexing, and $sid and
Chris@0 579 * $langcode are ignored.
Chris@0 580 * @param int $sid
Chris@0 581 * (optional) An ID number identifying this particular item (e.g., node ID).
Chris@0 582 * If omitted, everything matching $type is marked, and $langcode is ignored.
Chris@0 583 * @param string $langcode
Chris@0 584 * (optional) The language code to clear. If omitted, everything matching
Chris@0 585 * $type and $sid is marked.
Chris@0 586 */
Chris@0 587 function search_mark_for_reindex($type = NULL, $sid = NULL, $langcode = NULL) {
Chris@0 588 $query = db_update('search_dataset')
Chris@0 589 ->fields(['reindex' => REQUEST_TIME])
Chris@0 590 // Only mark items that were not previously marked for reindex, so that
Chris@0 591 // marked items maintain their priority by request time.
Chris@0 592 ->condition('reindex', 0);
Chris@0 593
Chris@0 594 if ($type) {
Chris@0 595 $query->condition('type', $type);
Chris@0 596 if ($sid) {
Chris@0 597 $query->condition('sid', $sid);
Chris@0 598 if ($langcode) {
Chris@0 599 $query->condition('langcode', $langcode);
Chris@0 600 }
Chris@0 601 }
Chris@0 602 }
Chris@0 603
Chris@0 604 $query->execute();
Chris@0 605 }
Chris@0 606
Chris@0 607 /**
Chris@0 608 * @defgroup search Search interface
Chris@0 609 * @{
Chris@0 610 * The Drupal search interface manages a global search mechanism.
Chris@0 611 *
Chris@0 612 * Modules may plug into this system to provide searches of different types of
Chris@0 613 * data. Most of the system is handled by the Search module, so this must be
Chris@0 614 * enabled for all of the search features to work.
Chris@0 615 *
Chris@0 616 * There are two ways to interact with the search system:
Chris@0 617 * - Specifically for searching nodes, you can implement
Chris@0 618 * hook_node_update_index() and hook_node_search_result(). However, note that
Chris@0 619 * the search system already indexes all visible output of a node; i.e.,
Chris@0 620 * everything displayed normally during node viewing. This is
Chris@0 621 * usually sufficient. You should only use this mechanism if you want
Chris@0 622 * additional, non-visible data to be indexed.
Chris@0 623 * - Define a plugin implementing \Drupal\search\Plugin\SearchInterface and
Chris@0 624 * annotated as \Drupal\search\Annotation\SearchPlugin. This will create a
Chris@0 625 * search page type that users can use to set up one or more search pages.
Chris@0 626 * Each of these corresponds to a tab on the /search page, which can be
Chris@0 627 * used to perform searches. You will also need to implement the execute()
Chris@0 628 * method from the interface to perform the search. A base class is provided
Chris@0 629 * in \Drupal\search\Plugin\SearchPluginBase. For more information about
Chris@0 630 * plugins, see the @link plugin_api Plugin API topic. @endlink
Chris@0 631 *
Chris@0 632 * If your module needs to provide a more complicated search form, then you
Chris@0 633 * need to implement it yourself. In that case, you may wish to define it as a
Chris@0 634 * local task (tab) under the /search page (e.g. /search/mymodule) so that users
Chris@0 635 * can easily find it.
Chris@0 636 *
Chris@0 637 * @see plugin_api
Chris@0 638 * @see annotation
Chris@0 639 */
Chris@0 640
Chris@0 641 /**
Chris@0 642 * Returns snippets from a piece of text, with search keywords highlighted.
Chris@0 643 *
Chris@0 644 * Used for formatting search results. All HTML tags will be stripped from
Chris@0 645 * $text.
Chris@0 646 *
Chris@0 647 * @param string $keys
Chris@0 648 * A string containing a search query.
Chris@0 649 * @param string $text
Chris@0 650 * The text to extract fragments from.
Chris@0 651 * @param string|null $langcode
Chris@0 652 * Language code for the language of $text, if known.
Chris@0 653 *
Chris@0 654 * @return array
Chris@0 655 * A render array containing HTML for the excerpt.
Chris@0 656 */
Chris@0 657 function search_excerpt($keys, $text, $langcode = NULL) {
Chris@0 658 // We highlight around non-indexable or CJK characters.
Chris@0 659 $boundary_character = '[' . Unicode::PREG_CLASS_WORD_BOUNDARY . PREG_CLASS_CJK . ']';
Chris@0 660 $preceded_by_boundary = '(?<=' . $boundary_character . ')';
Chris@0 661 $followed_by_boundary = '(?=' . $boundary_character . ')';
Chris@0 662
Chris@0 663 // Extract positive keywords and phrases.
Chris@0 664 preg_match_all('/ ("([^"]+)"|(?!OR)([^" ]+))/', ' ' . $keys, $matches);
Chris@0 665 $keys = array_merge($matches[2], $matches[3]);
Chris@0 666
Chris@0 667 // Prepare text by stripping HTML tags and decoding HTML entities.
Chris@0 668 $text = strip_tags(str_replace(['<', '>'], [' <', '> '], $text));
Chris@0 669 $text = Html::decodeEntities($text);
Chris@0 670 $text_length = strlen($text);
Chris@0 671
Chris@0 672 // Make a list of unique keywords that are actually found in the text,
Chris@0 673 // which could be items in $keys or replacements that are equivalent through
Chris@0 674 // search_simplify().
Chris@0 675 $temp_keys = [];
Chris@0 676 foreach ($keys as $key) {
Chris@0 677 $key = _search_find_match_with_simplify($key, $text, $boundary_character, $langcode);
Chris@0 678 if (isset($key)) {
Chris@0 679 // Quote slashes so they can be used in regular expressions.
Chris@0 680 $temp_keys[] = preg_quote($key, '/');
Chris@0 681 }
Chris@0 682 }
Chris@0 683 // Several keywords could have simplified down to the same thing, so pick
Chris@0 684 // out the unique ones.
Chris@0 685 $keys = array_unique($temp_keys);
Chris@0 686
Chris@0 687 // Extract fragments of about 60 characters around keywords, bounded by word
Chris@0 688 // boundary characters. Try to reach 256 characters, using second occurrences
Chris@0 689 // if necessary.
Chris@0 690 $ranges = [];
Chris@0 691 $length = 0;
Chris@0 692 $look_start = [];
Chris@0 693 $remaining_keys = $keys;
Chris@0 694
Chris@0 695 while ($length < 256 && !empty($remaining_keys)) {
Chris@0 696 $found_keys = [];
Chris@0 697 foreach ($remaining_keys as $key) {
Chris@0 698 if ($length >= 256) {
Chris@0 699 break;
Chris@0 700 }
Chris@0 701
Chris@0 702 // Remember where we last found $key, in case we are coming through a
Chris@0 703 // second time.
Chris@0 704 if (!isset($look_start[$key])) {
Chris@0 705 $look_start[$key] = 0;
Chris@0 706 }
Chris@0 707
Chris@0 708 // See if we can find $key after where we found it the last time. Since
Chris@0 709 // we are requiring a match on a word boundary, make sure $text starts
Chris@0 710 // and ends with a space.
Chris@0 711 $matches = [];
Chris@0 712 if (preg_match('/' . $preceded_by_boundary . $key . $followed_by_boundary . '/iu', ' ' . $text . ' ', $matches, PREG_OFFSET_CAPTURE, $look_start[$key])) {
Chris@0 713 $found_position = $matches[0][1];
Chris@0 714 $look_start[$key] = $found_position + 1;
Chris@0 715 // Keep track of which keys we found this time, in case we need to
Chris@0 716 // pass through again to find more text.
Chris@0 717 $found_keys[] = $key;
Chris@0 718
Chris@0 719 // Locate a space before and after this match, leaving about 60
Chris@0 720 // characters of context on each end.
Chris@0 721 $before = strpos(' ' . $text, ' ', max(0, $found_position - 61));
Chris@0 722 if ($before !== FALSE && $before <= $found_position) {
Chris@0 723 if ($text_length > $found_position + 60) {
Chris@0 724 $after = strrpos(substr($text, 0, $found_position + 60), ' ', $found_position);
Chris@0 725 }
Chris@0 726 else {
Chris@0 727 $after = $text_length;
Chris@0 728 }
Chris@0 729 if ($after !== FALSE && $after > $found_position) {
Chris@0 730 // Account for the spaces we added.
Chris@0 731 $before = max($before - 1, 0);
Chris@0 732 if ($before < $after) {
Chris@0 733 // Save this range.
Chris@0 734 $ranges[$before] = $after;
Chris@0 735 $length += $after - $before;
Chris@0 736 }
Chris@0 737 }
Chris@0 738 }
Chris@0 739 }
Chris@0 740 }
Chris@0 741 // Next time through this loop, only look for keys we found this time,
Chris@0 742 // if any.
Chris@0 743 $remaining_keys = $found_keys;
Chris@0 744 }
Chris@0 745
Chris@0 746 if (empty($ranges)) {
Chris@0 747 // We didn't find any keyword matches, so just return the first part of the
Chris@0 748 // text. We also need to re-encode any HTML special characters that we
Chris@0 749 // entity-decoded above.
Chris@0 750 return [
Chris@0 751 '#plain_text' => Unicode::truncate($text, 256, TRUE, TRUE),
Chris@0 752 ];
Chris@0 753 }
Chris@0 754
Chris@0 755 // Sort the text ranges by starting position.
Chris@0 756 ksort($ranges);
Chris@0 757
Chris@0 758 // Collapse overlapping text ranges into one. The sorting makes it O(n).
Chris@0 759 $new_ranges = [];
Chris@0 760 $max_end = 0;
Chris@0 761 foreach ($ranges as $this_from => $this_to) {
Chris@0 762 $max_end = max($max_end, $this_to);
Chris@0 763 if (!isset($working_from)) {
Chris@0 764 // This is the first time through this loop: initialize.
Chris@0 765 $working_from = $this_from;
Chris@0 766 $working_to = $this_to;
Chris@0 767 continue;
Chris@0 768 }
Chris@0 769 if ($this_from <= $working_to) {
Chris@0 770 // The ranges overlap: combine them.
Chris@0 771 $working_to = max($working_to, $this_to);
Chris@0 772 }
Chris@0 773 else {
Chris@0 774 // The ranges do not overlap: save the working range and start a new one.
Chris@0 775 $new_ranges[$working_from] = $working_to;
Chris@0 776 $working_from = $this_from;
Chris@0 777 $working_to = $this_to;
Chris@0 778 }
Chris@0 779 }
Chris@0 780 // Save the remaining working range.
Chris@0 781 $new_ranges[$working_from] = $working_to;
Chris@0 782
Chris@0 783 // Fetch text within the combined ranges we found.
Chris@0 784 $out = [];
Chris@0 785 foreach ($new_ranges as $from => $to) {
Chris@0 786 $out[] = substr($text, $from, $to - $from);
Chris@0 787 }
Chris@0 788
Chris@0 789 // Combine the text chunks with "…" separators. The "…" needs to be
Chris@0 790 // translated. Let translators have the … separator text as one chunk.
Chris@0 791 $ellipses = explode('@excerpt', t('… @excerpt … @excerpt …'));
Chris@0 792 $text = (isset($new_ranges[0]) ? '' : $ellipses[0]) . implode($ellipses[1], $out) . (($max_end < strlen($text) - 1) ? $ellipses[2] : '');
Chris@0 793 $text = Html::escape($text);
Chris@0 794
Chris@0 795 // Highlight keywords. Must be done at once to prevent conflicts ('strong'
Chris@0 796 // and '<strong>').
Chris@0 797 $text = trim(preg_replace('/' . $preceded_by_boundary . '(?:' . implode('|', $keys) . ')' . $followed_by_boundary . '/iu', '<strong>\0</strong>', ' ' . $text . ' '));
Chris@0 798 return [
Chris@0 799 '#markup' => $text,
Chris@0 800 '#allowed_tags' => ['strong']
Chris@0 801 ];
Chris@0 802 }
Chris@0 803
Chris@0 804 /**
Chris@0 805 * @} End of "defgroup search".
Chris@0 806 */
Chris@0 807
Chris@0 808 /**
Chris@0 809 * Finds an appropriate keyword in text.
Chris@0 810 *
Chris@0 811 * @param string $key
Chris@0 812 * The keyword to find.
Chris@0 813 * @param string $text
Chris@0 814 * The text to search for the keyword.
Chris@0 815 * @param string $boundary
Chris@0 816 * Regular expression for the boundary character class (characters that
Chris@0 817 * indicate spaces between words).
Chris@0 818 * @param string|null $langcode
Chris@0 819 * Language code for the language of $text, if known.
Chris@0 820 *
Chris@0 821 * @return string|null
Chris@0 822 * A segment of $text that is between word boundary characters that either
Chris@0 823 * matches $key directly, or matches $key when both this text segment and
Chris@0 824 * $key are processed by search_simplify(). If a matching text segment is
Chris@0 825 * not located, NULL is returned.
Chris@0 826 */
Chris@0 827 function _search_find_match_with_simplify($key, $text, $boundary, $langcode = NULL) {
Chris@0 828 $preceded_by_boundary = '(?<=' . $boundary . ')';
Chris@0 829 $followed_by_boundary = '(?=' . $boundary . ')';
Chris@0 830
Chris@0 831 // See if $key appears as-is. When testing, make sure $text starts/ends with
Chris@0 832 // a space, because we require $key to be surrounded by word boundary
Chris@0 833 // characters.
Chris@0 834 $temp = trim($key);
Chris@0 835 if ($temp == '') {
Chris@0 836 return NULL;
Chris@0 837 }
Chris@0 838 if (preg_match('/' . $preceded_by_boundary . preg_quote($temp, '/') . $followed_by_boundary . '/iu', ' ' . $text . ' ')) {
Chris@0 839 return $temp;
Chris@0 840 }
Chris@0 841
Chris@0 842 // See if there is a match after lower-casing and removing diacritics in
Chris@0 843 // both, which should preserve the string length.
Chris@0 844 $new_text = Unicode::strtolower($text);
Chris@0 845 $new_text = \Drupal::service('transliteration')->removeDiacritics($new_text);
Chris@0 846 $new_key = Unicode::strtolower($temp);
Chris@0 847 $new_key = \Drupal::service('transliteration')->removeDiacritics($new_key);
Chris@0 848 if (preg_match('/' . $preceded_by_boundary . preg_quote($new_key, '/') . $followed_by_boundary . '/u', ' ' . $new_text . ' ')) {
Chris@0 849 $position = Unicode::strpos($new_text, $new_key);
Chris@0 850 return Unicode::substr($text, $position, Unicode::strlen($new_key));
Chris@0 851 }
Chris@0 852
Chris@0 853 // Run both text and key through search_simplify.
Chris@0 854 $simplified_key = trim(search_simplify($key, $langcode));
Chris@0 855 $simplified_text = trim(search_simplify($text, $langcode));
Chris@0 856 if ($simplified_key == '' || $simplified_text == '' || strpos($simplified_text, $simplified_key) === FALSE) {
Chris@0 857 // The simplified keyword and text do not match at all, or are empty.
Chris@0 858 return NULL;
Chris@0 859 }
Chris@0 860
Chris@0 861 // Split $text into words, keeping track of where the word boundaries are.
Chris@0 862 $words = preg_split('/' . $boundary . '+/u', $text, NULL, PREG_SPLIT_OFFSET_CAPTURE);
Chris@0 863 // Add an entry pointing to the end of the string, for the loop below.
Chris@0 864 $words[] = ['', strlen($text)];
Chris@0 865
Chris@0 866 // Using a binary search, find the earliest possible ending position in
Chris@0 867 // $text where it will still match the keyword after applying
Chris@0 868 // search_simplify().
Chris@0 869 $start_index = 0;
Chris@0 870 $start_pos = $words[$start_index][1];
Chris@0 871 $min_end_index = 1;
Chris@0 872 $max_end_index = count($words) - 1;
Chris@0 873 while ($max_end_index > $min_end_index) {
Chris@0 874 // Check the index half way between min and max. See if we ended there,
Chris@0 875 // if we would still have a match.
Chris@0 876 $proposed_end_index = floor(($max_end_index + $min_end_index) / 2);
Chris@0 877 $proposed_end_pos = $words[$proposed_end_index][1];
Chris@0 878 // Since the split was done with preg_split(), the positions are byte counts
Chris@0 879 // not character counts, so use substr() not Unicode::substr() here.
Chris@0 880 $trial_text = trim(search_simplify(substr($text, $start_pos, $proposed_end_pos - $start_pos), $langcode));
Chris@0 881 if (strpos($trial_text, $simplified_key) !== FALSE) {
Chris@0 882 // The proposed endpoint is fine, text still matches.
Chris@0 883 $max_end_index = $proposed_end_index;
Chris@0 884 }
Chris@0 885 else {
Chris@0 886 // The proposed endpoint index is too early, so the earliest possible
Chris@0 887 // OK ending point would be the next index.
Chris@0 888 $min_end_index = $proposed_end_index + 1;
Chris@0 889 }
Chris@0 890 }
Chris@0 891
Chris@0 892 // Now do the same for the starting position: using a binary search, find the
Chris@0 893 // latest possible starting position in $text where it will still match the
Chris@0 894 // keyword after applying search_simplify().
Chris@0 895 $end_index = $min_end_index;
Chris@0 896 $end_pos = $words[$end_index][1];
Chris@0 897 $min_start_index = 0;
Chris@0 898 $max_start_index = $end_index - 1;
Chris@0 899 while ($max_start_index > $min_start_index) {
Chris@0 900 // Check the index half way between min and max. See if we started there,
Chris@0 901 // if we would still have a match.
Chris@0 902 $proposed_start_index = ceil(($max_start_index + $min_start_index) / 2);
Chris@0 903 $proposed_start_pos = $words[$proposed_start_index][1];
Chris@0 904 // Since the split was done with preg_split(), the positions are byte counts
Chris@0 905 // not character counts, so use substr() not Unicode::substr() here.
Chris@0 906 $trial_text = trim(search_simplify(substr($text, $proposed_start_pos, $end_pos - $proposed_start_pos), $langcode));
Chris@0 907 if (strpos($trial_text, $simplified_key) !== FALSE) {
Chris@0 908 // The proposed start point is fine, text still matches.
Chris@0 909 $min_start_index = $proposed_start_index;
Chris@0 910 }
Chris@0 911 else {
Chris@0 912 // The proposed start point index is too late, so the latest possible
Chris@0 913 // OK starting point would be the previous index.
Chris@0 914 $max_start_index = $proposed_start_index - 1;
Chris@0 915 }
Chris@0 916 }
Chris@0 917 $start_index = $max_start_index;
Chris@0 918
Chris@0 919 // Return the matching text. We need to use substr() here and not the
Chris@0 920 // Unicode::substr() function, because the indices in $words came from
Chris@0 921 // preg_split(), so they are Unicode-safe byte positions, not character
Chris@0 922 // positions.
Chris@0 923 return trim(substr($text, $words[$start_index][1], $words[$end_index][1] - $words[$start_index][1]));
Chris@0 924 }
Chris@0 925
Chris@0 926 /**
Chris@0 927 * Implements hook_form_FORM_ID_alter() for the search_block_form form.
Chris@0 928 *
Chris@0 929 * Since the exposed form is a GET form, we don't want it to send the form
Chris@0 930 * tokens. However, you cannot make this happen in the form builder function
Chris@0 931 * itself, because the tokens are added to the form after the builder function
Chris@0 932 * is called. So, we have to do it in a form_alter.
Chris@0 933 *
Chris@0 934 * @see \Drupal\search\Form\SearchBlockForm
Chris@0 935 */
Chris@0 936 function search_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
Chris@0 937 $form['form_build_id']['#access'] = FALSE;
Chris@0 938 $form['form_token']['#access'] = FALSE;
Chris@0 939 $form['form_id']['#access'] = FALSE;
Chris@0 940 }