annotate core/modules/search/search.module @ 19:fa3358dc1485 tip

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