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