57 parent::__construct( $mainModule, $moduleName );
60 $this->searchEngineConfig = $searchEngineConfig;
70 if ( $this->format ===
null ) {
79 if ( substr(
$format, -2 ) ===
'fm' ) {
80 $this->format = substr(
$format, 0, -2 );
98 $printer = $this->
getMain()->createPrinterByName(
'xml' . $this->fm );
99 '@phan-var ApiFormatXml $printer';
101 $printer->setRootElement(
'SearchSuggestion' );
111 $search = $params[
'search'];
114 $this->
getMain()->setCacheMaxAge( $this->
getConfig()->
get(
'SearchSuggestCacheExpiry' ) );
115 $this->
getMain()->setCacheMode(
'public' );
116 $results = $this->
search( $search, $params );
122 $length = $this->
getConfig()->get(
'OpenSearchDescriptionLength' );
123 foreach ( $results as &$r ) {
124 if ( is_string( $r[
'extract'] ) && !$r[
'extract trimmed'] ) {
141 private function search( $search, array $params ) {
143 $titles = $searchEngine->extractTitles( $searchEngine->completionSearchWithVariants( $search ) );
153 $nextSpecialPageId = -1;
155 if ( $params[
'redirects'] ===
null ) {
157 $resolveRedir = $this->
getFormat() !==
'json';
159 $resolveRedir = $params[
'redirects'] ===
'resolve';
162 if ( $resolveRedir ) {
165 $lb = $this->linkBatchFactory->newLinkBatch( $titles );
166 if ( !$lb->isEmpty() ) {
167 $db = $this->
getDB();
169 [
'page',
'redirect' ],
170 [
'page_namespace',
'page_title',
'rd_namespace',
'rd_title' ],
173 'rd_interwiki IS NULL OR rd_interwiki = ' . $db->addQuotes(
'' ),
174 $lb->constructSet(
'page', $db ),
178 foreach (
$res as $row ) {
179 $redirects[$row->page_namespace][$row->page_title] =
180 [ $row->rd_namespace, $row->rd_title ];
186 foreach ( $titles as
$title ) {
187 $ns =
$title->getNamespace();
188 $dbkey =
$title->getDBkey();
190 if ( isset( $redirects[$ns][$dbkey] ) ) {
191 list( $ns, $dbkey ) = $redirects[$ns][$dbkey];
193 $title = Title::makeTitle( $ns, $dbkey );
195 if ( !isset( $seen[$ns][$dbkey] ) ) {
196 $seen[$ns][$dbkey] =
true;
197 $resultId =
$title->getArticleID();
198 if ( $resultId === 0 ) {
199 $resultId = $nextSpecialPageId;
200 $nextSpecialPageId -= 1;
202 $results[$resultId] = [
204 'redirect from' => $from,
206 'extract trimmed' =>
false,
213 foreach ( $titles as
$title ) {
214 $resultId =
$title->getArticleID();
215 if ( $resultId === 0 ) {
216 $resultId = $nextSpecialPageId;
217 $nextSpecialPageId -= 1;
219 $results[$resultId] = [
221 'redirect from' =>
null,
223 'extract trimmed' =>
false,
243 $result->addArrayType(
null,
'array' );
244 $result->addValue(
null, 0, strval( $search ) );
248 foreach ( $results as $r ) {
249 $terms[] = $r[
'title']->getPrefixedText();
250 $descriptions[] = strval( $r[
'extract'] );
253 $result->addValue(
null, 1, $terms );
254 $result->addValue(
null, 2, $descriptions );
255 $result->addValue(
null, 3, $urls );
268 foreach ( $results as $r ) {
270 'Text' => $r[
'title']->getPrefixedText(),
273 if ( is_string( $r[
'extract'] ) && $r[
'extract'] !==
'' ) {
274 $item[
'Description'] = $r[
'extract'];
276 if ( is_array( $r[
'image'] ) && isset( $r[
'image'][
'source'] ) ) {
277 $item[
'Image'] = array_intersect_key( $r[
'image'], $imageKeys );
279 ApiResult::setSubelementsList( $item, array_keys( $item ) );
282 ApiResult::setIndexedTagName( $items,
'Item' );
283 $result->addValue(
null,
'version',
'2.0' );
284 $result->addValue(
null,
'xmlns',
'http://opensearch.org/searchsuggest2' );
285 $result->addValue(
null,
'Query', strval( $search ) );
286 $result->addSubelementsList(
null,
'Query' );
287 $result->addValue(
null,
'Section', $items );
296 if ( $this->allowedParams !==
null ) {
312 'warningsaserror' =>
false,
317 'OpenSearchDefaultLimit'
326 'profile-type' => SearchEngine::COMPLETION_PROFILE_TYPE,
327 'help-message' =>
'apihelp-query+prefixsearch-param-profile'
334 'action=opensearch&search=Te'
335 =>
'apihelp-opensearch-example-te',
340 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Opensearch';
354 static $regex =
null;
356 if ( $regex ===
null ) {
358 '([^\d])\.\s',
'\!\s',
'\?\s',
363 $endgroup = implode(
'|', $endchars );
364 $end =
"(?:$endgroup)";
365 $sentence =
".{{$length},}?$end+";
366 $regex =
"/^($sentence)/u";
370 if ( preg_match( $regex, $text,
$matches ) ) {
374 return trim( explode(
"\n", $text )[0] );
386 $config = MediaWikiServices::getInstance()->getSearchEngineConfig();
387 $template = $config->getConfig()->get(
'OpenSearchTemplate' );
389 if ( $template &&
$type ===
'application/x-suggestions+json' ) {
393 $ns = implode(
'|', $config->defaultNamespaces() );
399 case 'application/x-suggestions+json':
400 return $config->getConfig()->get(
'CanonicalServer' ) .
wfScript(
'api' )
401 .
'?action=opensearch&search={searchTerms}&namespace=' . $ns;
403 case 'application/x-suggestions+xml':
404 return $config->getConfig()->get(
'CanonicalServer' ) .
wfScript(
'api' )
405 .
'?action=opensearch&format=xml&search={searchTerms}&namespace=' . $ns;
408 throw new MWException( __METHOD__ .
": Unknown type '$type'" );
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
buildSearchEngine(array $params=null)
Build the search engine to use.
buildCommonApiParams( $isScrollable=true)
The set of api parameters that are shared between api calls that call the SearchEngine.
SearchEngineFactory null $searchEngineFactory
This abstract class implements many basic API functions, and is the base of all API classes.
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
getDB()
Gets a default replica DB connection object.
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
getMain()
Get the main module.
getResult()
Get the result object.
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
getHookRunner()
Get an ApiHookRunner for running core API hooks.
This is the main API class, used for both external and internal processing.
static trimExtract( $text, $length)
Trim an extract to a sensible length.
LinkBatchFactory $linkBatchFactory
array $allowedParams
list of api allowed params
getHelpUrls()
Return links to more detailed help pages about the module.
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
getCustomPrinter()
If the module may only be used with a certain format module, it should override this method to return...
getExamplesMessages()
Returns usage examples for this module.
populateResult( $search, &$results)
__construct(ApiMain $mainModule, $moduleName, LinkBatchFactory $linkBatchFactory, SearchEngineConfig $searchEngineConfig, SearchEngineFactory $searchEngineFactory)
getFormat()
Get the output format.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
static getOpenSearchTemplate( $type)
Fetch the template for a type.
search( $search, array $params)
Perform the search.
Configuration handling class for SearchEngine.
Factory class for SearchEngine.
trait SearchApi
Traits for API components that use a SearchEngine.