MediaWiki  1.33.0
PrefixSearch.php
Go to the documentation of this file.
1 <?php
24 
32 abstract class PrefixSearch {
43  public static function titleSearch( $search, $limit, $namespaces = [], $offset = 0 ) {
44  $prefixSearch = new StringPrefixSearch;
45  return $prefixSearch->search( $search, $limit, $namespaces, $offset );
46  }
47 
57  public function search( $search, $limit, $namespaces = [], $offset = 0 ) {
58  $search = trim( $search );
59  if ( $search == '' ) {
60  return []; // Return empty result
61  }
62 
63  $hasNamespace = SearchEngine::parseNamespacePrefixes( $search, false, true );
64  if ( $hasNamespace !== false ) {
65  list( $search, $namespaces ) = $hasNamespace;
66  }
67 
68  return $this->searchBackend( $namespaces, $search, $limit, $offset );
69  }
70 
80  public function searchWithVariants( $search, $limit, array $namespaces, $offset = 0 ) {
81  $searches = $this->search( $search, $limit, $namespaces, $offset );
82 
83  // if the content language has variants, try to retrieve fallback results
84  $fallbackLimit = $limit - count( $searches );
85  if ( $fallbackLimit > 0 ) {
86  $fallbackSearches = MediaWikiServices::getInstance()->getContentLanguage()->
87  autoConvertToAllVariants( $search );
88  $fallbackSearches = array_diff( array_unique( $fallbackSearches ), [ $search ] );
89 
90  foreach ( $fallbackSearches as $fbs ) {
91  $fallbackSearchResult = $this->search( $fbs, $fallbackLimit, $namespaces );
92  $searches = array_merge( $searches, $fallbackSearchResult );
93  $fallbackLimit -= count( $fallbackSearchResult );
94 
95  if ( $fallbackLimit == 0 ) {
96  break;
97  }
98  }
99  }
100  return $searches;
101  }
102 
110  abstract protected function titles( array $titles );
111 
120  abstract protected function strings( array $strings );
121 
130  protected function searchBackend( $namespaces, $search, $limit, $offset ) {
131  if ( count( $namespaces ) == 1 ) {
132  $ns = $namespaces[0];
133  if ( $ns == NS_MEDIA ) {
134  $namespaces = [ NS_FILE ];
135  } elseif ( $ns == NS_SPECIAL ) {
136  return $this->titles( $this->specialSearch( $search, $limit, $offset ) );
137  }
138  }
139  $srchres = [];
140  if ( Hooks::run(
141  'PrefixSearchBackend',
142  [ $namespaces, $search, $limit, &$srchres, $offset ]
143  ) ) {
144  return $this->titles( $this->defaultSearchBackend( $namespaces, $search, $limit, $offset ) );
145  }
146  return $this->strings(
147  $this->handleResultFromHook( $srchres, $namespaces, $search, $limit, $offset ) );
148  }
149 
150  private function handleResultFromHook( $srchres, $namespaces, $search, $limit, $offset ) {
151  if ( $offset === 0 ) {
152  // Only perform exact db match if offset === 0
153  // This is still far from perfect but at least we avoid returning the
154  // same title afain and again when the user is scrolling with a query
155  // that matches a title in the db.
156  $rescorer = new SearchExactMatchRescorer();
157  $srchres = $rescorer->rescore( $search, $namespaces, $srchres, $limit );
158  }
159  return $srchres;
160  }
161 
170  protected function specialSearch( $search, $limit, $offset ) {
171  $searchParts = explode( '/', $search, 2 );
172  $searchKey = $searchParts[0];
173  $subpageSearch = $searchParts[1] ?? null;
174 
175  // Handle subpage search separately.
176  $spFactory = MediaWikiServices::getInstance()->getSpecialPageFactory();
177  if ( $subpageSearch !== null ) {
178  // Try matching the full search string as a page name
179  $specialTitle = Title::makeTitleSafe( NS_SPECIAL, $searchKey );
180  if ( !$specialTitle ) {
181  return [];
182  }
183  $special = $spFactory->getPage( $specialTitle->getText() );
184  if ( $special ) {
185  $subpages = $special->prefixSearchSubpages( $subpageSearch, $limit, $offset );
186  return array_map( function ( $sub ) use ( $specialTitle ) {
187  return $specialTitle->getSubpage( $sub );
188  }, $subpages );
189  } else {
190  return [];
191  }
192  }
193 
194  # normalize searchKey, so aliases with spaces can be found - T27675
195  $contLang = MediaWikiServices::getInstance()->getContentLanguage();
196  $searchKey = str_replace( ' ', '_', $searchKey );
197  $searchKey = $contLang->caseFold( $searchKey );
198 
199  // Unlike SpecialPage itself, we want the canonical forms of both
200  // canonical and alias title forms...
201  $keys = [];
202  foreach ( $spFactory->getNames() as $page ) {
203  $keys[$contLang->caseFold( $page )] = [ 'page' => $page, 'rank' => 0 ];
204  }
205 
206  foreach ( $contLang->getSpecialPageAliases() as $page => $aliases ) {
207  if ( !in_array( $page, $spFactory->getNames() ) ) {# T22885
208  continue;
209  }
210 
211  foreach ( $aliases as $key => $alias ) {
212  $keys[$contLang->caseFold( $alias )] = [ 'page' => $alias, 'rank' => $key ];
213  }
214  }
215  ksort( $keys );
216 
217  $matches = [];
218  foreach ( $keys as $pageKey => $page ) {
219  if ( $searchKey === '' || strpos( $pageKey, $searchKey ) === 0 ) {
220  // T29671: Don't use SpecialPage::getTitleFor() here because it
221  // localizes its input leading to searches for e.g. Special:All
222  // returning Spezial:MediaWiki-Systemnachrichten and returning
223  // Spezial:Alle_Seiten twice when $wgLanguageCode == 'de'
224  $matches[$page['rank']][] = Title::makeTitleSafe( NS_SPECIAL, $page['page'] );
225 
226  if ( isset( $matches[0] ) && count( $matches[0] ) >= $limit + $offset ) {
227  // We have enough items in primary rank, no use to continue
228  break;
229  }
230  }
231 
232  }
233 
234  // Ensure keys are in order
235  ksort( $matches );
236  // Flatten the array
237  $matches = array_reduce( $matches, 'array_merge', [] );
238 
239  return array_slice( $matches, $offset, $limit );
240  }
241 
254  public function defaultSearchBackend( $namespaces, $search, $limit, $offset ) {
255  // Backwards compatability with old code. Default to NS_MAIN if no namespaces provided.
256  if ( $namespaces === null ) {
257  $namespaces = [];
258  }
259  if ( !$namespaces ) {
260  $namespaces[] = NS_MAIN;
261  }
262 
263  // Construct suitable prefix for each namespace. They differ in cases where
264  // some namespaces always capitalize and some don't.
265  $prefixes = [];
266  foreach ( $namespaces as $namespace ) {
267  // For now, if special is included, ignore the other namespaces
268  if ( $namespace == NS_SPECIAL ) {
269  return $this->specialSearch( $search, $limit, $offset );
270  }
271 
272  $title = Title::makeTitleSafe( $namespace, $search );
273  // Why does the prefix default to empty?
274  $prefix = $title ? $title->getDBkey() : '';
275  $prefixes[$prefix][] = $namespace;
276  }
277 
278  $dbr = wfGetDB( DB_REPLICA );
279  // Often there is only one prefix that applies to all requested namespaces,
280  // but sometimes there are two if some namespaces do not always capitalize.
281  $conds = [];
282  foreach ( $prefixes as $prefix => $namespaces ) {
283  $condition = [
284  'page_namespace' => $namespaces,
285  'page_title' . $dbr->buildLike( $prefix, $dbr->anyString() ),
286  ];
287  $conds[] = $dbr->makeList( $condition, LIST_AND );
288  }
289 
290  $table = 'page';
291  $fields = [ 'page_id', 'page_namespace', 'page_title' ];
292  $conds = $dbr->makeList( $conds, LIST_OR );
293  $options = [
294  'LIMIT' => $limit,
295  'ORDER BY' => [ 'page_title', 'page_namespace' ],
296  'OFFSET' => $offset
297  ];
298 
299  $res = $dbr->select( $table, $fields, $conds, __METHOD__, $options );
300 
301  return iterator_to_array( TitleArray::newFromResult( $res ) );
302  }
303 
310  protected function validateNamespaces( $namespaces ) {
311  // We will look at each given namespace against content language namespaces
312  $validNamespaces = MediaWikiServices::getInstance()->getContentLanguage()->getNamespaces();
313  if ( is_array( $namespaces ) && count( $namespaces ) > 0 ) {
314  $valid = [];
315  foreach ( $namespaces as $ns ) {
316  if ( is_numeric( $ns ) && array_key_exists( $ns, $validNamespaces ) ) {
317  $valid[] = $ns;
318  }
319  }
320  if ( count( $valid ) > 0 ) {
321  return $valid;
322  }
323  }
324 
325  return [ NS_MAIN ];
326  }
327 }
PrefixSearch\specialSearch
specialSearch( $search, $limit, $offset)
Prefix search special-case for Special: namespace.
Definition: PrefixSearch.php:170
TitleArray\newFromResult
static newFromResult( $res)
Definition: TitleArray.php:40
captcha-old.count
count
Definition: captcha-old.py:249
$namespaces
namespace and then decline to actually register it & $namespaces
Definition: hooks.txt:925
NS_FILE
const NS_FILE
Definition: Defines.php:70
PrefixSearch\handleResultFromHook
handleResultFromHook( $srchres, $namespaces, $search, $limit, $offset)
Definition: PrefixSearch.php:150
$res
$res
Definition: database.txt:21
SearchEngine\parseNamespacePrefixes
static parseNamespacePrefixes( $query, $withAllKeyword=true, $withPrefixSearchExtractNamespaceHook=false)
Parse some common prefixes: all (search everything) or namespace names.
Definition: SearchEngine.php:402
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
LIST_AND
const LIST_AND
Definition: Defines.php:43
$dbr
$dbr
Definition: testCompression.php:50
NS_MAIN
const NS_MAIN
Definition: Defines.php:64
NS_SPECIAL
const NS_SPECIAL
Definition: Defines.php:53
SearchExactMatchRescorer
An utility class to rescore search results by looking for an exact match in the db and add the page f...
Definition: SearchExactMatchRescorer.php:31
LIST_OR
const LIST_OR
Definition: Defines.php:46
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
$titles
linkcache txt The LinkCache class maintains a list of article titles and the information about whether or not the article exists in the database This is used to mark up links when displaying a page If the same link appears more than once on any page then it only has to be looked up once In most cases link lookups are done in batches with the LinkBatch class or the equivalent in so the link cache is mostly useful for short snippets of parsed and for links in the navigation areas of the skin The link cache was formerly used to track links used in a document for the purposes of updating the link tables This application is now deprecated To create a you can use the following $titles
Definition: linkcache.txt:17
PrefixSearch\searchWithVariants
searchWithVariants( $search, $limit, array $namespaces, $offset=0)
Do a prefix search for all possible variants of the prefix.
Definition: PrefixSearch.php:80
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2636
$matches
$matches
Definition: NoLocalSettings.php:24
PrefixSearch\search
search( $search, $limit, $namespaces=[], $offset=0)
Do a prefix search of titles and return a list of matching page names.
Definition: PrefixSearch.php:57
PrefixSearch\strings
strings(array $strings)
When implemented in a descendant class, receives an array of titles as strings and returns either an ...
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
PrefixSearch\titleSearch
static titleSearch( $search, $limit, $namespaces=[], $offset=0)
Do a prefix search of titles and return a list of matching page names.
Definition: PrefixSearch.php:43
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:604
NS_MEDIA
const NS_MEDIA
Definition: Defines.php:52
PrefixSearch\validateNamespaces
validateNamespaces( $namespaces)
Validate an array of numerical namespace indexes.
Definition: PrefixSearch.php:310
PrefixSearch\searchBackend
searchBackend( $namespaces, $search, $limit, $offset)
Do a prefix search of titles and return a list of matching page names.
Definition: PrefixSearch.php:130
PrefixSearch\defaultSearchBackend
defaultSearchBackend( $namespaces, $search, $limit, $offset)
Unless overridden by PrefixSearchBackend hook...
Definition: PrefixSearch.php:254
$options
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1985
PrefixSearch
Handles searching prefixes of titles and finding any page names that match.
Definition: PrefixSearch.php:32
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
$keys
$keys
Definition: testCompression.php:67
MediaWikiServices
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
StringPrefixSearch
Performs prefix search, returning strings.
Definition: StringPrefixSearch.php:28
PrefixSearch\titles
titles(array $titles)
When implemented in a descendant class, receives an array of Title objects and returns either an unmo...