f040c07270c68696433031b728f4ed574ddabbe4
[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 * @addtogroup SpecialPage
23 */
24
25 /**
26 * Entry point
27 *
28 * @param $par String: (default '')
29 */
30 function wfSpecialSearch( $par = '' ) {
31 global $wgRequest, $wgUser;
32
33 $search = $wgRequest->getText( 'search', $par );
34 $searchPage = new SpecialSearch( $wgRequest, $wgUser );
35 if( $wgRequest->getVal( 'fulltext' ) ||
36 !is_null( $wgRequest->getVal( 'offset' ) ) ||
37 !is_null ($wgRequest->getVal( 'searchx' ) ) ) {
38 $searchPage->showResults( $search );
39 } else {
40 $searchPage->goResult( $search );
41 }
42 }
43
44 /**
45 * implements Special:Search - Run text & title search and display the output
46 * @addtogroup SpecialPage
47 */
48 class SpecialSearch {
49
50 /**
51 * Set up basic search parameters from the request and user settings.
52 * Typically you'll pass $wgRequest and $wgUser.
53 *
54 * @param WebRequest $request
55 * @param User $user
56 * @public
57 */
58 function SpecialSearch( &$request, &$user ) {
59 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
60
61 if( $request->getCheck( 'searchx' ) ) {
62 $this->namespaces = $this->powerSearch( $request );
63 } else {
64 $this->namespaces = $this->userNamespaces( $user );
65 }
66
67 $this->searchRedirects = $request->getcheck( 'redirs' ) ? true : false;
68 }
69
70 /**
71 * If an exact title match can be found, jump straight ahead to it.
72 * @param string $term
73 * @public
74 */
75 function goResult( $term ) {
76 global $wgOut;
77 global $wgGoToEdit;
78
79 $this->setupPage( $term );
80
81 # Try to go to page as entered.
82 $t = Title::newFromText( $term );
83
84 # If the string cannot be used to create a title
85 if( is_null( $t ) ){
86 return $this->showResults( $term );
87 }
88
89 # If there's an exact or very near match, jump right there.
90 $t = SearchEngine::getNearMatch( $term );
91 if( !is_null( $t ) ) {
92 $wgOut->redirect( $t->getFullURL() );
93 return;
94 }
95
96 # No match, generate an edit URL
97 $t = Title::newFromText( $term );
98 if( ! is_null( $t ) ) {
99 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
100 # If the feature is enabled, go straight to the edit page
101 if ( $wgGoToEdit ) {
102 $wgOut->redirect( $t->getFullURL( 'action=edit' ) );
103 return;
104 }
105 }
106 if( $t->quickUserCan( 'create' ) && $t->quickUserCan( 'edit' ) ) {
107 $wgOut->addWikiMsg( 'noexactmatch', wfEscapeWikiText( $term ) );
108 } else {
109 $wgOut->addWikiMsg( 'noexactmatch-nocreate', wfEscapeWikiText( $term ) );
110 }
111
112 return $this->showResults( $term );
113 }
114
115 /**
116 * @param string $term
117 * @public
118 */
119 function showResults( $term ) {
120 $fname = 'SpecialSearch::showResults';
121 wfProfileIn( $fname );
122
123 $this->setupPage( $term );
124
125 global $wgOut;
126 $wgOut->addWikiMsg( 'searchresulttext' );
127
128 if( '' === trim( $term ) ) {
129 // Empty query -- straight view of search form
130 $wgOut->setSubtitle( '' );
131 $wgOut->addHTML( $this->powerSearchBox( $term ) );
132 $wgOut->addHTML( $this->powerSearchFocus() );
133 wfProfileOut( $fname );
134 return;
135 }
136
137 global $wgDisableTextSearch;
138 if ( $wgDisableTextSearch ) {
139 global $wgForwardSearchUrl;
140 if( $wgForwardSearchUrl ) {
141 $url = str_replace( '$1', urlencode( $term ), $wgForwardSearchUrl );
142 $wgOut->redirect( $url );
143 return;
144 }
145 global $wgInputEncoding;
146 $wgOut->addHTML( wfMsg( 'searchdisabled' ) );
147 $wgOut->addHTML(
148 wfMsg( 'googlesearch',
149 htmlspecialchars( $term ),
150 htmlspecialchars( $wgInputEncoding ),
151 htmlspecialchars( wfMsg( 'searchbutton' ) )
152 )
153 );
154 wfProfileOut( $fname );
155 return;
156 }
157
158 $wgOut->addHTML( $this->shortDialog( $term ) );
159
160 $search = SearchEngine::create();
161 $search->setLimitOffset( $this->limit, $this->offset );
162 $search->setNamespaces( $this->namespaces );
163 $search->showRedirects = $this->searchRedirects;
164 $titleMatches = $search->searchTitle( $term );
165
166 // Sometimes the search engine knows there are too many hits
167 if ($titleMatches instanceof SearchResultTooMany) {
168 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
169 $wgOut->addHTML( $this->powerSearchBox( $term ) );
170 $wgOut->addHTML( $this->powerSearchFocus() );
171 wfProfileOut( $fname );
172 return;
173 }
174 $textMatches = $search->searchText( $term );
175
176 $num = ( $titleMatches ? $titleMatches->numRows() : 0 )
177 + ( $textMatches ? $textMatches->numRows() : 0);
178 if ( $num > 0 ) {
179 if ( $num >= $this->limit ) {
180 $top = wfShowingResults( $this->offset, $this->limit );
181 } else {
182 $top = wfShowingResultsNum( $this->offset, $this->limit, $num );
183 }
184 $wgOut->addHTML( "<p>{$top}</p>\n" );
185 }
186
187 if( $num || $this->offset ) {
188 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
189 SpecialPage::getTitleFor( 'Search' ),
190 wfArrayToCGI(
191 $this->powerSearchOptions(),
192 array( 'search' => $term ) ),
193 ($num < $this->limit) );
194 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
195 }
196
197 if( $titleMatches ) {
198 if( $titleMatches->numRows() ) {
199 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
200 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
201 } else {
202 $wgOut->wrapWikiMsg( "==$1==\n", 'notitlematches' );
203 }
204 $titleMatches->free();
205 }
206
207 if( $textMatches ) {
208 if( $textMatches->numRows() ) {
209 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
210 $wgOut->addHTML( $this->showMatches( $textMatches ) );
211 } elseif( $num == 0 ) {
212 # Don't show the 'no text matches' if we received title matches
213 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
214 }
215 $textMatches->free();
216 }
217
218 if ( $num == 0 ) {
219 $wgOut->addWikiMsg( 'nonefound' );
220 }
221 if( $num || $this->offset ) {
222 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
223 }
224 $wgOut->addHTML( $this->powerSearchBox( $term ) );
225 wfProfileOut( $fname );
226 }
227
228 #------------------------------------------------------------------
229 # Private methods below this line
230
231 /**
232 *
233 */
234 function setupPage( $term ) {
235 global $wgOut;
236 $wgOut->setPageTitle( wfMsg( 'searchresults' ) );
237 $subtitlemsg = ( Title::newFromText($term) ? 'searchsubtitle' : 'searchsubtitleinvalid' );
238 $wgOut->setSubtitle( $wgOut->parse( wfMsg( $subtitlemsg, wfEscapeWikiText($term) ) ) );
239 $wgOut->setArticleRelated( false );
240 $wgOut->setRobotpolicy( 'noindex,nofollow' );
241 }
242
243 /**
244 * Extract default namespaces to search from the given user's
245 * settings, returning a list of index numbers.
246 *
247 * @param User $user
248 * @return array
249 * @private
250 */
251 function userNamespaces( &$user ) {
252 $arr = array();
253 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
254 if( $user->getOption( 'searchNs' . $ns ) ) {
255 $arr[] = $ns;
256 }
257 }
258 return $arr;
259 }
260
261 /**
262 * Extract "power search" namespace settings from the request object,
263 * returning a list of index numbers to search.
264 *
265 * @param WebRequest $request
266 * @return array
267 * @private
268 */
269 function powerSearch( &$request ) {
270 $arr = array();
271 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
272 if( $request->getCheck( 'ns' . $ns ) ) {
273 $arr[] = $ns;
274 }
275 }
276 return $arr;
277 }
278
279 /**
280 * Reconstruct the 'power search' options for links
281 * @return array
282 * @private
283 */
284 function powerSearchOptions() {
285 $opt = array();
286 foreach( $this->namespaces as $n ) {
287 $opt['ns' . $n] = 1;
288 }
289 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
290 $opt['searchx'] = 1;
291 return $opt;
292 }
293
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 = "<ul start='{$off}' class='mw-search-results'>\n";
310
311 while( $result = $matches->next() ) {
312 $out .= $this->showHit( $result, $terms );
313 }
314 $out .= "</ul>\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', 5 );
341 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
342 $contextchars = $wgUser->getOption( 'contextchars', 50 );
343
344 $link = $sk->makeKnownLinkObj( $t );
345
346 //If page content is not readable, just return the title.
347 //This is not quite safe, but better than showing excerpts from non-readable pages
348 //Note that hiding the entry entirely would screw up paging.
349 if (!$t->userCanRead()) {
350 return "<li>{$link}</li>\n";
351 }
352
353 $revision = Revision::newFromTitle( $t );
354 // If the page doesn't *exist*... our search index is out of date.
355 // The least confusing at this point is to drop the result.
356 // You may get less results, but... oh well. :P
357 if( !$revision ) {
358 return "<!-- missing page " .
359 htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
360 }
361
362 $text = $revision->getText();
363 $size = wfMsgExt( 'search-result-size', array( 'parsemag' ),
364 $sk->formatSize( strlen( $text ) ),
365 str_word_count( $text ) );
366 $date = $wgLang->timeanddate( $revision->getTimestamp() );
367
368 if( is_null( $result->getScore() ) ) {
369 // Search engine doesn't report scoring info
370 $score = '';
371 } else {
372 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
373 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
374 . ' - ';
375 }
376
377 $extract = $this->extractText( $text, $terms, $contextlines, $contextchars );
378
379 // Include a thumbnail for media files...
380 if( $t->getNamespace() == NS_IMAGE ) {
381 $img = wfFindFile( $t );
382 if( $img ) {
383 $thumb = $img->getThumbnail( 120, 120 );
384 if( $thumb ) {
385 $desc = $img->getShortDesc();
386 wfProfileOut( $fname );
387 // Ugly table. :D
388 // Float doesn't seem to interact well with the bullets.
389 // Table messes up vertical alignment of the bullet, but I'm
390 // not sure what more I can do about that. :(
391 return "<li>" .
392 '<table class="searchResultImage">' .
393 '<tr>' .
394 '<td width="120" align="center">' .
395 $thumb->toHtml( array( 'desc-link' => true ) ) .
396 '</td>' .
397 '<td valign="top">' .
398 $link .
399 $extract .
400 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}</div>" .
401 '</td>' .
402 '</tr>' .
403 '</table>' .
404 "</li>\n";
405 }
406 }
407 }
408
409 wfProfileOut( $fname );
410 return "<li>{$link} {$extract}\n" .
411 "<div class='mw-search-result-data'>{$score}{$size} - {$date}</div>" .
412 "</li>\n";
413
414 }
415
416 private function extractText( $text, $terms, $contextlines, $contextchars ) {
417 global $wgLang, $wgContLang;
418 $fname = __METHOD__;
419
420 $lines = explode( "\n", $text );
421
422 $max = intval( $contextchars ) + 1;
423 $pat1 = "/(.*)($terms)(.{0,$max})/i";
424
425 $lineno = 0;
426
427 $extract = "";
428 wfProfileIn( "$fname-extract" );
429 foreach ( $lines as $line ) {
430 if ( 0 == $contextlines ) {
431 break;
432 }
433 ++$lineno;
434 $m = array();
435 if ( ! preg_match( $pat1, $line, $m ) ) {
436 continue;
437 }
438 --$contextlines;
439 $pre = $wgContLang->truncate( $m[1], -$contextchars, '...' );
440
441 if ( count( $m ) < 3 ) {
442 $post = '';
443 } else {
444 $post = $wgContLang->truncate( $m[3], $contextchars, '...' );
445 }
446
447 $found = $m[2];
448
449 $line = htmlspecialchars( $pre . $found . $post );
450 $pat2 = '/(' . $terms . ")/i";
451 $line = preg_replace( $pat2,
452 "<span class='searchmatch'>\\1</span>", $line );
453
454 $extract .= "<br /><small>{$line}</small>\n";
455 }
456 wfProfileOut( "$fname-extract" );
457
458 return $extract;
459 }
460
461 /**
462 * Generates the power search box at bottom of [[Special:Search]]
463 * @param $term string: search term
464 * @return $out string: HTML form
465 */
466 function powerSearchBox( $term ) {
467 global $wgScript;
468
469 $namespaces = '';
470 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
471 $name = str_replace( '_', ' ', $name );
472 if( '' == $name ) {
473 $name = wfMsg( 'blanknamespace' );
474 }
475 $namespaces .= Xml::openElement( 'span', array( 'style' => 'white-space: nowrap' ) ) .
476 Xml::checkLabel( $name, "ns{$ns}", $name, in_array( $ns, $this->namespaces ) ) .
477 Xml::closeElement( 'span' ) . "\n";
478 }
479
480 $redirect = Xml::check( 'redirs', $this->searchRedirects, array( 'value' => '1' ) );
481 $searchField = Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'powerSearchText' ) );
482 $searchButton = Xml::submitButton( wfMsg( 'powersearch' ), array( 'name' => 'searchx' ) ) . "\n";
483
484 $out = Xml::openElement( 'form', array( 'id' => 'powersearch', 'method' => 'get', 'action' => $wgScript ) ) .
485 Xml::openElement( 'fieldset' ) .
486 Xml::element( 'legend', array( ), wfMsg( 'powersearch' ) ) .
487 Xml::hidden( 'title', 'Special:Search' ) .
488 wfMsgExt( 'powersearchtext', array( 'parse', 'replaceafter' ),
489 $namespaces, $redirect, $searchField,
490 '', '', '', '', '', # Dummy placeholders
491 $searchButton ) .
492 Xml::closeElement( 'fieldset' ) .
493 Xml::closeElement( 'form' );
494
495 return $out;
496 }
497
498 function powerSearchFocus() {
499 return "<script type='text/javascript'>" .
500 "document.getElementById('powerSearchText').focus();" .
501 "</script>";
502 }
503
504 function shortDialog($term) {
505 global $wgScript;
506
507 $out = Xml::openElement( 'form', array(
508 'id' => 'search',
509 'method' => 'get',
510 'action' => $wgScript
511 ));
512 $out .= Xml::hidden( 'title', 'Special:Search' );
513 $out .= Xml::input( 'search', 50, $term ) . ' ';
514 $out .= Xml::submitButton( wfMsg( 'searchbutton' ), array( 'name' => 'fulltext' ) );
515 $out .= Xml::closeElement( 'form' );
516
517 return $out;
518 }
519 }
520
521