MediaWiki  master
SearchResultSet.php
Go to the documentation of this file.
1 <?php
27 class SearchResultSet implements Countable, IteratorAggregate {
28 
33  const SECONDARY_RESULTS = 0;
34 
39  const INLINE_RESULTS = 1;
40 
41  protected $containedSyntax = false;
42 
48  private $titles;
49 
55  protected $results;
56 
64  protected $extraData = [];
65 
69  private $hasMoreResults;
70 
74  private $bcIterator;
75 
82  public function __construct( $containedSyntax = false, $hasMoreResults = false ) {
83  if ( static::class === self::class ) {
84  // This class will eventually be abstract. SearchEngine implementations
85  // already have to extend this class anyways to provide the actual
86  // search results.
87  wfDeprecated( __METHOD__, 1.32 );
88  }
89  $this->containedSyntax = $containedSyntax;
91  }
92 
100  function termMatches() {
101  return [];
102  }
103 
104  function numRows() {
105  return $this->count();
106  }
107 
108  final public function count() {
109  return count( $this->extractResults() );
110  }
111 
122  function getTotalHits() {
123  return null;
124  }
125 
133  function hasRewrittenQuery() {
134  return false;
135  }
136 
141  function getQueryAfterRewrite() {
142  return null;
143  }
144 
150  return null;
151  }
152 
159  function hasSuggestion() {
160  return false;
161  }
162 
166  function getSuggestionQuery() {
167  return null;
168  }
169 
173  function getSuggestionSnippet() {
174  return '';
175  }
176 
183  function getInterwikiResults( $type = self::SECONDARY_RESULTS ) {
184  return null;
185  }
186 
193  function hasInterwikiResults( $type = self::SECONDARY_RESULTS ) {
194  return false;
195  }
196 
202  public function next() {
203  wfDeprecated( __METHOD__, '1.32' );
204  $it = $this->bcIterator();
205  $searchResult = $it->current();
206  $it->next();
207  return $searchResult ?? false;
208  }
209 
214  public function rewind() {
215  wfDeprecated( __METHOD__, '1.32' );
216  $this->bcIterator()->rewind();
217  }
218 
219  private function bcIterator() {
220  if ( $this->bcIterator === null ) {
221  $this->bcIterator = 'RECURSION';
222  $this->bcIterator = $this->getIterator();
223  } elseif ( $this->bcIterator === 'RECURSION' ) {
224  // Either next/rewind or extractResults must be implemented. This
225  // class was potentially instantiated directly. It should be
226  // abstract with abstract methods to enforce this but that's a
227  // breaking change...
228  wfDeprecated( static::class . ' without implementing extractResults', '1.32' );
229  $this->bcIterator = new ArrayIterator( [] );
230  }
231  return $this->bcIterator;
232  }
233 
237  function free() {
238  // ...
239  }
240 
247  public function searchContainedSyntax() {
248  return $this->containedSyntax;
249  }
250 
254  public function hasMoreResults() {
255  return $this->hasMoreResults;
256  }
257 
262  public function shrink( $limit ) {
263  if ( $this->count() > $limit ) {
264  $this->hasMoreResults = true;
265  // shrinking result set for implementations that
266  // have not implemented extractResults and use
267  // the default cache location. Other implementations
268  // must override this as well.
269  if ( is_array( $this->results ) ) {
270  $this->results = array_slice( $this->results, 0, $limit );
271  } else {
272  throw new \UnexpectedValueException(
273  "When overriding result store extending classes must "
274  . " also override " . __METHOD__ );
275  }
276  }
277  }
278 
283  public function extractResults() {
284  if ( is_null( $this->results ) ) {
285  $this->results = [];
286  if ( $this->numRows() == 0 ) {
287  // Don't bother if we've got empty result
288  return $this->results;
289  }
290  $this->rewind();
291  while ( ( $result = $this->next() ) != false ) {
292  $this->results[] = $result;
293  }
294  $this->rewind();
295  }
296  return $this->results;
297  }
298 
303  public function extractTitles() {
304  if ( is_null( $this->titles ) ) {
305  if ( $this->numRows() == 0 ) {
306  // Don't bother if we've got empty result
307  $this->titles = [];
308  } else {
309  $this->titles = array_map(
310  function ( SearchResult $result ) {
311  return $result->getTitle();
312  },
313  $this->extractResults() );
314  }
315  }
316  return $this->titles;
317  }
318 
324  public function setAugmentedData( $name, $data ) {
325  foreach ( $data as $id => $resultData ) {
326  $this->extraData[$id][$name] = $resultData;
327  }
328  }
329 
334  public function augmentResult( SearchResult $result ) {
335  $id = $result->getTitle()->getArticleID();
336  if ( $id === -1 ) {
337  return;
338  }
339  $result->setExtensionData( function () use ( $id ) {
340  return $this->extraData[$id] ?? [];
341  } );
342  }
343 
350  public function getOffset() {
351  return null;
352  }
353 
354  final public function getIterator() {
355  return new ArrayIterator( $this->extractResults() );
356  }
357 }
array [] $extraData
Set of result&#39;s extra data, indexed per result id and then per data item name.
hasInterwikiResults( $type=self::SECONDARY_RESULTS)
Check if there are results on other wikis.
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
hasSuggestion()
Some search modes return a suggested alternate term if there are no exact hits.
hasRewrittenQuery()
Some search modes will run an alternative query that it thinks gives a better result than the provide...
searchContainedSyntax()
Did the search contain search syntax? If so, Special:Search won&#39;t offer the user a link to a create a...
setAugmentedData( $name, $data)
Sets augmented data for result set.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1980
SearchResult [] $results
Cache of results - serialization of the result iterator as an array.
free()
Frees the result set, if applicable.
boolean $hasMoreResults
True when there are more pages of search results available.
__construct( $containedSyntax=false, $hasMoreResults=false)
next()
Fetches next search result, or false.
const SECONDARY_RESULTS
Identifier for interwiki results that are displayed only together with existing main wiki results...
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
getTotalHits()
Some search modes return a total hit count for the query in the entire article database.
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
extractTitles()
Extract all the titles in the result set.
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
setExtensionData( $extensionData)
Set extension data for this result.
getInterwikiResults( $type=self::SECONDARY_RESULTS)
Return a result set of hits on other (multiple) wikis associated with this one.
rewind()
Rewind result set back to beginning.
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Title [] $titles
Cache of titles.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
termMatches()
Fetch an array of regular expression fragments for matching the search terms as parsed by this engine...
ArrayIterator null $bcIterator
Iterator supporting BC iteration methods.
extractResults()
Extract all the results in the result set as array.
augmentResult(SearchResult $result)
Returns extra data for specific result and store it in SearchResult object.
const INLINE_RESULTS
Identifier for interwiki results that can be displayed even if no existing main wiki results exist...