search.module

  1. 7.x drupal/modules/search/search.module
  2. 5.x drupal/modules/search/search.module
  3. 6.x drupal/modules/search/search.module
  4. 8.x drupal/core/modules/search/search.module

Enables site-wide keyword searching.

Functions

Namesort descending Description
search_cron Implements hook_cron().
search_dirty Marks a word as "dirty" (changed), or retrieves the list of dirty words.
search_excerpt Returns snippets from a piece of text, with search keywords highlighted.
search_expand_cjk Splits CJK (Chinese, Japanese, Korean) text into tokens.
search_form_search_block_form_alter Implements hook_form_FORM_ID_alter() for the search_block_form form.
search_help Implements hook_help().
search_index Updates the full-text search index for a particular item.
search_index_split Simplifies and splits a string into tokens for indexing.
search_invoke_preprocess Invokes hook_search_preprocess() in modules.
search_mark_for_reindex Changes the timestamp on an indexed item to 'now' to force reindexing.
search_module_preinstall Implements hook_module_preinstall().
search_permission Implements hook_permission().
search_preprocess_block Implements hook_preprocess_HOOK() for block templates.
search_reindex Clears either a part of, or the entire search index.
search_simplify Simplifies a string according to indexing rules.
search_theme Implements hook_theme().
search_update_totals Updates the {search_total} database table.
_search_find_match_with_simplify Finds an appropriate keyword in text.
_search_index_truncate Helper function for array_walk in search_index_split.

Constants

Namesort descending Description
PREG_CLASS_CJK Matches CJK (Chinese, Japanese, Korean) letter-like characters.
PREG_CLASS_NUMBERS Matches all 'N' Unicode character classes (numbers)
PREG_CLASS_PUNCTUATION Matches all 'P' Unicode character classes (punctuation)

File

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