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