Merge "API: Validate API error codes"
[lhc/web/wiklou.git] / includes / api / ApiErrorFormatter.php
1 <?php
2 /**
3 * This file contains the ApiErrorFormatter definition, plus implementations of
4 * specific formatters.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 */
23
24 /**
25 * Formats errors and warnings for the API, and add them to the associated
26 * ApiResult.
27 * @since 1.25
28 * @ingroup API
29 */
30 class ApiErrorFormatter {
31 /** @var Title Dummy title to silence warnings from MessageCache::parse() */
32 private static $dummyTitle = null;
33
34 /** @var ApiResult */
35 protected $result;
36
37 /** @var Language */
38 protected $lang;
39 protected $useDB = false;
40 protected $format = 'none';
41
42 /**
43 * @param ApiResult $result Into which data will be added
44 * @param Language $lang Used for i18n
45 * @param string $format
46 * - plaintext: Error message as something vaguely like plaintext
47 * (it's basically wikitext with HTML tags stripped and entities decoded)
48 * - wikitext: Error message as wikitext
49 * - html: Error message as HTML
50 * - raw: Raw message key and parameters, no human-readable text
51 * - none: Code and data only, no human-readable text
52 * @param bool $useDB Whether to use local translations for errors and warnings.
53 */
54 public function __construct( ApiResult $result, Language $lang, $format, $useDB = false ) {
55 $this->result = $result;
56 $this->lang = $lang;
57 $this->useDB = $useDB;
58 $this->format = $format;
59 }
60
61 /**
62 * Test whether a code is a valid API error code
63 *
64 * A valid code contains only ASCII letters, numbers, underscore, and
65 * hyphen and is not the empty string.
66 *
67 * For backwards compatibility, any code beginning 'internal_api_error_' is
68 * also allowed.
69 *
70 * @param string $code
71 * @return bool
72 */
73 public static function isValidApiCode( $code ) {
74 return is_string( $code ) && (
75 preg_match( '/^[a-zA-Z0-9_-]+$/', $code ) ||
76 // TODO: Deprecate this
77 preg_match( '/^internal_api_error_[^\0\r\n]+$/', $code )
78 );
79 }
80
81 /**
82 * Return a formatter like this one but with a different format
83 *
84 * @since 1.32
85 * @param string $format New format.
86 * @return ApiErrorFormatter
87 */
88 public function newWithFormat( $format ) {
89 return new self( $this->result, $this->lang, $format, $this->useDB );
90 }
91
92 /**
93 * Fetch the format for this formatter
94 * @since 1.32
95 * @return string
96 */
97 public function getFormat() {
98 return $this->format;
99 }
100
101 /**
102 * Fetch the Language for this formatter
103 * @since 1.29
104 * @return Language
105 */
106 public function getLanguage() {
107 return $this->lang;
108 }
109
110 /**
111 * Fetch a dummy title to set on Messages
112 * @return Title
113 */
114 protected function getDummyTitle() {
115 if ( self::$dummyTitle === null ) {
116 self::$dummyTitle = Title::makeTitle( NS_SPECIAL, 'Badtitle/' . __METHOD__ );
117 }
118 return self::$dummyTitle;
119 }
120
121 /**
122 * Add a warning to the result
123 * @param string|null $modulePath
124 * @param Message|array|string $msg Warning message. See ApiMessage::create().
125 * @param string|null $code See ApiMessage::create().
126 * @param array|null $data See ApiMessage::create().
127 */
128 public function addWarning( $modulePath, $msg, $code = null, $data = null ) {
129 $msg = ApiMessage::create( $msg, $code, $data )
130 ->inLanguage( $this->lang )
131 ->title( $this->getDummyTitle() )
132 ->useDatabase( $this->useDB );
133 $this->addWarningOrError( 'warning', $modulePath, $msg );
134 }
135
136 /**
137 * Add an error to the result
138 * @param string|null $modulePath
139 * @param Message|array|string $msg Warning message. See ApiMessage::create().
140 * @param string|null $code See ApiMessage::create().
141 * @param array|null $data See ApiMessage::create().
142 */
143 public function addError( $modulePath, $msg, $code = null, $data = null ) {
144 $msg = ApiMessage::create( $msg, $code, $data )
145 ->inLanguage( $this->lang )
146 ->title( $this->getDummyTitle() )
147 ->useDatabase( $this->useDB );
148 $this->addWarningOrError( 'error', $modulePath, $msg );
149 }
150
151 /**
152 * Add warnings and errors from a StatusValue object to the result
153 * @param string|null $modulePath
154 * @param StatusValue $status
155 * @param string[]|string $types 'warning' and/or 'error'
156 */
157 public function addMessagesFromStatus(
158 $modulePath, StatusValue $status, $types = [ 'warning', 'error' ]
159 ) {
160 if ( $status->isGood() || !$status->getErrors() ) {
161 return;
162 }
163
164 $types = (array)$types;
165 foreach ( $status->getErrors() as $error ) {
166 if ( !in_array( $error['type'], $types, true ) ) {
167 continue;
168 }
169
170 if ( $error['type'] === 'error' ) {
171 $tag = 'error';
172 } else {
173 // Assume any unknown type is a warning
174 $tag = 'warning';
175 }
176
177 $msg = ApiMessage::create( $error )
178 ->inLanguage( $this->lang )
179 ->title( $this->getDummyTitle() )
180 ->useDatabase( $this->useDB );
181 $this->addWarningOrError( $tag, $modulePath, $msg );
182 }
183 }
184
185 /**
186 * Get an ApiMessage from an exception
187 * @since 1.29
188 * @param Exception|Throwable $exception
189 * @param array $options
190 * - wrap: (string|array|MessageSpecifier) Used to wrap the exception's
191 * message if it's not an ILocalizedException. The exception's message
192 * will be added as the final parameter.
193 * - code: (string) Default code
194 * - data: (array) Default extra data
195 * @return IApiMessage
196 */
197 public function getMessageFromException( $exception, array $options = [] ) {
198 $options += [ 'code' => null, 'data' => [] ];
199
200 if ( $exception instanceof ILocalizedException ) {
201 $msg = $exception->getMessageObject();
202 $params = [];
203 } elseif ( $exception instanceof MessageSpecifier ) {
204 $msg = Message::newFromSpecifier( $exception );
205 $params = [];
206 } else {
207 if ( isset( $options['wrap'] ) ) {
208 $msg = $options['wrap'];
209 } else {
210 $msg = new RawMessage( '$1' );
211 if ( !isset( $options['code'] ) ) {
212 $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $exception ) );
213 $options['code'] = 'internal_api_error_' . $class;
214 }
215 }
216 $params = [ wfEscapeWikiText( $exception->getMessage() ) ];
217 }
218 return ApiMessage::create( $msg, $options['code'], $options['data'] )
219 ->params( $params )
220 ->inLanguage( $this->lang )
221 ->title( $this->getDummyTitle() )
222 ->useDatabase( $this->useDB );
223 }
224
225 /**
226 * Format an exception as an array
227 * @since 1.29
228 * @param Exception|Throwable $exception
229 * @param array $options See self::getMessageFromException(), plus
230 * - format: (string) Format override
231 * @return array
232 */
233 public function formatException( $exception, array $options = [] ) {
234 return $this->formatMessage(
235 $this->getMessageFromException( $exception, $options ),
236 $options['format'] ?? null
237 );
238 }
239
240 /**
241 * Format a message as an array
242 * @param Message|array|string $msg Message. See ApiMessage::create().
243 * @param string|null $format
244 * @return array
245 */
246 public function formatMessage( $msg, $format = null ) {
247 $msg = ApiMessage::create( $msg )
248 ->inLanguage( $this->lang )
249 ->title( $this->getDummyTitle() )
250 ->useDatabase( $this->useDB );
251 return $this->formatMessageInternal( $msg, $format ?: $this->format );
252 }
253
254 /**
255 * Format messages from a StatusValue as an array
256 * @param StatusValue $status
257 * @param string $type 'warning' or 'error'
258 * @param string|null $format
259 * @return array
260 */
261 public function arrayFromStatus( StatusValue $status, $type = 'error', $format = null ) {
262 if ( $status->isGood() || !$status->getErrors() ) {
263 return [];
264 }
265
266 $result = new ApiResult( 1e6 );
267 $formatter = new ApiErrorFormatter(
268 $result, $this->lang, $format ?: $this->format, $this->useDB
269 );
270 $formatter->addMessagesFromStatus( null, $status, [ $type ] );
271 switch ( $type ) {
272 case 'error':
273 return (array)$result->getResultData( [ 'errors' ] );
274 case 'warning':
275 return (array)$result->getResultData( [ 'warnings' ] );
276 }
277 }
278
279 /**
280 * Turn wikitext into something resembling plaintext
281 * @since 1.29
282 * @param string $text
283 * @return string
284 */
285 public static function stripMarkup( $text ) {
286 // Turn semantic quoting tags to quotes
287 $ret = preg_replace( '!</?(var|kbd|samp|code)>!', '"', $text );
288
289 // Strip tags and decode.
290 $ret = Sanitizer::stripAllTags( $ret );
291
292 return $ret;
293 }
294
295 /**
296 * Format a Message object for raw format
297 * @param MessageSpecifier $msg
298 * @return array
299 */
300 private function formatRawMessage( MessageSpecifier $msg ) {
301 $ret = [
302 'key' => $msg->getKey(),
303 'params' => $msg->getParams(),
304 ];
305 ApiResult::setIndexedTagName( $ret['params'], 'param' );
306
307 // Transform Messages as parameters in the style of Message::fooParam().
308 foreach ( $ret['params'] as $i => $param ) {
309 if ( $param instanceof MessageSpecifier ) {
310 $ret['params'][$i] = [ 'message' => $this->formatRawMessage( $param ) ];
311 }
312 }
313 return $ret;
314 }
315
316 /**
317 * Format a message as an array
318 * @since 1.29
319 * @param ApiMessage|ApiRawMessage $msg
320 * @param string|null $format
321 * @return array
322 */
323 protected function formatMessageInternal( $msg, $format ) {
324 $value = [ 'code' => $msg->getApiCode() ];
325 switch ( $format ) {
326 case 'plaintext':
327 $value += [
328 'text' => self::stripMarkup( $msg->text() ),
329 ApiResult::META_CONTENT => 'text',
330 ];
331 break;
332
333 case 'wikitext':
334 $value += [
335 'text' => $msg->text(),
336 ApiResult::META_CONTENT => 'text',
337 ];
338 break;
339
340 case 'html':
341 $value += [
342 'html' => $msg->parse(),
343 ApiResult::META_CONTENT => 'html',
344 ];
345 break;
346
347 case 'raw':
348 $value += $this->formatRawMessage( $msg );
349 break;
350
351 case 'none':
352 break;
353 }
354 $data = $msg->getApiData();
355 if ( $data ) {
356 $value['data'] = $msg->getApiData() + [
357 ApiResult::META_TYPE => 'assoc',
358 ];
359 }
360 return $value;
361 }
362
363 /**
364 * Actually add the warning or error to the result
365 * @param string $tag 'warning' or 'error'
366 * @param string|null $modulePath
367 * @param ApiMessage|ApiRawMessage $msg
368 */
369 protected function addWarningOrError( $tag, $modulePath, $msg ) {
370 $value = $this->formatMessageInternal( $msg, $this->format );
371 if ( $modulePath !== null ) {
372 $value += [ 'module' => $modulePath ];
373 }
374
375 $path = [ $tag . 's' ];
376 $existing = $this->result->getResultData( $path );
377 if ( $existing === null || !in_array( $value, $existing ) ) {
378 $flags = ApiResult::NO_SIZE_CHECK;
379 if ( $existing === null ) {
380 $flags |= ApiResult::ADD_ON_TOP;
381 }
382 $this->result->addValue( $path, null, $value, $flags );
383 $this->result->addIndexedTagName( $path, $tag );
384 }
385 }
386 }
387
388 /**
389 * Format errors and warnings in the old style, for backwards compatibility.
390 * @since 1.25
391 * @deprecated Only for backwards compatibility, do not use
392 * @ingroup API
393 */
394 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
395 class ApiErrorFormatter_BackCompat extends ApiErrorFormatter {
396
397 /**
398 * @param ApiResult $result Into which data will be added
399 */
400 public function __construct( ApiResult $result ) {
401 parent::__construct( $result, Language::factory( 'en' ), 'none', false );
402 }
403
404 public function getFormat() {
405 return 'bc';
406 }
407
408 public function arrayFromStatus( StatusValue $status, $type = 'error', $format = null ) {
409 if ( $status->isGood() || !$status->getErrors() ) {
410 return [];
411 }
412
413 $result = [];
414 foreach ( $status->getErrorsByType( $type ) as $error ) {
415 $msg = ApiMessage::create( $error );
416 $error = [
417 'message' => $msg->getKey(),
418 'params' => $msg->getParams(),
419 'code' => $msg->getApiCode(),
420 ] + $error;
421 ApiResult::setIndexedTagName( $error['params'], 'param' );
422 $result[] = $error;
423 }
424 ApiResult::setIndexedTagName( $result, $type );
425
426 return $result;
427 }
428
429 protected function formatMessageInternal( $msg, $format ) {
430 return [
431 'code' => $msg->getApiCode(),
432 'info' => $msg->text(),
433 ] + $msg->getApiData();
434 }
435
436 /**
437 * Format an exception as an array
438 * @since 1.29
439 * @param Exception|Throwable $exception
440 * @param array $options See parent::formatException(), plus
441 * - bc: (bool) Return only the string, not an array
442 * @return array|string
443 */
444 public function formatException( $exception, array $options = [] ) {
445 $ret = parent::formatException( $exception, $options );
446 return empty( $options['bc'] ) ? $ret : $ret['info'];
447 }
448
449 protected function addWarningOrError( $tag, $modulePath, $msg ) {
450 $value = self::stripMarkup( $msg->text() );
451
452 if ( $tag === 'error' ) {
453 // In BC mode, only one error
454 $existingError = $this->result->getResultData( [ 'error' ] );
455 if ( !is_array( $existingError ) ||
456 !isset( $existingError['code'] ) || !isset( $existingError['info'] )
457 ) {
458 $value = [
459 'code' => $msg->getApiCode(),
460 'info' => $value,
461 ] + $msg->getApiData();
462 $this->result->addValue( null, 'error', $value,
463 ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
464 }
465 } else {
466 if ( $modulePath === null ) {
467 $moduleName = 'unknown';
468 } else {
469 $i = strrpos( $modulePath, '+' );
470 $moduleName = $i === false ? $modulePath : substr( $modulePath, $i + 1 );
471 }
472
473 // Don't add duplicate warnings
474 $tag .= 's';
475 $path = [ $tag, $moduleName ];
476 $oldWarning = $this->result->getResultData( [ $tag, $moduleName, $tag ] );
477 if ( $oldWarning !== null ) {
478 $warnPos = strpos( $oldWarning, $value );
479 // If $value was found in $oldWarning, check if it starts at 0 or after "\n"
480 if ( $warnPos !== false && ( $warnPos === 0 || $oldWarning[$warnPos - 1] === "\n" ) ) {
481 // Check if $value is followed by "\n" or the end of the $oldWarning
482 $warnPos += strlen( $value );
483 if ( strlen( $oldWarning ) <= $warnPos || $oldWarning[$warnPos] === "\n" ) {
484 return;
485 }
486 }
487 // If there is a warning already, append it to the existing one
488 $value = "$oldWarning\n$value";
489 }
490 $this->result->addContentValue( $path, $tag, $value,
491 ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
492 }
493 }
494 }