Fix use of GenderCache in ApiPageSet::processTitlesArray
[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 // @phan-suppress-next-line PhanTypeInvalidDimOffset
100 if ( is_string( $r['extract'] ) && !$r['extract trimmed'] ) {
101 $r['extract'] = self::trimExtract( $r['extract'], $length );
102 }
103 }
104 }
105
106 // Populate result object
107 $this->populateResult( $search, $results );
108 }
109
110 /**
111 * Perform the search
112 * @param string $search the search query
113 * @param array $params api request params
114 * @return array search results. Keys are integers.
115 * @phan-return array<array{title:Title,extract:false,image:false,url:string}>
116 * Note that phan annotations don't support keys containing a space.
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 // https://msdn.microsoft.com/en-us/library/cc891508(v=vs.85).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 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
254 if ( is_array( $r['image'] ) && isset( $r['image']['source'] ) ) {
255 $item['Image'] = array_intersect_key( $r['image'], $imageKeys );
256 }
257 ApiResult::setSubelementsList( $item, array_keys( $item ) );
258 $items[] = $item;
259 }
260 ApiResult::setIndexedTagName( $items, 'Item' );
261 $result->addValue( null, 'version', '2.0' );
262 $result->addValue( null, 'xmlns', 'http://opensearch.org/searchsuggest2' );
263 $result->addValue( null, 'Query', strval( $search ) );
264 $result->addSubelementsList( null, 'Query' );
265 $result->addValue( null, 'Section', $items );
266 break;
267
268 default:
269 ApiBase::dieDebug( __METHOD__, "Unsupported format '{$this->getFormat()}'" );
270 }
271 }
272
273 public function getAllowedParams() {
274 if ( $this->allowedParams !== null ) {
275 return $this->allowedParams;
276 }
277 $this->allowedParams = $this->buildCommonApiParams( false ) + [
278 'suggest' => false,
279 'redirects' => [
280 ApiBase::PARAM_TYPE => [ 'return', 'resolve' ],
281 ],
282 'format' => [
283 ApiBase::PARAM_DFLT => 'json',
284 ApiBase::PARAM_TYPE => [ 'json', 'jsonfm', 'xml', 'xmlfm' ],
285 ],
286 'warningsaserror' => false,
287 ];
288
289 // Use open search specific default limit
290 $this->allowedParams['limit'][ApiBase::PARAM_DFLT] = $this->getConfig()->get(
291 'OpenSearchDefaultLimit'
292 );
293
294 return $this->allowedParams;
295 }
296
297 public function getSearchProfileParams() {
298 return [
299 'profile' => [
300 'profile-type' => SearchEngine::COMPLETION_PROFILE_TYPE,
301 'help-message' => 'apihelp-query+prefixsearch-param-profile'
302 ],
303 ];
304 }
305
306 protected function getExamplesMessages() {
307 return [
308 'action=opensearch&search=Te'
309 => 'apihelp-opensearch-example-te',
310 ];
311 }
312
313 public function getHelpUrls() {
314 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Opensearch';
315 }
316
317 /**
318 * Trim an extract to a sensible length.
319 *
320 * Adapted from Extension:OpenSearchXml, which adapted it from
321 * Extension:ActiveAbstract.
322 *
323 * @param string $text
324 * @param int $length Target length; actual result will continue to the end of a sentence.
325 * @return string
326 */
327 public static function trimExtract( $text, $length ) {
328 static $regex = null;
329
330 if ( $regex === null ) {
331 $endchars = [
332 '([^\d])\.\s', '\!\s', '\?\s', // regular ASCII
333 '。', // full-width ideographic full-stop
334 '.', '!', '?', // double-width roman forms
335 '。', // half-width ideographic full stop
336 ];
337 $endgroup = implode( '|', $endchars );
338 $end = "(?:$endgroup)";
339 $sentence = ".{{$length},}?$end+";
340 $regex = "/^($sentence)/u";
341 }
342
343 $matches = [];
344 if ( preg_match( $regex, $text, $matches ) ) {
345 return trim( $matches[1] );
346 } else {
347 // Just return the first line
348 return trim( explode( "\n", $text )[0] );
349 }
350 }
351
352 /**
353 * Fetch the template for a type.
354 *
355 * @param string $type MIME type
356 * @return string
357 * @throws MWException
358 */
359 public static function getOpenSearchTemplate( $type ) {
360 $config = MediaWikiServices::getInstance()->getSearchEngineConfig();
361 $template = $config->getConfig()->get( 'OpenSearchTemplate' );
362
363 if ( $template && $type === 'application/x-suggestions+json' ) {
364 return $template;
365 }
366
367 $ns = implode( '|', $config->defaultNamespaces() );
368 if ( !$ns ) {
369 $ns = '0';
370 }
371
372 switch ( $type ) {
373 case 'application/x-suggestions+json':
374 return $config->getConfig()->get( 'CanonicalServer' ) . wfScript( 'api' )
375 . '?action=opensearch&search={searchTerms}&namespace=' . $ns;
376
377 case 'application/x-suggestions+xml':
378 return $config->getConfig()->get( 'CanonicalServer' ) . wfScript( 'api' )
379 . '?action=opensearch&format=xml&search={searchTerms}&namespace=' . $ns;
380
381 default:
382 throw new MWException( __METHOD__ . ": Unknown type '$type'" );
383 }
384 }
385 }