Merge "Set default to 1 recent contributor instead of -1"
[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 use MediaWiki\MediaWikiServices;
28 use Wikimedia\Rdbms\Database;
29
30 /**
31 * @ingroup API
32 */
33 class ApiOpenSearch extends ApiBase {
34 use SearchApi;
35
36 private $format = null;
37 private $fm = null;
38
39 /** @var array list of api allowed params */
40 private $allowedParams = null;
41
42 /**
43 * Get the output format
44 *
45 * @return string
46 */
47 protected function getFormat() {
48 if ( $this->format === null ) {
49 $params = $this->extractRequestParams();
50 $format = $params['format'];
51
52 $allowedParams = $this->getAllowedParams();
53 if ( !in_array( $format, $allowedParams['format'][ApiBase::PARAM_TYPE] ) ) {
54 $format = $allowedParams['format'][ApiBase::PARAM_DFLT];
55 }
56
57 if ( substr( $format, -2 ) === 'fm' ) {
58 $this->format = substr( $format, 0, -2 );
59 $this->fm = 'fm';
60 } else {
61 $this->format = $format;
62 $this->fm = '';
63 }
64 }
65 return $this->format;
66 }
67
68 public function getCustomPrinter() {
69 switch ( $this->getFormat() ) {
70 case 'json':
71 return new ApiOpenSearchFormatJson(
72 $this->getMain(), $this->fm, $this->getParameter( 'warningsaserror' )
73 );
74
75 case 'xml':
76 $printer = $this->getMain()->createPrinterByName( 'xml' . $this->fm );
77 $printer->setRootElement( 'SearchSuggestion' );
78 return $printer;
79
80 default:
81 ApiBase::dieDebug( __METHOD__, "Unsupported format '{$this->getFormat()}'" );
82 }
83 }
84
85 public function execute() {
86 $params = $this->extractRequestParams();
87 $search = $params['search'];
88 $suggest = $params['suggest'];
89 $results = [];
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 );
95
96 // Allow hooks to populate extracts and images
97 Hooks::run( 'ApiOpenSearchSuggest', [ &$results ] );
98
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 );
104 }
105 }
106 }
107
108 // Populate result object
109 $this->populateResult( $search, $results );
110 }
111
112 /**
113 * Perform the search
114 * @param string $search the search query
115 * @param array $params api request params
116 * @return array search results. Keys are integers.
117 */
118 private function search( $search, array $params ) {
119 $searchEngine = $this->buildSearchEngine( $params );
120 $titles = $searchEngine->extractTitles( $searchEngine->completionSearchWithVariants( $search ) );
121 $results = [];
122
123 if ( !$titles ) {
124 return $results;
125 }
126
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;
131
132 if ( $params['redirects'] === null ) {
133 // Backwards compatibility, don't resolve for JSON.
134 $resolveRedir = $this->getFormat() !== 'json';
135 } else {
136 $resolveRedir = $params['redirects'] === 'resolve';
137 }
138
139 if ( $resolveRedir ) {
140 // Query for redirects
141 $redirects = [];
142 $lb = new LinkBatch( $titles );
143 if ( !$lb->isEmpty() ) {
144 $db = $this->getDB();
145 $res = $db->select(
146 [ 'page', 'redirect' ],
147 [ 'page_namespace', 'page_title', 'rd_namespace', 'rd_title' ],
148 [
149 'rd_from = page_id',
150 'rd_interwiki IS NULL OR rd_interwiki = ' . $db->addQuotes( '' ),
151 $lb->constructSet( 'page', $db ),
152 ],
153 __METHOD__
154 );
155 foreach ( $res as $row ) {
156 $redirects[$row->page_namespace][$row->page_title] =
157 [ $row->rd_namespace, $row->rd_title ];
158 }
159 }
160
161 // Bypass any redirects
162 $seen = [];
163 foreach ( $titles as $title ) {
164 $ns = $title->getNamespace();
165 $dbkey = $title->getDBkey();
166 $from = null;
167 if ( isset( $redirects[$ns][$dbkey] ) ) {
168 list( $ns, $dbkey ) = $redirects[$ns][$dbkey];
169 $from = $title;
170 $title = Title::makeTitle( $ns, $dbkey );
171 }
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;
178 }
179 $results[$resultId] = [
180 'title' => $title,
181 'redirect from' => $from,
182 'extract' => false,
183 'extract trimmed' => false,
184 'image' => false,
185 'url' => wfExpandUrl( $title->getFullURL(), PROTO_CURRENT ),
186 ];
187 }
188 }
189 } else {
190 foreach ( $titles as $title ) {
191 $resultId = $title->getArticleID();
192 if ( $resultId === 0 ) {
193 $resultId = $nextSpecialPageId;
194 $nextSpecialPageId -= 1;
195 }
196 $results[$resultId] = [
197 'title' => $title,
198 'redirect from' => null,
199 'extract' => false,
200 'extract trimmed' => false,
201 'image' => false,
202 'url' => wfExpandUrl( $title->getFullURL(), PROTO_CURRENT ),
203 ];
204 }
205 }
206
207 return $results;
208 }
209
210 /**
211 * @param string $search
212 * @param array &$results
213 */
214 protected function populateResult( $search, &$results ) {
215 $result = $this->getResult();
216
217 switch ( $this->getFormat() ) {
218 case 'json':
219 // http://www.opensearch.org/Specifications/OpenSearch/Extensions/Suggestions/1.1
220 $result->addArrayType( null, 'array' );
221 $result->addValue( null, 0, strval( $search ) );
222 $terms = [];
223 $descriptions = [];
224 $urls = [];
225 foreach ( $results as $r ) {
226 $terms[] = $r['title']->getPrefixedText();
227 $descriptions[] = strval( $r['extract'] );
228 $urls[] = $r['url'];
229 }
230 $result->addValue( null, 1, $terms );
231 $result->addValue( null, 2, $descriptions );
232 $result->addValue( null, 3, $urls );
233 break;
234
235 case 'xml':
236 // http://msdn.microsoft.com/en-us/library/cc891508%28v=vs.85%29.aspx
237 $imageKeys = [
238 'source' => true,
239 'alt' => true,
240 'width' => true,
241 'height' => true,
242 'align' => true,
243 ];
244 $items = [];
245 foreach ( $results as $r ) {
246 $item = [
247 'Text' => $r['title']->getPrefixedText(),
248 'Url' => $r['url'],
249 ];
250 if ( is_string( $r['extract'] ) && $r['extract'] !== '' ) {
251 $item['Description'] = $r['extract'];
252 }
253 if ( is_array( $r['image'] ) && isset( $r['image']['source'] ) ) {
254 $item['Image'] = array_intersect_key( $r['image'], $imageKeys );
255 }
256 ApiResult::setSubelementsList( $item, array_keys( $item ) );
257 $items[] = $item;
258 }
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 );
265 break;
266
267 default:
268 ApiBase::dieDebug( __METHOD__, "Unsupported format '{$this->getFormat()}'" );
269 }
270 }
271
272 public function getAllowedParams() {
273 if ( $this->allowedParams !== null ) {
274 return $this->allowedParams;
275 }
276 $this->allowedParams = $this->buildCommonApiParams( false ) + [
277 'suggest' => false,
278 'redirects' => [
279 ApiBase::PARAM_TYPE => [ 'return', 'resolve' ],
280 ],
281 'format' => [
282 ApiBase::PARAM_DFLT => 'json',
283 ApiBase::PARAM_TYPE => [ 'json', 'jsonfm', 'xml', 'xmlfm' ],
284 ],
285 'warningsaserror' => false,
286 ];
287
288 // Use open search specific default limit
289 $this->allowedParams['limit'][ApiBase::PARAM_DFLT] = $this->getConfig()->get(
290 'OpenSearchDefaultLimit'
291 );
292
293 return $this->allowedParams;
294 }
295
296 public function getSearchProfileParams() {
297 return [
298 'profile' => [
299 'profile-type' => SearchEngine::COMPLETION_PROFILE_TYPE,
300 'help-message' => 'apihelp-query+prefixsearch-param-profile'
301 ],
302 ];
303 }
304
305 protected function getExamplesMessages() {
306 return [
307 'action=opensearch&search=Te'
308 => 'apihelp-opensearch-example-te',
309 ];
310 }
311
312 public function getHelpUrls() {
313 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Opensearch';
314 }
315
316 /**
317 * Trim an extract to a sensible length.
318 *
319 * Adapted from Extension:OpenSearchXml, which adapted it from
320 * Extension:ActiveAbstract.
321 *
322 * @param string $text
323 * @param int $length Target length; actual result will continue to the end of a sentence.
324 * @return string
325 */
326 public static function trimExtract( $text, $length ) {
327 static $regex = null;
328
329 if ( $regex === null ) {
330 $endchars = [
331 '([^\d])\.\s', '\!\s', '\?\s', // regular ASCII
332 '。', // full-width ideographic full-stop
333 '.', '!', '?', // double-width roman forms
334 '。', // half-width ideographic full stop
335 ];
336 $endgroup = implode( '|', $endchars );
337 $end = "(?:$endgroup)";
338 $sentence = ".{{$length},}?$end+";
339 $regex = "/^($sentence)/u";
340 }
341
342 $matches = [];
343 if ( preg_match( $regex, $text, $matches ) ) {
344 return trim( $matches[1] );
345 } else {
346 // Just return the first line
347 return trim( explode( "\n", $text )[0] );
348 }
349 }
350
351 /**
352 * Fetch the template for a type.
353 *
354 * @param string $type MIME type
355 * @return string
356 * @throws MWException
357 */
358 public static function getOpenSearchTemplate( $type ) {
359 $config = MediaWikiServices::getInstance()->getSearchEngineConfig();
360 $template = $config->getConfig()->get( 'OpenSearchTemplate' );
361
362 if ( $template && $type === 'application/x-suggestions+json' ) {
363 return $template;
364 }
365
366 $ns = implode( '|', $config->defaultNamespaces() );
367 if ( !$ns ) {
368 $ns = '0';
369 }
370
371 switch ( $type ) {
372 case 'application/x-suggestions+json':
373 return $config->getConfig()->get( 'CanonicalServer' ) . wfScript( 'api' )
374 . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
375
376 case 'application/x-suggestions+xml':
377 return $config->getConfig()->get( 'CanonicalServer' ) . wfScript( 'api' )
378 . '?action=opensearch&format=xml&search={searchTerms}&namespace=' . $ns;
379
380 default:
381 throw new MWException( __METHOD__ . ": Unknown type '$type'" );
382 }
383 }
384 }
385
386 class ApiOpenSearchFormatJson extends ApiFormatJson {
387 private $warningsAsError = false;
388
389 public function __construct( ApiMain $main, $fm, $warningsAsError ) {
390 parent::__construct( $main, "json$fm" );
391 $this->warningsAsError = $warningsAsError;
392 }
393
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 ) {
400 $this->dieWithError(
401 'apierror-opensearch-json-warnings',
402 'warnings',
403 [ 'warnings' => $warnings ]
404 );
405 }
406
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' ]
411 ) );
412 foreach ( $remove as $key ) {
413 $result->removeValue( $key, null );
414 }
415 }
416
417 parent::execute();
418 }
419 }