Merge "Move HTMLForm-specific styles out of mediawiki.legacy.shared"
[lhc/web/wiklou.git] / includes / api / ApiOpenSearch.php
1 <?php
2 /**
3 * Created on Oct 13, 2006
4 *
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>
8 *
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.
13 *
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.
18 *
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
23 *
24 * @file
25 */
26
27 /**
28 * @ingroup API
29 */
30 class ApiOpenSearch extends ApiBase {
31
32 private $format = null;
33 private $fm = null;
34
35 /**
36 * Get the output format
37 *
38 * @return string
39 */
40 protected function getFormat() {
41 if ( $this->format === null ) {
42 $params = $this->extractRequestParams();
43 $format = $params['format'];
44
45 $allowedParams = $this->getAllowedParams();
46 if ( !in_array( $format, $allowedParams['format'][ApiBase::PARAM_TYPE] ) ) {
47 $format = $allowedParams['format'][ApiBase::PARAM_DFLT];
48 }
49
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 = '';
56 }
57 }
58 return $this->format;
59 }
60
61 public function getCustomPrinter() {
62 switch ( $this->getFormat() ) {
63 case 'json':
64 return new ApiOpenSearchFormatJson(
65 $this->getMain(), $this->fm, $this->getParameter( 'warningsaserror' )
66 );
67
68 case 'xml':
69 $printer = $this->getMain()->createPrinterByName( 'xml' . $this->fm );
70 $printer->setRootElement( 'SearchSuggestion' );
71 return $printer;
72
73 default:
74 ApiBase::dieDebug( __METHOD__, "Unsupported format '{$this->getFormat()}'" );
75 }
76 }
77
78 public function execute() {
79 $params = $this->extractRequestParams();
80 $search = $params['search'];
81 $limit = $params['limit'];
82 $namespaces = $params['namespace'];
83 $suggest = $params['suggest'];
84
85 if ( $params['redirects'] === null ) {
86 // Backwards compatibility, don't resolve for JSON.
87 $resolveRedir = $this->getFormat() !== 'json';
88 } else {
89 $resolveRedir = $params['redirects'] === 'resolve';
90 }
91
92 $results = array();
93
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 );
99
100 // Allow hooks to populate extracts and images
101 Hooks::run( 'ApiOpenSearchSuggest', array( &$results ) );
102
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 );
108 }
109 }
110 }
111
112 // Populate result object
113 $this->populateResult( $search, $results );
114 }
115
116 /**
117 * Perform the search
118 *
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.
124 */
125 protected function search( $search, $limit, $namespaces, $resolveRedir, &$results ) {
126 // Find matching titles as Title objects
127 $searcher = new TitlePrefixSearch;
128 $titles = $searcher->searchWithVariants( $search, $limit, $namespaces );
129 if ( !$titles ) {
130 return;
131 }
132
133 // Special pages need unique integer ids in the return list, so we just
134 // assign them negative numbers because those won't clash with the
135 // always positive articleIds that non-special pages get.
136 $nextSpecialPageId = -1;
137
138 if ( $resolveRedir ) {
139 // Query for redirects
140 $redirects = array();
141 $lb = new LinkBatch( $titles );
142 if ( !$lb->isEmpty() ) {
143 $db = $this->getDb();
144 $res = $db->select(
145 array( 'page', 'redirect' ),
146 array( 'page_namespace', 'page_title', 'rd_namespace', 'rd_title' ),
147 array(
148 'rd_from = page_id',
149 'rd_interwiki IS NULL OR rd_interwiki = ' . $db->addQuotes( '' ),
150 $lb->constructSet( 'page', $db ),
151 ),
152 __METHOD__
153 );
154 foreach ( $res as $row ) {
155 $redirects[$row->page_namespace][$row->page_title] =
156 array( $row->rd_namespace, $row->rd_title );
157 }
158 }
159
160 // Bypass any redirects
161 $seen = array();
162 foreach ( $titles as $title ) {
163 $ns = $title->getNamespace();
164 $dbkey = $title->getDBkey();
165 $from = null;
166 if ( isset( $redirects[$ns][$dbkey] ) ) {
167 list( $ns, $dbkey ) = $redirects[$ns][$dbkey];
168 $from = $title;
169 $title = Title::makeTitle( $ns, $dbkey );
170 }
171 if ( !isset( $seen[$ns][$dbkey] ) ) {
172 $seen[$ns][$dbkey] = true;
173 $resultId = $title->getArticleId();
174 if ( $resultId === 0 ) {
175 $resultId = $nextSpecialPageId;
176 $nextSpecialPageId -= 1;
177 }
178 $results[$resultId] = array(
179 'title' => $title,
180 'redirect from' => $from,
181 'extract' => false,
182 'extract trimmed' => false,
183 'image' => false,
184 'url' => wfExpandUrl( $title->getFullUrl(), PROTO_CURRENT ),
185 );
186 }
187 }
188 } else {
189 foreach ( $titles as $title ) {
190 $resultId = $title->getArticleId();
191 if ( $resultId === 0 ) {
192 $resultId = $nextSpecialPageId;
193 $nextSpecialPageId -= 1;
194 }
195 $results[$resultId] = array(
196 'title' => $title,
197 'redirect from' => null,
198 'extract' => false,
199 'extract trimmed' => false,
200 'image' => false,
201 'url' => wfExpandUrl( $title->getFullUrl(), PROTO_CURRENT ),
202 );
203 }
204 }
205 }
206
207 /**
208 * @param string $search
209 * @param array &$results
210 */
211 protected function populateResult( $search, &$results ) {
212 $result = $this->getResult();
213
214 switch ( $this->getFormat() ) {
215 case 'json':
216 // http://www.opensearch.org/Specifications/OpenSearch/Extensions/Suggestions/1.1
217 $result->addArrayType( null, 'array' );
218 $result->addValue( null, 0, strval( $search ) );
219 $terms = array();
220 $descriptions = array();
221 $urls = array();
222 foreach ( $results as $r ) {
223 $terms[] = $r['title']->getPrefixedText();
224 $descriptions[] = strval( $r['extract'] );
225 $urls[] = $r['url'];
226 }
227 $result->addValue( null, 1, $terms );
228 $result->addValue( null, 2, $descriptions );
229 $result->addValue( null, 3, $urls );
230 break;
231
232 case 'xml':
233 // http://msdn.microsoft.com/en-us/library/cc891508%28v=vs.85%29.aspx
234 $imageKeys = array(
235 'source' => true,
236 'alt' => true,
237 'width' => true,
238 'height' => true,
239 'align' => true,
240 );
241 $items = array();
242 foreach ( $results as $r ) {
243 $item = array(
244 'Text' => $r['title']->getPrefixedText(),
245 'Url' => $r['url'],
246 );
247 if ( is_string( $r['extract'] ) && $r['extract'] !== '' ) {
248 $item['Description'] = $r['extract'];
249 }
250 if ( is_array( $r['image'] ) && isset( $r['image']['source'] ) ) {
251 $item['Image'] = array_intersect_key( $r['image'], $imageKeys );
252 }
253 ApiResult::setSubelementsList( $item, array_keys( $item ) );
254 $items[] = $item;
255 }
256 ApiResult::setIndexedTagName( $items, 'Item' );
257 $result->addValue( null, 'version', '2.0' );
258 $result->addValue( null, 'xmlns', 'http://opensearch.org/searchsuggest2' );
259 $result->addValue( null, 'Query', strval( $search ) );
260 $result->addSubelementsList( null, 'Query' );
261 $result->addValue( null, 'Section', $items );
262 break;
263
264 default:
265 ApiBase::dieDebug( __METHOD__, "Unsupported format '{$this->getFormat()}'" );
266 }
267 }
268
269 public function getAllowedParams() {
270 return array(
271 'search' => null,
272 'limit' => array(
273 ApiBase::PARAM_DFLT => $this->getConfig()->get( 'OpenSearchDefaultLimit' ),
274 ApiBase::PARAM_TYPE => 'limit',
275 ApiBase::PARAM_MIN => 1,
276 ApiBase::PARAM_MAX => 100,
277 ApiBase::PARAM_MAX2 => 100
278 ),
279 'namespace' => array(
280 ApiBase::PARAM_DFLT => NS_MAIN,
281 ApiBase::PARAM_TYPE => 'namespace',
282 ApiBase::PARAM_ISMULTI => true
283 ),
284 'suggest' => false,
285 'redirects' => array(
286 ApiBase::PARAM_TYPE => array( 'return', 'resolve' ),
287 ),
288 'format' => array(
289 ApiBase::PARAM_DFLT => 'json',
290 ApiBase::PARAM_TYPE => array( 'json', 'jsonfm', 'xml', 'xmlfm' ),
291 ),
292 'warningsaserror' => false,
293 );
294 }
295
296 protected function getExamplesMessages() {
297 return array(
298 'action=opensearch&search=Te'
299 => 'apihelp-opensearch-example-te',
300 );
301 }
302
303 public function getHelpUrls() {
304 return 'https://www.mediawiki.org/wiki/API:Opensearch';
305 }
306
307 /**
308 * Trim an extract to a sensible length.
309 *
310 * Adapted from Extension:OpenSearchXml, which adapted it from
311 * Extension:ActiveAbstract.
312 *
313 * @param string $text
314 * @param int $len Target length; actual result will continue to the end of a sentence.
315 * @return string
316 */
317 public static function trimExtract( $text, $length ) {
318 static $regex = null;
319
320 if ( $regex === null ) {
321 $endchars = array(
322 '([^\d])\.\s', '\!\s', '\?\s', // regular ASCII
323 '。', // full-width ideographic full-stop
324 '.', '!', '?', // double-width roman forms
325 '。', // half-width ideographic full stop
326 );
327 $endgroup = implode( '|', $endchars );
328 $end = "(?:$endgroup)";
329 $sentence = ".{{$length},}?$end+";
330 $regex = "/^($sentence)/u";
331 }
332
333 $matches = array();
334 if ( preg_match( $regex, $text, $matches ) ) {
335 return trim( $matches[1] );
336 } else {
337 // Just return the first line
338 $lines = explode( "\n", $text );
339 return trim( $lines[0] );
340 }
341 }
342
343 /**
344 * Fetch the template for a type.
345 *
346 * @param string $type MIME type
347 * @return string
348 * @throws MWException
349 */
350 public static function getOpenSearchTemplate( $type ) {
351 global $wgOpenSearchTemplate, $wgCanonicalServer;
352
353 if ( $wgOpenSearchTemplate && $type === 'application/x-suggestions+json' ) {
354 return $wgOpenSearchTemplate;
355 }
356
357 $ns = implode( '|', SearchEngine::defaultNamespaces() );
358 if ( !$ns ) {
359 $ns = "0";
360 }
361
362 switch ( $type ) {
363 case 'application/x-suggestions+json':
364 return $wgCanonicalServer . wfScript( 'api' )
365 . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
366
367 case 'application/x-suggestions+xml':
368 return $wgCanonicalServer . wfScript( 'api' )
369 . '?action=opensearch&format=xml&search={searchTerms}&namespace=' . $ns;
370
371 default:
372 throw new MWException( __METHOD__ . ": Unknown type '$type'" );
373 }
374 }
375 }
376
377 class ApiOpenSearchFormatJson extends ApiFormatJson {
378 private $warningsAsError = false;
379
380 public function __construct( ApiMain $main, $fm, $warningsAsError ) {
381 parent::__construct( $main, "json$fm" );
382 $this->warningsAsError = $warningsAsError;
383 }
384
385 public function execute() {
386 if ( !$this->getResult()->getResultData( 'error' ) ) {
387 $result = $this->getResult();
388
389 // Ignore warnings or treat as errors, as requested
390 $warnings = $result->removeValue( 'warnings', null );
391 if ( $this->warningsAsError && $warnings ) {
392 $this->dieUsage(
393 'Warnings cannot be represented in OpenSearch JSON format', 'warnings', 0,
394 array( 'warnings' => $warnings )
395 );
396 }
397
398 // Ignore any other unexpected keys (e.g. from $wgDebugToolbar)
399 $remove = array_keys( array_diff_key(
400 $result->getResultData(),
401 array( 0 => 'search', 1 => 'terms', 2 => 'descriptions', 3 => 'urls' )
402 ) );
403 foreach ( $remove as $key ) {
404 $result->removeValue( $key, null );
405 }
406 }
407
408 parent::execute();
409 }
410 }