Code coverage for /20081101/modules/search/search.module

Line #Times calledCode
1
<?php
2
// $Id: search.module,v 1.271 2008/10/26 18:06:38 dries Exp $
3
4
/**
5
 * @file
6
 * Enables site-wide keyword searching.
7
 */
8
9
/**
10
 * Matches Unicode character classes to exclude from the search index.
11
 *
12
 * See:
http://www.unicode.org/Public/UNIDATA/UCD.html#General_Category_Values
13
 *
14
 * The index only contains the following character classes:
15
 * Lu     Letter, Uppercase
16
 * Ll     Letter, Lowercase
17
 * Lt     Letter, Titlecase
18
 * Lo     Letter, Other
19
 * Nd     Number, Decimal Digit
20
 * No     Number, Other
21
 */
2240
define('PREG_CLASS_SEARCH_EXCLUDE',
23
'\x{0}-\x{2f}\x{3a}-\x{40}\x{5b}-\x{60}\x{7b}-\x{bf}\x{d7}\x{f7}\x{2b0}-' .
2440
'\x{385}\x{387}\x{3f6}\x{482}-\x{489}\x{559}-\x{55f}\x{589}-\x{5c7}\x{5f3}-'
.
2540
'\x{61f}\x{640}\x{64b}-\x{65e}\x{66a}-\x{66d}\x{670}\x{6d4}\x{6d6}-\x{6ed}'
.
2640
'\x{6fd}\x{6fe}\x{700}-\x{70f}\x{711}\x{730}-\x{74a}\x{7a6}-\x{7b0}\x{901}-'
.
2740
'\x{903}\x{93c}\x{93e}-\x{94d}\x{951}-\x{954}\x{962}-\x{965}\x{970}\x{981}-'
.
2840
'\x{983}\x{9bc}\x{9be}-\x{9cd}\x{9d7}\x{9e2}\x{9e3}\x{9f2}-\x{a03}\x{a3c}-'
.
2940
'\x{a4d}\x{a70}\x{a71}\x{a81}-\x{a83}\x{abc}\x{abe}-\x{acd}\x{ae2}\x{ae3}'
.
3040
'\x{af1}-\x{b03}\x{b3c}\x{b3e}-\x{b57}\x{b70}\x{b82}\x{bbe}-\x{bd7}\x{bf0}-'
.
3140
'\x{c03}\x{c3e}-\x{c56}\x{c82}\x{c83}\x{cbc}\x{cbe}-\x{cd6}\x{d02}\x{d03}'
.
3240
'\x{d3e}-\x{d57}\x{d82}\x{d83}\x{dca}-\x{df4}\x{e31}\x{e34}-\x{e3f}\x{e46}-'
.
3340
'\x{e4f}\x{e5a}\x{e5b}\x{eb1}\x{eb4}-\x{ebc}\x{ec6}-\x{ecd}\x{f01}-\x{f1f}'
.
3440
'\x{f2a}-\x{f3f}\x{f71}-\x{f87}\x{f90}-\x{fd1}\x{102c}-\x{1039}\x{104a}-' .
3540
'\x{104f}\x{1056}-\x{1059}\x{10fb}\x{10fc}\x{135f}-\x{137c}\x{1390}-\x{1399}'
.
3640
'\x{166d}\x{166e}\x{1680}\x{169b}\x{169c}\x{16eb}-\x{16f0}\x{1712}-\x{1714}'
.
3740
'\x{1732}-\x{1736}\x{1752}\x{1753}\x{1772}\x{1773}\x{17b4}-\x{17db}\x{17dd}'
.
3840
'\x{17f0}-\x{180e}\x{1843}\x{18a9}\x{1920}-\x{1945}\x{19b0}-\x{19c0}\x{19c8}'
.
3940
'\x{19c9}\x{19de}-\x{19ff}\x{1a17}-\x{1a1f}\x{1d2c}-\x{1d61}\x{1d78}\x{1d9b}-'
.
4040
'\x{1dc3}\x{1fbd}\x{1fbf}-\x{1fc1}\x{1fcd}-\x{1fcf}\x{1fdd}-\x{1fdf}\x{1fed}-'
.
4140
'\x{1fef}\x{1ffd}-\x{2070}\x{2074}-\x{207e}\x{2080}-\x{2101}\x{2103}-\x{2106}'
.
4240
'\x{2108}\x{2109}\x{2114}\x{2116}-\x{2118}\x{211e}-\x{2123}\x{2125}\x{2127}'
.
4340
'\x{2129}\x{212e}\x{2132}\x{213a}\x{213b}\x{2140}-\x{2144}\x{214a}-\x{2b13}'
.
4440
'\x{2ce5}-\x{2cff}\x{2d6f}\x{2e00}-\x{3005}\x{3007}-\x{303b}\x{303d}-\x{303f}'
.
4540
'\x{3099}-\x{309e}\x{30a0}\x{30fb}-\x{30fe}\x{3190}-\x{319f}\x{31c0}-\x{31cf}'
.
4640
'\x{3200}-\x{33ff}\x{4dc0}-\x{4dff}\x{a015}\x{a490}-\x{a716}\x{a802}\x{a806}'
.
4740
'\x{a80b}\x{a823}-\x{a82b}\x{d800}-\x{f8ff}\x{fb1e}\x{fb29}\x{fd3e}\x{fd3f}'
.
4840
'\x{fdfc}-\x{fe6b}\x{feff}-\x{ff0f}\x{ff1a}-\x{ff20}\x{ff3b}-\x{ff40}\x{ff5b}-'
.
4940
'\x{ff65}\x{ff70}\x{ff9e}\x{ff9f}\x{ffe0}-\x{fffd}');
50
51
/**
52
 * Matches all 'N' Unicode character classes (numbers)
53
 */
5440
define('PREG_CLASS_NUMBERS',
55
'\x{30}-\x{39}\x{b2}\x{b3}\x{b9}\x{bc}-\x{be}\x{660}-\x{669}\x{6f0}-\x{6f9}'.
5640
'\x{966}-\x{96f}\x{9e6}-\x{9ef}\x{9f4}-\x{9f9}\x{a66}-\x{a6f}\x{ae6}-\x{aef}'.
5740
'\x{b66}-\x{b6f}\x{be7}-\x{bf2}\x{c66}-\x{c6f}\x{ce6}-\x{cef}\x{d66}-\x{d6f}'.
5840
'\x{e50}-\x{e59}\x{ed0}-\x{ed9}\x{f20}-\x{f33}\x{1040}-\x{1049}\x{1369}-'.
5940
'\x{137c}\x{16ee}-\x{16f0}\x{17e0}-\x{17e9}\x{17f0}-\x{17f9}\x{1810}-\x{1819}'.
6040
'\x{1946}-\x{194f}\x{2070}\x{2074}-\x{2079}\x{2080}-\x{2089}\x{2153}-\x{2183}'.
6140
'\x{2460}-\x{249b}\x{24ea}-\x{24ff}\x{2776}-\x{2793}\x{3007}\x{3021}-\x{3029}'.
6240
'\x{3038}-\x{303a}\x{3192}-\x{3195}\x{3220}-\x{3229}\x{3251}-\x{325f}\x{3280}-'.
6340
'\x{3289}\x{32b1}-\x{32bf}\x{ff10}-\x{ff19}');
64
65
/**
66
 * Matches all 'P' Unicode character classes (punctuation)
67
 */
