Fix hook situation for Skin::doEditSectionLink
[mediawiki.git] / includes / api / ApiOpenSearch.php
blobf24a03fb87eaa595ae425dee65b2e6f4195b89c7
1 <?php
2 /**
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
24 * @file
27 /**
28 * @ingroup API
30 class ApiOpenSearch extends ApiBase {
32 private $format = null;
33 private $fm = null;
35 /**
36 * Get the output format
38 * @return string
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 );
52 $this->fm = 'fm';
53 } else {
54 $this->format = $format;
55 $this->fm = '';
58 return $this->format;
61 public function getCustomPrinter() {
62 switch ( $this->getFormat() ) {
63 case 'json':
64 return $this->getMain()->createPrinterByName( 'json' . $this->fm );
66 case 'xml':
67 $printer = $this->getMain()->createPrinterByName( 'xml' . $this->fm );
68 $printer->setRootElement( 'SearchSuggestion' );
69 return $printer;
71 default:
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';
86 } else {
87 $resolveRedir = $params['redirects'] === 'resolve';
90 $results = array();
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 Hooks::run( '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 );
115 * Perform the search
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. Keys have to be integers.
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 );
127 if ( !$titles ) {
128 return;
131 // Special pages need unique integer ids in the return list, so we just
132 // assign them negative numbers because those won't clash with the
133 // always positive articleIds that non-special pages get.
134 $nextSpecialPageId = -1;
136 if ( $resolveRedir ) {
137 // Query for redirects
138 $redirects = array();
139 $lb = new LinkBatch( $titles );
140 if ( !$lb->isEmpty() ) {
141 $db = $this->getDb();
142 $res = $db->select(
143 array( 'page', 'redirect' ),
144 array( 'page_namespace', 'page_title', 'rd_namespace', 'rd_title' ),
145 array(
146 'rd_from = page_id',
147 'rd_interwiki IS NULL OR rd_interwiki = ' . $db->addQuotes( '' ),
148 $lb->constructSet( 'page', $db ),
150 __METHOD__
152 foreach ( $res as $row ) {
153 $redirects[$row->page_namespace][$row->page_title] =
154 array( $row->rd_namespace, $row->rd_title );
158 // Bypass any redirects
159 $seen = array();
160 foreach ( $titles as $title ) {
161 $ns = $title->getNamespace();
162 $dbkey = $title->getDBkey();
163 $from = null;
164 if ( isset( $redirects[$ns][$dbkey] ) ) {
165 list( $ns, $dbkey ) = $redirects[$ns][$dbkey];
166 $from = $title;
167 $title = Title::makeTitle( $ns, $dbkey );
169 if ( !isset( $seen[$ns][$dbkey] ) ) {
170 $seen[$ns][$dbkey] = true;
171 $resultId = $title->getArticleId();
172 if ( $resultId === 0 ) {
173 $resultId = $nextSpecialPageId;
174 $nextSpecialPageId -= 1;
176 $results[$resultId] = array(
177 'title' => $title,
178 'redirect from' => $from,
179 'extract' => false,
180 'extract trimmed' => false,
181 'image' => false,
182 'url' => wfExpandUrl( $title->getFullUrl(), PROTO_CURRENT ),
186 } else {
187 foreach ( $titles as $title ) {
188 $resultId = $title->getArticleId();
189 if ( $resultId === 0 ) {
190 $resultId = $nextSpecialPageId;
191 $nextSpecialPageId -= 1;
193 $results[$resultId] = array(
194 'title' => $title,
195 'redirect from' => null,
196 'extract' => false,
197 'extract trimmed' => false,
198 'image' => false,
199 'url' => wfExpandUrl( $title->getFullUrl(), PROTO_CURRENT ),
206 * @param string $search
207 * @param array &$results
209 protected function populateResult( $search, &$results ) {
210 $result = $this->getResult();
212 switch ( $this->getFormat() ) {
213 case 'json':
214 // http://www.opensearch.org/Specifications/OpenSearch/Extensions/Suggestions/1.1
215 $result->addValue( null, 0, strval( $search ) );
216 $terms = array();
217 $descriptions = array();
218 $urls = array();
219 foreach ( $results as $r ) {
220 $terms[] = $r['title']->getPrefixedText();
221 $descriptions[] = strval( $r['extract'] );
222 $urls[] = $r['url'];
224 $result->addValue( null, 1, $terms );
225 $result->addValue( null, 2, $descriptions );
226 $result->addValue( null, 3, $urls );
227 break;
229 case 'xml':
230 // http://msdn.microsoft.com/en-us/library/cc891508%28v=vs.85%29.aspx
231 $imageKeys = array(
232 'source' => true,
233 'alt' => true,
234 'width' => true,
235 'height' => true,
236 'align' => true,
238 $items = array();
239 foreach ( $results as $r ) {
240 $item = array();
241 $result->setContent( $item, $r['title']->getPrefixedText(), 'Text' );
242 $result->setContent( $item, $r['url'], 'Url' );
243 if ( is_string( $r['extract'] ) && $r['extract'] !== '' ) {
244 $result->setContent( $item, $r['extract'], 'Description' );
246 if ( is_array( $r['image'] ) && isset( $r['image']['source'] ) ) {
247 $item['Image'] = array_intersect_key( $r['image'], $imageKeys );
249 $items[] = $item;
251 $result->setIndexedTagName( $items, 'Item' );
252 $result->addValue( null, 'version', '2.0' );
253 $result->addValue( null, 'xmlns', 'http://opensearch.org/searchsuggest2' );
254 $query = array();
255 $result->setContent( $query, strval( $search ) );
256 $result->addValue( null, 'Query', $query );
257 $result->addValue( null, 'Section', $items );
258 break;
260 default:
261 ApiBase::dieDebug( __METHOD__, "Unsupported format '{$this->getFormat()}'" );
265 public function getAllowedParams() {
266 return array(
267 'search' => null,
268 'limit' => array(
269 ApiBase::PARAM_DFLT => $this->getConfig()->get( 'OpenSearchDefaultLimit' ),
270 ApiBase::PARAM_TYPE => 'limit',
271 ApiBase::PARAM_MIN => 1,
272 ApiBase::PARAM_MAX => 100,
273 ApiBase::PARAM_MAX2 => 100
275 'namespace' => array(
276 ApiBase::PARAM_DFLT => NS_MAIN,
277 ApiBase::PARAM_TYPE => 'namespace',
278 ApiBase::PARAM_ISMULTI => true
280 'suggest' => false,
281 'redirects' => array(
282 ApiBase::PARAM_TYPE => array( 'return', 'resolve' ),
284 'format' => array(
285 ApiBase::PARAM_DFLT => 'json',
286 ApiBase::PARAM_TYPE => array( 'json', 'jsonfm', 'xml', 'xmlfm' ),
291 protected function getExamplesMessages() {
292 return array(
293 'action=opensearch&search=Te'
294 => 'apihelp-opensearch-example-te',
298 public function getHelpUrls() {
299 return 'https://www.mediawiki.org/wiki/API:Opensearch';
303 * Trim an extract to a sensible length.
305 * Adapted from Extension:OpenSearchXml, which adapted it from
306 * Extension:ActiveAbstract.
308 * @param string $text
309 * @param int $len Target length; actual result will continue to the end of a sentence.
310 * @return string
312 public static function trimExtract( $text, $length ) {
313 static $regex = null;
315 if ( $regex === null ) {
316 $endchars = array(
317 '([^\d])\.\s', '\!\s', '\?\s', // regular ASCII
318 '。', // full-width ideographic full-stop
319 '.', '!', '?', // double-width roman forms
320 '。', // half-width ideographic full stop
322 $endgroup = implode( '|', $endchars );
323 $end = "(?:$endgroup)";
324 $sentence = ".{{$length},}?$end+";
325 $regex = "/^($sentence)/u";
328 $matches = array();
329 if ( preg_match( $regex, $text, $matches ) ) {
330 return trim( $matches[1] );
331 } else {
332 // Just return the first line
333 $lines = explode( "\n", $text );
334 return trim( $lines[0] );
339 * Fetch the template for a type.
341 * @param string $type MIME type
342 * @return string
343 * @throws MWException
345 public static function getOpenSearchTemplate( $type ) {
346 global $wgOpenSearchTemplate, $wgCanonicalServer;
348 if ( $wgOpenSearchTemplate && $type === 'application/x-suggestions+json' ) {
349 return $wgOpenSearchTemplate;
352 $ns = implode( '|', SearchEngine::defaultNamespaces() );
353 if ( !$ns ) {
354 $ns = "0";
357 switch ( $type ) {
358 case 'application/x-suggestions+json':
359 return $wgCanonicalServer . wfScript( 'api' )
360 . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
362 case 'application/x-suggestions+xml':
363 return $wgCanonicalServer . wfScript( 'api' )
364 . '?action=opensearch&format=xml&search={searchTerms}&namespace=' . $ns;
366 default:
367 throw new MWException( __METHOD__ . ": Unknown type '$type'" );