98852c4506555ef96a2629e78ec77abe665a1e7c
[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 $wgOut->addHTML( '<div id="searchHeader">' );
177
178 $num = ( $titleMatches ? $titleMatches->numRows() : 0 )
179 + ( $textMatches ? $textMatches->numRows() : 0);
180 if ( $num > 0 ) {
181 if ( $num >= $this->limit ) {
182 $top = wfShowingResults( $this->offset, $this->limit );
183 } else {
184 $top = wfShowingResultsNum( $this->offset, $this->limit, $num );
185 }
186 $wgOut->addHTML( "<p>{$top}</p>\n" );
187 }
188
189 if( $num || $this->offset ) {
190 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
191 SpecialPage::getTitleFor( 'Search' ),
192 wfArrayToCGI(
193 $this->powerSearchOptions(),
194 array( 'search' => $term ) ),
195 ($num < $this->limit) );
196 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
197 }
198
199 $wgOut->addHTML( "</div>\n" );
200
201 if( $titleMatches ) {
202 if( $titleMatches->numRows() ) {
203 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
204 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
205 } else {
206 $wgOut->wrapWikiMsg( "==$1==\n", 'notitlematches' );
207 }
208 $titleMatches->free();
209 }
210
211 if( $textMatches ) {
212 if( $textMatches->numRows() ) {
213 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
214 $wgOut->addHTML( $this->showMatches( $textMatches ) );
215 } elseif( $num == 0 ) {
216 # Don't show the 'no text matches' if we received title matches
217 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
218 }
219 $textMatches->free();
220 }
221
222 if ( $num == 0 ) {
223 $wgOut->addWikiMsg( 'nonefound' );
224 }
225 if( $num || $this->offset ) {
226 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
227 }
228 $wgOut->addHTML( $this->powerSearchBox( $term ) );
229 wfProfileOut( $fname );
230 }
231
232 #------------------------------------------------------------------
233 # Private methods below this line
234
235 /**
236 *
237 */
238 function setupPage( $term ) {
239 global $wgOut;
240 $wgOut->setPageTitle( wfMsg( 'searchresults' ) );
241 $subtitlemsg = ( Title::newFromText($term) ? 'searchsubtitle' : 'searchsubtitleinvalid' );
242 $wgOut->setSubtitle( $wgOut->parse( wfMsg( $subtitlemsg, wfEscapeWikiText($term) ) ) );
243 $wgOut->setArticleRelated( false );
244 $wgOut->setRobotpolicy( 'noindex,nofollow' );
245 }
246
247 /**
248 * Extract default namespaces to search from the given user's
249 * settings, returning a list of index numbers.
250 *
251 * @param User $user
252 * @return array
253 * @private
254 */
255 function userNamespaces( &$user ) {
256 $arr = array();
257 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
258 if( $user->getOption( 'searchNs' . $ns ) ) {
259 $arr[] = $ns;
260 }
261 }
262 return $arr;
263 }
264
265 /**
266 * Extract "power search" namespace settings from the request object,
267 * returning a list of index numbers to search.
268 *
269 * @param WebRequest $request
270 * @return array
271 * @private
272 */
273 function powerSearch( &$request ) {
274 $arr = array();
275 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
276 if( $request->getCheck( 'ns' . $ns ) ) {
277 $arr[] = $ns;
278 }
279 }
280 return $arr;
281 }
282
283 /**
284 * Reconstruct the 'power search' options for links
285 * @return array
286 * @private
287 */
288 function powerSearchOptions() {
289 $opt = array();
290 foreach( $this->namespaces as $n ) {
291 $opt['ns' . $n] = 1;
292 }
293 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
294 $opt['searchx'] = 1;
295 return $opt;
296 }
297
298
299
300 /**
301 * @param SearchResultSet $matches
302 * @param string $terms partial regexp for highlighting terms
303 */
304 function showMatches( &$matches ) {
305 $fname = 'SpecialSearch::showMatches';
306 wfProfileIn( $fname );
307
308 global $wgContLang;
309 $tm = $wgContLang->convertForSearchResult( $matches->termMatches() );
310 $terms = implode( '|', $tm );
311
312 $off = $this->offset + 1;
313 $out = "<ul start='{$off}' class='mw-search-results'>\n";
314
315 while( $result = $matches->next() ) {
316 $out .= $this->showHit( $result, $terms );
317 }
318 $out .= "</ul>\n";
319
320 // convert the whole thing to desired language variant
321 global $wgContLang;
322 $out = $wgContLang->convert( $out );
323 wfProfileOut( $fname );
324 return $out;
325 }
326
327 /**
328 * Format a single hit result
329 * @param SearchResult $result
330 * @param string $terms partial regexp for highlighting terms
331 */
332 function showHit( $result, $terms ) {
333 $fname = 'SpecialSearch::showHit';
334 wfProfileIn( $fname );
335 global $wgUser, $wgContLang, $wgLang;
336
337 $t = $result->getTitle();
338 if( is_null( $t ) ) {
339 wfProfileOut( $fname );
340 return "<!-- Broken link in search result -->\n";
341 }
342 $sk = $wgUser->getSkin();
343
344 //$contextlines = $wgUser->getOption( 'contextlines', 5 );
345 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
346 $contextchars = $wgUser->getOption( 'contextchars', 50 );
347
348 $link = $sk->makeKnownLinkObj( $t );
349
350 //If page content is not readable, just return the title.
351 //This is not quite safe, but better than showing excerpts from non-readable pages
352 //Note that hiding the entry entirely would screw up paging.
353 if (!$t->userCanRead()) {
354 return "<li>{$link}</li>\n";
355 }
356
357 $revision = Revision::newFromTitle( $t );
358 // If the page doesn't *exist*... our search index is out of date.
359 // The least confusing at this point is to drop the result.
360 // You may get less results, but... oh well. :P
361 if( !$revision ) {
362 return "<!-- missing page " .
363 htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
364 }
365
366 $text = $revision->getText();
367 $size = wfMsgExt( 'search-result-size', array( 'parsemag', 'escape' ),
368 $sk->formatSize( strlen( $text ) ),
369 str_word_count( $text ) );
370 $date = $wgLang->timeanddate( $revision->getTimestamp() );
371
372 if( is_null( $result->getScore() ) ) {
373 // Search engine doesn't report scoring info
374 $score = '';
375 } else {
376 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
377 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
378 . ' - ';
379 }
380
381 $extract = $this->extractText( $text, $terms, $contextlines, $contextchars );
382
383 // Include a thumbnail for media files...
384 if( $t->getNamespace() == NS_IMAGE ) {
385 $img = wfFindFile( $t );
386 if( $img ) {
387 $thumb = $img->getThumbnail( 120, 120 );
388 if( $thumb ) {
389 $desc = $img->getShortDesc();
390 wfProfileOut( $fname );
391 // Ugly table. :D
392 // Float doesn't seem to interact well with the bullets.
393 // Table messes up vertical alignment of the bullet, but I'm
394 // not sure what more I can do about that. :(
395 return "<li>" .
396 '<table class="searchResultImage">' .
397 '<tr>' .
398 '<td width="120" align="center">' .
399 $thumb->toHtml( array( 'desc-link' => true ) ) .
400 '</td>' .
401 '<td valign="top">' .
402 $link .
403 $extract .
404 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}</div>" .
405 '</td>' .
406 '</tr>' .
407 '</table>' .
408 "</li>\n";
409 }
410 }
411 }
412
413 wfProfileOut( $fname );
414 return "<li>{$link} {$extract}\n" .
415 "<div class='mw-search-result-data'>{$score}{$size} - {$date}</div>" .
416 "</li>\n";
417
418 }
419
420 private function extractText( $text, $terms, $contextlines, $contextchars ) {
421 global $wgLang, $wgContLang;
422 $fname = __METHOD__;
423
424 $lines = explode( "\n", $text );
425
426 $max = intval( $contextchars ) + 1;
427 $pat1 = "/(.*)($terms)(.{0,$max})/i";
428
429 $lineno = 0;
430
431 $extract = "";
432 wfProfileIn( "$fname-extract" );
433 foreach ( $lines as $line ) {
434 if ( 0 == $contextlines ) {
435 break;
436 }
437 ++$lineno;
438 $m = array();
439 if ( ! preg_match( $pat1, $line, $m ) ) {
440 continue;
441 }
442 --$contextlines;
443 $pre = $wgContLang->truncate( $m[1], -$contextchars, '...' );
444
445 if ( count( $m ) < 3 ) {
446 $post = '';
447 } else {
448 $post = $wgContLang->truncate( $m[3], $contextchars, '...' );
449 }
450
451 $found = $m[2];
452
453 $line = htmlspecialchars( $pre . $found . $post );
454 $pat2 = '/(' . $terms . ")/i";
455 $line = preg_replace( $pat2,
456 "<span class='searchmatch'>\\1</span>", $line );
457
458 $extract .= "<br /><small>{$line}</small>\n";
459 }
460 wfProfileOut( "$fname-extract" );
461
462 return $extract;
463 }
464
465 /**
466 * Generates the power search box at bottom of [[Special:Search]]
467 * @param $term string: search term
468 * @return $out string: HTML form
469 */
470 function powerSearchBox( $term ) {
471 global $wgScript;
472
473 $namespaces = '';
474 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
475 $name = str_replace( '_', ' ', $name );
476 if( '' == $name ) {
477 $name = wfMsg( 'blanknamespace' );
478 }
479 $namespaces .= Xml::openElement( 'span', array( 'style' => 'white-space: nowrap' ) ) .
480 Xml::checkLabel( $name, "ns{$ns}", $name, in_array( $ns, $this->namespaces ) ) .
481 Xml::closeElement( 'span' ) . "\n";
482 }
483
484 $redirect = Xml::check( 'redirs', $this->searchRedirects, array( 'value' => '1' ) );
485 $searchField = Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'powerSearchText' ) );
486 $searchButton = Xml::submitButton( wfMsg( 'powersearch' ), array( 'name' => 'searchx' ) ) . "\n";
487
488 $out = Xml::openElement( 'form', array( 'id' => 'powersearch', 'method' => 'get', 'action' => $wgScript ) ) .
489 Xml::openElement( 'fieldset' ) .
490 Xml::element( 'legend', array( ), wfMsg( 'searchbutton' ) ) .
491 Xml::hidden( 'title', 'Special:Search' ) .
492 wfMsgExt( 'powersearchtext', array( 'parse', 'replaceafter' ),
493 $namespaces, $redirect, $searchField,
494 '', '', '', '', '', # Dummy placeholders
495 $searchButton ) .
496 Xml::closeElement( 'fieldset' ) .
497 Xml::closeElement( 'form' );
498
499 return $out;
500 }
501
502 function powerSearchFocus() {
503 return "<script type='text/javascript'>" .
504 "document.getElementById('powerSearchText').focus();" .
505 "</script>";
506 }
507
508 function shortDialog($term) {
509 global $wgScript;
510
511 $form = Xml::hidden( 'title', 'Special:Search' );
512 $form .= Xml::input( 'search', 50, $term,
513 array( 'id' => 'searchBox' ) ).' ';
514 $form .= Xml::submitButton( wfMsg( 'searchbutton' ), array( 'name' => 'fulltext' ) );
515
516 $out = Xml::openElement( 'form', array(
517 'id' => 'search',
518 'method' => 'get',
519 'action' => $wgScript
520 ));
521 $out .= wfMsgExt( 'searchtext', array( 'parse', 'replaceafter' ), $form );
522 $out .= Xml::closeElement( 'form' );
523
524 return $out;
525 }
526 }