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

Line #Times calledCode
1
<?php
2
// $Id: search.module,v 1.260 2008/07/24 16:25:18 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
 */
2224
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}-'
.
2424
'\x{385}\x{387}\x{3f6}\x{482}-\x{489}\x{559}-\x{55f}\x{589}-\x{5c7}\x{5f3}-'
.
2524
'\x{61f}\x{640}\x{64b}-\x{65e}\x{66a}-\x{66d}\x{670}\x{6d4}\x{6d6}-\x{6ed}'
.
2624
'\x{6fd}\x{6fe}\x{700}-\x{70f}\x{711}\x{730}-\x{74a}\x{7a6}-\x{7b0}\x{901}-'
.
2724
'\x{903}\x{93c}\x{93e}-\x{94d}\x{951}-\x{954}\x{962}-\x{965}\x{970}\x{981}-'
.
2824
'\x{983}\x{9bc}\x{9be}-\x{9cd}\x{9d7}\x{9e2}\x{9e3}\x{9f2}-\x{a03}\x{a3c}-'
.
2924
'\x{a4d}\x{a70}\x{a71}\x{a81}-\x{a83}\x{abc}\x{abe}-\x{acd}\x{ae2}\x{ae3}'
.
3024
'\x{af1}-\x{b03}\x{b3c}\x{b3e}-\x{b57}\x{b70}\x{b82}\x{bbe}-\x{bd7}\x{bf0}-'
.
3124
'\x{c03}\x{c3e}-\x{c56}\x{c82}\x{c83}\x{cbc}\x{cbe}-\x{cd6}\x{d02}\x{d03}'
.
3224
'\x{d3e}-\x{d57}\x{d82}\x{d83}\x{dca}-\x{df4}\x{e31}\x{e34}-\x{e3f}\x{e46}-'
.
3324
'\x{e4f}\x{e5a}\x{e5b}\x{eb1}\x{eb4}-\x{ebc}\x{ec6}-\x{ecd}\x{f01}-\x{f1f}'
.
3424
'\x{f2a}-\x{f3f}\x{f71}-\x{f87}\x{f90}-\x{fd1}\x{102c}-\x{1039}\x{104a}-'
.
3524
'\x{104f}\x{1056}-\x{1059}\x{10fb}\x{10fc}\x{135f}-\x{137c}\x{1390}-\x{1399}'
.
3624
'\x{166d}\x{166e}\x{1680}\x{169b}\x{169c}\x{16eb}-\x{16f0}\x{1712}-\x{1714}'
.
3724
'\x{1732}-\x{1736}\x{1752}\x{1753}\x{1772}\x{1773}\x{17b4}-\x{17db}\x{17dd}'
.
3824
'\x{17f0}-\x{180e}\x{1843}\x{18a9}\x{1920}-\x{1945}\x{19b0}-\x{19c0}\x{19c8}'
.
3924
'\x{19c9}\x{19de}-\x{19ff}\x{1a17}-\x{1a1f}\x{1d2c}-\x{1d61}\x{1d78}\x{1d9b}-'
.
4024
'\x{1dc3}\x{1fbd}\x{1fbf}-\x{1fc1}\x{1fcd}-\x{1fcf}\x{1fdd}-\x{1fdf}\x{1fed}-'
.
4124
'\x{1fef}\x{1ffd}-\x{2070}\x{2074}-\x{207e}\x{2080}-\x{2101}\x{2103}-\x{2106}'
.
4224
'\x{2108}\x{2109}\x{2114}\x{2116}-\x{2118}\x{211e}-\x{2123}\x{2125}\x{2127}'
.
4324
'\x{2129}\x{212e}\x{2132}\x{213a}\x{213b}\x{2140}-\x{2144}\x{214a}-\x{2b13}'
.
4424
'\x{2ce5}-\x{2cff}\x{2d6f}\x{2e00}-\x{3005}\x{3007}-\x{303b}\x{303d}-\x{303f}'
.
4524
'\x{3099}-\x{309e}\x{30a0}\x{30fb}-\x{30fe}\x{3190}-\x{319f}\x{31c0}-\x{31cf}'
.
4624
'\x{3200}-\x{33ff}\x{4dc0}-\x{4dff}\x{a015}\x{a490}-\x{a716}\x{a802}\x{a806}'
.
4724
'\x{a80b}\x{a823}-\x{a82b}\x{d800}-\x{f8ff}\x{fb1e}\x{fb29}\x{fd3e}\x{fd3f}'
.
4824
'\x{fdfc}-\x{fe6b}\x{feff}-\x{ff0f}\x{ff1a}-\x{ff20}\x{ff3b}-\x{ff40}\x{ff5b}-'
.
4924
'\x{ff65}\x{ff70}\x{ff9e}\x{ff9f}\x{ffe0}-\x{fffd}');
50
51
/**
52
 * Matches all 'N' Unicode character classes (numbers)
53
 */
5424
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}'.
5624
'\x{966}-\x{96f}\x{9e6}-\x{9ef}\x{9f4}-\x{9f9}\x{a66}-\x{a6f}\x{ae6}-\x{aef}'.
5724
'\x{b66}-\x{b6f}\x{be7}-\x{bf2}\x{c66}-\x{c6f}\x{ce6}-\x{cef}\x{d66}-\x{d6f}'.
5824
'\x{e50}-\x{e59}\x{ed0}-\x{ed9}\x{f20}-\x{f33}\x{1040}-\x{1049}\x{1369}-'.
5924
'\x{137c}\x{16ee}-\x{16f0}\x{17e0}-\x{17e9}\x{17f0}-\x{17f9}\x{1810}-\x{1819}'.
6024
'\x{1946}-\x{194f}\x{2070}\x{2074}-\x{2079}\x{2080}-\x{2089}\x{2153}-\x{2183}'.
6124
'\x{2460}-\x{249b}\x{24ea}-\x{24ff}\x{2776}-\x{2793}\x{3007}\x{3021}-\x{3029}'.
6224
'\x{3038}-\x{303a}\x{3192}-\x{3195}\x{3220}-\x{3229}\x{3251}-\x{325f}\x{3280}-'.
6324
'\x{3289}\x{32b1}-\x{32bf}\x{ff10}-\x{ff19}');
64
65
/**
66
 * Matches all 'P' Unicode character classes (punctuation)
67
 */
