Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / PrefixSearch.php
blob55a4f49b34615768066c86ef0664c270b7b8ae53
1 <?php
2 /**
3 * Prefix search of page names.
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.
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.
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
20 * @file
23 /**
24 * Handles searching prefixes of titles and finding any page
25 * names that match. Used largely by the OpenSearch implementation.
27 * @ingroup Search
29 abstract class PrefixSearch {
30 /**
31 * Do a prefix search of titles and return a list of matching page names.
32 * @deprecated Since 1.23, use TitlePrefixSearch or StringPrefixSearch classes
34 * @param string $search
35 * @param int $limit
36 * @param array $namespaces Used if query is not explicitly prefixed
37 * @param int $offset How many results to offset from the beginning
38 * @return array Array of strings
40 public static function titleSearch( $search, $limit, $namespaces = array(), $offset = 0 ) {
41 $prefixSearch = new StringPrefixSearch;
42 return $prefixSearch->search( $search, $limit, $namespaces, $offset );
45 /**
46 * Do a prefix search of titles and return a list of matching page names.
48 * @param string $search
49 * @param int $limit
50 * @param array $namespaces Used if query is not explicitly prefixed
51 * @param int $offset How many results to offset from the beginning
52 * @return array Array of strings or Title objects
54 public function search( $search, $limit, $namespaces = array(), $offset = 0 ) {
55 $search = trim( $search );
56 if ( $search == '' ) {
57 return array(); // Return empty result
59 $namespaces = $this->validateNamespaces( $namespaces );
61 // Find a Title which is not an interwiki and is in NS_MAIN
62 $title = Title::newFromText( $search );
63 if ( $title && !$title->isExternal() ) {
64 $ns = array( $title->getNamespace() );
65 $search = $title->getText();
66 if ( $ns[0] == NS_MAIN ) {
67 $ns = $namespaces; // no explicit prefix, use default namespaces
68 Hooks::run( 'PrefixSearchExtractNamespace', array( &$ns, &$search ) );
70 return $this->searchBackend( $ns, $search, $limit, $offset );
73 // Is this a namespace prefix?
74 $title = Title::newFromText( $search . 'Dummy' );
75 if ( $title && $title->getText() == 'Dummy'
76 && $title->getNamespace() != NS_MAIN
77 && !$title->isExternal() )
79 $namespaces = array( $title->getNamespace() );
80 $search = '';
81 } else {
82 Hooks::run( 'PrefixSearchExtractNamespace', array( &$namespaces, &$search ) );
85 return $this->searchBackend( $namespaces, $search, $limit, $offset );
88 /**
89 * Do a prefix search for all possible variants of the prefix
90 * @param string $search
91 * @param int $limit
92 * @param array $namespaces
93 * @param int $offset How many results to offset from the beginning
95 * @return array
97 public function searchWithVariants( $search, $limit, array $namespaces, $offset = 0 ) {
98 $searches = $this->search( $search, $limit, $namespaces, $offset );
100 // if the content language has variants, try to retrieve fallback results
101 $fallbackLimit = $limit - count( $searches );
102 if ( $fallbackLimit > 0 ) {
103 global $wgContLang;
105 $fallbackSearches = $wgContLang->autoConvertToAllVariants( $search );
106 $fallbackSearches = array_diff( array_unique( $fallbackSearches ), array( $search ) );
108 foreach ( $fallbackSearches as $fbs ) {
109 $fallbackSearchResult = $this->search( $fbs, $fallbackLimit, $namespaces );
110 $searches = array_merge( $searches, $fallbackSearchResult );
111 $fallbackLimit -= count( $fallbackSearchResult );
113 if ( $fallbackLimit == 0 ) {
114 break;
118 return $searches;
122 * When implemented in a descendant class, receives an array of Title objects and returns
123 * either an unmodified array or an array of strings corresponding to titles passed to it.
125 * @param array $titles
126 * @return array
128 abstract protected function titles( array $titles );
131 * When implemented in a descendant class, receives an array of titles as strings and returns
132 * either an unmodified array or an array of Title objects corresponding to strings received.
134 * @param array $strings
136 * @return array
138 abstract protected function strings( array $strings );
141 * Do a prefix search of titles and return a list of matching page names.
142 * @param array $namespaces
143 * @param string $search
144 * @param int $limit
145 * @param int $offset How many results to offset from the beginning
146 * @return array Array of strings
148 protected function searchBackend( $namespaces, $search, $limit, $offset ) {
149 if ( count( $namespaces ) == 1 ) {
150 $ns = $namespaces[0];
151 if ( $ns == NS_MEDIA ) {
152 $namespaces = array( NS_FILE );
153 } elseif ( $ns == NS_SPECIAL ) {
154 return $this->titles( $this->specialSearch( $search, $limit, $offset ) );
157 $srchres = array();
158 if ( Hooks::run(
159 'PrefixSearchBackend',
160 array( $namespaces, $search, $limit, &$srchres, $offset )
161 ) ) {
162 return $this->titles( $this->defaultSearchBackend( $namespaces, $search, $limit, $offset ) );
164 return $this->strings( $this->handleResultFromHook( $srchres, $namespaces, $search, $limit ) );
168 * Default search backend does proper prefix searching, but custom backends
169 * may sort based on other algorythms that may cause the exact title match
170 * to not be in the results or be lower down the list.
171 * @param array $srchres results from the hook
172 * @return array munged results from the hook
174 private function handleResultFromHook( $srchres, $namespaces, $search, $limit ) {
175 // Pick namespace (based on PrefixSearch::defaultSearchBackend)
176 $ns = in_array( NS_MAIN, $namespaces ) ? NS_MAIN : $namespaces[0];
177 $t = Title::newFromText( $search, $ns );
178 if ( !$t || !$t->exists() ) {
179 // No exact match so just return the search results
180 return $srchres;
182 $string = $t->getPrefixedText();
183 $key = array_search( $string, $srchres );
184 if ( $key !== false ) {
185 // Exact match was in the results so just move it to the front
186 return $this->pullFront( $key, $srchres );
188 // Exact match not in the search results so check for some redirect handling cases
189 if ( $t->isRedirect() ) {
190 $target = $this->getRedirectTarget( $t );
191 $key = array_search( $target, $srchres );
192 if ( $key !== false ) {
193 // Exact match is a redirect to one of the returned matches so pull the
194 // returned match to the front. This might look odd but the alternative
195 // is to put the redirect in front and drop the match. The name of the
196 // found match is often more descriptive/better formed than the name of
197 // the redirect AND by definition they share a prefix. Hopefully this
198 // choice is less confusing and more helpful. But it might not be. But
199 // it is the choice we're going with for now.
200 return $this->pullFront( $key, $srchres );
202 $redirectTargetsToRedirect = $this->redirectTargetsToRedirect( $srchres );
203 if ( isset( $redirectTargetsToRedirect[$target] ) ) {
204 // The exact match and something in the results list are both redirects
205 // to the same thing! In this case we'll pull the returned match to the
206 // top following the same logic above. Again, it might not be a perfect
207 // choice but it'll do.
208 return $this->pullFront( $redirectTargetsToRedirect[$target], $srchres );
210 } else {
211 $redirectTargetsToRedirect = $this->redirectTargetsToRedirect( $srchres );
212 if ( isset( $redirectTargetsToRedirect[$string] ) ) {
213 // The exact match is the target of a redirect already in the results list so remove
214 // the redirect from the results list and push the exact match to the front
215 array_splice( $srchres, $redirectTargetsToRedirect[$string], 1 );
216 array_unshift( $srchres, $string );
217 return $srchres;
221 // Exact match is totally unique from the other results so just add it to the front
222 array_unshift( $srchres, $string );
223 // And roll one off the end if the results are too long
224 if ( count( $srchres ) > $limit ) {
225 array_pop( $srchres );
227 return $srchres;
231 * @param Array(string) $titles as strings
232 * @return Array(string => int) redirect target prefixedText to index of title in titles
233 * that is a redirect to it.
235 private function redirectTargetsToRedirect( $titles ) {
236 $result = array();
237 foreach ( $titles as $key => $titleText ) {
238 $title = Title::newFromText( $titleText );
239 if ( !$title || !$title->isRedirect() ) {
240 continue;
242 $target = $this->getRedirectTarget( $title );
243 if ( !$target ) {
244 continue;
246 $result[$target] = $key;
248 return $result;
252 * @param int $key key to pull to the front
253 * @return array $array with the item at $key pulled to the front
255 private function pullFront( $key, $array ) {
256 $cut = array_splice( $array, $key, 1 );
257 array_unshift( $array, $cut[0] );
258 return $array;
261 private function getRedirectTarget( $title ) {
262 $page = WikiPage::factory( $title );
263 if ( !$page->exists() ) {
264 return null;
266 return $page->getRedirectTarget()->getPrefixedText();
270 * Prefix search special-case for Special: namespace.
272 * @param string $search Term
273 * @param int $limit Max number of items to return
274 * @param int $offset Number of items to offset
275 * @return array
277 protected function specialSearch( $search, $limit, $offset ) {
278 global $wgContLang;
280 $searchParts = explode( '/', $search, 2 );
281 $searchKey = $searchParts[0];
282 $subpageSearch = isset( $searchParts[1] ) ? $searchParts[1] : null;
284 // Handle subpage search separately.
285 if ( $subpageSearch !== null ) {
286 // Try matching the full search string as a page name
287 $specialTitle = Title::makeTitleSafe( NS_SPECIAL, $searchKey );
288 if ( !$specialTitle ) {
289 return array();
291 $special = SpecialPageFactory::getPage( $specialTitle->getText() );
292 if ( $special ) {
293 $subpages = $special->prefixSearchSubpages( $subpageSearch, $limit, $offset );
294 return array_map( function ( $sub ) use ( $specialTitle ) {
295 return $specialTitle->getSubpage( $sub );
296 }, $subpages );
297 } else {
298 return array();
302 # normalize searchKey, so aliases with spaces can be found - bug 25675
303 $searchKey = str_replace( ' ', '_', $searchKey );
304 $searchKey = $wgContLang->caseFold( $searchKey );
306 // Unlike SpecialPage itself, we want the canonical forms of both
307 // canonical and alias title forms...
308 $keys = array();
309 foreach ( SpecialPageFactory::getNames() as $page ) {
310 $keys[$wgContLang->caseFold( $page )] = $page;
313 foreach ( $wgContLang->getSpecialPageAliases() as $page => $aliases ) {
314 if ( !in_array( $page, SpecialPageFactory::getNames() ) ) {# bug 20885
315 continue;
318 foreach ( $aliases as $alias ) {
319 $keys[$wgContLang->caseFold( $alias )] = $alias;
322 ksort( $keys );
324 $srchres = array();
325 $skipped = 0;
326 foreach ( $keys as $pageKey => $page ) {
327 if ( $searchKey === '' || strpos( $pageKey, $searchKey ) === 0 ) {
328 // bug 27671: Don't use SpecialPage::getTitleFor() here because it
329 // localizes its input leading to searches for e.g. Special:All
330 // returning Spezial:MediaWiki-Systemnachrichten and returning
331 // Spezial:Alle_Seiten twice when $wgLanguageCode == 'de'
332 if ( $offset > 0 && $skipped < $offset ) {
333 $skipped++;
334 continue;
336 $srchres[] = Title::makeTitleSafe( NS_SPECIAL, $page );
339 if ( count( $srchres ) >= $limit ) {
340 break;
344 return $srchres;
348 * Unless overridden by PrefixSearchBackend hook...
349 * This is case-sensitive (First character may
350 * be automatically capitalized by Title::secureAndSpit()
351 * later on depending on $wgCapitalLinks)
353 * @param array $namespaces Namespaces to search in
354 * @param string $search Term
355 * @param int $limit Max number of items to return
356 * @param int $offset Number of items to skip
357 * @return array Array of Title objects
359 protected function defaultSearchBackend( $namespaces, $search, $limit, $offset ) {
360 $ns = array_shift( $namespaces ); // support only one namespace
361 if ( in_array( NS_MAIN, $namespaces ) ) {
362 $ns = NS_MAIN; // if searching on many always default to main
365 $t = Title::newFromText( $search, $ns );
366 $prefix = $t ? $t->getDBkey() : '';
367 $dbr = wfGetDB( DB_SLAVE );
368 $res = $dbr->select( 'page',
369 array( 'page_id', 'page_namespace', 'page_title' ),
370 array(
371 'page_namespace' => $ns,
372 'page_title ' . $dbr->buildLike( $prefix, $dbr->anyString() )
374 __METHOD__,
375 array(
376 'LIMIT' => $limit,
377 'ORDER BY' => 'page_title',
378 'OFFSET' => $offset
381 $srchres = array();
382 foreach ( $res as $row ) {
383 $srchres[] = Title::newFromRow( $row );
385 return $srchres;
389 * Validate an array of numerical namespace indexes
391 * @param array $namespaces
392 * @return array (default: contains only NS_MAIN)
394 protected function validateNamespaces( $namespaces ) {
395 global $wgContLang;
397 // We will look at each given namespace against wgContLang namespaces
398 $validNamespaces = $wgContLang->getNamespaces();
399 if ( is_array( $namespaces ) && count( $namespaces ) > 0 ) {
400 $valid = array();
401 foreach ( $namespaces as $ns ) {
402 if ( is_numeric( $ns ) && array_key_exists( $ns, $validNamespaces ) ) {
403 $valid[] = $ns;
406 if ( count( $valid ) > 0 ) {
407 return $valid;
411 return array( NS_MAIN );
416 * Performs prefix search, returning Title objects
417 * @ingroup Search
419 class TitlePrefixSearch extends PrefixSearch {
421 protected function titles( array $titles ) {
422 return $titles;
425 protected function strings( array $strings ) {
426 $titles = array_map( 'Title::newFromText', $strings );
427 $lb = new LinkBatch( $titles );
428 $lb->setCaller( __METHOD__ );
429 $lb->execute();
430 return $titles;
435 * Performs prefix search, returning strings
436 * @ingroup Search
438 class StringPrefixSearch extends PrefixSearch {
440 protected function titles( array $titles ) {
441 return array_map( function ( Title $t ) {
442 return $t->getPrefixedText();
443 }, $titles );
446 protected function strings( array $strings ) {
447 return $strings;