3 * Created on Oct 13, 2006
5 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
6 * Copyright © 2008 Brion Vibber <brion@wikimedia.org>
7 * Copyright © 2014 Brad Jorsch <bjorsch@wikimedia.org>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
27 use MediaWiki\MediaWikiServices
;
28 use Wikimedia\Rdbms\Database
;
33 class ApiOpenSearch
extends ApiBase
{
36 private $format = null;
39 /** @var array list of api allowed params */
40 private $allowedParams = null;
43 * Get the output format
47 protected function getFormat() {
48 if ( $this->format
=== null ) {
49 $params = $this->extractRequestParams();
50 $format = $params['format'];
52 $allowedParams = $this->getAllowedParams();
53 if ( !in_array( $format, $allowedParams['format'][ApiBase
::PARAM_TYPE
] ) ) {
54 $format = $allowedParams['format'][ApiBase
::PARAM_DFLT
];
57 if ( substr( $format, -2 ) === 'fm' ) {
58 $this->format
= substr( $format, 0, -2 );
61 $this->format
= $format;
68 public function getCustomPrinter() {
69 switch ( $this->getFormat() ) {
71 return new ApiOpenSearchFormatJson(
72 $this->getMain(), $this->fm
, $this->getParameter( 'warningsaserror' )
76 $printer = $this->getMain()->createPrinterByName( 'xml' . $this->fm
);
77 $printer->setRootElement( 'SearchSuggestion' );
81 ApiBase
::dieDebug( __METHOD__
, "Unsupported format '{$this->getFormat()}'" );
85 public function execute() {
86 $params = $this->extractRequestParams();
87 $search = $params['search'];
88 $suggest = $params['suggest'];
90 if ( !$suggest ||
$this->getConfig()->get( 'EnableOpenSearchSuggest' ) ) {
91 // Open search results may be stored for a very long time
92 $this->getMain()->setCacheMaxAge( $this->getConfig()->get( 'SearchSuggestCacheExpiry' ) );
93 $this->getMain()->setCacheMode( 'public' );
94 $results = $this->search( $search, $params );
96 // Allow hooks to populate extracts and images
97 Hooks
::run( 'ApiOpenSearchSuggest', [ &$results ] );
99 // Trim extracts, if necessary
100 $length = $this->getConfig()->get( 'OpenSearchDescriptionLength' );
101 foreach ( $results as &$r ) {
102 if ( is_string( $r['extract'] ) && !$r['extract trimmed'] ) {
103 $r['extract'] = self
::trimExtract( $r['extract'], $length );
108 // Populate result object
109 $this->populateResult( $search, $results );
114 * @param string $search the search query
115 * @param array $params api request params
116 * @return array search results. Keys are integers.
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 // http://msdn.microsoft.com/en-us/library/cc891508%28v=vs.85%29.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 if ( is_array( $r['image'] ) && isset( $r['image']['source'] ) ) {
254 $item['Image'] = array_intersect_key( $r['image'], $imageKeys );
256 ApiResult
::setSubelementsList( $item, array_keys( $item ) );
259 ApiResult
::setIndexedTagName( $items, 'Item' );
260 $result->addValue( null, 'version', '2.0' );
261 $result->addValue( null, 'xmlns', 'http://opensearch.org/searchsuggest2' );
262 $result->addValue( null, 'Query', strval( $search ) );
263 $result->addSubelementsList( null, 'Query' );
264 $result->addValue( null, 'Section', $items );
268 ApiBase
::dieDebug( __METHOD__
, "Unsupported format '{$this->getFormat()}'" );
272 public function getAllowedParams() {
273 if ( $this->allowedParams
!== null ) {
274 return $this->allowedParams
;
276 $this->allowedParams
= $this->buildCommonApiParams( false ) +
[
279 ApiBase
::PARAM_TYPE
=> [ 'return', 'resolve' ],
282 ApiBase
::PARAM_DFLT
=> 'json',
283 ApiBase
::PARAM_TYPE
=> [ 'json', 'jsonfm', 'xml', 'xmlfm' ],
285 'warningsaserror' => false,
288 // Use open search specific default limit
289 $this->allowedParams
['limit'][ApiBase
::PARAM_DFLT
] = $this->getConfig()->get(
290 'OpenSearchDefaultLimit'
293 return $this->allowedParams
;
296 public function getSearchProfileParams() {
299 'profile-type' => SearchEngine
::COMPLETION_PROFILE_TYPE
,
300 'help-message' => 'apihelp-query+prefixsearch-param-profile'
305 protected function getExamplesMessages() {
307 'action=opensearch&search=Te'
308 => 'apihelp-opensearch-example-te',
312 public function getHelpUrls() {
313 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Opensearch';
317 * Trim an extract to a sensible length.
319 * Adapted from Extension:OpenSearchXml, which adapted it from
320 * Extension:ActiveAbstract.
322 * @param string $text
323 * @param int $length Target length; actual result will continue to the end of a sentence.
326 public static function trimExtract( $text, $length ) {
327 static $regex = null;
329 if ( $regex === null ) {
331 '([^\d])\.\s', '\!\s', '\?\s', // regular ASCII
332 '。', // full-width ideographic full-stop
333 '.', '!', '?', // double-width roman forms
334 '。', // half-width ideographic full stop
336 $endgroup = implode( '|', $endchars );
337 $end = "(?:$endgroup)";
338 $sentence = ".{{$length},}?$end+";
339 $regex = "/^($sentence)/u";
343 if ( preg_match( $regex, $text, $matches ) ) {
344 return trim( $matches[1] );
346 // Just return the first line
347 return trim( explode( "\n", $text )[0] );
352 * Fetch the template for a type.
354 * @param string $type MIME type
356 * @throws MWException
358 public static function getOpenSearchTemplate( $type ) {
359 $config = MediaWikiServices
::getInstance()->getSearchEngineConfig();
360 $template = $config->getConfig()->get( 'OpenSearchTemplate' );
362 if ( $template && $type === 'application/x-suggestions+json' ) {
366 $ns = implode( '|', $config->defaultNamespaces() );
372 case 'application/x-suggestions+json':
373 return $config->getConfig()->get( 'CanonicalServer' ) . wfScript( 'api' )
374 . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
376 case 'application/x-suggestions+xml':
377 return $config->getConfig()->get( 'CanonicalServer' ) . wfScript( 'api' )
378 . '?action=opensearch&format=xml&search={searchTerms}&namespace=' . $ns;
381 throw new MWException( __METHOD__
. ": Unknown type '$type'" );
386 class ApiOpenSearchFormatJson
extends ApiFormatJson
{
387 private $warningsAsError = false;
389 public function __construct( ApiMain
$main, $fm, $warningsAsError ) {
390 parent
::__construct( $main, "json$fm" );
391 $this->warningsAsError
= $warningsAsError;
394 public function execute() {
395 $result = $this->getResult();
396 if ( !$result->getResultData( 'error' ) && !$result->getResultData( 'errors' ) ) {
397 // Ignore warnings or treat as errors, as requested
398 $warnings = $result->removeValue( 'warnings', null );
399 if ( $this->warningsAsError
&& $warnings ) {
401 'apierror-opensearch-json-warnings',
403 [ 'warnings' => $warnings ]
407 // Ignore any other unexpected keys (e.g. from $wgDebugToolbar)
408 $remove = array_keys( array_diff_key(
409 $result->getResultData(),
410 [ 0 => 'search', 1 => 'terms', 2 => 'descriptions', 3 => 'urls' ]
412 foreach ( $remove as $key ) {
413 $result->removeValue( $key, null );