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