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