Merge "Unsuppress other phan issues (part 4)"
[lhc/web/wiklou.git] / includes / api / ApiOpenSearch.php
1 <?php
2 /**
3 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
4 * Copyright © 2008 Brion Vibber <brion@wikimedia.org>
5 * Copyright © 2014 Wikimedia Foundation and contributors
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 *
22 * @file
23 */
24
25 use MediaWiki\MediaWikiServices;
26
27 /**
28 * @ingroup API
29 */
30 class ApiOpenSearch extends ApiBase {
31 use SearchApi;
32
33 private $format = null;
34 private $fm = null;
35
36 /** @var array list of api allowed params */
37 private $allowedParams = null;
38
39 /**
40 * Get the output format
41 *
42 * @return string
43 */
44 protected function getFormat() {
45 if ( $this->format === null ) {
46 $params = $this->extractRequestParams();
47 $format = $params['format'];
48
49 $allowedParams = $this->getAllowedParams();
50 if ( !in_array( $format, $allowedParams['format'][ApiBase::PARAM_TYPE] ) ) {
51 $format = $allowedParams['format'][ApiBase::PARAM_DFLT];
52 }
53
54 if ( substr( $format, -2 ) === 'fm' ) {
55 $this->format = substr( $format, 0, -2 );
56 $this->fm = 'fm';
57 } else {
58 $this->format = $format;
59 $this->fm = '';
60 }
61 }
62 return $this->format;
63 }
64
65 public function getCustomPrinter() {
66 switch ( $this->getFormat() ) {
67 case 'json':
68 return new ApiOpenSearchFormatJson(
69 $this->getMain(), $this->fm, $this->getParameter( 'warningsaserror' )
70 );
71
72 case 'xml':
73 $printer = $this->getMain()->createPrinterByName( 'xml' . $this->fm );
74 $printer->setRootElement( 'SearchSuggestion' );
75 return $printer;
76
77 default:
78 ApiBase::dieDebug( __METHOD__, "Unsupported format '{$this->getFormat()}'" );
79 }
80 }
81
82 public function execute() {
83 $params = $this->extractRequestParams();
84 $search = $params['search'];
85 $suggest = $params['suggest'];
86 $results = [];
87 if ( !$suggest || $this->getConfig()->get( 'EnableOpenSearchSuggest' ) ) {
88 // Open search results may be stored for a very long time
89 $this->getMain()->setCacheMaxAge( $this->getConfig()->get( 'SearchSuggestCacheExpiry' ) );
90 $this->getMain()->setCacheMode( 'public' );
91 $results = $this->search( $search, $params );
92
93 // Allow hooks to populate extracts and images
94 Hooks::run( 'ApiOpenSearchSuggest', [ &$results ] );
95
96 // Trim extracts, if necessary
97 $length = $this->getConfig()->get( 'OpenSearchDescriptionLength' );
98 foreach ( $results as &$r ) {
99 if ( is_string( $r['extract'] ) && !$r['extract trimmed'] ) {
100 $r['extract'] = self::trimExtract( $r['extract'], $length );
101 }
102 }
103 }
104
105 // Populate result object
106 $this->populateResult( $search, $results );
107 }
108
109 /**
110 * Perform the search
111 * @param string $search the search query
112 * @param array $params api request params
113 * @return array search results. Keys are integers.
114 * @phan-return array<array{title:Title,extract:false,image:false,url:string}>
115 * Note that phan annotations don't support keys containing a space.
116 */
117 private function search( $search, array $params ) {
118 $searchEngine = $this->buildSearchEngine( $params );
119 $titles = $searchEngine->extractTitles( $searchEngine->completionSearchWithVariants( $search ) );
120 $results = [];
121
122 if ( !$titles ) {
123 return $results;
124 }
125
126 // Special pages need unique integer ids in the return list, so we just
127 // assign them negative numbers because those won't clash with the
128 // always positive articleIds that non-special pages get.
129 $nextSpecialPageId = -1;
130
131 if ( $params['redirects'] === null ) {
132 // Backwards compatibility, don't resolve for JSON.
133 $resolveRedir = $this->getFormat() !== 'json';
134 } else {
135 $resolveRedir = $params['redirects'] === 'resolve';
136 }
137
138 if ( $resolveRedir ) {
139 // Query for redirects
140 $redirects = [];
141 $lb = new LinkBatch( $titles );
142 if ( !$lb->isEmpty() ) {
143 $db = $this->getDB();
144 $res = $db->select(
145 [ 'page', 'redirect' ],
146 [ 'page_namespace', 'page_title', 'rd_namespace', 'rd_title' ],
147 [
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 [ $row->rd_namespace, $row->rd_title ];
157 }
158 }
159
160 // Bypass any redirects
161 $seen = [];
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] = [
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] = [
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 return $results;
207 }
208
209 /**
210 * @param string $search
211 * @param array &$results
212 */
213 protected function populateResult( $search, &$results ) {
214 $result = $this->getResult();
215
216 switch ( $this->getFormat() ) {
217 case 'json':
218 // http://www.opensearch.org/Specifications/OpenSearch/Extensions/Suggestions/1.1
219 $result->addArrayType( null, 'array' );
220 $result->addValue( null, 0, strval( $search ) );
221 $terms = [];
222 $descriptions = [];
223 $urls = [];
224 foreach ( $results as $r ) {
225 $terms[] = $r['title']->getPrefixedText();
226 $descriptions[] = strval( $r['extract'] );
227 $urls[] = $r['url'];
228 }
229 $result->addValue( null, 1, $terms );
230 $result->addValue( null, 2, $descriptions );
231 $result->addValue( null, 3, $urls );
232 break;
233
234 case 'xml':
235 // https://msdn.microsoft.com/en-us/library/cc891508(v=vs.85).aspx
236 $imageKeys = [
237 'source' => true,
238 'alt' => true,
239 'width' => true,
240 'height' => true,
241 'align' => true,
242 ];
243 $items = [];
244 foreach ( $results as $r ) {
245 $item = [
246 'Text' => $r['title']->getPrefixedText(),
247 'Url' => $r['url'],
248 ];
249 if ( is_string( $r['extract'] ) && $r['extract'] !== '' ) {
250 $item['Description'] = $r['extract'];
251 }
252 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
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 }