From 8daed9cbf353de947bc3916f103206edd121de33 Mon Sep 17 00:00:00 2001
From: Dries Buytaert The search page allows you to search the web site's content. You can specify multiple words, and they will all be searched for. You can also use wildcards, so 'walk*' will match 'walk', 'walking', 'walker', 'walkable' and so on. Furthermore, searches are not case sensitive so searching for 'walk', 'Walk' or 'WALK' will yield exactly the same results. Words that frequently occur, typically called 'noise words', are ignored. Example words are 'a', 'at', 'and', 'are', 'as', 'how', 'where', etc. Words shorter than %number letters are also ignored.
+
'. t('Approximately %percentage of the site has been indexed.', array('%percentage' => $percentage));
+ $output .= form_group('Indexing status', $status);
print theme('page', system_settings_form($output));
}
+/**
+ * Marks a word as dirty (or retrieves the list of dirty words). This is used
+ * during indexing (cron). Words which are dirty have outdated total counts in
+ * the search_total table, and need to be recounted.
+ */
+function search_dirty($word = null) {
+ static $dirty = array();
+ if ($word !== null) {
+ $dirty[$word] = true;
+ }
+ else {
+ return $dirty;
+ }
+}
+
/**
* Implementation of hook_cron().
*
- * Fires hook_update_index() in all modules and uses the results to make
- * the search index current.
+ * Fires hook_update_index() in all modules and cleans up dirty words (see
+ * search_dirty).
*/
function search_cron() {
+ /* Update word index */
foreach (module_list() as $module) {
- $module_array = module_invoke($module, 'update_index');
- if ($module_array) {
- update_index($module_array);
- }
- $module_array = null;
+ module_invoke($module, 'update_index');
+ }
+ /* Update word counts for new/changed words */
+ foreach (search_dirty() as $word => $dummy) {
+ db_query("DELETE FROM {search_total} WHERE word = '%s'", $word);
+ $total = db_result(db_query("SELECT SUM(score) FROM {search_index} WHERE word = '%s'", $word));
+ db_query("INSERT INTO {search_total} (word, count) VALUES ('%s', %d)", $word, $total);
}
- return;
}
/**
- * Perform a search on a word or words.
- *
- * This function is called by each node that supports the indexed search.
- *
- * @param $search_array
- * An array as returned from hook_search(). The format of this array is
- * array('keys' => ..., 'type' => ..., 'select' => ...). See the hook_search()
- * documentation for an explanation of the array values.
- *
- * @return
- * An array of search results, of which each element is an array with the
- * keys "count", "title", "link", "user" (name), "date", and "keywords".
+ * Splits a string into component words according to indexing rules.
*/
-function do_search($search_array) {
+function search_keywords_split($text) {
+ static $last = null;
+ static $lastsplit = null;
- $keys = strtolower($search_array['keys']);
- $type = $search_array['type'];
- $select = $search_array['select'];
+ if ($last == $text) {
+ return $lastsplit;
+ }
- // Remove punctuation/special characters (same rule as update_index()).
- $keys = preg_replace("'(!|%|,|:|;|\(|\)|\&|\"|\'|\.|-|\/|\?|\\\)'", '', $keys);
+ // Decode entities to UTF-8
+ $text = decode_entities($text);
- // Replace wildcards with MySQL wildcards.
- $keys = str_replace('*', '%', $keys);
+ // Call an external processor for word handling.
+ search_preprocess($text);
- // Split the words entered into an array.
- $words = explode(' ', $keys);
+ // To improve searching for numerical data such as dates, IP addresses
+ // or version numbers, we consider a group of numerical characters
+ // separated only by punctuation characters to be one piece.
+ // This also means that searching for e.g. '20/03/1984' also returns
+ // results with '20-03-1984' in them.
+ // Readable regexp: ([number]+)[punctuation]+(?=[number])
+ $text = preg_replace('/(['. PREG_CLASS_NUMBERS .']+)['. PREG_CLASS_PUNCTUATION .']+(?=['. PREG_CLASS_NUMBERS .'])/u', '\1', $text);
- foreach ($words as $word) {
+ // The dot, underscore and dash are simply removed. This allows meaningful
+ // search behaviour with acronyms and URLs.
+ $text = preg_replace('/[._-]+/', '', $text);
- // If the word is too short, and we've got it set to skip them, loop.
- if (strlen($word) < variable_get('remove_short', 0)) {
- continue;
- }
+ // With the exception of the rules above, we consider all punctuation,
+ // marks, spacers, etc, to be a word boundary.
+ $text = preg_replace('/['. PREG_CLASS_SEARCH_EXCLUDE . ']+/u', ' ', $text);
- // Put the next search word into the query and do the query.
- $query = str_replace("'%'", "'". check_query($word) ."'", $select);
- $result = db_query($query);
-
- if (db_num_rows($result) != 0) {
- // At least one matching record was found.
- $found = 1;
-
- // Create an in memory array of the results.
- while ($row = db_fetch_array($result)) {
- $lno = $row['lno'];
- $nid = $row['nid'];
- $title = $row['title'];
- $created = $row['created'];
- $uid = $row['uid'];
- $name = $row['name'];
- $count = $row['count'];
-
- // Build reduction variable.
- $reduction[$lno][$word] = true;
-
- // Check whether the just-fetched row is already in the table.
- if ($results[$lno]['lno'] != $lno) {
- $results[$lno]['count'] = $count;
-
- $results[$lno]['lno'] = $lno;
- $results[$lno]['nid'] = $nid;
- $results[$lno]['title'] = $title;
- $results[$lno]['created'] = $created;
- $results[$lno]['uid'] = $uid;
- $results[$lno]['name'] = $name;
- }
- else {
- // Different word, but existing "lno". Increase the count of
- // matches against this "lno" by the number of times this
- // word appears in the text.
- $results[$lno]['count'] = $results[$lno]['count'] + $count;
- }
- }
- }
- }
+ // Process words
+ $words = explode(' ', $text);
- if ($found) {
- foreach ($results as $lno => $values) {
- $pass = true;
- foreach ($words as $word) {
- if (!$reduction[$lno][$word]) {
- $pass = false;
- }
- }
- if ($pass) {
- $fullresults[$lno] = $values;
+ // Save last keyword result
+ $last = $text;
+ $lastsplit = $words;
+
+ return $words;
+}
+
+/**
+ * Invokes hook_search_preprocess() in modules.
+ */
+function search_preprocess(&$text) {
+ static $modules = null;
+ // Cache list of modules which implement this hook. This function gets called
+ // a lot during reindexing.
+ if (!is_array($modules)) {
+ $modules = array();
+ foreach (module_list() as $module) {
+ if (module_hook($module, 'search_preprocess')) {
+ $modules[] = $module;
}
}
- $results = $fullresults;
- if (!is_array($results)) {
- $found = 0;
- }
}
- if ($found) {
- // Black magic here to sort the results.
- array_multisort($results, SORT_DESC);
-
- // Now, output the results.
- foreach ($results as $key => $value) {
- $lno = $value['lno'];
- $nid = $value['nid'];
- $title = $value['title'];
- $created = $value['created'];
- $uid = $value['uid'];
- $name = $value['name'];
- $count = $value['count'];
- switch ($type) {
- case 'node':
- $find[$i++] = array('count' => $count, 'title' => $title, 'link' => url("node/$lno"), 'user' => $name, 'date' => $created, 'keywords' => implode('|', $words));
- break;
- case 'comment':
- $find[$i++] = array('count' => $count, 'title' => $title, 'link' => (strstr(request_uri(), 'admin') ? url("admin/comment/edit/$lno") : url("node/$nid", NULL, "comment-$lno")), 'user' => $name, 'date' => $created, 'keywords' => implode('|', $words));
- break;
- break;
- }
+ // Process $text
+ if (count($modules) > 0) {
+ foreach ($modules as $module) {
+ $text = module_invoke($module, 'search_preprocess', $text);
}
}
-
- return $find;
}
+
/**
- * Update the search_index table.
+ * Update the search index for a particular item.
+ *
+ * @param $sid
+ * A number identifying this particular item (e.g. node id).
*
- * @param $search_array
- * An array as returned from hook_update_index().
+ * @param $type
+ * A string defining this type of item (e.g. 'node')
+ *
+ * @param $text
+ * The content of this item. Must be a piece of HTML text.
*/
-function update_index($search_array) {
- $last_update = variable_get($search_array['last_update'], 1);
- $node_type = $search_array['node_type'];
- $select = $search_array['select'];
- $minimum_word_size = variable_get('minimum_word_size', 2);
-
- //watchdog('user', "$last_update
$node_type
$select");
-
- $result = db_query($select);
-
- if (db_num_rows($result)) {
- // Results were found. Look through the nodes we just selected.
- while ($node = db_fetch_array ($result)) {
-
- // Trash any existing entries in the search index for this node,
- // in case it is a modified node.
- db_query("DELETE from {search_index} WHERE lno = '". $node['lno'] ."' AND type = '". $node_type ."'");
-
- // Build the word list (teaser not included, as it would give a
- // false count of the number of hits).
- $wordlist = $node['text1'] .' '. $node['text2'];
-
- // Strip heaps of stuff out of it.
- $wordlist = preg_replace("'<[\/\!]*?[^<>]*?>'si", '', $wordlist);
-
- // Remove punctuation/special characters (same rule as do_search()).
- $keys = preg_replace("'(!|%|,|:|;|\(|\)|\&|\"|\'|\.|-|\/|\?|\\\)'", '', $keys);
-
- // Strip out (now mangled) http and tags.
- $wordlist = preg_replace("'http\w+'", '', $wordlist);
- $wordlist = preg_replace("'www\w+'", '', $wordlist);
-
- // Remove all newlines of any type.
- $wordlist = preg_replace("'([\r\n]|[\r]|[\n])'", ' ', $wordlist);
-
- // Lower case the whole thing.
- $wordlist = strtolower($wordlist);
-
- // Remove "noise words".
- $noise = explode(',', variable_get('noisewords', ''));
- foreach ($noise as $word) {
- $word = trim($word);
- $wordlist = trim(preg_replace("' $word '", ' ', ' ' .$wordlist. ' '));
+function search_index($sid, $type, $text) {
+ $minimum_word_size = variable_get('minimum_word_size', 3);
+
+ global $base_url;
+ $node_regexp = '!href=[\'"]?(?:'. preg_quote($base_url) .'/)?(?:\?q=)?([^\'">]+)[\'">]!i';
+
+ // Multipliers for scores of words inside certain HTML tags.
+ // Note: 'a' must be included for link ranking to work.
+ $tags = array('h1' => 21,
+ 'h2' => 18,
+ 'h3' => 15,
+ 'h4' => 12,
+ 'h5' => 9,
+ 'h6' => 6,
+ 'u' => 5,
+ 'b' => 5,
+ 'strong' => 5,
+ 'em' => 5,
+ 'a' => 10);
+
+ // Strip off all ignored tags to speed up processing, but insert space before/after
+ // them to keep word boundaries.
+ $text = str_replace(array('<', '>'), array(' <', '> '), $text);
+ $text = strip_tags($text, '<'. implode('><', array_keys($tags)) .'>');
+
+ // Split HTML tags from plain text.
+ $split = preg_split('/\s*<([^>]+?)>\s*/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
+ // Note: PHP ensures the array consists of alternating delimiters and literals
+ // and begins and ends with a literal (inserting $null as required).
+
+ $tag = false; // Odd/even counter. Tag or no tag.
+ $link = false; // State variable for link analyser
+ $score = 1; // Starting score per word
+
+ $results = array(0 => array());
+
+ foreach ($split as $value) {
+ if ($tag) {
+ // Increase or decrease score per word based on tag
+ list($tagname) = explode(' ', $value, 2);
+ $tagname = strtolower($tagname);
+ if ($tagname{0} == '/') {
+ $score -= $tags[substr($tagname, 1)];
+ if ($score < 1) { // possible due to bad HTML
+ $score = 1;
+ }
+ if ($tagname == '/a') {
+ $link = false;
+ }
}
-
- // Remove whitespace.
- $wordlist = preg_replace("'[\s]+'", ' ', $wordlist);
-
- // Make it an array.
- $eachword = explode(' ', $wordlist);
-
- // Walk through the array, giving a "weight" to each word based on
- // the number of times it appears in a page.
- foreach ($eachword as $word) {
- if (strlen($word) >= $minimum_word_size && strlen($word) <= 50) {
- if ($newwords[$word]) {
- $newwords[$word]++;
- }
- else {
- $newwords[$word] = 1;
+ else {
+ if ($tagname == 'a') {
+ // Check if link points to a node on this site
+ if (preg_match($node_regexp, $value, $match)) {
+ $path = drupal_get_normal_path($match[1]);
+ if (preg_match('!(node|book)/(?:view/)?([0-9]+)!i', $path, $match)) {
+ $linknid = $match[1];
+ if ($linknid > 0) {
+ $link = true;
+ }
+ }
}
}
+ $score += $tags[$tagname];
}
-
- // Walk through the weighted words array, inserting them into
- // the search index.
- if ($newwords) {
- foreach ($newwords as $key => $value) {
- db_query("INSERT INTO {search_index} VALUES('%s', %d, '%s', %d)", $key, $node['lno'], $node_type, $value);
+ }
+ else {
+ // Note: use of PREG_SPLIT_DELIM_CAPTURE above will introduce empty values
+ if ($value != '') {
+ $words = search_keywords_split($value);
+ foreach ($words as $word) {
+ // Check wordlength
+ if (string_length($word) >= $minimum_word_size) {
+ $word = strtolower($word);
+ if ($link) {
+ if (!isset($results[$linknid])) {
+ $results[$linknid] = array();
+ }
+ $results[$linknid][$word] += $score;
+ }
+ else {
+ $results[0][$word] += $score;
+ }
+ }
}
}
-
- // Reset the weighted words array, so we don't add multiples.
- $newwords = array ();
}
+ $tag = !$tag;
}
- // Update the last time this process was run.
- variable_set($search_array['last_update'], time());
-
- return true;
-}
+ db_query("DELETE FROM {search_index} WHERE sid = %d AND type = '%s'", $sid, $type);
+ // Insert results into search index
+ foreach ($results[0] as $word => $score) {
+ db_query("INSERT INTO {search_index} (word, sid, type, score) VALUES ('%s', %d, '%s', %d)", $word, $sid, $type, $score);
+ search_dirty($word);
+ }
+ unset($results[0]);
-function search_invalidate() {
- foreach (module_list() as $module) {
- $module_array = module_invoke($module, 'update_index');
- if ($module_array) {
- variable_set($module_array['last_update'], 1);
+ // Now insert links to nodes
+ foreach ($results as $nid => $words) {
+ foreach ($words as $word => $score) {
+ db_query("INSERT INTO {search_index} (word, sid, type, fromsid, fromtype, score) VALUES ('%s', %d, '%s', %d, '%s', %d)", $word, $nid, 'node', $sid, $type, $score);
+ search_dirty($word);
}
- $module_array = null;
}
- return;
}
/**
- * Save the values entered by the administrator for the search module
+ * Perform a search on a word or words.
+ *
+ * This function is called by each module that supports the indexed search.
+ *
+ * The end result is an SQL select on the search_index table. As a guide for
+ * writing the optional extra SQL fragments (see below), use this query:
+ *
+ * SELECT i.type, i.sid, i.word, SUM(i.score/t.count) AS score
+ * FROM {search_index} i
+ * $join INNER JOIN {search_total} t ON i.word = t.word
+ * WHERE $where AND (i.word = '...' OR ...)
+ * GROUP BY i.type, i.sid
+ * ORDER BY score DESC";
+ *
+ * @param $keys
+ * A search string as entered by the user.
+ *
+ * @param $type
+ * A string identifying the calling module.
*
- * @param $edit
- * An array of fields as set up by calling form_textfield(),
- * form_textarea(), etc.
+ * @param $join
+ * (optional) A string to be inserted into the JOIN part of the SQL query.
+ * For example "INNER JOIN {node} n ON n.nid = i.sid".
+ *
+ * @param $where
+ * (optional) A string to be inserted into the WHERE part of the SQL query.
+ * For example "(n.status > 0)".
+ *
+ * @return
+ * An array of SIDs for the search results.
*/
-function search_save($edit) {
- variable_set('minimum_word_size', $edit['minimum_word_size']);
-
- $data = strtr($edit['noisewords'], "\n\r\t", ' ');
- $data = str_replace(' ', '', $data);
- variable_set('noisewords', $data);
- variable_set('help_pos', $edit['help_pos']);
- variable_set('remove_short', $edit['remove_short']);
+function do_search($keys, $type, $join = '', $where = '1') {
+ // Note, we replace the wildcards with U+FFFD (Replacement character) to pass
+ // through the keyword extractor.
+ $keys = str_replace('*', '�', $keys);
+
+ // Split into words
+ $keys = search_keywords_split($keys);
+ // Lowercase
+ foreach ($keys as $k => $v) {
+ $keys[$k] = strtolower($v);
+ }
+
+ $words = array();
+ $arguments = array();
+ // Build WHERE clause
+ foreach ($keys as $word) {
+ if (string_length($word) < variable_get('remove_short', 3)) {
+ continue;
+ }
+ if (strpos($word, '�') !== false) {
+ $words[] = "i.word LIKE '%s'";
+ $arguments[] = str_replace('�', '%', $word);
+ }
+ else {
+ $words[] = "i.word = '%s'";
+ $arguments[] = $word;
+ }
+ }
+ if (count($words) == 0) {
+ return array();
+ }
+ $where .= ' AND ('. implode(' OR ', $words) .')';
+
+ // Get result count (for pager)
+ $count = db_result(db_query("SELECT COUNT(DISTINCT i.sid, i.type) FROM {search_index} i $join WHERE $where", $arguments));
+ if ($count == 0) {
+ return array();
+ }
+ $count_query = "SELECT $count";
+
+ // Do pager query
+ $query = "SELECT i.type, i.sid, i.word, SUM(i.score/t.count) AS score FROM {search_index} i $join INNER JOIN {search_total} t ON i.word = t.word WHERE $where GROUP BY i.type, i.sid ORDER BY score DESC";
+ $arguments = array_merge(array($query, 15, 0, $count_query), $arguments);
+ $result = call_user_func_array('pager_query', $arguments);
+
+ $results = array();
+ while ($item = db_fetch_object($result)) {
+ $results[] = $item->sid;
+ }
+
+ return $results;
}
/**
* Menu callback; presents the search form and/or search results.
*/
function search_view() {
- global $type;
- $keys = isset($_GET['keys']) ? $_GET['keys'] : $_POST['keys'];
+ $keys = isset($_GET['keys']) ? $_GET['keys'] : $_POST['edit']['keys'];
+ $type = isset($_GET['type']) ? $_GET['type'] : ($_POST['edit']['type'] ? $_POST['edit']['type'] : 'node');
if (user_access('search content')) {
- // Construct the search form.
- $output = search_form(NULL, $keys, TRUE);
-
- // Display form and search results.
- $help_link = l(t('search help'), 'search/help');
- switch (variable_get('help_pos', 1)) {
- case '1':
- $output = search_help(). $output .'
';
- break;
- case '2':
- $output .= search_help() .'
';
- break;
- case '3':
- $output = $help_link. '
'. $output .'
';
- break;
- case '4':
- $output .= '
'. $help_link .'
';
- }
-
// Only perform search if there is non-whitespace search term:
if (trim($keys)) {
// Log the search keys:
- watchdog('search', t('Search: %keys.', array('%keys' => "$keys")), l(t('results'), 'search', NULL, 'keys='. urlencode($keys)));
+ watchdog('search', t('Search: %keys (%type).', array('%keys' => "$keys", '%type' => $type)), l(t('results'), 'search', NULL, 'keys='. urlencode($keys) . '&type='. urlencode($type)));
// Collect the search results:
- $results = search_data($keys);
+ $results = search_data($keys, $type);
if ($results) {
- $output .= theme('box', t('Search Results'), $results);
+ $results = theme('box', t('Search results'), $results);
}
else {
- $output .= theme('box', t('Search Results'), t('Your search yielded no results.'));
+ $results = theme('box', t('Your search yielded no results'), search_help('search#noresults'));
}
}
+ else if (isset($_POST['edit'])) {
+ form_set_error('keys', t('Please enter some keywords.'));
+ }
+
+ // Construct the search form.
+ // Note, we do this last because of the form_set_error() above.
+ $output = search_form(NULL, $keys, $type, TRUE);
+
+ $output .= $results;
print theme('page', $output, t('Search'));
}
@@ -407,4 +482,242 @@ function search_help_page() {
print theme('page', search_help());
}
+/**
+ * @defgroup search Search interface
+ * @{
+ * The Drupal search interface manages a global search mechanism.
+ *
+ * Modules may plug into this system to provide searches of different types of
+ * data. Most of the system is handled by search.module, so this must be enabled
+ * for all of the search features to work.
+ */
+
+/**
+ * Render a search form.
+ *
+ * This form must be usable not only within "http://example.com/search", but also
+ * as a simple search box (without "Restrict search to", help text, etc.), in the
+ * theme's header, and so forth. This means we must provide options to
+ * conditionally render certain parts of this form.
+ *
+ * @param $action
+ * Form action. Defaults to "search".
+ * @param $keys
+ * The search string entered by the user, containing keywords for the search.
+ * @param $options
+ * Whether to render the optional form fields and text ("Restrict search
+ * to", help text, etc.).
+ * @return
+ * An HTML string containing the search form.
+ */
+function search_form($action = '', $keys = '', $type = null, $options = FALSE) {
+ $edit = $_POST['edit'];
+
+ if (!$action) {
+ $action = url('search');
+ }
+
+ $output = '
'. $item['snippet'] . '
' : '') . '' . implode(' - ', $info) .'