6824
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}'.
7024
'\x{5f}\x{7b}\x{7d}\x{a1}\x{ab}\x{b7}\x{bb}\x{bf}\x{37e}\x{387}\x{55a}-\x{55f}'.
7124
'\x{589}\x{58a}\x{5be}\x{5c0}\x{5c3}\x{5f3}\x{5f4}\x{60c}\x{60d}\x{61b}\x{61f}'.
7224
'\x{66a}-\x{66d}\x{6d4}\x{700}-\x{70d}\x{964}\x{965}\x{970}\x{df4}\x{e4f}'.
7324
'\x{e5a}\x{e5b}\x{f04}-\x{f12}\x{f3a}-\x{f3d}\x{f85}\x{104a}-\x{104f}\x{10fb}'.
7424
'\x{1361}-\x{1368}\x{166d}\x{166e}\x{169b}\x{169c}\x{16eb}-\x{16ed}\x{1735}'.
7524
'\x{1736}\x{17d4}-\x{17d6}\x{17d8}-\x{17da}\x{1800}-\x{180a}\x{1944}\x{1945}'.
7624
'\x{2010}-\x{2027}\x{2030}-\x{2043}\x{2045}-\x{2051}\x{2053}\x{2054}\x{2057}'.
7724
'\x{207d}\x{207e}\x{208d}\x{208e}\x{2329}\x{232a}\x{23b4}-\x{23b6}\x{2768}-'.
7824
'\x{2775}\x{27e6}-\x{27eb}\x{2983}-\x{2998}\x{29d8}-\x{29db}\x{29fc}\x{29fd}'.
7924
'\x{3001}-\x{3003}\x{3008}-\x{3011}\x{3014}-\x{301f}\x{3030}\x{303d}\x{30a0}'.
8024
'\x{30fb}\x{fd3e}\x{fd3f}\x{fe30}-\x{fe52}\x{fe54}-\x{fe61}\x{fe63}\x{fe68}'.
8124
'\x{fe6a}\x{fe6b}\x{ff01}-\x{ff03}\x{ff05}-\x{ff0a}\x{ff0c}-\x{ff0f}\x{ff1a}'.
8224
'\x{ff1b}\x{ff1f}\x{ff20}\x{ff3b}-\x{ff3d}\x{ff3f}\x{ff5b}\x{ff5d}\x{ff5f}-'.
8324
'\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
 */
9024
define('PREG_CLASS_CJK',
'\x{3041}-\x{30ff}\x{31f0}-\x{31ff}\x{3400}-\x{4db5}' .
9124
'\x{4e00}-\x{9fbb}\x{f900}-\x{fad9}');
92
93
/**
94
 * Implementation of hook_help().
95
 */
9624
function search_help($path, $arg) {
97
  switch ($path) {
9817
    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;
10317
    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>';
10517
    case 'search#noresults':
1061
      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>
1101
</ul>');
1110
  }
11217
}
113
114
/**
115
 * Implementation of hook_theme().
116
 */
11724
function search_theme() {
118
  return array(
119
    'search_theme_form' => array(
1202
      'arguments' => array('form' => NULL),
1212
      'template' => 'search-theme-form',
1222
    ),
123
    'search_block_form' => array(
1242
      'arguments' => array('form' => NULL),
1252
      'template' => 'search-block-form',
1262
    ),
127
    'search_result' => array(
1282
      'arguments' => array('result' => NULL, 'type' => NULL),
1292
      'file' => 'search.pages.inc',
1302
      'template' => 'search-result',
1312
    ),
132
    'search_results' => array(
1332
      'arguments' => array('results' => NULL, 'type' => NULL),
1342
      'file' => 'search.pages.inc',
1352
      'template' => 'search-results',
1362
    ),
1372
  );
1380
}
139
140
/**
141
 * Implementation of hook_perm().
142
 */
