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