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
30 class ApiOpenSearch
extends ApiBase
{
32 private $format = null;
36 * Get the output format
40 protected function getFormat() {
41 if ( $this->format
=== null ) {
42 $params = $this->extractRequestParams();
43 $format = $params['format'];
45 $allowedParams = $this->getAllowedParams();
46 if ( !in_array( $format, $allowedParams['format'][ApiBase
::PARAM_TYPE
] ) ) {
47 $format = $allowedParams['format'][ApiBase
::PARAM_DFLT
];
50 if ( substr( $format, -2 ) === 'fm' ) {
51 $this->format
= substr( $format, 0, -2 );
54 $this->format
= $format;
61 public function getCustomPrinter() {
62 switch ( $this->getFormat() ) {
64 return new ApiOpenSearchFormatJson(
65 $this->getMain(), $this->fm
, $this->getParameter( 'warningsaserror' )
69 $printer = $this->getMain()->createPrinterByName( 'xml' . $this->fm
);
70 $printer->setRootElement( 'SearchSuggestion' );
74 ApiBase
::dieDebug( __METHOD__
, "Unsupported format '{$this->getFormat()}'" );
78 public function execute() {
79 $params = $this->extractRequestParams();
80 $search = $params['search'];
81 $limit = $params['limit'];
82 $namespaces = $params['namespace'];
83 $suggest = $params['suggest'];
85 if ( $params['redirects'] === null ) {
86 // Backwards compatibility, don't resolve for JSON.
87 $resolveRedir = $this->getFormat() !== 'json';
89 $resolveRedir = $params['redirects'] === 'resolve';
94 if ( !$suggest ||
$this->getConfig()->get( 'EnableOpenSearchSuggest' ) ) {
95 // Open search results may be stored for a very long time
96 $this->getMain()->setCacheMaxAge( $this->getConfig()->get( 'SearchSuggestCacheExpiry' ) );
97 $this->getMain()->setCacheMode( 'public' );
98 $this->search( $search, $limit, $namespaces, $resolveRedir, $results );
100 // Allow hooks to populate extracts and images
101 Hooks
::run( 'ApiOpenSearchSuggest', array( &$results ) );
103 // Trim extracts, if necessary
104 $length = $this->getConfig()->get( 'OpenSearchDescriptionLength' );
105 foreach ( $results as &$r ) {
106 if ( is_string( $r['extract'] ) && !$r['extract trimmed'] ) {
107 $r['extract'] = self
::trimExtract( $r['extract'], $length );
112 // Populate result object
113 $this->populateResult( $search, $results );
119 * @param string $search Text to search
120 * @param int $limit Maximum items to return
121 * @param array $namespaces Namespaces to search
122 * @param bool $resolveRedir Whether to resolve redirects
123 * @param array &$results Put results here. Keys have to be integers.
125 protected function search( $search, $limit, $namespaces, $resolveRedir, &$results ) {
127 $searchEngine = SearchEngine
::create();
128 $searchEngine->setLimitOffset( $limit );
129 $searchEngine->setNamespaces( $namespaces );
130 $titles = $searchEngine->extractTitles( $searchEngine->completionSearchWithVariants( $search ) );
136 // Special pages need unique integer ids in the return list, so we just
137 // assign them negative numbers because those won't clash with the
138 // always positive articleIds that non-special pages get.
139 $nextSpecialPageId = -1;
141 if ( $resolveRedir ) {
142 // Query for redirects
143 $redirects = array();
144 $lb = new LinkBatch( $titles );
145 if ( !$lb->isEmpty() ) {
146 $db = $this->getDB();
148 array( 'page', 'redirect' ),
149 array( 'page_namespace', 'page_title', 'rd_namespace', 'rd_title' ),
152 'rd_interwiki IS NULL OR rd_interwiki = ' . $db->addQuotes( '' ),
153 $lb->constructSet( 'page', $db ),
157 foreach ( $res as $row ) {
158 $redirects[$row->page_namespace
][$row->page_title
] =
159 array( $row->rd_namespace
, $row->rd_title
);
163 // Bypass any redirects
165 foreach ( $titles as $title ) {
166 $ns = $title->getNamespace();
167 $dbkey = $title->getDBkey();
169 if ( isset( $redirects[$ns][$dbkey] ) ) {
170 list( $ns, $dbkey ) = $redirects[$ns][$dbkey];
172 $title = Title
::makeTitle( $ns, $dbkey );
174 if ( !isset( $seen[$ns][$dbkey] ) ) {
175 $seen[$ns][$dbkey] = true;
176 $resultId = $title->getArticleID();
177 if ( $resultId === 0 ) {
178 $resultId = $nextSpecialPageId;
179 $nextSpecialPageId -= 1;
181 $results[$resultId] = array(
183 'redirect from' => $from,
185 'extract trimmed' => false,
187 'url' => wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
),
192 foreach ( $titles as $title ) {
193 $resultId = $title->getArticleId();
194 if ( $resultId === 0 ) {
195 $resultId = $nextSpecialPageId;
196 $nextSpecialPageId -= 1;
198 $results[$resultId] = array(
200 'redirect from' => null,
202 'extract trimmed' => false,
204 '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 ) );
223 $descriptions = array();
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() {
276 ApiBase
::PARAM_DFLT
=> $this->getConfig()->get( 'OpenSearchDefaultLimit' ),
277 ApiBase
::PARAM_TYPE
=> 'limit',
278 ApiBase
::PARAM_MIN
=> 1,
279 ApiBase
::PARAM_MAX
=> 100,
280 ApiBase
::PARAM_MAX2
=> 100
282 'namespace' => array(
283 ApiBase
::PARAM_DFLT
=> NS_MAIN
,
284 ApiBase
::PARAM_TYPE
=> 'namespace',
285 ApiBase
::PARAM_ISMULTI
=> true
288 'redirects' => array(
289 ApiBase
::PARAM_TYPE
=> array( 'return', 'resolve' ),
292 ApiBase
::PARAM_DFLT
=> 'json',
293 ApiBase
::PARAM_TYPE
=> array( 'json', 'jsonfm', 'xml', 'xmlfm' ),
295 'warningsaserror' => false,
299 protected function getExamplesMessages() {
301 'action=opensearch&search=Te'
302 => 'apihelp-opensearch-example-te',
306 public function getHelpUrls() {
307 return 'https://www.mediawiki.org/wiki/API:Opensearch';
311 * Trim an extract to a sensible length.
313 * Adapted from Extension:OpenSearchXml, which adapted it from
314 * Extension:ActiveAbstract.
316 * @param string $text
317 * @param int $length Target length; actual result will continue to the end of a sentence.
320 public static function trimExtract( $text, $length ) {
321 static $regex = null;
323 if ( $regex === null ) {
325 '([^\d])\.\s', '\!\s', '\?\s', // regular ASCII
326 '。', // full-width ideographic full-stop
327 '.', '!', '?', // double-width roman forms
328 '。', // half-width ideographic full stop
330 $endgroup = implode( '|', $endchars );
331 $end = "(?:$endgroup)";
332 $sentence = ".{{$length},}?$end+";
333 $regex = "/^($sentence)/u";
337 if ( preg_match( $regex, $text, $matches ) ) {
338 return trim( $matches[1] );
340 // Just return the first line
341 $lines = explode( "\n", $text );
342 return trim( $lines[0] );
347 * Fetch the template for a type.
349 * @param string $type MIME type
351 * @throws MWException
353 public static function getOpenSearchTemplate( $type ) {
354 global $wgOpenSearchTemplate, $wgCanonicalServer;
356 if ( $wgOpenSearchTemplate && $type === 'application/x-suggestions+json' ) {
357 return $wgOpenSearchTemplate;
360 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
366 case 'application/x-suggestions+json':
367 return $wgCanonicalServer . wfScript( 'api' )
368 . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
370 case 'application/x-suggestions+xml':
371 return $wgCanonicalServer . wfScript( 'api' )
372 . '?action=opensearch&format=xml&search={searchTerms}&namespace=' . $ns;
375 throw new MWException( __METHOD__
. ": Unknown type '$type'" );
380 class ApiOpenSearchFormatJson
extends ApiFormatJson
{
381 private $warningsAsError = false;
383 public function __construct( ApiMain
$main, $fm, $warningsAsError ) {
384 parent
::__construct( $main, "json$fm" );
385 $this->warningsAsError
= $warningsAsError;
388 public function execute() {
389 if ( !$this->getResult()->getResultData( 'error' ) ) {
390 $result = $this->getResult();
392 // Ignore warnings or treat as errors, as requested
393 $warnings = $result->removeValue( 'warnings', null );
394 if ( $this->warningsAsError
&& $warnings ) {
396 'Warnings cannot be represented in OpenSearch JSON format', 'warnings', 0,
397 array( 'warnings' => $warnings )
401 // Ignore any other unexpected keys (e.g. from $wgDebugToolbar)
402 $remove = array_keys( array_diff_key(
403 $result->getResultData(),
404 array( 0 => 'search', 1 => 'terms', 2 => 'descriptions', 3 => 'urls' )
406 foreach ( $remove as $key ) {
407 $result->removeValue( $key, null );