better support for multiple language variants when displaying the search result.
[lhc/web/wiklou.git] / includes / SpecialSearch.php
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 # http://www.gnu.org/copyleft/gpl.html
19
20 /**
21 * Run text & title search and display the output
22 * @package MediaWiki
23 * @subpackage SpecialPage
24 */
25
26 require_once( 'SearchEngine.php' );
27
28 function wfSpecialSearch( $par='' ) {
29 global $wgRequest, $wgUser;
30
31 $search = $wgRequest->getText( 'search', $par );
32 $searchPage = new SpecialSearch( $wgRequest, $wgUser );
33 if( $wgRequest->getVal( 'fulltext' ) ||
34 !is_null( $wgRequest->getVal( 'offset' ) ) ||
35 !is_null ($wgRequest->getVal( 'searchx' ) ) ) {
36 $searchPage->showResults( $search );
37 } else {
38 $searchPage->goResult( $search );
39 }
40 }
41
42
43 class SpecialSearch {
44 /**
45 * Set up basic search parameters from the request and user settings.
46 * Typically you'll pass $wgRequest and $wgUser.
47 *
48 * @param WebRequest $request
49 * @param User $user
50 * @access public
51 */
52 function SpecialSearch( &$request, &$user ) {
53 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
54
55 if( $request->getCheck( 'searchx' ) ) {
56 $this->namespaces = $this->powerSearch( $request );
57 } else {
58 $this->namespaces = $this->userNamespaces( $user );
59 }
60
61 $this->searchRedirects = false;
62 }
63
64 /**
65 * If an exact title match can be found, jump straight ahead to
66 * @param string $term
67 * @access public
68 */
69 function goResult( $term ) {
70 global $wgOut;
71 global $wgGoToEdit;
72
73 $this->setupPage( $term );
74
75 # Try to go to page as entered.
76 #
77 $t = Title::newFromText( $term );
78
79 # If the string cannot be used to create a title
80 if( is_null( $t ) ){
81 return $this->showResults( $term );
82 }
83
84 # If there's an exact or very near match, jump right there.
85 $t = SearchEngine::getNearMatch( $term );
86 if( !is_null( $t ) ) {
87 $wgOut->redirect( $t->getFullURL() );
88 return;
89 }
90
91 # No match, generate an edit URL
92 $t = Title::newFromText( $term );
93 if( is_null( $t ) ) {
94 $editurl = ''; # hrm...
95 } else {
96 # If the feature is enabled, go straight to the edit page
97 if ( $wgGoToEdit ) {
98 $wgOut->redirect( $t->getFullURL( 'action=edit' ) );
99 return;
100 } else {
101 $editurl = $t->escapeLocalURL( 'action=edit' );
102 }
103 }
104 # FIXME: HTML in wiki message
105 $wgOut->addHTML( '<p>' . wfMsg('nogomatch', $editurl, htmlspecialchars( $term ) ) . "</p>\n" );
106
107 return $this->showResults( $term );
108 }
109
110 /**
111 * @param string $term
112 * @access public
113 */
114 function showResults( $term ) {
115 $fname = 'SpecialSearch::showResults';
116 wfProfileIn( $fname );
117
118 $this->setupPage( $term );
119
120 global $wgUser, $wgOut;
121 $sk = $wgUser->getSkin();
122 $wgOut->addWikiText( wfMsg( 'searchresulttext' ) );
123
124 #if ( !$this->parseQuery() ) {
125 if( '' === trim( $term ) ) {
126 $wgOut->addWikiText(
127 '==' . wfMsg( 'badquery' ) . "==\n" .
128 wfMsg( 'badquerytext' ) );
129 wfProfileOut( $fname );
130 return;
131 }
132
133 global $wgDisableTextSearch;
134 if ( $wgDisableTextSearch ) {
135 global $wgInputEncoding;
136 $wgOut->addHTML( wfMsg( 'searchdisabled' ) );
137 $wgOut->addHTML( wfMsg( 'googlesearch',
138 htmlspecialchars( $term ),
139 htmlspecialchars( $wgInputEncoding ) ) );
140 wfProfileOut( $fname );
141 return;
142 }
143
144 $search =& $this->getSearchEngine();
145 $titleMatches = $search->searchTitle( $term );
146 $textMatches = $search->searchText( $term );
147
148 $num = $titleMatches->numRows() + $textMatches->numRows();
149 if ( $num >= $this->limit ) {
150 $top = wfShowingResults( $this->offset, $this->limit );
151 } else {
152 $top = wfShowingResultsNum( $this->offset, $this->limit, $num );
153 }
154 $wgOut->addHTML( "<p>{$top}</p>\n" );
155
156 if( $num || $this->offset ) {
157 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
158 'Special:Search',
159 wfArrayToCGI(
160 $this->powerSearchOptions(),
161 array( 'search' => $term ) ) );
162 $wgOut->addHTML( "<br />{$prevnext}\n" );
163 }
164
165 global $wgContLang;
166 $tm = $wgContLang->convertForSearchResult( $search->termMatches() );
167 $terms = implode( '|', $tm );
168
169 if( $titleMatches->numRows() ) {
170 $wgOut->addWikiText( '==' . wfMsg( 'titlematches' ) . "==\n" );
171 $wgOut->addHTML( $this->showMatches( $titleMatches, $terms ) );
172 } else {
173 $wgOut->addWikiText( '==' . wfMsg( 'notitlematches' ) . "==\n" );
174 }
175
176 if( $textMatches->numRows() ) {
177 $wgOut->addWikiText( '==' . wfMsg( 'textmatches' ) . "==\n" );
178 $wgOut->addHTML( $this->showMatches( $textMatches, $terms ) );
179 } elseif( $num == 0 ) {
180 # Don't show the 'no text matches' if we received title matches
181 $wgOut->addWikiText( '==' . wfMsg( 'notextmatches' ) . "==\n" );
182 }
183
184 if ( $num == 0 ) {
185 $wgOut->addWikiText( wfMsg( 'nonefound' ) );
186 }
187 if( $num || $this->offset ) {
188 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
189 }
190 $wgOut->addHTML( $this->powerSearchBox( $term ) );
191 wfProfileOut( $fname );
192 }
193
194 #------------------------------------------------------------------
195 # Private methods below this line
196
197 /**
198 *
199 */
200 function setupPage( $term ) {
201 global $wgOut;
202 $wgOut->setPageTitle( wfMsg( 'searchresults' ) );
203 $wgOut->setSubtitle( wfMsg( 'searchquery', htmlspecialchars( $term ) ) );
204 $wgOut->setArticleRelated( false );
205 $wgOut->setRobotpolicy( 'noindex,nofollow' );
206 }
207
208 /**
209 * Load up the appropriate search engine class for the currently
210 * active database backend, and return a configured instance.
211 *
212 * @return SearchEngine
213 * @access private
214 */
215 function &getSearchEngine() {
216 global $wgDBtype, $wgDBmysql4, $wgSearchType;
217 if( $wgDBtype == 'mysql' ) {
218 if( $wgDBmysql4 ) {
219 $class = 'SearchMySQL4';
220 require_once( 'SearchMySQL4.php' );
221 } else {
222 $class = 'SearchMysql3';
223 require_once( 'SearchMySQL3.php' );
224 }
225 } else if ( $wgDBtype == 'PostgreSQL' ) {
226 $class = 'SearchTsearch2';
227 require_once( 'SearchTsearch2.php' );
228 } else {
229 $class = 'SearchEngineDummy';
230 }
231 $search = new $class( wfGetDB( DB_SLAVE ) );
232 $search->setLimitOffset( $this->limit, $this->offset );
233 $search->setNamespaces( $this->namespaces );
234 return $search;
235 }
236
237 /**
238 * Extract default namespaces to search from the given user's
239 * settings, returning a list of index numbers.
240 *
241 * @param User $user
242 * @return array
243 * @access private
244 */
245 function userNamespaces( &$user ) {
246 $arr = array();
247 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
248 if( $user->getOption( 'searchNs' . $ns ) ) {
249 $arr[] = $ns;
250 }
251 }
252 return $arr;
253 }
254
255 /**
256 * Extract "power search" namespace settings from the request object,
257 * returning a list of index numbers to search.
258 *
259 * @param WebRequest $request
260 * @return array
261 * @access private
262 */
263 function powerSearch( &$request ) {
264 $arr = array();
265 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
266 if( $request->getCheck( 'ns' . $ns ) ) {
267 $arr[] = $ns;
268 }
269 }
270 return $arr;
271 }
272
273 /**
274 * Reconstruct the 'power search' options for links
275 * @return array
276 * @access private
277 */
278 function powerSearchOptions() {
279 $opt = array();
280 foreach( $this->namespaces as $n ) {
281 $opt['ns' . $n] = 1;
282 }
283 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
284 $opt['searchx'] = 1;
285 return $opt;
286 }
287
288 /**
289 * @param ResultWrapper $matches
290 * @param string $terms partial regexp for highlighting terms
291 */
292 function showMatches( &$matches, $terms ) {
293 $fname = 'SpecialSearch::showMatches';
294 wfProfileIn( $fname );
295
296 global $wgOut;
297 $off = $this->offset + 1;
298 $out = "<ol start='{$off}'>\n";
299
300 while( $row = $matches->fetchObject() ) {
301 $out .= $this->showHit( $row, $terms );
302 }
303 $out .= "</ol>\n";
304
305 // convert the whole thing to desired language variant
306 global $wgContLang;
307 $out = $wgContLang->convert( $out );
308 wfProfileOut( $fname );
309 return $out;
310 }
311
312 /**
313 * Format a single hit result
314 * @param object $row
315 * @param string $terms partial regexp for highlighting terms
316 */
317 function showHit( $row, $terms ) {
318 $fname = 'SpecialSearch::showHit';
319 wfProfileIn( $fname );
320 global $wgUser, $wgContLang;
321
322 $t = Title::makeTitle( $row->cur_namespace, $row->cur_title );
323 if( is_null( $t ) ) {
324 wfProfileOut( $fname );
325 return "<!-- Broken link in search result -->\n";
326 }
327 $sk =& $wgUser->getSkin();
328
329 $contextlines = $wgUser->getOption( 'contextlines' );
330 if ( '' == $contextlines ) { $contextlines = 5; }
331 $contextchars = $wgUser->getOption( 'contextchars' );
332 if ( '' == $contextchars ) { $contextchars = 50; }
333
334 $link = $sk->makeKnownLinkObj( $t, '' );
335 $size = wfMsg( 'nbytes', strlen( $row->cur_text ) );
336
337 $lines = explode( "\n", $row->cur_text );
338
339 $max = IntVal( $contextchars ) + 1;
340 $pat1 = "/(.*)($terms)(.{0,$max})/i";
341
342 $lineno = 0;
343
344 $extract = '';
345 wfProfileIn( "$fname-extract" );
346 foreach ( $lines as $line ) {
347 if ( 0 == $contextlines ) {
348 break;
349 }
350 ++$lineno;
351 if ( ! preg_match( $pat1, $line, $m ) ) {
352 continue;
353 }
354 --$contextlines;
355 $pre = $wgContLang->truncate( $m[1], -$contextchars, '...' );
356
357 if ( count( $m ) < 3 ) {
358 $post = '';
359 } else {
360 $post = $wgContLang->truncate( $m[3], $contextchars, '...' );
361 }
362
363 $found = $m[2];
364
365 $line = htmlspecialchars( $pre . $found . $post );
366 $pat2 = '/(' . $terms . ")/i";
367 $line = preg_replace( $pat2,
368 "<span class='searchmatch'>\\1</span>", $line );
369
370 $extract .= "<br /><small>{$lineno}: {$line}</small>\n";
371 }
372 wfProfileOut( "$fname-extract" );
373 wfProfileOut( $fname );
374 return "<li>{$link} ({$size}){$extract}</li>\n";
375 }
376
377 function powerSearchBox( $term ) {
378 $namespaces = '';
379 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
380 $checked = in_array( $ns, $this->namespaces )
381 ? ' checked="checked"'
382 : '';
383 $name = str_replace( '_', ' ', $name );
384 if( '' == $name ) {
385 $name = wfMsg( 'blanknamespace' );
386 }
387 $namespaces .= " <label><input type='checkbox' value=\"1\" name=\"" .
388 "ns{$ns}\"{$checked} />{$name}</label>\n";
389 }
390
391 $checked = $this->searchRedirects
392 ? ' checked="checked"'
393 : '';
394 $redirect = "<input type='checkbox' value='1' name=\"redirs\"{$checked} />\n";
395
396 $searchField = "<input type='text' name=\"search\" value=\"" .
397 htmlspecialchars( $term ) ."\" width=\"80\" />\n";
398
399 $searchButton = '<input type="submit" name="searchx" value="' .
400 htmlspecialchars( wfMsg('powersearch') ) . "\" />\n";
401
402 $ret = wfMsg( 'powersearchtext',
403 $namespaces, $redirect, $searchField,
404 '', '', '', '', '', # Dummy placeholders
405 $searchButton );
406
407 $title = Title::makeTitle( NS_SPECIAL, 'Search' );
408 $action = $title->escapeLocalURL();
409 return "<br /><br />\n<form id=\"powersearch\" method=\"get\" " .
410 "action=\"$action\">\n{$ret}\n</form>\n";
411 }
412 }
413
414 ?>