search.module 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356
  1. <?php
  2. /**
  3. * @file
  4. * Enables site-wide keyword searching.
  5. */
  6. /**
  7. * Matches all 'N' Unicode character classes (numbers)
  8. */
  9. define('PREG_CLASS_NUMBERS',
  10. '\x{30}-\x{39}\x{b2}\x{b3}\x{b9}\x{bc}-\x{be}\x{660}-\x{669}\x{6f0}-\x{6f9}' .
  11. '\x{966}-\x{96f}\x{9e6}-\x{9ef}\x{9f4}-\x{9f9}\x{a66}-\x{a6f}\x{ae6}-\x{aef}' .
  12. '\x{b66}-\x{b6f}\x{be7}-\x{bf2}\x{c66}-\x{c6f}\x{ce6}-\x{cef}\x{d66}-\x{d6f}' .
  13. '\x{e50}-\x{e59}\x{ed0}-\x{ed9}\x{f20}-\x{f33}\x{1040}-\x{1049}\x{1369}-' .
  14. '\x{137c}\x{16ee}-\x{16f0}\x{17e0}-\x{17e9}\x{17f0}-\x{17f9}\x{1810}-\x{1819}' .
  15. '\x{1946}-\x{194f}\x{2070}\x{2074}-\x{2079}\x{2080}-\x{2089}\x{2153}-\x{2183}' .
  16. '\x{2460}-\x{249b}\x{24ea}-\x{24ff}\x{2776}-\x{2793}\x{3007}\x{3021}-\x{3029}' .
  17. '\x{3038}-\x{303a}\x{3192}-\x{3195}\x{3220}-\x{3229}\x{3251}-\x{325f}\x{3280}-' .
  18. '\x{3289}\x{32b1}-\x{32bf}\x{ff10}-\x{ff19}');
  19. /**
  20. * Matches all 'P' Unicode character classes (punctuation)
  21. */
  22. define('PREG_CLASS_PUNCTUATION',
  23. '\x{21}-\x{23}\x{25}-\x{2a}\x{2c}-\x{2f}\x{3a}\x{3b}\x{3f}\x{40}\x{5b}-\x{5d}' .
  24. '\x{5f}\x{7b}\x{7d}\x{a1}\x{ab}\x{b7}\x{bb}\x{bf}\x{37e}\x{387}\x{55a}-\x{55f}' .
  25. '\x{589}\x{58a}\x{5be}\x{5c0}\x{5c3}\x{5f3}\x{5f4}\x{60c}\x{60d}\x{61b}\x{61f}' .
  26. '\x{66a}-\x{66d}\x{6d4}\x{700}-\x{70d}\x{964}\x{965}\x{970}\x{df4}\x{e4f}' .
  27. '\x{e5a}\x{e5b}\x{f04}-\x{f12}\x{f3a}-\x{f3d}\x{f85}\x{104a}-\x{104f}\x{10fb}' .
  28. '\x{1361}-\x{1368}\x{166d}\x{166e}\x{169b}\x{169c}\x{16eb}-\x{16ed}\x{1735}' .
  29. '\x{1736}\x{17d4}-\x{17d6}\x{17d8}-\x{17da}\x{1800}-\x{180a}\x{1944}\x{1945}' .
  30. '\x{2010}-\x{2027}\x{2030}-\x{2043}\x{2045}-\x{2051}\x{2053}\x{2054}\x{2057}' .
  31. '\x{207d}\x{207e}\x{208d}\x{208e}\x{2329}\x{232a}\x{23b4}-\x{23b6}\x{2768}-' .
  32. '\x{2775}\x{27e6}-\x{27eb}\x{2983}-\x{2998}\x{29d8}-\x{29db}\x{29fc}\x{29fd}' .
  33. '\x{3001}-\x{3003}\x{3008}-\x{3011}\x{3014}-\x{301f}\x{3030}\x{303d}\x{30a0}' .
  34. '\x{30fb}\x{fd3e}\x{fd3f}\x{fe30}-\x{fe52}\x{fe54}-\x{fe61}\x{fe63}\x{fe68}' .
  35. '\x{fe6a}\x{fe6b}\x{ff01}-\x{ff03}\x{ff05}-\x{ff0a}\x{ff0c}-\x{ff0f}\x{ff1a}' .
  36. '\x{ff1b}\x{ff1f}\x{ff20}\x{ff3b}-\x{ff3d}\x{ff3f}\x{ff5b}\x{ff5d}\x{ff5f}-' .
  37. '\x{ff65}');
  38. /**
  39. * Matches CJK (Chinese, Japanese, Korean) letter-like characters.
  40. *
  41. * This list is derived from the "East Asian Scripts" section of
  42. * http://www.unicode.org/charts/index.html, as well as a comment on
  43. * http://unicode.org/reports/tr11/tr11-11.html listing some character
  44. * ranges that are reserved for additional CJK ideographs.
  45. *
  46. * The character ranges do not include numbers, punctuation, or symbols, since
  47. * these are handled separately in search. Note that radicals and strokes are
  48. * considered symbols. (See
  49. * http://www.unicode.org/Public/UNIDATA/extracted/DerivedGeneralCategory.txt)
  50. *
  51. * @see search_expand_cjk()
  52. */
  53. define('PREG_CLASS_CJK', '\x{1100}-\x{11FF}\x{3040}-\x{309F}\x{30A1}-\x{318E}' .
  54. '\x{31A0}-\x{31B7}\x{31F0}-\x{31FF}\x{3400}-\x{4DBF}\x{4E00}-\x{9FCF}' .
  55. '\x{A000}-\x{A48F}\x{A4D0}-\x{A4FD}\x{A960}-\x{A97F}\x{AC00}-\x{D7FF}' .
  56. '\x{F900}-\x{FAFF}\x{FF21}-\x{FF3A}\x{FF41}-\x{FF5A}\x{FF66}-\x{FFDC}' .
  57. '\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}');
  58. /**
  59. * Implements hook_help().
  60. */
  61. function search_help($path, $arg) {
  62. switch ($path) {
  63. case 'admin/help#search':
  64. $output = '';
  65. $output .= '<h3>' . t('About') . '</h3>';
  66. $output .= '<p>' . t('The Search module provides the ability to index and search for content by exact keywords, and for users by username or e-mail. For more information, see the online handbook entry for <a href="@search-module">Search module</a>.', array('@search-module' => 'http://drupal.org/documentation/modules/search/', '@search' => url('search'))) . '</p>';
  67. $output .= '<h3>' . t('Uses') . '</h3>';
  68. $output .= '<dl>';
  69. $output .= '<dt>' . t('Searching content and users') . '</dt>';
  70. $output .= '<dd>' . t('Users with <em>Use search</em> permission can use the search block and <a href="@search">Search page</a>. Users with the <em>View published content</em> permission can search for content containing exact keywords. Users with the <em>View user profiles</em> permission can search for users containing the keyword anywhere in the user name, and users with the <em>Administer users</em> permission can search for users by email address. Additionally, users with <em>Use advanced search</em> permission can find content using more complex search methods and filtering by choosing the <em>Advanced search</em> option on the <a href="@search">Search page</a>.', array('@search' => url('search'))) . '</dd>';
  71. $output .= '<dt>' . t('Indexing content with cron') . '</dt>';
  72. $output .= '<dd>' . t('To provide keyword searching, the search engine maintains an index of words found in the content and its fields, along with text added to your content by other modules (such as comments from the core Comment module, and taxonomy terms from the core Taxonomy module). To build and maintain this index, a correctly configured <a href="@cron">cron maintenance task</a> is required. Users with <em>Administer search</em> permission can further configure the cron settings on the <a href="@searchsettings">Search settings page</a>.', array('@cron' => 'http://drupal.org/cron', '@searchsettings' => url('admin/config/search/settings'))) . '</dd>';
  73. $output .= '<dt>' . t('Content reindexing') . '</dt>';
  74. $output .= '<dd>' . t('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. Unlike content-related actions, actions related to the structure of your site 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="@searchsettings">Search settings 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('@searchsettings' => url('admin/config/search/settings'))) . '</dd>';
  75. $output .= '<dt>' . t('Configuring search settings') . '</dt>';
  76. $output .= '<dd>' . t('Indexing behavior can be adjusted using the <a href="@searchsettings">Search settings page</a>. Users with <em>Administer search</em> permission can control settings such as the <em>Number of items to index per cron run</em>, <em>Indexing settings</em> (word length), <em>Active search modules</em>, and <em>Content ranking</em>, which lets you adjust the priority in which indexed content is returned in results.', array('@searchsettings' => url('admin/config/search/settings'))) . '</dd>';
  77. $output .= '<dt>' . t('Search block') . '</dt>';
  78. $output .= '<dd>' . t('The Search module includes a default <em>Search form</em> block, which can be enabled and configured on the <a href="@blocks">Blocks administration page</a>. The block is available to users with the <em>Search content</em> permission.', array('@blocks' => url('admin/structure/block'))) . '</dd>';
  79. $output .= '<dt>' . t('Extending Search module') . '</dt>';
  80. $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="http://drupal.org/project/porterstemmer">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="http://drupal.org/project/apachesolr">Apache Solr</a> or <a href="http://drupal.org/project/sphinx">Sphinx</a>. These and other <a href="@contrib-search">search-related contributed modules</a> can be downloaded by visiting Drupal.org.', array('@contrib-search' => 'http://drupal.org/project/modules?filters=tid%3A105')) . '</dd>';
  81. $output .= '</dl>';
  82. return $output;
  83. case 'admin/config/search/settings':
  84. 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>';
  85. case 'search#noresults':
  86. return t('<ul>
  87. <li>Check if your spelling is correct.</li>
  88. <li>Remove quotes around phrases to search for each word individually. <em>bike shed</em> will often show more results than <em>&quot;bike shed&quot;</em>.</li>
  89. <li>Consider loosening your query with <em>OR</em>. <em>bike OR shed</em> will often show more results than <em>bike shed</em>.</li>
  90. </ul>');
  91. }
  92. }
  93. /**
  94. * Implements hook_theme().
  95. */
  96. function search_theme() {
  97. return array(
  98. 'search_block_form' => array(
  99. 'render element' => 'form',
  100. 'template' => 'search-block-form',
  101. ),
  102. 'search_result' => array(
  103. 'variables' => array('result' => NULL, 'module' => NULL),
  104. 'file' => 'search.pages.inc',
  105. 'template' => 'search-result',
  106. ),
  107. 'search_results' => array(
  108. 'variables' => array('results' => NULL, 'module' => NULL),
  109. 'file' => 'search.pages.inc',
  110. 'template' => 'search-results',
  111. ),
  112. );
  113. }
  114. /**
  115. * Implements hook_permission().
  116. */
  117. function search_permission() {
  118. return array(
  119. 'administer search' => array(
  120. 'title' => t('Administer search'),
  121. ),
  122. 'search content' => array(
  123. 'title' => t('Use search'),
  124. ),
  125. 'use advanced search' => array(
  126. 'title' => t('Use advanced search'),
  127. ),
  128. );
  129. }
  130. /**
  131. * Implements hook_block_info().
  132. */
  133. function search_block_info() {
  134. $blocks['form']['info'] = t('Search form');
  135. // Not worth caching.
  136. $blocks['form']['cache'] = DRUPAL_NO_CACHE;
  137. $blocks['form']['properties']['administrative'] = TRUE;
  138. return $blocks;
  139. }
  140. /**
  141. * Implements hook_block_view().
  142. */
  143. function search_block_view($delta = '') {
  144. if (user_access('search content')) {
  145. $block['content'] = drupal_get_form('search_block_form');
  146. return $block;
  147. }
  148. }
  149. /**
  150. * Implements hook_menu().
  151. */
  152. function search_menu() {
  153. $items['search'] = array(
  154. 'title' => 'Search',
  155. 'page callback' => 'search_view',
  156. 'access callback' => 'search_is_active',
  157. 'type' => MENU_SUGGESTED_ITEM,
  158. 'file' => 'search.pages.inc',
  159. );
  160. $items['admin/config/search/settings'] = array(
  161. 'title' => 'Search settings',
  162. 'description' => 'Configure relevance settings for search and other indexing options.',
  163. 'page callback' => 'drupal_get_form',
  164. 'page arguments' => array('search_admin_settings'),
  165. 'access arguments' => array('administer search'),
  166. 'weight' => -10,
  167. 'file' => 'search.admin.inc',
  168. );
  169. $items['admin/config/search/settings/reindex'] = array(
  170. 'title' => 'Clear index',
  171. 'page callback' => 'drupal_get_form',
  172. 'page arguments' => array('search_reindex_confirm'),
  173. 'access arguments' => array('administer search'),
  174. 'type' => MENU_VISIBLE_IN_BREADCRUMB,
  175. 'file' => 'search.admin.inc',
  176. );
  177. // Add paths for searching. We add each module search path twice: once without
  178. // and once with %menu_tail appended. The reason for this is that we want to
  179. // preserve keywords when switching tabs, and also to have search tabs
  180. // highlighted properly. The only way to do that within the Drupal menu
  181. // system appears to be having two sets of tabs. See discussion on issue
  182. // http://drupal.org/node/245103 for details.
  183. drupal_static_reset('search_get_info');
  184. $default_info = search_get_default_module_info();
  185. if ($default_info) {
  186. foreach (search_get_info() as $module => $search_info) {
  187. $path = 'search/' . $search_info['path'];
  188. $items[$path] = array(
  189. 'title' => $search_info['title'],
  190. 'page callback' => 'search_view',
  191. 'page arguments' => array($module, ''),
  192. 'access callback' => '_search_menu_access',
  193. 'access arguments' => array($module),
  194. 'type' => MENU_LOCAL_TASK,
  195. 'file' => 'search.pages.inc',
  196. 'weight' => $module == $default_info['module'] ? -10 : 0,
  197. );
  198. $items["$path/%menu_tail"] = array(
  199. 'title' => $search_info['title'],
  200. 'load arguments' => array('%map', '%index'),
  201. 'page callback' => 'search_view',
  202. 'page arguments' => array($module, 2),
  203. 'access callback' => '_search_menu_access',
  204. 'access arguments' => array($module),
  205. // The default local task points to its parent, but this item points to
  206. // where it should so it should not be changed.
  207. 'type' => MENU_LOCAL_TASK,
  208. 'file' => 'search.pages.inc',
  209. 'weight' => 0,
  210. // These tabs are not subtabs.
  211. 'tab_root' => 'search/' . $default_info['path'] . '/%',
  212. // These tabs need to display at the same level.
  213. 'tab_parent' => 'search/' . $default_info['path'],
  214. );
  215. }
  216. }
  217. return $items;
  218. }
  219. /**
  220. * Determines access for the ?q=search path.
  221. */
  222. function search_is_active() {
  223. // This path cannot be accessed if there are no active modules.
  224. return user_access('search content') && search_get_info();
  225. }
  226. /**
  227. * Returns information about available search modules.
  228. *
  229. * @param $all
  230. * If TRUE, information about all enabled modules implementing
  231. * hook_search_info() will be returned. If FALSE (default), only modules that
  232. * have been set to active on the search settings page will be returned.
  233. *
  234. * @return
  235. * Array of hook_search_info() return values, keyed by module name. The
  236. * 'title' and 'path' array elements will be set to defaults for each module
  237. * if not supplied by hook_search_info(), and an additional array element of
  238. * 'module' will be added (set to the module name).
  239. */
  240. function search_get_info($all = FALSE) {
  241. $search_hooks = &drupal_static(__FUNCTION__);
  242. if (!isset($search_hooks)) {
  243. foreach (module_implements('search_info') as $module) {
  244. $search_hooks[$module] = call_user_func($module . '_search_info');
  245. // Use module name as the default value.
  246. $search_hooks[$module] += array('title' => $module, 'path' => $module);
  247. // Include the module name itself in the array.
  248. $search_hooks[$module]['module'] = $module;
  249. }
  250. }
  251. if ($all) {
  252. return $search_hooks;
  253. }
  254. $active = variable_get('search_active_modules', array('node', 'user'));
  255. return array_intersect_key($search_hooks, array_flip($active));
  256. }
  257. /**
  258. * Returns information about the default search module.
  259. *
  260. * @return
  261. * The search_get_info() array element for the default search module, if any.
  262. */
  263. function search_get_default_module_info() {
  264. $info = search_get_info();
  265. $default = variable_get('search_default_module', 'node');
  266. if (isset($info[$default])) {
  267. return $info[$default];
  268. }
  269. // The variable setting does not match any active module, so just return
  270. // the info for the first active module (if any).
  271. return reset($info);
  272. }
  273. /**
  274. * Access callback for search tabs.
  275. */
  276. function _search_menu_access($name) {
  277. return user_access('search content') && (!function_exists($name . '_search_access') || module_invoke($name, 'search_access'));
  278. }
  279. /**
  280. * Clears a part of or the entire search index.
  281. *
  282. * @param $sid
  283. * (optional) The ID of the item to remove from the search index. If
  284. * specified, $module must also be given. Omit both $sid and $module to clear
  285. * the entire search index.
  286. * @param $module
  287. * (optional) The machine-readable name of the module for the item to remove
  288. * from the search index.
  289. */
  290. function search_reindex($sid = NULL, $module = NULL, $reindex = FALSE) {
  291. if ($module == NULL && $sid == NULL) {
  292. module_invoke_all('search_reset');
  293. }
  294. else {
  295. db_delete('search_dataset')
  296. ->condition('sid', $sid)
  297. ->condition('type', $module)
  298. ->execute();
  299. db_delete('search_index')
  300. ->condition('sid', $sid)
  301. ->condition('type', $module)
  302. ->execute();
  303. // Don't remove links if re-indexing.
  304. if (!$reindex) {
  305. db_delete('search_node_links')
  306. ->condition('sid', $sid)
  307. ->condition('type', $module)
  308. ->execute();
  309. }
  310. }
  311. }
  312. /**
  313. * Marks a word as "dirty" (changed), or retrieves the list of dirty words.
  314. *
  315. * This is used during indexing (cron). Words that are dirty have outdated
  316. * total counts in the search_total table, and need to be recounted.
  317. */
  318. function search_dirty($word = NULL) {
  319. $dirty = &drupal_static(__FUNCTION__, array());
  320. if ($word !== NULL) {
  321. $dirty[$word] = TRUE;
  322. }
  323. else {
  324. return $dirty;
  325. }
  326. }
  327. /**
  328. * Implements hook_cron().
  329. *
  330. * Fires hook_update_index() in all modules and cleans up dirty words.
  331. *
  332. * @see search_dirty()
  333. */
  334. function search_cron() {
  335. // We register a shutdown function to ensure that search_total is always up
  336. // to date.
  337. drupal_register_shutdown_function('search_update_totals');
  338. foreach (variable_get('search_active_modules', array('node', 'user')) as $module) {
  339. // Update word index
  340. module_invoke($module, 'update_index');
  341. }
  342. }
  343. /**
  344. * Updates the {search_total} database table.
  345. *
  346. * This function is called on shutdown to ensure that {search_total} is always
  347. * up to date (even if cron times out or otherwise fails).
  348. */
  349. function search_update_totals() {
  350. // Update word IDF (Inverse Document Frequency) counts for new/changed words.
  351. foreach (search_dirty() as $word => $dummy) {
  352. // Get total count
  353. $total = db_query("SELECT SUM(score) FROM {search_index} WHERE word = :word", array(':word' => $word), array('target' => 'slave'))->fetchField();
  354. // Apply Zipf's law to equalize the probability distribution.
  355. $total = log10(1 + 1/(max(1, $total)));
  356. db_merge('search_total')
  357. ->key(array('word' => $word))
  358. ->fields(array('count' => $total))
  359. ->execute();
  360. }
  361. // Find words that were deleted from search_index, but are still in
  362. // search_total. We use a LEFT JOIN between the two tables and keep only the
  363. // rows which fail to join.
  364. $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' => 'slave'));
  365. $or = db_or();
  366. foreach ($result as $word) {
  367. $or->condition('word', $word->realword);
  368. }
  369. if (count($or) > 0) {
  370. db_delete('search_total')
  371. ->condition($or)
  372. ->execute();
  373. }
  374. }
  375. /**
  376. * Simplifies a string according to indexing rules.
  377. *
  378. * @param $text
  379. * Text to simplify.
  380. *
  381. * @return
  382. * Simplified text.
  383. *
  384. * @see hook_search_preprocess()
  385. */
  386. function search_simplify($text) {
  387. // Decode entities to UTF-8
  388. $text = decode_entities($text);
  389. // Lowercase
  390. $text = drupal_strtolower($text);
  391. // Call an external processor for word handling.
  392. search_invoke_preprocess($text);
  393. // Simple CJK handling
  394. if (variable_get('overlap_cjk', TRUE)) {
  395. $text = preg_replace_callback('/[' . PREG_CLASS_CJK . ']+/u', 'search_expand_cjk', $text);
  396. }
  397. // To improve searching for numerical data such as dates, IP addresses
  398. // or version numbers, we consider a group of numerical characters
  399. // separated only by punctuation characters to be one piece.
  400. // This also means that searching for e.g. '20/03/1984' also returns
  401. // results with '20-03-1984' in them.
  402. // Readable regexp: ([number]+)[punctuation]+(?=[number])
  403. $text = preg_replace('/([' . PREG_CLASS_NUMBERS . ']+)[' . PREG_CLASS_PUNCTUATION . ']+(?=[' . PREG_CLASS_NUMBERS . '])/u', '\1', $text);
  404. // Multiple dot and dash groups are word boundaries and replaced with space.
  405. // No need to use the unicode modifer here because 0-127 ASCII characters
  406. // can't match higher UTF-8 characters as the leftmost bit of those are 1.
  407. $text = preg_replace('/[.-]{2,}/', ' ', $text);
  408. // The dot, underscore and dash are simply removed. This allows meaningful
  409. // search behavior with acronyms and URLs. See unicode note directly above.
  410. $text = preg_replace('/[._-]+/', '', $text);
  411. // With the exception of the rules above, we consider all punctuation,
  412. // marks, spacers, etc, to be a word boundary.
  413. $text = preg_replace('/[' . PREG_CLASS_UNICODE_WORD_BOUNDARY . ']+/u', ' ', $text);
  414. // Truncate everything to 50 characters.
  415. $words = explode(' ', $text);
  416. array_walk($words, '_search_index_truncate');
  417. $text = implode(' ', $words);
  418. return $text;
  419. }
  420. /**
  421. * Splits CJK (Chinese, Japanese, Korean) text into tokens.
  422. *
  423. * The Search module matches exact words, where a word is defined to be a
  424. * sequence of characters delimited by spaces or punctuation. CJK languages are
  425. * written in long strings of characters, though, not split up into words. So
  426. * in order to allow search matching, we split up CJK text into tokens
  427. * consisting of consecutive, overlapping sequences of characters whose length
  428. * is equal to the 'minimum_word_size' variable. This tokenizing is only done if
  429. * the 'overlap_cjk' variable is TRUE.
  430. *
  431. * @param $matches
  432. * This function is a callback for preg_replace_callback(), which is called
  433. * from search_simplify(). So, $matches is an array of regular expression
  434. * matches, which means that $matches[0] contains the matched text -- a string
  435. * of CJK characters to tokenize.
  436. *
  437. * @return
  438. * Tokenized text, starting and ending with a space character.
  439. */
  440. function search_expand_cjk($matches) {
  441. $min = variable_get('minimum_word_size', 3);
  442. $str = $matches[0];
  443. $length = drupal_strlen($str);
  444. // If the text is shorter than the minimum word size, don't tokenize it.
  445. if ($length <= $min) {
  446. return ' ' . $str . ' ';
  447. }
  448. $tokens = ' ';
  449. // Build a FIFO queue of characters.
  450. $chars = array();
  451. for ($i = 0; $i < $length; $i++) {
  452. // Add the next character off the beginning of the string to the queue.
  453. $current = drupal_substr($str, 0, 1);
  454. $str = substr($str, strlen($current));
  455. $chars[] = $current;
  456. if ($i >= $min - 1) {
  457. // Make a token of $min characters, and add it to the token string.
  458. $tokens .= implode('', $chars) . ' ';
  459. // Shift out the first character in the queue.
  460. array_shift($chars);
  461. }
  462. }
  463. return $tokens;
  464. }
  465. /**
  466. * Simplifies and splits a string into tokens for indexing.
  467. */
  468. function search_index_split($text) {
  469. $last = &drupal_static(__FUNCTION__);
  470. $lastsplit = &drupal_static(__FUNCTION__ . ':lastsplit');
  471. if ($last == $text) {
  472. return $lastsplit;
  473. }
  474. // Process words
  475. $text = search_simplify($text);
  476. $words = explode(' ', $text);
  477. // Save last keyword result
  478. $last = $text;
  479. $lastsplit = $words;
  480. return $words;
  481. }
  482. /**
  483. * Helper function for array_walk in search_index_split.
  484. */
  485. function _search_index_truncate(&$text) {
  486. if (is_numeric($text)) {
  487. $text = ltrim($text, '0');
  488. }
  489. $text = truncate_utf8($text, 50);
  490. }
  491. /**
  492. * Invokes hook_search_preprocess() in modules.
  493. */
  494. function search_invoke_preprocess(&$text) {
  495. foreach (module_implements('search_preprocess') as $module) {
  496. $text = module_invoke($module, 'search_preprocess', $text);
  497. }
  498. }
  499. /**
  500. * Update the full-text search index for a particular item.
  501. *
  502. * @param $sid
  503. * An ID number identifying this particular item (e.g., node ID).
  504. * @param $module
  505. * The machine-readable name of the module that this item comes from (a module
  506. * that implements hook_search_info()).
  507. * @param $text
  508. * The content of this item. Must be a piece of HTML or plain text.
  509. *
  510. * @ingroup search
  511. */
  512. function search_index($sid, $module, $text) {
  513. $minimum_word_size = variable_get('minimum_word_size', 3);
  514. // Link matching
  515. global $base_url;
  516. $node_regexp = '@href=[\'"]?(?:' . preg_quote($base_url, '@') . '/|' . preg_quote(base_path(), '@') . ')(?:\?q=)?/?((?![a-z]+:)[^\'">]+)[\'">]@i';
  517. // Multipliers for scores of words inside certain HTML tags. The weights are stored
  518. // in a variable so that modules can overwrite the default weights.
  519. // Note: 'a' must be included for link ranking to work.
  520. $tags = variable_get('search_tag_weights', array(
  521. 'h1' => 25,
  522. 'h2' => 18,
  523. 'h3' => 15,
  524. 'h4' => 12,
  525. 'h5' => 9,
  526. 'h6' => 6,
  527. 'u' => 3,
  528. 'b' => 3,
  529. 'i' => 3,
  530. 'strong' => 3,
  531. 'em' => 3,
  532. 'a' => 10));
  533. // Strip off all ignored tags to speed up processing, but insert space before/after
  534. // them to keep word boundaries.
  535. $text = str_replace(array('<', '>'), array(' <', '> '), $text);
  536. $text = strip_tags($text, '<' . implode('><', array_keys($tags)) . '>');
  537. // Split HTML tags from plain text.
  538. $split = preg_split('/\s*<([^>]+?)>\s*/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  539. // Note: PHP ensures the array consists of alternating delimiters and literals
  540. // and begins and ends with a literal (inserting $null as required).
  541. $tag = FALSE; // Odd/even counter. Tag or no tag.
  542. $link = FALSE; // State variable for link analyzer
  543. $score = 1; // Starting score per word
  544. $accum = ' '; // Accumulator for cleaned up data
  545. $tagstack = array(); // Stack with open tags
  546. $tagwords = 0; // Counter for consecutive words
  547. $focus = 1; // Focus state
  548. $results = array(0 => array()); // Accumulator for words for index
  549. foreach ($split as $value) {
  550. if ($tag) {
  551. // Increase or decrease score per word based on tag
  552. list($tagname) = explode(' ', $value, 2);
  553. $tagname = drupal_strtolower($tagname);
  554. // Closing or opening tag?
  555. if ($tagname[0] == '/') {
  556. $tagname = substr($tagname, 1);
  557. // If we encounter unexpected tags, reset score to avoid incorrect boosting.
  558. if (!count($tagstack) || $tagstack[0] != $tagname) {
  559. $tagstack = array();
  560. $score = 1;
  561. }
  562. else {
  563. // Remove from tag stack and decrement score
  564. $score = max(1, $score - $tags[array_shift($tagstack)]);
  565. }
  566. if ($tagname == 'a') {
  567. $link = FALSE;
  568. }
  569. }
  570. else {
  571. if (isset($tagstack[0]) && $tagstack[0] == $tagname) {
  572. // None of the tags we look for make sense when nested identically.
  573. // If they are, it's probably broken HTML.
  574. $tagstack = array();
  575. $score = 1;
  576. }
  577. else {
  578. // Add to open tag stack and increment score
  579. array_unshift($tagstack, $tagname);
  580. $score += $tags[$tagname];
  581. }
  582. if ($tagname == 'a') {
  583. // Check if link points to a node on this site
  584. if (preg_match($node_regexp, $value, $match)) {
  585. $path = drupal_get_normal_path($match[1]);
  586. if (preg_match('!(?:node|book)/(?:view/)?([0-9]+)!i', $path, $match)) {
  587. $linknid = $match[1];
  588. if ($linknid > 0) {
  589. $node = db_query('SELECT title, nid, vid FROM {node} WHERE nid = :nid', array(':nid' => $linknid), array('target' => 'slave'))->fetchObject();
  590. $link = TRUE;
  591. $linktitle = $node->title;
  592. }
  593. }
  594. }
  595. }
  596. }
  597. // A tag change occurred, reset counter.
  598. $tagwords = 0;
  599. }
  600. else {
  601. // Note: use of PREG_SPLIT_DELIM_CAPTURE above will introduce empty values
  602. if ($value != '') {
  603. if ($link) {
  604. // Check to see if the node link text is its URL. If so, we use the target node title instead.
  605. if (preg_match('!^https?://!i', $value)) {
  606. $value = $linktitle;
  607. }
  608. }
  609. $words = search_index_split($value);
  610. foreach ($words as $word) {
  611. // Add word to accumulator
  612. $accum .= $word . ' ';
  613. // Check wordlength
  614. if (is_numeric($word) || drupal_strlen($word) >= $minimum_word_size) {
  615. // Links score mainly for the target.
  616. if ($link) {
  617. if (!isset($results[$linknid])) {
  618. $results[$linknid] = array();
  619. }
  620. $results[$linknid][] = $word;
  621. // Reduce score of the link caption in the source.
  622. $focus *= 0.2;
  623. }
  624. // Fall-through
  625. if (!isset($results[0][$word])) {
  626. $results[0][$word] = 0;
  627. }
  628. $results[0][$word] += $score * $focus;
  629. // Focus is a decaying value in terms of the amount of unique words up to this point.
  630. // From 100 words and more, it decays, to e.g. 0.5 at 500 words and 0.3 at 1000 words.
  631. $focus = min(1, .01 + 3.5 / (2 + count($results[0]) * .015));
  632. }
  633. $tagwords++;
  634. // Too many words inside a single tag probably mean a tag was accidentally left open.
  635. if (count($tagstack) && $tagwords >= 15) {
  636. $tagstack = array();
  637. $score = 1;
  638. }
  639. }
  640. }
  641. }
  642. $tag = !$tag;
  643. }
  644. search_reindex($sid, $module, TRUE);
  645. // Insert cleaned up data into dataset
  646. db_insert('search_dataset')
  647. ->fields(array(
  648. 'sid' => $sid,
  649. 'type' => $module,
  650. 'data' => $accum,
  651. 'reindex' => 0,
  652. ))
  653. ->execute();
  654. // Insert results into search index
  655. foreach ($results[0] as $word => $score) {
  656. // If a word already exists in the database, its score gets increased
  657. // appropriately. If not, we create a new record with the appropriate
  658. // starting score.
  659. db_merge('search_index')
  660. ->key(array(
  661. 'word' => $word,
  662. 'sid' => $sid,
  663. 'type' => $module,
  664. ))
  665. ->fields(array('score' => $score))
  666. ->expression('score', 'score + :score', array(':score' => $score))
  667. ->execute();
  668. search_dirty($word);
  669. }
  670. unset($results[0]);
  671. // Get all previous links from this item.
  672. $result = db_query("SELECT nid, caption FROM {search_node_links} WHERE sid = :sid AND type = :type", array(
  673. ':sid' => $sid,
  674. ':type' => $module
  675. ), array('target' => 'slave'));
  676. $links = array();
  677. foreach ($result as $link) {
  678. $links[$link->nid] = $link->caption;
  679. }
  680. // Now store links to nodes.
  681. foreach ($results as $nid => $words) {
  682. $caption = implode(' ', $words);
  683. if (isset($links[$nid])) {
  684. if ($links[$nid] != $caption) {
  685. // Update the existing link and mark the node for reindexing.
  686. db_update('search_node_links')
  687. ->fields(array('caption' => $caption))
  688. ->condition('sid', $sid)
  689. ->condition('type', $module)
  690. ->condition('nid', $nid)
  691. ->execute();
  692. search_touch_node($nid);
  693. }
  694. // Unset the link to mark it as processed.
  695. unset($links[$nid]);
  696. }
  697. elseif ($sid != $nid || $module != 'node') {
  698. // Insert the existing link and mark the node for reindexing, but don't
  699. // reindex if this is a link in a node pointing to itself.
  700. db_insert('search_node_links')
  701. ->fields(array(
  702. 'caption' => $caption,
  703. 'sid' => $sid,
  704. 'type' => $module,
  705. 'nid' => $nid,
  706. ))
  707. ->execute();
  708. search_touch_node($nid);
  709. }
  710. }
  711. // Any left-over links in $links no longer exist. Delete them and mark the nodes for reindexing.
  712. foreach ($links as $nid => $caption) {
  713. db_delete('search_node_links')
  714. ->condition('sid', $sid)
  715. ->condition('type', $module)
  716. ->condition('nid', $nid)
  717. ->execute();
  718. search_touch_node($nid);
  719. }
  720. }
  721. /**
  722. * Changes a node's changed timestamp to 'now' to force reindexing.
  723. *
  724. * @param $nid
  725. * The node ID of the node that needs reindexing.
  726. */
  727. function search_touch_node($nid) {
  728. db_update('search_dataset')
  729. ->fields(array('reindex' => REQUEST_TIME))
  730. ->condition('type', 'node')
  731. ->condition('sid', $nid)
  732. ->execute();
  733. }
  734. /**
  735. * Implements hook_node_update_index().
  736. */
  737. function search_node_update_index($node) {
  738. // Transplant links to a node into the target node.
  739. $result = db_query("SELECT caption FROM {search_node_links} WHERE nid = :nid", array(':nid' => $node->nid), array('target' => 'slave'));
  740. $output = array();
  741. foreach ($result as $link) {
  742. $output[] = $link->caption;
  743. }
  744. if (count($output)) {
  745. return '<a>(' . implode(', ', $output) . ')</a>';
  746. }
  747. }
  748. /**
  749. * Implements hook_node_update().
  750. */
  751. function search_node_update($node) {
  752. // Reindex the node when it is updated. The node is automatically indexed
  753. // when it is added, simply by being added to the node table.
  754. search_touch_node($node->nid);
  755. }
  756. /**
  757. * Implements hook_comment_insert().
  758. */
  759. function search_comment_insert($comment) {
  760. // Reindex the node when comments are added.
  761. search_touch_node($comment->nid);
  762. }
  763. /**
  764. * Implements hook_comment_update().
  765. */
  766. function search_comment_update($comment) {
  767. // Reindex the node when comments are changed.
  768. search_touch_node($comment->nid);
  769. }
  770. /**
  771. * Implements hook_comment_delete().
  772. */
  773. function search_comment_delete($comment) {
  774. // Reindex the node when comments are deleted.
  775. search_touch_node($comment->nid);
  776. }
  777. /**
  778. * Implements hook_comment_publish().
  779. */
  780. function search_comment_publish($comment) {
  781. // Reindex the node when comments are published.
  782. search_touch_node($comment->nid);
  783. }
  784. /**
  785. * Implements hook_comment_unpublish().
  786. */
  787. function search_comment_unpublish($comment) {
  788. // Reindex the node when comments are unpublished.
  789. search_touch_node($comment->nid);
  790. }
  791. /**
  792. * Extracts a module-specific search option from a search expression.
  793. *
  794. * Search options are added using search_expression_insert(), and retrieved
  795. * using search_expression_extract(). They take the form option:value, and
  796. * are added to the ordinary keywords in the search expression.
  797. *
  798. * @param $expression
  799. * The search expression to extract from.
  800. * @param $option
  801. * The name of the option to retrieve from the search expression.
  802. *
  803. * @return
  804. * The value previously stored in the search expression for option $option,
  805. * if any. Trailing spaces in values will not be included.
  806. */
  807. function search_expression_extract($expression, $option) {
  808. if (preg_match('/(^| )' . $option . ':([^ ]*)( |$)/i', $expression, $matches)) {
  809. return $matches[2];
  810. }
  811. }
  812. /**
  813. * Adds a module-specific search option to a search expression.
  814. *
  815. * Search options are added using search_expression_insert(), and retrieved
  816. * using search_expression_extract(). They take the form option:value, and
  817. * are added to the ordinary keywords in the search expression.
  818. *
  819. * @param $expression
  820. * The search expression to add to.
  821. * @param $option
  822. * The name of the option to add to the search expression.
  823. * @param $value
  824. * The value to add for the option. If present, it will replace any previous
  825. * value added for the option. Cannot contain any spaces or | characters, as
  826. * these are used as delimiters. If you want to add a blank value $option: to
  827. * the search expression, pass in an empty string or a string that is composed
  828. * of only spaces. To clear a previously-stored option without adding a
  829. * replacement, pass in NULL for $value or omit.
  830. *
  831. * @return
  832. * $expression, with any previous value for this option removed, and a new
  833. * $option:$value pair added if $value was provided.
  834. */
  835. function search_expression_insert($expression, $option, $value = NULL) {
  836. // Remove any previous values stored with $option.
  837. $expression = trim(preg_replace('/(^| )' . $option . ':[^ ]*/i', '', $expression));
  838. // Set new value, if provided.
  839. if (isset($value)) {
  840. $expression .= ' ' . $option . ':' . trim($value);
  841. }
  842. return $expression;
  843. }
  844. /**
  845. * @defgroup search Search interface
  846. * @{
  847. * The Drupal search interface manages a global search mechanism.
  848. *
  849. * Modules may plug into this system to provide searches of different types of
  850. * data. Most of the system is handled by search.module, so this must be enabled
  851. * for all of the search features to work.
  852. *
  853. * There are three ways to interact with the search system:
  854. * - Specifically for searching nodes, you can implement
  855. * hook_node_update_index() and hook_node_search_result(). However, note that
  856. * the search system already indexes all visible output of a node; i.e.,
  857. * everything displayed normally by hook_view() and hook_node_view(). This is
  858. * usually sufficient. You should only use this mechanism if you want
  859. * additional, non-visible data to be indexed.
  860. * - Implement hook_search_info(). This will create a search tab for your module
  861. * on the /search page with a simple keyword search form. You will also need
  862. * to implement hook_search_execute() to perform the search.
  863. * - Implement hook_update_index(). This allows your module to use Drupal's
  864. * HTML indexing mechanism for searching full text efficiently.
  865. *
  866. * If your module needs to provide a more complicated search form, then you need
  867. * to implement it yourself without hook_search_info(). In that case, you should
  868. * define it as a local task (tab) under the /search page (e.g. /search/mymodule)
  869. * so that users can easily find it.
  870. */
  871. /**
  872. * Builds a search form.
  873. *
  874. * @param $action
  875. * Form action. Defaults to "search/$path", where $path is the search path
  876. * associated with the module in its hook_search_info(). This will be
  877. * run through url().
  878. * @param $keys
  879. * The search string entered by the user, containing keywords for the search.
  880. * @param $module
  881. * The search module to render the form for: a module that implements
  882. * hook_search_info(). If not supplied, the default search module is used.
  883. * @param $prompt
  884. * Label for the keywords field. Defaults to t('Enter your keywords') if NULL.
  885. * Supply '' to omit.
  886. *
  887. * @return
  888. * A Form API array for the search form.
  889. */
  890. function search_form($form, &$form_state, $action = '', $keys = '', $module = NULL, $prompt = NULL) {
  891. $module_info = FALSE;
  892. if (!$module) {
  893. $module_info = search_get_default_module_info();
  894. }
  895. else {
  896. $info = search_get_info();
  897. $module_info = isset($info[$module]) ? $info[$module] : FALSE;
  898. }
  899. // Sanity check.
  900. if (!$module_info) {
  901. form_set_error(NULL, t('Search is currently disabled.'), 'error');
  902. return $form;
  903. }
  904. if (!$action) {
  905. $action = 'search/' . $module_info['path'];
  906. }
  907. if (!isset($prompt)) {
  908. $prompt = t('Enter your keywords');
  909. }
  910. $form['#action'] = url($action);
  911. // Record the $action for later use in redirecting.
  912. $form_state['action'] = $action;
  913. $form['#attributes']['class'][] = 'search-form';
  914. $form['module'] = array('#type' => 'value', '#value' => $module);
  915. $form['basic'] = array('#type' => 'container', '#attributes' => array('class' => array('container-inline')));
  916. $form['basic']['keys'] = array(
  917. '#type' => 'textfield',
  918. '#title' => $prompt,
  919. '#default_value' => $keys,
  920. '#size' => $prompt ? 40 : 20,
  921. '#maxlength' => 255,
  922. );
  923. // processed_keys is used to coordinate keyword passing between other forms
  924. // that hook into the basic search form.
  925. $form['basic']['processed_keys'] = array('#type' => 'value', '#value' => '');
  926. $form['basic']['submit'] = array('#type' => 'submit', '#value' => t('Search'));
  927. return $form;
  928. }
  929. /**
  930. * Form builder; Output a search form for the search block's search box.
  931. *
  932. * @ingroup forms
  933. * @see search_box_form_submit()
  934. * @see search-block-form.tpl.php
  935. */
  936. function search_box($form, &$form_state, $form_id) {
  937. $form[$form_id] = array(
  938. '#type' => 'textfield',
  939. '#title' => t('Search'),
  940. '#title_display' => 'invisible',
  941. '#size' => 15,
  942. '#default_value' => '',
  943. '#attributes' => array('title' => t('Enter the terms you wish to search for.')),
  944. );
  945. $form['actions'] = array('#type' => 'actions');
  946. $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Search'));
  947. $form['#submit'][] = 'search_box_form_submit';
  948. return $form;
  949. }
  950. /**
  951. * Process a block search form submission.
  952. */
  953. function search_box_form_submit($form, &$form_state) {
  954. // The search form relies on control of the redirect destination for its
  955. // functionality, so we override any static destination set in the request,
  956. // for example by drupal_access_denied() or drupal_not_found()
  957. // (see http://drupal.org/node/292565).
  958. if (isset($_GET['destination'])) {
  959. unset($_GET['destination']);
  960. }
  961. // Check to see if the form was submitted empty.
  962. // If it is empty, display an error message.
  963. // (This method is used instead of setting #required to TRUE for this field
  964. // because that results in a confusing error message. It would say a plain
  965. // "field is required" because the search keywords field has no title.
  966. // The error message would also complain about a missing #title field.)
  967. if ($form_state['values']['search_block_form'] == '') {
  968. form_set_error('keys', t('Please enter some keywords.'));
  969. }
  970. $form_id = $form['form_id']['#value'];
  971. $info = search_get_default_module_info();
  972. if ($info) {
  973. $form_state['redirect'] = 'search/' . $info['path'] . '/' . trim($form_state['values'][$form_id]);
  974. }
  975. else {
  976. form_set_error(NULL, t('Search is currently disabled.'), 'error');
  977. }
  978. }
  979. /**
  980. * Process variables for search-block-form.tpl.php.
  981. *
  982. * The $variables array contains the following arguments:
  983. * - $form
  984. *
  985. * @see search-block-form.tpl.php
  986. */
  987. function template_preprocess_search_block_form(&$variables) {
  988. $variables['search'] = array();
  989. $hidden = array();
  990. // Provide variables named after form keys so themers can print each element independently.
  991. foreach (element_children($variables['form']) as $key) {
  992. $type = $variables['form'][$key]['#type'];
  993. if ($type == 'hidden' || $type == 'token') {
  994. $hidden[] = drupal_render($variables['form'][$key]);
  995. }
  996. else {
  997. $variables['search'][$key] = drupal_render($variables['form'][$key]);
  998. }
  999. }
  1000. // Hidden form elements have no value to themers. No need for separation.
  1001. $variables['search']['hidden'] = implode($hidden);
  1002. // Collect all form elements to make it easier to print the whole form.
  1003. $variables['search_form'] = implode($variables['search']);
  1004. }
  1005. /**
  1006. * Performs a search by calling hook_search_execute().
  1007. *
  1008. * @param $keys
  1009. * Keyword query to search on.
  1010. * @param $module
  1011. * Search module to search.
  1012. * @param $conditions
  1013. * Optional array of additional search conditions.
  1014. *
  1015. * @return
  1016. * Renderable array of search results. No return value if $keys are not
  1017. * supplied or if the given search module is not active.
  1018. */
  1019. function search_data($keys, $module, $conditions = NULL) {
  1020. if (module_hook($module, 'search_execute')) {
  1021. $results = module_invoke($module, 'search_execute', $keys, $conditions);
  1022. if (module_hook($module, 'search_page')) {
  1023. return module_invoke($module, 'search_page', $results);
  1024. }
  1025. else {
  1026. return array(
  1027. '#theme' => 'search_results',
  1028. '#results' => $results,
  1029. '#module' => $module,
  1030. );
  1031. }
  1032. }
  1033. }
  1034. /**
  1035. * Returns snippets from a piece of text, with certain keywords highlighted.
  1036. * Used for formatting search results.
  1037. *
  1038. * @param $keys
  1039. * A string containing a search query.
  1040. *
  1041. * @param $text
  1042. * The text to extract fragments from.
  1043. *
  1044. * @return
  1045. * A string containing HTML for the excerpt.
  1046. */
  1047. function search_excerpt($keys, $text) {
  1048. // We highlight around non-indexable or CJK characters.
  1049. $boundary = '(?:(?<=[' . PREG_CLASS_UNICODE_WORD_BOUNDARY . PREG_CLASS_CJK . '])|(?=[' . PREG_CLASS_UNICODE_WORD_BOUNDARY . PREG_CLASS_CJK . ']))';
  1050. // Extract positive keywords and phrases
  1051. preg_match_all('/ ("([^"]+)"|(?!OR)([^" ]+))/', ' ' . $keys, $matches);
  1052. $keys = array_merge($matches[2], $matches[3]);
  1053. // Prepare text by stripping HTML tags and decoding HTML entities.
  1054. $text = strip_tags(str_replace(array('<', '>'), array(' <', '> '), $text));
  1055. $text = decode_entities($text);
  1056. // Slash-escape quotes in the search keyword string.
  1057. array_walk($keys, '_search_excerpt_replace');
  1058. $workkeys = $keys;
  1059. // Extract fragments around keywords.
  1060. // First we collect ranges of text around each keyword, starting/ending
  1061. // at spaces, trying to get to 256 characters.
  1062. // If the sum of all fragments is too short, we look for second occurrences.
  1063. $ranges = array();
  1064. $included = array();
  1065. $foundkeys = array();
  1066. $length = 0;
  1067. while ($length < 256 && count($workkeys)) {
  1068. foreach ($workkeys as $k => $key) {
  1069. if (strlen($key) == 0) {
  1070. unset($workkeys[$k]);
  1071. unset($keys[$k]);
  1072. continue;
  1073. }
  1074. if ($length >= 256) {
  1075. break;
  1076. }
  1077. // Remember occurrence of key so we can skip over it if more occurrences
  1078. // are desired.
  1079. if (!isset($included[$key])) {
  1080. $included[$key] = 0;
  1081. }
  1082. // Locate a keyword (position $p, always >0 because $text starts with a
  1083. // space). First try bare keyword, but if that doesn't work, try to find a
  1084. // derived form from search_simplify().
  1085. $p = 0;
  1086. if (preg_match('/' . $boundary . $key . $boundary . '/iu', $text, $match, PREG_OFFSET_CAPTURE, $included[$key])) {
  1087. $p = $match[0][1];
  1088. }
  1089. else {
  1090. $info = search_simplify_excerpt_match($key, $text, $included[$key], $boundary);
  1091. if ($info['where']) {
  1092. $p = $info['where'];
  1093. if ($info['keyword']) {
  1094. $foundkeys[] = $info['keyword'];
  1095. }
  1096. }
  1097. }
  1098. // Now locate a space in front (position $q) and behind it (position $s),
  1099. // leaving about 60 characters extra before and after for context.
  1100. // Note that a space was added to the front and end of $text above.
  1101. if ($p) {
  1102. if (($q = strpos(' ' . $text, ' ', max(0, $p - 61))) !== FALSE) {
  1103. $end = substr($text . ' ', $p, 80);
  1104. if (($s = strrpos($end, ' ')) !== FALSE) {
  1105. // Account for the added spaces.
  1106. $q = max($q - 1, 0);
  1107. $s = min($s, strlen($end) - 1);
  1108. $ranges[$q] = $p + $s;
  1109. $length += $p + $s - $q;
  1110. $included[$key] = $p + 1;
  1111. }
  1112. else {
  1113. unset($workkeys[$k]);
  1114. }
  1115. }
  1116. else {
  1117. unset($workkeys[$k]);
  1118. }
  1119. }
  1120. else {
  1121. unset($workkeys[$k]);
  1122. }
  1123. }
  1124. }
  1125. if (count($ranges) == 0) {
  1126. // We didn't find any keyword matches, so just return the first part of the
  1127. // text. We also need to re-encode any HTML special characters that we
  1128. // entity-decoded above.
  1129. return check_plain(truncate_utf8($text, 256, TRUE, TRUE));
  1130. }
  1131. // Sort the text ranges by starting position.
  1132. ksort($ranges);
  1133. // Now we collapse overlapping text ranges into one. The sorting makes it O(n).
  1134. $newranges = array();
  1135. foreach ($ranges as $from2 => $to2) {
  1136. if (!isset($from1)) {
  1137. $from1 = $from2;
  1138. $to1 = $to2;
  1139. continue;
  1140. }
  1141. if ($from2 <= $to1) {
  1142. $to1 = max($to1, $to2);
  1143. }
  1144. else {
  1145. $newranges[$from1] = $to1;
  1146. $from1 = $from2;
  1147. $to1 = $to2;
  1148. }
  1149. }
  1150. $newranges[$from1] = $to1;
  1151. // Fetch text
  1152. $out = array();
  1153. foreach ($newranges as $from => $to) {
  1154. $out[] = substr($text, $from, $to - $from);
  1155. }
  1156. // Let translators have the ... separator text as one chunk.
  1157. $dots = explode('!excerpt', t('... !excerpt ... !excerpt ...'));
  1158. $text = (isset($newranges[0]) ? '' : $dots[0]) . implode($dots[1], $out) . $dots[2];
  1159. $text = check_plain($text);
  1160. // Slash-escape quotes in keys found in a derived form and merge with original keys.
  1161. array_walk($foundkeys, '_search_excerpt_replace');
  1162. $keys = array_merge($keys, $foundkeys);
  1163. // Highlight keywords. Must be done at once to prevent conflicts ('strong' and '<strong>').
  1164. $text = preg_replace('/' . $boundary . '(' . implode('|', $keys) . ')' . $boundary . '/iu', '<strong>\0</strong>', $text);
  1165. return $text;
  1166. }
  1167. /**
  1168. * @} End of "defgroup search".
  1169. */
  1170. /**
  1171. * Helper function for array_walk() in search_excerpt().
  1172. */
  1173. function _search_excerpt_replace(&$text) {
  1174. $text = preg_quote($text, '/');
  1175. }
  1176. /**
  1177. * Find words in the original text that matched via search_simplify().
  1178. *
  1179. * This is called in search_excerpt() if an exact match is not found in the
  1180. * text, so that we can find the derived form that matches.
  1181. *
  1182. * @param $key
  1183. * The keyword to find.
  1184. * @param $text
  1185. * The text to search for the keyword.
  1186. * @param $offset
  1187. * Offset position in $text to start searching at.
  1188. * @param $boundary
  1189. * Text to include in a regular expression that will match a word boundary.
  1190. *
  1191. * @return
  1192. * FALSE if no match is found. If a match is found, return an associative
  1193. * array with element 'where' giving the position of the match, and element
  1194. * 'keyword' giving the actual word found in the text at that position.
  1195. */
  1196. function search_simplify_excerpt_match($key, $text, $offset, $boundary) {
  1197. $pos = NULL;
  1198. $simplified_key = search_simplify($key);
  1199. $simplified_text = search_simplify($text);
  1200. // Return immediately if simplified key or text are empty.
  1201. if (!$simplified_key || !$simplified_text) {
  1202. return FALSE;
  1203. }
  1204. // Check if we have a match after simplification in the text.
  1205. if (!preg_match('/' . $boundary . $simplified_key . $boundary . '/iu', $simplified_text, $match, PREG_OFFSET_CAPTURE, $offset)) {
  1206. return FALSE;
  1207. }
  1208. // If we get here, we have a match. Now find the exact location of the match
  1209. // and the original text that matched. Start by splitting up the text by all
  1210. // potential starting points of the matching text and iterating through them.
  1211. $split = array_filter(preg_split('/' . $boundary . '/iu', $text, -1, PREG_SPLIT_OFFSET_CAPTURE), '_search_excerpt_match_filter');
  1212. foreach ($split as $value) {
  1213. // Skip starting points before the offset.
  1214. if ($value[1] < $offset) {
  1215. continue;
  1216. }
  1217. // Check a window of 80 characters after the starting point for a match,
  1218. // based on the size of the excerpt window.
  1219. $window = substr($text, $value[1], 80);
  1220. $simplified_window = search_simplify($window);
  1221. if (strpos($simplified_window, $simplified_key) === 0) {
  1222. // We have a match in this window. Store the position of the match.
  1223. $pos = $value[1];
  1224. // Iterate through the text in the window until we find the full original
  1225. // matching text.
  1226. $length = strlen($window);
  1227. for ($i = 1; $i <= $length; $i++) {
  1228. $keyfound = substr($text, $value[1], $i);
  1229. if ($simplified_key == search_simplify($keyfound)) {
  1230. break;
  1231. }
  1232. }
  1233. break;
  1234. }
  1235. }
  1236. return $pos ? array('where' => $pos, 'keyword' => $keyfound) : FALSE;
  1237. }
  1238. /**
  1239. * Helper function for array_filter() in search_search_excerpt_match().
  1240. */
  1241. function _search_excerpt_match_filter($var) {
  1242. return strlen(trim($var[0]));
  1243. }
  1244. /**
  1245. * Implements hook_forms().
  1246. */
  1247. function search_forms() {
  1248. $forms['search_block_form']= array(
  1249. 'callback' => 'search_box',
  1250. 'callback arguments' => array('search_block_form'),
  1251. );
  1252. return $forms;
  1253. }