Follow-up to r51572. SpecialSearch.php was a bit broken, because methods like getTitl...
[lhc/web/wiklou.git] / includes / specials / 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 * @file
23 * @ingroup SpecialPage
24 */
25
26 /**
27 * Entry point
28 *
29 * @param $par String: (default '')
30 */
31 function wfSpecialSearch( $par = '' ) {
32 global $wgRequest, $wgUser, $wgUseOldSearchUI;
33 // Strip underscores from title parameter; most of the time we'll want
34 // text form here. But don't strip underscores from actual text params!
35 $titleParam = str_replace( '_', ' ', $par );
36 // Fetch the search term
37 $search = str_replace( "\n", " ", $wgRequest->getText( 'search', $titleParam ) );
38 $class = $wgUseOldSearchUI ? 'SpecialSearchOld' : 'SpecialSearch';
39 $searchPage = new $class( $wgRequest, $wgUser );
40 if( $wgRequest->getVal( 'fulltext' )
41 || !is_null( $wgRequest->getVal( 'offset' ))
42 || !is_null( $wgRequest->getVal( 'searchx' )) )
43 {
44 $searchPage->showResults( $search );
45 } else {
46 $searchPage->goResult( $search );
47 }
48 }
49
50 /**
51 * implements Special:Search - Run text & title search and display the output
52 * @ingroup SpecialPage
53 */
54 class SpecialSearch {
55
56 /**
57 * Set up basic search parameters from the request and user settings.
58 * Typically you'll pass $wgRequest and $wgUser.
59 *
60 * @param WebRequest $request
61 * @param User $user
62 * @public
63 */
64 function __construct( &$request, &$user ) {
65 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
66 $this->mPrefix = $request->getVal('prefix', '');
67 # Extract requested namespaces
68 $this->namespaces = $this->powerSearch( $request );
69 if( empty( $this->namespaces ) ) {
70 $this->namespaces = SearchEngine::userNamespaces( $user );
71 }
72 $this->searchRedirects = $request->getcheck( 'redirs' ) ? true : false;
73 $this->searchAdvanced = $request->getVal( 'advanced' );
74 $this->active = 'advanced';
75 $this->sk = $user->getSkin();
76 $this->didYouMeanHtml = ''; # html of did you mean... link
77 $this->fulltext = $request->getVal('fulltext');
78 }
79
80 /**
81 * If an exact title match can be found, jump straight ahead to it.
82 * @param string $term
83 */
84 public function goResult( $term ) {
85 global $wgOut;
86 $this->setupPage( $term );
87 # Try to go to page as entered.
88 $t = Title::newFromText( $term );
89 # If the string cannot be used to create a title
90 if( is_null( $t ) ) {
91 return $this->showResults( $term );
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 # No match, generate an edit URL
100 $t = Title::newFromText( $term );
101 if( !is_null( $t ) ) {
102 global $wgGoToEdit;
103 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
104 # If the feature is enabled, go straight to the edit page
105 if( $wgGoToEdit ) {
106 $wgOut->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
107 return;
108 }
109 }
110 return $this->showResults( $term );
111 }
112
113 /**
114 * @param string $term
115 */
116 public function showResults( $term ) {
117 global $wgOut, $wgUser, $wgDisableTextSearch, $wgContLang;
118 wfProfileIn( __METHOD__ );
119
120 $sk = $wgUser->getSkin();
121
122 $this->searchEngine = SearchEngine::create();
123 $search =& $this->searchEngine;
124 $search->setLimitOffset( $this->limit, $this->offset );
125 $search->setNamespaces( $this->namespaces );
126 $search->showRedirects = $this->searchRedirects;
127 $search->prefix = $this->mPrefix;
128 $term = $search->transformSearchTerm($term);
129
130 $this->setupPage( $term );
131
132 if( $wgDisableTextSearch ) {
133 global $wgSearchForwardUrl;
134 if( $wgSearchForwardUrl ) {
135 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
136 $wgOut->redirect( $url );
137 wfProfileOut( __METHOD__ );
138 return;
139 }
140 global $wgInputEncoding;
141 $wgOut->addHTML(
142 Xml::openElement( 'fieldset' ) .
143 Xml::element( 'legend', null, wfMsg( 'search-external' ) ) .
144 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
145 wfMsg( 'googlesearch',
146 htmlspecialchars( $term ),
147 htmlspecialchars( $wgInputEncoding ),
148 htmlspecialchars( wfMsg( 'searchbutton' ) )
149 ) .
150 Xml::closeElement( 'fieldset' )
151 );
152 wfProfileOut( __METHOD__ );
153 return;
154 }
155
156 $t = Title::newFromText( $term );
157
158 // fetch search results
159 $rewritten = $search->replacePrefixes($term);
160
161 $titleMatches = $search->searchTitle( $rewritten );
162 if( !($titleMatches instanceof SearchResultTooMany))
163 $textMatches = $search->searchText( $rewritten );
164
165 // did you mean... suggestions
166 if( $textMatches && $textMatches->hasSuggestion() ) {
167 $st = SpecialPage::getTitleFor( 'Search' );
168
169 # mirror Go/Search behaviour of original request ..
170 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
171
172 if($this->fulltext != NULL)
173 $didYouMeanParams['fulltext'] = $this->fulltext;
174
175 $stParams = array_merge(
176 $didYouMeanParams,
177 $this->powerSearchOptions()
178 );
179
180 $suggestionSnippet = $textMatches->getSuggestionSnippet();
181
182 if( $suggestionSnippet == '' )
183 $suggestionSnippet = null;
184
185 $suggestLink = $sk->linkKnown(
186 $st,
187 $suggestionSnippet,
188 array(),
189 $stParams
190 );
191
192 $this->didYouMeanHtml = '<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>';
193 }
194
195 // start rendering the page
196 $wgOut->addHtml(
197 Xml::openElement( 'table', array( 'border'=>0, 'cellpadding'=>0, 'cellspacing'=>0 ) ) .
198 Xml::openElement( 'tr' ) .
199 Xml::openElement( 'td' ) . "\n" .
200 ( $this->searchAdvanced ? $this->powerSearchBox( $term ) : $this->shortDialog( $term ) ) .
201 Xml::closeElement('td') .
202 Xml::closeElement('tr') .
203 Xml::closeElement('table')
204 );
205
206 // Sometimes the search engine knows there are too many hits
207 if( $titleMatches instanceof SearchResultTooMany ) {
208 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
209 wfProfileOut( __METHOD__ );
210 return;
211 }
212
213 $filePrefix = $wgContLang->getFormattedNsText(NS_FILE).':';
214 if( '' === trim( $term ) || $filePrefix === trim( $term ) ) {
215 $wgOut->addHTML( $this->searchAdvanced ? $this->powerSearchFocus() : $this->searchFocus() );
216 $wgOut->addHTML( $this->formHeader($term, 0, 0));
217 // Empty query -- straight view of search form
218 wfProfileOut( __METHOD__ );
219 return;
220 }
221
222
223 // Get number of results
224 $titleMatchesNum = $titleMatches ? $titleMatches->numRows() : 0;
225 $textMatchesNum = $textMatches ? $textMatches->numRows() : 0;
226 // Total initial query matches (possible false positives)
227 $num = $titleMatchesNum + $textMatchesNum;
228
229 // Get total actual results (after second filtering, if any)
230 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
231 $titleMatches->getTotalHits() : $titleMatchesNum;
232 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
233 $textMatches->getTotalHits() : $textMatchesNum;
234
235 // get total number of results if backend can calculate it
236 $totalRes = 0;
237 if($titleMatches && !is_null( $titleMatches->getTotalHits() ) )
238 $totalRes += $titleMatches->getTotalHits();
239 if($textMatches && !is_null( $textMatches->getTotalHits() ))
240 $totalRes += $textMatches->getTotalHits();
241
242 // show number of results and current offset
243 $wgOut->addHTML( $this->formHeader($term, $num, $totalRes));
244
245 $wgOut->addHtml( "<div class='searchresults'>" );
246
247 // show direct page/create link
248 if( !is_null($t) && ($this->active=='default' || $this->active=='all') ) {
249 if( !$t->exists() ) {
250 $wgOut->addWikiMsg( 'searchmenu-new', wfEscapeWikiText( $t->getPrefixedText() ) );
251 } else {
252 $wgOut->addWikiMsg( 'searchmenu-exists', wfEscapeWikiText( $t->getPrefixedText() ) );
253 }
254 }
255
256 // prev/next links
257 if( $num || $this->offset ) {
258 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
259 SpecialPage::getTitleFor( 'Search' ),
260 wfArrayToCGI( $this->powerSearchOptions(), array( 'search' => $term ) ),
261 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
262 );
263 //$wgOut->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
264 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
265 } else {
266 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
267 }
268
269
270 if( $titleMatches ) {
271 if( $numTitleMatches > 0 ) {
272 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
273 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
274 }
275 $titleMatches->free();
276 }
277 if( $textMatches ) {
278 // output appropriate heading
279 if( $numTextMatches > 0 && $numTitleMatches > 0 ) {
280 // if no title matches the heading is redundant
281 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
282 } elseif( $totalRes == 0 ) {
283 # Don't show the 'no text matches' if we received title matches
284 # $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
285 }
286 // show interwiki results if any
287 if( $textMatches->hasInterwikiResults() ) {
288 $wgOut->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
289 }
290 // show results
291 if( $numTextMatches > 0 ) {
292 $wgOut->addHTML( $this->showMatches( $textMatches ) );
293 }
294
295 $textMatches->free();
296 }
297 if( $num === 0 ) {
298 $wgOut->addWikiMsg( 'search-nonefound' );
299 }
300 $wgOut->addHtml( "</div>" );
301 if( $num === 0 ) {
302 $wgOut->addHTML( $this->searchAdvanced ? $this->powerSearchFocus() : $this->searchFocus() );
303 }
304
305 if( $num || $this->offset ) {
306 $wgOut->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
307 }
308 wfProfileOut( __METHOD__ );
309 }
310
311 /**
312 *
313 */
314 protected function setupPage( $term ) {
315 global $wgOut;
316 // Figure out the active search profile header
317 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
318 if( $this->searchAdvanced )
319 $this->active = 'advanced';
320 else if( $this->namespaces === array(NS_FILE) || $this->startsWithImage( $term ) )
321 $this->active = 'images';
322 elseif( $this->namespaces === $nsAllSet || $this->startsWithAll( $term ) )
323 $this->active = 'all';
324 elseif( $this->namespaces === SearchEngine::defaultNamespaces() )
325 $this->active = 'default';
326 elseif( $this->namespaces === SearchEngine::helpNamespaces() )
327 $this->active = 'help';
328 else
329 $this->active = 'advanced';
330 # Should advanced UI be used?
331 $this->searchAdvanced = ($this->active === 'advanced');
332 if( !empty( $term ) ) {
333 $wgOut->setPageTitle( wfMsg( 'searchresults') );
334 $wgOut->setHTMLTitle( wfMsg( 'pagetitle', wfMsg( 'searchresults-title', $term ) ) );
335 }
336 $wgOut->setArticleRelated( false );
337 $wgOut->setRobotPolicy( 'noindex,nofollow' );
338 // add javascript specific to special:search
339 $wgOut->addScriptFile( 'search.js' );
340 }
341
342 /**
343 * Extract "power search" namespace settings from the request object,
344 * returning a list of index numbers to search.
345 *
346 * @param WebRequest $request
347 * @return array
348 */
349 protected function powerSearch( &$request ) {
350 $arr = array();
351 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
352 if( $request->getCheck( 'ns' . $ns ) ) {
353 $arr[] = $ns;
354 }
355 }
356 return $arr;
357 }
358
359 /**
360 * Reconstruct the 'power search' options for links
361 * @return array
362 */
363 protected function powerSearchOptions() {
364 $opt = array();
365 foreach( $this->namespaces as $n ) {
366 $opt['ns' . $n] = 1;
367 }
368 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
369 if( $this->searchAdvanced ) {
370 $opt['advanced'] = $this->searchAdvanced;
371 }
372 return $opt;
373 }
374
375 /**
376 * Show whole set of results
377 *
378 * @param SearchResultSet $matches
379 */
380 protected function showMatches( &$matches ) {
381 global $wgContLang;
382 wfProfileIn( __METHOD__ );
383
384 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
385
386 $out = "";
387 $infoLine = $matches->getInfo();
388 if( !is_null($infoLine) ) {
389 $out .= "\n<!-- {$infoLine} -->\n";
390 }
391 $off = $this->offset + 1;
392 $out .= "<ul class='mw-search-results'>\n";
393 while( $result = $matches->next() ) {
394 $out .= $this->showHit( $result, $terms );
395 }
396 $out .= "</ul>\n";
397
398 // convert the whole thing to desired language variant
399 $out = $wgContLang->convert( $out );
400 wfProfileOut( __METHOD__ );
401 return $out;
402 }
403
404 /**
405 * Format a single hit result
406 * @param SearchResult $result
407 * @param array $terms terms to highlight
408 */
409 protected function showHit( $result, $terms ) {
410 global $wgContLang, $wgLang, $wgUser;
411 wfProfileIn( __METHOD__ );
412
413 if( $result->isBrokenTitle() ) {
414 wfProfileOut( __METHOD__ );
415 return "<!-- Broken link in search result -->\n";
416 }
417
418 $sk = $wgUser->getSkin();
419 $t = $result->getTitle();
420
421 $titleSnippet = $result->getTitleSnippet($terms);
422
423 if( $titleSnippet == '' )
424 $titleSnippet = null;
425
426 $link = $this->sk->linkKnown(
427 $t,
428 $titleSnippet
429 );
430
431 //If page content is not readable, just return the title.
432 //This is not quite safe, but better than showing excerpts from non-readable pages
433 //Note that hiding the entry entirely would screw up paging.
434 if( !$t->userCanRead() ) {
435 wfProfileOut( __METHOD__ );
436 return "<li>{$link}</li>\n";
437 }
438
439 // If the page doesn't *exist*... our search index is out of date.
440 // The least confusing at this point is to drop the result.
441 // You may get less results, but... oh well. :P
442 if( $result->isMissingRevision() ) {
443 wfProfileOut( __METHOD__ );
444 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
445 }
446
447 // format redirects / relevant sections
448 $redirectTitle = $result->getRedirectTitle();
449 $redirectText = $result->getRedirectSnippet($terms);
450 $sectionTitle = $result->getSectionTitle();
451 $sectionText = $result->getSectionSnippet($terms);
452 $redirect = '';
453
454 if( !is_null($redirectTitle) ) {
455 if( $redirectText == '' )
456 $redirectText = null;
457
458 $redirect = "<span class='searchalttitle'>" .
459 wfMsg(
460 'search-redirect',
461 $this->sk->linkKnown(
462 $redirectTitle,
463 $redirectText
464 )
465 ) .
466 "</span>";
467 }
468
469 $section = '';
470
471
472 if( !is_null($sectionTitle) ) {
473 if( $sectionText == '' )
474 $sectionText = null;
475
476 $section = "<span class='searchalttitle'>" .
477 wfMsg(
478 'search-section', $this->sk->linkKnown(
479 $sectionTitle,
480 $sectionText
481 )
482 ) .
483 "</span>";
484 }
485
486 // format text extract
487 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
488
489 // format score
490 if( is_null( $result->getScore() ) ) {
491 // Search engine doesn't report scoring info
492 $score = '';
493 } else {
494 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
495 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
496 . ' - ';
497 }
498
499 // format description
500 $byteSize = $result->getByteSize();
501 $wordCount = $result->getWordCount();
502 $timestamp = $result->getTimestamp();
503 $size = wfMsgExt(
504 'search-result-size',
505 array( 'parsemag', 'escape' ),
506 $this->sk->formatSize( $byteSize ),
507 $wordCount
508 );
509 $date = $wgLang->timeanddate( $timestamp );
510
511 // link to related articles if supported
512 $related = '';
513 if( $result->hasRelated() ) {
514 $st = SpecialPage::getTitleFor( 'Search' );
515 $stParams = array_merge(
516 $this->powerSearchOptions(),
517 array(
518 'search' => wfMsgForContent( 'searchrelated' ) . ':' . $t->getPrefixedText(),
519 'fulltext' => wfMsg( 'search' )
520 )
521 );
522
523 $related = ' -- ' . $sk->linkKnown(
524 $st,
525 wfMsg('search-relatedarticle'),
526 array(),
527 $stParams
528 );
529 }
530
531 // Include a thumbnail for media files...
532 if( $t->getNamespace() == NS_FILE ) {
533 $img = wfFindFile( $t );
534 if( $img ) {
535 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
536 if( $thumb ) {
537 $desc = $img->getShortDesc();
538 wfProfileOut( __METHOD__ );
539 // Float doesn't seem to interact well with the bullets.
540 // Table messes up vertical alignment of the bullets.
541 // Bullets are therefore disabled (didn't look great anyway).
542 return "<li>" .
543 '<table class="searchResultImage">' .
544 '<tr>' .
545 '<td width="120" align="center" valign="top">' .
546 $thumb->toHtml( array( 'desc-link' => true ) ) .
547 '</td>' .
548 '<td valign="top">' .
549 $link .
550 $extract .
551 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
552 '</td>' .
553 '</tr>' .
554 '</table>' .
555 "</li>\n";
556 }
557 }
558 }
559
560 wfProfileOut( __METHOD__ );
561 return "<li>{$link} {$redirect} {$section} {$extract}\n" .
562 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
563 "</li>\n";
564
565 }
566
567 /**
568 * Show results from other wikis
569 *
570 * @param SearchResultSet $matches
571 */
572 protected function showInterwiki( &$matches, $query ) {
573 global $wgContLang;
574 wfProfileIn( __METHOD__ );
575 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
576
577 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
578 wfMsg('search-interwiki-caption')."</div>\n";
579 $off = $this->offset + 1;
580 $out .= "<ul class='mw-search-iwresults'>\n";
581
582 // work out custom project captions
583 $customCaptions = array();
584 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
585 foreach($customLines as $line) {
586 $parts = explode(":",$line,2);
587 if(count($parts) == 2) // validate line
588 $customCaptions[$parts[0]] = $parts[1];
589 }
590
591 $prev = null;
592 while( $result = $matches->next() ) {
593 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
594 $prev = $result->getInterwikiPrefix();
595 }
596 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
597 $out .= "</ul></div>\n";
598
599 // convert the whole thing to desired language variant
600 $out = $wgContLang->convert( $out );
601 wfProfileOut( __METHOD__ );
602 return $out;
603 }
604
605 /**
606 * Show single interwiki link
607 *
608 * @param SearchResult $result
609 * @param string $lastInterwiki
610 * @param array $terms
611 * @param string $query
612 * @param array $customCaptions iw prefix -> caption
613 */
614 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
615 wfProfileIn( __METHOD__ );
616 global $wgContLang, $wgLang;
617
618 if( $result->isBrokenTitle() ) {
619 wfProfileOut( __METHOD__ );
620 return "<!-- Broken link in search result -->\n";
621 }
622
623 $t = $result->getTitle();
624
625 $titleSnippet = $result->getTitleSnippet($terms);
626
627 if( $titleSnippet == '' )
628 $titleSnippet = null;
629
630 $link = $this->sk->linkKnown(
631 $t,
632 $titleSnippet
633 );
634
635 // format redirect if any
636 $redirectTitle = $result->getRedirectTitle();
637 $redirectText = $result->getRedirectSnippet($terms);
638 $redirect = '';
639 if( !is_null($redirectTitle) ) {
640 if( $redirectText == '' )
641 $redirectText = null;
642
643 $redirect = "<span class='searchalttitle'>" .
644 wfMsg(
645 'search-redirect',
646 $this->sk->linkKnown(
647 $redirectTitle,
648 $redirectText
649 )
650 ) .
651 "</span>";
652 }
653
654 $out = "";
655 // display project name
656 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()) {
657 if( key_exists($t->getInterwiki(),$customCaptions) )
658 // captions from 'search-interwiki-custom'
659 $caption = $customCaptions[$t->getInterwiki()];
660 else{
661 // default is to show the hostname of the other wiki which might suck
662 // if there are many wikis on one hostname
663 $parsed = parse_url($t->getFullURL());
664 $caption = wfMsg('search-interwiki-default', $parsed['host']);
665 }
666 // "more results" link (special page stuff could be localized, but we might not know target lang)
667 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
668 $searchLink = $this->sk->linkKnown(
669 $searchTitle,
670 wfMsg('search-interwiki-more'),
671 array(),
672 array(
673 'search' => $query,
674 'fulltext' => 'Search'
675 )
676 );
677 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
678 {$searchLink}</span>{$caption}</div>\n<ul>";
679 }
680
681 $out .= "<li>{$link} {$redirect}</li>\n";
682 wfProfileOut( __METHOD__ );
683 return $out;
684 }
685
686
687 /**
688 * Generates the power search box at bottom of [[Special:Search]]
689 * @param $term string: search term
690 * @return $out string: HTML form
691 */
692 protected function powerSearchBox( $term ) {
693 global $wgScript;
694
695 $namespaces = SearchEngine::searchableNamespaces();
696
697 $tables = $this->namespaceTables( $namespaces );
698
699 // include redirects in the search
700 $redirect = Xml::check( 'redirs', $this->searchRedirects, array( 'value' => '1', 'id' => 'redirs' ) );
701 $redirectLabel = Xml::label( wfMsg( 'powersearch-redir' ), 'redirs' );
702
703 $redirectText = '';
704 // show redirects check only if backend supports it
705 if( $this->searchEngine->acceptListRedirects() ) {
706 $redirectText = $redirect . " " . $redirectLabel;
707 }
708
709
710 $searchField = Xml::inputLabel( wfMsg( 'powersearch-field' ), 'search', 'powerSearchText', 50, $term,
711 array( 'type' => 'text') );
712
713 // toggle for turning on and off all checkboxes
714 $selectOptionsLabel = Xml::label( wfMsg( 'powersearch-togglelabel' ), 'mw-search-togglelabel' );
715 $selectAllButton = Xml::openElement('input', array('type'=>'button', 'id' => 'mw-search-toggleall', 'onclick' => 'mwToggleSearchCheckboxes("all");',
716 'value' => wfMsg( 'powersearch-toggleall' ) )) . '</input>';
717
718 $selectNoneButton = Xml::openElement('input', array('type'=>'button', 'id' => 'mw-search-togglenone', 'onclick' => 'mwToggleSearchCheckboxes("none");',
719 'value' => wfMsg( 'powersearch-togglenone' ) )) . '</input>';
720
721 $selectOptionsText = "<td id='mw-search-togglebox' align='right'>" . $selectOptionsLabel . ' ' . $selectAllButton . $selectNoneButton . "</td>";
722
723 $searchButton = Xml::submitButton( wfMsg( 'powersearch' ) ) . "\n";
724 $searchTitle = SpecialPage::getTitleFor( 'Search' );
725
726 $topText = "<table id='mw-search-powertable'><tr><td>" . wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ). '</td>' . $selectOptionsText . "</tr></table>";
727
728 $out = Xml::openElement( 'form', array( 'id' => 'powersearch', 'method' => 'get', 'action' => $wgScript ) ) .
729 Xml::hidden( 'title', $searchTitle->getPrefixedText() ) . "\n" .
730 $topText .
731 '<input type="hidden" name="advanced" value="'.$this->searchAdvanced."\"/>\n".
732 $tables .
733 "<hr style=\"clear: both;\" />\n".
734 $redirectText . "\n".
735 "<div style=\"padding-top:4px;padding-bottom:2px;\">".
736 $searchField .
737 "&nbsp;" .
738 Xml::hidden( 'fulltext', 'Advanced search' ) . "\n" .
739 $searchButton .
740 "</div>".
741 "</form>";
742 return Xml::openElement( 'fieldset', array('id' => 'mw-searchoptions','style' => 'margin:0em;') ) .
743 Xml::element( 'legend', null, wfMsg('powersearch-legend') ) .
744 $out . $this->didYouMeanHtml .
745 Xml::closeElement( 'fieldset' );
746 }
747
748 protected function searchFocus() {
749 global $wgJsMimeType;
750 return "<script type=\"$wgJsMimeType\">" .
751 "hookEvent(\"load\", function() {" .
752 "document.getElementById('searchText').focus();" .
753 "});" .
754 "</script>";
755 }
756
757 protected function powerSearchFocus() {
758 global $wgJsMimeType;
759 return "<script type=\"$wgJsMimeType\">" .
760 "hookEvent(\"load\", function() {" .
761 "document.getElementById('powerSearchText').focus();" .
762 "});" .
763 "</script>";
764 }
765
766 protected function formHeader( $term, $resultsShown, $totalNum ) {
767 global $wgContLang, $wgCanonicalNamespaceNames, $wgLang;
768
769 $sep = '&nbsp;&nbsp;&nbsp;';
770 $out = Xml::openElement('div', array( 'class' => 'mw-search-formheader' ) );
771 $out .= Xml::openElement('div');
772
773 $bareterm = $term;
774 if( $this->startsWithImage( $term ) )
775 $bareterm = substr( $term, strpos( $term, ':' ) + 1 ); // delete all/image prefix
776
777 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
778
779 // search profiles headers
780 $m = wfMsg( 'searchprofile-articles' );
781 $tt = wfMsg( 'searchprofile-articles-tooltip',
782 $wgLang->commaList( SearchEngine::namespacesAsText( SearchEngine::defaultNamespaces() ) ) );
783 if( $this->active == 'default' ) {
784 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
785 } else {
786 $out .= $this->makeSearchLink( $bareterm, SearchEngine::defaultNamespaces(), $m, $tt);
787 }
788 $out .= $sep;
789
790 $m = wfMsg( 'searchprofile-images' );
791 $tt = wfMsg( 'searchprofile-images-tooltip' );
792 if( $this->active == 'images' ) {
793 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
794 } else {
795 $out .= $this->makeSearchLink( $bareterm, array( NS_FILE ) , $m, $tt );
796 }
797 $out .= $sep;
798
799 $m = wfMsg( 'searchprofile-project' );
800 $tt = wfMsg( 'searchprofile-project-tooltip',
801 $wgLang->commaList( SearchEngine::namespacesAsText( SearchEngine::helpNamespaces() ) ) );
802 if( $this->active == 'help' ) {
803 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
804 } else {
805 $out .= $this->makeSearchLink( $bareterm, SearchEngine::helpNamespaces(), $m, $tt );
806 }
807 $out .= $sep;
808
809 $m = wfMsg( 'searchprofile-everything' );
810 $tt = wfMsg( 'searchprofile-everything-tooltip' );
811 if( $this->active == 'all' ) {
812 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
813 } else {
814 $out .= $this->makeSearchLink( $bareterm, $nsAllSet, $m, $tt );
815 }
816 $out .= $sep;
817
818 $m = wfMsg( 'searchprofile-advanced' );
819 $tt = wfMsg( 'searchprofile-advanced-tooltip' );
820 if( $this->active == 'advanced' ) {
821 $out .= Xml::element( 'strong', array( 'title'=>$tt ), $m );
822 } else {
823 $out .= $this->makeSearchLink( $bareterm, $this->namespaces, $m, $tt, array( 'advanced' => '1' ) );
824 }
825 $out .= Xml::closeElement('div') ;
826
827 if ( $resultsShown > 0 ) {
828 if ( $totalNum > 0 ){
829 $top = wfMsgExt('showingresultsheader', array( 'parseinline' ),
830 $this->offset+1, $this->offset+$resultsShown, $totalNum, $term, $resultsShown );
831 } elseif ( $resultsShown >= $this->limit ) {
832 $top = wfShowingResults( $this->offset, $this->limit );
833 } else {
834 $top = wfShowingResultsNum( $this->offset, $this->limit, $resultsShown );
835 }
836 $out .= "<p>{$top}</p>\n";
837 } else
838 $out .= "<p>&nbsp;</p>\n";
839
840 $out .= Xml::closeElement('div') ;
841
842 return $out;
843 }
844
845 protected function shortDialog( $term ) {
846 global $wgScript;
847 $searchTitle = SpecialPage::getTitleFor( 'Search' );
848 $searchable = SearchEngine::searchableNamespaces();
849 $out = Xml::openElement( 'form', array( 'id' => 'search', 'method' => 'get', 'action' => $wgScript ) );
850 $out .= Xml::hidden( 'title', $searchTitle->getPrefixedText() ) . "\n";
851 // show namespaces only for advanced search
852 if( $this->active == 'advanced' ) {
853 $active = array();
854 foreach( $this->namespaces as $ns ) {
855 $active[$ns] = $searchable[$ns];
856 }
857 $out .= wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) . "<br/>\n";
858 $out .= $this->namespaceTables( $active, 1 )."<br/>\n";
859 // Still keep namespace settings otherwise, but don't show them
860 } else {
861 foreach( $this->namespaces as $ns ) {
862 $out .= Xml::hidden( "ns{$ns}", '1' );
863 }
864 }
865 // Keep redirect setting
866 $out .= Xml::hidden( "redirs", (int)$this->searchRedirects );
867 // Term box
868 $out .= Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'searchText' ) ) . "\n";
869 $out .= Xml::hidden( 'fulltext', 'Search' );
870 $out .= Xml::submitButton( wfMsg( 'searchbutton' ) );
871 $out .= Xml::closeElement( 'form' );
872 return $out . $this->didYouMeanHtml;
873 }
874
875 /** Make a search link with some target namespaces */
876 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params=array() ) {
877 $opt = $params;
878 foreach( $namespaces as $n ) {
879 $opt['ns' . $n] = 1;
880 }
881 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
882
883 $st = SpecialPage::getTitleFor( 'Search' );
884 $stParams = array_merge(
885 array(
886 'search' => $term,
887 'fulltext' => wfMsg( 'search' )
888 ),
889 $opt
890 );
891
892 return Xml::element(
893 'a',
894 array(
895 'href' => $st->getLocalURL( $stParams ),
896 'title' => $tooltip,
897 'onmousedown' => 'mwSearchHeaderClick(this);',
898 'onkeydown' => 'mwSearchHeaderClick(this);'),
899 $label
900 );
901 }
902
903 /** Check if query starts with image: prefix */
904 protected function startsWithImage( $term ) {
905 global $wgContLang;
906
907 $p = explode( ':', $term );
908 if( count( $p ) > 1 ) {
909 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE;
910 }
911 return false;
912 }
913
914 /** Check if query starts with all: prefix */
915 protected function startsWithAll( $term ) {
916
917 $allkeyword = wfMsgForContent('searchall');
918
919 $p = explode( ':', $term );
920 if( count( $p ) > 1 ) {
921 return $p[0] == $allkeyword;
922 }
923 return false;
924 }
925
926 protected function namespaceTables( $namespaces, $rowsPerTable = 3 ) {
927 global $wgContLang;
928 // Group namespaces into rows according to subject.
929 // Try not to make too many assumptions about namespace numbering.
930 $rows = array();
931 $tables = "";
932 foreach( $namespaces as $ns => $name ) {
933 $subj = MWNamespace::getSubject( $ns );
934 if( !array_key_exists( $subj, $rows ) ) {
935 $rows[$subj] = "";
936 }
937 $name = str_replace( '_', ' ', $name );
938 if( '' == $name ) {
939 $name = wfMsg( 'blanknamespace' );
940 }
941 $rows[$subj] .= Xml::openElement( 'td', array( 'style' => 'white-space: nowrap' ) ) .
942 Xml::checkLabel( $name, "ns{$ns}", "mw-search-ns{$ns}", in_array( $ns, $this->namespaces ) ) .
943 Xml::closeElement( 'td' ) . "\n";
944 }
945 $rows = array_values( $rows );
946 $numRows = count( $rows );
947 // Lay out namespaces in multiple floating two-column tables so they'll
948 // be arranged nicely while still accommodating different screen widths
949 // Float to the right on RTL wikis
950 $tableStyle = $wgContLang->isRTL() ?
951 'float: right; margin: 0 0 0em 1em' : 'float: left; margin: 0 1em 0em 0';
952 // Build the final HTML table...
953 for( $i = 0; $i < $numRows; $i += $rowsPerTable ) {
954 $tables .= Xml::openElement( 'table', array( 'style' => $tableStyle ) );
955 for( $j = $i; $j < $i + $rowsPerTable && $j < $numRows; $j++ ) {
956 $tables .= "<tr>\n" . $rows[$j] . "</tr>";
957 }
958 $tables .= Xml::closeElement( 'table' ) . "\n";
959 }
960 return $tables;
961 }
962 }
963
964 /**
965 * implements Special:Search - Run text & title search and display the output
966 * @ingroup SpecialPage
967 */
968 class SpecialSearchOld {
969
970 /**
971 * Set up basic search parameters from the request and user settings.
972 * Typically you'll pass $wgRequest and $wgUser.
973 *
974 * @param WebRequest $request
975 * @param User $user
976 * @public
977 */
978 function __construct( &$request, &$user ) {
979 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
980 $this->mPrefix = $request->getVal('prefix', '');
981 $this->namespaces = $this->powerSearch( $request );
982 if( empty( $this->namespaces ) ) {
983 $this->namespaces = SearchEngine::userNamespaces( $user );
984 }
985
986 $this->searchRedirects = $request->getcheck( 'redirs' ) ? true : false;
987 $this->fulltext = $request->getVal('fulltext');
988 }
989
990 /**
991 * If an exact title match can be found, jump straight ahead to it.
992 * @param string $term
993 * @public
994 */
995 function goResult( $term ) {
996 global $wgOut;
997 global $wgGoToEdit;
998
999 $this->setupPage( $term );
1000
1001 # Try to go to page as entered.
1002 $t = Title::newFromText( $term );
1003
1004 # If the string cannot be used to create a title
1005 if( is_null( $t ) ){
1006 return $this->showResults( $term );
1007 }
1008
1009 # If there's an exact or very near match, jump right there.
1010 $t = SearchEngine::getNearMatch( $term );
1011 if( !is_null( $t ) ) {
1012 $wgOut->redirect( $t->getFullURL() );
1013 return;
1014 }
1015
1016 # No match, generate an edit URL
1017 $t = Title::newFromText( $term );
1018 if( ! is_null( $t ) ) {
1019 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
1020 # If the feature is enabled, go straight to the edit page
1021 if ( $wgGoToEdit ) {
1022 $wgOut->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
1023 return;
1024 }
1025 }
1026
1027 $extra = $wgOut->parse( '=='.wfMsgNoTrans( 'notitlematches' )."==\n" );
1028 if( $t->quickUserCan( 'create' ) && $t->quickUserCan( 'edit' ) ) {
1029 $extra .= wfMsgExt( 'noexactmatch', 'parse', wfEscapeWikiText( $term ) );
1030 } else {
1031 $extra .= wfMsgExt( 'noexactmatch-nocreate', 'parse', wfEscapeWikiText( $term ) );
1032 }
1033
1034 $this->showResults( $term, $extra );
1035 }
1036
1037 /**
1038 * @param string $term
1039 * @param string $extra Extra HTML to add after "did you mean"
1040 */
1041 public function showResults( $term, $extra = '' ) {
1042 wfProfileIn( __METHOD__ );
1043 global $wgOut, $wgUser;
1044 $sk = $wgUser->getSkin();
1045
1046 $search = SearchEngine::create();
1047 $search->setLimitOffset( $this->limit, $this->offset );
1048 $search->setNamespaces( $this->namespaces );
1049 $search->showRedirects = $this->searchRedirects;
1050 $search->prefix = $this->mPrefix;
1051 $term = $search->transformSearchTerm($term);
1052
1053 $this->setupPage( $term );
1054
1055 $rewritten = $search->replacePrefixes($term);
1056 $titleMatches = $search->searchTitle( $rewritten );
1057 $textMatches = $search->searchText( $rewritten );
1058
1059 // did you mean... suggestions
1060 if($textMatches && $textMatches->hasSuggestion()){
1061 $st = SpecialPage::getTitleFor( 'Search' );
1062
1063 # mirror Go/Search behaviour of original request
1064 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
1065 if($this->fulltext != NULL)
1066 $didYouMeanParams['fulltext'] = $this->fulltext;
1067 $stParams = array_merge(
1068 $didYouMeanParams,
1069 $this->powerSearchOptions()
1070 );
1071
1072 $suggestionSnippet = $textMatches->getSuggestionSnippet();
1073
1074 if( $suggestionSnippet )
1075 $suggestionSnippet = null;
1076
1077 $suggestLink = $sk->linkKnown(
1078 $st,
1079 $suggestionSnippet,
1080 array(),
1081 $stParams
1082 );
1083
1084 $wgOut->addHTML('<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>');
1085 }
1086
1087 $wgOut->addHTML( $extra );
1088
1089 $wgOut->wrapWikiMsg( "<div class='mw-searchresult'>\n$1</div>", 'searchresulttext' );
1090
1091 if( '' === trim( $term ) ) {
1092 // Empty query -- straight view of search form
1093 $wgOut->setSubtitle( '' );
1094 $wgOut->addHTML( $this->powerSearchBox( $term ) );
1095 $wgOut->addHTML( $this->powerSearchFocus() );
1096 wfProfileOut( __METHOD__ );
1097 return;
1098 }
1099
1100 global $wgDisableTextSearch;
1101 if ( $wgDisableTextSearch ) {
1102 global $wgSearchForwardUrl;
1103 if( $wgSearchForwardUrl ) {
1104 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
1105 $wgOut->redirect( $url );
1106 wfProfileOut( __METHOD__ );
1107 return;
1108 }
1109 global $wgInputEncoding;
1110 $wgOut->addHTML(
1111 Xml::openElement( 'fieldset' ) .
1112 Xml::element( 'legend', null, wfMsg( 'search-external' ) ) .
1113 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
1114 wfMsg( 'googlesearch',
1115 htmlspecialchars( $term ),
1116 htmlspecialchars( $wgInputEncoding ),
1117 htmlspecialchars( wfMsg( 'searchbutton' ) )
1118 ) .
1119 Xml::closeElement( 'fieldset' )
1120 );
1121 wfProfileOut( __METHOD__ );
1122 return;
1123 }
1124
1125 $wgOut->addHTML( $this->shortDialog( $term ) );
1126
1127 // Sometimes the search engine knows there are too many hits
1128 if ($titleMatches instanceof SearchResultTooMany) {
1129 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
1130 $wgOut->addHTML( $this->powerSearchBox( $term ) );
1131 $wgOut->addHTML( $this->powerSearchFocus() );
1132 wfProfileOut( __METHOD__ );
1133 return;
1134 }
1135
1136 // show number of results
1137 $num = ( $titleMatches ? $titleMatches->numRows() : 0 )
1138 + ( $textMatches ? $textMatches->numRows() : 0);
1139 $totalNum = 0;
1140 if($titleMatches && !is_null($titleMatches->getTotalHits()))
1141 $totalNum += $titleMatches->getTotalHits();
1142 if($textMatches && !is_null($textMatches->getTotalHits()))
1143 $totalNum += $textMatches->getTotalHits();
1144 if ( $num > 0 ) {
1145 if ( $totalNum > 0 ){
1146 $top = wfMsgExt('showingresultstotal', array( 'parseinline' ),
1147 $this->offset+1, $this->offset+$num, $totalNum, $num );
1148 } elseif ( $num >= $this->limit ) {
1149 $top = wfShowingResults( $this->offset, $this->limit );
1150 } else {
1151 $top = wfShowingResultsNum( $this->offset, $this->limit, $num );
1152 }
1153 $wgOut->addHTML( "<p class='mw-search-numberresults'>{$top}</p>\n" );
1154 }
1155
1156 // prev/next links
1157 if( $num || $this->offset ) {
1158 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
1159 SpecialPage::getTitleFor( 'Search' ),
1160 wfArrayToCGI(
1161 $this->powerSearchOptions(),
1162 array( 'search' => $term ) ),
1163 ($num < $this->limit) );
1164 $wgOut->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
1165 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
1166 } else {
1167 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
1168 }
1169
1170 if( $titleMatches ) {
1171 if( $titleMatches->numRows() ) {
1172 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
1173 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
1174 }
1175 $titleMatches->free();
1176 }
1177
1178 if( $textMatches ) {
1179 // output appropriate heading
1180 if( $textMatches->numRows() ) {
1181 if($titleMatches)
1182 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
1183 else // if no title matches the heading is redundant
1184 $wgOut->addHTML("<hr/>");
1185 } elseif( $num == 0 ) {
1186 # Don't show the 'no text matches' if we received title matches
1187 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
1188 }
1189 // show interwiki results if any
1190 if( $textMatches->hasInterwikiResults() )
1191 $wgOut->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ));
1192 // show results
1193 if( $textMatches->numRows() )
1194 $wgOut->addHTML( $this->showMatches( $textMatches ) );
1195
1196 $textMatches->free();
1197 }
1198
1199 if ( $num == 0 ) {
1200 $wgOut->addWikiMsg( 'nonefound' );
1201 }
1202 if( $num || $this->offset ) {
1203 $wgOut->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
1204 }
1205 $wgOut->addHTML( $this->powerSearchBox( $term ) );
1206 wfProfileOut( __METHOD__ );
1207 }
1208
1209 #------------------------------------------------------------------
1210 # Private methods below this line
1211
1212 /**
1213 *
1214 */
1215 function setupPage( $term ) {
1216 global $wgOut;
1217 if( !empty( $term ) ){
1218 $wgOut->setPageTitle( wfMsg( 'searchresults') );
1219 $wgOut->setHTMLTitle( wfMsg( 'pagetitle', wfMsg( 'searchresults-title', $term) ) );
1220 }
1221 $subtitlemsg = ( Title::newFromText( $term ) ? 'searchsubtitle' : 'searchsubtitleinvalid' );
1222 $wgOut->setSubtitle( $wgOut->parse( wfMsg( $subtitlemsg, wfEscapeWikiText($term) ) ) );
1223 $wgOut->setArticleRelated( false );
1224 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1225 }
1226
1227 /**
1228 * Extract "power search" namespace settings from the request object,
1229 * returning a list of index numbers to search.
1230 *
1231 * @param WebRequest $request
1232 * @return array
1233 * @private
1234 */
1235 function powerSearch( &$request ) {
1236 $arr = array();
1237 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
1238 if( $request->getCheck( 'ns' . $ns ) ) {
1239 $arr[] = $ns;
1240 }
1241 }
1242 return $arr;
1243 }
1244
1245 /**
1246 * Reconstruct the 'power search' options for links
1247 * @return array
1248 * @private
1249 */
1250 function powerSearchOptions() {
1251 $opt = array();
1252 foreach( $this->namespaces as $n ) {
1253 $opt['ns' . $n] = 1;
1254 }
1255 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
1256 return $opt;
1257 }
1258
1259 /**
1260 * Show whole set of results
1261 *
1262 * @param SearchResultSet $matches
1263 */
1264 function showMatches( &$matches ) {
1265 wfProfileIn( __METHOD__ );
1266
1267 global $wgContLang;
1268 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
1269
1270 $out = "";
1271
1272 $infoLine = $matches->getInfo();
1273 if( !is_null($infoLine) )
1274 $out .= "\n<!-- {$infoLine} -->\n";
1275
1276
1277 $off = $this->offset + 1;
1278 $out .= "<ul class='mw-search-results'>\n";
1279
1280 while( $result = $matches->next() ) {
1281 $out .= $this->showHit( $result, $terms );
1282 }
1283 $out .= "</ul>\n";
1284
1285 // convert the whole thing to desired language variant
1286 global $wgContLang;
1287 $out = $wgContLang->convert( $out );
1288 wfProfileOut( __METHOD__ );
1289 return $out;
1290 }
1291
1292 /**
1293 * Format a single hit result
1294 * @param SearchResult $result
1295 * @param array $terms terms to highlight
1296 */
1297 function showHit( $result, $terms ) {
1298 wfProfileIn( __METHOD__ );
1299 global $wgUser, $wgContLang, $wgLang;
1300
1301 if( $result->isBrokenTitle() ) {
1302 wfProfileOut( __METHOD__ );
1303 return "<!-- Broken link in search result -->\n";
1304 }
1305
1306 $t = $result->getTitle();
1307 $sk = $wgUser->getSkin();
1308
1309 $titleSnippet = $result->getTitleSnippet($terms);
1310
1311 if( $titleSnippet == '' )
1312 $titleSnippet = null;
1313
1314 $link = $sk->linkKnown(
1315 $t,
1316 $titleSnippet
1317 );
1318
1319 //If page content is not readable, just return the title.
1320 //This is not quite safe, but better than showing excerpts from non-readable pages
1321 //Note that hiding the entry entirely would screw up paging.
1322 if (!$t->userCanRead()) {
1323 wfProfileOut( __METHOD__ );
1324 return "<li>{$link}</li>\n";
1325 }
1326
1327 // If the page doesn't *exist*... our search index is out of date.
1328 // The least confusing at this point is to drop the result.
1329 // You may get less results, but... oh well. :P
1330 if( $result->isMissingRevision() ) {
1331 wfProfileOut( __METHOD__ );
1332 return "<!-- missing page " .
1333 htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
1334 }
1335
1336 // format redirects / relevant sections
1337 $redirectTitle = $result->getRedirectTitle();
1338 $redirectText = $result->getRedirectSnippet($terms);
1339 $sectionTitle = $result->getSectionTitle();
1340 $sectionText = $result->getSectionSnippet($terms);
1341 $redirect = '';
1342 if( !is_null($redirectTitle) ) {
1343 if( $redirectText == '' )
1344 $redirectText = null;
1345
1346 $redirect = "<span class='searchalttitle'>" .
1347 wfMsg(
1348 'search-redirect',
1349 $sk->linkKnown(
1350 $redirectTitle,
1351 $redirectText
1352 )
1353 ) .
1354 "</span>";
1355 }
1356
1357 $section = '';
1358
1359 if( !is_null($sectionTitle) ) {
1360 if( $sectionText == '' )
1361 $sectionText = null;
1362
1363 $section = "<span class='searchalttitle'>" .
1364 wfMsg(
1365 'search-section',
1366 $sk->linkKnown(
1367 $sectionTitle,
1368 $sectionText
1369 )
1370 ) .
1371 "</span>";
1372 }
1373
1374 // format text extract
1375 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
1376
1377 // format score
1378 if( is_null( $result->getScore() ) ) {
1379 // Search engine doesn't report scoring info
1380 $score = '';
1381 } else {
1382 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
1383 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
1384 . ' - ';
1385 }
1386
1387 // format description
1388 $byteSize = $result->getByteSize();
1389 $wordCount = $result->getWordCount();
1390 $timestamp = $result->getTimestamp();
1391 $size = wfMsgExt( 'search-result-size', array( 'parsemag', 'escape' ),
1392 $sk->formatSize( $byteSize ),
1393 $wordCount );
1394 $date = $wgLang->timeanddate( $timestamp );
1395
1396 // link to related articles if supported
1397 $related = '';
1398 if( $result->hasRelated() ){
1399 $st = SpecialPage::getTitleFor( 'Search' );
1400 $stParams = array_merge(
1401 $this->powerSearchOptions(),
1402 array(
1403 'search' => wfMsgForContent( 'searchrelated' ) . ':' . $t->getPrefixedText(),
1404 'fulltext' => wfMsg( 'search' )
1405 )
1406 );
1407
1408 $related = ' -- ' . $sk->linkKnown(
1409 $st,
1410 wfMsg('search-relatedarticle'),
1411 array(),
1412 $stParams
1413 );
1414 }
1415
1416 // Include a thumbnail for media files...
1417 if( $t->getNamespace() == NS_FILE ) {
1418 $img = wfFindFile( $t );
1419 if( $img ) {
1420 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
1421 if( $thumb ) {
1422 $desc = $img->getShortDesc();
1423 wfProfileOut( __METHOD__ );
1424 // Ugly table. :D
1425 // Float doesn't seem to interact well with the bullets.
1426 // Table messes up vertical alignment of the bullet, but I'm
1427 // not sure what more I can do about that. :(
1428 return "<li>" .
1429 '<table class="searchResultImage">' .
1430 '<tr>' .
1431 '<td width="120" align="center">' .
1432 $thumb->toHtml( array( 'desc-link' => true ) ) .
1433 '</td>' .
1434 '<td valign="top">' .
1435 $link .
1436 $extract .
1437 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
1438 '</td>' .
1439 '</tr>' .
1440 '</table>' .
1441 "</li>\n";
1442 }
1443 }
1444 }
1445
1446 wfProfileOut( __METHOD__ );
1447 return "<li>{$link} {$redirect} {$section} {$extract}\n" .
1448 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
1449 "</li>\n";
1450
1451 }
1452
1453 /**
1454 * Show results from other wikis
1455 *
1456 * @param SearchResultSet $matches
1457 */
1458 function showInterwiki( &$matches, $query ) {
1459 wfProfileIn( __METHOD__ );
1460
1461 global $wgContLang;
1462 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
1463
1464 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".wfMsg('search-interwiki-caption')."</div>\n";
1465 $off = $this->offset + 1;
1466 $out .= "<ul start='{$off}' class='mw-search-iwresults'>\n";
1467
1468 // work out custom project captions
1469 $customCaptions = array();
1470 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
1471 foreach($customLines as $line){
1472 $parts = explode(":",$line,2);
1473 if(count($parts) == 2) // validate line
1474 $customCaptions[$parts[0]] = $parts[1];
1475 }
1476
1477
1478 $prev = null;
1479 while( $result = $matches->next() ) {
1480 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
1481 $prev = $result->getInterwikiPrefix();
1482 }
1483 // FIXME: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
1484 $out .= "</ul></div>\n";
1485
1486 // convert the whole thing to desired language variant
1487 global $wgContLang;
1488 $out = $wgContLang->convert( $out );
1489 wfProfileOut( __METHOD__ );
1490 return $out;
1491 }
1492
1493 /**
1494 * Show single interwiki link
1495 *
1496 * @param SearchResult $result
1497 * @param string $lastInterwiki
1498 * @param array $terms
1499 * @param string $query
1500 * @param array $customCaptions iw prefix -> caption
1501 */
1502 function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
1503 wfProfileIn( __METHOD__ );
1504 global $wgUser, $wgContLang, $wgLang;
1505
1506 if( $result->isBrokenTitle() ) {
1507 wfProfileOut( __METHOD__ );
1508 return "<!-- Broken link in search result -->\n";
1509 }
1510
1511 $t = $result->getTitle();
1512 $sk = $wgUser->getSkin();
1513
1514 $titleSnippet = $result->getTitleSnippet($terms);
1515
1516 if( $titleSnippet == '' )
1517 $titleSnippet = null;
1518
1519 $link = $sk->linkKnown(
1520 $t,
1521 $titleSnippet
1522 );
1523
1524 // format redirect if any
1525 $redirectTitle = $result->getRedirectTitle();
1526 $redirectText = $result->getRedirectSnippet($terms);
1527 $redirect = '';
1528 if( !is_null($redirectTitle) ) {
1529 if( $redirectText == '' )
1530 $redirectText = null;
1531
1532 $redirect = "<span class='searchalttitle'>" .
1533 wfMsg(
1534 'search-redirect',
1535 $sk->linkKnown(
1536 $redirectTitle,
1537 $redirectText
1538 )
1539 ) .
1540 "</span>";
1541 }
1542
1543 $out = "";
1544 // display project name
1545 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()){
1546 if( key_exists($t->getInterwiki(),$customCaptions) )
1547 // captions from 'search-interwiki-custom'
1548 $caption = $customCaptions[$t->getInterwiki()];
1549 else{
1550 // default is to show the hostname of the other wiki which might suck
1551 // if there are many wikis on one hostname
1552 $parsed = parse_url($t->getFullURL());
1553 $caption = wfMsg('search-interwiki-default', $parsed['host']);
1554 }
1555 // "more results" link (special page stuff could be localized, but we might not know target lang)
1556 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
1557 $searchLink = $sk->linkKnown(
1558 $searchTitle,
1559 wfMsg( 'search-interwiki-more' ),
1560 array(),
1561 array(
1562 'search' => $query,
1563 'fulltext' => 'Search'
1564 )
1565 );
1566 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>{$searchLink}</span>{$caption}</div>\n<ul>";
1567 }
1568
1569 $out .= "<li>{$link} {$redirect}</li>\n";
1570 wfProfileOut( __METHOD__ );
1571 return $out;
1572 }
1573
1574
1575 /**
1576 * Generates the power search box at bottom of [[Special:Search]]
1577 * @param $term string: search term
1578 * @return $out string: HTML form
1579 */
1580 function powerSearchBox( $term ) {
1581 global $wgScript, $wgContLang;
1582
1583 $namespaces = SearchEngine::searchableNamespaces();
1584
1585 // group namespaces into rows according to subject; try not to make too
1586 // many assumptions about namespace numbering
1587 $rows = array();
1588 foreach( $namespaces as $ns => $name ) {
1589 $subj = MWNamespace::getSubject( $ns );
1590 if( !array_key_exists( $subj, $rows ) ) {
1591 $rows[$subj] = "";
1592 }
1593 $name = str_replace( '_', ' ', $name );
1594 if( '' == $name ) {
1595 $name = wfMsg( 'blanknamespace' );
1596 }
1597 $rows[$subj] .= Xml::openElement( 'td', array( 'style' => 'white-space: nowrap' ) ) .
1598 Xml::checkLabel( $name, "ns{$ns}", "mw-search-ns{$ns}", in_array( $ns, $this->namespaces ) ) .
1599 Xml::closeElement( 'td' ) . "\n";
1600 }
1601 $rows = array_values( $rows );
1602 $numRows = count( $rows );
1603
1604 // lay out namespaces in multiple floating two-column tables so they'll
1605 // be arranged nicely while still accommodating different screen widths
1606 $rowsPerTable = 3; // seems to look nice
1607
1608 // float to the right on RTL wikis
1609 $tableStyle = ( $wgContLang->isRTL() ?
1610 'float: right; margin: 0 0 1em 1em' :
1611 'float: left; margin: 0 1em 1em 0' );
1612
1613 $tables = "";
1614 for( $i = 0; $i < $numRows; $i += $rowsPerTable ) {
1615 $tables .= Xml::openElement( 'table', array( 'style' => $tableStyle ) );
1616 for( $j = $i; $j < $i + $rowsPerTable && $j < $numRows; $j++ ) {
1617 $tables .= "<tr>\n" . $rows[$j] . "</tr>";
1618 }
1619 $tables .= Xml::closeElement( 'table' ) . "\n";
1620 }
1621
1622 $redirect = Xml::check( 'redirs', $this->searchRedirects, array( 'value' => '1', 'id' => 'redirs' ) );
1623 $redirectLabel = Xml::label( wfMsg( 'powersearch-redir' ), 'redirs' );
1624 $searchField = Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'powerSearchText' ) );
1625 $searchButton = Xml::submitButton( wfMsg( 'powersearch' ) ) . "\n";
1626 $searchTitle = SpecialPage::getTitleFor( 'Search' );
1627 $searchHiddens = Xml::hidden( 'title', $searchTitle->getPrefixedText() ) . "\n";
1628 $searchHiddens .= Xml::hidden( 'fulltext', 'Advanced search' ) . "\n";
1629
1630 $out = Xml::openElement( 'form', array( 'id' => 'powersearch', 'method' => 'get', 'action' => $wgScript ) ) .
1631 Xml::fieldset( wfMsg( 'powersearch-legend' ),
1632 "<p>" .
1633 wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) .
1634 "</p>\n" .
1635 $tables .
1636 "<hr style=\"clear: both\" />\n" .
1637 "<p>" .
1638 $redirect . " " . $redirectLabel .
1639 "</p>\n" .
1640 wfMsgExt( 'powersearch-field', array( 'parseinline' ) ) .
1641 "&nbsp;" .
1642 $searchField .
1643 "&nbsp;" .
1644 $searchHiddens .
1645 $searchButton ) .
1646 "</form>";
1647
1648 return $out;
1649 }
1650
1651 function powerSearchFocus() {
1652 global $wgJsMimeType;
1653 return "<script type=\"$wgJsMimeType\">" .
1654 "hookEvent(\"load\", function(){" .
1655 "document.getElementById('powerSearchText').focus();" .
1656 "});" .
1657 "</script>";
1658 }
1659
1660 function shortDialog($term) {
1661 global $wgScript;
1662
1663 $out = Xml::openElement( 'form', array(
1664 'id' => 'search',
1665 'method' => 'get',
1666 'action' => $wgScript
1667 ));
1668 $searchTitle = SpecialPage::getTitleFor( 'Search' );
1669 $out .= Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'searchText' ) ) . ' ';
1670 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
1671 if( in_array( $ns, $this->namespaces ) ) {
1672 $out .= Xml::hidden( "ns{$ns}", '1' );
1673 }
1674 }
1675 $out .= Xml::hidden( 'title', $searchTitle->getPrefixedText() );
1676 $out .= Xml::hidden( 'fulltext', 'Search' );
1677 $out .= Xml::submitButton( wfMsg( 'searchbutton' ) );
1678 $out .= Xml::closeElement( 'form' );
1679
1680 return $out;
1681 }
1682 }