MediaWiki  1.28.1
ApiQuerySearch.php
Go to the documentation of this file.
1 <?php
33  use SearchApi;
34 
36  private $allowedParams;
37 
38  public function __construct( ApiQuery $query, $moduleName ) {
39  parent::__construct( $query, $moduleName, 'sr' );
40  }
41 
42  public function execute() {
43  $this->run();
44  }
45 
46  public function executeGenerator( $resultPageSet ) {
47  $this->run( $resultPageSet );
48  }
49 
54  private function run( $resultPageSet = null ) {
56  $params = $this->extractRequestParams();
57 
58  // Extract parameters
59  $query = $params['search'];
60  $what = $params['what'];
61  $interwiki = $params['interwiki'];
62  $searchInfo = array_flip( $params['info'] );
63  $prop = array_flip( $params['prop'] );
64 
65  // Deprecated parameters
66  if ( isset( $prop['hasrelated'] ) ) {
67  $this->logFeatureUsage( 'action=search&srprop=hasrelated' );
68  $this->setWarning( 'srprop=hasrelated has been deprecated' );
69  }
70  if ( isset( $prop['score'] ) ) {
71  $this->logFeatureUsage( 'action=search&srprop=score' );
72  $this->setWarning( 'srprop=score has been deprecated' );
73  }
74 
75  // Create search engine instance and set options
76  $search = $this->buildSearchEngine( $params );
77  $search->setFeatureData( 'rewrite', (bool)$params['enablerewrites'] );
78  $search->setFeatureData( 'interwiki', (bool)$interwiki );
79 
80  $query = $search->transformSearchTerm( $query );
81  $query = $search->replacePrefixes( $query );
82 
83  // Perform the actual search
84  if ( $what == 'text' ) {
85  $matches = $search->searchText( $query );
86  } elseif ( $what == 'title' ) {
87  $matches = $search->searchTitle( $query );
88  } elseif ( $what == 'nearmatch' ) {
89  // near matches must receive the user input as provided, otherwise
90  // the near matches within namespaces are lost.
91  $matches = $search->getNearMatcher( $this->getConfig() )
92  ->getNearMatchResultSet( $params['search'] );
93  } else {
94  // We default to title searches; this is a terrible legacy
95  // of the way we initially set up the MySQL fulltext-based
96  // search engine with separate title and text fields.
97  // In the future, the default should be for a combined index.
98  $what = 'title';
99  $matches = $search->searchTitle( $query );
100 
101  // Not all search engines support a separate title search,
102  // for instance the Lucene-based engine we use on Wikipedia.
103  // In this case, fall back to full-text search (which will
104  // include titles in it!)
105  if ( is_null( $matches ) ) {
106  $what = 'text';
107  $matches = $search->searchText( $query );
108  }
109  }
110  if ( is_null( $matches ) ) {
111  $this->dieUsage( "{$what} search is disabled", "search-{$what}-disabled" );
112  } elseif ( $matches instanceof Status && !$matches->isGood() ) {
113  $this->dieUsage( $matches->getWikiText( false, false, 'en' ), 'search-error' );
114  }
115 
116  if ( $resultPageSet === null ) {
117  $apiResult = $this->getResult();
118  // Add search meta data to result
119  if ( isset( $searchInfo['totalhits'] ) ) {
120  $totalhits = $matches->getTotalHits();
121  if ( $totalhits !== null ) {
122  $apiResult->addValue( [ 'query', 'searchinfo' ],
123  'totalhits', $totalhits );
124  }
125  }
126  if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
127  $apiResult->addValue( [ 'query', 'searchinfo' ],
128  'suggestion', $matches->getSuggestionQuery() );
129  $apiResult->addValue( [ 'query', 'searchinfo' ],
130  'suggestionsnippet', $matches->getSuggestionSnippet() );
131  }
132  if ( isset( $searchInfo['rewrittenquery'] ) && $matches->hasRewrittenQuery() ) {
133  $apiResult->addValue( [ 'query', 'searchinfo' ],
134  'rewrittenquery', $matches->getQueryAfterRewrite() );
135  $apiResult->addValue( [ 'query', 'searchinfo' ],
136  'rewrittenquerysnippet', $matches->getQueryAfterRewriteSnippet() );
137  }
138  }
139 
140  // Add the search results to the result
141  $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
142  $titles = [];
143  $count = 0;
144  $result = $matches->next();
145  $limit = $params['limit'];
146 
147  while ( $result ) {
148  if ( ++$count > $limit ) {
149  // We've reached the one extra which shows that there are
150  // additional items to be had. Stop here...
151  $this->setContinueEnumParameter( 'offset', $params['offset'] + $params['limit'] );
152  break;
153  }
154 
155  // Silently skip broken and missing titles
156  if ( $result->isBrokenTitle() || $result->isMissingRevision() ) {
157  $result = $matches->next();
158  continue;
159  }
160 
161  $title = $result->getTitle();
162  if ( $resultPageSet === null ) {
163  $vals = [];
165 
166  if ( isset( $prop['snippet'] ) ) {
167  $vals['snippet'] = $result->getTextSnippet( $terms );
168  }
169  if ( isset( $prop['size'] ) ) {
170  $vals['size'] = $result->getByteSize();
171  }
172  if ( isset( $prop['wordcount'] ) ) {
173  $vals['wordcount'] = $result->getWordCount();
174  }
175  if ( isset( $prop['timestamp'] ) ) {
176  $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $result->getTimestamp() );
177  }
178  if ( isset( $prop['titlesnippet'] ) ) {
179  $vals['titlesnippet'] = $result->getTitleSnippet();
180  }
181  if ( isset( $prop['categorysnippet'] ) ) {
182  $vals['categorysnippet'] = $result->getCategorySnippet();
183  }
184  if ( !is_null( $result->getRedirectTitle() ) ) {
185  if ( isset( $prop['redirecttitle'] ) ) {
186  $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
187  }
188  if ( isset( $prop['redirectsnippet'] ) ) {
189  $vals['redirectsnippet'] = $result->getRedirectSnippet();
190  }
191  }
192  if ( !is_null( $result->getSectionTitle() ) ) {
193  if ( isset( $prop['sectiontitle'] ) ) {
194  $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
195  }
196  if ( isset( $prop['sectionsnippet'] ) ) {
197  $vals['sectionsnippet'] = $result->getSectionSnippet();
198  }
199  }
200  if ( isset( $prop['isfilematch'] ) ) {
201  $vals['isfilematch'] = $result->isFileMatch();
202  }
203 
204  // Add item to results and see whether it fits
205  $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ],
206  null, $vals );
207  if ( !$fit ) {
208  $this->setContinueEnumParameter( 'offset', $params['offset'] + $count - 1 );
209  break;
210  }
211  } else {
212  $titles[] = $title;
213  }
214 
215  $result = $matches->next();
216  }
217 
218  $hasInterwikiResults = false;
219  $totalhits = null;
220  if ( $interwiki && $resultPageSet === null && $matches->hasInterwikiResults() ) {
221  foreach ( $matches->getInterwikiResults() as $interwikiMatches ) {
222  $hasInterwikiResults = true;
223 
224  // Include number of results if requested
225  if ( $resultPageSet === null && isset( $searchInfo['totalhits'] ) ) {
226  $totalhits += $interwikiMatches->getTotalHits();
227  }
228 
229  $result = $interwikiMatches->next();
230  while ( $result ) {
231  $title = $result->getTitle();
232 
233  if ( $resultPageSet === null ) {
234  $vals = [
235  'namespace' => $result->getInterwikiNamespaceText(),
236  'title' => $title->getText(),
237  'url' => $title->getFullURL(),
238  ];
239 
240  // Add item to results and see whether it fits
241  $fit = $apiResult->addValue(
242  [ 'query', 'interwiki' . $this->getModuleName(), $result->getInterwikiPrefix() ],
243  null,
244  $vals
245  );
246 
247  if ( !$fit ) {
248  // We hit the limit. We can't really provide any meaningful
249  // pagination info so just bail out
250  break;
251  }
252  } else {
253  $titles[] = $title;
254  }
255 
256  $result = $interwikiMatches->next();
257  }
258  }
259  if ( $totalhits !== null ) {
260  $apiResult->addValue( [ 'query', 'interwikisearchinfo' ],
261  'totalhits', $totalhits );
262  }
263  }
264 
265  if ( $resultPageSet === null ) {
266  $apiResult->addIndexedTagName( [
267  'query', $this->getModuleName()
268  ], 'p' );
269  if ( $hasInterwikiResults ) {
270  $apiResult->addIndexedTagName( [
271  'query', 'interwiki' . $this->getModuleName()
272  ], 'p' );
273  }
274  } else {
275  $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
276  if ( !isset( $current['index'] ) || $new['index'] < $current['index'] ) {
277  $current['index'] = $new['index'];
278  }
279  return $current;
280  } );
281  $resultPageSet->populateFromTitles( $titles );
282  $offset = $params['offset'] + 1;
283  foreach ( $titles as $index => $title ) {
284  $resultPageSet->setGeneratorData( $title, [ 'index' => $index + $offset ] );
285  }
286  }
287  }
288 
289  public function getCacheMode( $params ) {
290  return 'public';
291  }
292 
293  public function getAllowedParams() {
294  if ( $this->allowedParams !== null ) {
295  return $this->allowedParams;
296  }
297 
298  $this->allowedParams = $this->buildCommonApiParams() + [
299  'what' => [
301  'title',
302  'text',
303  'nearmatch',
304  ]
305  ],
306  'info' => [
307  ApiBase::PARAM_DFLT => 'totalhits|suggestion|rewrittenquery',
309  'totalhits',
310  'suggestion',
311  'rewrittenquery',
312  ],
313  ApiBase::PARAM_ISMULTI => true,
314  ],
315  'prop' => [
316  ApiBase::PARAM_DFLT => 'size|wordcount|timestamp|snippet',
318  'size',
319  'wordcount',
320  'timestamp',
321  'snippet',
322  'titlesnippet',
323  'redirecttitle',
324  'redirectsnippet',
325  'sectiontitle',
326  'sectionsnippet',
327  'isfilematch',
328  'categorysnippet',
329  'score', // deprecated
330  'hasrelated', // deprecated
331  ],
332  ApiBase::PARAM_ISMULTI => true,
334  ],
335  'interwiki' => false,
336  'enablerewrites' => false,
337  ];
338 
339  return $this->allowedParams;
340  }
341 
342  public function getSearchProfileParams() {
343  return [
344  'qiprofile' => [
346  'help-message' => 'apihelp-query+search-param-qiprofile',
347  ],
348  ];
349  }
350 
351  protected function getExamplesMessages() {
352  return [
353  'action=query&list=search&srsearch=meaning'
354  => 'apihelp-query+search-example-simple',
355  'action=query&list=search&srwhat=text&srsearch=meaning'
356  => 'apihelp-query+search-example-text',
357  'action=query&generator=search&gsrsearch=meaning&prop=info'
358  => 'apihelp-query+search-example-generator',
359  ];
360  }
361 
362  public function getHelpUrls() {
363  return 'https://www.mediawiki.org/wiki/API:Search';
364  }
365 }
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:88
run($resultPageSet=null)
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1555
getResult()
Get the result object.
Definition: ApiBase.php:584
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:50
trait SearchApi
Traits for API components that use a SearchEngine.
Definition: SearchApi.php:28
extractRequestParams($parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:685
buildCommonApiParams($isScrollable=true)
The set of api parameters that are shared between api calls that call the SearchEngine.
Definition: SearchApi.php:46
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, this is an array mapping those values to $msg...
Definition: ApiBase.php:157
getCacheMode($params)
setContinueEnumParameter($paramName, $paramValue)
Overridden to set the generator param if in generator mode.
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
const TS_ISO_8601
ISO 8601 format with no timezone: 1986-02-09T20:00:00Z.
Definition: defines.php:28
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 '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. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) '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 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) '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:Associative array mapping language codes to prefixed links of the form"language:title".&$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!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:1934
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
__construct(ApiQuery $query, $moduleName)
getConfig()
Get the Config object.
$params
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:953
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:464
This is the main query class.
Definition: ApiQuery.php:38
setWarning($warning)
Set warning section for this module.
Definition: ApiBase.php:1554
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
const FT_QUERY_INDEP_PROFILE_TYPE
string profile type for query independent ranking features
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
buildSearchEngine(array $params=null)
Build the search engine to use.
Definition: SearchApi.php:151
executeGenerator($resultPageSet)
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
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:53
dieUsage($description, $errorCode, $httpRespCode=0, $extradata=null)
Throw a UsageException, which will (if uncaught) call the main module's error handler and die with an...
Definition: ApiBase.php:1585
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive $limit
Definition: hooks.txt:1046
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition: design.txt:56
array $allowedParams
list of api allowed params
$count
logFeatureUsage($feature)
Write logging information for API features to a debug log, for usage analysis.
Definition: ApiBase.php:2304
static addTitleInfo(&$arr, $title, $prefix= '')
Add information (title and namespace) about a Title object to a result array.
Query module to perform full text search within wiki titles and content.
$matches