search.module

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

Enables site-wide keyword searching.

Functions & methods

NameDescription
do_searchDo a query on the full-text search index for a word or words.
search_blockImplementation of hook_block().
search_boxOutput a search form for the search block and the theme's search box.
search_box_form_submitProcess a block search form submission.
search_cronImplementation of hook_cron().
search_dataPerform a standard search on the given keys, and return the formatted results.
search_dirtyMarks a word as dirty (or retrieves the list of dirty words). This is used during indexing (cron). Words which are dirty have outdated total counts in the search_total table, and need to be recounted.
search_excerptReturns snippets from a piece of text, with certain keywords highlighted. Used for formatting search results.
search_expand_cjkBasic CJK tokenizer. Simply splits a string into consecutive, overlapping sequences of characters ('minimum_word_size' long).
search_formRender a search form.
search_form_submitProcess a search form submission.
search_form_validateAs the search form collates keys from other modules hooked in via hook_form_alter, the validation takes place in _submit. search_form_validate() is used solely to set the 'processed_keys' form value for the basic search form.
search_get_keysHelper function for grabbing search keys.
search_helpImplementation of hook_help().
search_indexUpdate the full-text search index for a particular item.
search_index_splitSplits a string into tokens for indexing.
search_menuImplementation of hook_menu().
search_parse_queryParse a search query into SQL conditions.
search_permImplementation of hook_perm().
search_preprocessInvokes hook_search_preprocess() in modules.
search_query_extractExtract a module-specific search option from a search query. e.g. 'type:book'
search_query_insertReturn a query with the given module-specific search option inserted in. e.g. 'type:book'.
search_settingsMenu callback; displays the search module settings page.
search_settings_form_validateImplementation of hook_validate().
search_simplifySimplifies a string according to indexing rules.
search_update_totalsThis function is called on shutdown to ensure that search_total is always up to date (even if cron times out or otherwise fails).
search_viewMenu callback; presents the search form and/or search results.
search_wipeWipes a part of or the entire search index.
search_wipe_confirmMenu callback: confirm wiping of the index.
search_wipe_confirm_submitHandler for wipe confirmation
theme_search_block_formTheme the block search form.
theme_search_itemFormat a single result entry of a search query. This function is normally called by theme_search_page() or hook_search_page().
theme_search_pageFormat the result page of a search query.
theme_search_theme_formTheme the theme search form.
_search_excerpt_replaceHelper function for array_walk in search_except.
_search_index_truncateHelper function for array_walk in search_index_split.
_search_parse_queryHelper function for search_parse_query();

Constants

NameDescription
PREG_CLASS_CJKMatches all CJK characters that are candidates for auto-splitting (Chinese, Japanese, Korean). Contains kana and BMP ideographs.
PREG_CLASS_NUMBERSMatches all 'N' Unicode character classes (numbers)
PREG_CLASS_PUNCTUATIONMatches all 'P' Unicode character classes (punctuation)
PREG_CLASS_SEARCH_EXCLUDEMatches Unicode character classes to exclude from the search index.

File

