search.module 40 KB

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