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