search.module 45.8 KB
Newer Older
1
<?php
2
// $Id$
3

4 5 6 7 8
/**
 * @file
 * Enables site-wide keyword searching.
 */

9
/**
10
 * Matches Unicode character classes to exclude from the search index.
Steven Wittens's avatar
Steven Wittens committed
11
 *
12 13
 * See: http://www.unicode.org/Public/UNIDATA/UCD.html#General_Category_Values
 *
14
 * The index only contains the following character classes:
15 16 17 18 19 20 21
 * Lu     Letter, Uppercase
 * Ll     Letter, Lowercase
 * Lt     Letter, Titlecase
 * Lo     Letter, Other
 * Nd     Number, Decimal Digit
 * No     Number, Other
 */
22
define('PREG_CLASS_SEARCH_EXCLUDE',
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
'\x{0}-\x{2f}\x{3a}-\x{40}\x{5b}-\x{60}\x{7b}-\x{bf}\x{d7}\x{f7}\x{2b0}-' .
'\x{385}\x{387}\x{3f6}\x{482}-\x{489}\x{559}-\x{55f}\x{589}-\x{5c7}\x{5f3}-' .
'\x{61f}\x{640}\x{64b}-\x{65e}\x{66a}-\x{66d}\x{670}\x{6d4}\x{6d6}-\x{6ed}' .
'\x{6fd}\x{6fe}\x{700}-\x{70f}\x{711}\x{730}-\x{74a}\x{7a6}-\x{7b0}\x{901}-' .
'\x{903}\x{93c}\x{93e}-\x{94d}\x{951}-\x{954}\x{962}-\x{965}\x{970}\x{981}-' .
'\x{983}\x{9bc}\x{9be}-\x{9cd}\x{9d7}\x{9e2}\x{9e3}\x{9f2}-\x{a03}\x{a3c}-' .
'\x{a4d}\x{a70}\x{a71}\x{a81}-\x{a83}\x{abc}\x{abe}-\x{acd}\x{ae2}\x{ae3}' .
'\x{af1}-\x{b03}\x{b3c}\x{b3e}-\x{b57}\x{b70}\x{b82}\x{bbe}-\x{bd7}\x{bf0}-' .
'\x{c03}\x{c3e}-\x{c56}\x{c82}\x{c83}\x{cbc}\x{cbe}-\x{cd6}\x{d02}\x{d03}' .
'\x{d3e}-\x{d57}\x{d82}\x{d83}\x{dca}-\x{df4}\x{e31}\x{e34}-\x{e3f}\x{e46}-' .
'\x{e4f}\x{e5a}\x{e5b}\x{eb1}\x{eb4}-\x{ebc}\x{ec6}-\x{ecd}\x{f01}-\x{f1f}' .
'\x{f2a}-\x{f3f}\x{f71}-\x{f87}\x{f90}-\x{fd1}\x{102c}-\x{1039}\x{104a}-' .
'\x{104f}\x{1056}-\x{1059}\x{10fb}\x{10fc}\x{135f}-\x{137c}\x{1390}-\x{1399}' .
'\x{166d}\x{166e}\x{1680}\x{169b}\x{169c}\x{16eb}-\x{16f0}\x{1712}-\x{1714}' .
'\x{1732}-\x{1736}\x{1752}\x{1753}\x{1772}\x{1773}\x{17b4}-\x{17db}\x{17dd}' .
'\x{17f0}-\x{180e}\x{1843}\x{18a9}\x{1920}-\x{1945}\x{19b0}-\x{19c0}\x{19c8}' .
'\x{19c9}\x{19de}-\x{19ff}\x{1a17}-\x{1a1f}\x{1d2c}-\x{1d61}\x{1d78}\x{1d9b}-' .
'\x{1dc3}\x{1fbd}\x{1fbf}-\x{1fc1}\x{1fcd}-\x{1fcf}\x{1fdd}-\x{1fdf}\x{1fed}-' .
'\x{1fef}\x{1ffd}-\x{2070}\x{2074}-\x{207e}\x{2080}-\x{2101}\x{2103}-\x{2106}' .
'\x{2108}\x{2109}\x{2114}\x{2116}-\x{2118}\x{211e}-\x{2123}\x{2125}\x{2127}' .
'\x{2129}\x{212e}\x{2132}\x{213a}\x{213b}\x{2140}-\x{2144}\x{214a}-\x{2b13}' .
'\x{2ce5}-\x{2cff}\x{2d6f}\x{2e00}-\x{3005}\x{3007}-\x{303b}\x{303d}-\x{303f}' .
'\x{3099}-\x{309e}\x{30a0}\x{30fb}-\x{30fe}\x{3190}-\x{319f}\x{31c0}-\x{31cf}' .
'\x{3200}-\x{33ff}\x{4dc0}-\x{4dff}\x{a015}\x{a490}-\x{a716}\x{a802}\x{a806}' .
'\x{a80b}\x{a823}-\x{a82b}\x{d800}-\x{f8ff}\x{fb1e}\x{fb29}\x{fd3e}\x{fd3f}' .
'\x{fdfc}-\x{fe6b}\x{feff}-\x{ff0f}\x{ff1a}-\x{ff20}\x{ff3b}-\x{ff40}\x{ff5b}-' .
49
'\x{ff65}\x{ff70}\x{ff9e}\x{ff9f}\x{ffe0}-\x{fffd}');
50 51

/**
Steven Wittens's avatar
Steven Wittens committed
52
 * Matches all 'N' Unicode character classes (numbers)
53
 */
