annotate modules/search/search.module @ 1:c1f4ac30525a 6.0

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