6840
define('PREG_CLASS_PUNCTUATION',
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}'.
7040
'\x{5f}\x{7b}\x{7d}\x{a1}\x{ab}\x{b7}\x{bb}\x{bf}\x{37e}\x{387}\x{55a}-\x{55f}'.
7140
'\x{589}\x{58a}\x{5be}\x{5c0}\x{5c3}\x{5f3}\x{5f4}\x{60c}\x{60d}\x{61b}\x{61f}'.
7240
'\x{66a}-\x{66d}\x{6d4}\x{700}-\x{70d}\x{964}\x{965}\x{970}\x{df4}\x{e4f}'.
7340
'\x{e5a}\x{e5b}\x{f04}-\x{f12}\x{f3a}-\x{f3d}\x{f85}\x{104a}-\x{104f}\x{10fb}'.
7440
'\x{1361}-\x{1368}\x{166d}\x{166e}\x{169b}\x{169c}\x{16eb}-\x{16ed}\x{1735}'.
7540
'\x{1736}\x{17d4}-\x{17d6}\x{17d8}-\x{17da}\x{1800}-\x{180a}\x{1944}\x{1945}'.
7640
'\x{2010}-\x{2027}\x{2030}-\x{2043}\x{2045}-\x{2051}\x{2053}\x{2054}\x{2057}'.
7740
'\x{207d}\x{207e}\x{208d}\x{208e}\x{2329}\x{232a}\x{23b4}-\x{23b6}\x{2768}-'.
7840
'\x{2775}\x{27e6}-\x{27eb}\x{2983}-\x{2998}\x{29d8}-\x{29db}\x{29fc}\x{29fd}'.
7940
'\x{3001}-\x{3003}\x{3008}-\x{3011}\x{3014}-\x{301f}\x{3030}\x{303d}\x{30a0}'.
8040
'\x{30fb}\x{fd3e}\x{fd3f}\x{fe30}-\x{fe52}\x{fe54}-\x{fe61}\x{fe63}\x{fe68}'.
8140
'\x{fe6a}\x{fe6b}\x{ff01}-\x{ff03}\x{ff05}-\x{ff0a}\x{ff0c}-\x{ff0f}\x{ff1a}'.
8240
'\x{ff1b}\x{ff1f}\x{ff20}\x{ff3b}-\x{ff3d}\x{ff3f}\x{ff5b}\x{ff5d}\x{ff5f}-'.
8340
'\x{ff65}');
84
85
/**
86
 * Matches all CJK characters that are candidates for auto-splitting
87
 * (Chinese, Japanese, Korean).
88
 * Contains kana and BMP ideographs.
89
 */
9040
define('PREG_CLASS_CJK',
'\x{3041}-\x{30ff}\x{31f0}-\x{31ff}\x{3400}-\x{4db5}' .
9140
'\x{4e00}-\x{9fbb}\x{f900}-\x{fad9}');
92
93
/**
94
 * Implementation of hook_help().
95
 */