54
define('PREG_CLASS_NUMBERS',
55 56 57 58 59 60 61 62
'\x{30}-\x{39}\x{b2}\x{b3}\x{b9}\x{bc}-\x{be}\x{660}-\x{669}\x{6f0}-\x{6f9}' .
'\x{966}-\x{96f}\x{9e6}-\x{9ef}\x{9f4}-\x{9f9}\x{a66}-\x{a6f}\x{ae6}-\x{aef}' .
'\x{b66}-\x{b6f}\x{be7}-\x{bf2}\x{c66}-\x{c6f}\x{ce6}-\x{cef}\x{d66}-\x{d6f}' .
'\x{e50}-\x{e59}\x{ed0}-\x{ed9}\x{f20}-\x{f33}\x{1040}-\x{1049}\x{1369}-' .
'\x{137c}\x{16ee}-\x{16f0}\x{17e0}-\x{17e9}\x{17f0}-\x{17f9}\x{1810}-\x{1819}' .
'\x{1946}-\x{194f}\x{2070}\x{2074}-\x{2079}\x{2080}-\x{2089}\x{2153}-\x{2183}' .
'\x{2460}-\x{249b}\x{24ea}-\x{24ff}\x{2776}-\x{2793}\x{3007}\x{3021}-\x{3029}' .
'\x{3038}-\x{303a}\x{3192}-\x{3195}\x{3220}-\x{3229}\x{3251}-\x{325f}\x{3280}-' .
63
'\x{3289}\x{32b1}-\x{32bf}\x{ff10}-\x{ff19}');
64 65

/**
Steven Wittens's avatar
Steven Wittens committed
66
 * Matches all 'P' Unicode character classes (punctuation)
67
 */
68
define('PREG_CLASS_PUNCTUATION',
69 70 71 72 73 74 75 76 77 78 79 80 81 82
'\x{21}-\x{23}\x{25}-\x{2a}\x{2c}-\x{2f}\x{3a}\x{3b}\x{3f}\x{40}\x{5b}-\x{5d}' .
'\x{5f}\x{7b}\x{7d}\x{a1}\x{ab}\x{b7}\x{bb}\x{bf}\x{37e}\x{387}\x{55a}-\x{55f}' .
'\x{589}\x{58a}\x{5be}\x{5c0}\x{5c3}\x{5f3}\x{5f4}\x{60c}\x{60d}\x{61b}\x{61f}' .
'\x{66a}-\x{66d}\x{6d4}\x{700}-\x{70d}\x{964}\x{965}\x{970}\x{df4}\x{e4f}' .
'\x{e5a}\x{e5b}\x{f04}-\x{f12}\x{f3a}-\x{f3d}\x{f85}\x{104a}-\x{104f}\x{10fb}' .
'\x{1361}-\x{1368}\x{166d}\x{166e}\x{169b}\x{169c}\x{16eb}-\x{16ed}\x{1735}' .
'\x{1736}\x{17d4}-\x{17d6}\x{17d8}-\x{17da}\x{1800}-\x{180a}\x{1944}\x{1945}' .
'\x{2010}-\x{2027}\x{2030}-\x{2043}\x{2045}-\x{2051}\x{2053}\x{2054}\x{2057}' .
'\x{207d}\x{207e}\x{208d}\x{208e}\x{2329}\x{232a}\x{23b4}-\x{23b6}\x{2768}-' .
'\x{2775}\x{27e6}-\x{27eb}\x{2983}-\x{2998}\x{29d8}-\x{29db}\x{29fc}\x{29fd}' .
'\x{3001}-\x{3003}\x{3008}-\x{3011}\x{3014}-\x{301f}\x{3030}\x{303d}\x{30a0}' .
'\x{30fb}\x{fd3e}\x{fd3f}\x{fe30}-\x{fe52}\x{fe54}-\x{fe61}\x{fe63}\x{fe68}' .
'\x{fe6a}\x{fe6b}\x{ff01}-\x{ff03}\x{ff05}-\x{ff0a}\x{ff0c}-\x{ff0f}\x{ff1a}' .
'\x{ff1b}\x{ff1f}\x{ff20}\x{ff3b}-\x{ff3d}\x{ff3f}\x{ff5b}\x{ff5d}\x{ff5f}-' .
83 84 85 86 87 88 89
'\x{ff65}');

/**
 * Matches all CJK characters that are candidates for auto-splitting
 * (Chinese, Japanese, Korean).
 * Contains kana and BMP ideographs.
 */
90
define('PREG_CLASS_CJK', '\x{3041}-\x{30ff}\x{31f0}-\x{31ff}\x{3400}-\x{4db5}' .
91
'\x{4e00}-\x{9fbb}\x{f900}-\x{fad9}');
92

Dries's avatar
Dries committed
93
/**
94
 * Implement hook_help().
Dries's avatar
Dries committed
95
 */
