1<?php
2
3/**
4 * @file
5 * Enables site-wide keyword searching.
6 */
7
8use Drupal\Component\Utility\Html;
9use Drupal\Component\Utility\Unicode;
10use Drupal\Core\Form\FormStateInterface;
11use Drupal\Core\Routing\RouteMatchInterface;
12use Drupal\Core\Url;
13
14/**
15 * Matches all 'N' Unicode character classes (numbers)
16 */
17define('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 */
31define('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 */
63define('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 */
72function 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' => Url::fromRoute('entity.search_page.collection')->toString(), ':search-url' => Url::fromRoute('search.view')->toString()]) . '</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' => Url::fromRoute('system.cron_settings')->toString(), ':search-settings' => Url::fromRoute('entity.search_page.collection')->toString()]) . '</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' => Url::fromRoute('entity.search_page.collection')->toString()]) . '</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')) ? Url::fromRoute('block.admin_display')->toString() : '#', ':search_permission' => Url::fromRoute('user.admin_permissions', [], ['fragment' => 'module-search'])->toString()]) . '</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' => 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>';
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 */
99function 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_theme_suggestions_HOOK().
110 */
111function search_theme_suggestions_search_result(array $variables) {
112  return ['search_result__' . $variables['plugin_id']];
113}
114
115/**
116 * Implements hook_preprocess_HOOK() for block templates.
117 */
118function search_preprocess_block(&$variables) {
119  if ($variables['plugin_id'] == 'search_form_block') {
120    $variables['attributes']['role'] = 'search';
121  }
122}
123
124/**
125 * Clears either a part of, or the entire search index.
126 *
127 * This function is meant for use by search page plugins, or for building a
128 * user interface that lets users clear all or parts of the search index.
129 *
130 * @param string|null $type
131 *   (optional) The plugin ID or other machine-readable type for the items to
132 *   remove from the search index. If omitted, $sid and $langcode are ignored
133 *   and the entire search index is cleared.
134 * @param int|array|null $sid
135 *   (optional) The ID or array of IDs of the items to remove from the search
136 *   index. If omitted, all items matching $type are cleared, and $langcode
137 *   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 * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
143 *   \Drupal\search\SearchIndex::clear() instead.
144 *
145 * @see https://www.drupal.org/node/3075696
146 */
147function search_index_clear($type = NULL, $sid = NULL, $langcode = NULL) {
148  @trigger_error("search_index_clear() is deprecated in drupal:8.8.0 and is removed in drupal:9.0.0. Use \Drupal\search\SearchIndex::clear() instead. See https://www.drupal.org/node/3075696", E_USER_DEPRECATED);
149  \Drupal::service('search.index')->clear($type, $sid, $langcode);
150}
151
152/**
153 * Marks a word as "dirty" (changed), or retrieves the list of dirty words.
154 *
155 * This is used during indexing (cron). Words that are dirty have outdated
156 * total counts in the search_total table, and need to be recounted.
157 *
158 * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use custom
159 *   implementation of \Drupal\search\SearchIndexInterface instead.
160 *
161 * @see https://www.drupal.org/node/3075696
162 */
163function search_dirty($word = NULL) {
164  @trigger_error("search_dirty() is deprecated in drupal:8.8.0 and is removed in drupal:9.0.0. Use custom implementation of \Drupal\search\SearchIndexInterface instead. See https://www.drupal.org/node/3075696", E_USER_DEPRECATED);
165  // Keep return result type for backward compatibility.
166  if ($word === NULL) {
167    return [];
168  }
169}
170
171/**
172 * Implements hook_cron().
173 *
174 * Fires updateIndex() in the plugins for all indexable active search pages,
175 * and cleans up dirty words.
176 */
177function search_cron() {
178  /** @var $search_page_repository \Drupal\search\SearchPageRepositoryInterface */
179  $search_page_repository = \Drupal::service('search.search_page_repository');
180  foreach ($search_page_repository->getIndexableSearchPages() as $entity) {
181    $entity->getPlugin()->updateIndex();
182  }
183}
184
185/**
186 * Updates the {search_total} database table.
187 *
188 * This function is called on shutdown to ensure that {search_total} is always
189 * up to date (even if cron times out or otherwise fails).
190 *
191 * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use custom
192 *   implementation of \Drupal\search\SearchIndexInterface instead.
193 *
194 * @see https://www.drupal.org/node/3075696
195 */
196function search_update_totals() {
197  @trigger_error("search_update_totals() is deprecated in drupal:8.8.0 and is removed in drupal:9.0.0. Use custom implementation of \Drupal\search\SearchIndexInterface instead. See https://www.drupal.org/node/3075696", E_USER_DEPRECATED);
198}
199
200/**
201 * Simplifies and preprocesses text for searching.
202 *
203 * Processing steps:
204 * - Entities are decoded.
205 * - Text is lower-cased and diacritics (accents) are removed.
206 * - hook_search_preprocess() is invoked.
207 * - CJK (Chinese, Japanese, Korean) characters are processed, depending on
208 *   the search settings.
209 * - Punctuation is processed (removed or replaced with spaces, depending on
210 *   where it is; see code for details).
211 * - Words are truncated to 50 characters maximum.
212 *
213 * @param string $text
214 *   Text to simplify.
215 * @param string|null $langcode
216 *   Language code for the language of $text, if known.
217 *
218 * @return string
219 *   Simplified and processed text.
220 *
221 * @see hook_search_preprocess()
222 */
223function search_simplify($text, $langcode = NULL) {
224  // Decode entities to UTF-8
225  $text = Html::decodeEntities($text);
226
227  // Lowercase
228  $text = mb_strtolower($text);
229
230  // Remove diacritics.
231  $text = \Drupal::service('transliteration')->removeDiacritics($text);
232
233  // Call an external processor for word handling.
234  search_invoke_preprocess($text, $langcode);
235
236  // Simple CJK handling
237  if (\Drupal::config('search.settings')->get('index.overlap_cjk')) {
238    $text = preg_replace_callback('/[' . PREG_CLASS_CJK . ']+/u', 'search_expand_cjk', $text);
239  }
240
241  // To improve searching for numerical data such as dates, IP addresses
242  // or version numbers, we consider a group of numerical characters
243  // separated only by punctuation characters to be one piece.
244  // This also means that searching for e.g. '20/03/1984' also returns
245  // results with '20-03-1984' in them.
246  // Readable regexp: ([number]+)[punctuation]+(?=[number])
247  $text = preg_replace('/([' . PREG_CLASS_NUMBERS . ']+)[' . PREG_CLASS_PUNCTUATION . ']+(?=[' . PREG_CLASS_NUMBERS . '])/u', '\1', $text);
248
249  // Multiple dot and dash groups are word boundaries and replaced with space.
250  // No need to use the unicode modifier here because 0-127 ASCII characters
251  // can't match higher UTF-8 characters as the leftmost bit of those are 1.
252  $text = preg_replace('/[.-]{2,}/', ' ', $text);
253
254  // The dot, underscore and dash are simply removed. This allows meaningful
255  // search behavior with acronyms and URLs. See unicode note directly above.
256  $text = preg_replace('/[._-]+/', '', $text);
257
258  // With the exception of the rules above, we consider all punctuation,
259  // marks, spacers, etc, to be a word boundary.
260  $text = preg_replace('/[' . Unicode::PREG_CLASS_WORD_BOUNDARY . ']+/u', ' ', $text);
261
262  // Truncate everything to 50 characters.
263  $words = explode(' ', $text);
264  array_walk($words, '_search_index_truncate');
265  $text = implode(' ', $words);
266
267  return $text;
268}
269
270/**
271 * Splits CJK (Chinese, Japanese, Korean) text into tokens.
272 *
273 * The Search module matches exact words, where a word is defined to be a
274 * sequence of characters delimited by spaces or punctuation. CJK languages are
275 * written in long strings of characters, though, not split up into words. So
276 * in order to allow search matching, we split up CJK text into tokens
277 * consisting of consecutive, overlapping sequences of characters whose length
278 * is equal to the 'minimum_word_size' variable. This tokenizing is only done
279 * if the 'overlap_cjk' variable is TRUE.
280 *
281 * @param array $matches
282 *   This function is a callback for preg_replace_callback(), which is called
283 *   from search_simplify(). So, $matches is an array of regular expression
284 *   matches, which means that $matches[0] contains the matched text -- a
285 *   string of CJK characters to tokenize.
286 *
287 * @return string
288 *   Tokenized text, starting and ending with a space character.
289 */
290function search_expand_cjk($matches) {
291  $min = \Drupal::config('search.settings')->get('index.minimum_word_size');
292  $str = $matches[0];
293  $length = mb_strlen($str);
294  // If the text is shorter than the minimum word size, don't tokenize it.
295  if ($length <= $min) {
296    return ' ' . $str . ' ';
297  }
298  $tokens = ' ';
299  // Build a FIFO queue of characters.
300  $chars = [];
301  for ($i = 0; $i < $length; $i++) {
302    // Add the next character off the beginning of the string to the queue.
303    $current = mb_substr($str, 0, 1);
304    $str = substr($str, strlen($current));
305    $chars[] = $current;
306    if ($i >= $min - 1) {
307      // Make a token of $min characters, and add it to the token string.
308      $tokens .= implode('', $chars) . ' ';
309      // Shift out the first character in the queue.
310      array_shift($chars);
311    }
312  }
313  return $tokens;
314}
315
316/**
317 * Simplifies and splits a string into words for indexing.
318 *
319 * @param string $text
320 *   Text to process.
321 * @param string|null $langcode
322 *   Language code for the language of $text, if known.
323 *
324 * @return array
325 *   Array of words in the simplified, preprocessed text.
326 *
327 * @see search_simplify()
328 */
329function search_index_split($text, $langcode = NULL) {
330  $last = &drupal_static(__FUNCTION__);
331  $lastsplit = &drupal_static(__FUNCTION__ . ':lastsplit');
332
333  if ($last == $text) {
334    return $lastsplit;
335  }
336  // Process words
337  $text = search_simplify($text, $langcode);
338  $words = explode(' ', $text);
339
340  // Save last keyword result
341  $last = $text;
342  $lastsplit = $words;
343
344  return $words;
345}
346
347/**
348 * Helper function for array_walk in search_index_split.
349 */
350function _search_index_truncate(&$text) {
351  // Use a static array to avoid re-truncating text we've done before.
352  // The same words may often be passed in during excerpt generation.
353  static $truncated = [];
354  if (isset($truncated[$text])) {
355    $text = $truncated[$text];
356    return;
357  }
358
359  // If we didn't find it in the static array, perform the operation.
360  $original = $text;
361  if (is_numeric($text)) {
362    $text = ltrim($text, '0');
363  }
364  $text = Unicode::truncate($text, 50);
365  // Save it for the next time.
366  $truncated[$original] = $text;
367}
368
369/**
370 * Invokes hook_search_preprocess() to simplify text.
371 *
372 * @param string $text
373 *   Text to preprocess, passed by reference and altered in place.
374 * @param string|null $langcode
375 *   Language code for the language of $text, if known.
376 */
377function search_invoke_preprocess(&$text, $langcode = NULL) {
378  foreach (\Drupal::moduleHandler()->getImplementations('search_preprocess') as $module) {
379    $text = \Drupal::moduleHandler()->invoke($module, 'search_preprocess', [$text, $langcode]);
380  }
381}
382
383/**
384 * Updates the full-text search index for a particular item.
385 *
386 * @param string $type
387 *   The plugin ID or other machine-readable type of this item,
388 *   which should be less than 64 bytes.
389 * @param int $sid
390 *   An ID number identifying this particular item (e.g., node ID).
391 * @param string $langcode
392 *   Language code for the language of the text being indexed.
393 * @param string $text
394 *   The content of this item. Must be a piece of HTML or plain text.
395 *
396 * @ingroup search
397 *
398 * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
399 *   \Drupal\search\SearchIndex::index() instead.
400 *
401 * @see https://www.drupal.org/node/3075696
402 */
403function search_index($type, $sid, $langcode, $text) {
404  @trigger_error("search_index() is deprecated in drupal:8.8.0 and is removed in drupal:9.0.0. Use \Drupal\search\SearchIndex::index() instead. See https://www.drupal.org/node/3075696", E_USER_DEPRECATED);
405  \Drupal::service('search.index')->index($type, $sid, $langcode, $text);
406}
407
408/**
409 * Changes the timestamp on indexed items to 'now' to force reindexing.
410 *
411 * This function is meant for use by search page plugins, or for building a
412 * user interface that lets users mark all or parts of the search index for
413 * reindexing.
414 *
415 * @param string $type
416 *   (optional) The plugin ID or other machine-readable type of this item. If
417 *   omitted, the entire search index is marked for reindexing, and $sid and
418 *   $langcode are ignored.
419 * @param int $sid
420 *   (optional) An ID number identifying this particular item (e.g., node ID).
421 *   If omitted, everything matching $type is marked, and $langcode is ignored.
422 * @param string $langcode
423 *   (optional) The language code to clear. If omitted, everything matching
424 *   $type and $sid is marked.
425 *
426 * @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
427 *   \Drupal\search\SearchIndex::markForReindex() instead.
428 *
429 * @see https://www.drupal.org/node/3075696
430 */
431function search_mark_for_reindex($type = NULL, $sid = NULL, $langcode = NULL) {
432  @trigger_error("search_mark_for_reindex() is deprecated in drupal:8.8.0 and is removed in drupal:9.0.0. Use \Drupal\search\SearchIndex::markForReindex() instead. See https://www.drupal.org/node/3075696", E_USER_DEPRECATED);
433  \Drupal::service('search.index')->markForReindex($type, $sid, $langcode);
434}
435
436/**
437 * @defgroup search Search interface
438 * @{
439 * The Drupal search interface manages a global search mechanism.
440 *
441 * Modules may plug into this system to provide searches of different types of
442 * data. Most of the system is handled by the Search module, so this must be
443 * enabled for all of the search features to work.
444 *
445 * There are two ways to interact with the search system:
446 * - Specifically for searching nodes, you can implement
447 *   hook_node_update_index() and hook_node_search_result(). However, note that
448 *   the search system already indexes all visible output of a node; i.e.,
449 *   everything displayed normally during node viewing. This is
450 *   usually sufficient. You should only use this mechanism if you want
451 *   additional, non-visible data to be indexed.
452 * - Define a plugin implementing \Drupal\search\Plugin\SearchInterface and
453 *   annotated as \Drupal\search\Annotation\SearchPlugin. This will create a
454 *   search page type that users can use to set up one or more search pages.
455 *   Each of these corresponds to a tab on the /search page, which can be
456 *   used to perform searches. You will also need to implement the execute()
457 *   method from the interface to perform the search. A base class is provided
458 *   in \Drupal\search\Plugin\SearchPluginBase. For more information about
459 *   plugins, see the @link plugin_api Plugin API topic. @endlink
460 *
461 * If your module needs to provide a more complicated search form, then you
462 * need to implement it yourself. In that case, you may wish to define it as a
463 * local task (tab) under the /search page (e.g. /search/mymodule) so that users
464 * can easily find it.
465 *
466 * @see plugin_api
467 * @see annotation
468 */
469
470/**
471 * Returns snippets from a piece of text, with search keywords highlighted.
472 *
473 * Used for formatting search results. All HTML tags will be stripped from
474 * $text.
475 *
476 * @param string $keys
477 *   A string containing a search query.
478 * @param string $text
479 *   The text to extract fragments from.
480 * @param string|null $langcode
481 *   Language code for the language of $text, if known.
482 *
483 * @return array
484 *   A render array containing HTML for the excerpt.
485 */
486function search_excerpt($keys, $text, $langcode = NULL) {
487  // We highlight around non-indexable or CJK characters.
488  $boundary_character = '[' . Unicode::PREG_CLASS_WORD_BOUNDARY . PREG_CLASS_CJK . ']';
489  $preceded_by_boundary = '(?<=' . $boundary_character . ')';
490  $followed_by_boundary = '(?=' . $boundary_character . ')';
491
492  // Extract positive keywords and phrases.
493  preg_match_all('/ ("([^"]+)"|(?!OR)([^" ]+))/', ' ' . $keys, $matches);
494  $keys = array_merge($matches[2], $matches[3]);
495
496  // Prepare text by stripping HTML tags and decoding HTML entities.
497  $text = strip_tags(str_replace(['<', '>'], [' <', '> '], $text));
498  $text = Html::decodeEntities($text);
499  $text_length = strlen($text);
500
501  // Make a list of unique keywords that are actually found in the text,
502  // which could be items in $keys or replacements that are equivalent through
503  // search_simplify().
504  $temp_keys = [];
505  foreach ($keys as $key) {
506    $key = _search_find_match_with_simplify($key, $text, $boundary_character, $langcode);
507    if (isset($key)) {
508      // Quote slashes so they can be used in regular expressions.
509      $temp_keys[] = preg_quote($key, '/');
510    }
511  }
512  // Several keywords could have simplified down to the same thing, so pick
513  // out the unique ones.
514  $keys = array_unique($temp_keys);
515
516  // Extract fragments of about 60 characters around keywords, bounded by word
517  // boundary characters. Try to reach 256 characters, using second occurrences
518  // if necessary.
519  $ranges = [];
520  $length = 0;
521  $look_start = [];
522  $remaining_keys = $keys;
523
524  while ($length < 256 && !empty($remaining_keys)) {
525    $found_keys = [];
526    foreach ($remaining_keys as $key) {
527      if ($length >= 256) {
528        break;
529      }
530
531      // Remember where we last found $key, in case we are coming through a
532      // second time.
533      if (!isset($look_start[$key])) {
534        $look_start[$key] = 0;
535      }
536
537      // See if we can find $key after where we found it the last time. Since
538      // we are requiring a match on a word boundary, make sure $text starts
539      // and ends with a space.
540      $matches = [];
541      if (preg_match('/' . $preceded_by_boundary . $key . $followed_by_boundary . '/iu', ' ' . $text . ' ', $matches, PREG_OFFSET_CAPTURE, $look_start[$key])) {
542        $found_position = $matches[0][1];
543        $look_start[$key] = $found_position + 1;
544        // Keep track of which keys we found this time, in case we need to
545        // pass through again to find more text.
546        $found_keys[] = $key;
547
548        // Locate a space before and after this match, leaving about 60
549        // characters of context on each end.
550        $before = strpos(' ' . $text, ' ', max(0, $found_position - 61));
551        if ($before !== FALSE && $before <= $found_position) {
552          if ($text_length > $found_position + 60) {
553            $after = strrpos(substr($text, 0, $found_position + 60), ' ', $found_position);
554          }
555          else {
556            $after = $text_length;
557          }
558          if ($after !== FALSE && $after > $found_position) {
559            // Account for the spaces we added.
560            $before = max($before - 1, 0);
561            if ($before < $after) {
562              // Save this range.
563              $ranges[$before] = $after;
564              $length += $after - $before;
565            }
566          }
567        }
568      }
569    }
570    // Next time through this loop, only look for keys we found this time,
571    // if any.
572    $remaining_keys = $found_keys;
573  }
574
575  if (empty($ranges)) {
576    // We didn't find any keyword matches, so just return the first part of the
577    // text. We also need to re-encode any HTML special characters that we
578    // entity-decoded above.
579    return [
580      '#plain_text' => Unicode::truncate($text, 256, TRUE, TRUE),
581    ];
582  }
583
584  // Sort the text ranges by starting position.
585  ksort($ranges);
586
587  // Collapse overlapping text ranges into one. The sorting makes it O(n).
588  $new_ranges = [];
589  $max_end = 0;
590  foreach ($ranges as $this_from => $this_to) {
591    $max_end = max($max_end, $this_to);
592    if (!isset($working_from)) {
593      // This is the first time through this loop: initialize.
594      $working_from = $this_from;
595      $working_to = $this_to;
596      continue;
597    }
598    if ($this_from <= $working_to) {
599      // The ranges overlap: combine them.
600      $working_to = max($working_to, $this_to);
601    }
602    else {
603      // The ranges do not overlap: save the working range and start a new one.
604      $new_ranges[$working_from] = $working_to;
605      $working_from = $this_from;
606      $working_to = $this_to;
607    }
608  }
609  // Save the remaining working range.
610  $new_ranges[$working_from] = $working_to;
611
612  // Fetch text within the combined ranges we found.
613  $out = [];
614  foreach ($new_ranges as $from => $to) {
615    $out[] = substr($text, $from, $to - $from);
616  }
617
618  // Combine the text chunks with "…" separators. The "…" needs to be
619  // translated. Let translators have the … separator text as one chunk.
620  $ellipses = explode('@excerpt', t('… @excerpt … @excerpt …'));
621  $text = (isset($new_ranges[0]) ? '' : $ellipses[0]) . implode($ellipses[1], $out) . (($max_end < strlen($text) - 1) ? $ellipses[2] : '');
622  $text = Html::escape($text);
623
624  // Highlight keywords. Must be done at once to prevent conflicts ('strong'
625  // and '<strong>').
626  $text = trim(preg_replace('/' . $preceded_by_boundary . '(?:' . implode('|', $keys) . ')' . $followed_by_boundary . '/iu', '<strong>\0</strong>', ' ' . $text . ' '));
627  return [
628    '#markup' => $text,
629    '#allowed_tags' => ['strong'],
630  ];
631}
632
633/**
634 * @} End of "defgroup search".
635 */
636
637/**
638 * Finds an appropriate keyword in text.
639 *
640 * @param string $key
641 *   The keyword to find.
642 * @param string $text
643 *   The text to search for the keyword.
644 * @param string $boundary
645 *   Regular expression for the boundary character class (characters that
646 *   indicate spaces between words).
647 * @param string|null $langcode
648 *   Language code for the language of $text, if known.
649 *
650 * @return string|null
651 *   A segment of $text that is between word boundary characters that either
652 *   matches $key directly, or matches $key when both this text segment and
653 *   $key are processed by search_simplify(). If a matching text segment is
654 *   not located, NULL is returned.
655 */
656function _search_find_match_with_simplify($key, $text, $boundary, $langcode = NULL) {
657  $preceded_by_boundary = '(?<=' . $boundary . ')';
658  $followed_by_boundary = '(?=' . $boundary . ')';
659
660  // See if $key appears as-is. When testing, make sure $text starts/ends with
661  // a space, because we require $key to be surrounded by word boundary
662  // characters.
663  $temp = trim($key);
664  if ($temp == '') {
665    return NULL;
666  }
667  if (preg_match('/' . $preceded_by_boundary . preg_quote($temp, '/') . $followed_by_boundary . '/iu', ' ' . $text . ' ')) {
668    return $temp;
669  }
670
671  // See if there is a match after lower-casing and removing diacritics in
672  // both, which should preserve the string length.
673  $new_text = mb_strtolower($text);
674  $new_text = \Drupal::service('transliteration')->removeDiacritics($new_text);
675  $new_key = mb_strtolower($temp);
676  $new_key = \Drupal::service('transliteration')->removeDiacritics($new_key);
677  if (preg_match('/' . $preceded_by_boundary . preg_quote($new_key, '/') . $followed_by_boundary . '/u', ' ' . $new_text . ' ')) {
678    $position = mb_strpos($new_text, $new_key);
679    return mb_substr($text, $position, mb_strlen($new_key));
680  }
681
682  // Run both text and key through search_simplify.
683  $simplified_key = trim(search_simplify($key, $langcode));
684  $simplified_text = trim(search_simplify($text, $langcode));
685  if ($simplified_key == '' || $simplified_text == '' || strpos($simplified_text, $simplified_key) === FALSE) {
686    // The simplified keyword and text do not match at all, or are empty.
687    return NULL;
688  }
689
690  // Split $text into words, keeping track of where the word boundaries are.
691  $words = preg_split('/' . $boundary . '+/u', $text, NULL, PREG_SPLIT_OFFSET_CAPTURE);
692  // Add an entry pointing to the end of the string, for the loop below.
693  $words[] = ['', strlen($text)];
694
695  // Using a binary search, find the earliest possible ending position in
696  // $text where it will still match the keyword after applying
697  // search_simplify().
698  $start_index = 0;
699  $start_pos = $words[$start_index][1];
700  $min_end_index = 1;
701  $max_end_index = count($words) - 1;
702  while ($max_end_index > $min_end_index) {
703    // Check the index half way between min and max. See if we ended there,
704    // if we would still have a match.
705    $proposed_end_index = floor(($max_end_index + $min_end_index) / 2);
706    $proposed_end_pos = $words[$proposed_end_index][1];
707    // Since the split was done with preg_split(), the positions are byte counts
708    // not character counts, so use substr() not mb_substr() here.
709    $trial_text = trim(search_simplify(substr($text, $start_pos, $proposed_end_pos - $start_pos), $langcode));
710    if (strpos($trial_text, $simplified_key) !== FALSE) {
711      // The proposed endpoint is fine, text still matches.
712      $max_end_index = $proposed_end_index;
713    }
714    else {
715      // The proposed endpoint index is too early, so the earliest possible
716      // OK ending point would be the next index.
717      $min_end_index = $proposed_end_index + 1;
718    }
719  }
720
721  // Now do the same for the starting position: using a binary search, find the
722  // latest possible starting position in $text where it will still match the
723  // keyword after applying search_simplify().
724  $end_index = $min_end_index;
725  $end_pos = $words[$end_index][1];
726  $min_start_index = 0;
727  $max_start_index = $end_index - 1;
728  while ($max_start_index > $min_start_index) {
729    // Check the index half way between min and max. See if we started there,
730    // if we would still have a match.
731    $proposed_start_index = ceil(($max_start_index + $min_start_index) / 2);
732    $proposed_start_pos = $words[$proposed_start_index][1];
733    // Since the split was done with preg_split(), the positions are byte counts
734    // not character counts, so use substr() not mb_substr() here.
735    $trial_text = trim(search_simplify(substr($text, $proposed_start_pos, $end_pos - $proposed_start_pos), $langcode));
736    if (strpos($trial_text, $simplified_key) !== FALSE) {
737      // The proposed start point is fine, text still matches.
738      $min_start_index = $proposed_start_index;
739    }
740    else {
741      // The proposed start point index is too late, so the latest possible
742      // OK starting point would be the previous index.
743      $max_start_index = $proposed_start_index - 1;
744    }
745  }
746  $start_index = $max_start_index;
747
748  // Return the matching text. We need to use substr() here and not the
749  // mb_substr() function, because the indices in $words came from preg_split(),
750  // so they are Unicode-safe byte positions, not character positions.
751  return trim(substr($text, $words[$start_index][1], $words[$end_index][1] - $words[$start_index][1]));
752}
753
754/**
755 * Implements hook_form_FORM_ID_alter() for the search_block_form form.
756 *
757 * Since the exposed form is a GET form, we don't want it to send the form
758 * tokens. However, you cannot make this happen in the form builder function
759 * itself, because the tokens are added to the form after the builder function
760 * is called. So, we have to do it in a form_alter.
761 *
762 * @see \Drupal\search\Form\SearchBlockForm
763 */
764function search_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
765  $form['form_build_id']['#access'] = FALSE;
766  $form['form_token']['#access'] = FALSE;
767  $form['form_id']['#access'] = FALSE;
768}
769