* (bug 9447) Added hooks for search result headings
[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 = str_replace( "\n", " ", $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 $this->namespaces = $this->powerSearch( $request );
62 if( empty( $this->namespaces ) ) {
63 $this->namespaces = $this->userNamespaces( $user );
64 }
65
66 $this->searchRedirects = $request->getcheck( 'redirs' ) ? true : false;
67 }
68
69 /**
70 * If an exact title match can be found, jump straight ahead to it.
71 * @param string $term
72 * @public
73 */
74 function goResult( $term ) {
75 global $wgOut;
76 global $wgGoToEdit;
77
78 $this->setupPage( $term );
79
80 # Try to go to page as entered.
81 $t = Title::newFromText( $term );
82
83 # If the string cannot be used to create a title
84 if( is_null( $t ) ){
85 return $this->showResults( $term );
86 }
87
88 # If there's an exact or very near match, jump right there.
89 $t = SearchEngine::getNearMatch( $term );
90 if( !is_null( $t ) ) {
91 $wgOut->redirect( $t->getFullURL() );
92 return;
93 }
94
95 # No match, generate an edit URL
96 $t = Title::newFromText( $term );
97 if( ! is_null( $t ) ) {
98 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
99 # If the feature is enabled, go straight to the edit page
100 if ( $wgGoToEdit ) {
101 $wgOut->redirect( $t->getFullURL( 'action=edit' ) );
102 return;
103 }
104 }
105 if( $t->quickUserCan( 'create' ) && $t->quickUserCan( 'edit' ) ) {
106 $wgOut->addWikiMsg( 'noexactmatch', wfEscapeWikiText( $term ) );
107 } else {
108 $wgOut->addWikiMsg( 'noexactmatch-nocreate', wfEscapeWikiText( $term ) );
109 }
110
111 return $this->showResults( $term );
112 }
113
114 /**
115 * @param string $term
116 * @public
117 */
118 function showResults( $term ) {
119 $fname = 'SpecialSearch::showResults';
120 wfProfileIn( $fname );
121
122 $this->setupPage( $term );
123
124 global $wgOut;
125 $wgOut->addWikiMsg( 'searchresulttext' );
126
127 if( '' === trim( $term ) ) {
128 // Empty query -- straight view of search form
129 $wgOut->setSubtitle( '' );
130 $wgOut->addHTML( $this->powerSearchBox( $term ) );
131 $wgOut->addHTML( $this->powerSearchFocus() );
132 wfProfileOut( $fname );
133 return;
134 }
135
136 global $wgDisableTextSearch;
137 if ( $wgDisableTextSearch ) {
138 global $wgForwardSearchUrl;
139 if( $wgForwardSearchUrl ) {
140 $url = str_replace( '$1', urlencode( $term ), $wgForwardSearchUrl );
141 $wgOut->redirect( $url );
142 return;
143 }
144 global $wgInputEncoding;
145 $wgOut->addHTML( wfMsg( 'searchdisabled' ) );
146 $wgOut->addHTML(
147 wfMsg( 'googlesearch',
148 htmlspecialchars( $term ),
149 htmlspecialchars( $wgInputEncoding ),
150 htmlspecialchars( wfMsg( 'searchbutton' ) )
151 )
152 );
153 wfProfileOut( $fname );
154 return;
155 }
156
157 $wgOut->addHTML( $this->shortDialog( $term ) );
158
159 $search = SearchEngine::create();
160 $search->setLimitOffset( $this->limit, $this->offset );
161 $search->setNamespaces( $this->namespaces );
162 $search->showRedirects = $this->searchRedirects;
163 $titleMatches = $search->searchTitle( $term );
164
165 // Sometimes the search engine knows there are too many hits
166 if ($titleMatches instanceof SearchResultTooMany) {
167 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
168 $wgOut->addHTML( $this->powerSearchBox( $term ) );
169 $wgOut->addHTML( $this->powerSearchFocus() );
170 wfProfileOut( $fname );
171 return;
172 }
173 $textMatches = $search->searchText( $term );
174
175 $num = ( $titleMatches ? $titleMatches->numRows() : 0 )
176 + ( $textMatches ? $textMatches->numRows() : 0);
177 if ( $num > 0 ) {
178 if ( $num >= $this->limit ) {
179 $top = wfShowingResults( $this->offset, $this->limit );
180 } else {
181 $top = wfShowingResultsNum( $this->offset, $this->limit, $num );
182 }
183 $wgOut->addHTML( "<p>{$top}</p>\n" );
184 }
185
186 if( $num || $this->offset ) {
187 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
188 SpecialPage::getTitleFor( 'Search' ),
189 wfArrayToCGI(
190 $this->powerSearchOptions(),
191 array( 'search' => $term ) ),
192 ($num < $this->limit) );
193 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
194 wfRunHooks( 'SpecialSearchResults', array( $term, $titleMatches, $textMatches ) );
195 } else {
196 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
197 }
198
199 if( $titleMatches ) {
200 if( $titleMatches->numRows() ) {
201 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
202 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
203 } else {
204 $wgOut->wrapWikiMsg( "==$1==\n", 'notitlematches' );
205 }
206 $titleMatches->free();
207 }
208
209 if( $textMatches ) {
210 if( $textMatches->numRows() ) {
211 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
212 $wgOut->addHTML( $this->showMatches( $textMatches ) );
213 } elseif( $num == 0 ) {
214 # Don't show the 'no text matches' if we received title matches
215 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
216 }
217 $textMatches->free();
218 }
219
220 if ( $num == 0 ) {
221 $wgOut->addWikiMsg( '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 return $opt;
293 }
294
295
296
297 /**
298 * @param SearchResultSet $matches
299 * @param string $terms partial regexp for highlighting terms
300 */
301 function showMatches( &$matches ) {
302 $fname = 'SpecialSearch::showMatches';
303 wfProfileIn( $fname );
304
305 global $wgContLang;
306 $tm = $wgContLang->convertForSearchResult( $matches->termMatches() );
307 $terms = implode( '|', $tm );
308
309 $off = $this->offset + 1;
310 $out = "<ul start='{$off}' class='mw-search-results'>\n";
311
312 while( $result = $matches->next() ) {
313 $out .= $this->showHit( $result, $terms );
314 }
315 $out .= "</ul>\n";
316
317 // convert the whole thing to desired language variant
318 global $wgContLang;
319 $out = $wgContLang->convert( $out );
320 wfProfileOut( $fname );
321 return $out;
322 }
323
324 /**
325 * Format a single hit result
326 * @param SearchResult $result
327 * @param string $terms partial regexp for highlighting terms
328 */
329 function showHit( $result, $terms ) {
330 $fname = 'SpecialSearch::showHit';
331 wfProfileIn( $fname );
332 global $wgUser, $wgContLang, $wgLang;
333
334 $t = $result->getTitle();
335 if( is_null( $t ) ) {
336 wfProfileOut( $fname );
337 return "<!-- Broken link in search result -->\n";
338 }
339 $sk = $wgUser->getSkin();
340
341 //$contextlines = $wgUser->getOption( 'contextlines', 5 );
342 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
343 $contextchars = $wgUser->getOption( 'contextchars', 50 );
344
345 $link = $sk->makeKnownLinkObj( $t );
346
347 //If page content is not readable, just return the title.
348 //This is not quite safe, but better than showing excerpts from non-readable pages
349 //Note that hiding the entry entirely would screw up paging.
350 if (!$t->userCanRead()) {
351 return "<li>{$link}</li>\n";
352 }
353
354 $revision = Revision::newFromTitle( $t );
355 // If the page doesn't *exist*... our search index is out of date.
356 // The least confusing at this point is to drop the result.
357 // You may get less results, but... oh well. :P
358 if( !$revision ) {
359 return "<!-- missing page " .
360 htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
361 }
362
363 $text = $revision->getText();
364 $size = wfMsgExt( 'search-result-size', array( 'parsemag', 'escape' ),
365 $sk->formatSize( strlen( $text ) ),
366 str_word_count( $text ) );
367 $date = $wgLang->timeanddate( $revision->getTimestamp() );
368
369 if( is_null( $result->getScore() ) ) {
370 // Search engine doesn't report scoring info
371 $score = '';
372 } else {
373 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
374 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
375 . ' - ';
376 }
377
378 $extract = $this->extractText( $text, $terms, $contextlines, $contextchars );
379
380 // Include a thumbnail for media files...
381 if( $t->getNamespace() == NS_IMAGE ) {
382 $img = wfFindFile( $t );
383 if( $img ) {
384 $thumb = $img->getThumbnail( 120, 120 );
385 if( $thumb ) {
386 $desc = $img->getShortDesc();
387 wfProfileOut( $fname );
388 // Ugly table. :D
389 // Float doesn't seem to interact well with the bullets.
390 // Table messes up vertical alignment of the bullet, but I'm
391 // not sure what more I can do about that. :(
392 return "<li>" .
393 '<table class="searchResultImage">' .
394 '<tr>' .
395 '<td width="120" align="center">' .
396 $thumb->toHtml( array( 'desc-link' => true ) ) .
397 '</td>' .
398 '<td valign="top">' .
399 $link .
400 $extract .
401 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}</div>" .
402 '</td>' .
403 '</tr>' .
404 '</table>' .
405 "</li>\n";
406 }
407 }
408 }
409
410 wfProfileOut( $fname );
411 return "<li>{$link} {$extract}\n" .
412 "<div class='mw-search-result-data'>{$score}{$size} - {$date}</div>" .
413 "</li>\n";
414
415 }
416
417 private function extractText( $text, $terms, $contextlines, $contextchars ) {
418 global $wgLang, $wgContLang;
419 $fname = __METHOD__;
420
421 $lines = explode( "\n", $text );
422
423 $max = intval( $contextchars ) + 1;
424 $pat1 = "/(.*)($terms)(.{0,$max})/i";
425
426 $lineno = 0;
427
428 $extract = "";
429 wfProfileIn( "$fname-extract" );
430 foreach ( $lines as $line ) {
431 if ( 0 == $contextlines ) {
432 break;
433 }
434 ++$lineno;
435 $m = array();
436 if ( ! preg_match( $pat1, $line, $m ) ) {
437 continue;
438 }
439 --$contextlines;
440 $pre = $wgContLang->truncate( $m[1], -$contextchars, '...' );
441
442 if ( count( $m ) < 3 ) {
443 $post = '';
444 } else {
445 $post = $wgContLang->truncate( $m[3], $contextchars, '...' );
446 }
447
448 $found = $m[2];
449
450 $line = htmlspecialchars( $pre . $found . $post );
451 $pat2 = '/(' . $terms . ")/i";
452 $line = preg_replace( $pat2,
453 "<span class='searchmatch'>\\1</span>", $line );
454
455 $extract .= "<br /><small>{$line}</small>\n";
456 }
457 wfProfileOut( "$fname-extract" );
458
459 return $extract;
460 }
461
462 /**
463 * Generates the power search box at bottom of [[Special:Search]]
464 * @param $term string: search term
465 * @return $out string: HTML form
466 */
467 function powerSearchBox( $term ) {
468 global $wgScript;
469
470 $namespaces = '';
471 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
472 $name = str_replace( '_', ' ', $name );
473 if( '' == $name ) {
474 $name = wfMsg( 'blanknamespace' );
475 }
476 $namespaces .= Xml::openElement( 'span', array( 'style' => 'white-space: nowrap' ) ) .
477 Xml::checkLabel( $name, "ns{$ns}", $name, in_array( $ns, $this->namespaces ) ) .
478 Xml::closeElement( 'span' ) . "\n";
479 }
480
481 $redirect = Xml::check( 'redirs', $this->searchRedirects, array( 'value' => '1' ) );
482 $searchField = Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'powerSearchText' ) );
483 $searchButton = Xml::submitButton( wfMsg( 'powersearch' ), array( 'name' => 'fulltext' ) ) . "\n";
484
485 $out = Xml::openElement( 'form', array( 'id' => 'powersearch', 'method' => 'get', 'action' => $wgScript ) ) .
486 Xml::openElement( 'fieldset' ) .
487 Xml::element( 'legend', array( ), wfMsg( 'powersearch-legend' ) ) .
488 Xml::hidden( 'title', 'Special:Search' ) .
489 wfMsgExt( 'powersearchtext', array( 'parse', 'replaceafter' ),
490 $namespaces, $redirect, $searchField,
491 '', '', '', '', '', # Dummy placeholders
492 $searchButton ) .
493 Xml::closeElement( 'fieldset' ) .
494 Xml::closeElement( 'form' );
495
496 return $out;
497 }
498
499 function powerSearchFocus() {
500 return "<script type='text/javascript'>" .
501 "document.getElementById('powerSearchText').focus();" .
502 "</script>";
503 }
504
505 function shortDialog($term) {
506 global $wgScript;
507
508 $out = Xml::openElement( 'form', array(
509 'id' => 'search',
510 'method' => 'get',
511 'action' => $wgScript
512 ));
513 $out .= Xml::hidden( 'title', 'Special:Search' );
514 $out .= Xml::input( 'search', 50, $term ) . ' ';
515 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
516 if( in_array( $ns, $this->namespaces ) ) {
517 $out .= Xml::hidden( "ns{$ns}", '1' );
518 }
519 }
520 $out .= Xml::submitButton( wfMsg( 'searchbutton' ), array( 'name' => 'fulltext' ) );
521 $out .= Xml::closeElement( 'form' );
522
523 return $out;
524 }
525 }