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