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