9640
function search_help($path, $arg) {
97
  switch ($path) {
9828
    case 'admin/help#search':
990
      $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>';
1000
      $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>';
1010
      $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>';
1020
      return $output;
10328
    case 'admin/settings/search':
1040
      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>';
10528
    case 'search#noresults':
1063
      return t('<ul>
107
<li>Check if your spelling is correct.</li>
108
<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>
109
<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>
1103
</ul>');
1110
  }
11228
}
113
114
/**
115
 * Implementation of hook_theme().
116
 */
11740
function search_theme() {
118
  return array(
119
    'search_theme_form' => array(
1204
      'arguments' => array('form' => NULL),
1214
      'template' => 'search-theme-form',
1224
    ),
123
    'search_block_form' => array(
1244
      'arguments' => array('form' => NULL),
1254
      'template' => 'search-block-form',
1264
    ),
127
    'search_result' => array(
1284
      'arguments' => array('result' => NULL, 'type' => NULL),
1294
      'file' => 'search.pages.inc',
1304
      'template' => 'search-result',
1314
    ),
132
    'search_results' => array(
1334
      'arguments' => array('results' => NULL, 'type' => NULL),
1344
      'file' => 'search.pages.inc',
1354
      'template' => 'search-results',
1364
    ),
1374
  );
1380
}
139
140
/**
141
 * Implementation of hook_perm().
142
 */
14340
function search_perm() {
144
  return array(
145
    'administer search' => array(
1464
      'title' => t('Administer search'),
1474
      'description' => t('Configure search administration settings.'),
1484
    ),
149
    'search content' => array(
1504
      'title' => t('Search content'),
1514
      'description' => t('Search website content.'),
1524
    ),
153
    'use advanced search' => array(
1544
      'title' => t('Use advanced search'),
1554
      'description' => t('Limit search results with additional criteria,
such as specific content types. Could have performance implications.'),
1564
    ),
1574
  );
1580
}
159
160
/**
161
 * Implementation of hook_block().
162
 */
16340
function search_block($op = 'list', $delta = '') {
1640
  if ($op == 'list') {
1650
    $blocks['form']['info'] = t('Search form');
166
    // Not worth caching.
1670
    $blocks['form']['cache'] = BLOCK_NO_CACHE;
1680
    return $blocks;
1690
  }
1700
  elseif ($op == 'view' && user_access('search content')) {
1710
    $block['content'] = drupal_get_form('search_block_form');
1720
    $block['subject'] = t('Search');
1730
    return $block;
1740
  }
1750
}
176
177
/**
178
 * Implementation of hook_menu().
179
 */
18040
function search_menu() {
1814
  $items['search'] = array(
1824
    'title' => 'Search',
1834
    'page callback' => 'search_view',
1844
    'access arguments' => array('search content'),
1854
    'type' => MENU_SUGGESTED_ITEM,
186
  );
1874
  $items['admin/settings/search'] = array(
1884
    'title' => 'Search settings',
1894
    'description' => 'Configure relevance settings for search and other
indexing options',
1904
    'page callback' => 'drupal_get_form',
1914
    'page arguments' => array('search_admin_settings'),
1924
    'access arguments' => array('administer search'),
1934
    'type' => MENU_NORMAL_ITEM,
194
  );
1954
  $items['admin/settings/search/wipe'] = array(
1964
    'title' => 'Clear index',
1974
    'page callback' => 'drupal_get_form',
1984
    'page arguments' => array('search_wipe_confirm'),
1994
    'access arguments' => array('administer search'),
2004
    'type' => MENU_CALLBACK,
201
  );
2024
  $items['admin/reports/search'] = array(
2034
    'title' => 'Top search phrases',
2044
    'description' => 'View most popular search phrases.',
2054
    'page callback' => 'dblog_top',
2064
    'page arguments' => array('search'),
2074
    'access arguments' => array('access site reports'),
2084
    'file path' => drupal_get_path('module', 'dblog'),
209
  );
210
2114
  foreach (module_implements('search') as $name) {
2124
    $items['search/' . $name . '/%menu_tail'] = array(
2134
      'title callback' => 'module_invoke',
2144
      'title arguments' => array($name, 'search', 'name', TRUE),
2154
      'page callback' => 'search_view',
2164
      'page arguments' => array($name),
2174
      'access callback' => '_search_menu',
2184
      'access arguments' => array($name),
2194
      'type' => MENU_LOCAL_TASK,
2204
      'parent' => 'search',
221
    );
2224
  }
2234
  return $items;
2240
}
225
22640
function _search_menu($name) {
22711
  return user_access('search content') && module_invoke($name, 'search',
'name');
2280
}
229
230
/**
231
 * Wipes a part of or the entire search index.
232
 *
233
 * @param $sid
234
 *  (optional) The SID of the item to wipe. If specified, $type must be
passed
235
 *  too.
236
 * @param $type
237
 *  (optional) The type of item to wipe.
238
 */
23940
function search_wipe($sid = NULL, $type = NULL, $reindex = FALSE) {
2403
  if ($type == NULL && $sid == NULL) {
2410
    module_invoke_all('search', 'reset');
2420
  }
243
  else {
2443
    db_query("DELETE FROM {search_dataset} WHERE sid = %d AND type = '%s'",
$sid, $type);
2453
    db_query("DELETE FROM {search_index} WHERE sid = %d AND type = '%s'",
$sid, $type);
246
    // Don't remove links if re-indexing.
2473
    if (!$reindex) {
2480
      db_query("DELETE FROM {search_node_links} WHERE sid = %d AND type =
'%s'", $sid, $type);
2490
    }
250
  }
2513
}
252
253
/**
254
 * Marks a word as dirty (or retrieves the list of dirty words). This is
used
255
 * during indexing (cron). Words which are dirty have outdated total counts
in
256
 * the search_total table, and need to be recounted.
257
 */
25840
function search_dirty($word = NULL) {
2593
  static $dirty = array();
2603
  if ($word !== NULL) {
2613
    $dirty[$word] = TRUE;
2623
  }
263
  else {
2643
    return $dirty;
265
  }
2663
}
267
268
/**
269
 * Implementation of hook_cron().
270
 *
271
 * Fires hook_update_index() in all modules and cleans up dirty words (see
272
 * search_dirty).
273
 */
27440
function search_cron() {
275
  // We register a shutdown function to ensure that search_total is always
up
276
  // to date.
2770
  register_shutdown_function('search_update_totals');
278
279
  // Update word index
2800
  foreach (module_list() as $module) {
2810
    module_invoke($module, 'update_index');
2820
  }
2830
}
284
285
/**
286
 * This function is called on shutdown to ensure that search_total is
always
287
 * up to date (even if cron times out or otherwise fails).
288
 */
28940
function search_update_totals() {
290
  // Update word IDF (Inverse Document Frequency) counts for new/changed
words
2913
  foreach (search_dirty() as $word => $dummy) {
292
    // Get total count
2933
    $total = db_result(db_query("SELECT SUM(score) FROM {search_index}
WHERE word = '%s'", $word));
294
    // Apply Zipf's law to equalize the probability distribution
2953
    $total = log10(1 + 1/(max(1, $total)));
2963
    db_merge('search_total')->key(array('word' =>
$word))->fields(array('count' => $total))->execute();
2973
  }
298
  // Find words that were deleted from search_index, but are still in
299
  // search_total. We use a LEFT JOIN between the two tables and keep only
the
300
  // rows which fail to join.
3013
  $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");
3023
  while ($word = db_fetch_object($result)) {
3030
    db_query("DELETE FROM {search_total} WHERE word = '%s'",
$word->realword);
3040
  }
3053
}
306
307
/**
308
 * Simplifies a string according to indexing rules.
309
 */
31040
function search_simplify($text) {
311
  // Decode entities to UTF-8
3129
  $text = decode_entities($text);
313
314
  // Lowercase
3159
  $text = drupal_strtolower($text);
316
317
  // Call an external processor for word handling.
3189
  search_invoke_preprocess($text);
319
320
  // Simple CJK handling
3219
  if (variable_get('overlap_cjk', TRUE)) {
3229
    $text = preg_replace_callback('/[' . PREG_CLASS_CJK . ']+/u',
'search_expand_cjk', $text);
3239
  }
324
325
  // To improve searching for numerical data such as dates, IP addresses
326
  // or version numbers, we consider a group of numerical characters
327
  // separated only by punctuation characters to be one piece.
328
  // This also means that searching for e.g. '20/03/1984' also returns
329
  // results with '20-03-1984' in them.
330
  // Readable regexp: ([number]+)[punctuation]+(?=[number])
3319
  $text = preg_replace('/([' . PREG_CLASS_NUMBERS . ']+)[' .
PREG_CLASS_PUNCTUATION . ']+(?=[' . PREG_CLASS_NUMBERS . '])/u', '\1',
$text);
332
333
  // The dot, underscore and dash are simply removed. This allows
meaningful
334
  // search behavior with acronyms and URLs.
3359
  $text = preg_replace('/[._-]+/', '', $text);
336
337
  // With the exception of the rules above, we consider all punctuation,
338
  // marks, spacers, etc, to be a word boundary.
3399
  $text = preg_replace('/[' . PREG_CLASS_SEARCH_EXCLUDE . ']+/u', ' ',
$text);
340
3419
  return $text;
3420
}
343
344
/**
345
 * Basic CJK tokenizer. Simply splits a string into consecutive,
overlapping
346
 * sequences of characters ('minimum_word_size' long).
347
 */
34840
function search_expand_cjk($matches) {
3490
  $min = variable_get('minimum_word_size', 3);
3500
  $str = $matches[0];
3510
  $l = drupal_strlen($str);
352
  // Passthrough short words
3530
  if ($l <= $min) {
3540
    return ' ' . $str . ' ';
3550
  }
3560
  $tokens = ' ';
357
  // FIFO queue of characters
3580
  $chars = array();
359
  // Begin loop
3600
  for ($i = 0; $i < $l; ++$i) {
361
    // Grab next character
3620
    $current = drupal_substr($str, 0, 1);
3630
    $str = substr($str, strlen($current));
3640
    $chars[] = $current;
3650
    if ($i >= $min - 1) {
3660
      $tokens .= implode('', $chars) . ' ';
3670
      array_shift($chars);
3680
    }
3690
  }
3700
  return $tokens;
3710
}
372
373
/**
374
 * Splits a string into tokens for indexing.
375
 */
37640
function search_index_split($text) {
3773
  static $last = NULL;
3783
  static $lastsplit = NULL;
379
3803
  if ($last == $text) {
3810
    return $lastsplit;
3820
  }
383
  // Process words
3843
  $text = search_simplify($text);
3853
  $words = explode(' ', $text);
3863
  array_walk($words, '_search_index_truncate');
387
388
  // Save last keyword result
3893
  $last = $text;
3903
  $lastsplit = $words;
391
3923
  return $words;
3930
}
394
395
/**
396
 * Helper function for array_walk in search_index_split.
397
 */
39840
function _search_index_truncate(&$text) {
3993
  $text = truncate_utf8($text, 50);
4003
}
401
402
/**
403
 * Invokes hook_search_preprocess() in modules.
404
 */
40540
function search_invoke_preprocess(&$text) {
4069
  foreach (module_implements('search_preprocess') as $module) {
4070
    $text = module_invoke($module, 'search_preprocess', $text);
4080
  }
4099
}
410
411
/**
412
 * Update the full-text search index for a particular item.
413
 *
414
 * @param $sid
415
 *   A number identifying this particular item (e.g. node id).
416
 *
417
 * @param $type
418
 *   A string defining this type of item (e.g. 'node')
419
 *
420
 * @param $text
421
 *   The content of this item. Must be a piece of HTML text.
422
 *
423
 * @ingroup search
424
 */
42540
function search_index($sid, $type, $text) {
4263
  $minimum_word_size = variable_get('minimum_word_size', 3);
427
428
  // Link matching
4293
  global $base_url;
4303
  $node_regexp = '@href=[\'"]?(?:' . preg_quote($base_url, '@') . '/|' .
preg_quote(base_path(), '@') . ')(?:\?q=)?/?((?![a-z]+:)[^\'">]+)[\'">]@i';
431
432
  // Multipliers for scores of words inside certain HTML tags.  The weights
are stored
433
  // in a variable so that modules can overwrite the default weights.
434
  // Note: 'a' must be included for link ranking to work.
4353
  $tags = variable_get('search_tag_weights', array(
4363
    'h1' => 25,
4373
    'h2' => 18,
4383
    'h3' => 15,
4393
    'h4' => 12,
4403
    'h5' => 9,
4413
    'h6' => 6,
4423
    'u' => 3,
4433
    'b' => 3,
4443
    'i' => 3,
4453
    'strong' => 3,
4463
    'em' => 3,
4473
    'a' => 10));
448
449
  // Strip off all ignored tags to speed up processing, but insert space
before/after
450
  // them to keep word boundaries.
4513
  $text = str_replace(array('<', '>'), array(' <', '> '), $text);
4523
  $text = strip_tags($text, '<' . implode('><', array_keys($tags)) . '>');
453
454
  // Split HTML tags from plain text.
4553
  $split = preg_split('/\s*<([^>]+?)>\s*/', $text, -1,
PREG_SPLIT_DELIM_CAPTURE);
456
  // Note: PHP ensures the array consists of alternating delimiters and
literals
457
  // and begins and ends with a literal (inserting $null as required).
458
4593
  $tag = FALSE; // Odd/even counter. Tag or no tag.
4603
  $link = FALSE; // State variable for link analyser
4613
  $score = 1; // Starting score per word
4623
  $accum = ' '; // Accumulator for cleaned up data
4633
  $tagstack = array(); // Stack with open tags
4643
  $tagwords = 0; // Counter for consecutive words
4653
  $focus = 1; // Focus state
466
4673
  $results = array(0 => array()); // Accumulator for words for index
468
4693
  foreach ($split as $value) {
4703
    if ($tag) {
471
      // Increase or decrease score per word based on tag
4722
      list($tagname) = explode(' ', $value, 2);
4732
      $tagname = drupal_strtolower($tagname);
474
      // Closing or opening tag?
4752
      if ($tagname[0] == '/') {
4762
        $tagname = substr($tagname, 1);
477
        // If we encounter unexpected tags, reset score to avoid incorrect
boosting.
4782
        if (!count($tagstack) || $tagstack[0] != $tagname) {
4790
          $tagstack = array();
4800
          $score = 1;
4810
        }
482
        else {
483
          // Remove from tag stack and decrement score
4842
          $score = max(1, $score - $tags[array_shift($tagstack)]);
485
        }
4862
        if ($tagname == 'a') {
4872
          $link = FALSE;
4882
        }
4892
      }
490
      else {
4912
        if (isset($tagstack[0]) && $tagstack[0] == $tagname) {
492
          // None of the tags we look for make sense when nested
identically.
493
          // If they are, it's probably broken HTML.
4940
          $tagstack = array();
4950
          $score = 1;
4960
        }
497
        else {
498
          // Add to open tag stack and increment score
4992
          array_unshift($tagstack, $tagname);
5002
          $score += $tags[$tagname];
501
        }
5022
        if ($tagname == 'a') {
503
          // Check if link points to a node on this site
5042
          if (preg_match($node_regexp, $value, $match)) {
5050
            $path = drupal_get_normal_path($match[1]);
5060
            if (preg_match('!(?:node|book)/(?:view/)?([0-9]+)!i', $path,
$match)) {
5070
              $linknid = $match[1];
5080
              if ($linknid > 0) {
509
                // Note: ignore links to uncachable nodes to avoid redirect
bugs.
5100
                $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));
5110
                if (filter_format_allowcache($node->format)) {
5120
                  $link = TRUE;
5130
                  $linktitle = $node->title;
5140
                }
5150
              }
5160
            }
5170
          }
5182
        }
519
      }
520
      // A tag change occurred, reset counter.
5212
      $tagwords = 0;
5222
    }
523
    else {
524
      // Note: use of PREG_SPLIT_DELIM_CAPTURE above will introduce empty
values
5253
      if ($value != '') {
5263
        if ($link) {
527
          // Check to see if the node link text is its URL. If so, we use
the target node title instead.
5280
          if (preg_match('!^https?://!i', $value)) {
5290
            $value = $linktitle;
5300
          }
5310
        }
5323
        $words = search_index_split($value);
5333
        foreach ($words as $word) {
534
          // Add word to accumulator
5353
          $accum .= $word . ' ';
5363
          $num = is_numeric($word);
537
          // Check wordlength
5383
          if ($num || drupal_strlen($word) >= $minimum_word_size) {
539
            // Normalize numbers
5403
            if ($num) {
5410
              $word = (int)ltrim($word, '-0');
5420
            }
543
544
            // Links score mainly for the target.
5453
            if ($link) {
5460
              if (!isset($results[$linknid])) {
5470
                $results[$linknid] = array();
5480
              }
5490
              $results[$linknid][] = $word;
550
              // Reduce score of the link caption in the source.
5510
              $focus *= 0.2;
5520
            }
553
            // Fall-through
5543
            if (!isset($results[0][$word])) {
5553
              $results[0][$word] = 0;
5563
            }
5573
            $results[0][$word] += $score * $focus;
558
559
            // Focus is a decaying value in terms of the amount of unique
words up to this point.
560
            // From 100 words and more, it decays, to e.g. 0.5 at 500 words
and 0.3 at 1000 words.
5613
            $focus = min(1, .01 + 3.5 / (2 + count($results[0]) * .015));
5623
          }
5633
          $tagwords++;
564
          // Too many words inside a single tag probably mean a tag was
accidentally left open.
5653
          if (count($tagstack) && $tagwords >= 15) {
5660
            $tagstack = array();
5670
            $score = 1;
5680
          }
5693
        }
5703
      }
571
    }
5723
    $tag = !$tag;
5733
  }
574
5753
  search_wipe($sid, $type, TRUE);
576
577
  // Insert cleaned up data into dataset
5783
  db_query("INSERT INTO {search_dataset} (sid, type, data, reindex) VALUES
(%d, '%s', '%s', %d)", $sid, $type, $accum, 0);
579
580
  // Insert results into search index
5813
  foreach ($results[0] as $word => $score) {
582
    // If a word already exists in the database, its score gets increased 
583
    // appropriately.  If not, we create a new record with the appropriate 
584
    // starting score.
5853
    db_merge('search_index')->key(array(
5863
      'word' => $word,
5873
      'sid' => $sid,
5883
      'type' => $type,
5893
    ))->fields(array('score' => $score))->expression('score', 'score +
:score', array(':score' => $score))
5903
    ->execute();
5913
    search_dirty($word);
5923
  }
5933
  unset($results[0]);
594
595
  // Get all previous links from this item.
5963
  $result = db_query("SELECT nid, caption FROM {search_node_links} WHERE
sid = %d AND type = '%s'", $sid, $type);
5973
  $links = array();
5983
  while ($link = db_fetch_object($result)) {
5990
    $links[$link->nid] = $link->caption;
6000
  }
601
602
  // Now store links to nodes.
6033
  foreach ($results as $nid => $words) {
6040
    $caption = implode(' ', $words);
6050
    if (isset($links[$nid])) {
6060
      if ($links[$nid] != $caption) {
607
        // Update the existing link and mark the node for reindexing.
6080
        db_query("UPDATE {search_node_links} SET caption = '%s' WHERE sid =
%d AND type = '%s' AND nid = %d", $caption, $sid, $type, $nid);
6090
        search_touch_node($nid);
6100
      }
611
      // Unset the link to mark it as processed.
6120
      unset($links[$nid]);
6130
    }
614
    else {
615
      // Insert the existing link and mark the node for reindexing.
6160
      db_query("INSERT INTO {search_node_links} (caption, sid, type, nid)
VALUES ('%s', %d, '%s', %d)", $caption, $sid, $type, $nid);
6170
      search_touch_node($nid);
618
    }
6190
  }
620
  // Any left-over links in $links no longer exist. Delete them and mark
the nodes for reindexing.
6213
  foreach ($links as $nid => $caption) {
6220
    db_query("DELETE FROM {search_node_links} WHERE sid = %d AND type =
'%s' AND nid = %d", $sid, $type, $nid);
6230
    search_touch_node($nid);
6240
  }
6253
}
626
627
/**
628
 * Change a node's changed timestamp to 'now' to force reindexing.
629
 *
630
 * @param $nid
631
 *   The nid of the node that needs reindexing.
632
 */
63340
function search_touch_node($nid) {
6341
  db_query("UPDATE {search_dataset} SET reindex = %d WHERE sid = %d AND
type = 'node'", REQUEST_TIME, $nid);
6351
}
636
637
/**
638
 * Implementation of hook_nodeapi_update_index().
639
 */
64040
function search_nodeapi_update_index(&$node, $teaser = NULL, $page = NULL)
{
641
  // Transplant links to a node into the target node.
6422
  $result = db_query("SELECT caption FROM {search_node_links} WHERE nid =
%d", $node->nid);
6432
  $output = array();
6442
  while ($link = db_fetch_object($result)) {
6450
    $output[] = $link->caption;
6460
  }
6472
  return '<a>(' . implode(', ', $output) . ')</a>';
6480
}
649
650
/**
651
 * Implementation of hook_nodeapi_update().
652
 */
65340
function search_nodeapi_update(&$node, $teaser = NULL, $page = NULL) {
654
  // Reindex the node when it is updated.  The node is automatically
indexed
655
  // when it is added, simply by being added to the node table.
6560
  search_touch_node($node->nid);
6570
}
658
659
/**
660
 * Implementation of hook_comment().
661
 */
66240
function search_comment($a1, $op) {
663
  switch ($op) {
664
    // Reindex the node when comments are added or changed
6653
    case 'insert':
6663
    case 'update':
6673
    case 'delete':
6683
    case 'publish':
6693
    case 'unpublish':
6701
      search_touch_node(is_array($a1) ? $a1['nid'] : $a1->nid);
6711
      break;
6720
  }
6733
}
674
675
/**
676
 * Extract a module-specific search option from a search query. e.g.
'type:book'
677
 */
67840
function search_query_extract($keys, $option) {
6799
  if (preg_match('/(^| )' . $option . ':([^ ]*)( |$)/i', $keys, $matches))
{
6802
    return $matches[2];
6810
  }
6829
}
683
684
/**
685
 * Return a query with the given module-specific search option inserted in.
686
 * e.g. 'type:book'.
687
 */
68840
function search_query_insert($keys, $option, $value = '') {
6894
  if (search_query_extract($keys, $option)) {
6902
    $keys = trim(preg_replace('/(^| )' . $option . ':[^ ]*/i', '', $keys));
6912
  }
6924
  if ($value != '') {
6932
    $keys .= ' ' . $option . ':' . $value;
6942
  }
6954
  return $keys;
6960
}
697
698
/**
699
 * Parse a search query into SQL conditions.
700
 *
701
 * We build two queries that matches the dataset bodies. @See do_search for
702
 * more about these.
703
 *
704
 * @param $text
705
 *   The search keys.
706
 * @return
707
 *   A list of six elements.
708
 *    * A series of statements AND'd together which will be used to provide
all
709
 *      possible matches.
710
 *    * Arguments for this query part.
711
 *    * A series of exact word matches OR'd together.
712
 *    * Arguments for this query part.
713
 *    * A bool indicating whether this is a simple query or not. Negative
714
 *      terms, presence of both AND / OR make this FALSE.
715
 *    * A bool indicating the presence of a lowercase or. Maybe the user
716
 *      wanted to use OR.
717
 */
71840
function search_parse_query($text) {
7198
  $keys = array('positive' => array(), 'negative' => array());
720
721
  // Tokenize query string
7228
  preg_match_all('/ (-?)("[^"]+"|[^" ]+)/i', ' ' . $text, $matches,
PREG_SET_ORDER);
723
7248
  if (count($matches) < 1) {
7250
    return NULL;
7260
  }
727
728
  // Classify tokens
7298
  $or = FALSE;
7308
  $warning = '';
7318
  $simple = TRUE;
7328
  foreach ($matches as $match) {
7338
    $phrase = FALSE;
734
    // Strip off phrase quotes
7358
    if ($match[2]{0} == '"') {
7361
      $match[2] = substr($match[2], 1, -1);
7371
      $phrase = TRUE;
7381
      $simple = FALSE;
7391
    }
740
    // Simplify keyword according to indexing rules and external
preprocessors
7418
    $words = search_simplify($match[2]);
742
    // Re-explode in case simplification added more words, except when
matching a phrase
7438
    $words = $phrase ? array($words) : preg_split('/ /', $words, -1,
PREG_SPLIT_NO_EMPTY);
744
    // Negative matches
7458
    if ($match[1] == '-') {
7461
      $keys['negative'] = array_merge($keys['negative'], $words);
7471
    }
748
    // OR operator: instead of a single keyword, we store an array of all
749
    // OR'd keywords.
7508
    elseif ($match[2] == 'OR' && count($keys['positive'])) {
7511
      $last = array_pop($keys['positive']);
752
      // Starting a new OR?
7531
      if (!is_array($last)) {
7541
        $last = array($last);
7551
      }
7561
      $keys['positive'][] = $last;
7571
      $or = TRUE;
7581
      continue;
7590
    }
760
    // AND operator: implied, so just ignore it
7618
    elseif ($match[2] == 'AND' || $match[2] == 'and') {
7620
      $warning = $match[2];
7630
      continue;
7640
    }
765
766
    // Plain keyword
767
    else {
7688
      if ($match[2] == 'or') {
7690
        $warning = $match[2];
7700
      }
7718
      if ($or) {
772
        // Add to last element (which is an array)
7731
        $keys['positive'][count($keys['positive']) - 1] =
array_merge($keys['positive'][count($keys['positive']) - 1], $words);
7741
      }
775
      else {
7768
        $keys['positive'] = array_merge($keys['positive'], $words);
777
      }
778
    }
7798
    $or = FALSE;
7808
  }
781
782
  // Convert keywords into SQL statements.
7838
  $query = array();
7848
  $query2 = array();
7858
  $arguments = array();
7868
  $arguments2 = array();
7878
  $matches = 0;
7888
  $simple_and = FALSE;
7898
  $simple_or = FALSE;
790
  // Positive matches
7918
  foreach ($keys['positive'] as $key) {
792
    // Group of ORed terms
7938
    if (is_array($key) && count($key)) {
7941
      $simple_or = TRUE;
7951
      $queryor = array();
7961
      $any = FALSE;
7971
      foreach ($key as $or) {
7981
        list($q, $num_new_scores) = _search_parse_query($or, $arguments2);
7991
        $any |= $num_new_scores;
8001
        if ($q) {
8011
          $queryor[] = $q;
8021
          $arguments[] = "% $or %";
8031
        }
8041
      }
8051
      if (count($queryor)) {
8061
        $query[] = '(' . implode(' OR ', $queryor) . ')';
807
        // A group of OR keywords only needs to match once
8081
        $matches += ($any > 0);
8091
      }
8101
    }
811
    // Single ANDed term
812
    else {
8138
      $simple_and = TRUE;
8148
      list($q, $num_new_scores, $num_valid_words) =
_search_parse_query($key, $arguments2);
8158
      if ($q) {
8168
        $query[] = $q;
8178
        $arguments[] = "% $key %";
8188
        if (!$num_valid_words) {
8191
          $simple = FALSE;
8201
        }
821
        // Each AND keyword needs to match at least once
8228
        $matches += $num_new_scores;
8238
      }
824
    }
8258
  }
8268
  if ($simple_and && $simple_or) {
8271
    $simple = FALSE;
8281
  }
829
  // Negative matches
8308
  foreach ($keys['negative'] as $key) {
8311
    list($q) = _search_parse_query($key, $arguments2, TRUE);
8321
    if ($q) {
8331
      $query[] = $q;
8341
      $arguments[] = "% $key %";
8351
      $simple = FALSE;
8361
    }
8371
  }
8388
  $query = implode(' AND ', $query);
839
840
  // Build word-index conditions for the first pass
8418
  $query2 = substr(str_repeat("i.word = '%s' OR ", count($arguments2)), 0,
-4);
842
8438
  return array($query, $arguments, $query2, $arguments2, $matches, $simple,
$warning);
8440
}
845
846
/**
847
 * Helper function for search_parse_query();
848
 */
84940
function _search_parse_query(&$word, &$scores, $not = FALSE) {
8508
  $num_new_scores = 0;
8518
  $num_valid_words = 0;
852
  // Determine the scorewords of this word/phrase
8538
  if (!$not) {
8548
    $split = explode(' ', $word);
8558
    foreach ($split as $s) {
8568
      $num = is_numeric($s);
8578
      if ($num || drupal_strlen($s) >= variable_get('minimum_word_size',
3)) {
8588
        $s = $num ? ((int)ltrim($s, '-0')) : $s;
8598
        if (!isset($scores[$s])) {
8608
          $scores[$s] = $s;
8618
          $num_new_scores++;
8628
        }
8638
        $num_valid_words++;
8648
      }
8658
    }
8668
  }
867
  // Return matching snippet and number of added words
8688
  return array("d.data " . ($not ? 'NOT ' : '') . "LIKE '%s'",
$num_new_scores, $num_valid_words);
8690
}
870
871
/**
872
 * Do a query on the full-text search index for a word or words.
873
 *
874
 * This function is normally only called by each module that support the
875
 * indexed search (and thus, implements hook_update_index()).
876
 *
877
 * Results are retrieved in two logical passes. However, the two passes are
878
 * joined together into a single query.  And in the case of most simple
879
 * queries the second pass is not even used.
880
 *
881
 * The first pass selects a set of all possible matches, which has the
benefit
882
 * of also providing the exact result set for simple "AND" or "OR"
searches.
883
 *
884
 * The second portion of the query further refines this set by verifying
885
 * advanced text conditions (such negative or phrase matches)
886
 *
887
 * @param $keywords
888
 *   A search string as entered by the user.
889
 *
890
 * @param $type
891
 *   A string identifying the calling module.
892
 *
893
 * @param $join1
894
 *   (optional) Inserted into the JOIN part of the first SQL query.
895
 *   For example "INNER JOIN {node} n ON n.nid = i.sid".
896
 *
897
 * @param $where1
898
 *   (optional) Inserted into the WHERE part of the first SQL query.
899
 *   For example "(n.status > %d)".
900
 *
901
 * @param $arguments1
902
 *   (optional) Extra SQL arguments belonging to the first query.
903
 *
904
 * @param $columns2
905
 *   (optional) Inserted into the SELECT pat of the second query. Must
contain
906
 *   a column selected as 'score'.
907
 *   defaults to 'i.relevance AS score'
908
 *
909
 * @param $join2
910
 *   (optional) Inserted into the JOIN par of the second SQL query.
911
 *   For example "INNER JOIN {node_comment_statistics} n ON n.nid = i.sid"
912
 *
913
 * @param $arguments2
914
 *   (optional) Extra SQL arguments belonging to the second query
parameter.
915
 *
916
 * @param $sort_parameters
917
 *   (optional) SQL arguments for sorting the final results.
918
 *              Default: 'ORDER BY score DESC'
919
 *
920
 * @return
921
 *   An array of SIDs for the search results.
922
 *
923
 * @ingroup search
924
 */
92540
function do_search($keywords, $type, $join1 = '', $where1 = '1 = 1',
$arguments1 = array(), $columns2 = 'i.relevance AS score', $join2 = '',
$arguments2 = array(), $sort_parameters = 'ORDER BY score DESC') {
9268
  $query = search_parse_query($keywords);
927
9288
  if ($query[2] == '') {
9290
    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))));
9300
  }
9318
  if ($query[6]) {
9320
    if ($query[6] == 'or') {
9330
      drupal_set_message(t('Search for either of the two terms with
uppercase <strong>OR</strong>. For example, <strong>cats OR
dogs</strong>.'));
9340
    }
9350
  }
9368
  if ($query === NULL || $query[0] == '' || $query[2] == '') {
9370
    return array();
9380
  }
939
940
  // Build query for keyword normalization.
9418
  $conditions = "$where1 AND ($query[2]) AND i.type = '%s'";
9428
  $arguments1 = array_merge($arguments1, $query[3], array($type));
9438
  $join = "INNER JOIN {search_total} t ON i.word = t.word $join1";
9448
  if (!$query[5]) {
9451
    $conditions .= " AND ($query[0])";
9461
    $arguments1 = array_merge($arguments1, $query[1]);
9471
    $join .= " INNER JOIN {search_dataset} d ON i.sid = d.sid AND i.type =
d.type";
9481
  }
949
950
  // Calculate maximum keyword relevance, to normalize it.
9518
  $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";
9528
  $arguments = array_merge($arguments1, array($query[4]));
9538
  $normalize = db_result(db_query_range($select, $arguments, 0, 1));
9548
  if (!$normalize) {
9554
    return array();
9560
  }
9575
  $columns2 = str_replace('i.relevance', '(' . (1.0 / $normalize) . ' *
SUM(i.score * t.count))', $columns2);
958
959
  // Build query to retrieve results.
9605
  $select = "SELECT i.type, i.sid, $columns2 FROM {search_index} i $join
$join2 WHERE $conditions GROUP BY i.type, i.sid HAVING COUNT(*) >= %d";
9615
  $count_select =  "SELECT COUNT(*) FROM ($select) n1";
9625
  $arguments = array_merge($arguments2, $arguments1, array($query[4]));
963
964
  // Do actual search query
9655
  $result = pager_query("$select $sort_parameters", 10, 0, $count_select,
$arguments);
9665
  $results = array();
9675
  while ($item = db_fetch_object($result)) {
9685
    $results[] = $item;
9695
  }
9705
  return $results;
9710
}
972
973
/**
974
 * Helper function for grabbing search keys.
975
 */
97640
function search_get_keys() {
97711
  static $return;
97811
  if (!isset($return)) {
979
    // Extract keys as remainder of path
980
    // Note: support old GET format of searches for existing links.
98111
    $path = explode('/', $_GET['q'], 3);
98211
    $keys = empty($_REQUEST['keys']) ? '' : $_REQUEST['keys'];
98311
    $return = count($path) == 3 ? $path[2] : $keys;
98411
  }
98511
  return $return;
9860
}
987
988
/**
989
 * @defgroup search Search interface
990
 * @{
991
 * The Drupal search interface manages a global search mechanism.
992
 *
993
 * Modules may plug into this system to provide searches of different types
of
994
 * data. Most of the system is handled by search.module, so this must be
enabled
995
 * for all of the search features to work.
996
 *
997
 * There are three ways to interact with the search system:
998
 * - Specifically for searching nodes, you can implement
nodeapi('update_index')
999
 *   and nodeapi('search_result'). However, note that the search system
already
1000
 *   indexes all visible output of a node, i.e. everything displayed
normally
1001
 *   by hook_view() and hook_nodeapi('view'). This is usually sufficient.
1002
 *   You should only use this mechanism if you want additional, non-visible
data
1003
 *   to be indexed.
1004
 * - Implement hook_search(). This will create a search tab for your module
on
1005
 *   the /search page with a simple keyword search form. You may optionally
1006
 *   implement hook_search_item() to customize the display of your results.
1007
 * - Implement hook_update_index(). This allows your module to use Drupal's
1008
 *   HTML indexing mechanism for searching full text efficiently.
1009
 *
1010
 * If your module needs to provide a more complicated search form, then you
need
1011
 * to implement it yourself without hook_search(). In that case, you should
1012
 * define it as a local task (tab) under the /search page (e.g.
/search/mymodule)
1013
 * so that users can easily find it.
1014
 */
1015
1016
/**
1017
 * Render a search form.
1018
 *
1019
 * @param $action
1020
 *   Form action. Defaults to "search".
1021
 * @param $keys
1022
 *   The search string entered by the user, containing keywords for the
search.
1023
 * @param $type
1024
 *   The type of search to render the node for. Must be the name of module
1025
 *   which implements hook_search(). Defaults to 'node'.
1026
 * @param $prompt
1027
 *   A piece of text to put before the form (e.g. "Enter your keywords")
1028
 * @return
1029
 *   An HTML string containing the search form.
1030
 */
103140
function search_form(&$form_state, $action = '', $keys = '', $type = NULL,
$prompt = NULL) {
1032
1033
  // Add CSS
103415
  drupal_add_css(drupal_get_path('module', 'search') . '/search.css',
array('preprocess' => FALSE));
1035
103615
  if (!$action) {
103715
    $action = url('search/' . $type);
103815
  }
103915
  if (is_null($prompt)) {
104015
    $prompt = t('Enter your keywords');
104115
  }
1042
1043
  $form = array(
104415
    '#action' => $action,
104515
    '#attributes' => array('class' => 'search-form'),
104615
  );
104715
  $form['module'] = array('#type' => 'value', '#value' => $type);
104815
  $form['basic'] = array('#type' => 'item', '#title' => $prompt);
104915
  $form['basic']['inline'] = array('#prefix' => '<div
class="container-inline">', '#suffix' => '</div>');
105015
  $form['basic']['inline']['keys'] = array(
105115
    '#type' => 'textfield',
105215
    '#title' => '',
105315
    '#default_value' => $keys,
105415
    '#size' => $prompt ? 40 : 20,
105515
    '#maxlength' => 255,
1056
  );
1057
  // processed_keys is used to coordinate keyword passing between other
forms
1058
  // that hook into the basic search form.
105915
  $form['basic']['inline']['processed_keys'] = array('#type' => 'value',
'#value' => array());
106015
  $form['basic']['inline']['submit'] = array('#type' => 'submit', '#value'
=> t('Search'));
1061
106215
  return $form;
10630
}
1064
1065
/**
1066
 * Form builder; Output a search form for the search block and the theme's
search box.
1067
 *
1068
 * @ingroup forms
1069
 * @see search_box_form_submit()
1070
 * @see theme_search_box_form()
1071
 */
107240
function search_box(&$form_state, $form_id) {
107313
  $form[$form_id] = array(
107413
    '#title' => t('Search this site'),
107513
    '#type' => 'textfield',
107613
    '#size' => 15,
107713
    '#default_value' => '',
107813
    '#attributes' => array('title' => t('Enter the terms you wish to search
for.')),
1079
  );
108013
  $form['submit'] = array('#type' => 'submit', '#value' => t('Search'));
108113
  $form['#submit'][] = 'search_box_form_submit';
1082
108313
  return $form;
10840
}
1085
1086
/**
1087
 * Process a block search form submission.
1088
 */
108940
function search_box_form_submit($form, &$form_state) {
10900
  $form_id = $form['form_id']['#value'];
10910
  $form_state['redirect'] = 'search/node/' .
trim($form_state['values'][$form_id]);
10920
}
1093
1094
/**
1095
 * Process variables for search-theme-form.tpl.php.
1096
 *
1097
 * The $variables array contains the following arguments:
1098
 * - $form
1099
 *
1100
 * @see search-theme-form.tpl.php
1101
 */
110240
function template_preprocess_search_theme_form(&$variables) {
110313
  $variables['search'] = array();
110413
  $hidden = array();
1105
  // Provide variables named after form keys so themers can print each
element independently.
110613
  foreach (element_children($variables['form']) as $key) {
110713
    $type = $variables['form'][$key]['#type'];
110813
    if ($type == 'hidden' || $type == 'token') {
110913
      $hidden[] = drupal_render($variables['form'][$key]);
111013
    }
1111
    else {
111213
      $variables['search'][$key] = drupal_render($variables['form'][$key]);
1113
    }
111413
  }
1115
  // Hidden form elements have no value to themers. No need for separation.
111613
  $variables['search']['hidden'] = implode($hidden);
1117
  // Collect all form elements to make it easier to print the whole form.
111813
  $variables['search_form'] = implode($variables['search']);
111913
}
1120
1121
/**
1122
 * Process variables for search-block-form.tpl.php.
1123
 *
1124
 * The $variables array contains the following arguments:
1125
 * - $form
1126
 *
1127
 * @see search-block-form.tpl.php
1128
 */
112940
function template_preprocess_search_block_form(&$variables) {
11300
  $variables['search'] = array();
11310
  $hidden = array();
1132
  // Provide variables named after form keys so themers can print each
element independently.
11330
  foreach (element_children($variables['form']) as $key) {
11340
    $type = $variables['form'][$key]['#type'];
11350
    if ($type == 'hidden' || $type == 'token') {
11360
      $hidden[] = drupal_render($variables['form'][$key]);
11370
    }
1138
    else {
11390
      $variables['search'][$key] = drupal_render($variables['form'][$key]);
1140
    }
11410
  }
1142
  // Hidden form elements have no value to themers. No need for separation.
11430
  $variables['search']['hidden'] = implode($hidden);
1144
  // Collect all form elements to make it easier to print the whole form.
11450
  $variables['search_form'] = implode($variables['search']);
11460
}
1147
1148
/**
1149
 * Perform a standard search on the given keys, and return the formatted
results.
1150
 */
115140
function search_data($keys = NULL, $type = 'node') {
1152
11536
  if (isset($keys)) {
11546
    if (module_hook($type, 'search')) {
11556
      $results = module_invoke($type, 'search', 'search', $keys);
11566
      if (isset($results) && is_array($results) && count($results)) {
11573
        if (module_hook($type, 'search_page')) {
11580
          return module_invoke($type, 'search_page', $results);
11590
        }
1160
        else {
11613
          return theme('search_results', $results, $type);
1162
        }
11630
      }
11643
    }
11653
  }
11663
}
1167
1168
/**
1169
 * Returns snippets from a piece of text, with certain keywords
highlighted.
1170
 * Used for formatting search results.
1171
 *
1172
 * @param $keys
1173
 *   A string containing a search query.
1174
 *
1175
 * @param $text
1176
 *   The text to extract fragments from.
1177
 *
1178
 * @return
1179
 *   A string containing HTML for the excerpt.
1180
 */
118140
function search_excerpt($keys, $text) {
1182
  // We highlight around non-indexable or CJK characters.
11834
  $boundary = '(?:(?<=[' . PREG_CLASS_SEARCH_EXCLUDE . PREG_CLASS_CJK .
'])|(?=[' . PREG_CLASS_SEARCH_EXCLUDE . PREG_CLASS_CJK . ']))';
1184
1185
  // Extract positive keywords and phrases
11864
  preg_match_all('/ ("([^"]+)"|(?!OR)([^" ]+))/', ' ' . $keys, $matches);
11874
  $keys = array_merge($matches[2], $matches[3]);
1188
1189
  // Prepare text
11904
  $text = ' ' . strip_tags(str_replace(array('<', '>'), array(' <', '> '),
$text)) . ' ';
11914
  array_walk($keys, '_search_excerpt_replace');
11924
  $workkeys = $keys;
1193
1194
  // Extract a fragment per keyword for at most 4 keywords.
1195
  // First we collect ranges of text around each keyword, starting/ending
1196
  // at spaces.
1197
  // If the sum of all fragments is too short, we look for second
occurrences.
11984
  $ranges = array();
11994
  $included = array();
12004
  $length = 0;
12014
  while ($length < 256 && count($workkeys)) {
12024
    foreach ($workkeys as $k => $key) {
12034
      if (strlen($key) == 0) {
12044
        unset($workkeys[$k]);
12054
        unset($keys[$k]);
12064
        continue;
12070
      }
12084
      if ($length >= 256) {
12090
        break;
12100
      }
1211
      // Remember occurrence of key so we can skip over it if more
occurrences
1212
      // are desired.
12134
      if (!isset($included[$key])) {
12144
        $included[$key] = 0;
12154
      }
1216
      // Locate a keyword (position $p), then locate a space in front
(position
1217
      // $q) and behind it (position $s)
12184
      if (preg_match('/' . $boundary . $key . $boundary . '/iu', $text,
$match, PREG_OFFSET_CAPTURE, $included[$key])) {
12191
        $p = $match[0][1];
12201
        if (($q = strpos($text, ' ', max(0, $p - 60))) !== FALSE) {
12211
          $end = substr($text, $p, 80);
12221
          if (($s = strrpos($end, ' ')) !== FALSE) {
12231
            $ranges[$q] = $p + $s;
12241
            $length += $p + $s - $q;
12251
            $included[$key] = $p + 1;
12261
          }
1227
          else {
12280
            unset($workkeys[$k]);
1229
          }
12301
        }
1231
        else {
12320
          unset($workkeys[$k]);
1233
        }
12341
      }
1235
      else {
12364
        unset($workkeys[$k]);
1237
      }
12384
    }
12394
  }
1240
1241
  // If we didn't find anything, return the beginning.
12424
  if (count($ranges) == 0) {
12433
    return truncate_utf8($text, 256) . ' ...';
12440
  }
1245
1246
  // Sort the text ranges by starting position.
12471
  ksort($ranges);
1248
1249
  // Now we collapse overlapping text ranges into one. The sorting makes it
O(n).
12501
  $newranges = array();
12511
  foreach ($ranges as $from2 => $to2) {
12521
    if (!isset($from1)) {
12531
      $from1 = $from2;
12541
      $to1 = $to2;
12551
      continue;
12560
    }
12570
    if ($from2 <= $to1) {
12580
      $to1 = max($to1, $to2);
12590
    }
1260
    else {
12610
      $newranges[$from1] = $to1;
12620
      $from1 = $from2;
12630
      $to1 = $to2;
1264
    }
12650
  }
12661
  $newranges[$from1] = $to1;
1267
1268
  // Fetch text
12691
  $out = array();
12701
  foreach ($newranges as $from => $to) {
12711
    $out[] = substr($text, $from, $to - $from);
12721
  }
12731
  $text = (isset($newranges[0]) ? '' : '... ') . implode(' ... ', $out) . '
...';
1274
1275
  // Highlight keywords. Must be done at once to prevent conflicts
('strong' and '<strong>').
12761
  $text = preg_replace('/' . $boundary . '(' . implode('|', $keys) . ')' .
$boundary . '/iu', '<strong>\0</strong>', $text);
12771
  return $text;
12780
}
1279
1280
/**
1281
 * @} End of "defgroup search".
1282
 */
1283
1284
/**
1285
 * Helper function for array_walk in search_except.
1286
 */
128740
function _search_excerpt_replace(&$text) {
12884
  $text = preg_quote($text, '/');
12894
}
1290
129140
function search_forms() {
129213
  $forms['search_theme_form']= array(
129313
    'callback' => 'search_box',
129413
    'callback arguments' => array('search_theme_form'),
1295
  );
129613
  $forms['search_block_form']= array(
129713
    'callback' => 'search_box',
129813
    'callback arguments' => array('search_block_form'),
1299
  );
130013
  return $forms;
13010
}
130240