modules/search.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * Enables site-wide keyword searching.
  5. */
  6. /**
  7. * Matches Unicode character classes to exclude from the search index.
  8. *
  9. * See: http://www.unicode.org/Public/UNIDATA/UCD.html#General_Category_Values
  10. *
  11. * The index only contains the following character classes:
  12. * Lu Letter, Uppercase
  13. * Ll Letter, Lowercase
  14. * Lt Letter, Titlecase
  15. * Lo Letter, Other
  16. * Nd Number, Decimal Digit
  17. * No Number, Other
  18. */
  19. define('PREG_CLASS_SEARCH_EXCLUDE',
  20. '\x{0}-\x{2f}\x{3a}-\x{40}\x{5b}-\x{60}\x{7b}-\x{bf}\x{d7}\x{f7}\x{2b0}-'.
  21. '\x{385}\x{387}\x{3f6}\x{482}-\x{489}\x{559}-\x{55f}\x{589}-\x{5c7}\x{5f3}-'.
  22. '\x{61f}\x{640}\x{64b}-\x{65e}\x{66a}-\x{66d}\x{670}\x{6d4}\x{6d6}-\x{6ed}'.
  23. '\x{6fd}\x{6fe}\x{700}-\x{70f}\x{711}\x{730}-\x{74a}\x{7a6}-\x{7b0}\x{901}-'.
  24. '\x{903}\x{93c}\x{93e}-\x{94d}\x{951}-\x{954}\x{962}-\x{965}\x{970}\x{981}-'.
  25. '\x{983}\x{9bc}\x{9be}-\x{9cd}\x{9d7}\x{9e2}\x{9e3}\x{9f2}-\x{a03}\x{a3c}-'.
  26. '\x{a4d}\x{a70}\x{a71}\x{a81}-\x{a83}\x{abc}\x{abe}-\x{acd}\x{ae2}\x{ae3}'.
  27. '\x{af1}-\x{b03}\x{b3c}\x{b3e}-\x{b57}\x{b70}\x{b82}\x{bbe}-\x{bd7}\x{bf0}-'.
  28. '\x{c03}\x{c3e}-\x{c56}\x{c82}\x{c83}\x{cbc}\x{cbe}-\x{cd6}\x{d02}\x{d03}'.
  29. '\x{d3e}-\x{d57}\x{d82}\x{d83}\x{dca}-\x{df4}\x{e31}\x{e34}-\x{e3f}\x{e46}-'.
  30. '\x{e4f}\x{e5a}\x{e5b}\x{eb1}\x{eb4}-\x{ebc}\x{ec6}-\x{ecd}\x{f01}-\x{f1f}'.
  31. '\x{f2a}-\x{f3f}\x{f71}-\x{f87}\x{f90}-\x{fd1}\x{102c}-\x{1039}\x{104a}-'.
  32. '\x{104f}\x{1056}-\x{1059}\x{10fb}\x{10fc}\x{135f}-\x{137c}\x{1390}-\x{1399}'.
  33. '\x{166d}\x{166e}\x{1680}\x{169b}\x{169c}\x{16eb}-\x{16f0}\x{1712}-\x{1714}'.
  34. '\x{1732}-\x{1736}\x{1752}\x{1753}\x{1772}\x{1773}\x{17b4}-\x{17db}\x{17dd}'.
  35. '\x{17f0}-\x{180e}\x{1843}\x{18a9}\x{1920}-\x{1945}\x{19b0}-\x{19c0}\x{19c8}'.
  36. '\x{19c9}\x{19de}-\x{19ff}\x{1a17}-\x{1a1f}\x{1d2c}-\x{1d61}\x{1d78}\x{1d9b}-'.
  37. '\x{1dc3}\x{1fbd}\x{1fbf}-\x{1fc1}\x{1fcd}-\x{1fcf}\x{1fdd}-\x{1fdf}\x{1fed}-'.
  38. '\x{1fef}\x{1ffd}-\x{2070}\x{2074}-\x{207e}\x{2080}-\x{2101}\x{2103}-\x{2106}'.
  39. '\x{2108}\x{2109}\x{2114}\x{2116}-\x{2118}\x{211e}-\x{2123}\x{2125}\x{2127}'.
  40. '\x{2129}\x{212e}\x{2132}\x{213a}\x{213b}\x{2140}-\x{2144}\x{214a}-\x{2b13}'.
  41. '\x{2ce5}-\x{2cff}\x{2d6f}\x{2e00}-\x{3005}\x{3007}-\x{303b}\x{303d}-\x{303f}'.
  42. '\x{3099}-\x{309e}\x{30a0}\x{30fb}-\x{30fe}\x{3190}-\x{319f}\x{31c0}-\x{31cf}'.
  43. '\x{3200}-\x{33ff}\x{4dc0}-\x{4dff}\x{a015}\x{a490}-\x{a716}\x{a802}\x{a806}'.
  44. '\x{a80b}\x{a823}-\x{a82b}\x{d800}-\x{f8ff}\x{fb1e}\x{fb29}\x{fd3e}\x{fd3f}'.
  45. '\x{fdfc}-\x{fe6b}\x{feff}-\x{ff0f}\x{ff1a}-\x{ff20}\x{ff3b}-\x{ff40}\x{ff5b}-'.
  46. '\x{ff65}\x{ff70}\x{ff9e}\x{ff9f}\x{ffe0}-\x{fffd}');
  47. /**
  48. * Matches all 'N' Unicode character classes (numbers)
  49. */
  50. define('PREG_CLASS_NUMBERS',
  51. '\x{30}-\x{39}\x{b2}\x{b3}\x{b9}\x{bc}-\x{be}\x{660}-\x{669}\x{6f0}-\x{6f9}'.
  52. '\x{966}-\x{96f}\x{9e6}-\x{9ef}\x{9f4}-\x{9f9}\x{a66}-\x{a6f}\x{ae6}-\x{aef}'.
  53. '\x{b66}-\x{b6f}\x{be7}-\x{bf2}\x{c66}-\x{c6f}\x{ce6}-\x{cef}\x{d66}-\x{d6f}'.
  54. '\x{e50}-\x{e59}\x{ed0}-\x{ed9}\x{f20}-\x{f33}\x{1040}-\x{1049}\x{1369}-'.
  55. '\x{137c}\x{16ee}-\x{16f0}\x{17e0}-\x{17e9}\x{17f0}-\x{17f9}\x{1810}-\x{1819}'.
  56. '\x{1946}-\x{194f}\x{2070}\x{2074}-\x{2079}\x{2080}-\x{2089}\x{2153}-\x{2183}'.
  57. '\x{2460}-\x{249b}\x{24ea}-\x{24ff}\x{2776}-\x{2793}\x{3007}\x{3021}-\x{3029}'.
  58. '\x{3038}-\x{303a}\x{3192}-\x{3195}\x{3220}-\x{3229}\x{3251}-\x{325f}\x{3280}-'.
  59. '\x{3289}\x{32b1}-\x{32bf}\x{ff10}-\x{ff19}');
  60. /**
  61. * Matches all 'P' Unicode character classes (punctuation)
  62. */
  63. define('PREG_CLASS_PUNCTUATION',
  64. '\x{21}-\x{23}\x{25}-\x{2a}\x{2c}-\x{2f}\x{3a}\x{3b}\x{3f}\x{40}\x{5b}-\x{5d}'.
  65. '\x{5f}\x{7b}\x{7d}\x{a1}\x{ab}\x{b7}\x{bb}\x{bf}\x{37e}\x{387}\x{55a}-\x{55f}'.
  66. '\x{589}\x{58a}\x{5be}\x{5c0}\x{5c3}\x{5f3}\x{5f4}\x{60c}\x{60d}\x{61b}\x{61f}'.
  67. '\x{66a}-\x{66d}\x{6d4}\x{700}-\x{70d}\x{964}\x{965}\x{970}\x{df4}\x{e4f}'.
  68. '\x{e5a}\x{e5b}\x{f04}-\x{f12}\x{f3a}-\x{f3d}\x{f85}\x{104a}-\x{104f}\x{10fb}'.
  69. '\x{1361}-\x{1368}\x{166d}\x{166e}\x{169b}\x{169c}\x{16eb}-\x{16ed}\x{1735}'.
  70. '\x{1736}\x{17d4}-\x{17d6}\x{17d8}-\x{17da}\x{1800}-\x{180a}\x{1944}\x{1945}'.
  71. '\x{2010}-\x{2027}\x{2030}-\x{2043}\x{2045}-\x{2051}\x{2053}\x{2054}\x{2057}'.
  72. '\x{207d}\x{207e}\x{208d}\x{208e}\x{2329}\x{232a}\x{23b4}-\x{23b6}\x{2768}-'.
  73. '\x{2775}\x{27e6}-\x{27eb}\x{2983}-\x{2998}\x{29d8}-\x{29db}\x{29fc}\x{29fd}'.
  74. '\x{3001}-\x{3003}\x{3008}-\x{3011}\x{3014}-\x{301f}\x{3030}\x{303d}\x{30a0}'.
  75. '\x{30fb}\x{fd3e}\x{fd3f}\x{fe30}-\x{fe52}\x{fe54}-\x{fe61}\x{fe63}\x{fe68}'.
  76. '\x{fe6a}\x{fe6b}\x{ff01}-\x{ff03}\x{ff05}-\x{ff0a}\x{ff0c}-\x{ff0f}\x{ff1a}'.
  77. '\x{ff1b}\x{ff1f}\x{ff20}\x{ff3b}-\x{ff3d}\x{ff3f}\x{ff5b}\x{ff5d}\x{ff5f}-'.
  78. '\x{ff65}');
  79. /**
  80. * Matches all CJK characters that are candidates for auto-splitting
  81. * (Chinese, Japanese, Korean).
  82. * Contains kana and BMP ideographs.
  83. */
  84. define('PREG_CLASS_CJK', '\x{3041}-\x{30ff}\x{31f0}-\x{31ff}\x{3400}-\x{4db5}'.
  85. '\x{4e00}-\x{9fbb}\x{f900}-\x{fad9}');
  86. /**
  87. * Implementation of hook_help().
  88. */
  89. function search_help($section) {
  90. switch ($section) {
  91. case 'admin/help#search':
  92. $output = '<p>'. t('The search module adds the ability to search for content by keywords. Search is often the only practical way to find content on a large site. Search is useful for finding users and posts by searching on keywords.') .'</p>';
  93. $output .= '<p>'. t('The search engine works by maintaining an index of the words in your site\'s content. It indexes the posts and users. You can adjust the settings to tweak the indexing behaviour. Note that the search requires cron to be set up correctly. The index percentage sets the maximum amount of items that will be indexed in one cron run. Set this number lower if your cron is timing out or if PHP is running out of memory.') .'</p>';
  94. $output .= t('<p>You can</p>
  95. <ul>
  96. <li>read about how your site uses cron in the <a href="%admin-help-system">administer &gt;&gt; help &gt;&gt; system</a>.</li>
  97. <li>run your <a href="%file-cron">cron.php</a>.</li>
  98. <li>read about <a href="%external-http-drupal-org-node-23714">configuring cron jobs</a>.</li>
  99. <li><a href="%admin-settings-search">administer &gt;&gt; settings &gt;&gt; search</a>.</li></ul>
  100. ', array('%admin-help-system' => url('admin/help/system'), '%file-cron' => 'cron.php', '%external-http-drupal-org-node-23714' => 'http://drupal.org/node/23714', '%admin-settings-search' => url('admin/settings/search')));
  101. $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="%search">Search page</a>.', array('%search' => 'http://drupal.org/handbook/modules/search/')) .'</p>';
  102. return $output;
  103. case 'admin/modules#description':
  104. return t('Enables site-wide keyword searching.');
  105. case 'admin/settings/search':
  106. return t('
  107. <p>The search engine works by maintaining an index of the words in your site\'s content. You can adjust the settings below to tweak the indexing behaviour. Note that the search requires cron to be set up correctly.</p>
  108. ');
  109. case 'search#noresults':
  110. return t('<ul>
  111. <li>Check if your spelling is correct.</li>
  112. <li>Remove quotes around phrases to match each word individually: <em>"blue smurf"</em> will match less than <em>blue smurf</em>.</li>
  113. <li>Consider loosening your query with <em>OR</em>: <em>blue smurf</em> will match less than <em>blue OR smurf</em>.</li>
  114. </ul>');
  115. }
  116. }
  117. /**
  118. * Implementation of hook_perm().
  119. */
  120. function search_perm() {
  121. return array('search content', 'administer search');
  122. }
  123. /**
  124. * Implementation of hook_block().
  125. */
  126. function search_block($op = 'list', $delta = 0) {
  127. if ($op == 'list') {
  128. $blocks[0]['info'] = t('Search form');
  129. return $blocks;
  130. }
  131. else if ($op == 'view' && user_access('search content')) {
  132. $block['content'] = search_box('search_block_form');
  133. $block['subject'] = t('Search');
  134. return $block;
  135. }
  136. }
  137. /**
  138. * Implementation of hook_menu().
  139. */
  140. function search_menu($may_cache) {
  141. $items = array();
  142. if ($may_cache) {
  143. $items[] = array('path' => 'search', 'title' => t('search'),
  144. 'callback' => 'search_view',
  145. 'access' => user_access('search content'),
  146. 'type' => MENU_SUGGESTED_ITEM);
  147. $items[] = array('path' => 'admin/settings/search/wipe', 'title' => t('Clear index'),
  148. 'callback' => 'search_wipe_confirm',
  149. 'access' => user_access('administer search'),
  150. 'type' => MENU_CALLBACK);
  151. }
  152. else if (arg(0) == 'search') {
  153. // To remember the user's search keywords when switching across tabs,
  154. // we dynamically add the keywords to the search tabs' paths.
  155. $keys = search_get_keys();
  156. $keys = strlen($keys) ? '/'. $keys : '';
  157. foreach (module_list() as $name) {
  158. if (module_hook($name, 'search') && $title = module_invoke($name, 'search', 'name')) {
  159. $items[] = array('path' => 'search/'. $name . $keys, 'title' => $title,
  160. 'callback' => 'search_view',
  161. 'access' => user_access('search content'),
  162. 'type' => MENU_LOCAL_TASK);
  163. }
  164. }
  165. }
  166. return $items;
  167. }
  168. /**
  169. * Implementation of hook_validate().
  170. */
  171. function search_settings_form_validate($form_id, &$form) {
  172. if ($_POST['op'] == t('Re-index site')) {
  173. drupal_goto('admin/settings/search/wipe');
  174. }
  175. // If these settings change, the index needs to be rebuilt.
  176. if ((variable_get('minimum_word_size', 3) != $form['minimum_word_size']) ||
  177. (variable_get('overlap_cjk', true) != $form['overlap_cjk'])) {
  178. drupal_set_message(t('The index will be rebuilt.'));
  179. search_wipe();
  180. }
  181. }
  182. /**
  183. * Menu callback; displays the search module settings page.
  184. */
  185. function search_settings() {
  186. // Collect some stats
  187. $remaining = 0;
  188. $total = 0;
  189. foreach (module_list() as $module) {
  190. if (module_hook($module, 'search')) {
  191. $status = module_invoke($module, 'search', 'status');
  192. $remaining += $status['remaining'];
  193. $total += $status['total'];
  194. }
  195. }
  196. $count = format_plural($remaining, 'There is 1 item left to index.', 'There are %count items left to index.');
  197. $percentage = ((int)min(100, 100 * ($total - $remaining) / max(1, $total))) . '%';
  198. $status = '<p><strong>'. t('%percentage of the site has been indexed.', array('%percentage' => $percentage)) .' '. $count .'</strong></p>';
  199. $form['status'] = array('#type' => 'fieldset', '#title' => t('Indexing status'));
  200. $form['status']['status'] = array('#type' => 'markup', '#value' => $status);
  201. $form['status']['wipe'] = array('#type' => 'submit', '#value' => t('Re-index site'));
  202. $items = drupal_map_assoc(array(10, 20, 50, 100, 200, 500));
  203. // Indexing throttle:
  204. $form['indexing_throttle'] = array('#type' => 'fieldset', '#title' => t('Indexing throttle'));
  205. $form['indexing_throttle']['search_cron_limit'] = array('#type' => 'select', '#title' => t('Items to index per cron run'), '#default_value' => variable_get('search_cron_limit', 100), '#options' => $items, '#description' => t('The maximum amount of items that will be indexed in one cron run. Set this number lower if your cron is timing out or if PHP is running out of memory.'));
  206. // Indexing settings:
  207. $form['indexing_settings'] = array('#type' => 'fieldset', '#title' => t('Indexing settings'));
  208. $form['indexing_settings']['info'] = array('#type' => 'markup', '#value' => '<em>'. t('<p>Changing the settings below will cause the site index to be rebuilt. The search index is not cleared but systematically updated to reflect the new settings. Searching will continue to work but new content won\'t be indexed until all existing content has been re-indexed.</p><p>The default settings should be appropriate for the majority of sites.</p>') .'</em>');
  209. $form['indexing_settings']['minimum_word_size'] = array('#type' => 'textfield', '#title' => t('Minimum word length to index'), '#default_value' => variable_get('minimum_word_size', 3), '#size' => 5, '#maxlength' => 3, '#description' => t('The number of characters a word has to be to be indexed. A lower setting means better search result ranking, but also a larger database. Each search query must contain at least one keyword that is this size (or longer).'));
  210. $form['indexing_settings']['overlap_cjk'] = array('#type' => 'checkbox', '#title' => t('Simple CJK handling'), '#default_value' => variable_get('overlap_cjk', true), '#description' => t('Whether to apply a simple Chinese/Japanese/Korean tokenizer based on overlapping sequences. Turn this off if you want to use an external preprocessor for this instead. Does not affect other languages.'));
  211. // Per module settings
  212. $form = array_merge($form, module_invoke_all('search', 'admin'));
  213. return $form;
  214. }
  215. /**
  216. * Menu callback: confirm wiping of the index.
  217. */
  218. function search_wipe_confirm() {
  219. return confirm_form('search_wipe_confirm', $form, t('Are you sure you want to re-index the site?'),
  220. 'admin/settings/search', t(' The search index is not cleared but systematically updated to reflect the new settings. Searching will continue to work but new content won\'t be indexed until all existing content has been re-indexed. This action cannot be undone.'), t('Re-index site'), t('Cancel'));
  221. }
  222. /**
  223. * Handler for wipe confirmation
  224. */
  225. function search_wipe_confirm_submit($form_id, &$form) {
  226. if ($form['confirm']) {
  227. search_wipe();
  228. drupal_set_message(t('The index will be rebuilt.'));
  229. return 'admin/settings/search';
  230. }
  231. }
  232. /**
  233. * Wipes a part of or the entire search index.
  234. *
  235. * @param $sid
  236. * (optional) The SID of the item to wipe. If specified, $type must be passed
  237. * too.
  238. * @param $type
  239. * (optional) The type of item to wipe.
  240. */
  241. function search_wipe($sid = NULL, $type = NULL, $reindex = FALSE) {
  242. if ($type == NULL && $sid == NULL) {
  243. module_invoke_all('search', 'reset');
  244. }
  245. else {
  246. db_query("DELETE FROM {search_dataset} WHERE sid = %d AND type = '%s'", $sid, $type);
  247. db_query("DELETE FROM {search_index} WHERE fromsid = %d AND fromtype = '%s'", $sid, $type);
  248. // When re-indexing, keep link references
  249. db_query("DELETE FROM {search_index} WHERE sid = %d AND type = '%s'". ($reindex ? " AND fromsid = 0" : ''), $sid, $type);
  250. }
  251. }
  252. /**
  253. * Marks a word as dirty (or retrieves the list of dirty words). This is used
  254. * during indexing (cron). Words which are dirty have outdated total counts in
  255. * the search_total table, and need to be recounted.
  256. */
  257. function search_dirty($word = null) {
  258. static $dirty = array();
  259. if ($word !== null) {
  260. $dirty[$word] = true;
  261. }
  262. else {
  263. return $dirty;
  264. }
  265. }
  266. /**
  267. * Implementation of hook_cron().
  268. *
  269. * Fires hook_update_index() in all modules and cleans up dirty words (see
  270. * search_dirty).
  271. */
  272. function search_cron() {
  273. // We register a shutdown function to ensure that search_total is always up
  274. // to date.
  275. register_shutdown_function('search_update_totals');
  276. // Update word index
  277. foreach (module_list() as $module) {
  278. module_invoke($module, 'update_index');
  279. }
  280. }
  281. /**
  282. * This function is called on shutdown to ensure that search_total is always
  283. * up to date (even if cron times out or otherwise fails).
  284. */
  285. function search_update_totals() {
  286. // Update word IDF (Inverse Document Frequency) counts for new/changed words
  287. foreach (search_dirty() as $word => $dummy) {
  288. // Get total count
  289. $total = db_result(db_query("SELECT SUM(score) FROM {search_index} WHERE word = '%s'", $word));
  290. // Apply Zipf's law to equalize the probability distribution
  291. $total = log10(1 + 1/(max(1, $total)));
  292. db_query("UPDATE {search_total} SET count = %f WHERE word = '%s'", $total, $word);
  293. if (!db_affected_rows()) {
  294. db_query("INSERT INTO {search_total} (word, count) VALUES ('%s', %f)", $word, $total);
  295. }
  296. }
  297. // Find words that were deleted from search_index, but are still in
  298. // search_total. We use a LEFT JOIN between the two tables and keep only the
  299. // rows which fail to join.
  300. $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");
  301. while ($word = db_fetch_object($result)) {
  302. db_query("DELETE FROM {search_total} WHERE word = '%s'", $word->realword);
  303. }
  304. }
  305. /**
  306. * Simplifies a string according to indexing rules.
  307. */
  308. function search_simplify($text) {
  309. // Decode entities to UTF-8
  310. $text = decode_entities($text);
  311. // Lowercase
  312. $text = drupal_strtolower($text);
  313. // Call an external processor for word handling.
  314. search_preprocess($text);
  315. // Simple CJK handling
  316. if (variable_get('overlap_cjk', true)) {
  317. $text = preg_replace_callback('/['. PREG_CLASS_CJK .']+/u', 'search_expand_cjk', $text);
  318. }
  319. // To improve searching for numerical data such as dates, IP addresses
  320. // or version numbers, we consider a group of numerical characters
  321. // separated only by punctuation characters to be one piece.
  322. // This also means that searching for e.g. '20/03/1984' also returns
  323. // results with '20-03-1984' in them.
  324. // Readable regexp: ([number]+)[punctuation]+(?=[number])
  325. $text = preg_replace('/(['. PREG_CLASS_NUMBERS .']+)['. PREG_CLASS_PUNCTUATION .']+(?=['. PREG_CLASS_NUMBERS .'])/u', '\1', $text);
  326. // The dot, underscore and dash are simply removed. This allows meaningful
  327. // search behaviour with acronyms and URLs.
  328. $text = preg_replace('/[._-]+/', '', $text);
  329. // With the exception of the rules above, we consider all punctuation,
  330. // marks, spacers, etc, to be a word boundary.
  331. $text = preg_replace('/['. PREG_CLASS_SEARCH_EXCLUDE . ']+/u', ' ', $text);
  332. return $text;
  333. }
  334. /**
  335. * Basic CJK tokenizer. Simply splits a string into consecutive, overlapping
  336. * sequences of characters ('minimum_word_size' long).
  337. */
  338. function search_expand_cjk($matches) {
  339. $min = variable_get('minimum_word_size', 3);
  340. $str = $matches[0];
  341. $l = drupal_strlen($str);
  342. // Passthrough short words
  343. if ($l <= $min) {
  344. return ' '. $str .' ';
  345. }
  346. $tokens = ' ';
  347. // FIFO queue of characters
  348. $chars = array();
  349. // Begin loop
  350. for ($i = 0; $i < $l; ++$i) {
  351. // Grab next character
  352. $current = drupal_substr($str, 0, 1);
  353. $str = substr($str, strlen($current));
  354. $chars[] = $current;
  355. if ($i >= $min - 1) {
  356. $tokens .= implode('', $chars) .' ';
  357. array_shift($chars);
  358. }
  359. }
  360. return $tokens;
  361. }
  362. /**
  363. * Splits a string into tokens for indexing.
  364. */
  365. function search_index_split($text) {
  366. static $last = null;
  367. static $lastsplit = null;
  368. if ($last == $text) {
  369. return $lastsplit;
  370. }
  371. // Process words
  372. $text = search_simplify($text);
  373. $words = explode(' ', $text);
  374. array_walk($words, '_search_index_truncate');
  375. // Save last keyword result
  376. $last = $text;
  377. $lastsplit = $words;
  378. return $words;
  379. }
  380. /**
  381. * Helper function for array_walk in search_index_split.
  382. */
  383. function _search_index_truncate(&$text) {
  384. $text = truncate_utf8($text, 50);
  385. }
  386. /**
  387. * Invokes hook_search_preprocess() in modules.
  388. */
  389. function search_preprocess(&$text) {
  390. foreach (module_implements('search_preprocess') as $module) {
  391. $text = module_invoke($module, 'search_preprocess', $text);
  392. }
  393. }
  394. /**
  395. * Update the full-text search index for a particular item.
  396. *
  397. * @param $sid
  398. * A number identifying this particular item (e.g. node id).
  399. *
  400. * @param $type
  401. * A string defining this type of item (e.g. 'node')
  402. *
  403. * @param $text
  404. * The content of this item. Must be a piece of HTML text.
  405. *
  406. * @ingroup search
  407. */
  408. function search_index($sid, $type, $text) {
  409. $minimum_word_size = variable_get('minimum_word_size', 3);
  410. // Link matching
  411. global $base_url;
  412. $node_regexp = '@href=[\'"]?(?:'. preg_quote($base_url, '@') .'/|'. preg_quote(base_path(), '@') .')(?:\?q=)?/?((?![a-z]+:)[^\'">]+)[\'">]@i';
  413. // Multipliers for scores of words inside certain HTML tags.
  414. // Note: 'a' must be included for link ranking to work.
  415. $tags = array('h1' => 25,
  416. 'h2' => 18,
  417. 'h3' => 15,
  418. 'h4' => 12,
  419. 'h5' => 9,
  420. 'h6' => 6,
  421. 'u' => 3,
  422. 'b' => 3,
  423. 'i' => 3,
  424. 'strong' => 3,
  425. 'em' => 3,
  426. 'a' => 10);
  427. // Strip off all ignored tags to speed up processing, but insert space before/after
  428. // them to keep word boundaries.
  429. $text = str_replace(array('<', '>'), array(' <', '> '), $text);
  430. $text = strip_tags($text, '<'. implode('><', array_keys($tags)) .'>');
  431. // Split HTML tags from plain text.
  432. $split = preg_split('/\s*<([^>]+?)>\s*/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  433. // Note: PHP ensures the array consists of alternating delimiters and literals
  434. // and begins and ends with a literal (inserting $null as required).
  435. $tag = false; // Odd/even counter. Tag or no tag.
  436. $link = false; // State variable for link analyser
  437. $score = 1; // Starting score per word
  438. $accum = ' '; // Accumulator for cleaned up data
  439. $tagstack = array(); // Stack with open tags
  440. $tagwords = 0; // Counter for consecutive words
  441. $focus = 1; // Focus state
  442. $results = array(0 => array()); // Accumulator for words for index
  443. foreach ($split as $value) {
  444. if ($tag) {
  445. // Increase or decrease score per word based on tag
  446. list($tagname) = explode(' ', $value, 2);
  447. $tagname = drupal_strtolower($tagname);
  448. // Closing or opening tag?
  449. if ($tagname[0] == '/') {
  450. $tagname = substr($tagname, 1);
  451. // If we encounter unexpected tags, reset score to avoid incorrect boosting.
  452. if (!count($tagstack) || $tagstack[0] != $tagname) {
  453. $tagstack = array();
  454. $score = 1;
  455. }
  456. else {
  457. // Remove from tag stack and decrement score
  458. $score = max(1, $score - $tags[array_shift($tagstack)]);
  459. }
  460. if ($tagname == 'a') {
  461. $link = false;
  462. }
  463. }
  464. else {
  465. if ($tagstack[0] == $tagname) {
  466. // None of the tags we look for make sense when nested identically.
  467. // If they are, it's probably broken HTML.
  468. $tagstack = array();
  469. $score = 1;
  470. }
  471. else {
  472. // Add to open tag stack and increment score
  473. array_unshift($tagstack, $tagname);
  474. $score += $tags[$tagname];
  475. }
  476. if ($tagname == 'a') {
  477. // Check if link points to a node on this site
  478. if (preg_match($node_regexp, $value, $match)) {
  479. $path = drupal_get_normal_path($match[1]);
  480. if (preg_match('!(?:node|book)/(?:view/)?([0-9]+)!i', $path, $match)) {
  481. $linknid = $match[1];
  482. if ($linknid > 0) {
  483. // Note: ignore links to uncachable nodes to avoid redirect bugs.
  484. $node = db_fetch_object(db_query('SELECT n.title, n.nid, n.vid, r.format FROM {node} n INNER JOIN {node_revisions} r ON n.vid = r.vid WHERE n.nid = %d', $linknid));
  485. if (filter_format_allowcache($node->format)) {
  486. $link = true;
  487. $linktitle = $node->title;
  488. }
  489. }
  490. }
  491. }
  492. }
  493. }
  494. // A tag change occurred, reset counter.
  495. $tagwords = 0;
  496. }
  497. else {
  498. // Note: use of PREG_SPLIT_DELIM_CAPTURE above will introduce empty values
  499. if ($value != '') {
  500. if ($link) {
  501. // Check to see if the node link text is its URL. If so, we use the target node title instead.
  502. if (preg_match('!^https?://!i', $value)) {
  503. $value = $linktitle;
  504. }
  505. }
  506. $words = search_index_split($value);
  507. foreach ($words as $word) {
  508. // Add word to accumulator
  509. $accum .= $word .' ';
  510. $num = is_numeric($word);
  511. // Check wordlength
  512. if ($num || drupal_strlen($word) >= $minimum_word_size) {
  513. // Normalize numbers
  514. if ($num) {
  515. $word = (int)ltrim($word, '-0');
  516. }
  517. if ($link) {
  518. if (!isset($results[$linknid])) {
  519. $results[$linknid] = array();
  520. }
  521. $results[$linknid][$word] += $score * $focus;
  522. }
  523. else {
  524. $results[0][$word] += $score * $focus;
  525. // Focus is a decaying value in terms of the amount of unique words up to this point.
  526. // From 100 words and more, it decays, to e.g. 0.5 at 500 words and 0.3 at 1000 words.
  527. $focus = min(1, .01 + 3.5 / (2 + count($results[0]) * .015));
  528. }
  529. }
  530. $tagwords++;
  531. // Too many words inside a single tag probably mean a tag was accidentally left open.
  532. if (count($tagstack) && $tagwords >= 15) {
  533. $tagstack = array();
  534. $score = 1;
  535. }
  536. }
  537. }
  538. }
  539. $tag = !$tag;
  540. }
  541. search_wipe($sid, $type, TRUE);
  542. // Insert cleaned up data into dataset
  543. db_query("INSERT INTO {search_dataset} (sid, type, data) VALUES (%d, '%s', '%s')", $sid, $type, $accum);
  544. // Insert results into search index
  545. foreach ($results[0] as $word => $score) {
  546. db_query("INSERT INTO {search_index} (word, sid, type, score) VALUES ('%s', %d, '%s', %f)", $word, $sid, $type, $score);
  547. search_dirty($word);
  548. }
  549. unset($results[0]);
  550. // Now insert links to nodes
  551. foreach ($results as $nid => $words) {
  552. foreach ($words as $word => $score) {
  553. db_query("INSERT INTO {search_index} (word, sid, type, fromsid, fromtype, score) VALUES ('%s', %d, '%s', %d, '%s', %f)", $word, $nid, 'node', $sid, $type, $score);
  554. search_dirty($word);
  555. }
  556. }
  557. }
  558. /**
  559. * Extract a module-specific search option from a search query. e.g. 'type:book'
  560. */
  561. function search_query_extract($keys, $option) {
  562. if (preg_match('/(^| )'. $option .':([^ ]*)( |$)/i', $keys, $matches)) {
  563. return $matches[2];
  564. }
  565. }
  566. /**
  567. * Return a query with the given module-specific search option inserted in.
  568. * e.g. 'type:book'.
  569. */
  570. function search_query_insert($keys, $option, $value = '') {
  571. if (search_query_extract($keys, $option)) {
  572. $keys = trim(preg_replace('/(^| )'. $option .':[^ ]*/i', '', $keys));
  573. }
  574. if ($value != '') {
  575. $keys .= ' '. $option .':'. $value;
  576. }
  577. return $keys;
  578. }
  579. /**
  580. * Parse a search query into SQL conditions.
  581. *
  582. * We build a query that matches the dataset bodies.
  583. */
  584. function search_parse_query($text) {
  585. $keys = array('positive' => array(), 'negative' => array());
  586. // Tokenize query string
  587. preg_match_all('/ (-?)("[^"]+"|[^" ]+)/i', ' '. $text, $matches, PREG_SET_ORDER);
  588. if (count($matches) < 1) {
  589. return NULL;
  590. }
  591. // Classify tokens
  592. $or = false;
  593. foreach ($matches as $match) {
  594. $phrase = false;
  595. // Strip off phrase quotes
  596. if ($match[2]{0} == '"') {
  597. $match[2] = substr($match[2], 1, -1);
  598. $phrase = true;
  599. }
  600. // Simplify keyword according to indexing rules and external preprocessors
  601. $words = search_simplify($match[2]);
  602. // Re-explode in case simplification added more words, except when matching a phrase
  603. $words = $phrase ? array($words) : preg_split('/ /', $words, -1, PREG_SPLIT_NO_EMPTY);
  604. // Negative matches
  605. if ($match[1] == '-') {
  606. $keys['negative'] = array_merge($keys['negative'], $words);
  607. }
  608. // OR operator: instead of a single keyword, we store an array of all
  609. // OR'd keywords.
  610. elseif ($match[2] == 'OR' && count($keys['positive'])) {
  611. $last = array_pop($keys['positive']);
  612. // Starting a new OR?
  613. if (!is_array($last)) {
  614. $last = array($last);
  615. }
  616. $keys['positive'][] = $last;
  617. $or = true;
  618. continue;
  619. }
  620. // Plain keyword
  621. else {
  622. if ($or) {
  623. // Add to last element (which is an array)
  624. $keys['positive'][count($keys['positive']) - 1] = array_merge($keys['positive'][count($keys['positive']) - 1], $words);
  625. }
  626. else {
  627. $keys['positive'] = array_merge($keys['positive'], $words);
  628. }
  629. }
  630. $or = false;
  631. }
  632. // Convert keywords into SQL statements.
  633. $query = array();
  634. $query2 = array();
  635. $arguments = array();
  636. $arguments2 = array();
  637. $matches = 0;
  638. // Positive matches
  639. foreach ($keys['positive'] as $key) {
  640. // Group of ORed terms
  641. if (is_array($key) && count($key)) {
  642. $queryor = array();
  643. $any = false;
  644. foreach ($key as $or) {
  645. list($q, $count) = _search_parse_query($or, $arguments2);
  646. $any |= $count;
  647. if ($q) {
  648. $queryor[] = $q;
  649. $arguments[] = $or;
  650. }
  651. }
  652. if (count($queryor)) {
  653. $query[] = '('. implode(' OR ', $queryor) .')';
  654. // A group of OR keywords only needs to match once
  655. $matches += ($any > 0);
  656. }
  657. }
  658. // Single ANDed term
  659. else {
  660. list($q, $count) = _search_parse_query($key, $arguments2);
  661. if ($q) {
  662. $query[] = $q;
  663. $arguments[] = $key;
  664. // Each AND keyword needs to match at least once
  665. $matches += $count;
  666. }
  667. }
  668. }
  669. // Negative matches
  670. foreach ($keys['negative'] as $key) {
  671. list($q) = _search_parse_query($key, $arguments2, true);
  672. if ($q) {
  673. $query[] = $q;
  674. $arguments[] = $key;
  675. }
  676. }
  677. $query = implode(' AND ', $query);
  678. // Build word-index conditions for the first pass
  679. $query2 = substr(str_repeat("i.word = '%s' OR ", count($arguments2)), 0, -4);
  680. return array($query, $arguments, $query2, $arguments2, $matches);
  681. }
  682. /**
  683. * Helper function for search_parse_query();
  684. */
  685. function _search_parse_query(&$word, &$scores, $not = false) {
  686. $count = 0;
  687. // Determine the scorewords of this word/phrase
  688. if (!$not) {
  689. $split = explode(' ', $word);
  690. foreach ($split as $s) {
  691. $num = is_numeric($s);
  692. if ($num || drupal_strlen($s) >= variable_get('minimum_word_size', 3)) {
  693. $s = $num ? ((int)ltrim($s, '-0')) : $s;
  694. if (!isset($scores[$s])) {
  695. $scores[$s] = $s;
  696. $count++;
  697. }
  698. }
  699. }
  700. }
  701. // Return matching snippet and number of added words
  702. return array("d.data ". ($not ? 'NOT ' : '') ."LIKE '%% %s %%'", $count);
  703. }
  704. /**
  705. * Do a query on the full-text search index for a word or words.
  706. *
  707. * This function is normally only called by each module that support the
  708. * indexed search (and thus, implements hook_update_index()).
  709. *
  710. * Two queries are performed which can be extended by the caller.
  711. *
  712. * The first query selects a set of possible matches based on the search index
  713. * and any extra given restrictions. This is the classic "OR" search.
  714. *
  715. * SELECT i.type, i.sid, SUM(i.score*t.count) AS relevance
  716. * FROM {search_index} i
  717. * INNER JOIN {search_total} t ON i.word = t.word
  718. * $join1
  719. * WHERE $where1 AND (...)
  720. * GROUP BY i.type, i.sid
  721. *
  722. * The second query further refines this set by verifying advanced text
  723. * conditions (such as AND, negative or phrase matches), and orders the results
  724. * on a the column or expression 'score':
  725. *
  726. * SELECT i.type, i.sid, $select2
  727. * FROM temp_search_sids i
  728. * INNER JOIN {search_dataset} d ON i.sid = d.sid AND i.type = d.type
  729. * $join2
  730. * WHERE (...)
  731. * ORDER BY score DESC
  732. *
  733. * @param $keywords
  734. * A search string as entered by the user.
  735. *
  736. * @param $type
  737. * A string identifying the calling module.
  738. *
  739. * @param $join1
  740. * (optional) Inserted into the JOIN part of the first SQL query.
  741. * For example "INNER JOIN {node} n ON n.nid = i.sid".
  742. *
  743. * @param $where1
  744. * (optional) Inserted into the WHERE part of the first SQL query.
  745. * For example "(n.status > %d)".
  746. *
  747. * @param $arguments1
  748. * (optional) Extra SQL arguments belonging to the first query.
  749. *
  750. * @param $select2
  751. * (optional) Inserted into the SELECT pat of the second query. Must contain
  752. * a column selected as 'score'.
  753. * defaults to 'i.relevance AS score'
  754. *
  755. * @param $join2
  756. * (optional) Inserted into the JOIN par of the second SQL query.
  757. * For example "INNER JOIN {node_comment_statistics} n ON n.nid = i.sid"
  758. *
  759. * @param $arguments2
  760. * (optional) Extra SQL arguments belonging to the second query parameter.
  761. *
  762. * @param $sort_parameters
  763. * (optional) SQL arguments for sorting the final results.
  764. * Default: 'ORDER BY score DESC'
  765. *
  766. * @return
  767. * An array of SIDs for the search results.
  768. *
  769. * @ingroup search
  770. */
  771. function do_search($keywords, $type, $join1 = '', $where1 = '1', $arguments1 = array(), $select2 = 'i.relevance AS score', $join2 = '', $arguments2 = array(), $sort_parameters = 'ORDER BY score DESC') {
  772. $query = search_parse_query($keywords);
  773. if ($query[2] == '') {
  774. form_set_error('keys', t('You must include at least one positive keyword with %count characters or more.', array('%count' => variable_get('minimum_word_size', 3))));
  775. }
  776. if ($query === NULL || $query[0] == '' || $query[2] == '') {
  777. return array();
  778. }
  779. // First pass: select all possible matching sids, doing a simple index-based OR matching on the keywords.
  780. // 'matches' is used to reject those items that cannot possibly match the query.
  781. $conditions = $where1 .' AND ('. $query[2] .") AND i.type = '%s'";
  782. $arguments = array_merge($arguments1, $query[3], array($type, $query[4]));
  783. $result = db_query_temporary("SELECT i.type, i.sid, SUM(i.score * t.count) AS relevance, COUNT(*) AS matches FROM {search_index} i INNER JOIN {search_total} t ON i.word = t.word $join1 WHERE $conditions GROUP BY i.type, i.sid HAVING COUNT(*) >= %d", $arguments, 'temp_search_sids');
  784. // Calculate maximum relevance, to normalize it
  785. $normalize = db_result(db_query('SELECT MAX(relevance) FROM temp_search_sids'));
  786. if (!$normalize) {
  787. return array();
  788. }
  789. $select2 = str_replace('i.relevance', '('. (1.0 / $normalize) .' * i.relevance)', $select2);
  790. // Second pass: only keep items that match the complicated keywords conditions (phrase search, negative keywords, ...)
  791. $conditions = '('. $query[0] .')';
  792. $arguments = array_merge($arguments2, $query[1]);
  793. $result = db_query_temporary("SELECT i.type, i.sid, $select2 FROM temp_search_sids i INNER JOIN {search_dataset} d ON i.sid = d.sid AND i.type = d.type $join2 WHERE $conditions $sort_parameters", $arguments, 'temp_search_results');
  794. if (($count = db_result(db_query('SELECT COUNT(*) FROM temp_search_results'))) == 0) {
  795. return array();
  796. }
  797. $count_query = "SELECT $count";
  798. // Do actual search query
  799. $result = pager_query("SELECT * FROM temp_search_results", 10, 0, $count_query);
  800. $results = array();
  801. while ($item = db_fetch_object($result)) {
  802. $results[] = $item;
  803. }
  804. return $results;
  805. }
  806. /**
  807. * Helper function for grabbing search keys.
  808. */
  809. function search_get_keys() {
  810. // Extract keys as remainder of path
  811. // Note: support old GET format of searches for existing links.
  812. $path = explode('/', $_GET['q'], 3);
  813. return count($path) == 3 ? $path[2] : $_REQUEST['keys'];
  814. }
  815. /**
  816. * Menu callback; presents the search form and/or search results.
  817. */
  818. function search_view() {
  819. $type = arg(1);
  820. // Search form submits with POST but redirects to GET. This way we can keep
  821. // the search query URL clean as a whistle:
  822. // search/type/keyword+keyword
  823. if (!isset($_POST['edit']['form_id'])) {
  824. if ($type == '') {
  825. // Note: search/node can not be a default tab because it would take on the
  826. // path of its parent (search). It would prevent remembering keywords when
  827. // switching tabs. This is why we drupal_goto to it from the parent instead.
  828. drupal_goto('search/node');
  829. }
  830. $keys = search_get_keys();
  831. // Only perform search if there is non-whitespace search term:
  832. if (trim($keys)) {
  833. // Log the search keys:
  834. watchdog('search', t('Search: %keys (%type).', array('%keys' => theme('placeholder', $keys), '%type' => module_invoke($type, 'search', 'name'))), WATCHDOG_NOTICE, l(t('results'), 'search/'. $type .'/'. $keys));
  835. // Collect the search results:
  836. $results = search_data($keys, $type);
  837. if ($results) {
  838. $results = theme('box', t('Search results'), $results);
  839. }
  840. else {
  841. $results = theme('box', t('Your search yielded no results'), search_help('search#noresults'));
  842. }
  843. }
  844. // Construct the search form.
  845. $output = search_form(NULL, $keys, $type);
  846. $output .= $results;
  847. return $output;
  848. }
  849. return search_form(NULL, $keys, $type);
  850. }
  851. /**
  852. * @defgroup search Search interface
  853. * @{
  854. * The Drupal search interface manages a global search mechanism.
  855. *
  856. * Modules may plug into this system to provide searches of different types of
  857. * data. Most of the system is handled by search.module, so this must be enabled
  858. * for all of the search features to work.
  859. *
  860. * There are three ways to interact with the search system:
  861. * - Specifically for searching nodes, you can implement nodeapi('update index')
  862. * and nodeapi('search result'). However, note that the search system already
  863. * indexes all visible output of a node, i.e. everything displayed normally
  864. * by hook_view() and hook_nodeapi('view'). This is usually sufficient.
  865. * You should only use this mechanism if you want additional, non-visible data
  866. * to be indexed.
  867. * - Implement hook_search(). This will create a search tab for your module on
  868. * the /search page with a simple keyword search form. You may optionally
  869. * implement hook_search_item() to customize the display of your results.
  870. * - Implement hook_update_index(). This allows your module to use Drupal's
  871. * HTML indexing mechanism for searching full text efficiently.
  872. *
  873. * If your module needs to provide a more complicated search form, then you need
  874. * to implement it yourself without hook_search(). In that case, you should
  875. * define it as a local task (tab) under the /search page (e.g. /search/mymodule)
  876. * so that users can easily find it.
  877. */
  878. /**
  879. * Render a search form.
  880. *
  881. * @param $action
  882. * Form action. Defaults to "search".
  883. * @param $keys
  884. * The search string entered by the user, containing keywords for the search.
  885. * @param $type
  886. * The type of search to render the node for. Must be the name of module
  887. * which implements hook_search(). Defaults to 'node'.
  888. * @param $prompt
  889. * A piece of text to put before the form (e.g. "Enter your keywords")
  890. * @return
  891. * An HTML string containing the search form.
  892. */
  893. function search_form($action = '', $keys = '', $type = NULL, $prompt = NULL) {
  894. if (!$action) {
  895. $action = url('search/'. $type);
  896. }
  897. if (is_null($prompt)) {
  898. $prompt = t('Enter your keywords');
  899. }
  900. $form = array(
  901. '#action' => $action,
  902. '#attributes' => array('class' => 'search-form'),
  903. );
  904. $form['module'] = array('#type' => 'value', '#value' => $type);
  905. $form['basic'] = array('#type' => 'item', '#title' => $prompt);
  906. $form['basic']['inline'] = array('#prefix' => '<div class="container-inline">', '#suffix' => '</div>');
  907. $form['basic']['inline']['keys'] = array(
  908. '#type' => 'textfield',
  909. '#title' => '',
  910. '#default_value' => $keys,
  911. '#size' => $prompt ? 40 : 20,
  912. '#maxlength' => 255,
  913. );
  914. // processed_keys is used to coordinate keyword passing between other forms
  915. // that hook into the basic search form.
  916. $form['basic']['inline']['processed_keys'] = array('#type' => 'value', '#value' => array());
  917. $form['basic']['inline']['submit'] = array('#type' => 'submit', '#value' => t('Search'));
  918. return drupal_get_form('search_form', $form);
  919. }
  920. /**
  921. * As the search form collates keys from other modules hooked in via
  922. * hook_form_alter, the validation takes place in _submit.
  923. * search_form_validate() is used solely to set the 'processed_keys' form
  924. * value for the basic search form.
  925. */
  926. function search_form_validate($form_id, $form_values, $form) {
  927. form_set_value($form['basic']['inline']['processed_keys'], trim($form_values['keys']));
  928. }
  929. /**
  930. * Process a search form submission.
  931. */
  932. function search_form_submit($form_id, $form_values) {
  933. $keys = $form_values['processed_keys'];
  934. if ($keys == '') {
  935. form_set_error('keys', t('Please enter some keywords.'));
  936. // Fall through to the drupal_goto() call.
  937. }
  938. $type = $form_values['module'] ? $form_values['module'] : 'node';
  939. return 'search/'. $type .'/'. $keys;
  940. }
  941. /**
  942. * Output a search form for the search block and the theme's search box.
  943. */
  944. function search_box($form_id = 'search_theme_form') {
  945. // Use search_keys instead of keys to avoid ID conflicts with the search block.
  946. $form[$form_id .'_keys'] = array(
  947. '#type' => 'textfield',
  948. '#size' => 15,
  949. '#default_value' => '',
  950. '#attributes' => array('title' => t('Enter the terms you wish to search for.')),
  951. );
  952. $form['submit'] = array('#type' => 'submit', '#value' => t('Search'));
  953. // Always go to the search page since the search form is not guaranteed to be
  954. // on every page.
  955. $form['#action'] = url('search/node');
  956. return drupal_get_form($form_id, $form, 'search_box_form');
  957. }
  958. /**
  959. * Process a block search form submission.
  960. */
  961. function search_box_form_submit($form_id, $form_values) {
  962. return 'search/node/'. trim($form_values[$form_id .'_keys']);
  963. }
  964. /**
  965. * Theme the theme search form.
  966. */
  967. function theme_search_theme_form($form) {
  968. return '<div id="search" class="container-inline">'. form_render($form) .'</div>';
  969. }
  970. /**
  971. * Theme the block search form.
  972. */
  973. function theme_search_block_form($form) {
  974. return '<div class="container-inline">'. form_render($form) .'</div>';
  975. }
  976. /**
  977. * Perform a standard search on the given keys, and return the formatted results.
  978. */
  979. function search_data($keys = NULL, $type = 'node') {
  980. if (isset($keys)) {
  981. if (module_hook($type, 'search')) {
  982. $results = module_invoke($type, 'search', 'search', $keys);
  983. if (isset($results) && is_array($results) && count($results)) {
  984. if (module_hook($type, 'search_page')) {
  985. return module_invoke($type, 'search_page', $results);
  986. }
  987. else {
  988. return theme('search_page', $results, $type);
  989. }
  990. }
  991. }
  992. }
  993. }
  994. /**
  995. * Returns snippets from a piece of text, with certain keywords highlighted.
  996. * Used for formatting search results.
  997. *
  998. * @param $keys
  999. * A string containing a search query.
  1000. *
  1001. * @param $text
  1002. * The text to extract fragments from.
  1003. *
  1004. * @return
  1005. * A string containing HTML for the excerpt.
  1006. */
  1007. function search_excerpt($keys, $text) {
  1008. // We highlight around non-indexable or CJK characters.
  1009. $boundary = '(?:(?<=['. PREG_CLASS_SEARCH_EXCLUDE . PREG_CLASS_CJK .'])|(?=['. PREG_CLASS_SEARCH_EXCLUDE . PREG_CLASS_CJK .']))';
  1010. // Extract positive keywords and phrases
  1011. preg_match_all('/ ("([^"]+)"|(?!OR)([^" ]+))/', ' '. $keys, $matches);
  1012. $keys = array_merge($matches[2], $matches[3]);
  1013. // Prepare text
  1014. $text = ' '. strip_tags(str_replace(array('<', '>'), array(' <', '> '), $text)) .' ';
  1015. array_walk($keys, '_search_excerpt_replace');
  1016. $workkeys = $keys;
  1017. // Extract a fragment per keyword for at most 4 keywords.
  1018. // First we collect ranges of text around each keyword, starting/ending
  1019. // at spaces.
  1020. // If the sum of all fragments is too short, we look for second occurrences.
  1021. $ranges = array();
  1022. $included = array();
  1023. $length = 0;
  1024. while ($length < 256 && count($workkeys)) {
  1025. foreach ($workkeys as $k => $key) {
  1026. if (strlen($key) == 0) {
  1027. unset($workkeys[$k]);
  1028. unset($keys[$k]);
  1029. continue;
  1030. }
  1031. if ($length >= 256) {
  1032. break;
  1033. }
  1034. // Remember occurrence of key so we can skip over it if more occurrences
  1035. // are desired.
  1036. if (!isset($included[$key])) {
  1037. $included[$key] = 0;
  1038. }
  1039. // Locate a keyword (position $p), then locate a space in front (position
  1040. // $q) and behind it (position $s)
  1041. if (preg_match('/'. $boundary . $key . $boundary .'/iu', $text, $match, PREG_OFFSET_CAPTURE, $included[$key])) {
  1042. $p = $match[0][1];
  1043. if (($q = strpos($text, ' ', max(0, $p - 60))) !== false) {
  1044. $end = substr($text, $p, 80);
  1045. if (($s = strrpos($end, ' ')) !== false) {
  1046. $ranges[$q] = $p + $s;
  1047. $length += $p + $s - $q;
  1048. $included[$key] = $p + 1;
  1049. }
  1050. else {
  1051. unset($workkeys[$k]);
  1052. }
  1053. }
  1054. else {
  1055. unset($workkeys[$k]);
  1056. }
  1057. }
  1058. else {
  1059. unset($workkeys[$k]);
  1060. }
  1061. }
  1062. }
  1063. // If we didn't find anything, return the beginning.
  1064. if (count($ranges) == 0) {
  1065. return truncate_utf8($text, 256) . ' ...';
  1066. }
  1067. // Sort the text ranges by starting position.
  1068. ksort($ranges);
  1069. // Now we collapse overlapping text ranges into one. The sorting makes it O(n).
  1070. $newranges = array();
  1071. foreach ($ranges as $from2 => $to2) {
  1072. if (!isset($from1)) {
  1073. $from1 = $from2;
  1074. $to1 = $to2;
  1075. continue;
  1076. }
  1077. if ($from2 <= $to1) {
  1078. $to1 = max($to1, $to2);
  1079. }
  1080. else {
  1081. $newranges[$from1] = $to1;
  1082. $from1 = $from2;
  1083. $to1 = $to2;
  1084. }
  1085. }
  1086. $newranges[$from1] = $to1;
  1087. // Fetch text
  1088. $out = array();
  1089. foreach ($newranges as $from => $to) {
  1090. $out[] = substr($text, $from, $to - $from);
  1091. }
  1092. $text = (isset($newranges[0]) ? '' : '... '). implode(' ... ', $out) .' ...';
  1093. // Highlight keywords. Must be done at once to prevent conflicts ('strong' and '<strong>').
  1094. $text = preg_replace('/'. $boundary .'('. implode('|', $keys) .')'. $boundary .'/iu', '<strong>\0</strong>', $text);
  1095. return $text;
  1096. }
  1097. /**
  1098. * @} End of "defgroup search".
  1099. */
  1100. /**
  1101. * Helper function for array_walk in search_except.
  1102. */
  1103. function _search_excerpt_replace(&$text) {
  1104. $text = preg_quote($text, '/');
  1105. }
  1106. /**
  1107. * Format a single result entry of a search query. This function is normally
  1108. * called by theme_search_page() or hook_search_page().
  1109. *
  1110. * @param $item
  1111. * A single search result as returned by hook_search(). The result should be
  1112. * an array with keys "link", "title", "type", "user", "date", and "snippet".
  1113. * Optionally, "extra" can be an array of extra info to show along with the
  1114. * result.
  1115. * @param $type
  1116. * The type of item found, such as "user" or "node".
  1117. *
  1118. * @ingroup themeable
  1119. */
  1120. function theme_search_item($item, $type) {
  1121. $output = ' <dt class="title"><a href="'. check_url($item['link']) .'">'. check_plain($item['title']) .'</a></dt>';
  1122. $info = array();
  1123. if ($item['type']) {
  1124. $info[] = $item['type'];
  1125. }
  1126. if ($item['user']) {
  1127. $info[] = $item['user'];
  1128. }
  1129. if ($item['date']) {
  1130. $info[] = format_date($item['date'], 'small');
  1131. }
  1132. if (is_array($item['extra'])) {
  1133. $info = array_merge($info, $item['extra']);
  1134. }
  1135. $output .= ' <dd>'. ($item['snippet'] ? '<p>'. $item['snippet'] . '</p>' : '') . '<p class="search-info">' . implode(' - ', $info) .'</p></dd>';
  1136. return $output;
  1137. }
  1138. /**
  1139. * Format the result page of a search query.
  1140. *
  1141. * Modules may implement hook_search_page() in order to override this default
  1142. * function to display search results. In that case it is expected they provide
  1143. * their own themeable functions.
  1144. *
  1145. * @param $results
  1146. * All search result as returned by hook_search().
  1147. * @param $type
  1148. * The type of item found, such as "user" or "node".
  1149. *
  1150. * @ingroup themeable
  1151. */
  1152. function theme_search_page($results, $type) {
  1153. $output = '<dl class="search-results">';
  1154. foreach ($results as $entry) {
  1155. $output .= theme('search_item', $entry, $type);
  1156. }
  1157. $output .= '</dl>';
  1158. $output .= theme('pager', NULL, 10, 0);
  1159. return $output;
  1160. }
Login or register to post comments