Allow wikitext for 'powersearchtext' (from r319410)
[lhc/web/wiklou.git] / includes / 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 * @addtogroup SpecialPage
23 */
24
25 /**
26 * Entry point
27 *
28 * @param $par String: (default '')
29 */
30 function wfSpecialSearch( $par = '' ) {
31 global $wgRequest, $wgUser;
32
33 $search = $wgRequest->getText( 'search', $par );
34 $searchPage = new SpecialSearch( $wgRequest, $wgUser );
35 if( $wgRequest->getVal( 'fulltext' ) ||
36 !is_null( $wgRequest->getVal( 'offset' ) ) ||
37 !is_null ($wgRequest->getVal( 'searchx' ) ) ) {
38 $searchPage->showResults( $search );
39 } else {
40 $searchPage->goResult( $search );
41 }
42 }
43
44 /**
45 * implements Special:Search - Run text & title search and display the output
46 * @addtogroup SpecialPage
47 */
48 class SpecialSearch {
49
50 /**
51 * Set up basic search parameters from the request and user settings.
52 * Typically you'll pass $wgRequest and $wgUser.
53 *
54 * @param WebRequest $request
55 * @param User $user
56 * @public
57 */
58 function SpecialSearch( &$request, &$user ) {
59 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
60
61 if( $request->getCheck( 'searchx' ) ) {
62 $this->namespaces = $this->powerSearch( $request );
63 } else {
64 $this->namespaces = $this->userNamespaces( $user );
65 }
66
67 $this->searchRedirects = $request->getcheck( 'redirs' ) ? true : false;
68 }
69
70 /**
71 * If an exact title match can be found, jump straight ahead to it.
72 * @param string $term
73 * @public
74 */
75 function goResult( $term ) {
76 global $wgOut;
77 global $wgGoToEdit;
78
79 $this->setupPage( $term );
80
81 # Try to go to page as entered.
82 $t = Title::newFromText( $term );
83
84 # If the string cannot be used to create a title
85 if( is_null( $t ) ){
86 return $this->showResults( $term );
87 }
88
89 # If there's an exact or very near match, jump right there.
90 $t = SearchEngine::getNearMatch( $term );
91 if( !is_null( $t ) ) {
92 $wgOut->redirect( $t->getFullURL() );
93 return;
94 }
95
96 # No match, generate an edit URL
97 $t = Title::newFromText( $term );
98 if( ! is_null( $t ) ) {
99 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
100 # If the feature is enabled, go straight to the edit page
101 if ( $wgGoToEdit ) {
102 $wgOut->redirect( $t->getFullURL( 'action=edit' ) );
103 return;
104 }
105 }
106 if( $t->quickUserCan( 'create' ) && $t->quickUserCan( 'edit' ) ) {
107 $wgOut->addWikiMsg( 'noexactmatch', wfEscapeWikiText( $term ) );
108 } else {
109 $wgOut->addWikiMsg( 'noexactmatch-nocreate', wfEscapeWikiText( $term ) );
110 }
111
112 return $this->showResults( $term );
113 }
114
115 /**
116 * @param string $term
117 * @public
118 */
119 function showResults( $term ) {
120 $fname = 'SpecialSearch::showResults';
121 wfProfileIn( $fname );
122
123 $this->setupPage( $term );
124
125 global $wgOut;
126 $wgOut->addWikiMsg( 'searchresulttext' );
127
128 if( '' === trim( $term ) ) {
129 // Empty query -- straight view of search form
130 $wgOut->setSubtitle( '' );
131 $wgOut->addHTML( $this->powerSearchBox( $term ) );
132 $wgOut->addHTML( $this->powerSearchFocus() );
133 wfProfileOut( $fname );
134 return;
135 }
136
137 global $wgDisableTextSearch;
138 if ( $wgDisableTextSearch ) {
139 global $wgForwardSearchUrl;
140 if( $wgForwardSearchUrl ) {
141 $url = str_replace( '$1', urlencode( $term ), $wgForwardSearchUrl );
142 $wgOut->redirect( $url );
143 return;
144 }
145 global $wgInputEncoding;
146 $wgOut->addHTML( wfMsg( 'searchdisabled' ) );
147 $wgOut->addHTML(
148 wfMsg( 'googlesearch',
149 htmlspecialchars( $term ),
150 htmlspecialchars( $wgInputEncoding ),
151 htmlspecialchars( wfMsg( 'searchbutton' ) )
152 )
153 );
154 wfProfileOut( $fname );
155 return;
156 }
157
158 $wgOut->addHTML( $this->shortDialog( $term ) );
159
160 $search = SearchEngine::create();
161 $search->setLimitOffset( $this->limit, $this->offset );
162 $search->setNamespaces( $this->namespaces );
163 $search->showRedirects = $this->searchRedirects;
164 $titleMatches = $search->searchTitle( $term );
165
166 // Sometimes the search engine knows there are too many hits
167 if ($titleMatches instanceof SearchResultTooMany) {
168 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
169 $wgOut->addHTML( $this->powerSearchBox( $term ) );
170 $wgOut->addHTML( $this->powerSearchFocus() );
171 wfProfileOut( $fname );
172 return;
173 }
174 $textMatches = $search->searchText( $term );
175
176 $num = ( $titleMatches ? $titleMatches->numRows() : 0 )
177 + ( $textMatches ? $textMatches->numRows() : 0);
178 if ( $num > 0 ) {
179 if ( $num >= $this->limit ) {
180 $top = wfShowingResults( $this->offset, $this->limit );
181 } else {
182 $top = wfShowingResultsNum( $this->offset, $this->limit, $num );
183 }
184 $wgOut->addHTML( "<p>{$top}</p>\n" );
185 }
186
187 if( $num || $this->offset ) {
188 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
189 SpecialPage::getTitleFor( 'Search' ),
190 wfArrayToCGI(
191 $this->powerSearchOptions(),
192 array( 'search' => $term ) ),
193 ($num < $this->limit) );
194 $wgOut->addHTML( "<br />{$prevnext}\n" );
195 }
196
197 if( $titleMatches ) {
198 if( $titleMatches->numRows() ) {
199 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
200 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
201 } else {
202 $wgOut->wrapWikiMsg( "==$1==\n", 'notitlematches' );
203 }
204 $titleMatches->free();
205 }
206
207 if( $textMatches ) {
208 if( $textMatches->numRows() ) {
209 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
210 $wgOut->addHTML( $this->showMatches( $textMatches ) );
211 } elseif( $num == 0 ) {
212 # Don't show the 'no text matches' if we received title matches
213 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
214 }
215 $textMatches->free();
216 }
217
218 if ( $num == 0 ) {
219 $wgOut->addWikiMsg( 'nonefound' );
220 }
221 if( $num || $this->offset ) {
222 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
223 }
224 $wgOut->addHTML( $this->powerSearchBox( $term ) );
225 wfProfileOut( $fname );
226 }
227
228 #------------------------------------------------------------------
229 # Private methods below this line
230
231 /**
232 *
233 */
234 function setupPage( $term ) {
235 global $wgOut;
236 $wgOut->setPageTitle( wfMsg( 'searchresults' ) );
237 $subtitlemsg = ( Title::newFromText($term) ? 'searchsubtitle' : 'searchsubtitleinvalid' );
238 $wgOut->setSubtitle( $wgOut->parse( wfMsg( $subtitlemsg, wfEscapeWikiText($term) ) ) );
239 $wgOut->setArticleRelated( false );
240 $wgOut->setRobotpolicy( 'noindex,nofollow' );
241 }
242
243 /**
244 * Extract default namespaces to search from the given user's
245 * settings, returning a list of index numbers.
246 *
247 * @param User $user
248 * @return array
249 * @private
250 */
251 function userNamespaces( &$user ) {
252 $arr = array();
253 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
254 if( $user->getOption( 'searchNs' . $ns ) ) {
255 $arr[] = $ns;
256 }
257 }
258 return $arr;
259 }
260
261 /**
262 * Extract "power search" namespace settings from the request object,
263 * returning a list of index numbers to search.
264 *
265 * @param WebRequest $request
266 * @return array
267 * @private
268 */
269 function powerSearch( &$request ) {
270 $arr = array();
271 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
272 if( $request->getCheck( 'ns' . $ns ) ) {
273 $arr[] = $ns;
274 }
275 }
276 return $arr;
277 }
278
279 /**
280 * Reconstruct the 'power search' options for links
281 * @return array
282 * @private
283 */
284 function powerSearchOptions() {
285 $opt = array();
286 foreach( $this->namespaces as $n ) {
287 $opt['ns' . $n] = 1;
288 }
289 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
290 $opt['searchx'] = 1;
291 return $opt;
292 }
293
294
295
296 /**
297 * @param SearchResultSet $matches
298 * @param string $terms partial regexp for highlighting terms
299 */
300 function showMatches( &$matches ) {
301 $fname = 'SpecialSearch::showMatches';
302 wfProfileIn( $fname );
303
304 global $wgContLang;
305 $tm = $wgContLang->convertForSearchResult( $matches->termMatches() );
306 $terms = implode( '|', $tm );
307
308 $off = $this->offset + 1;
309 $out = "<ol start='{$off}' id='searchResults'>\n";
310
311 while( $result = $matches->next() ) {
312 $out .= $this->showHit( $result, $terms );
313 }
314 $out .= "</ol>\n";
315
316 // convert the whole thing to desired language variant
317 global $wgContLang;
318 $out = $wgContLang->convert( $out );
319 wfProfileOut( $fname );
320 return $out;
321 }
322
323 /**
324 * Format a single hit result
325 * @param SearchResult $result
326 * @param string $terms partial regexp for highlighting terms
327 */
328 function showHit( $result, $terms ) {
329 $fname = 'SpecialSearch::showHit';
330 wfProfileIn( $fname );
331 global $wgUser, $wgContLang, $wgLang;
332
333 $t = $result->getTitle();
334 if( is_null( $t ) ) {
335 wfProfileOut( $fname );
336 return "<!-- Broken link in search result -->\n";
337 }
338 $sk = $wgUser->getSkin();
339
340 $contextlines = $wgUser->getOption( 'contextlines', 5 );
341 $contextchars = $wgUser->getOption( 'contextchars', 50 );
342
343 $link = $sk->makeKnownLinkObj( $t );
344
345 //If page content is not readable, just return the title.
346 //This is not quite safe, but better than showing excerpts from non-readable pages
347 //Note that hiding the entry entirely would screw up paging.
348 if (!$t->userCanRead()) {
349 return "<li>{$link}</li>\n";
350 }
351
352 $extract = $size = '';
353 // Include a thumbnail for media files...
354 if( $t->getNamespace() == NS_IMAGE ) {
355 $img = wfFindFile( $t );
356 if( $img ) {
357 $thumb = $img->getThumbnail( 120, 120 );
358 if( $thumb ) {
359 $extract = '<table class="searchResultImage">' .
360 '<tr>' .
361 '<td width="120" align="center">' .
362 $sk->makeKnownLinkObj( $t, $thumb->toHtml() ) .
363 '</td>' .
364 '<td>' .
365 $link .
366 '<br />' .
367 $img->getLongDesc() .
368 '</td>' .
369 '</tr>' .
370 '</table>';
371 wfProfileOut( $fname );
372 return "<li><div>{$extract}</div></li>\n";
373 }
374 }
375 }
376
377 $extract = $this->extractText( $t, $terms, $contextlines, $contextchars );
378 wfProfileOut( $fname );
379 return "<li>{$link} {$extract}</li>\n";
380
381 }
382
383 private function extractText( $t, $terms, $contextlines, $contextchars ) {
384 global $wgLang, $wgContLang;
385 $fname = __METHOD__;
386
387 $revision = Revision::newFromTitle( $t );
388 if( !$revision ) {
389 return '<!-- missing page -->';
390 }
391
392 $text = $revision->getText();
393 $size = wfMsgExt( 'nbytes', array( 'parsemag', 'escape'),
394 $wgLang->formatNum( strlen( $text ) ) );
395
396 $lines = explode( "\n", $text );
397
398 $max = intval( $contextchars ) + 1;
399 $pat1 = "/(.*)($terms)(.{0,$max})/i";
400
401 $lineno = 0;
402
403 $extract = "($size)";
404 wfProfileIn( "$fname-extract" );
405 foreach ( $lines as $line ) {
406 if ( 0 == $contextlines ) {
407 break;
408 }
409 ++$lineno;
410 $m = array();
411 if ( ! preg_match( $pat1, $line, $m ) ) {
412 continue;
413 }
414 --$contextlines;
415 $pre = $wgContLang->truncate( $m[1], -$contextchars, '...' );
416
417 if ( count( $m ) < 3 ) {
418 $post = '';
419 } else {
420 $post = $wgContLang->truncate( $m[3], $contextchars, '...' );
421 }
422
423 $found = $m[2];
424
425 $line = htmlspecialchars( $pre . $found . $post );
426 $pat2 = '/(' . $terms . ")/i";
427 $line = preg_replace( $pat2,
428 "<span class='searchmatch'>\\1</span>", $line );
429
430 $extract .= "<br /><small>{$lineno}: {$line}</small>\n";
431 }
432 wfProfileOut( "$fname-extract" );
433
434 return $extract;
435 }
436
437 function powerSearchBox( $term ) {
438 global $wgScript;
439
440 $namespaces = '';
441 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
442 $name = str_replace( '_', ' ', $name );
443 if( '' == $name ) {
444 $name = wfMsg( 'blanknamespace' );
445 }
446 $encName = htmlspecialchars( $name );
447 $namespaces .= '<label>' .
448 Xml::check( "ns{$ns}", in_array( $ns, $this->namespaces ),
449 array( 'value' => '1' ) ) .
450 "{$encName}</label> ";
451 }
452
453 $redirect = Xml::check( 'redirs', $this->searchRedirects,
454 array( 'value' => '1' ) );
455
456 $searchField = Xml::input( 'search', 50, $term, array(
457 'type' => 'text', 'id' => 'powerSearchText' ) );
458
459 $searchButton = Xml::element( 'input', array(
460 'type' => 'submit',
461 'name' => 'searchx',
462 'value' => wfMsg('powersearch')
463 ) ) . "\n";
464
465 $out = Xml::openElement( 'form', array(
466 'id' => 'powersearch',
467 'method' => 'get',
468 'action' => $wgScript ) );
469 $out .= Xml::openElement( 'fieldset' );
470 $out .= Xml::element( 'legend', array( ), wfMsg( 'powersearch' ));
471 $out .= Xml::hidden( 'title', 'Special:Search' );
472 $out .= wfMsgExt( 'powersearchtext', array( 'parse', 'replaceafter' ),
473 $namespaces, $redirect, $searchField,
474 '', '', '', '', '', # Dummy placeholders
475 $searchButton );
476 $out .= Xml::closeElement( 'fieldset' );
477 $out .= Xml::closeElement( 'form' );
478
479 return $out;
480 }
481
482 function powerSearchFocus() {
483 return "<script type='text/javascript'>" .
484 "document.getElementById('powerSearchText').focus();" .
485 "</script>";
486 }
487
488 function shortDialog($term) {
489 global $wgScript;
490
491 $out = Xml::openElement( 'form', array(
492 'id' => 'search',
493 'method' => 'get',
494 'action' => $wgScript
495 ));
496 $out .= Xml::openElement( 'fieldset' );
497 $out .= Xml::element( 'legend', array(), wfMsg( 'searchresultshead' ) );
498 $out .= Xml::hidden( 'title', 'Special:Search' );
499 $out .= Xml::inputLabel( wfMsg( 'search' ), 'search', 'searchbox', 50, $term ) . ' ';
500 $out .= Xml::submitButton( wfMsg( 'searchbutton' ) );
501 $out .= Xml::closeElement( 'fieldset' );
502 $out .= Xml::closeElement( 'form' );
503
504 return $out;
505 }
506 }
507
508