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