More typos
[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 $search = SearchEngine::create();
159 $search->setLimitOffset( $this->limit, $this->offset );
160 $search->setNamespaces( $this->namespaces );
161 $search->showRedirects = $this->searchRedirects;
162 $titleMatches = $search->searchTitle( $term );
163
164 // Sometimes the search engine knows there are too many hits
165 if ($titleMatches instanceof SearchResultTooMany) {
166 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
167 $wgOut->addHTML( $this->powerSearchBox( $term ) );
168 $wgOut->addHTML( $this->powerSearchFocus() );
169 wfProfileOut( $fname );
170 return;
171 }
172 $textMatches = $search->searchText( $term );
173
174 $num = ( $titleMatches ? $titleMatches->numRows() : 0 )
175 + ( $textMatches ? $textMatches->numRows() : 0);
176 if ( $num > 0 ) {
177 if ( $num >= $this->limit ) {
178 $top = wfShowingResults( $this->offset, $this->limit );
179 } else {
180 $top = wfShowingResultsNum( $this->offset, $this->limit, $num );
181 }
182 $wgOut->addHTML( "<p>{$top}</p>\n" );
183 }
184
185 if( $num || $this->offset ) {
186 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
187 SpecialPage::getTitleFor( 'Search' ),
188 wfArrayToCGI(
189 $this->powerSearchOptions(),
190 array( 'search' => $term ) ),
191 ($num < $this->limit) );
192 $wgOut->addHTML( "<br />{$prevnext}\n" );
193 }
194
195 if( $titleMatches ) {
196 if( $titleMatches->numRows() ) {
197 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
198 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
199 } else {
200 $wgOut->wrapWikiMsg( "==$1==\n", 'notitlematches' );
201 }
202 $titleMatches->free();
203 }
204
205 if( $textMatches ) {
206 if( $textMatches->numRows() ) {
207 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
208 $wgOut->addHTML( $this->showMatches( $textMatches ) );
209 } elseif( $num == 0 ) {
210 # Don't show the 'no text matches' if we received title matches
211 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
212 }
213 $textMatches->free();
214 }
215
216 if ( $num == 0 ) {
217 $wgOut->addWikiMsg( 'nonefound' );
218 }
219 if( $num || $this->offset ) {
220 $wgOut->addHTML( "<p>{$prevnext}</p>\n" );
221 }
222 $wgOut->addHTML( $this->powerSearchBox( $term ) );
223 wfProfileOut( $fname );
224 }
225
226 #------------------------------------------------------------------
227 # Private methods below this line
228
229 /**
230 *
231 */
232 function setupPage( $term ) {
233 global $wgOut;
234 $wgOut->setPageTitle( wfMsg( 'searchresults' ) );
235 $subtitlemsg = ( Title::newFromText($term) ? 'searchsubtitle' : 'searchsubtitleinvalid' );
236 $wgOut->setSubtitle( $wgOut->parse( wfMsg( $subtitlemsg, wfEscapeWikiText($term) ) ) );
237 $wgOut->setArticleRelated( false );
238 $wgOut->setRobotpolicy( 'noindex,nofollow' );
239 }
240
241 /**
242 * Extract default namespaces to search from the given user's
243 * settings, returning a list of index numbers.
244 *
245 * @param User $user
246 * @return array
247 * @private
248 */
249 function userNamespaces( &$user ) {
250 $arr = array();
251 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
252 if( $user->getOption( 'searchNs' . $ns ) ) {
253 $arr[] = $ns;
254 }
255 }
256 return $arr;
257 }
258
259 /**
260 * Extract "power search" namespace settings from the request object,
261 * returning a list of index numbers to search.
262 *
263 * @param WebRequest $request
264 * @return array
265 * @private
266 */
267 function powerSearch( &$request ) {
268 $arr = array();
269 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
270 if( $request->getCheck( 'ns' . $ns ) ) {
271 $arr[] = $ns;
272 }
273 }
274 return $arr;
275 }
276
277 /**
278 * Reconstruct the 'power search' options for links
279 * @return array
280 * @private
281 */
282 function powerSearchOptions() {
283 $opt = array();
284 foreach( $this->namespaces as $n ) {
285 $opt['ns' . $n] = 1;
286 }
287 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
288 $opt['searchx'] = 1;
289 return $opt;
290 }
291
292 /**
293 * @param SearchResultSet $matches
294 * @param string $terms partial regexp for highlighting terms
295 */
296 function showMatches( &$matches ) {
297 $fname = 'SpecialSearch::showMatches';
298 wfProfileIn( $fname );
299
300 global $wgContLang;
301 $tm = $wgContLang->convertForSearchResult( $matches->termMatches() );
302 $terms = implode( '|', $tm );
303
304 $off = $this->offset + 1;
305 $out = "<ol start='{$off}'>\n";
306
307 while( $result = $matches->next() ) {
308 $out .= $this->showHit( $result, $terms );
309 }
310 $out .= "</ol>\n";
311
312 // convert the whole thing to desired language variant
313 global $wgContLang;
314 $out = $wgContLang->convert( $out );
315 wfProfileOut( $fname );
316 return $out;
317 }
318
319 /**
320 * Format a single hit result
321 * @param SearchResult $result
322 * @param string $terms partial regexp for highlighting terms
323 */
324 function showHit( $result, $terms ) {
325 $fname = 'SpecialSearch::showHit';
326 wfProfileIn( $fname );
327 global $wgUser, $wgContLang, $wgLang;
328
329 $t = $result->getTitle();
330 if( is_null( $t ) ) {
331 wfProfileOut( $fname );
332 return "<!-- Broken link in search result -->\n";
333 }
334 $sk = $wgUser->getSkin();
335
336 $contextlines = $wgUser->getOption( 'contextlines', 5 );
337 $contextchars = $wgUser->getOption( 'contextchars', 50 );
338
339 $link = $sk->makeKnownLinkObj( $t );
340
341 //If page content is not readable, just return the title.
342 //This is not quite safe, but better than showing excerpts from non-readable pages
343 //Note that hiding the entry entirely would screw up paging.
344 if (!$t->userCanRead()) {
345 return "<li>{$link}</li>\n";
346 }
347
348 $revision = Revision::newFromTitle( $t );
349 $text = $revision->getText();
350 $size = wfMsgExt( 'nbytes', array( 'parsemag', 'escape'),
351 $wgLang->formatNum( strlen( $text ) ) );
352
353 $lines = explode( "\n", $text );
354
355 $max = intval( $contextchars ) + 1;
356 $pat1 = "/(.*)($terms)(.{0,$max})/i";
357
358 $lineno = 0;
359
360 $extract = '';
361 wfProfileIn( "$fname-extract" );
362 foreach ( $lines as $line ) {
363 if ( 0 == $contextlines ) {
364 break;
365 }
366 ++$lineno;
367 $m = array();
368 if ( ! preg_match( $pat1, $line, $m ) ) {
369 continue;
370 }
371 --$contextlines;
372 $pre = $wgContLang->truncate( $m[1], -$contextchars, '...' );
373
374 if ( count( $m ) < 3 ) {
375 $post = '';
376 } else {
377 $post = $wgContLang->truncate( $m[3], $contextchars, '...' );
378 }
379
380 $found = $m[2];
381
382 $line = htmlspecialchars( $pre . $found . $post );
383 $pat2 = '/(' . $terms . ")/i";
384 $line = preg_replace( $pat2,
385 "<span class='searchmatch'>\\1</span>", $line );
386
387 $extract .= "<br /><small>{$lineno}: {$line}</small>\n";
388 }
389 wfProfileOut( "$fname-extract" );
390 wfProfileOut( $fname );
391 return "<li>{$link} ({$size}){$extract}</li>\n";
392 }
393
394 function powerSearchBox( $term ) {
395 $namespaces = '';
396 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
397 $checked = in_array( $ns, $this->namespaces )
398 ? ' checked="checked"'
399 : '';
400 $name = str_replace( '_', ' ', $name );
401 if( '' == $name ) {
402 $name = wfMsg( 'blanknamespace' );
403 }
404 $encName = htmlspecialchars( $name );
405 $namespaces .= " <label><input type='checkbox' value=\"1\" name=\"" .
406 "ns{$ns}\"{$checked} />{$encName}</label>\n";
407 }
408
409 $checked = $this->searchRedirects
410 ? ' checked="checked"'
411 : '';
412 $redirect = "<input type='checkbox' value='1' name=\"redirs\"{$checked} />\n";
413
414 $searchField = '<input type="text" id="powerSearchText" name="search" value="' .
415 htmlspecialchars( $term ) ."\" size=\"16\" />\n";
416
417 $searchButton = '<input type="submit" name="searchx" value="' .
418 htmlspecialchars( wfMsg('powersearch') ) . "\" />\n";
419
420 $ret = wfMsg( 'powersearchtext',
421 $namespaces, $redirect, $searchField,
422 '', '', '', '', '', # Dummy placeholders
423 $searchButton );
424
425 $title = SpecialPage::getTitleFor( 'Search' );
426 $action = $title->escapeLocalURL();
427 return "<br /><br />\n<form id=\"powersearch\" method=\"get\" " .
428 "action=\"$action\">\n{$ret}\n</form>\n";
429 }
430
431 function powerSearchFocus() {
432 return "<script type='text/javascript'>" .
433 "document.getElementById('powerSearchText').focus();" .
434 "</script>";
435 }
436 }
437
438