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 $this->getMain()->createPrinterByName( 'json' . $this->fm
);
67 $printer = $this->getMain()->createPrinterByName( 'xml' . $this->fm
);
68 $printer->setRootElement( 'SearchSuggestion' );
72 ApiBase
::dieDebug( __METHOD__
, "Unsupported format '{$this->getFormat()}'" );
76 public function execute() {
77 $params = $this->extractRequestParams();
78 $search = $params['search'];
79 $limit = $params['limit'];
80 $namespaces = $params['namespace'];
81 $suggest = $params['suggest'];
83 if ( $params['redirects'] === null ) {
84 // Backwards compatibility, don't resolve for JSON.
85 $resolveRedir = $this->getFormat() !== 'json';
87 $resolveRedir = $params['redirects'] === 'resolve';
92 if ( !$suggest ||
$this->getConfig()->get( 'EnableOpenSearchSuggest' ) ) {
93 // Open search results may be stored for a very long time
94 $this->getMain()->setCacheMaxAge( $this->getConfig()->get( 'SearchSuggestCacheExpiry' ) );
95 $this->getMain()->setCacheMode( 'public' );
96 $this->search( $search, $limit, $namespaces, $resolveRedir, $results );
98 // Allow hooks to populate extracts and images
99 wfRunHooks( 'ApiOpenSearchSuggest', array( &$results ) );
101 // Trim extracts, if necessary
102 $length = $this->getConfig()->get( 'OpenSearchDescriptionLength' );
103 foreach ( $results as &$r ) {
104 if ( is_string( $r['extract'] ) && !$r['extract trimmed'] ) {
105 $r['extract'] = self
::trimExtract( $r['extract'], $length );
110 // Populate result object
111 $this->populateResult( $search, $results );
117 * @param string $search Text to search
118 * @param int $limit Maximum items to return
119 * @param array $namespaces Namespaces to search
120 * @param bool $resolveRedir Whether to resolve redirects
121 * @param array &$results Put results here
123 protected function search( $search, $limit, $namespaces, $resolveRedir, &$results ) {
124 // Find matching titles as Title objects
125 $searcher = new TitlePrefixSearch
;
126 $titles = $searcher->searchWithVariants( $search, $limit, $namespaces );
128 if ( $resolveRedir ) {
129 // Query for redirects
130 $db = $this->getDb();
131 $lb = new LinkBatch( $titles );
133 array( 'page', 'redirect' ),
134 array( 'page_namespace', 'page_title', 'rd_namespace', 'rd_title' ),
137 'rd_interwiki IS NULL OR rd_interwiki = ' . $db->addQuotes( '' ),
138 $lb->constructSet( 'page', $db ),
142 $redirects = array();
143 foreach ( $res as $row ) {
144 $redirects[$row->page_namespace
][$row->page_title
] =
145 array( $row->rd_namespace
, $row->rd_title
);
148 // Bypass any redirects
150 foreach ( $titles as $title ) {
151 $ns = $title->getNamespace();
152 $dbkey = $title->getDBkey();
154 if ( isset( $redirects[$ns][$dbkey] ) ) {
155 list( $ns, $dbkey ) = $redirects[$ns][$dbkey];
157 $title = Title
::makeTitle( $ns, $dbkey );
159 if ( !isset( $seen[$ns][$dbkey] ) ) {
160 $seen[$ns][$dbkey] = true;
161 $results[$title->getArticleId()] = array(
163 'redirect from' => $from,
165 'extract trimmed' => false,
167 'url' => wfExpandUrl( $title->getFullUrl(), PROTO_CURRENT
),
172 foreach ( $titles as $title ) {
173 $results[$title->getArticleId()] = array(
175 'redirect from' => null,
177 'extract trimmed' => false,
179 'url' => wfExpandUrl( $title->getFullUrl(), PROTO_CURRENT
),
186 * @param string $search
187 * @param array &$results
189 protected function populateResult( $search, &$results ) {
190 $result = $this->getResult();
192 switch ( $this->getFormat() ) {
194 // http://www.opensearch.org/Specifications/OpenSearch/Extensions/Suggestions/1.1
195 $result->addValue( null, 0, strval( $search ) );
197 $descriptions = array();
199 foreach ( $results as $r ) {
200 $terms[] = $r['title']->getPrefixedText();
201 $descriptions[] = strval( $r['extract'] );
204 $result->addValue( null, 1, $terms );
205 $result->addValue( null, 2, $descriptions );
206 $result->addValue( null, 3, $urls );
210 // http://msdn.microsoft.com/en-us/library/cc891508%28v=vs.85%29.aspx
219 foreach ( $results as $r ) {
221 $result->setContent( $item, $r['title']->getPrefixedText(), 'Text' );
222 $result->setContent( $item, $r['url'], 'Url' );
223 if ( is_string( $r['extract'] ) && $r['extract'] !== '' ) {
224 $result->setContent( $item, $r['extract'], 'Description' );
226 if ( is_array( $r['image'] ) && isset( $r['image']['source'] ) ) {
227 $item['Image'] = array_intersect_key( $r['image'], $imageKeys );
231 $result->setIndexedTagName( $items, 'Item' );
232 $result->addValue( null, 'version', '2.0' );
233 $result->addValue( null, 'xmlns', 'http://opensearch.org/searchsuggest2' );
235 $result->setContent( $query, strval( $search ) );
236 $result->addValue( null, 'Query', $query );
237 $result->addValue( null, 'Section', $items );
241 ApiBase
::dieDebug( __METHOD__
, "Unsupported format '{$this->getFormat()}'" );
245 public function getAllowedParams() {
249 ApiBase
::PARAM_DFLT
=> $this->getConfig()->get( 'OpenSearchDefaultLimit' ),
250 ApiBase
::PARAM_TYPE
=> 'limit',
251 ApiBase
::PARAM_MIN
=> 1,
252 ApiBase
::PARAM_MAX
=> 100,
253 ApiBase
::PARAM_MAX2
=> 100
255 'namespace' => array(
256 ApiBase
::PARAM_DFLT
=> NS_MAIN
,
257 ApiBase
::PARAM_TYPE
=> 'namespace',
258 ApiBase
::PARAM_ISMULTI
=> true
261 'redirects' => array(
262 ApiBase
::PARAM_TYPE
=> array( 'return', 'resolve' ),
265 ApiBase
::PARAM_DFLT
=> 'json',
266 ApiBase
::PARAM_TYPE
=> array( 'json', 'jsonfm', 'xml', 'xmlfm' ),
271 protected function getExamplesMessages() {
273 'action=opensearch&search=Te'
274 => 'apihelp-opensearch-example-te',
278 public function getHelpUrls() {
279 return 'https://www.mediawiki.org/wiki/API:Opensearch';
283 * Trim an extract to a sensible length.
285 * Adapted from Extension:OpenSearchXml, which adapted it from
286 * Extension:ActiveAbstract.
288 * @param string $text
289 * @param int $len Target length; actual result will continue to the end of a sentence.
292 public static function trimExtract( $text, $length ) {
293 static $regex = null;
295 if ( $regex === null ) {
297 '([^\d])\.\s', '\!\s', '\?\s', // regular ASCII
298 '。', // full-width ideographic full-stop
299 '.', '!', '?', // double-width roman forms
300 '。', // half-width ideographic full stop
302 $endgroup = implode( '|', $endchars );
303 $end = "(?:$endgroup)";
304 $sentence = ".{{$length},}?$end+";
305 $regex = "/^($sentence)/u";
309 if ( preg_match( $regex, $text, $matches ) ) {
310 return trim( $matches[1] );
312 // Just return the first line
313 $lines = explode( "\n", $text );
314 return trim( $lines[0] );
319 * Fetch the template for a type.
321 * @param string $type MIME type
324 public static function getOpenSearchTemplate( $type ) {
325 global $wgOpenSearchTemplate, $wgCanonicalServer;
327 if ( $wgOpenSearchTemplate && $type === 'application/x-suggestions+json' ) {
328 return $wgOpenSearchTemplate;
331 $ns = implode( '|', SearchEngine
::defaultNamespaces() );
337 case 'application/x-suggestions+json':
338 return $wgCanonicalServer . wfScript( 'api' )
339 . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
341 case 'application/x-suggestions+xml':
342 return $wgCanonicalServer . wfScript( 'api' )
343 . '?action=opensearch&format=xml&search={searchTerms}&namespace=' . $ns;
346 throw new MWException( __METHOD__
. ": Unknown type '$type'" );