MediaWiki  master
PrefixSearch.php
Go to the documentation of this file.
1 <?php
24 
32 abstract class PrefixSearch {
42  public function search( $search, $limit, $namespaces = [], $offset = 0 ) {
43  $search = trim( $search );
44  if ( $search == '' ) {
45  return []; // Return empty result
46  }
47 
48  $hasNamespace = SearchEngine::parseNamespacePrefixes( $search, false, true );
49  if ( $hasNamespace !== false ) {
50  list( $search, $namespaces ) = $hasNamespace;
51  }
52 
53  return $this->searchBackend( $namespaces, $search, $limit, $offset );
54  }
55 
65  public function searchWithVariants( $search, $limit, array $namespaces, $offset = 0 ) {
66  $searches = $this->search( $search, $limit, $namespaces, $offset );
67 
68  // if the content language has variants, try to retrieve fallback results
69  $fallbackLimit = $limit - count( $searches );
70  if ( $fallbackLimit > 0 ) {
71  $fallbackSearches = MediaWikiServices::getInstance()->getContentLanguage()->
72  autoConvertToAllVariants( $search );
73  $fallbackSearches = array_diff( array_unique( $fallbackSearches ), [ $search ] );
74 
75  foreach ( $fallbackSearches as $fbs ) {
76  $fallbackSearchResult = $this->search( $fbs, $fallbackLimit, $namespaces );
77  $searches = array_merge( $searches, $fallbackSearchResult );
78  $fallbackLimit -= count( $fallbackSearchResult );
79 
80  if ( $fallbackLimit == 0 ) {
81  break;
82  }
83  }
84  }
85  return $searches;
86  }
87 
95  abstract protected function titles( array $titles );
96 
105  abstract protected function strings( array $strings );
106 
115  protected function searchBackend( $namespaces, $search, $limit, $offset ) {
116  if ( count( $namespaces ) == 1 ) {
117  $ns = $namespaces[0];
118  if ( $ns == NS_MEDIA ) {
119  $namespaces = [ NS_FILE ];
120  } elseif ( $ns == NS_SPECIAL ) {
121  return $this->titles( $this->specialSearch( $search, $limit, $offset ) );
122  }
123  }
124  $srchres = [];
125  if ( Hooks::runner()->onPrefixSearchBackend(
126  $namespaces, $search, $limit, $srchres, $offset )
127  ) {
128  return $this->titles( $this->defaultSearchBackend( $namespaces, $search, $limit, $offset ) );
129  }
130  return $this->strings(
131  $this->handleResultFromHook( $srchres, $namespaces, $search, $limit, $offset ) );
132  }
133 
134  private function handleResultFromHook( $srchres, $namespaces, $search, $limit, $offset ) {
135  if ( $offset === 0 ) {
136  // Only perform exact db match if offset === 0
137  // This is still far from perfect but at least we avoid returning the
138  // same title afain and again when the user is scrolling with a query
139  // that matches a title in the db.
140  $rescorer = new SearchExactMatchRescorer();
141  $srchres = $rescorer->rescore( $search, $namespaces, $srchres, $limit );
142  }
143  return $srchres;
144  }
145 
154  protected function specialSearch( $search, $limit, $offset ) {
155  $searchParts = explode( '/', $search, 2 );
156  $searchKey = $searchParts[0];
157  $subpageSearch = $searchParts[1] ?? null;
158 
159  // Handle subpage search separately.
160  $spFactory = MediaWikiServices::getInstance()->getSpecialPageFactory();
161  if ( $subpageSearch !== null ) {
162  // Try matching the full search string as a page name
163  $specialTitle = Title::makeTitleSafe( NS_SPECIAL, $searchKey );
164  if ( !$specialTitle ) {
165  return [];
166  }
167  $special = $spFactory->getPage( $specialTitle->getText() );
168  if ( $special ) {
169  $subpages = $special->prefixSearchSubpages( $subpageSearch, $limit, $offset );
170  return array_map( function ( $sub ) use ( $specialTitle ) {
171  return $specialTitle->getSubpage( $sub );
172  }, $subpages );
173  } else {
174  return [];
175  }
176  }
177 
178  # normalize searchKey, so aliases with spaces can be found - T27675
179  $contLang = MediaWikiServices::getInstance()->getContentLanguage();
180  $searchKey = str_replace( ' ', '_', $searchKey );
181  $searchKey = $contLang->caseFold( $searchKey );
182 
183  // Unlike SpecialPage itself, we want the canonical forms of both
184  // canonical and alias title forms...
185  $keys = [];
186  foreach ( $spFactory->getNames() as $page ) {
187  $keys[$contLang->caseFold( $page )] = [ 'page' => $page, 'rank' => 0 ];
188  }
189 
190  foreach ( $contLang->getSpecialPageAliases() as $page => $aliases ) {
191  if ( !in_array( $page, $spFactory->getNames() ) ) {# T22885
192  continue;
193  }
194 
195  foreach ( $aliases as $key => $alias ) {
196  $keys[$contLang->caseFold( $alias )] = [ 'page' => $alias, 'rank' => $key ];
197  }
198  }
199  ksort( $keys );
200 
201  $matches = [];
202  foreach ( $keys as $pageKey => $page ) {
203  if ( $searchKey === '' || strpos( $pageKey, $searchKey ) === 0 ) {
204  // T29671: Don't use SpecialPage::getTitleFor() here because it
205  // localizes its input leading to searches for e.g. Special:All
206  // returning Spezial:MediaWiki-Systemnachrichten and returning
207  // Spezial:Alle_Seiten twice when $wgLanguageCode == 'de'
208  $matches[$page['rank']][] = Title::makeTitleSafe( NS_SPECIAL, $page['page'] );
209 
210  if ( isset( $matches[0] ) && count( $matches[0] ) >= $limit + $offset ) {
211  // We have enough items in primary rank, no use to continue
212  break;
213  }
214  }
215 
216  }
217 
218  // Ensure keys are in order
219  ksort( $matches );
220  // Flatten the array
221  $matches = array_reduce( $matches, 'array_merge', [] );
222 
223  return array_slice( $matches, $offset, $limit );
224  }
225 
238  public function defaultSearchBackend( $namespaces, $search, $limit, $offset ) {
239  // Backwards compatability with old code. Default to NS_MAIN if no namespaces provided.
240  if ( $namespaces === null ) {
241  $namespaces = [];
242  }
243  if ( !$namespaces ) {
244  $namespaces[] = NS_MAIN;
245  }
246 
247  // Construct suitable prefix for each namespace. They differ in cases where
248  // some namespaces always capitalize and some don't.
249  $prefixes = [];
250  foreach ( $namespaces as $namespace ) {
251  // For now, if special is included, ignore the other namespaces
252  if ( $namespace == NS_SPECIAL ) {
253  return $this->specialSearch( $search, $limit, $offset );
254  }
255 
256  $title = Title::makeTitleSafe( $namespace, $search );
257  // Why does the prefix default to empty?
258  $prefix = $title ? $title->getDBkey() : '';
259  $prefixes[$prefix][] = $namespace;
260  }
261 
262  $dbr = wfGetDB( DB_REPLICA );
263  // Often there is only one prefix that applies to all requested namespaces,
264  // but sometimes there are two if some namespaces do not always capitalize.
265  $conds = [];
266  foreach ( $prefixes as $prefix => $namespaces ) {
267  $condition = [
268  'page_namespace' => $namespaces,
269  'page_title' . $dbr->buildLike( $prefix, $dbr->anyString() ),
270  ];
271  $conds[] = $dbr->makeList( $condition, LIST_AND );
272  }
273 
274  $table = 'page';
275  $fields = [ 'page_id', 'page_namespace', 'page_title' ];
276  $conds = $dbr->makeList( $conds, LIST_OR );
277  $options = [
278  'LIMIT' => $limit,
279  'ORDER BY' => [ 'page_title', 'page_namespace' ],
280  'OFFSET' => $offset
281  ];
282 
283  $res = $dbr->select( $table, $fields, $conds, __METHOD__, $options );
284 
285  return iterator_to_array( TitleArray::newFromResult( $res ) );
286  }
287 
294  protected function validateNamespaces( $namespaces ) {
295  // We will look at each given namespace against content language namespaces
296  $validNamespaces = MediaWikiServices::getInstance()->getContentLanguage()->getNamespaces();
297  if ( is_array( $namespaces ) && count( $namespaces ) > 0 ) {
298  $valid = [];
299  foreach ( $namespaces as $ns ) {
300  if ( is_numeric( $ns ) && array_key_exists( $ns, $validNamespaces ) ) {
301  $valid[] = $ns;
302  }
303  }
304  if ( count( $valid ) > 0 ) {
305  return $valid;
306  }
307  }
308 
309  return [ NS_MAIN ];
310  }
311 }
PrefixSearch\specialSearch
specialSearch( $search, $limit, $offset)
Prefix search special-case for Special: namespace.
Definition: PrefixSearch.php:154
TitleArray\newFromResult
static newFromResult( $res)
Definition: TitleArray.php:42
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:146
NS_FILE
const NS_FILE
Definition: Defines.php:75
PrefixSearch\handleResultFromHook
handleResultFromHook( $srchres, $namespaces, $search, $limit, $offset)
Definition: PrefixSearch.php:134
SearchEngine\parseNamespacePrefixes
static parseNamespacePrefixes( $query, $withAllKeyword=true, $withPrefixSearchExtractNamespaceHook=false)
Parse some common prefixes: all (search everything) or namespace names.
Definition: SearchEngine.php:388
$res
$res
Definition: testCompression.php:57
LIST_AND
const LIST_AND
Definition: Defines.php:48
$dbr
$dbr
Definition: testCompression.php:54
NS_MAIN
const NS_MAIN
Definition: Defines.php:69
NS_SPECIAL
const NS_SPECIAL
Definition: Defines.php:58
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:51
PrefixSearch\searchWithVariants
searchWithVariants( $search, $limit, array $namespaces, $offset=0)
Do a prefix search for all possible variants of the prefix.
Definition: PrefixSearch.php:65
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2463
$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:42
PrefixSearch\strings
strings(array $strings)
When implemented in a descendant class, receives an array of titles as strings and returns either an ...
$title
$title
Definition: testCompression.php:38
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:621
NS_MEDIA
const NS_MEDIA
Definition: Defines.php:57
Hooks\runner
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition: Hooks.php:171
PrefixSearch\validateNamespaces
validateNamespaces( $namespaces)
Validate an array of numerical namespace indexes.
Definition: PrefixSearch.php:294
PrefixSearch\searchBackend
searchBackend( $namespaces, $search, $limit, $offset)
Do a prefix search of titles and return a list of matching page names.
Definition: PrefixSearch.php:115
PrefixSearch\defaultSearchBackend
defaultSearchBackend( $namespaces, $search, $limit, $offset)
Unless overridden by PrefixSearchBackend hook...
Definition: PrefixSearch.php:238
PrefixSearch
Handles searching prefixes of titles and finding any page names that match.
Definition: PrefixSearch.php:32
$keys
$keys
Definition: testCompression.php:72
PrefixSearch\titles
titles(array $titles)
When implemented in a descendant class, receives an array of Title objects and returns either an unmo...