96 97
function search_help($path, $arg) {
  switch ($path) {
98
    case 'admin/help#search':
99 100 101
      $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>';
      $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>';
      $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>';
102
      return $output;
103
    case 'admin/settings/search':
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>';
105
    case 'search#noresults':
106
      return t('<ul>
107
<li>Check if your spelling is correct.</li>
108 109
<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>
<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>
110
</ul>');
111
  }
112
}
Kjartan's avatar
Kjartan committed
113

114
/**
115
 * Implement hook_theme().
116 117 118 119 120
 */
function search_theme() {
  return array(
    'search_theme_form' => array(
      'arguments' => array('form' => NULL),
121
      'template' => 'search-theme-form',
122 123 124
    ),
    'search_block_form' => array(
      'arguments' => array('form' => NULL),
125
      'template' => 'search-block-form',
126
    ),
127 128
    'search_result' => array(
      'arguments' => array('result' => NULL, 'type' => NULL),
129
      'file' => 'search.pages.inc',
130
      'template' => 'search-result',
131
    ),
132
    'search_results' => array(
133
      'arguments' => array('results' => NULL, 'type' => NULL),
134
      'file' => 'search.pages.inc',
135
      'template' => 'search-results',
136
    ),
137 138 139
    'search_results_listing' => array(
      'arguments' => array('title' => NULL, 'content' => NULL),
    ),
140 141 142
  );
}

Kjartan's avatar
Kjartan committed
143
/**
144
 * Implement hook_permission().
Kjartan's avatar
Kjartan committed
145
 */
146
function search_permission() {
147
  return array(
148 149 150 151 152 153 154 155 156 157 158 159
    'administer search' => array(
      'title' => t('Administer search'),
      'description' => t('Configure search administration settings.'),
    ),
    'search content' => array(
      'title' => t('Search content'),
      'description' => t('Search website content.'),
    ),
    'use advanced search' => array(
      'title' => t('Use advanced search'),
      'description' => t('Limit search results with additional criteria, such as specific content types. Could have performance implications.'),
    ),
160
  );
161 162
}

163
/**
164
 * Implement hook_block_list().
165
 */
166 167 168 169 170 171 172 173
function search_block_list() {
  $blocks['form']['info'] = t('Search form');
  // Not worth caching.
  $blocks['form']['cache'] = BLOCK_NO_CACHE;
  return $blocks;
}

/**
174
 * Implement hook_block_view().
175 176 177
 */
function search_block_view($delta = '') {
  if (user_access('search content')) {
178
    $block['content'] = drupal_get_form('search_block_form');
179 180 181 182 183
    $block['subject'] = t('Search');
    return $block;
  }
}

Dries's avatar
Dries committed
184
/**
185
 * Implement hook_menu().
Dries's avatar
Dries committed
186
 */
187 188
function search_menu() {
  $items['search'] = array(
189
    'title' => 'Search',
190 191 192 193 194
    'page callback' => 'search_view',
    'access arguments' => array('search content'),
    'type' => MENU_SUGGESTED_ITEM,
  );
  $items['admin/settings/search'] = array(
195 196
    'title' => 'Search settings',
    'description' => 'Configure relevance settings for search and other indexing options',
197 198 199 200 201
    'page callback' => 'drupal_get_form',
    'page arguments' => array('search_admin_settings'),
    'access arguments' => array('administer search'),
    'type' => MENU_NORMAL_ITEM,
  );
202
  $items['admin/settings/search/reindex'] = array(
203
    'title' => 'Clear index',
204
    'page callback' => 'drupal_get_form',
205
    'page arguments' => array('search_reindex_confirm'),
206 207 208
    'access arguments' => array('administer search'),
    'type' => MENU_CALLBACK,
  );
209
  $items['admin/reports/search'] = array(
210 211
    'title' => 'Top search phrases',
    'description' => 'View most popular search phrases.',
212
    'page callback' => 'dblog_top',
213
    'page arguments' => array('search'),
214
    'access arguments' => array('access site reports'),
215
    'file path' => drupal_get_path('module', 'dblog'),
216
  );
217

218 219
  foreach (module_implements('search') as $module) {
    $items['search/' . $module . '/%menu_tail'] = array(
220
      'title callback' => 'module_invoke',
221
      'title arguments' => array($module, 'search', 'name', TRUE),
222
      'page callback' => 'search_view',
223
      'page arguments' => array($module),
224
      'access callback' => '_search_menu',
225
      'access arguments' => array($module),
226
      'type' => MENU_LOCAL_TASK,
227
      'parent' => 'search',
228
    );
229
  }
230 231 232
  return $items;
}

233 234
function _search_menu($name) {
  return user_access('search content') && module_invoke($name, 'search', 'name');
Dries's avatar
Dries committed
235 236
}

Dries's avatar
Dries committed
237
/**
238 239 240 241 242 243 244
 * Wipes a part of or the entire search index.
 *
 * @param $sid
 *  (optional) The SID of the item to wipe. If specified, $type must be passed
 *  too.
 * @param $type
 *  (optional) The type of item to wipe.
Dries's avatar
Dries committed
245
 */
246
function search_reindex($sid = NULL, $type = NULL, $reindex = FALSE) {
247 248 249 250
  if ($type == NULL && $sid == NULL) {
    module_invoke_all('search', 'reset');
  }
  else {
251
    db_query("DELETE FROM {search_dataset} WHERE sid = %d AND type = '%s'", $sid, $type);
252 253 254 255 256
    db_query("DELETE FROM {search_index} WHERE sid = %d AND type = '%s'", $sid, $type);
    // Don't remove links if re-indexing.
    if (!$reindex) {
      db_query("DELETE FROM {search_node_links} WHERE sid = %d AND type = '%s'", $sid, $type);
    }
257
  }
Dries's avatar
Dries committed
258 259
}

260 261 262 263 264
/**
 * Marks a word as dirty (or retrieves the list of dirty words). This is used
 * during indexing (cron). Words which are dirty have outdated total counts in
 * the search_total table, and need to be recounted.
 */
265
function search_dirty($word = NULL) {
266
  static $dirty = array();
267 268
  if ($word !== NULL) {
    $dirty[$word] = TRUE;
269 270 271 272 273 274
  }
  else {
    return $dirty;
  }
}

Kjartan's avatar
Kjartan committed
275
/**
276
 * Implement hook_cron().
Dries's avatar
Dries committed
277
 *
278 279
 * Fires hook_update_index() in all modules and cleans up dirty words (see
 * search_dirty).
Kjartan's avatar
Kjartan committed
280 281
 */
function search_cron() {
282 283 284 285
  // We register a shutdown function to ensure that search_total is always up
  // to date.
  register_shutdown_function('search_update_totals');

Dries's avatar
Dries committed
286
  // Update word index
287
  module_invoke_all('update_index');
288 289 290 291 292 293 294
}

/**
 * This function is called on shutdown to ensure that search_total is always
 * up to date (even if cron times out or otherwise fails).
 */
function search_update_totals() {
295
  // Update word IDF (Inverse Document Frequency) counts for new/changed words
296
  foreach (search_dirty() as $word => $dummy) {
297
    // Get total count
298
    $total = db_result(db_query("SELECT SUM(score) FROM {search_index} WHERE word = '%s'", $word));
299 300
    // Apply Zipf's law to equalize the probability distribution
    $total = log10(1 + 1/(max(1, $total)));
301
    db_merge('search_total')->key(array('word' => $word))->fields(array('count' => $total))->execute();
Dries's avatar
Dries committed
302 303 304 305 306 307 308
  }
  // Find words that were deleted from search_index, but are still in
  // search_total. We use a LEFT JOIN between the two tables and keep only the
  // rows which fail to join.
  $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");
  while ($word = db_fetch_object($result)) {
    db_query("DELETE FROM {search_total} WHERE word = '%s'", $word->realword);
Kjartan's avatar
Kjartan committed
309 310 311 312
  }
}

/**
313
 * Simplifies a string according to indexing rules.
Kjartan's avatar
Kjartan committed
314
 */
315
function search_simplify($text) {
316 317
  // Decode entities to UTF-8
  $text = decode_entities($text);
318

319 320 321
  // Lowercase
  $text = drupal_strtolower($text);

322
  // Call an external processor for word handling.
323
  search_invoke_preprocess($text);
Kjartan's avatar
Kjartan committed
324

325
  // Simple CJK handling
326
  if (variable_get('overlap_cjk', TRUE)) {
327
    $text = preg_replace_callback('/[' . PREG_CLASS_CJK . ']+/u', 'search_expand_cjk', $text);
328
  }
329

330 331 332 333 334 335
  // To improve searching for numerical data such as dates, IP addresses
  // or version numbers, we consider a group of numerical characters
  // separated only by punctuation characters to be one piece.
  // This also means that searching for e.g. '20/03/1984' also returns
  // results with '20-03-1984' in them.
  // Readable regexp: ([number]+)[punctuation]+(?=[number])
336
  $text = preg_replace('/([' . PREG_CLASS_NUMBERS . ']+)[' . PREG_CLASS_PUNCTUATION . ']+(?=[' . PREG_CLASS_NUMBERS . '])/u', '\1', $text);
Kjartan's avatar
Kjartan committed
337

338
  // The dot, underscore and dash are simply removed. This allows meaningful
339
  // search behavior with acronyms and URLs.
340
  $text = preg_replace('/[._-]+/', '', $text);
Kjartan's avatar
Kjartan committed
341

342 343
  // With the exception of the rules above, we consider all punctuation,
  // marks, spacers, etc, to be a word boundary.
344
  $text = preg_replace('/[' . PREG_CLASS_SEARCH_EXCLUDE . ']+/u', ' ', $text);
Kjartan's avatar
Kjartan committed
345

346 347 348 349 350
  return $text;
}

/**
 * Basic CJK tokenizer. Simply splits a string into consecutive, overlapping
351
 * sequences of characters ('minimum_word_size' long).
352 353
 */
function search_expand_cjk($matches) {
354 355 356 357 358
  $min = variable_get('minimum_word_size', 3);
  $str = $matches[0];
  $l = drupal_strlen($str);
  // Passthrough short words
  if ($l <= $min) {
359
    return ' ' . $str . ' ';
360
  }
361
  $tokens = ' ';
362 363
  // FIFO queue of characters
  $chars = array();
364 365 366 367
  // Begin loop
  for ($i = 0; $i < $l; ++$i) {
    // Grab next character
    $current = drupal_substr($str, 0, 1);
368 369 370
    $str = substr($str, strlen($current));
    $chars[] = $current;
    if ($i >= $min - 1) {
371
      $tokens .= implode('', $chars) . ' ';
372 373
      array_shift($chars);
    }
374 375 376 377 378 379 380 381
  }
  return $tokens;
}

/**
 * Splits a string into tokens for indexing.
 */
function search_index_split($text) {
382 383
  static $last = NULL;
  static $lastsplit = NULL;
384 385 386 387

  if ($last == $text) {
    return $lastsplit;
  }
388
  // Process words
389
  $text = search_simplify($text);
390
  $words = explode(' ', $text);
391
  array_walk($words, '_search_index_truncate');
Kjartan's avatar
Kjartan committed
392

393 394 395 396 397 398 399
  // Save last keyword result
  $last = $text;
  $lastsplit = $words;

  return $words;
}

400
/**
401
 * Helper function for array_walk in search_index_split.
402
 */
403
function _search_index_truncate(&$text) {
Steven Wittens's avatar
Steven Wittens committed
404
  $text = truncate_utf8($text, 50);
405 406
}

407 408 409
/**
 * Invokes hook_search_preprocess() in modules.
 */
410
function search_invoke_preprocess(&$text) {
411 412
  foreach (module_implements('search_preprocess') as $module) {
    $text = module_invoke($module, 'search_preprocess', $text);
Kjartan's avatar
Kjartan committed
413 414 415 416
  }
}

/**
417
 * Update the full-text search index for a particular item.
418 419 420
 *
 * @param $sid
 *   A number identifying this particular item (e.g. node id).
Kjartan's avatar
Kjartan committed
421
 *
422 423 424 425 426
 * @param $type
 *   A string defining this type of item (e.g. 'node')
 *
 * @param $text
 *   The content of this item. Must be a piece of HTML text.
427 428
 *
 * @ingroup search
Kjartan's avatar
Kjartan committed
429
 */
430
function search_index($sid, $type, $text) {
431
  $minimum_word_size = variable_get('minimum_word_size', 3);
432

433
  // Link matching
434
  global $base_url;
435
  $node_regexp = '@href=[\'"]?(?:' . preg_quote($base_url, '@') . '/|' . preg_quote(base_path(), '@') . ')(?:\?q=)?/?((?![a-z]+:)[^\'">]+)[\'">]@i';
436

437
  // Multipliers for scores of words inside certain HTML tags. The weights are stored
438
  // in a variable so that modules can overwrite the default weights.
439
  // Note: 'a' must be included for link ranking to work.
440 441 442 443 444 445 446 447 448 449 450 451 452
  $tags = variable_get('search_tag_weights', array(
    'h1' => 25,
    'h2' => 18,
    'h3' => 15,
    'h4' => 12,
    'h5' => 9,
    'h6' => 6,
    'u' => 3,
    'b' => 3,
    'i' => 3,
    'strong' => 3,
    'em' => 3,
    'a' => 10));
453 454 455 456

  // Strip off all ignored tags to speed up processing, but insert space before/after
  // them to keep word boundaries.
  $text = str_replace(array('<', '>'), array(' <', '> '), $text);
457
  $text = strip_tags($text, '<' . implode('><', array_keys($tags)) . '>');
458 459 460 461 462 463

  // Split HTML tags from plain text.
  $split = preg_split('/\s*<([^>]+?)>\s*/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  // Note: PHP ensures the array consists of alternating delimiters and literals
  // and begins and ends with a literal (inserting $null as required).

464
  $tag = FALSE; // Odd/even counter. Tag or no tag.
465
  $link = FALSE; // State variable for link analyzer
466
  $score = 1; // Starting score per word
467 468 469 470
  $accum = ' '; // Accumulator for cleaned up data
  $tagstack = array(); // Stack with open tags
  $tagwords = 0; // Counter for consecutive words
  $focus = 1; // Focus state
471

472
  $results = array(0 => array()); // Accumulator for words for index
473 474 475 476 477

  foreach ($split as $value) {
    if ($tag) {
      // Increase or decrease score per word based on tag
      list($tagname) = explode(' ', $value, 2);
478
      $tagname = drupal_strtolower($tagname);
479
      // Closing or opening tag?
480
      if ($tagname[0] == '/') {
481 482 483 484
        $tagname = substr($tagname, 1);
        // If we encounter unexpected tags, reset score to avoid incorrect boosting.
        if (!count($tagstack) || $tagstack[0] != $tagname) {
          $tagstack = array();
485 486
          $score = 1;
        }
487 488 489 490 491
        else {
          // Remove from tag stack and decrement score
          $score = max(1, $score - $tags[array_shift($tagstack)]);
        }
        if ($tagname == 'a') {
492
          $link = FALSE;
493
        }
Kjartan's avatar
Kjartan committed
494
      }
495
      else {
496
        if (isset($tagstack[0]) && $tagstack[0] == $tagname) {
497 498 499
          // None of the tags we look for make sense when nested identically.
          // If they are, it's probably broken HTML.
          $tagstack = array();
500
          $score = 1;
501 502 503 504 505 506
        }
        else {
          // Add to open tag stack and increment score
          array_unshift($tagstack, $tagname);
          $score += $tags[$tagname];
        }
507 508 509 510
        if ($tagname == 'a') {
          // Check if link points to a node on this site
          if (preg_match($node_regexp, $value, $match)) {
            $path = drupal_get_normal_path($match[1]);
511
            if (preg_match('!(?:node|book)/(?:view/)?([0-9]+)!i', $path, $match)) {
512 513
              $linknid = $match[1];
              if ($linknid > 0) {
514
                // Note: ignore links to uncacheable nodes to avoid redirect bugs.
515 516 517
                $node = db_query('SELECT title, nid, vid FROM {node} WHERE nid = :nid', array(':nid' => $linknid))->fetchObject();
                $link = TRUE;
                $linktitle = $node->title;
518 519
              }
            }
Kjartan's avatar
Kjartan committed
520 521 522
          }
        }
      }
523 524
      // A tag change occurred, reset counter.
      $tagwords = 0;
525 526 527 528
    }
    else {
      // Note: use of PREG_SPLIT_DELIM_CAPTURE above will introduce empty values
      if ($value != '') {
529 530 531 532 533 534 535
        if ($link) {
          // Check to see if the node link text is its URL. If so, we use the target node title instead.
          if (preg_match('!^https?://!i', $value)) {
            $value = $linktitle;
          }
        }
        $words = search_index_split($value);
536
        foreach ($words as $word) {
537
          // Add word to accumulator
538
          $accum .= $word . ' ';
539
          $num = is_numeric($word);
540
          // Check wordlength
541 542 543 544 545 546
          if ($num || drupal_strlen($word) >= $minimum_word_size) {
            // Normalize numbers
            if ($num) {
              $word = (int)ltrim($word, '-0');
            }

547
            // Links score mainly for the target.
548 549 550 551
            if ($link) {
              if (!isset($results[$linknid])) {
                $results[$linknid] = array();
              }
552 553 554
              $results[$linknid][] = $word;
              // Reduce score of the link caption in the source.
              $focus *= 0.2;
555
            }
556 557 558
            // Fall-through
            if (!isset($results[0][$word])) {
              $results[0][$word] = 0;
559
            }
560 561 562 563 564
            $results[0][$word] += $score * $focus;

            // Focus is a decaying value in terms of the amount of unique words up to this point.
            // From 100 words and more, it decays, to e.g. 0.5 at 500 words and 0.3 at 1000 words.
            $focus = min(1, .01 + 3.5 / (2 + count($results[0]) * .015));
565
          }
566 567 568 569 570 571
          $tagwords++;
          // Too many words inside a single tag probably mean a tag was accidentally left open.
          if (count($tagstack) && $tagwords >= 15) {
            $tagstack = array();
            $score = 1;
          }
572
        }
Kjartan's avatar
Kjartan committed
573 574
      }
    }
575
    $tag = !$tag;
Kjartan's avatar
Kjartan committed
576 577
  }

578
  search_reindex($sid, $type, TRUE);
Kjartan's avatar
Kjartan committed
579

580
  // Insert cleaned up data into dataset
581
  db_query("INSERT INTO {search_dataset} (sid, type, data, reindex) VALUES (%d, '%s', '%s', %d)", $sid, $type, $accum, 0);
582

583 584
  // Insert results into search index
  foreach ($results[0] as $word => $score) {
585
    // If a word already exists in the database, its score gets increased
586
    // appropriately. If not, we create a new record with the appropriate
587 588 589 590 591 592 593
    // starting score.
    db_merge('search_index')->key(array(
      'word' => $word,
      'sid' => $sid,
      'type' => $type,
    ))->fields(array('score' => $score))->expression('score', 'score + :score', array(':score' => $score))
    ->execute();
594 595 596
    search_dirty($word);
  }
  unset($results[0]);
597

598 599 600 601 602 603 604 605
  // Get all previous links from this item.
  $result = db_query("SELECT nid, caption FROM {search_node_links} WHERE sid = %d AND type = '%s'", $sid, $type);
  $links = array();
  while ($link = db_fetch_object($result)) {
    $links[$link->nid] = $link->caption;
  }

  // Now store links to nodes.
606
  foreach ($results as $nid => $words) {
607 608 609 610 611 612 613 614 615 616 617 618 619 620
    $caption = implode(' ', $words);
    if (isset($links[$nid])) {
      if ($links[$nid] != $caption) {
        // Update the existing link and mark the node for reindexing.
        db_query("UPDATE {search_node_links} SET caption = '%s' WHERE sid = %d AND type = '%s' AND nid = %d", $caption, $sid, $type, $nid);
        search_touch_node($nid);
      }
      // Unset the link to mark it as processed.
      unset($links[$nid]);
    }
    else {
      // Insert the existing link and mark the node for reindexing.
      db_query("INSERT INTO {search_node_links} (caption, sid, type, nid) VALUES ('%s', %d, '%s', %d)", $caption, $sid, $type, $nid);
      search_touch_node($nid);
Kjartan's avatar
Kjartan committed
621 622
    }
  }
623
  // Any left-over links in $links no longer exist. Delete them and mark the nodes for reindexing.
624
  foreach ($links as $nid => $caption) {
625 626 627 628 629 630 631 632 633 634 635 636
    db_query("DELETE FROM {search_node_links} WHERE sid = %d AND type = '%s' AND nid = %d", $sid, $type, $nid);
    search_touch_node($nid);
  }
}

/**
 * Change a node's changed timestamp to 'now' to force reindexing.
 *
 * @param $nid
 *   The nid of the node that needs reindexing.
 */
function search_touch_node($nid) {
637
  db_query("UPDATE {search_dataset} SET reindex = %d WHERE sid = %d AND type = 'node'", REQUEST_TIME, $nid);
638 639 640
}

/**
641
 * Implement hook_node_update_index().
642
 */
643
function search_node_update_index($node) {
644 645 646 647 648
  // Transplant links to a node into the target node.
  $result = db_query("SELECT caption FROM {search_node_links} WHERE nid = %d", $node->nid);
  $output = array();
  while ($link = db_fetch_object($result)) {
    $output[] = $link->caption;
649
  }
650
  if (count($output)) {
651 652
    return '<a>(' . implode(', ', $output) . ')</a>';
  }
653 654 655
}

/**
656
 * Implement hook_node_update().
657
 */
658
function search_node_update($node) {
659
  // Reindex the node when it is updated. The node is automatically indexed
660 661
  // when it is added, simply by being added to the node table.
  search_touch_node($node->nid);
662 663 664
}

/**
665
 * Implement hook_comment_insert().
666
 */
667
function search_comment_insert($comment) {
668
  // Reindex the node when comments are added.
669
  search_touch_node($comment->nid);
670 671 672
}

/**
673
 * Implement hook_comment_update().
674
 */
675
function search_comment_update($comment) {
676
  // Reindex the node when comments are changed.
677
  search_touch_node($comment->nid);
678 679 680
}

/**
681
 * Implement hook_comment_delete().
682 683 684 685 686 687 688
 */
function search_comment_delete($comment) {
  // Reindex the node when comments are deleted.
  search_touch_node($comment->nid);
}

/**
689
 * Implement hook_comment_publish().
690
 */
691
function search_comment_publish($comment) {
692
  // Reindex the node when comments are published.
693
  search_touch_node($comment->nid);
694 695 696
}

/**
697
 * Implement hook_comment_unpublish().
698 699 700 701
 */
function search_comment_unpublish($comment) {
  // Reindex the node when comments are unpublished.
  search_touch_node($comment->nid);
Kjartan's avatar
Kjartan committed
702 703
}

704 705 706 707
/**
 * Extract a module-specific search option from a search query. e.g. 'type:book'
 */
function search_query_extract($keys, $option) {
708
  if (preg_match('/(^| )' . $option . ':([^ ]*)( |$)/i', $keys, $matches)) {
709 710 711 712 713 714 715 716 717 718
    return $matches[2];
  }
}

/**
 * Return a query with the given module-specific search option inserted in.
 * e.g. 'type:book'.
 */
function search_query_insert($keys, $option, $value = '') {
  if (search_query_extract($keys, $option)) {
719
    $keys = trim(preg_replace('/(^| )' . $option . ':[^ ]*/i', '', $keys));
720 721
  }
  if ($value != '') {
722
    $keys .= ' ' . $option . ':' . $value;
723 724 725 726 727 728 729
  }
  return $keys;
}

/**
 * Parse a search query into SQL conditions.
 *
730 731 732 733 734 735 736 737 738 739 740 741
 * We build two queries that matches the dataset bodies. @See do_search for
 * more about these.
 *
 * @param $text
 *   The search keys.
 * @return
 *   A list of six elements.
 *    * A series of statements AND'd together which will be used to provide all
 *      possible matches.
 *    * Arguments for this query part.
 *    * A series of exact word matches OR'd together.
 *    * Arguments for this query part.
742
 *    * A boolean indicating whether this is a simple query or not. Negative
743
 *      terms, presence of both AND / OR make this FALSE.
744
 *    * A boolean indicating the presence of a lowercase or. Maybe the user
745
 *      wanted to use OR.
746 747 748 749 750
 */
function search_parse_query($text) {
  $keys = array('positive' => array(), 'negative' => array());

  // Tokenize query string
751
  preg_match_all('/ (-?)("[^"]+"|[^" ]+)/i', ' ' . $text, $matches, PREG_SET_ORDER);
752 753 754 755 756 757

  if (count($matches) < 1) {
    return NULL;
  }

  // Classify tokens
758
  $or = FALSE;
759
  $warning = '';
760
  $simple = TRUE;
761
  foreach ($matches as $match) {
762
    $phrase = FALSE;
Steven Wittens's avatar
Steven Wittens committed
763
    // Strip off phrase quotes
764 765
    if ($match[2]{0} == '"') {
      $match[2] = substr($match[2], 1, -1);
766
      $phrase = TRUE;
767
      $simple = FALSE;
768
    }
Steven Wittens's avatar
Steven Wittens committed
769
    // Simplify keyword according to indexing rules and external preprocessors
770 771
    $words = search_simplify($match[2]);
    // Re-explode in case simplification added more words, except when matching a phrase
Steven Wittens's avatar
Steven Wittens committed
772
    $words = $phrase ? array($words) : preg_split('/ /', $words, -1, PREG_SPLIT_NO_EMPTY);
773 774
    // Negative matches
    if ($match[1] == '-') {
775
      $keys['negative'] = array_merge($keys['negative'], $words);
776 777 778 779
    }
    // OR operator: instead of a single keyword, we store an array of all
    // OR'd keywords.
    elseif ($match[2] == 'OR' && count($keys['positive'])) {
Steven Wittens's avatar
Steven Wittens committed
780 781 782 783 784 785
      $last = array_pop($keys['positive']);
      // Starting a new OR?
      if (!is_array($last)) {
        $last = array($last);
      }
      $keys['positive'][] = $last;
786
      $or = TRUE;
787 788
      continue;
    }
789 790 791 792 793 794
    // AND operator: implied, so just ignore it
    elseif ($match[2] == 'AND' || $match[2] == 'and') {
      $warning = $match[2];
      continue;
    }

795 796
    // Plain keyword
    else {
797
      if ($match[2] == 'or') {
798
        $warning = $match[2];
799
      }
800
      if ($or) {
801 802
        // Add to last element (which is an array)
        $keys['positive'][count($keys['positive']) - 1] = array_merge($keys['positive'][count($keys['positive']) - 1], $words);
803 804
      }
      else {
805
        $keys['positive'] = array_merge($keys['positive'], $words);
806 807
      }
    }
808
    $or = FALSE;
809 810 811 812 813 814 815
  }

  // Convert keywords into SQL statements.
  $query = array();
  $query2 = array();
  $arguments = array();
  $arguments2 = array();
Steven Wittens's avatar
Steven Wittens committed
816
  $matches = 0;
817 818
  $simple_and = FALSE;
  $simple_or = FALSE;
819 820 821 822
  // Positive matches
  foreach ($keys['positive'] as $key) {
    // Group of ORed terms
    if (is_array($key) && count($key)) {
823
      $simple_or = TRUE;
824
      $queryor = array();
825
      $any = FALSE;
826
      foreach ($key as $or) {
827 828
        list($q, $num_new_scores) = _search_parse_query($or, $arguments2);
        $any |= $num_new_scores;
829 830
        if ($q) {
          $queryor[] = $q;
831
          $arguments[] = "% $or %";
832 833 834
        }
      }
      if (count($queryor)) {
835
        $query[] = '(' . implode(' OR ', $queryor) . ')';
Steven Wittens's avatar
Steven Wittens committed
836 837
        // A group of OR keywords only needs to match once
        $matches += ($any > 0);
838 839 840 841
      }
    }
    // Single ANDed term
    else {
842
      $simple_and = TRUE;
843
      list($q, $num_new_scores, $num_valid_words) = _search_parse_query($key, $arguments2);
844 845
      if ($q) {
        $query[] = $q;
846
        $arguments[] = "% $key %";
847 848 849
        if (!$num_valid_words) {
          $simple = FALSE;
        }
Steven Wittens's avatar
Steven Wittens committed
850
        // Each AND keyword needs to match at least once
851
        $matches += $num_new_scores;
852 853 854
      }
    }
  }
855 856 857
  if ($simple_and && $simple_or) {
    $simple = FALSE;
  }
Steven Wittens's avatar
Steven Wittens committed
858
  // Negative matches
859
  foreach ($keys['negative'] as $key) {
860
    list($q) = _search_parse_query($key, $arguments2, TRUE);
861 862
    if ($q) {
      $query[] = $q;
863
      $arguments[] = "% $key %";
864
      $simple = FALSE;
865 866 867
    }
  }
  $query = implode(' AND ', $query);
868

Steven Wittens's avatar
Steven Wittens committed
869
  // Build word-index conditions for the first pass
870
  $query2 = substr(str_repeat("i.word = '%s' OR ", count($arguments2)), 0, -4);
Steven Wittens's avatar
Steven Wittens committed
871

872
  return array($query, $arguments, $query2, $arguments2, $matches, $simple, $warning);
873 874 875 876 877
}

/**
 * Helper function for search_parse_query();
 */
878
function _search_parse_query(&$word, &$scores, $not = FALSE) {
879 880
  $num_new_scores = 0;
  $num_valid_words = 0;
881 882 883 884 885
  // Determine the scorewords of this word/phrase
  if (!$not) {
    $split = explode(' ', $word);
    foreach ($split as $s) {
      $num = is_numeric($s);
886
      if ($num || drupal_strlen($s) >= variable_get('minimum_word_size', 3)) {
Steven Wittens's avatar
Steven Wittens committed
887 888 889
        $s = $num ? ((int)ltrim($s, '-0')) : $s;
        if (!isset($scores[$s])) {
          $scores[$s] = $s;
890
          $num_new_scores++;
Steven Wittens's avatar
Steven Wittens committed
891
        }
892
        $num_valid_words++;
893 894 895
      }
    }
  }
Steven Wittens's avatar
Steven Wittens committed
896
  // Return matching snippet and number of added words
897
  return array("d.data " . ($not ? 'NOT ' : '') . "LIKE '%s'", $num_new_scores, $num_valid_words);
898 899
}

Kjartan's avatar
Kjartan committed
900
/**
901
 * Do a query on the full-text search index for a word or words.
902
 *
903 904
 * This function is normally only called by each module that support the
 * indexed search (and thus, implements hook_update_index()).
905
 *
906
 * Results are retrieved in two logical passes. However, the two passes are
907
 * joined together into a single query. And in the case of most simple
908
 * queries the second pass is not even used.
909
 *
910 911
 * The first pass selects a set of all possible matches, which has the benefit
 * of also providing the exact result set for simple "AND" or "OR" searches.
912
 *
913 914
 * The second portion of the query further refines this set by verifying
 * advanced text conditions (such negative or phrase matches)
915
 *
916
 * @param $keywords
917 918 919 920
 *   A search string as entered by the user.
 *
 * @param $type
 *   A string identifying the calling module.
Kjartan's avatar
Kjartan committed
921
 *
922 923
 * @param $join1
 *   (optional) Inserted into the JOIN part of the first SQL query.
924 925
 *   For example "INNER JOIN {node} n ON n.nid = i.sid".
 *
926 927 928 929 930 931 932
 * @param $where1
 *   (optional) Inserted into the WHERE part of the first SQL query.
 *   For example "(n.status > %d)".
 *
 * @param $arguments1
 *   (optional) Extra SQL arguments belonging to the first query.
 *
933
 * @param $columns2
934
 *   (optional) Inserted into the SELECT pat of the second query. Must contain
935
 *   a column selected as 'calculated_score'.
936
 *   defaults to 'SUM(i.relevance) AS calculated_score'
937
 *
938 939 940 941 942 943
 * @param $join2
 *   (optional) Inserted into the JOIN par of the second SQL query.
 *   For example "INNER JOIN {node_comment_statistics} n ON n.nid = i.sid"
 *
 * @param $arguments2
 *   (optional) Extra SQL arguments belonging to the second query parameter.
944
 *
945
 * @param $sort_parameters
Dries's avatar
Dries committed
946
 *   (optional) SQL arguments for sorting the final results.
947
 *              Default: 'ORDER BY calculated_score DESC'
948
 *
949 950
 * @return
 *   An array of SIDs for the search results.
951 952
 *
 * @ingroup search
Kjartan's avatar
Kjartan committed
953
 */
954
function do_search($keywords, $type, $join1 = '', $where1 = '1 = 1', $arguments1 = array(), $columns2 = 'SUM(i.relevance) AS calculated_score', $join2 = '', $arguments2 = array(), $sort_parameters = 'ORDER BY calculated_score DESC') {
955
  $query = search_parse_query($keywords);
956

Steven Wittens's avatar
Steven Wittens committed
957
  if ($query[2] == '') {
958
    form_set_error('keys', format_plural(variable_get('minimum_word_size', 3), 'You must include at least one positive keyword with 1 character or more.', 'You must include at least one positive keyword with @count characters or more.'));
Steven Wittens's avatar
Steven Wittens committed
959
  }
960
  if ($query[6]) {
961 962 963
    if ($query[6] == 'or') {
      drupal_set_message(t('Search for either of the two terms with uppercase <strong>OR</strong>. For example, <strong>cats OR dogs</strong>.'));
    }
964
  }
965 966
  if ($query === NULL || $query[0] == '' || $query[2] == '') {
    return array();
967
  }
968

969 970 971 972 973 974 975 976 977
  // Build query for keyword normalization.
  $conditions = "$where1 AND ($query[2]) AND i.type = '%s'";
  $arguments1 = array_merge($arguments1, $query[3], array($type));
  $join = "INNER JOIN {search_total} t ON i.word = t.word $join1";
  if (!$query[5]) {
    $conditions .= " AND ($query[0])";
    $arguments1 = array_merge($arguments1, $query[1]);
    $join .= " INNER JOIN {search_dataset} d ON i.sid = d.sid AND i.type = d.type";
  }
978

979
  // Calculate maximum keyword relevance, to normalize it.
980
  $select = "SELECT SUM(i.score * t.count) AS calculated_score FROM {search_index} i $join WHERE $conditions GROUP BY i.type, i.sid HAVING COUNT(*) >= %d ORDER BY calculated_score DESC";
981
  $arguments = array_merge($arguments1, array($query[4]));
982
  $normalize = db_result(db_query_range($select, $arguments, 0, 1));
983
  if (!$normalize) {
984 985
    return array();
  }
986
  $columns2 = str_replace('i.relevance', '(' . (1.0 / $normalize) . ' * i.score * t.count)', $columns2);
987

988 989 990
  // Build query to retrieve results.
  $select = "SELECT i.type, i.si