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 $printer->setRootElement( 'SearchSuggestion' );
78 ApiBase
::dieDebug( __METHOD__
, "Unsupported format '{$this->getFormat()}'" );
82 public function execute() {
83 $params = $this->extractRequestParams();
84 $search = $params['search'];
85 $suggest = $params['suggest'];
87 if ( !$suggest ||
$this->getConfig()->get( 'EnableOpenSearchSuggest' ) ) {
88 // Open search results may be stored for a very long time
89 $this->getMain()->setCacheMaxAge( $this->getConfig()->get( 'SearchSuggestCacheExpiry' ) );
90 $this->getMain()->setCacheMode( 'public' );
91 $results = $this->search( $search, $params );
93 // Allow hooks to populate extracts and images
94 Hooks
::run( 'ApiOpenSearchSuggest', [ &$results ] );
96 // Trim extracts, if necessary
97 $length = $this->getConfig()->get( 'OpenSearchDescriptionLength' );
98 foreach ( $results as &$r ) {
99 // @phan-suppress-next-line PhanTypeInvalidDimOffset
100 if ( is_string( $r['extract'] ) && !$r['extract trimmed'] ) {
101 $r['extract'] = self
::trimExtract( $r['extract'], $length );
106 // Populate result object
107 $this->populateResult( $search, $results );
112 * @param string $search the search query
113 * @param array $params api request params
114 * @return array search results. Keys are integers.
115 * @phan-return array<array{title:Title,extract:false,image:false,url:string}>
116 * Note that phan annotations don't support keys containing a space.
118 private function search( $search, array $params ) {
119 $searchEngine = $this->buildSearchEngine( $params );
120 $titles = $searchEngine->extractTitles( $searchEngine->completionSearchWithVariants( $search ) );
127 // Special pages need unique integer ids in the return list, so we just
128 // assign them negative numbers because those won't clash with the
129 // always positive articleIds that non-special pages get.
130 $nextSpecialPageId = -1;
132 if ( $params['redirects'] === null ) {
133 // Backwards compatibility, don't resolve for JSON.
134 $resolveRedir = $this->getFormat() !== 'json';
136 $resolveRedir = $params['redirects'] === 'resolve';
139 if ( $resolveRedir ) {
140 // Query for redirects
142 $lb = new LinkBatch( $titles );
143 if ( !$lb->isEmpty() ) {
144 $db = $this->getDB();
146 [ 'page', 'redirect' ],
147 [ 'page_namespace', 'page_title', 'rd_namespace', 'rd_title' ],
150 'rd_interwiki IS NULL OR rd_interwiki = ' . $db->addQuotes( '' ),
151 $lb->constructSet( 'page', $db ),
155 foreach ( $res as $row ) {
156 $redirects[$row->page_namespace
][$row->page_title
] =
157 [ $row->rd_namespace
, $row->rd_title
];
161 // Bypass any redirects
163 foreach ( $titles as $title ) {
164 $ns = $title->getNamespace();
165 $dbkey = $title->getDBkey();
167 if ( isset( $redirects[$ns][$dbkey] ) ) {
168 list( $ns, $dbkey ) = $redirects[$ns][$dbkey];
170 $title = Title
::makeTitle( $ns, $dbkey );
172 if ( !isset( $seen[$ns][$dbkey] ) ) {
173 $seen[$ns][$dbkey] = true;
174 $resultId = $title->getArticleID();
175 if ( $resultId === 0 ) {
176 $resultId = $nextSpecialPageId;
177 $nextSpecialPageId -= 1;
179 $results[$resultId] = [
181 'redirect from' => $from,
183 'extract trimmed' => false,
185 'url' => wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
),
190 foreach ( $titles as $title ) {
191 $resultId = $title->getArticleID();
192 if ( $resultId === 0 ) {
193 $resultId = $nextSpecialPageId;
194 $nextSpecialPageId -= 1;
196 $results[$resultId] = [
198 'redirect from' => null,
200 'extract trimmed' => false,
202 'url' => wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
),
211 * @param string $search
212 * @param array &$results
214 protected function populateResult( $search, &$results ) {
215 $result = $this->getResult();
217 switch ( $this->getFormat() ) {
219 // http://www.opensearch.org/Specifications/OpenSearch/Extensions/Suggestions/1.1
220 $result->addArrayType( null, 'array' );
221 $result->addValue( null, 0, strval( $search ) );
225 foreach ( $results as $r ) {
226 $terms[] = $r['title']->getPrefixedText();
227 $descriptions[] = strval( $r['extract'] );
230 $result->addValue( null, 1, $terms );
231 $result->addValue( null, 2, $descriptions );
232 $result->addValue( null, 3, $urls );
236 // https://msdn.microsoft.com/en-us/library/cc891508(v=vs.85).aspx
245 foreach ( $results as $r ) {
247 'Text' => $r['title']->getPrefixedText(),
250 if ( is_string( $r['extract'] ) && $r['extract'] !== '' ) {
251 $item['Description'] = $r['extract'];
253 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
254 if ( is_array( $r['image'] ) && isset( $r['image']['source'] ) ) {
255 $item['Image'] = array_intersect_key( $r['image'], $imageKeys );
257 ApiResult
::setSubelementsList( $item, array_keys( $item ) );
260 ApiResult
::setIndexedTagName( $items, 'Item' );
261 $result->addValue( null, 'version', '2.0' );
262 $result->addValue( null, 'xmlns', 'http://opensearch.org/searchsuggest2' );
263 $result->addValue( null, 'Query', strval( $search ) );
264 $result->addSubelementsList( null, 'Query' );
265 $result->addValue( null, 'Section', $items );
269 ApiBase
::dieDebug( __METHOD__
, "Unsupported format '{$this->getFormat()}'" );
273 public function getAllowedParams() {
274 if ( $this->allowedParams
!== null ) {
275 return $this->allowedParams
;
277 $this->allowedParams
= $this->buildCommonApiParams( false ) +
[
280 ApiBase
::PARAM_TYPE
=> [ 'return', 'resolve' ],
283 ApiBase
::PARAM_DFLT
=> 'json',
284 ApiBase
::PARAM_TYPE
=> [ 'json', 'jsonfm', 'xml', 'xmlfm' ],
286 'warningsaserror' => false,
289 // Use open search specific default limit
290 $this->allowedParams
['limit'][ApiBase
::PARAM_DFLT
] = $this->getConfig()->get(
291 'OpenSearchDefaultLimit'
294 return $this->allowedParams
;
297 public function getSearchProfileParams() {
300 'profile-type' => SearchEngine
::COMPLETION_PROFILE_TYPE
,
301 'help-message' => 'apihelp-query+prefixsearch-param-profile'
306 protected function getExamplesMessages() {
308 'action=opensearch&search=Te'
309 => 'apihelp-opensearch-example-te',
313 public function getHelpUrls() {
314 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Opensearch';
318 * Trim an extract to a sensible length.
320 * Adapted from Extension:OpenSearchXml, which adapted it from
321 * Extension:ActiveAbstract.
323 * @param string $text
324 * @param int $length Target length; actual result will continue to the end of a sentence.
327 public static function trimExtract( $text, $length ) {
328 static $regex = null;
330 if ( $regex === null ) {
332 '([^\d])\.\s', '\!\s', '\?\s', // regular ASCII
333 '。', // full-width ideographic full-stop
334 '.', '!', '?', // double-width roman forms
335 '。', // half-width ideographic full stop
337 $endgroup = implode( '|', $endchars );
338 $end = "(?:$endgroup)";
339 $sentence = ".{{$length},}?$end+";
340 $regex = "/^($sentence)/u";
344 if ( preg_match( $regex, $text, $matches ) ) {
345 return trim( $matches[1] );
347 // Just return the first line
348 return trim( explode( "\n", $text )[0] );
353 * Fetch the template for a type.
355 * @param string $type MIME type
357 * @throws MWException
359 public static function getOpenSearchTemplate( $type ) {
360 $config = MediaWikiServices
::getInstance()->getSearchEngineConfig();
361 $template = $config->getConfig()->get( 'OpenSearchTemplate' );
363 if ( $template && $type === 'application/x-suggestions+json' ) {
367 $ns = implode( '|', $config->defaultNamespaces() );
373 case 'application/x-suggestions+json':
374 return $config->getConfig()->get( 'CanonicalServer' ) . wfScript( 'api' )
375 . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
377 case 'application/x-suggestions+xml':
378 return $config->getConfig()->get( 'CanonicalServer' ) . wfScript( 'api' )
379 . '?action=opensearch&format=xml&search={searchTerms}&namespace=' . $ns;
382 throw new MWException( __METHOD__
. ": Unknown type '$type'" );