Enable UTF-8 lower/upper case operations in SearchEngine,
[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 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 /**
27 * Entry point
28 *
29 * @param $par String: (default '')
30 */
31 function wfSpecialSearch( $par = '' ) {
32 global $wgRequest, $wgUser;
33
34 $search = $wgRequest->getText( 'search', $par );
35 $searchPage = new SpecialSearch( $wgRequest, $wgUser );
36 if( $wgRequest->getVal( 'fulltext' ) ||
37 !is_null( $wgRequest->getVal( 'offset' ) ) ||
38 !is_null ($wgRequest->getVal( 'searchx' ) ) ) {
39 $searchPage->showResults( $search );
40 } else {
41 $searchPage->goResult( $search );
42 }
43 }
44
45 /**
46 * @todo document
47 * @package MediaWiki
48 * @subpackage SpecialPage
49 */
50 class SpecialSearch {
51
52 /**
53 * Set up basic search parameters from the request and user settings.
54 * Typically you'll pass $wgRequest and $wgUser.
55 *
56 * @param WebRequest $request
57 * @param User $user
58 * @public
59 */
60 function SpecialSearch( &$request, &$user ) {
61 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
62
63 if( $request->getCheck( 'searchx' ) ) {
64 $this->namespaces = $this->powerSearch( $request );
65 } else {
66 $this->namespaces = $this->userNamespaces( $user );
67 }
68
69 $this->searchRedirects = $request->getcheck( 'redirs' ) ? true : false;
70 }
71
72 /**
73 * If an exact title match can be found, jump straight ahead to
74 * @param string $term
75 * @public
76 */
77 function goResult( $term ) {
78 global $wgOut;
79 global $wgGoToEdit;
80 global $wgContLang;
81
82 $this->setupPage( $term );
83
84 # Try to go to page as entered.
85 #
86 $t = Title::newFromText( $term );
87
88 # If the string cannot be used to create a title
89 if( is_null( $t ) ){
90 return $this->showResults( $term );
91 }
92
93 # If there's an exact or very near match, jump right there.
94 $t = SearchEngine::getNearMatch( $term );
95 if( !is_null( $t ) ) {
96 $wgOut->redirect( $t->getFullURL() );
97 return;
98 }
99
100 # if language supports variants, search in all variants
101 if(sizeof($wgContLang->getVariants())>1){
102 $allTermVariants = $wgContLang->convertLinkToAllVariants($term);
103
104 foreach($allTermVariants as $termVariant){
105 $t = SearchEngine::getNearMatch( $termVariant );
106 if( !is_null( $t ) ) {
107 $wgOut->redirect( $t->getFullURL() );
108 wfProfileOut( $fname );
109 return;
110 }
111 }
112 }
113
114 # No match, generate an edit URL
115 $t = Title::newFromText( $term );
116 if( is_null( $t ) ) {
117 $editurl = ''; # hrm...
118 } else {
119 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
120 # If the feature is enabled, go straight to the edit page
121 if ( $wgGoToEdit ) {
122 $wgOut->redirect( $t->getFullURL( 'action=edit' ) );
123 return;
124 } else {
125 $editurl = $t->escapeLocalURL( 'action=edit' );
126 }
127 }
128 $wgOut->addWikiText( wfMsg( 'noexactmatch', wfEscapeWikiText( $term ) ) );
129
130 return $this->showResults( $term );
131 }
132
133 /**
134 * @param string $term
135 * @public
136 */
137 function showResults( $term ) {
138 $fname = 'SpecialSearch::showResults';
139 wfProfileIn( $fname );
140
141 $this->setupPage( $term );
142
143 global $wgUser, $wgOut;
144 $sk = $wgUser->getSkin();
145 $wgOut->addWikiText( wfMsg( 'searchresulttext' ) );
146
147 #if ( !$this->parseQuery() ) {
148 if( '' === trim( $term ) ) {
149 $wgOut->setSubtitle( '' );
150 $wgOut->addHTML( $this->powerSearchBox( $term ) );
151 wfProfileOut( $fname );
152 return;
153 }
154
155 global $wgDisableTextSearch;
156 if ( $wgDisableTextSearch ) {
157 global $wgForwardSearchUrl;
158 if( $wgForwardSearchUrl ) {
159 $url = str_replace( '$1', urlencode( $term ), $wgForwardSearchUrl );
160 $wgOut->redirect( $url );
161 return;
162 }
163 global $wgInputEncoding;
164 $wgOut->addHTML( wfMsg( 'searchdisabled' ) );
165 $wgOut->addHTML(
166 wfMsg( 'googlesearch',
167 htmlspecialchars( $term ),
168 htmlspecialchars( $wgInputEncoding ),
169 htmlspecialchars( wfMsg( 'search' ) )
170 )
171 );
172 wfProfileOut( $fname );
173 return;
174 }
175
176 $search = SearchEngine::create();
177 $search->setLimitOffset( $this->limit, $this->offset );
178 $search->setNamespaces( $this->namespaces );
179 $search->showRedirects = $this->searchRedirects;
180 $titleMatches = $search->searchTitle( $term );
181 $textMatches = $search->searchText( $term );
182
183 $num = ( $titleMatches ? $titleMatches->numRows() : 0 )
184 + ( $textMatches ? $textMatches->numRows() : 0);
185 if ( $num >= $this->limit ) {
186 $top = wfShowingResults( $this->offset, $this->limit );
187 } else {
188 $top = wfShowingResultsNum( $this->offset, $this->limit, $num );
189 }
190 $wgOut->addHTML( "<p>{$top}</p>\n" );
191
192 if( $num || $this->offset ) {
193 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
194 'Special:Search',
195 wfArrayToCGI(
196 $this->powerSearchOptions(),
197 array( 'search' => $term ) ) );
198 $wgOut->addHTML( "<br />{$prevnext}\n" );
199 }
200
201 if( $titleMatches ) {
202 if( $titleMatches->numRows() ) {
203 $wgOut->addWikiText( '==' . wfMsg( 'titlematches' ) . "==\n" );
204 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
205 } else {
206 $wgOut->addWikiText( '==' . wfMsg( 'notitlematches' ) . "==\n" );
207 }
208 }
209
210 if( $textMatches ) {
211 if( $textMatches->numRows() ) {
212 $wgOut->addWikiText( '==' . wfMsg( 'textmatches' ) . "==\n" );
213 $wgOut->addHTML( $this->showMatches( $textMatches ) );
214 } elseif( $num == 0 ) {
215 # Don't show the 'no text matches' if we received title matches
216 $wgOut->addWikiText( '==' . wfMsg( 'notextmatches' ) . "==\n" );
217 }
218 }
219
220 if ( $num == 0 ) {
221 $wgOut->addWikiText( wfMsg( 'nonefound' ) );
222 }
223 if( $num || $this->offset ) {
224 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
225 }
226 $wgOut->addHTML( $this->powerSearchBox( $term ) );
227 wfProfileOut( $fname );
228 }
229
230 #------------------------------------------------------------------
231 # Private methods below this line
232
233 /**
234 *
235 */
236 function setupPage( $term ) {
237 global $wgOut;
238 $wgOut->setPageTitle( wfMsg( 'searchresults' ) );
239 $subtitlemsg = ( Title::newFromText($term) ? 'searchsubtitle' : 'searchsubtitleinvalid' );
240 $wgOut->setSubtitle( $wgOut->parse( wfMsg( $subtitlemsg, wfEscapeWikiText($term) ) ) );
241 $wgOut->setArticleRelated( false );
242 $wgOut->setRobotpolicy( 'noindex,nofollow' );
243 }
244
245 /**
246 * Extract default namespaces to search from the given user's
247 * settings, returning a list of index numbers.
248 *
249 * @param User $user
250 * @return array
251 * @private
252 */
253 function userNamespaces( &$user ) {
254 $arr = array();
255 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
256 if( $user->getOption( 'searchNs' . $ns ) ) {
257 $arr[] = $ns;
258 }
259 }
260 return $arr;
261 }
262
263 /**
264 * Extract "power search" namespace settings from the request object,
265 * returning a list of index numbers to search.
266 *
267 * @param WebRequest $request
268 * @return array
269 * @private
270 */
271 function powerSearch( &$request ) {
272 $arr = array();
273 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
274 if( $request->getCheck( 'ns' . $ns ) ) {
275 $arr[] = $ns;
276 }
277 }
278 return $arr;
279 }
280
281 /**
282 * Reconstruct the 'power search' options for links
283 * @return array
284 * @private
285 */
286 function powerSearchOptions() {
287 $opt = array();
288 foreach( $this->namespaces as $n ) {
289 $opt['ns' . $n] = 1;
290 }
291 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
292 $opt['searchx'] = 1;
293 return $opt;
294 }
295
296 /**
297 * @param SearchResultSet $matches
298 * @param string $terms partial regexp for highlighting terms
299 */
300 function showMatches( &$matches ) {
301 $fname = 'SpecialSearch::showMatches';
302 wfProfileIn( $fname );
303
304 global $wgContLang;
305 $tm = $wgContLang->convertForSearchResult( $matches->termMatches() );
306 $terms = implode( '|', $tm );
307
308 $off = $this->offset + 1;
309 $out = "<ol start='{$off}'>\n";
310
311 while( $result = $matches->next() ) {
312 $out .= $this->showHit( $result, $terms );
313 }
314 $out .= "</ol>\n";
315
316 // convert the whole thing to desired language variant
317 global $wgContLang;
318 $out = $wgContLang->convert( $out );
319 wfProfileOut( $fname );
320 return $out;
321 }
322
323 /**
324 * Format a single hit result
325 * @param SearchResult $result
326 * @param string $terms partial regexp for highlighting terms
327 */
328 function showHit( $result, $terms ) {
329 $fname = 'SpecialSearch::showHit';
330 wfProfileIn( $fname );
331 global $wgUser, $wgContLang, $wgLang;
332
333 $t = $result->getTitle();
334 if( is_null( $t ) ) {
335 wfProfileOut( $fname );
336 return "<!-- Broken link in search result -->\n";
337 }
338 $sk =& $wgUser->getSkin();
339
340 $contextlines = $wgUser->getOption( 'contextlines' );
341 if ( '' == $contextlines ) { $contextlines = 5; }
342 $contextchars = $wgUser->getOption( 'contextchars' );
343 if ( '' == $contextchars ) { $contextchars = 50; }
344
345 $link = $sk->makeKnownLinkObj( $t );
346 $revision = Revision::newFromTitle( $t );
347 $text = $revision->getText();
348 $size = wfMsgExt( 'nbytes', array( 'parsemag', 'escape'),
349 $wgLang->formatNum( strlen( $text ) ) );
350
351 $lines = explode( "\n", $text );
352
353 $max = intval( $contextchars ) + 1;
354 $pat1 = "/(.*)($terms)(.{0,$max})/i";
355
356 $lineno = 0;
357
358 $extract = '';
359 wfProfileIn( "$fname-extract" );
360 foreach ( $lines as $line ) {
361 if ( 0 == $contextlines ) {
362 break;
363 }
364 ++$lineno;
365 if ( ! preg_match( $pat1, $line, $m ) ) {
366 continue;
367 }
368 --$contextlines;
369 $pre = $wgContLang->truncate( $m[1], -$contextchars, '...' );
370
371 if ( count( $m ) < 3 ) {
372 $post = '';
373 } else {
374 $post = $wgContLang->truncate( $m[3], $contextchars, '...' );
375 }
376
377 $found = $m[2];
378
379 $line = htmlspecialchars( $pre . $found . $post );
380 $pat2 = '/(' . $terms . ")/i";
381 $line = preg_replace( $pat2,
382 "<span class='searchmatch'>\\1</span>", $line );
383
384 $extract .= "<br /><small>{$lineno}: {$line}</small>\n";
385 }
386 wfProfileOut( "$fname-extract" );
387 wfProfileOut( $fname );
388 return "<li>{$link} ({$size}){$extract}</li>\n";
389 }
390
391 function powerSearchBox( $term ) {
392 $namespaces = '';
393 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
394 $checked = in_array( $ns, $this->namespaces )
395 ? ' checked="checked"'
396 : '';
397 $name = str_replace( '_', ' ', $name );
398 if( '' == $name ) {
399 $name = wfMsg( 'blanknamespace' );
400 }
401 $namespaces .= " <label><input type='checkbox' value=\"1\" name=\"" .
402 "ns{$ns}\"{$checked} />{$name}</label>\n";
403 }
404
405 $checked = $this->searchRedirects
406 ? ' checked="checked"'
407 : '';
408 $redirect = "<input type='checkbox' value='1' name=\"redirs\"{$checked} />\n";
409
410 $searchField = '<input type="text" name="search" value="' .
411 htmlspecialchars( $term ) ."\" size=\"16\" />\n";
412
413 $searchButton = '<input type="submit" name="searchx" value="' .
414 htmlspecialchars( wfMsg('powersearch') ) . "\" />\n";
415
416 $ret = wfMsg( 'powersearchtext',
417 $namespaces, $redirect, $searchField,
418 '', '', '', '', '', # Dummy placeholders
419 $searchButton );
420
421 $title = Title::makeTitle( NS_SPECIAL, 'Search' );
422 $action = $title->escapeLocalURL();
423 return "<br /><br />\n<form id=\"powersearch\" method=\"get\" " .
424 "action=\"$action\">\n{$ret}\n</form>\n";
425 }
426 }
427
428 ?>