14324
function search_perm() {
144
  return array(
1453
    'search content' => t('Search website content.'),
1463
    'use advanced search' => t('Limit search results with additional
criteria, such as specific content types. Could have performance
implications.'),
1473
    'administer search' => t('Configure search administration settings.'),
1483
  );
1490
}
150
151
/**
152
 * Implementation of hook_block().
153
 */
15424
function search_block($op = 'list', $delta = '') {
1550
  if ($op == 'list') {
1560
    $blocks['form']['info'] = t('Search form');
157
    // Not worth caching.
1580
    $blocks['form']['cache'] = BLOCK_NO_CACHE;
1590
    return $blocks;
1600
  }
1610
  else if ($op == 'view' && user_access('search content')) {
1620
    $block['content'] = drupal_get_form('search_block_form');
1630
    $block['subject'] = t('Search');
1640
    return $block;
1650
  }
1660
}
167
168
/**
169
 * Implementation of hook_menu().
170
 */
17124
function search_menu() {
1723
  $items['search'] = array(
1733
    'title' => 'Search',
1743
    'page callback' => 'search_view',
1753
    'access arguments' => array('search content'),
1763
    'type' => MENU_SUGGESTED_ITEM,
177
  );
1783
  $items['admin/settings/search'] = array(
1793
    'title' => 'Search settings',
1803
    'description' => 'Configure relevance settings for search and other
indexing options',
1813
    'page callback' => 'drupal_get_form',
1823
    'page arguments' => array('search_admin_settings'),
1833
    'access arguments' => array('administer search'),
1843
    'type' => MENU_NORMAL_ITEM,
185
  );
1863
  $items['admin/settings/search/wipe'] = array(
1873
    'title' => 'Clear index',
1883
    'page callback' => 'drupal_get_form',
1893
    'page arguments' => array('search_wipe_confirm'),
1903
    'access arguments' => array('administer search'),
1913
    'type' => MENU_CALLBACK,
192
  );
1933
  $items['admin/reports/search'] = array(
1943
    'title' => 'Top search phrases',
1953
    'description' => 'View most popular search phrases.',
1963
    'page callback' => 'dblog_top',
1973
    'page arguments' => array('search'),
1983
    'access arguments' => array('access site reports'),
1993
    'file path' => drupal_get_path('module', 'dblog'),
200
  );
201
2023
  foreach (module_implements('search') as $name) {
2033
    $items['search/' . $name . '/%menu_tail'] = array(
2043
      'title callback' => 'module_invoke',
2053
      'title arguments' => array($name, 'search', 'name', TRUE),
2063
      'page callback' => 'search_view',
2073
      'page arguments' => array($name),
2083
      'access callback' => '_search_menu',
2093
      'access arguments' => array($name),
2103
      'type' => MENU_LOCAL_TASK,
2113
      'parent' => 'search',
212
    );
2133
  }
2143
  return $items;
2150
}
216
21724
function _search_menu($name) {
2183
  return user_access('search content') && module_invoke($name, 'search',
'name');
2190
}
220
221
/**
222
 * Wipes a part of or the entire search index.
223
 *
224
 * @param $sid
225
 *  (optional) The SID of the item to wipe. If specified, $type must be
passed
226
 *  too.
227
 * @param $type
228
 *  (optional) The type of item to wipe.
229
 */
23024
function search_wipe($sid = NULL, $type = NULL, $reindex = FALSE) {
2312
  if ($type == NULL && $sid == NULL) {
2320
    module_invoke_all('search', 'reset');
2330
  }
234
  else {
2352
    db_query("DELETE FROM {search_dataset} WHERE sid = %d AND type = '%s'",
$sid, $type);
2362
    db_query("DELETE FROM {search_index} WHERE sid = %d AND type = '%s'",
$sid, $type);
237
    // Don't remove links if re-indexing.
2382
    if (!$reindex) {
2390
      db_query("DELETE FROM {search_node_links} WHERE sid = %d AND type =
'%s'", $sid, $type);
2400
    }
241
  }
2422
}
243
244
/**
245
 * Marks a word as dirty (or retrieves the list of dirty words). This is
used
246
 * during indexing (cron). Words which are dirty have outdated total counts
in
247
 * the search_total table, and need to be recounted.
248
 */
24924
function search_dirty($word = NULL) {
2502
  static $dirty = array();
2512
  if ($word !== NULL) {
2522
    $dirty[$word] = TRUE;
2532
  }
254
  else {
2552
    return $dirty;
256
  }
2572
}
258
259
/**
260
 * Implementation of hook_cron().
261
 *
262
 * Fires hook_update_index() in all modules and cleans up dirty words (see
263
 * search_dirty).
264
 */
26524
function search_cron() {
266
  // We register a shutdown function to ensure that search_total is always
up
267
  // to date.
2680
  register_shutdown_function('search_update_totals');
269
270
  // Update word index
2710
  foreach (module_list() as $module) {
2720
    module_invoke($module, 'update_index');
2730
  }
2740
}
275
276
/**
277
 * This function is called on shutdown to ensure that search_total is
always
278
 * up to date (even if cron times out or otherwise fails).
279
 */
28024
function search_update_totals() {
281
  // Update word IDF (Inverse Document Frequency) counts for new/changed
words
2822
  foreach (search_dirty() as $word => $dummy) {
283
    // Get total count
2842
    $total = db_result(db_query("SELECT SUM(score) FROM {search_index}
WHERE word = '%s'", $word));
285
    // Apply Zipf's law to equalize the probability distribution
2862
    $total = log10(1 + 1/(max(1, $total)));
2872
    db_query("UPDATE {search_total} SET count = %f WHERE word = '%s'",
$total, $word);
2882
    if (!db_affected_rows()) {
2892
      db_query("INSERT INTO {search_total} (word, count) VALUES ('%s',
%f)", $word, $total);
2902
    }
2912
  }
292
  // Find words that were deleted from search_index, but are still in
293
  // search_total. We use a LEFT JOIN between the two tables and keep only
the
294
  // rows which fail to join.
2952
  $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");
2962
  while ($word = db_fetch_object($result)) {
2970
    db_query("DELETE FROM {search_total} WHERE word = '%s'",
$word->realword);
2980
  }
2992
}
300
301
/**
302
 * Simplifies a string according to indexing rules.
303
 */
30424
function search_simplify($text) {
305
  // Decode entities to UTF-8
3063
  $text = decode_entities($text);
307
308
  // Lowercase
3093
  $text = drupal_strtolower($text);
310
311
  // Call an external processor for word handling.
3123
  search_invoke_preprocess($text);
313
314
  // Simple CJK handling
3153
  if (variable_get('overlap_cjk', TRUE)) {
3163
    $text = preg_replace_callback('/[' . PREG_CLASS_CJK . ']+/u',
'search_expand_cjk', $text);
3173
  }
318
319
  // To improve searching for numerical data such as dates, IP addresses
320
  // or version numbers, we consider a group of numerical characters
321
  // separated only by punctuation characters to be one piece.
322
  // This also means that searching for e.g. '20/03/1984' also returns
323
  // results with '20-03-1984' in them.
324
  // Readable regexp: ([number]+)[punctuation]+(?=[number])
3253
  $text = preg_replace('/([' . PREG_CLASS_NUMBERS . ']+)[' .
PREG_CLASS_PUNCTUATION . ']+(?=[' . PREG_CLASS_NUMBERS . '])/u', '\1',
$text);
326
327
  // The dot, underscore and dash are simply removed. This allows
meaningful
328
  // search behavior with acronyms and URLs.
3293
  $text = preg_replace('/[._-]+/', '', $text);
330
331
  // With the exception of the rules above, we consider all punctuation,
332
  // marks, spacers, etc, to be a word boundary.
3333
  $text = preg_replace('/[' . PREG_CLASS_SEARCH_EXCLUDE . ']+/u', ' ',
$text);
334
3353
  return $text;
3360
}
337
338
/**
339
 * Basic CJK tokenizer. Simply splits a string into consecutive,
overlapping
340
 * sequences of characters ('minimum_word_size' long).
341
 */
34224
function search_expand_cjk($matches) {
3430
  $min = variable_get('minimum_word_size', 3);
3440
  $str = $matches[0];
3450
  $l = drupal_strlen($str);
346
  // Passthrough short words
3470
  if ($l <= $min) {
3480
    return ' ' . $str . ' ';
3490
  }
3500
  $tokens = ' ';
351
  // FIFO queue of characters
3520
  $chars = array();
353
  // Begin loop
3540
  for ($i = 0; $i < $l; ++$i) {
355
    // Grab next character
3560
    $current = drupal_substr($str, 0, 1);
3570
    $str = substr($str, strlen($current));
3580
    $chars[] = $current;
3590
    if ($i >= $min - 1) {
3600
      $tokens .= implode('', $chars) . ' ';
3610
      array_shift($chars);
3620
    }
3630
  }
3640
  return $tokens;
3650
}
366
367
/**
368
 * Splits a string into tokens for indexing.
369
 */
37024
function search_index_split($text) {
3712
  static $last = NULL;
3722
  static $lastsplit = NULL;
373
3742
  if ($last == $text) {
3750
    return $lastsplit;
3760
  }
377
  // Process words
3782
  $text = search_simplify($text);
3792
  $words = explode(' ', $text);
3802
  array_walk($words, '_search_index_truncate');
381
382
  // Save last keyword result
3832
  $last = $text;
3842
  $lastsplit = $words;
385
3862
  return $words;
3870
}
388
389
/**
390
 * Helper function for array_walk in search_index_split.
391
 */
39224
function _search_index_truncate(&$text) {
3932
  $text = truncate_utf8($text, 50);
3942
}
395
396
/**
397
 * Invokes hook_search_preprocess() in modules.
398
 */
39924
function search_invoke_preprocess(&$text) {
4003
  foreach (module_implements('search_preprocess') as $module) {
4010
    $text = module_invoke($module, 'search_preprocess', $text);
4020
  }
4033
}
404
405
/**
406
 * Update the full-text search index for a particular item.
407
 *
408
 * @param $sid
409
 *   A number identifying this particular item (e.g. node id).
410
 *
411
 * @param $type
412
 *   A string defining this type of item (e.g. 'node')
413
 *
414
 * @param $text
415
 *   The content of this item. Must be a piece of HTML text.
416
 *
417
 * @ingroup search
418
 */
41924
function search_index($sid, $type, $text) {
4202
  $minimum_word_size = variable_get('minimum_word_size', 3);
421
422
  // Link matching
4232
  global $base_url;
4242
  $node_regexp = '@href=[\'"]?(?:' . preg_quote($base_url, '@') . '/|' .
preg_quote(base_path(), '@') .
')(?:\?q=)?/?((?![a-z]+:)[^\'">]+)[\'">]@i';
425
426
  // Multipliers for scores of words inside certain HTML tags.  The weights
are stored
427
  // in a variable so that modules can overwrite the default weights.
428
  // Note: 'a' must be included for link ranking to work.
4292
  $tags = variable_get('search_tag_weights', array(
4302
    'h1' => 25,
4312
    'h2' => 18,
4322
    'h3' => 15,
4332
    'h4' => 12,
4342
    'h5' => 9,
4352
    'h6' => 6,
4362
    'u' => 3,
4372
    'b' => 3,
4382
    'i' => 3,
4392
    'strong' => 3,
4402
    'em' => 3,
4412
    'a' => 10));
442
443
  // Strip off all ignored tags to speed up processing, but insert space
before/after
444
  // them to keep word boundaries.
4452
  $text = str_replace(array('<', '>'), array(' <', '> '), $text);
4462
  $text = strip_tags($text, '<' . implode('><', array_keys($tags)) . '>');
447
448
  // Split HTML tags from plain text.
4492
  $split = preg_split('/\s*<([^>]+?)>\s*/', $text, -1,
PREG_SPLIT_DELIM_CAPTURE);
450
  // Note: PHP ensures the array consists of alternating delimiters and
literals
451
  // and begins and ends with a literal (inserting $null as required).
452
4532
  $tag = FALSE; // Odd/even counter. Tag or no tag.
4542
  $link = FALSE; // State variable for link analyser
4552
  $score = 1; // Starting score per word
4562
  $accum = ' '; // Accumulator for cleaned up data
4572
  $tagstack = array(); // Stack with open tags
4582
  $tagwords = 0; // Counter for consecutive words
4592
  $focus = 1; // Focus state
460
4612
  $results = array(0 => array()); // Accumulator for words for index
462
4632
  foreach ($split as $value) {
4642
    if ($tag) {
465
      // Increase or decrease score per word based on tag
4661
      list($tagname) = explode(' ', $value, 2);
4671
      $tagname = drupal_strtolower($tagname);
468
      // Closing or opening tag?
4691
      if ($tagname[0] == '/') {
4701
        $tagname = substr($tagname, 1);
471
        // If we encounter unexpected tags, reset score to avoid incorrect
boosting.
4721
        if (!count($tagstack) || $tagstack[0] != $tagname) {
4730
          $tagstack = array();
4740
          $score = 1;
4750
        }
476
        else {
477
          // Remove from tag stack and decrement score
4781
          $score = max(1, $score - $tags[array_shift($tagstack)]);
479
        }
4801
        if ($tagname == 'a') {
4811
          $link = FALSE;
4821
        }
4831
      }
484
      else {
4851
        if (isset($tagstack[0]) && $tagstack[0] == $tagname) {
486
          // None of the tags we look for make sense when nested
identically.
487
          // If they are, it's probably broken HTML.
4880
          $tagstack = array();
4890
          $score = 1;
4900
        }
491
        else {
492
          // Add to open tag stack and increment score
4931
          array_unshift($tagstack, $tagname);
4941
          $score += $tags[$tagname];
495
        }
4961
        if ($tagname == 'a') {
497
          // Check if link points to a node on this site
4981
          if (preg_match($node_regexp, $value, $match)) {
4990
            $path = drupal_get_normal_path($match[1]);
5000
            if (preg_match('!(?:node|book)/(?:view/)?([0-9]+)!i', $path,
$match)) {
5010
              $linknid = $match[1];
5020
              if ($linknid > 0) {
503
                // Note: ignore links to uncachable nodes to avoid redirect
bugs.
5040
                $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));
5050
                if (filter_format_allowcache($node->format)) {
5060
                  $link = TRUE;
5070
                  $linktitle = $node->title;
5080
                }
5090
              }
5100
            }
5110
          }
5121
        }
513
      }
514
      // A tag change occurred, reset counter.
5151
      $tagwords = 0;
5161
    }
517
    else {
518
      // Note: use of PREG_SPLIT_DELIM_CAPTURE above will introduce empty
values
5192
      if ($value != '') {
5202
        if ($link) {
521
          // Check to see if the node link text is its URL. If so, we use
the target node title instead.
5220
          if (preg_match('!^https?://!i', $value)) {
5230
            $value = $linktitle;
5240
          }
5250
        }
5262
        $words = search_index_split($value);
5272
        foreach ($words as $word) {
528
          // Add word to accumulator
5292
          $accum .= $word . ' ';
5302
          $num = is_numeric($word);
531
          // Check wordlength
5322
          if ($num || drupal_strlen($word) >= $minimum_word_size) {
533
            // Normalize numbers
5342
            if ($num) {
5350
              $word = (int)ltrim($word, '-0');
5360
            }
537
538
            // Links score mainly for the target.
5392
            if ($link) {
5400
              if (!isset($results[$linknid])) {
5410
                $results[$linknid] = array();
5420
              }
5430
              $results[$linknid][] = $word;
544
              // Reduce score of the link caption in the source.
5450
              $focus *= 0.2;
5460
            }
547
            // Fall-through
5482
            if (!isset($results[0][$word])) {
5492
              $results[0][$word] = 0;
5502
            }
5512
            $results[0][$word] += $score * $focus;
552
553
            // Focus is a decaying value in terms of the amount of unique
words up to this point.
554
            // From 100 words and more, it decays, to e.g. 0.5 at 500 words
and 0.3 at 1000 words.
5552
            $focus = min(1, .01 + 3.5 / (2 + count($results[0]) * .015));
5562
          }
5572
          $tagwords++;
558
          // Too many words inside a single tag probably mean a tag was
accidentally left open.
5592
          if (count($tagstack) && $tagwords >= 15) {
5600
            $tagstack = array();
5610
            $score = 1;
5620
          }
5632
        }
5642
      }
565
    }
5662
    $tag = !$tag;
5672
  }
568
5692
  search_wipe($sid, $type, TRUE);
570
571
  // Insert cleaned up data into dataset
5722
  db_query("INSERT INTO {search_dataset} (sid, type, data, reindex) VALUES
(%d, '%s', '%s', %d)", $sid, $type, $accum, 0);
573
574
  // Insert results into search index
5752
  foreach ($results[0] as $word => $score) {
576
    // The database will collate similar words (accented and non-accented
forms, etc.),
577
    // and the score is additive, so first add and then insert.
5782
    db_query("UPDATE {search_index} SET score = score + %d WHERE word =
'%s' AND sid = '%d' AND type = '%s'", $score, $word, $sid, $type);
5792
    if (!db_affected_rows()) {
5802
      db_query("INSERT INTO {search_index} (word, sid, type, score) VALUES
('%s', %d, '%s', %f)", $word, $sid, $type, $score);
5812
    }
5822
    search_dirty($word);
5832
  }
5842
  unset($results[0]);
585
586
  // Get all previous links from this item.
5872
  $result = db_query("SELECT nid, caption FROM {search_node_links} WHERE
sid = %d AND type = '%s'", $sid, $type);
5882
  $links = array();
5892
  while ($link = db_fetch_object($result)) {
5900
    $links[$link->nid] = $link->caption;
5910
  }
592
593
  // Now store links to nodes.
5942
  foreach ($results as $nid => $words) {
5950
    $caption = implode(' ', $words);
5960
    if (isset($links[$nid])) {
5970
      if ($links[$nid] != $caption) {
598
        // Update the existing link and mark the node for reindexing.
5990
        db_query("UPDATE {search_node_links} SET caption = '%s' WHERE sid =
%d AND type = '%s' AND nid = %d", $caption, $sid, $type, $nid);
6000
        search_touch_node($nid);
6010
      }
602
      // Unset the link to mark it as processed.
6030
      unset($links[$nid]);
6040
    }
605
    else {
606
      // Insert the existing link and mark the node for reindexing.
6070
      db_query("INSERT INTO {search_node_links} (caption, sid, type, nid)
VALUES ('%s', %d, '%s', %d)", $caption, $sid, $type, $nid);
6080
      search_touch_node($nid);
609
    }
6100
  }
611
  // Any left-over links in $links no longer exist. Delete them and mark
the nodes for reindexing.
6122
  foreach ($links as $nid => $caption) {
6130
    db_query("DELETE FROM {search_node_links} WHERE sid = %d AND type =
'%s' AND nid = %d", $sid, $type, $nid);
6140
    search_touch_node($nid);
6150
  }
6162
}
617
618
/**
619
 * Change a node's changed timestamp to 'now' to force reindexing.
620
 *
621
 * @param $nid
622
 *   The nid of the node that needs reindexing.
623
 */
62424
function search_touch_node($nid) {
6251
  db_query("UPDATE {search_dataset} SET reindex = %d WHERE sid = %d AND
type = 'node'", time(), $nid);
6261
}
627
628
/**
629
 * Implementation of hook_nodeapi().
630
 */
63124
function search_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
632
  switch ($op) {
633
    // Transplant links to a node into the target node.
63410
    case 'update index':
6351
      $result = db_query("SELECT caption FROM {search_node_links} WHERE nid
= %d", $node->nid);
6361
      $output = array();
6371
      while ($link = db_fetch_object($result)) {
6380
        $output[] = $link->caption;
6390
      }
6401
      return '<a>(' . implode(', ', $output) . ')</a>';
641
    // Reindex the node when it is updated.  The node is automatically
indexed
642
    // when it is added, simply by being added to the node table.
64310
    case 'update':
6440
      search_touch_node($node->nid);
6450
      break;
6460
  }
64710
}
648
649
/**
650
 * Implementation of hook_comment().
651
 */
65224
function search_comment($a1, $op) {
653
  switch ($op) {
654
    // Reindex the node when comments are added or changed
6553
    case 'insert':
6563
    case 'update':
6573
    case 'delete':
6583
    case 'publish':
6593
    case 'unpublish':
6601
      search_touch_node(is_array($a1) ? $a1['nid'] : $a1->nid);
6611
      break;
6620
  }
6633
}
664
665
/**
666
 * Extract a module-specific search option from a search query. e.g.
'type:book'
667
 */
66824
function search_query_extract($keys, $option) {
6692
  if (preg_match('/(^| )' . $option . ':([^ ]*)( |$)/i', $keys, $matches))
{
6700
    return $matches[2];
6710
  }
6722
}
673
674
/**
675
 * Return a query with the given module-specific search option inserted
in.
676
 * e.g. 'type:book'.
677
 */
67824
function search_query_insert($keys, $option, $value = '') {
6790
  if (search_query_extract($keys, $option)) {
6800
    $keys = trim(preg_replace('/(^| )' . $option . ':[^ ]*/i', '',
$keys));
6810
  }
6820
  if ($value != '') {
6830
    $keys .= ' ' . $option . ':' . $value;
6840
  }
6850
  return $keys;
6860
}
687
688
/**
689
 * Parse a search query into SQL conditions.
690
 *
691
 * We build two queries that matches the dataset bodies. @See do_search
for
692
 * more about these.
693
 *
694
 * @param $text
695
 *   The search keys.
696
 * @return
697
 *   A list of six elements.
698
 *    * A series of statements AND'd together which will be used to provide
all
699
 *      possible matches.
700
 *    * Arguments for this query part.
701
 *    * A series of exact word matches OR'd together.
702
 *    * Arguments for this query part.
703
 *    * A bool indicating whether this is a simple query or not. Negative
704
 *      terms, presence of both AND / OR make this FALSE.
705
 *    * A bool indicating the presence of a lowercase or. Maybe the user
706
 *      wanted to use OR.
707
 */
70824
function search_parse_query($text) {
7093
  $keys = array('positive' => array(), 'negative' => array());
710
711
  // Tokenize query string
7123
  preg_match_all('/ (-?)("[^"]+"|[^" ]+)/i', ' ' . $text, $matches,
PREG_SET_ORDER);
713
7143
  if (count($matches) < 1) {
7150
    return NULL;
7160
  }
717
718
  // Classify tokens
7193
  $or = FALSE;
7203
  $warning = '';
7213
  $simple = TRUE;
7223
  foreach ($matches as $match) {
7233
    $phrase = FALSE;
724
    // Strip off phrase quotes
7253
    if ($match[2]{0} == '"') {
7261
      $match[2] = substr($match[2], 1, -1);
7271
      $phrase = TRUE;
7281
      $simple = FALSE;
7291
    }
730
    // Simplify keyword according to indexing rules and external
preprocessors
7313
    $words = search_simplify($match[2]);
732
    // Re-explode in case simplification added more words, except when
matching a phrase
7333
    $words = $phrase ? array($words) : preg_split('/ /', $words, -1,
PREG_SPLIT_NO_EMPTY);
734
    // Negative matches
7353
    if ($match[1] == '-') {
7361
      $keys['negative'] = array_merge($keys['negative'], $words);
7371
    }
738
    // OR operator: instead of a single keyword, we store an array of all
739
    // OR'd keywords.
7403
    elseif ($match[2] == 'OR' && count($keys['positive'])) {
7411
      $last = array_pop($keys['positive']);
742
      // Starting a new OR?
7431
      if (!is_array($last)) {
7441
        $last = array($last);
7451
      }
7461
      $keys['positive'][] = $last;
7471
      $or = TRUE;
7481
      continue;
7490
    }
750
    // AND operator: implied, so just ignore it
7513
    elseif ($match[2] == 'AND' || $match[2] == 'and') {
7520
      $warning = $match[2];
7530
      continue;
7540
    }
755
756
    // Plain keyword
757
    else {
7583
      if ($match[2] == 'or') {
7590
        $warning = $match[2];
7600
      }
7613
      if ($or) {
762
        // Add to last element (which is an array)
7631
        $keys['positive'][count($keys['positive']) - 1] =
array_merge($keys['positive'][count($keys['positive']) - 1], $words);
7641
      }
765
      else {
7663
        $keys['positive'] = array_merge($keys['positive'], $words);
767
      }
768
    }
7693
    $or = FALSE;
7703
  }
771
772
  // Convert keywords into SQL statements.
7733
  $query = array();
7743
  $query2 = array();
7753
  $arguments = array();
7763
  $arguments2 = array();
7773
  $matches = 0;
7783
  $simple_and = FALSE;
7793
  $simple_or = FALSE;
780
  // Positive matches
7813
  foreach ($keys['positive'] as $key) {
782
    // Group of ORed terms
7833
    if (is_array($key) && count($key)) {
7841
      $simple_or = TRUE;
7851
      $queryor = array();
7861
      $any = FALSE;
7871
      foreach ($key as $or) {
7881
        list($q, $num_new_scores) = _search_parse_query($or, $arguments2);
7891
        $any |= $num_new_scores;
7901
        if ($q) {
7911
          $queryor[] = $q;
7921
          $arguments[] = $or;
7931
        }
7941
      }
7951
      if (count($queryor)) {
7961
        $query[] = '(' . implode(' OR ', $queryor) . ')';
797
        // A group of OR keywords only needs to match once
7981
        $matches += ($any > 0);
7991
      }
8001
    }
801
    // Single ANDed term
802
    else {
8033
      $simple_and = TRUE;
8043
      list($q, $num_new_scores, $num_valid_words) =
_search_parse_query($key, $arguments2);
8053
      if ($q) {
8063
        $query[] = $q;
8073
        $arguments[] = $key;
8083
        if (!$num_valid_words) {
8091
          $simple = FALSE;
8101
        }
811
        // Each AND keyword needs to match at least once
8123
        $matches += $num_new_scores;
8133
      }
814
    }
8153
  }
8163
  if ($simple_and && $simple_or) {
8171
    $simple = FALSE;
8181
  }
819
  // Negative matches
8203
  foreach ($keys['negative'] as $key) {
8211
    list($q) = _search_parse_query($key, $arguments2, TRUE);
8221
    if ($q) {
8231
      $query[] = $q;
8241
      $arguments[] = $key;
8251
      $simple = FALSE;
8261
    }
8271
  }
8283
  $query = implode(' AND ', $query);
829
830
  // Build word-index conditions for the first pass
8313
  $query2 = substr(str_repeat("i.word = '%s' OR ", count($arguments2)), 0,
-4);
832
8333
  return array($query, $arguments, $query2, $arguments2, $matches, $simple,
$warning);
8340
}
835
836
/**
837
 * Helper function for search_parse_query();
838
 */
83924
function _search_parse_query(&$word, &$scores, $not = FALSE) {
8403
  $num_new_scores = 0;
8413
  $num_valid_words = 0;
842
  // Determine the scorewords of this word/phrase
8433
  if (!$not) {
8443
    $split = explode(' ', $word);
8453
    foreach ($split as $s) {
8463
      $num = is_numeric($s);
8473
      if ($num || drupal_strlen($s) >= variable_get('minimum_word_size',
3)) {
8483
        $s = $num ? ((int)ltrim($s, '-0')) : $s;
8493
        if (!isset($scores[$s])) {
8503
          $scores[$s] = $s;
8513
          $num_new_scores++;
8523
        }
8533
        $num_valid_words++;
8543
      }
8553
    }
8563
  }
857
  // Return matching snippet and number of added words
8583
  return array("d.data " . ($not ? 'NOT ' : '') . "LIKE '%% %s %%'",
$num_new_scores, $num_valid_words);
8590
}
860
861
/**
862
 * Do a query on the full-text search index for a word or words.
863
 *
864
 * This function is normally only called by each module that support the
865
 * indexed search (and thus, implements hook_update_index()).
866
 *
867
 * Results are retrieved in two logical passes. However, the two passes
are
868
 * joined together into a single query.  And in the case of most simple
869
 * queries the second pass is not even used.
870
 *
871
 * The first pass selects a set of all possible matches, which has the
benefit
872
 * of also providing the exact result set for simple "AND" or "OR"
searches.
873
 *
874
 * The second portion of the query further refines this set by verifying
875
 * advanced text conditions (such negative or phrase matches)
876
 *
877
 * @param $keywords
878
 *   A search string as entered by the user.
879
 *
880
 * @param $type
881
 *   A string identifying the calling module.
882
 *
883
 * @param $join1
884
 *   (optional) Inserted into the JOIN part of the first SQL query.
885
 *   For example "INNER JOIN {node} n ON n.nid = i.sid".
886
 *
887
 * @param $where1
888
 *   (optional) Inserted into the WHERE part of the first SQL query.
889
 *   For example "(n.status > %d)".
890
 *
891
 * @param $arguments1
892
 *   (optional) Extra SQL arguments belonging to the first query.
893
 *
894
 * @param $columns2
895
 *   (optional) Inserted into the SELECT pat of the second query. Must
contain
896
 *   a column selected as 'score'.
897
 *   defaults to 'i.relevance AS score'
898
 *
899
 * @param $join2
900
 *   (optional) Inserted into the JOIN par of the second SQL query.
901
 *   For example "INNER JOIN {node_comment_statistics} n ON n.nid = i.sid"
902
 *
903
 * @param $arguments2
904
 *   (optional) Extra SQL arguments belonging to the second query
parameter.
905
 *
906
 * @param $sort_parameters
907
 *   (optional) SQL arguments for sorting the final results.
908
 *              Default: 'ORDER BY score DESC'
909
 *
910
 * @return
911
 *   An array of SIDs for the search results.
912
 *
913
 * @ingroup search
914
 */
91524
function do_search($keywords, $type, $join1 = '', $where1 = '1',
$arguments1 = array(), $columns2 = 'i.relevance AS score', $join2 = '',
$arguments2 = array(), $sort_parameters = 'ORDER BY score DESC') {
9163
  $query = search_parse_query($keywords);
917
9183
  if ($query[2] == '') {
9190
    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))));
9200
  }
9213
  if ($query[6]) {
9220
    if ($query[6] == 'or') {
9230
      drupal_set_message(t('Search for either of the two terms with
uppercase <strong>OR</strong>. For example, <strong>cats OR
dogs</strong>.'));
9240
    }
9250
  }
9263
  if ($query === NULL || $query[0] == '' || $query[2] == '') {
9270
    return array();
9280
  }
929
930
  // Build query for keyword normalization.
9313
  $conditions = "$where1 AND ($query[2]) AND i.type = '%s'";
9323
  $arguments1 = array_merge($arguments1, $query[3], array($type));
9333
  $join = "INNER JOIN {search_total} t ON i.word = t.word $join1";
9343
  if (!$query[5]) {
9351
    $conditions .= " AND ($query[0])";
9361
    $arguments1 = array_merge($arguments1, $query[1]);
9371
    $join .= " INNER JOIN {search_dataset} d ON i.sid = d.sid AND i.type =
d.type";
9381
  }
939
940
  // Calculate maximum keyword relevance, to normalize it.
9413
  $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";
9423
  $arguments = array_merge($arguments1, array($query[4]));
9433
  $normalize = db_result(db_query_range($select, $arguments, 0, 1));
9443
  if (!$normalize) {
9452
    return array();
9460
  }
9472
  $columns2 = str_replace('i.relevance', '(' . (1.0 / $normalize) . ' *
SUM(i.score * t.count))', $columns2);
948
949
  // Build query to retrieve results.
9502
  $select = "SELECT i.type, i.sid, $columns2 FROM {search_index} i $join
$join2 WHERE $conditions GROUP BY i.type, i.sid HAVING COUNT(*) >= %d";
9512
  $count_select =  "SELECT COUNT(*) FROM ($select) n1";
9522
  $arguments = array_merge($arguments2, $arguments1, array($query[4]));
953
954
  // Do actual search query
9552
  $result = pager_query("$select $sort_parameters", 10, 0, $count_select,
$arguments);
9562
  $results = array();
9572
  while ($item = db_fetch_object($result)) {
9582
    $results[] = $item;
9592
  }
9602
  return $results;
9610
}
962
963
/**
964
 * Helper function for grabbing search keys.
965
 */
96624
function search_get_keys() {
9673
  static $return;
9683
  if (!isset($return)) {
969
    // Extract keys as remainder of path
970
    // Note: support old GET format of searches for existing links.
9713
    $path = explode('/', $_GET['q'], 3);
9723
    $keys = empty($_REQUEST['keys']) ? '' : $_REQUEST['keys'];
9733
    $return = count($path) == 3 ? $path[2] : $keys;
9743
  }
9753
  return $return;
9760
}
977
978
/**
979
 * @defgroup search Search interface
980
 * @{
981
 * The Drupal search interface manages a global search mechanism.
982
 *
983
 * Modules may plug into this system to provide searches of different types
of
984
 * data. Most of the system is handled by search.module, so this must be
enabled
985
 * for all of the search features to work.
986
 *
987
 * There are three ways to interact with the search system:
988
 * - Specifically for searching nodes, you can implement nodeapi('update
index')
989
 *   and nodeapi('search result'). However, note that the search system
already
990
 *   indexes all visible output of a node, i.e. everything displayed
normally
991
 *   by hook_view() and hook_nodeapi('view'). This is usually sufficient.
992
 *   You should only use this mechanism if you want additional, non-visible
data
993
 *   to be indexed.
994
 * - Implement hook_search(). This will create a search tab for your module
on
995
 *   the /search page with a simple keyword search form. You may
optionally
996
 *   implement hook_search_item() to customize the display of your
results.
997
 * - Implement hook_update_index(). This allows your module to use
Drupal's
998
 *   HTML indexing mechanism for searching full text efficiently.
999
 *
1000
 * If your module needs to provide a more complicated search form, then you
need
1001
 * to implement it yourself without hook_search(). In that case, you
should
1002
 * define it as a local task (tab) under the /search page (e.g.
/search/mymodule)
1003
 * so that users can easily find it.
1004
 */
1005
1006
/**
1007
 * Render a search form.
1008
 *
1009
 * @param $action
1010
 *   Form action. Defaults to "search".
1011
 * @param $keys
1012
 *   The search string entered by the user, containing keywords for the
search.
1013
 * @param $type
1014
 *   The type of search to render the node for. Must be the name of module
1015
 *   which implements hook_search(). Defaults to 'node'.
1016
 * @param $prompt
1017
 *   A piece of text to put before the form (e.g. "Enter your keywords")
1018
 * @return
1019
 *   An HTML string containing the search form.
1020
 */
102124
function search_form(&$form_state, $action = '', $keys = '', $type = NULL,
$prompt = NULL) {
1022
1023
  // Add CSS
10244
  drupal_add_css(drupal_get_path('module', 'search') . '/search.css',
'module', 'all', FALSE);
1025
10264
  if (!$action) {
10274
    $action = url('search/' . $type);
10284
  }
10294
  if (is_null($prompt)) {
10304
    $prompt = t('Enter your keywords');
10314
  }
1032
1033
  $form = array(
10344
    '#action' => $action,
10354
    '#attributes' => array('class' => 'search-form'),
10364
  );
10374
  $form['module'] = array('#type' => 'value', '#value' => $type);
10384
  $form['basic'] = array('#type' => 'item', '#title' => $prompt);
10394
  $form['basic']['inline'] = array('#prefix' => '<div
class="container-inline">', '#suffix' => '</div>');
10404
  $form['basic']['inline']['keys'] = array(
10414
    '#type' => 'textfield',
10424
    '#title' => '',
10434
    '#default_value' => $keys,
10444
    '#size' => $prompt ? 40 : 20,
10454
    '#maxlength' => 255,
1046
  );
1047
  // processed_keys is used to coordinate keyword passing between other
forms
1048
  // that hook into the basic search form.
10494
  $form['basic']['inline']['processed_keys'] = array('#type' => 'value',
'#value' => array());
10504
  $form['basic']['inline']['submit'] = array('#type' => 'submit', '#value'
=> t('Search'));
1051
10524
  return $form;
10530
}
1054
1055
/**
1056
 * Form builder; Output a search form for the search block and the theme's
search box.
1057
 *
1058
 * @ingroup forms
1059
 * @see search_box_form_submit()
1060
 * @see theme_search_box_form()
1061
 */
106224
function search_box(&$form_state, $form_id) {
10634
  $form[$form_id] = array(
10644
    '#title' => t('Search this site'),
10654
    '#type' => 'textfield',
10664
    '#size' => 15,
10674
    '#default_value' => '',
10684
    '#attributes' => array('title' => t('Enter the terms you wish to search
for.')),
1069
  );
10704
  $form['submit'] = array('#type' => 'submit', '#value' => t('Search'));
10714
  $form['#submit'][] = 'search_box_form_submit';
1072
10734
  return $form;
10740
}
1075
1076
/**
1077
 * Process a block search form submission.
1078
 */
107924
function search_box_form_submit($form, &$form_state) {
10800
  $form_id = $form['form_id']['#value'];
10810
  $form_state['redirect'] = 'search/node/' .
trim($form_state['values'][$form_id]);
10820
}
1083
1084
/**
1085
 * Process variables for search-theme-form.tpl.php.
1086
 *
1087
 * The $variables array contains the following arguments:
1088
 * - $form
1089
 *
1090
 * @see search-theme-form.tpl.php
1091
 */
109224
function template_preprocess_search_theme_form(&$variables) {
10934
  $variables['search'] = array();
10944
  $hidden = array();
1095
  // Provide variables named after form keys so themers can print each
element independently.
10964
  foreach (element_children($variables['form']) as $key) {
10974
    $type = $variables['form'][$key]['#type'];
10984
    if ($type == 'hidden' || $type == 'token') {
10994
      $hidden[] = drupal_render($variables['form'][$key]);
11004
    }
1101
    else {
11024
      $variables['search'][$key] =
drupal_render($variables['form'][$key]);
1103
    }
11044
  }
1105
  // Hidden form elements have no value to themers. No need for
separation.
11064
  $variables['search']['hidden'] = implode($hidden);
1107
  // Collect all form elements to make it easier to print the whole form.
11084
  $variables['search_form'] = implode($variables['search']);
11094
}
1110
1111
/**
1112
 * Process variables for search-block-form.tpl.php.
1113
 *
1114
 * The $variables array contains the following arguments:
1115
 * - $form
1116
 *
1117
 * @see search-block-form.tpl.php
1118
 */
111924
function template_preprocess_search_block_form(&$variables) {
11200
  $variables['search'] = array();
11210
  $hidden = array();
1122
  // Provide variables named after form keys so themers can print each
element independently.
11230
  foreach (element_children($variables['form']) as $key) {
11240
    $type = $variables['form'][$key]['#type'];
11250
    if ($type == 'hidden' || $type == 'token') {
11260
      $hidden[] = drupal_render($variables['form'][$key]);
11270
    }
1128
    else {
11290
      $variables['search'][$key] =
drupal_render($variables['form'][$key]);
1130
    }
11310
  }
1132
  // Hidden form elements have no value to themers. No need for
separation.
11330
  $variables['search']['hidden'] = implode($hidden);
1134
  // Collect all form elements to make it easier to print the whole form.
11350
  $variables['search_form'] = implode($variables['search']);
11360
}
1137
1138
/**
1139
 * Perform a standard search on the given keys, and return the formatted
results.
1140
 */
114124
function search_data($keys = NULL, $type = 'node') {
1142
11431
  if (isset($keys)) {
11441
    if (module_hook($type, 'search')) {
11451
      $results = module_invoke($type, 'search', 'search', $keys);
11461
      if (isset($results) && is_array($results) && count($results)) {
11470
        if (module_hook($type, 'search_page')) {
11480
          return module_invoke($type, 'search_page', $results);
11490
        }
1150
        else {
11510
          return theme('search_results', $results, $type);
1152
        }
11530
      }
11541
    }
11551
  }
11561
}
1157
1158
/**
1159
 * Returns snippets from a piece of text, with certain keywords
highlighted.
1160
 * Used for formatting search results.
1161
 *
1162
 * @param $keys
1163
 *   A string containing a search query.
1164
 *
1165
 * @param $text
1166
 *   The text to extract fragments from.
1167
 *
1168
 * @return
1169
 *   A string containing HTML for the excerpt.
1170
 */
117124
function search_excerpt($keys, $text) {
1172
  // We highlight around non-indexable or CJK characters.
11731
  $boundary = '(?:(?<=[' . PREG_CLASS_SEARCH_EXCLUDE . PREG_CLASS_CJK .
'])|(?=[' . PREG_CLASS_SEARCH_EXCLUDE . PREG_CLASS_CJK . ']))';
1174
1175
  // Extract positive keywords and phrases
11761
  preg_match_all('/ ("([^"]+)"|(?!OR)([^" ]+))/', ' ' . $keys, $matches);
11771
  $keys = array_merge($matches[2], $matches[3]);
1178
1179
  // Prepare text
11801
  $text = ' ' . strip_tags(str_replace(array('<', '>'), array(' <', '> '),
$text)) . ' ';
11811
  array_walk($keys, '_search_excerpt_replace');
11821
  $workkeys = $keys;
1183
1184
  // Extract a fragment per keyword for at most 4 keywords.
1185
  // First we collect ranges of text around each keyword, starting/ending
1186
  // at spaces.
1187
  // If the sum of all fragments is too short, we look for second
occurrences.
11881
  $ranges = array();
11891
  $included = array();
11901
  $length = 0;
11911
  while ($length < 256 && count($workkeys)) {
11921
    foreach ($workkeys as $k => $key) {
11931
      if (strlen($key) == 0) {
11941
        unset($workkeys[$k]);
11951
        unset($keys[$k]);
11961
        continue;
11970
      }
11981
      if ($length >= 256) {
11990
        break;
12000
      }
1201
      // Remember occurrence of key so we can skip over it if more
occurrences
1202
      // are desired.
12031
      if (!isset($included[$key])) {
12041
        $included[$key] = 0;
12051
      }
1206
      // Locate a keyword (position $p), then locate a space in front
(position
1207
      // $q) and behind it (position $s)
12081
      if (preg_match('/' . $boundary . $key . $boundary . '/iu', $text,
$match, PREG_OFFSET_CAPTURE, $included[$key])) {
12091
        $p = $match[0][1];
12101
        if (($q = strpos($text, ' ', max(0, $p - 60))) !== FALSE) {
12111
          $end = substr($text, $p, 80);
12121
          if (($s = strrpos($end, ' ')) !== FALSE) {
12131
            $ranges[$q] = $p + $s;
12141
            $length += $p + $s - $q;
12151
            $included[$key] = $p + 1;
12161
          }
1217
          else {
12180
            unset($workkeys[$k]);
1219
          }
12201
        }
1221
        else {
12220
          unset($workkeys[$k]);
1223
        }
12241
      }
1225
      else {
12261
        unset($workkeys[$k]);
1227
      }
12281
    }
12291
  }
1230
1231
  // If we didn't find anything, return the beginning.
12321
  if (count($ranges) == 0) {
12330
    return truncate_utf8($text, 256) . ' ...';
12340
  }
1235
1236
  // Sort the text ranges by starting position.
12371
  ksort($ranges);
1238
1239
  // Now we collapse overlapping text ranges into one. The sorting makes it
O(n).
12401
  $newranges = array();
12411
  foreach ($ranges as $from2 => $to2) {
12421
    if (!isset($from1)) {
12431
      $from1 = $from2;
12441
      $to1 = $to2;
12451
      continue;
12460
    }
12470
    if ($from2 <= $to1) {
12480
      $to1 = max($to1, $to2);
12490
    }
1250
    else {
12510
      $newranges[$from1] = $to1;
12520
      $from1 = $from2;
12530
      $to1 = $to2;
1254
    }
12550
  }
12561
  $newranges[$from1] = $to1;
1257
1258
  // Fetch text
12591
  $out = array();
12601
  foreach ($newranges as $from => $to) {
12611
    $out[] = substr($text, $from, $to - $from);
12621
  }
12631
  $text = (isset($newranges[0]) ? '' : '... ') . implode(' ... ', $out) . '
...';
1264
1265
  // Highlight keywords. Must be done at once to prevent conflicts
('strong' and '<strong>').
12661
  $text = preg_replace('/' . $boundary . '(' . implode('|', $keys) . ')' .
$boundary . '/iu', '<strong>\0</strong>', $text);
12671
  return $text;
12680
}
1269
1270
/**
1271
 * @} End of "defgroup search".
1272
 */
1273
1274
/**
1275
 * Helper function for array_walk in search_except.
1276
 */
127724
function _search_excerpt_replace(&$text) {
12781
  $text = preg_quote($text, '/');
12791
}
1280
128124
function search_forms() {
12824
  $forms['search_theme_form']= array(
12834
    'callback' => 'search_box',
12844
    'callback arguments' => array('search_theme_form'),
1285
  );
12864
  $forms['search_block_form']= array(
12874
    'callback' => 'search_box',
12884
    'callback arguments' => array('search_block_form'),
1289
  );
12904
  return $forms;
12910
}
129224