/[drupal]/drupal/modules/search/search.module
ViewVC logotype

Contents of /drupal/modules/search/search.module

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.323 - (show annotations) (download) (as text)
Sun Nov 1 21:46:16 2009 UTC (3 weeks, 5 days ago) by webchick
Branch: MAIN
Changes since 1.322: +6 -6 lines
File MIME type: text/x-php
#615508 by Crell: Use slave servers for search module.
1 <?php
2 // $Id: search.module,v 1.322 2009/11/01 12:11:10 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 */
22 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}-' .
24 '\x{385}\x{387}\x{3f6}\x{482}-\x{489}\x{559}-\x{55f}\x{589}-\x{5c7}\x{5f3}-' .
25 '\x{61f}\x{640}\x{64b}-\x{65e}\x{66a}-\x{66d}\x{670}\x{6d4}\x{6d6}-\x{6ed}' .
26 '\x{6fd}\x{6fe}\x{700}-\x{70f}\x{711}\x{730}-\x{74a}\x{7a6}-\x{7b0}\x{901}-' .
27 '\x{903}\x{93c}\x{93e}-\x{94d}\x{951}-\x{954}\x{962}-\x{965}\x{970}\x{981}-' .
28 '\x{983}\x{9bc}\x{9be}-\x{9cd}\x{9d7}\x{9e2}\x{9e3}\x{9f2}-\x{a03}\x{a3c}-' .
29 '\x{a4d}\x{a70}\x{a71}\x{a81}-\x{a83}\x{abc}\x{abe}-\x{acd}\x{ae2}\x{ae3}' .
30 '\x{af1}-\x{b03}\x{b3c}\x{b3e}-\x{b57}\x{b70}\x{b82}\x{bbe}-\x{bd7}\x{bf0}-' .
31 '\x{c03}\x{c3e}-\x{c56}\x{c82}\x{c83}\x{cbc}\x{cbe}-\x{cd6}\x{d02}\x{d03}' .
32 '\x{d3e}-\x{d57}\x{d82}\x{d83}\x{dca}-\x{df4}\x{e31}\x{e34}-\x{e3f}\x{e46}-' .
33 '\x{e4f}\x{e5a}\x{e5b}\x{eb1}\x{eb4}-\x{ebc}\x{ec6}-\x{ecd}\x{f01}-\x{f1f}' .
34 '\x{f2a}-\x{f3f}\x{f71}-\x{f87}\x{f90}-\x{fd1}\x{102c}-\x{1039}\x{104a}-' .
35 '\x{104f}\x{1056}-\x{1059}\x{10fb}\x{10fc}\x{135f}-\x{137c}\x{1390}-\x{1399}' .
36 '\x{166d}\x{166e}\x{1680}\x{169b}\x{169c}\x{16eb}-\x{16f0}\x{1712}-\x{1714}' .
37 '\x{1732}-\x{1736}\x{1752}\x{1753}\x{1772}\x{1773}\x{17b4}-\x{17db}\x{17dd}' .
38 '\x{17f0}-\x{180e}\x{1843}\x{18a9}\x{1920}-\x{1945}\x{19b0}-\x{19c0}\x{19c8}' .
39 '\x{19c9}\x{19de}-\x{19ff}\x{1a17}-\x{1a1f}\x{1d2c}-\x{1d61}\x{1d78}\x{1d9b}-' .
40 '\x{1dc3}\x{1fbd}\x{1fbf}-\x{1fc1}\x{1fcd}-\x{1fcf}\x{1fdd}-\x{1fdf}\x{1fed}-' .
41 '\x{1fef}\x{1ffd}-\x{2070}\x{2074}-\x{207e}\x{2080}-\x{2101}\x{2103}-\x{2106}' .
42 '\x{2108}\x{2109}\x{2114}\x{2116}-\x{2118}\x{211e}-\x{2123}\x{2125}\x{2127}' .
43 '\x{2129}\x{212e}\x{2132}\x{213a}\x{213b}\x{2140}-\x{2144}\x{214a}-\x{2b13}' .
44 '\x{2ce5}-\x{2cff}\x{2d6f}\x{2e00}-\x{3005}\x{3007}-\x{303b}\x{303d}-\x{303f}' .
45 '\x{3099}-\x{309e}\x{30a0}\x{30fb}-\x{30fe}\x{3190}-\x{319f}\x{31c0}-\x{31cf}' .
46 '\x{3200}-\x{33ff}\x{4dc0}-\x{4dff}\x{a015}\x{a490}-\x{a716}\x{a802}\x{a806}' .
47 '\x{a80b}\x{a823}-\x{a82b}\x{d800}-\x{f8ff}\x{fb1e}\x{fb29}\x{fd3e}\x{fd3f}' .
48 '\x{fdfc}-\x{fe6b}\x{feff}-\x{ff0f}\x{ff1a}-\x{ff20}\x{ff3b}-\x{ff40}\x{ff5b}-' .
49 '\x{ff65}\x{ff70}\x{ff9e}\x{ff9f}\x{ffe0}-\x{fffd}');
50
51 /**
52 * Matches all 'N' Unicode character classes (numbers)
53 */
54 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}' .
56 '\x{966}-\x{96f}\x{9e6}-\x{9ef}\x{9f4}-\x{9f9}\x{a66}-\x{a6f}\x{ae6}-\x{aef}' .
57 '\x{b66}-\x{b6f}\x{be7}-\x{bf2}\x{c66}-\x{c6f}\x{ce6}-\x{cef}\x{d66}-\x{d6f}' .
58 '\x{e50}-\x{e59}\x{ed0}-\x{ed9}\x{f20}-\x{f33}\x{1040}-\x{1049}\x{1369}-' .
59 '\x{137c}\x{16ee}-\x{16f0}\x{17e0}-\x{17e9}\x{17f0}-\x{17f9}\x{1810}-\x{1819}' .
60 '\x{1946}-\x{194f}\x{2070}\x{2074}-\x{2079}\x{2080}-\x{2089}\x{2153}-\x{2183}' .
61 '\x{2460}-\x{249b}\x{24ea}-\x{24ff}\x{2776}-\x{2793}\x{3007}\x{3021}-\x{3029}' .
62 '\x{3038}-\x{303a}\x{3192}-\x{3195}\x{3220}-\x{3229}\x{3251}-\x{325f}\x{3280}-' .
63 '\x{3289}\x{32b1}-\x{32bf}\x{ff10}-\x{ff19}');
64
65 /**
66 * Matches all 'P' Unicode character classes (punctuation)
67 */
68 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}' .
70 '\x{5f}\x{7b}\x{7d}\x{a1}\x{ab}\x{b7}\x{bb}\x{bf}\x{37e}\x{387}\x{55a}-\x{55f}' .
71 '\x{589}\x{58a}\x{5be}\x{5c0}\x{5c3}\x{5f3}\x{5f4}\x{60c}\x{60d}\x{61b}\x{61f}' .
72 '\x{66a}-\x{66d}\x{6d4}\x{700}-\x{70d}\x{964}\x{965}\x{970}\x{df4}\x{e4f}' .
73 '\x{e5a}\x{e5b}\x{f04}-\x{f12}\x{f3a}-\x{f3d}\x{f85}\x{104a}-\x{104f}\x{10fb}' .
74 '\x{1361}-\x{1368}\x{166d}\x{166e}\x{169b}\x{169c}\x{16eb}-\x{16ed}\x{1735}' .
75 '\x{1736}\x{17d4}-\x{17d6}\x{17d8}-\x{17da}\x{1800}-\x{180a}\x{1944}\x{1945}' .
76 '\x{2010}-\x{2027}\x{2030}-\x{2043}\x{2045}-\x{2051}\x{2053}\x{2054}\x{2057}' .
77 '\x{207d}\x{207e}\x{208d}\x{208e}\x{2329}\x{232a}\x{23b4}-\x{23b6}\x{2768}-' .
78 '\x{2775}\x{27e6}-\x{27eb}\x{2983}-\x{2998}\x{29d8}-\x{29db}\x{29fc}\x{29fd}' .
79 '\x{3001}-\x{3003}\x{3008}-\x{3011}\x{3014}-\x{301f}\x{3030}\x{303d}\x{30a0}' .
80 '\x{30fb}\x{fd3e}\x{fd3f}\x{fe30}-\x{fe52}\x{fe54}-\x{fe61}\x{fe63}\x{fe68}' .
81 '\x{fe6a}\x{fe6b}\x{ff01}-\x{ff03}\x{ff05}-\x{ff0a}\x{ff0c}-\x{ff0f}\x{ff1a}' .
82 '\x{ff1b}\x{ff1f}\x{ff20}\x{ff3b}-\x{ff3d}\x{ff3f}\x{ff5b}\x{ff5d}\x{ff5f}-' .
83 '\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 */
90 define('PREG_CLASS_CJK', '\x{3041}-\x{30ff}\x{31f0}-\x{31ff}\x{3400}-\x{4db5}' .
91 '\x{4e00}-\x{9fbb}\x{f900}-\x{fad9}');
92
93 /**
94 * Implement hook_help().
95 */
96 function search_help($path, $arg) {
97 switch ($path) {
98 case 'admin/help#search':
99 $output = '<p>' . t('The search module adds the ability to search for content by keywords. Search is often the only practical way to find content on a large site, and is useful for finding both users and posts.') . '</p>';
100 $output = '<p>' . t('It is important to note that by default, the search module only supports exact keyword matching. You can modify this behavior by installing a language-specific stemming module for your language, which allows words such as walk, walking, and walked all to match each other. Another approach is to install an n-gram module, which breaks words down into small, overlapping chunks and finds words with a high degree of overlap, so that words like earthquake and quake can match each other. A third approach is to use a third-party search technology with features like this built in; there are modules available for several of these, such as Apache Solr and Sphinx.') . '</p>';
101 $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/config/search/settings'))) . '</p>';
102 $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>';
103 return $output;
104 case 'admin/config/search/settings':
105 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>';
106 case 'search#noresults':
107 return t('<ul>
108 <li>Check if your spelling is correct.</li>
109 <li>Remove quotes around phrases to search for each word individually. <em>bike shed</em> will often show more results than <em>&quot;bike shed&quot;</em>.</li>
110 <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>
111 </ul>');
112 }
113 }
114
115 /**
116 * Implement hook_theme().
117 */
118 function search_theme() {
119 return array(
120 'search_block_form' => array(
121 'render element' => 'form',
122 'template' => 'search-block-form',
123 ),
124 'search_result' => array(
125 'variables' => array('result' => NULL, 'type' => NULL),
126 'file' => 'search.pages.inc',
127 'template' => 'search-result',
128 ),
129 'search_results' => array(
130 'variables' => array('results' => NULL, 'type' => NULL),
131 'file' => 'search.pages.inc',
132 'template' => 'search-results',
133 ),
134 'search_results_listing' => array(
135 'variables' => array('title' => NULL, 'content' => NULL),
136 ),
137 );
138 }
139
140 /**
141 * Implement hook_permission().
142 */
143 function search_permission() {
144 return array(
145 'administer search' => array(
146 'title' => t('Administer search'),
147 'description' => t('Configure search administration settings.'),
148 ),
149 'search content' => array(
150 'title' => t('Search content'),
151 'description' => t('Search website content.'),
152 ),
153 'use advanced search' => array(
154 'title' => t('Use advanced search'),
155 'description' => t('Limit search results with additional criteria, such as specific content types. Could have performance implications.'),
156 ),
157 );
158 }
159
160 /**
161 * Implement hook_block_info().
162 */
163 function search_block_info() {
164 $blocks['form']['info'] = t('Search form');
165 // Not worth caching.
166 $blocks['form']['cache'] = DRUPAL_NO_CACHE;
167 return $blocks;
168 }
169
170 /**
171 * Implement hook_block_view().
172 */
173 function search_block_view($delta = '') {
174 if (user_access('search content')) {
175 $block['content'] = drupal_get_form('search_block_form');
176 return $block;
177 }
178 }
179
180 /**
181 * Implement hook_menu().
182 */
183 function search_menu() {
184 $items['search'] = array(
185 'title' => 'Search',
186 'page callback' => 'search_view',
187 'access arguments' => array('search content'),
188 'type' => MENU_SUGGESTED_ITEM,
189 'file' => 'search.pages.inc',
190 );
191 $items['admin/config/search/settings'] = array(
192 'title' => 'Search settings',
193 'description' => 'Configure relevance settings for search and other indexing options',
194 'page callback' => 'drupal_get_form',
195 'page arguments' => array('search_admin_settings'),
196 'access arguments' => array('administer search'),
197 'type' => MENU_NORMAL_ITEM,
198 'file' => 'search.admin.inc',
199 );
200 $items['admin/config/search/settings/reindex'] = array(
201 'title' => 'Clear index',
202 'page callback' => 'drupal_get_form',
203 'page arguments' => array('search_reindex_confirm'),
204 'access arguments' => array('administer search'),
205 'type' => MENU_CALLBACK,
206 'file' => 'search.admin.inc',
207 );
208 $items['admin/reports/search'] = array(
209 'title' => 'Top search phrases',
210 'description' => 'View most popular search phrases.',
211 'page callback' => 'dblog_top',
212 'page arguments' => array('search'),
213 'access arguments' => array('access site reports'),
214 'file path' => drupal_get_path('module', 'dblog'),
215 'file' => 'dblog.admin.inc',
216 );
217 drupal_static_reset('search_get_info');
218 $search_hooks = search_get_info();
219 foreach(variable_get('search_active_modules', array('node', 'user')) as $module) {
220 if (isset($search_hooks[$module])) {
221 $items['search/' . $search_hooks[$module]['path'] . '/%menu_tail'] = array(
222 'title' => $search_hooks[$module]['title'],
223 'page callback' => 'search_view',
224 'page arguments' => array($module),
225 'access callback' => '_search_menu_access',
226 'access arguments' => array($module),
227 'type' => MENU_LOCAL_TASK,
228 'file' => 'search.pages.inc',
229 );
230 }
231 }
232 return $items;
233 }
234
235 /**
236 * Get information about all available search hooks.
237 */
238 function search_get_info() {
239 $search_hooks = &drupal_static(__FUNCTION__);
240
241 if (!isset($search_hooks)) {
242 foreach (module_implements('search_info') as $module) {
243 $search_hooks[$module] = call_user_func($module . '_search_info');
244 // Use module name as the default.
245 $search_hooks[$module] += array('title' => $module, 'path' => $module);
246 }
247 }
248 return $search_hooks;
249 }
250
251 /**
252 * Access callback for search tabs.
253 */
254 function _search_menu_access($name) {
255 return user_access('search content') && (!function_exists($name . '_search_access') || module_invoke($name, 'search_access'));
256 }
257
258 /**
259 * Wipes a part of or the entire search index.
260 *
261 * @param $sid
262 * (optional) The SID of the item to wipe. If specified, $type must be passed
263 * too.
264 * @param $type
265 * (optional) The type of item to wipe.
266 */
267 function search_reindex($sid = NULL, $type = NULL, $reindex = FALSE) {
268 if ($type == NULL && $sid == NULL) {
269 module_invoke_all('search_reset');
270 }
271 else {
272 db_delete('search_dataset')
273 ->condition('sid', $sid)
274 ->condition('type', $type)
275 ->execute();
276 db_delete('search_index')
277 ->condition('sid', $sid)
278 ->condition('type', $type)
279 ->execute();
280 // Don't remove links if re-indexing.
281 if (!$reindex) {
282 db_delete('search_node_links')
283 ->condition('sid', $sid)
284 ->condition('type', $type)
285 ->execute();
286 }
287 }
288 }
289
290 /**
291 * Marks a word as dirty (or retrieves the list of dirty words). This is used
292 * during indexing (cron). Words which are dirty have outdated total counts in
293 * the search_total table, and need to be recounted.
294 */
295 function search_dirty($word = NULL) {
296 static $dirty = array();
297 if ($word !== NULL) {
298 $dirty[$word] = TRUE;
299 }
300 else {
301 return $dirty;
302 }
303 }
304
305 /**
306 * Implement hook_cron().
307 *
308 * Fires hook_update_index() in all modules and cleans up dirty words (see
309 * search_dirty).
310 */
311 function search_cron() {
312 // We register a shutdown function to ensure that search_total is always up
313 // to date.
314 register_shutdown_function('search_update_totals');
315
316 foreach(variable_get('search_active_modules', array('node', 'user')) as $module) {
317 // Update word index
318 module_invoke($module, 'update_index');
319 }
320 }
321
322 /**
323 * This function is called on shutdown to ensure that search_total is always
324 * up to date (even if cron times out or otherwise fails).
325 */
326 function search_update_totals() {
327 // Update word IDF (Inverse Document Frequency) counts for new/changed words.
328 foreach (search_dirty() as $word => $dummy) {
329 // Get total count
330 $total = db_query("SELECT SUM(score) FROM {search_index} WHERE word = :word", array(':word' => $word), array('target' => 'slave'))->fetchField();
331 // Apply Zipf's law to equalize the probability distribution.
332 $total = log10(1 + 1/(max(1, $total)));
333 db_merge('search_total')
334 ->key(array('word' => $word))
335 ->fields(array('count' => $total))
336 ->execute();
337 }
338 // Find words that were deleted from search_index, but are still in
339 // search_total. We use a LEFT JOIN between the two tables and keep only the
340 // rows which fail to join.
341 $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", array(), array('target' => 'slave'));
342 $or = db_or();
343 foreach ($result as $word) {
344 $or->condition('word', $word->realword);
345 }
346 if (count($or) > 0) {
347 db_delete('search_total')
348 ->condition($or)
349 ->execute();
350 }
351 }
352
353 /**
354 * Simplifies a string according to indexing rules.
355 */
356 function search_simplify($text) {
357 // Decode entities to UTF-8
358 $text = decode_entities($text);
359
360 // Lowercase
361 $text = drupal_strtolower($text);
362
363 // Call an external processor for word handling.
364 search_invoke_preprocess($text);
365
366 // Simple CJK handling
367 if (variable_get('overlap_cjk', TRUE)) {
368 $text = preg_replace_callback('/[' . PREG_CLASS_CJK . ']+/u', 'search_expand_cjk', $text);
369 }
370
371 // To improve searching for numerical data such as dates, IP addresses
372 // or version numbers, we consider a group of numerical characters
373 // separated only by punctuation characters to be one piece.
374 // This also means that searching for e.g. '20/03/1984' also returns
375 // results with '20-03-1984' in them.
376 // Readable regexp: ([number]+)[punctuation]+(?=[number])
377 $text = preg_replace('/([' . PREG_CLASS_NUMBERS . ']+)[' . PREG_CLASS_PUNCTUATION . ']+(?=[' . PREG_CLASS_NUMBERS . '])/u', '\1', $text);
378
379 // The dot, underscore and dash are simply removed. This allows meaningful
380 // search behavior with acronyms and URLs.
381 $text = preg_replace('/[._-]+/', '', $text);
382
383 // With the exception of the rules above, we consider all punctuation,
384 // marks, spacers, etc, to be a word boundary.
385 $text = preg_replace('/[' . PREG_CLASS_SEARCH_EXCLUDE . ']+/u', ' ', $text);
386
387 return $text;
388 }
389
390 /**
391 * Basic CJK tokenizer. Simply splits a string into consecutive, overlapping
392 * sequences of characters ('minimum_word_size' long).
393 */
394 function search_expand_cjk($matches) {
395 $min = variable_get('minimum_word_size', 3);
396 $str = $matches[0];
397 $l = drupal_strlen($str);
398 // Passthrough short words
399 if ($l <= $min) {
400 return ' ' . $str . ' ';
401 }
402 $tokens = ' ';
403 // FIFO queue of characters
404 $chars = array();
405 // Begin loop
406 for ($i = 0; $i < $l; ++$i) {
407 // Grab next character
408 $current = drupal_substr($str, 0, 1);
409 $str = substr($str, strlen($current));
410 $chars[] = $current;
411 if ($i >= $min - 1) {
412 $tokens .= implode('', $chars) . ' ';
413 array_shift($chars);
414 }
415 }
416 return $tokens;
417 }
418
419 /**
420 * Splits a string into tokens for indexing.
421 */
422 function search_index_split($text) {
423 static $last = NULL;
424 static $lastsplit = NULL;
425
426 if ($last == $text) {
427 return $lastsplit;
428 }
429 // Process words
430 $text = search_simplify($text);
431 $words = explode(' ', $text);
432 array_walk($words, '_search_index_truncate');
433
434 // Save last keyword result
435 $last = $text;
436 $lastsplit = $words;
437
438 return $words;
439 }
440
441 /**
442 * Helper function for array_walk in search_index_split.
443 */
444 function _search_index_truncate(&$text) {
445 $text = truncate_utf8($text, 50);
446 }
447
448 /**
449 * Invokes hook_search_preprocess() in modules.
450 */
451 function search_invoke_preprocess(&$text) {
452 foreach (module_implements('search_preprocess') as $module) {
453 $text = module_invoke($module, 'search_preprocess', $text);
454 }
455 }
456
457 /**
458 * Update the full-text search index for a particular item.
459 *
460 * @param $sid
461 * A number identifying this particular item (e.g. node id).
462 *
463 * @param $type
464 * A string defining this type of item (e.g. 'node')
465 *
466 * @param $text
467 * The content of this item. Must be a piece of HTML text.
468 *
469 * @ingroup search
470 */
471 function search_index($sid, $type, $text) {
472 $minimum_word_size = variable_get('minimum_word_size', 3);
473
474 // Link matching
475 global $base_url;
476 $node_regexp = '@href=[\'"]?(?:' . preg_quote($base_url, '@') . '/|' . preg_quote(base_path(), '@') . ')(?:\?q=)?/?((?![a-z]+:)[^\'">]+)[\'">]@i';
477
478 // Multipliers for scores of words inside certain HTML tags. The weights are stored
479 // in a variable so that modules can overwrite the default weights.
480 // Note: 'a' must be included for link ranking to work.
481 $tags = variable_get('search_tag_weights', array(
482 'h1' => 25,
483 'h2' => 18,
484 'h3' => 15,
485 'h4' => 12,
486 'h5' => 9,
487 'h6' => 6,
488 'u' => 3,
489 'b' => 3,
490 'i' => 3,
491 'strong' => 3,
492 'em' => 3,
493 'a' => 10));
494
495 // Strip off all ignored tags to speed up processing, but insert space before/after
496 // them to keep word boundaries.
497 $text = str_replace(array('<', '>'), array(' <', '> '), $text);
498 $text = strip_tags($text, '<' . implode('><', array_keys($tags)) . '>');
499
500 // Split HTML tags from plain text.
501 $split = preg_split('/\s*<([^>]+?)>\s*/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
502 // Note: PHP ensures the array consists of alternating delimiters and literals
503 // and begins and ends with a literal (inserting $null as required).
504
505 $tag = FALSE; // Odd/even counter. Tag or no tag.
506 $link = FALSE; // State variable for link analyzer
507 $score = 1; // Starting score per word
508 $accum = ' '; // Accumulator for cleaned up data
509 $tagstack = array(); // Stack with open tags
510 $tagwords = 0; // Counter for consecutive words
511 $focus = 1; // Focus state
512
513 $results = array(0 => array()); // Accumulator for words for index
514
515 foreach ($split as $value) {
516 if ($tag) {
517 // Increase or decrease score per word based on tag
518 list($tagname) = explode(' ', $value, 2);
519 $tagname = drupal_strtolower($tagname);
520 // Closing or opening tag?
521 if ($tagname[0] == '/') {
522 $tagname = substr($tagname, 1);
523 // If we encounter unexpected tags, reset score to avoid incorrect boosting.
524 if (!count($tagstack) || $tagstack[0] != $tagname) {
525 $tagstack = array();
526 $score = 1;
527 }
528 else {
529 // Remove from tag stack and decrement score
530 $score = max(1, $score - $tags[array_shift($tagstack)]);
531 }
532 if ($tagname == 'a') {
533 $link = FALSE;
534 }
535 }
536 else {
537 if (isset($tagstack[0]) && $tagstack[0] == $tagname) {
538 // None of the tags we look for make sense when nested identically.
539 // If they are, it's probably broken HTML.
540 $tagstack = array();
541 $score = 1;
542 }
543 else {
544 // Add to open tag stack and increment score
545 array_unshift($tagstack, $tagname);
546 $score += $tags[$tagname];
547 }
548 if ($tagname == 'a') {
549 // Check if link points to a node on this site
550 if (preg_match($node_regexp, $value, $match)) {
551 $path = drupal_get_normal_path($match[1]);
552 if (preg_match('!(?:node|book)/(?:view/)?([0-9]+)!i', $path, $match)) {
553 $linknid = $match[1];
554 if ($linknid > 0) {
555 // Note: ignore links to uncacheable nodes to avoid redirect bugs.
556 $node = db_query('SELECT title, nid, vid FROM {node} WHERE nid = :nid', array(':nid' => $linknid), array('target' => 'slave'))->fetchObject();
557 $link = TRUE;
558 $linktitle = $node->title;
559 }
560 }
561 }
562 }
563 }
564 // A tag change occurred, reset counter.
565 $tagwords = 0;
566 }
567 else {
568 // Note: use of PREG_SPLIT_DELIM_CAPTURE above will introduce empty values
569 if ($value != '') {
570 if ($link) {
571 // Check to see if the node link text is its URL. If so, we use the target node title instead.
572 if (preg_match('!^https?://!i', $value)) {
573 $value = $linktitle;
574 }
575 }
576 $words = search_index_split($value);
577 foreach ($words as $word) {
578 // Add word to accumulator
579 $accum .= $word . ' ';
580 $num = is_numeric($word);
581 // Check wordlength
582 if ($num || drupal_strlen($word) >= $minimum_word_size) {
583 // Normalize numbers
584 if ($num) {
585 $word = (int)ltrim($word, '-0');
586 }
587
588 // Links score mainly for the target.
589 if ($link) {
590 if (!isset($results[$linknid])) {
591 $results[$linknid] = array();
592 }
593 $results[$linknid][] = $word;
594 // Reduce score of the link caption in the source.
595 $focus *= 0.2;
596 }
597 // Fall-through
598 if (!isset($results[0][$word])) {
599 $results[0][$word] = 0;
600 }
601 $results[0][$word] += $score * $focus;
602
603 // Focus is a decaying value in terms of the amount of unique words up to this point.
604 // From 100 words and more, it decays, to e.g. 0.5 at 500 words and 0.3 at 1000 words.
605 $focus = min(1, .01 + 3.5 / (2 + count($results[0]) * .015));
606 }
607 $tagwords++;
608 // Too many words inside a single tag probably mean a tag was accidentally left open.
609 if (count($tagstack) && $tagwords >= 15) {
610 $tagstack = array();
611 $score = 1;
612 }
613 }
614 }
615 }
616 $tag = !$tag;
617 }
618
619 search_reindex($sid, $type, TRUE);
620
621 // Insert cleaned up data into dataset
622 db_insert('search_dataset')
623 ->fields(array(
624 'sid' => $sid,
625 'type' => $type,
626 'data' => $accum,
627 'reindex' => 0,
628 ))
629 ->execute();
630
631 // Insert results into search index
632 foreach ($results[0] as $word => $score) {
633 // If a word already exists in the database, its score gets increased
634 // appropriately. If not, we create a new record with the appropriate
635 // starting score.
636 db_merge('search_index')
637 ->key(array(
638 'word' => $word,
639 'sid' => $sid,
640 'type' => $type,
641 ))
642 ->fields(array('score' => $score))
643 ->expression('score', 'score + :score', array(':score' => $score))
644 ->execute();
645 search_dirty($word);
646 }
647 unset($results[0]);
648
649 // Get all previous links from this item.
650 $result = db_query("SELECT nid, caption FROM {search_node_links} WHERE sid = :sid AND type = :type", array(
651 ':sid' => $sid,
652 ':type' => $type
653 ), array('target' => 'slave'));
654 $links = array();
655 foreach ($result as $link) {
656 $links[$link->nid] = $link->caption;
657 }
658
659 // Now store links to nodes.
660 foreach ($results as $nid => $words) {
661 $caption = implode(' ', $words);
662 if (isset($links[$nid])) {
663 if ($links[$nid] != $caption) {
664 // Update the existing link and mark the node for reindexing.
665 db_update('search_node_links')
666 ->fields(array('caption' => $caption))
667 ->condition('sid', $sid)
668 ->condition('type', $type)
669 ->condition('nid', $nid)
670 ->execute();
671 search_touch_node($nid);
672 }
673 // Unset the link to mark it as processed.
674 unset($links[$nid]);
675 }
676 else {
677 // Insert the existing link and mark the node for reindexing.
678 db_insert('search_node_links')
679 ->fields(array(
680 'caption' => $caption,
681 'sid' => $sid,
682 'type' => $type,
683 'nid' => $nid,
684 ))
685 ->execute();
686 search_touch_node($nid);
687 }
688 }
689 // Any left-over links in $links no longer exist. Delete them and mark the nodes for reindexing.
690 foreach ($links as $nid => $caption) {
691 db_delete('search_node_links')
692 ->condition('sid', $sid)
693 ->condition('type', $type)
694 ->condition('nid', $nid)
695 ->execute();
696 search_touch_node($nid);
697 }
698 }
699
700 /**
701 * Change a node's changed timestamp to 'now' to force reindexing.
702 *
703 * @param $nid
704 * The nid of the node that needs reindexing.
705 */
706 function search_touch_node($nid) {
707 db_update('search_dataset')
708 ->fields(array('reindex' => REQUEST_TIME))
709 ->condition('type', 'node')
710 ->condition('sid', $nid)
711 ->execute();
712 }
713
714 /**
715 * Implement hook_node_update_index().
716 */
717 function search_node_update_index(stdClass $node) {
718 // Transplant links to a node into the target node.
719 $result = db_query("SELECT caption FROM {search_node_links} WHERE nid = :nid", array(':nid' => $node->nid), array('target' => 'slave'));
720 $output = array();
721 foreach ($result as $link) {
722 $output[] = $link->caption;
723 }
724 if (count($output)) {
725 return '<a>(' . implode(', ', $output) . ')</a>';
726 }
727 }
728
729 /**
730 * Implement hook_node_update().
731 */
732 function search_node_update(stdClass $node) {
733 // Reindex the node when it is updated. The node is automatically indexed
734 // when it is added, simply by being added to the node table.
735 search_touch_node($node->nid);
736 }
737
738 /**
739 * Implement hook_comment_insert().
740 */
741 function search_comment_insert($comment) {
742 // Reindex the node when comments are added.
743 search_touch_node($comment->nid);
744 }
745
746 /**
747 * Implement hook_comment_update().
748 */
749 function search_comment_update($comment) {
750 // Reindex the node when comments are changed.
751 search_touch_node($comment->nid);
752 }
753
754 /**
755 * Implement hook_comment_delete().
756 */
757 function search_comment_delete($comment) {
758 // Reindex the node when comments are deleted.
759 search_touch_node($comment->nid);
760 }
761
762 /**
763 * Implement hook_comment_publish().
764 */
765 function search_comment_publish($comment) {
766 // Reindex the node when comments are published.
767 search_touch_node($comment->nid);
768 }
769
770 /**
771 * Implement hook_comment_unpublish().
772 */
773 function search_comment_unpublish($comment) {
774 // Reindex the node when comments are unpublished.
775 search_touch_node($comment->nid);
776 }
777
778 /**
779 * Extract a module-specific search option from a search query. e.g. 'type:book'
780 */
781 function search_expression_extract($keys, $option) {
782 if (preg_match('/(^| )' . $option . ':([^ ]*)( |$)/i', $keys, $matches)) {
783 return $matches[2];
784 }
785 }
786
787 /**
788 * Return a query with the given module-specific search option inserted in.
789 * e.g. 'type:book'.
790 */
791 function search_expression_insert($keys, $option, $value = '') {
792 if (search_expression_extract($keys, $option)) {
793 $keys = trim(preg_replace('/(^| )' . $option . ':[^ ]*/i', '', $keys));
794 }
795 if ($value != '') {
796 $keys .= ' ' . $option . ':' . $value;
797 }
798 return $keys;
799 }
800
801 /**
802 * Helper function for grabbing search keys.
803 */
804 function search_get_keys() {
805 static $return;
806 if (!isset($return)) {
807 // Extract keys as remainder of path
808 // Note: support old GET format of searches for existing links.
809 $path = explode('/', $_GET['q'], 3);
810 $keys = empty($_REQUEST['keys']) ? '' : $_REQUEST['keys'];
811 $return = count($path) == 3 ? $path[2] : $keys;
812 }
813 return $return;
814 }
815
816 /**
817 * @defgroup search Search interface
818 * @{
819 * The Drupal search interface manages a global search mechanism.
820 *
821 * Modules may plug into this system to provide searches of different types of
822 * data. Most of the system is handled by search.module, so this must be enabled
823 * for all of the search features to work.
824 *
825 * There are three ways to interact with the search system:
826 * - Specifically for searching nodes, you can implement hook_node_update_index()
827 * and hook_node_search_result(). However, note that the search system already
828 * indexes all visible output of a node, i.e. everything displayed normally
829 * by hook_view() and hook_node_view(). This is usually sufficient. You should
830 * only use this mechanism if you want additional, non-visible data to be
831 * indexed.
832 * - Implement hook_search(). This will create a search tab for your module on
833 * the /search page with a simple keyword search form.
834 * - Implement hook_update_index(). This allows your module to use Drupal's
835 * HTML indexing mechanism for searching full text efficiently.
836 *
837 * If your module needs to provide a more complicated search form, then you need
838 * to implement it yourself without hook_search(). In that case, you should
839 * define it as a local task (tab) under the /search page (e.g. /search/mymodule)
840 * so that users can easily find it.
841 */
842
843 /**
844 * Render a search form.
845 *
846 * @param $action
847 * Form action. Defaults to "search".
848 * @param $keys
849 * The search string entered by the user, containing keywords for the search.
850 * @param $type
851 * The type of search to render the node for. Must be the name of module
852 * which implements hook_search(). Defaults to 'node'.
853 * @param $prompt
854 * A piece of text to put before the form (e.g. "Enter your keywords")
855 * @return
856 * An HTML string containing the search form.
857 */
858 function search_form($form, &$form_state, $action = '', $keys = '', $type = NULL, $prompt = NULL) {
859 // Add CSS
860 drupal_add_css(drupal_get_path('module', 'search') . '/search.css', array('preprocess' => FALSE));
861
862 if (!$action) {
863 $action = url('search/' . $type);
864 }
865 if (is_null($prompt)) {
866 $prompt = t('Enter your keywords');
867 }
868
869 $form['#action'] = $action;
870 $form['#attributes']['class'][] = 'search-form';
871 $form['module'] = array('#type' => 'value', '#value' => $type);
872 $form['basic'] = array('#type' => 'item', '#title' => $prompt, '#id' => 'edit-keys');
873 $form['basic']['inline'] = array('#prefix' => '<div class="container-inline">', '#suffix' => '</div>');
874 $form['basic']['inline']['keys'] = array(
875 '#type' => 'textfield',
876 '#title' => '',
877 '#default_value' => $keys,
878 '#size' => $prompt ? 40 : 20,
879 '#maxlength' => 255,
880 );
881 // processed_keys is used to coordinate keyword passing between other forms
882 // that hook into the basic search form.
883 $form['basic']['inline']['processed_keys'] = array('#type' => 'value', '#value' => array());
884 $form['basic']['inline']['submit'] = array('#type' => 'submit', '#value' => t('Search'));
885
886 return $form;
887 }
888
889 /**
890 * Form builder; Output a search form for the search block's search box.
891 *
892 * @ingroup forms
893 * @see search_box_form_submit()
894 * @see search-theme-form.tpl.php
895 * @see search-block-form.tpl.php
896 */
897 function search_box($form, &$form_state, $form_id) {
898 $form[$form_id] = array(
899 '#type' => 'textfield',
900 '#size' => 15,
901 '#default_value' => '',
902 '#attributes' => array('title' => t('Enter the terms you wish to search for.')),
903 );
904 $form['submit'] = array('#type' => 'submit', '#value' => t('Search'));
905 $form['#submit'][] = 'search_box_form_submit';
906
907 return $form;
908 }
909
910 /**
911 * Process a block search form submission.
912 */
913 function search_box_form_submit($form, &$form_state) {
914 // The search form relies on control of the redirect destination for its
915 // functionality, so we override any static destination set in the request,
916 // for example by drupal_access_denied() or drupal_not_found()
917 // (see http://drupal.org/node/292565).
918 if (isset($_GET['destination'])) {
919 unset($_GET['destination']);
920 }
921
922 $form_id = $form['form_id']['#value'];
923 $form_state['redirect'] = 'search/node/' . trim($form_state['values'][$form_id]);
924 }
925
926 /**
927 * Process variables for search-block-form.tpl.php.
928 *
929 * The $variables array contains the following arguments:
930 * - $form
931 *
932 * @see search-block-form.tpl.php
933 */
934 function template_preprocess_search_block_form(&$variables) {
935 $variables['search'] = array();
936 $hidden = array();
937 // Provide variables named after form keys so themers can print each element independently.
938 foreach (element_children($variables['form']) as $key) {
939 $type = $variables['form'][$key]['#type'];
940 if ($type == 'hidden' || $type == 'token') {
941 $hidden[] = drupal_render($variables['form'][$key]);
942 }
943 else {
944 $variables['search'][$key] = drupal_render($variables['form'][$key]);
945 }
946 }
947 // Hidden form elements have no value to themers. No need for separation.
948 $variables['search']['hidden'] = implode($hidden);
949 // Collect all form elements to make it easier to print the whole form.
950 $variables['search_form'] = implode($variables['search']);
951 }
952
953 /**
954 * Perform a standard search on the given keys, and return the formatted results.
955 */
956 function search_data($keys = NULL, $type = 'node') {
957
958 if (isset($keys)) {
959 if (module_hook($type, 'search_execute')) {
960 $results = module_invoke($type, 'search_execute', $keys);
961 if (isset($results) && is_array($results) && count($results)) {
962 if (module_hook($type, 'search_page')) {
963 return module_invoke($type, 'search_page', $results);
964 }
965 else {
966 return theme('search_results', array('results' => $results, 'type' => $type));
967 }
968 }
969 }
970 }
971 }
972
973 /**
974 * Returns snippets from a piece of text, with certain keywords highlighted.
975 * Used for formatting search results.
976 *
977 * @param $keys
978 * A string containing a search query.
979 *
980 * @param $text
981 * The text to extract fragments from.
982 *
983 * @return
984 * A string containing HTML for the excerpt.
985 */
986 function search_excerpt($keys, $text) {
987 // We highlight around non-indexable or CJK characters.
988 $boundary = '(?:(?<=[' . PREG_CLASS_SEARCH_EXCLUDE . PREG_CLASS_CJK . '])|(?=[' . PREG_CLASS_SEARCH_EXCLUDE . PREG_CLASS_CJK . ']))';
989
990 // Extract positive keywords and phrases
991 preg_match_all('/ ("([^"]+)"|(?!OR)([^" ]+))/', ' ' . $keys, $matches);
992 $keys = array_merge($matches[2], $matches[3]);
993
994 // Prepare text
995 $text = ' ' . strip_tags(str_replace(array('<', '>'), array(' <', '> '), $text)) . ' ';
996 array_walk($keys, '_search_excerpt_replace');
997 $workkeys = $keys;
998
999 // Extract a fragment per keyword for at most 4 keywords.
1000 // First we collect ranges of text around each keyword, starting/ending
1001 // at spaces.
1002 // If the sum of all fragments is too short, we look for second occurrences.
1003 $ranges = array();
1004 $included = array();
1005 $length = 0;
1006 while ($length < 256 && count($workkeys)) {
1007 foreach ($workkeys as $k => $key) {
1008 if (strlen($key) == 0) {
1009 unset($workkeys[$k]);
1010 unset($keys[$k]);
1011 continue;
1012 }
1013 if ($length >= 256) {
1014 break;
1015 }
1016 // Remember occurrence of key so we can skip over it if more occurrences
1017 // are desired.
1018 if (!isset($included[$key])) {
1019 $included[$key] = 0;
1020 }
1021 // Locate a keyword (position $p), then locate a space in front (position
1022 // $q) and behind it (position $s)
1023 if (preg_match('/' . $boundary . $key . $boundary . '/iu', $text, $match, PREG_OFFSET_CAPTURE, $included[$key])) {
1024 $p = $match[0][1];
1025 if (($q = strpos($text, ' ', max(0, $p - 60))) !== FALSE) {
1026 $end = substr($text, $p, 80);
1027 if (($s = strrpos($end, ' ')) !== FALSE) {
1028 $ranges[$q] = $p + $s;
1029 $length += $p + $s - $q;
1030 $included[$key] = $p + 1;
1031 }
1032 else {
1033 unset($workkeys[$k]);
1034 }
1035 }
1036 else {
1037 unset($workkeys[$k]);
1038 }
1039 }
1040 else {
1041 unset($workkeys[$k]);
1042 }
1043 }
1044 }
1045
1046 // If we didn't find anything, return the beginning.
1047 if (count($ranges) == 0) {
1048 return truncate_utf8($text, 256) . ' ...';
1049 }
1050
1051 // Sort the text ranges by starting position.
1052 ksort($ranges);
1053
1054 // Now we collapse overlapping text ranges into one. The sorting makes it O(n).
1055 $newranges = array();
1056 foreach ($ranges as $from2 => $to2) {
1057 if (!isset($from1)) {
1058 $from1 = $from2;
1059 $to1 = $to2;
1060 continue;
1061 }
1062 if ($from2 <= $to1) {
1063 $to1 = max($to1, $to2);
1064 }
1065 else {
1066 $newranges[$from1] = $to1;
1067 $from1 = $from2;
1068 $to1 = $to2;
1069 }
1070 }
1071 $newranges[$from1] = $to1;
1072
1073 // Fetch text
1074 $out = array();
1075 foreach ($newranges as $from => $to) {
1076 $out[] = substr($text, $from, $to - $from);
1077 }
1078 $text = (isset($newranges[0]) ? '' : '... ') . implode(' ... ', $out) . ' ...';
1079
1080 // Highlight keywords. Must be done at once to prevent conflicts ('strong' and '<strong>').
1081 $text = preg_replace('/' . $boundary . '(' . implode('|', $keys) . ')' . $boundary . '/iu', '<strong>\0</strong>', $text);
1082 return $text;
1083 }
1084
1085 /**
1086 * @} End of "defgroup search".
1087 */
1088
1089 /**
1090 * Helper function for array_walk in search_except.
1091 */
1092 function _search_excerpt_replace(&$text) {
1093 $text = preg_quote($text, '/');
1094 }
1095
1096 function search_forms() {
1097 $forms['search_block_form']= array(
1098 'callback' => 'search_box',
1099 'callback arguments' => array('search_block_form'),
1100 );
1101 return $forms;
1102 }

  ViewVC Help
Powered by ViewVC 1.1.2