3 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
4 * Copyright © 2008 Brion Vibber <brion@wikimedia.org>
5 * Copyright © 2014 Wikimedia Foundation and contributors
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
25 use MediaWiki\MediaWikiServices
;
30 class ApiOpenSearch
extends ApiBase
{
33 private $format = null;
36 /** @var array list of api allowed params */
37 private $allowedParams = null;
40 * Get the output format
44 protected function getFormat() {
45 if ( $this->format
=== null ) {
46 $params = $this->extractRequestParams();
47 $format = $params['format'];
49 $allowedParams = $this->getAllowedParams();
50 if ( !in_array( $format, $allowedParams['format'][ApiBase
::PARAM_TYPE
] ) ) {
51 $format = $allowedParams['format'][ApiBase
::PARAM_DFLT
];
54 if ( substr( $format, -2 ) === 'fm' ) {
55 $this->format
= substr( $format, 0, -2 );
58 $this->format
= $format;
65 public function getCustomPrinter() {
66 switch ( $this->getFormat() ) {
68 return new ApiOpenSearchFormatJson(
69 $this->getMain(), $this->fm
, $this->getParameter( 'warningsaserror' )
73 $printer = $this->getMain()->createPrinterByName( 'xml' . $this->fm
);
74 '@phan-var ApiFormatXML $printer';
75 $printer->setRootElement( 'SearchSuggestion' );
79 ApiBase
::dieDebug( __METHOD__
, "Unsupported format '{$this->getFormat()}'" );
83 public function execute() {
84 $params = $this->extractRequestParams();
85 $search = $params['search'];
86 $suggest = $params['suggest'];
88 if ( !$suggest ||
$this->getConfig()->get( 'EnableOpenSearchSuggest' ) ) {
89 // Open search results may be stored for a very long time
90 $this->getMain()->setCacheMaxAge( $this->getConfig()->get( 'SearchSuggestCacheExpiry' ) );
91 $this->getMain()->setCacheMode( 'public' );
92 $results = $this->search( $search, $params );
94 // Allow hooks to populate extracts and images
95 Hooks
::run( 'ApiOpenSearchSuggest', [ &$results ] );
97 // Trim extracts, if necessary
98 $length = $this->getConfig()->get( 'OpenSearchDescriptionLength' );
99 foreach ( $results as &$r ) {
100 // @phan-suppress-next-line PhanTypeInvalidDimOffset
101 if ( is_string( $r['extract'] ) && !$r['extract trimmed'] ) {
102 $r['extract'] = self
::trimExtract( $r['extract'], $length );
107 // Populate result object
108 $this->populateResult( $search, $results );
113 * @param string $search the search query
114 * @param array $params api request params
115 * @return array search results. Keys are integers.
116 * @phan-return array<array{title:Title,redirect_from:?Title,extract:false,extract_trimmed:false,image:false,url:string}>
117 * Note that phan annotations don't support keys containing a space.
119 private function search( $search, array $params ) {
120 $searchEngine = $this->buildSearchEngine( $params );
121 $titles = $searchEngine->extractTitles( $searchEngine->completionSearchWithVariants( $search ) );
128 // Special pages need unique integer ids in the return list, so we just
129 // assign them negative numbers because those won't clash with the
130 // always positive articleIds that non-special pages get.
131 $nextSpecialPageId = -1;
133 if ( $params['redirects'] === null ) {
134 // Backwards compatibility, don't resolve for JSON.
135 $resolveRedir = $this->getFormat() !== 'json';
137 $resolveRedir = $params['redirects'] === 'resolve';
140 if ( $resolveRedir ) {
141 // Query for redirects
143 $lb = new LinkBatch( $titles );
144 if ( !$lb->isEmpty() ) {
145 $db = $this->getDB();
147 [ 'page', 'redirect' ],
148 [ 'page_namespace', 'page_title', 'rd_namespace', 'rd_title' ],
151 'rd_interwiki IS NULL OR rd_interwiki = ' . $db->addQuotes( '' ),
152 $lb->constructSet( 'page', $db ),
156 foreach ( $res as $row ) {
157 $redirects[$row->page_namespace
][$row->page_title
] =
158 [ $row->rd_namespace
, $row->rd_title
];
162 // Bypass any redirects
164 foreach ( $titles as $title ) {
165 $ns = $title->getNamespace();
166 $dbkey = $title->getDBkey();
168 if ( isset( $redirects[$ns][$dbkey] ) ) {
169 list( $ns, $dbkey ) = $redirects[$ns][$dbkey];
171 $title = Title
::makeTitle( $ns, $dbkey );
173 if ( !isset( $seen[$ns][$dbkey] ) ) {
174 $seen[$ns][$dbkey] = true;
175 $resultId = $title->getArticleID();
176 if ( $resultId === 0 ) {
177 $resultId = $nextSpecialPageId;
178 $nextSpecialPageId -= 1;
180 $results[$resultId] = [
182 'redirect from' => $from,
184 'extract trimmed' => false,
186 'url' => wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
),
191 foreach ( $titles as $title ) {
192 $resultId = $title->getArticleID();
193 if ( $resultId === 0 ) {
194 $resultId = $nextSpecialPageId;
195 $nextSpecialPageId -= 1;
197 $results[$resultId] = [
199 'redirect from' => null,
201 'extract trimmed' => false,
203 'url' => wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
),
212 * @param string $search
213 * @param array &$results
215 protected function populateResult( $search, &$results ) {
216 $result = $this->getResult();
218 switch ( $this->getFormat() ) {
220 // http://www.opensearch.org/Specifications/OpenSearch/Extensions/Suggestions/1.1
221 $result->addArrayType( null, 'array' );
222 $result->addValue( null, 0, strval( $search ) );
226 foreach ( $results as $r ) {
227 $terms[] = $r['title']->getPrefixedText();
228 $descriptions[] = strval( $r['extract'] );
231 $result->addValue( null, 1, $terms );
232 $result->addValue( null, 2, $descriptions );
233 $result->addValue( null, 3, $urls );
237 // https://msdn.microsoft.com/en-us/library/cc891508(v=vs.85).aspx
246 foreach ( $results as $r ) {
248 'Text' => $r['title']->getPrefixedText(),
251 if ( is_string( $r['extract'] ) && $r['extract'] !== '' ) {
252 $item['Description'] = $r['extract'];
254 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
255 if ( is_array( $r['image'] ) && isset( $r['image']['source'] ) ) {
256 $item['Image'] = array_intersect_key( $r['image'], $imageKeys );
258 ApiResult
::setSubelementsList( $item, array_keys( $item ) );
261 ApiResult
::setIndexedTagName( $items, 'Item' );
262 $result->addValue( null, 'version', '2.0' );
263 $result->addValue( null, 'xmlns', 'http://opensearch.org/searchsuggest2' );
264 $result->addValue( null, 'Query', strval( $search ) );
265 $result->addSubelementsList( null, 'Query' );
266 $result->addValue( null, 'Section', $items );
270 ApiBase
::dieDebug( __METHOD__
, "Unsupported format '{$this->getFormat()}'" );
274 public function getAllowedParams() {
275 if ( $this->allowedParams
!== null ) {
276 return $this->allowedParams
;
278 $this->allowedParams
= $this->buildCommonApiParams( false ) +
[
281 ApiBase
::PARAM_TYPE
=> [ 'return', 'resolve' ],
284 ApiBase
::PARAM_DFLT
=> 'json',
285 ApiBase
::PARAM_TYPE
=> [ 'json', 'jsonfm', 'xml', 'xmlfm' ],
287 'warningsaserror' => false,
290 // Use open search specific default limit
291 $this->allowedParams
['limit'][ApiBase
::PARAM_DFLT
] = $this->getConfig()->get(
292 'OpenSearchDefaultLimit'
295 return $this->allowedParams
;
298 public function getSearchProfileParams() {
301 'profile-type' => SearchEngine
::COMPLETION_PROFILE_TYPE
,
302 'help-message' => 'apihelp-query+prefixsearch-param-profile'
307 protected function getExamplesMessages() {
309 'action=opensearch&search=Te'
310 => 'apihelp-opensearch-example-te',
314 public function getHelpUrls() {
315 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Opensearch';
319 * Trim an extract to a sensible length.
321 * Adapted from Extension:OpenSearchXml, which adapted it from
322 * Extension:ActiveAbstract.
324 * @param string $text
325 * @param int $length Target length; actual result will continue to the end of a sentence.
328 public static function trimExtract( $text, $length ) {
329 static $regex = null;
331 if ( $regex === null ) {
333 '([^\d])\.\s', '\!\s', '\?\s', // regular ASCII
334 '。', // full-width ideographic full-stop
335 '.', '!', '?', // double-width roman forms
336 '。', // half-width ideographic full stop
338 $endgroup = implode( '|', $endchars );
339 $end = "(?:$endgroup)";
340 $sentence = ".{{$length},}?$end+";
341 $regex = "/^($sentence)/u";
345 if ( preg_match( $regex, $text, $matches ) ) {
346 return trim( $matches[1] );
348 // Just return the first line
349 return trim( explode( "\n", $text )[0] );
354 * Fetch the template for a type.
356 * @param string $type MIME type
358 * @throws MWException
360 public static function getOpenSearchTemplate( $type ) {
361 $config = MediaWikiServices
::getInstance()->getSearchEngineConfig();
362 $template = $config->getConfig()->get( 'OpenSearchTemplate' );
364 if ( $template && $type === 'application/x-suggestions+json' ) {
368 $ns = implode( '|', $config->defaultNamespaces() );
374 case 'application/x-suggestions+json':
375 return $config->getConfig()->get( 'CanonicalServer' ) . wfScript( 'api' )
376 . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
378 case 'application/x-suggestions+xml':
379 return $config->getConfig()->get( 'CanonicalServer' ) . wfScript( 'api' )
380 . '?action=opensearch&format=xml&search={searchTerms}&namespace=' . $ns;
383 throw new MWException( __METHOD__
. ": Unknown type '$type'" );