37 private $format =
null;
41 private $allowedParams =
null;
44 private $linkBatchFactory;
60 parent::__construct( $mainModule, $moduleName );
61 $this->linkBatchFactory = $linkBatchFactory;
63 $this->searchEngineConfig = $searchEngineConfig;
64 $this->searchEngineFactory = $searchEngineFactory;
73 if ( $this->format ===
null ) {
75 $format = $params[
'format'];
78 if ( !in_array( $format, $allowedParams[
'format'][ParamValidator::PARAM_TYPE] ) ) {
79 $format = $allowedParams[
'format'][ParamValidator::PARAM_DEFAULT];
82 if ( str_ends_with( $format,
'fm' ) ) {
83 $this->format = substr( $format, 0, -2 );
86 $this->format = $format;
101 $printer = $this->
getMain()->createPrinterByName(
'xml' . $this->fm );
102 '@phan-var ApiFormatXml $printer';
104 $printer->setRootElement(
'SearchSuggestion' );
114 $search = $params[
'search'];
117 $this->
getMain()->setCacheMaxAge(
118 $this->
getConfig()->
get( MainConfigNames::SearchSuggestCacheExpiry ) );
119 $this->
getMain()->setCacheMode(
'public' );
120 $results = $this->search( $search, $params );
126 $length = $this->
getConfig()->get( MainConfigNames::OpenSearchDescriptionLength );
127 foreach ( $results as &$r ) {
128 if ( is_string( $r[
'extract'] ) && !$r[
'extract trimmed'] ) {
145 private function search( $search, array $params ) {
147 $titles = $searchEngine->extractTitles( $searchEngine->completionSearchWithVariants( $search ) );
157 $nextSpecialPageId = -1;
159 if ( $params[
'redirects'] ===
null ) {
161 $resolveRedir = $this->
getFormat() !==
'json';
163 $resolveRedir = $params[
'redirects'] ===
'resolve';
166 if ( $resolveRedir ) {
169 $lb = $this->linkBatchFactory->newLinkBatch( $titles );
170 if ( !$lb->isEmpty() ) {
171 $db = $this->
getDB();
172 $res = $db->newSelectQueryBuilder()
173 ->select( [
'page_namespace',
'page_title',
'rd_namespace',
'rd_title' ] )
176 'rd_interwiki IS NULL OR rd_interwiki = ' . $db->addQuotes(
'' ),
177 $lb->constructSet(
'page', $db )
179 ->join(
'redirect',
null, [
'rd_from = page_id' ] )
180 ->caller( __METHOD__ )
182 foreach (
$res as $row ) {
183 $redirects[$row->page_namespace][$row->page_title] =
184 [ $row->rd_namespace, $row->rd_title ];
190 foreach ( $titles as
$title ) {
191 $ns =
$title->getNamespace();
192 $dbkey =
$title->getDBkey();
194 if ( isset( $redirects[$ns][$dbkey] ) ) {
195 [ $ns, $dbkey ] = $redirects[$ns][$dbkey];
197 $title = Title::makeTitle( $ns, $dbkey );
199 if ( !isset( $seen[$ns][$dbkey] ) ) {
200 $seen[$ns][$dbkey] =
true;
201 $resultId =
$title->getArticleID();
202 if ( $resultId === 0 ) {
203 $resultId = $nextSpecialPageId;
204 $nextSpecialPageId--;
206 $results[$resultId] = [
208 'redirect from' => $from,
210 'extract trimmed' =>
false,
217 foreach ( $titles as
$title ) {
218 $resultId =
$title->getArticleID();
219 if ( $resultId === 0 ) {
220 $resultId = $nextSpecialPageId;
221 $nextSpecialPageId--;
223 $results[$resultId] = [
225 'redirect from' =>
null,
227 'extract trimmed' =>
false,
247 $result->addArrayType(
null,
'array' );
248 $result->addValue(
null, 0, strval( $search ) );
252 foreach ( $results as $r ) {
253 $terms[] = $r[
'title']->getPrefixedText();
254 $descriptions[] = strval( $r[
'extract'] );
257 $result->addValue(
null, 1, $terms );
258 $result->addValue(
null, 2, $descriptions );
259 $result->addValue(
null, 3, $urls );
272 foreach ( $results as $r ) {
274 'Text' => $r[
'title']->getPrefixedText(),
277 if ( is_string( $r[
'extract'] ) && $r[
'extract'] !==
'' ) {
278 $item[
'Description'] = $r[
'extract'];
280 if ( is_array( $r[
'image'] ) && isset( $r[
'image'][
'source'] ) ) {
281 $item[
'Image'] = array_intersect_key( $r[
'image'], $imageKeys );
287 $result->addValue(
null,
'version',
'2.0' );
288 $result->addValue(
null,
'xmlns',
'http://opensearch.org/searchsuggest2' );
289 $result->addValue(
null,
'Query', strval( $search ) );
290 $result->addSubelementsList(
null,
'Query' );
291 $result->addValue(
null,
'Section', $items );
300 if ( $this->allowedParams !==
null ) {
301 return $this->allowedParams;
305 ParamValidator::PARAM_DEFAULT =>
false,
307 ParamValidator::PARAM_DEPRECATED =>
true,
310 ParamValidator::PARAM_TYPE => [
'return',
'resolve' ],
313 ParamValidator::PARAM_DEFAULT =>
'json',
314 ParamValidator::PARAM_TYPE => [
'json',
'jsonfm',
'xml',
'xmlfm' ],
316 'warningsaserror' =>
false,
320 $this->allowedParams[
'limit'][ParamValidator::PARAM_DEFAULT] = $this->
getConfig()->get(
321 MainConfigNames::OpenSearchDefaultLimit
324 return $this->allowedParams;
331 'help-message' =>
'apihelp-query+prefixsearch-param-profile'
338 'action=opensearch&search=Te'
339 =>
'apihelp-opensearch-example-te',
344 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Opensearch';
358 static $regex =
null;
360 if ( $regex ===
null ) {
362 '([^\d])\.\s',
'\!\s',
'\?\s',
367 $endgroup = implode(
'|', $endchars );
368 $end =
"(?:$endgroup)";
369 $sentence =
".{{$length},}?$end+";
370 $regex =
"/^($sentence)/u";
374 if ( preg_match( $regex, $text,
$matches ) ) {
378 return trim( explode(
"\n", $text )[0] );
390 $config = MediaWikiServices::getInstance()->getSearchEngineConfig();
391 $template = $config->getConfig()->get( MainConfigNames::OpenSearchTemplate );
393 if ( $template &&
$type ===
'application/x-suggestions+json' ) {
397 $ns = implode(
'|', $config->defaultNamespaces() );
403 case 'application/x-suggestions+json':
404 return $config->getConfig()->get( MainConfigNames::CanonicalServer ) .
405 wfScript(
'api' ) .
'?action=opensearch&search={searchTerms}&namespace=' . $ns;
407 case 'application/x-suggestions+xml':
408 return $config->getConfig()->get( MainConfigNames::CanonicalServer ) .
410 '?action=opensearch&format=xml&search={searchTerms}&namespace=' . $ns;
413 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.
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.
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.
static setSubelementsList(array &$arr, $names)
Causes the elements with the specified names to be output as subelements rather than attributes.
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
A class containing constants representing the names of configuration variables.
Configuration handling class for SearchEngine.
Factory class for SearchEngine.
const COMPLETION_PROFILE_TYPE
Profile type for completionSearch.
trait SearchApi
Traits for API components that use a SearchEngine.