MediaWiki  master
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  wfDeprecated( __METHOD__, '1.23' );
45  $prefixSearch = new StringPrefixSearch;
46  return $prefixSearch->search( $search, $limit, $namespaces, $offset );
47  }
48 
58  public function search( $search, $limit, $namespaces = [], $offset = 0 ) {
59  $search = trim( $search );
60  if ( $search == '' ) {
61  return []; // Return empty result
62  }
63 
64  $hasNamespace = SearchEngine::parseNamespacePrefixes( $search, false, true );
65  if ( $hasNamespace !== false ) {
66  list( $search, $namespaces ) = $hasNamespace;
67  }
68 
69  return $this->searchBackend( $namespaces, $search, $limit, $offset );
70  }
71 
81  public function searchWithVariants( $search, $limit, array $namespaces, $offset = 0 ) {
82  $searches = $this->search( $search, $limit, $namespaces, $offset );
83 
84  // if the content language has variants, try to retrieve fallback results
85  $fallbackLimit = $limit - count( $searches );
86  if ( $fallbackLimit > 0 ) {
87  $fallbackSearches = MediaWikiServices::getInstance()->getContentLanguage()->
88  autoConvertToAllVariants( $search );
89  $fallbackSearches = array_diff( array_unique( $fallbackSearches ), [ $search ] );
90 
91  foreach ( $fallbackSearches as $fbs ) {
92  $fallbackSearchResult = $this->search( $fbs, $fallbackLimit, $namespaces );
93  $searches = array_merge( $searches, $fallbackSearchResult );
94  $fallbackLimit -= count( $fallbackSearchResult );
95 
96  if ( $fallbackLimit == 0 ) {
97  break;
98  }
99  }
100  }
101  return $searches;
102  }
103 
111  abstract protected function titles( array $titles );
112 
121  abstract protected function strings( array $strings );
122 
131  protected function searchBackend( $namespaces, $search, $limit, $offset ) {
132  if ( count( $namespaces ) == 1 ) {
133  $ns = $namespaces[0];
134  if ( $ns == NS_MEDIA ) {
135  $namespaces = [ NS_FILE ];
136  } elseif ( $ns == NS_SPECIAL ) {
137  return $this->titles( $this->specialSearch( $search, $limit, $offset ) );
138  }
139  }
140  $srchres = [];
141  if ( Hooks::run(
142  'PrefixSearchBackend',
143  [ $namespaces, $search, $limit, &$srchres, $offset ]
144  ) ) {
145  return $this->titles( $this->defaultSearchBackend( $namespaces, $search, $limit, $offset ) );
146  }
147  return $this->strings(
148  $this->handleResultFromHook( $srchres, $namespaces, $search, $limit, $offset ) );
149  }
150 
151  private function handleResultFromHook( $srchres, $namespaces, $search, $limit, $offset ) {
152  if ( $offset === 0 ) {
153  // Only perform exact db match if offset === 0
154  // This is still far from perfect but at least we avoid returning the
155  // same title afain and again when the user is scrolling with a query
156  // that matches a title in the db.
157  $rescorer = new SearchExactMatchRescorer();
158  $srchres = $rescorer->rescore( $search, $namespaces, $srchres, $limit );
159  }
160  return $srchres;
161  }
162 
171  protected function specialSearch( $search, $limit, $offset ) {
172  $searchParts = explode( '/', $search, 2 );
173  $searchKey = $searchParts[0];
174  $subpageSearch = $searchParts[1] ?? null;
175 
176  // Handle subpage search separately.
177  $spFactory = MediaWikiServices::getInstance()->getSpecialPageFactory();
178  if ( $subpageSearch !== null ) {
179  // Try matching the full search string as a page name
180  $specialTitle = Title::makeTitleSafe( NS_SPECIAL, $searchKey );
181  if ( !$specialTitle ) {
182  return [];
183  }
184  $special = $spFactory->getPage( $specialTitle->getText() );
185  if ( $special ) {
186  $subpages = $special->prefixSearchSubpages( $subpageSearch, $limit, $offset );
187  return array_map( function ( $sub ) use ( $specialTitle ) {
188  return $specialTitle->getSubpage( $sub );
189  }, $subpages );
190  } else {
191  return [];
192  }
193  }
194 
195  # normalize searchKey, so aliases with spaces can be found - T27675
196  $contLang = MediaWikiServices::getInstance()->getContentLanguage();
197  $searchKey = str_replace( ' ', '_', $searchKey );
198  $searchKey = $contLang->caseFold( $searchKey );
199 
200  // Unlike SpecialPage itself, we want the canonical forms of both
201  // canonical and alias title forms...
202  $keys = [];
203  foreach ( $spFactory->getNames() as $page ) {
204  $keys[$contLang->caseFold( $page )] = [ 'page' => $page, 'rank' => 0 ];
205  }
206 
207  foreach ( $contLang->getSpecialPageAliases() as $page => $aliases ) {
208  if ( !in_array( $page, $spFactory->getNames() ) ) {# T22885
209  continue;
210  }
211 
212  foreach ( $aliases as $key => $alias ) {
213  $keys[$contLang->caseFold( $alias )] = [ 'page' => $alias, 'rank' => $key ];
214  }
215  }
216  ksort( $keys );
217 
218  $matches = [];
219  foreach ( $keys as $pageKey => $page ) {
220  if ( $searchKey === '' || strpos( $pageKey, $searchKey ) === 0 ) {
221  // T29671: Don't use SpecialPage::getTitleFor() here because it
222  // localizes its input leading to searches for e.g. Special:All
223  // returning Spezial:MediaWiki-Systemnachrichten and returning
224  // Spezial:Alle_Seiten twice when $wgLanguageCode == 'de'
225  $matches[$page['rank']][] = Title::makeTitleSafe( NS_SPECIAL, $page['page'] );
226 
227  if ( isset( $matches[0] ) && count( $matches[0] ) >= $limit + $offset ) {
228  // We have enough items in primary rank, no use to continue
229  break;
230  }
231  }
232 
233  }
234 
235  // Ensure keys are in order
236  ksort( $matches );
237  // Flatten the array
238  $matches = array_reduce( $matches, 'array_merge', [] );
239 
240  return array_slice( $matches, $offset, $limit );
241  }
242 
255  public function defaultSearchBackend( $namespaces, $search, $limit, $offset ) {
256  // Backwards compatability with old code. Default to NS_MAIN if no namespaces provided.
257  if ( $namespaces === null ) {
258  $namespaces = [];
259  }
260  if ( !$namespaces ) {
261  $namespaces[] = NS_MAIN;
262  }
263 
264  // Construct suitable prefix for each namespace. They differ in cases where
265  // some namespaces always capitalize and some don't.
266  $prefixes = [];
267  foreach ( $namespaces as $namespace ) {
268  // For now, if special is included, ignore the other namespaces
269  if ( $namespace == NS_SPECIAL ) {
270  return $this->specialSearch( $search, $limit, $offset );
271  }
272 
273  $title = Title::makeTitleSafe( $namespace, $search );
274  // Why does the prefix default to empty?
275  $prefix = $title ? $title->getDBkey() : '';
276  $prefixes[$prefix][] = $namespace;
277  }
278 
279  $dbr = wfGetDB( DB_REPLICA );
280  // Often there is only one prefix that applies to all requested namespaces,
281  // but sometimes there are two if some namespaces do not always capitalize.
282  $conds = [];
283  foreach ( $prefixes as $prefix => $namespaces ) {
284  $condition = [
285  'page_namespace' => $namespaces,
286  'page_title' . $dbr->buildLike( $prefix, $dbr->anyString() ),
287  ];
288  $conds[] = $dbr->makeList( $condition, LIST_AND );
289  }
290 
291  $table = 'page';
292  $fields = [ 'page_id', 'page_namespace', 'page_title' ];
293  $conds = $dbr->makeList( $conds, LIST_OR );
294  $options = [
295  'LIMIT' => $limit,
296  'ORDER BY' => [ 'page_title', 'page_namespace' ],
297  'OFFSET' => $offset
298  ];
299 
300  $res = $dbr->select( $table, $fields, $conds, __METHOD__, $options );
301 
302  return iterator_to_array( TitleArray::newFromResult( $res ) );
303  }
304 
311  protected function validateNamespaces( $namespaces ) {
312  // We will look at each given namespace against content language namespaces
313  $validNamespaces = MediaWikiServices::getInstance()->getContentLanguage()->getNamespaces();
314  if ( is_array( $namespaces ) && count( $namespaces ) > 0 ) {
315  $valid = [];
316  foreach ( $namespaces as $ns ) {
317  if ( is_numeric( $ns ) && array_key_exists( $ns, $validNamespaces ) ) {
318  $valid[] = $ns;
319  }
320  }
321  if ( count( $valid ) > 0 ) {
322  return $valid;
323  }
324  }
325 
326  return [ NS_MAIN ];
327  }
328 }
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))
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
Performs prefix search, returning strings.
const NS_MAIN
Definition: Defines.php:60
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
static parseNamespacePrefixes( $query, $withAllKeyword=true, $withPrefixSearchExtractNamespaceHook=false)
Parse some common prefixes: all (search everything) or namespace names.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
specialSearch( $search, $limit, $offset)
Prefix search special-case for Special: namespace.
const NS_SPECIAL
Definition: Defines.php:49
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
strings(array $strings)
When implemented in a descendant class, receives an array of titles as strings and returns either an ...
static titleSearch( $search, $limit, $namespaces=[], $offset=0)
Do a prefix search of titles and return a list of matching page names.
const LIST_AND
Definition: Defines.php:39
const NS_MEDIA
Definition: Defines.php:48
$res
Definition: database.txt:21
An utility class to rescore search results by looking for an exact match in the db and add the page f...
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:1982
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
static newFromResult( $res)
Definition: TitleArray.php:40
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
searchBackend( $namespaces, $search, $limit, $offset)
Do a prefix search of titles and return a list of matching page names.
const NS_FILE
Definition: Defines.php:66
namespace and then decline to actually register it & $namespaces
Definition: hooks.txt:925
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
Handles searching prefixes of titles and finding any page names that match.
const LIST_OR
Definition: Defines.php:42
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:617
search( $search, $limit, $namespaces=[], $offset=0)
Do a prefix search of titles and return a list of matching page names.
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
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
handleResultFromHook( $srchres, $namespaces, $search, $limit, $offset)
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
titles(array $titles)
When implemented in a descendant class, receives an array of Title objects and returns either an unmo...
validateNamespaces( $namespaces)
Validate an array of numerical namespace indexes.
const DB_REPLICA
Definition: defines.php:25
defaultSearchBackend( $namespaces, $search, $limit, $offset)
Unless overridden by PrefixSearchBackend hook...
searchWithVariants( $search, $limit, array $namespaces, $offset=0)
Do a prefix search for all possible variants of the prefix.
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
$matches