Merge "Avoid expensive array_shift where possible"
[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 * @param string[] $filter Messages to filter out (since 1.33)
157 */
158 public function addMessagesFromStatus(
159 $modulePath, StatusValue $status, $types = [ 'warning', 'error' ], array $filter = []
160 ) {
161 if ( $status->isGood() || !$status->getErrors() ) {
162 return;
163 }
164
165 $types = (array)$types;
166 foreach ( $status->getErrors() as $error ) {
167 if ( !in_array( $error['type'], $types, true ) ) {
168 continue;
169 }
170
171 if ( $error['type'] === 'error' ) {
172 $tag = 'error';
173 } else {
174 // Assume any unknown type is a warning
175 $tag = 'warning';
176 }
177
178 $msg = ApiMessage::create( $error )
179 ->inLanguage( $this->lang )
180 ->title( $this->getDummyTitle() )
181 ->useDatabase( $this->useDB );
182 if ( !in_array( $msg->getKey(), $filter, true ) ) {
183 $this->addWarningOrError( $tag, $modulePath, $msg );
184 }
185 }
186 }
187
188 /**
189 * Get an ApiMessage from an exception
190 * @since 1.29
191 * @param Exception|Throwable $exception
192 * @param array $options
193 * - wrap: (string|array|MessageSpecifier) Used to wrap the exception's
194 * message if it's not an ILocalizedException. The exception's message
195 * will be added as the final parameter.
196 * - code: (string) Default code
197 * - data: (array) Default extra data
198 * @return IApiMessage
199 */
200 public function getMessageFromException( $exception, array $options = [] ) {
201 $options += [ 'code' => null, 'data' => [] ];
202
203 if ( $exception instanceof ILocalizedException ) {
204 $msg = $exception->getMessageObject();
205 $params = [];
206 } elseif ( $exception instanceof MessageSpecifier ) {
207 $msg = Message::newFromSpecifier( $exception );
208 $params = [];
209 } else {
210 if ( isset( $options['wrap'] ) ) {
211 $msg = $options['wrap'];
212 } else {
213 $msg = new RawMessage( '$1' );
214 if ( !isset( $options['code'] ) ) {
215 $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $exception ) );
216 $options['code'] = 'internal_api_error_' . $class;
217 $options['data']['errorclass'] = get_class( $exception );
218 }
219 }
220 $params = [ wfEscapeWikiText( $exception->getMessage() ) ];
221 }
222 return ApiMessage::create( $msg, $options['code'], $options['data'] )
223 ->params( $params )
224 ->inLanguage( $this->lang )
225 ->title( $this->getDummyTitle() )
226 ->useDatabase( $this->useDB );
227 }
228
229 /**
230 * Format an exception as an array
231 * @since 1.29
232 * @param Exception|Throwable $exception
233 * @param array $options See self::getMessageFromException(), plus
234 * - format: (string) Format override
235 * @return array
236 */
237 public function formatException( $exception, array $options = [] ) {
238 return $this->formatMessage(
239 $this->getMessageFromException( $exception, $options ),
240 $options['format'] ?? null
241 );
242 }
243
244 /**
245 * Format a message as an array
246 * @param Message|array|string $msg Message. See ApiMessage::create().
247 * @param string|null $format
248 * @return array
249 */
250 public function formatMessage( $msg, $format = null ) {
251 $msg = ApiMessage::create( $msg )
252 ->inLanguage( $this->lang )
253 ->title( $this->getDummyTitle() )
254 ->useDatabase( $this->useDB );
255 return $this->formatMessageInternal( $msg, $format ?: $this->format );
256 }
257
258 /**
259 * Format messages from a StatusValue as an array
260 * @param StatusValue $status
261 * @param string $type 'warning' or 'error'
262 * @param string|null $format
263 * @return array
264 */
265 public function arrayFromStatus( StatusValue $status, $type = 'error', $format = null ) {
266 if ( $status->isGood() || !$status->getErrors() ) {
267 return [];
268 }
269
270 $result = new ApiResult( 1e6 );
271 $formatter = new ApiErrorFormatter(
272 $result, $this->lang, $format ?: $this->format, $this->useDB
273 );
274 $formatter->addMessagesFromStatus( null, $status, [ $type ] );
275 switch ( $type ) {
276 case 'error':
277 return (array)$result->getResultData( [ 'errors' ] );
278 case 'warning':
279 return (array)$result->getResultData( [ 'warnings' ] );
280 }
281 }
282
283 /**
284 * Turn wikitext into something resembling plaintext
285 * @since 1.29
286 * @param string $text
287 * @return string
288 */
289 public static function stripMarkup( $text ) {
290 // Turn semantic quoting tags to quotes
291 $ret = preg_replace( '!</?(var|kbd|samp|code)>!', '"', $text );
292
293 // Strip tags and decode.
294 $ret = Sanitizer::stripAllTags( $ret );
295
296 return $ret;
297 }
298
299 /**
300 * Format a Message object for raw format
301 * @param MessageSpecifier $msg
302 * @return array
303 */
304 private function formatRawMessage( MessageSpecifier $msg ) {
305 $ret = [
306 'key' => $msg->getKey(),
307 'params' => $msg->getParams(),
308 ];
309 ApiResult::setIndexedTagName( $ret['params'], 'param' );
310
311 // Transform Messages as parameters in the style of Message::fooParam().
312 foreach ( $ret['params'] as $i => $param ) {
313 if ( $param instanceof MessageSpecifier ) {
314 $ret['params'][$i] = [ 'message' => $this->formatRawMessage( $param ) ];
315 }
316 }
317 return $ret;
318 }
319
320 /**
321 * Format a message as an array
322 * @since 1.29
323 * @param ApiMessage|ApiRawMessage $msg
324 * @param string|null $format
325 * @return array
326 */
327 protected function formatMessageInternal( $msg, $format ) {
328 $value = [ 'code' => $msg->getApiCode() ];
329 switch ( $format ) {
330 case 'plaintext':
331 $value += [
332 'text' => self::stripMarkup( $msg->text() ),
333 ApiResult::META_CONTENT => 'text',
334 ];
335 break;
336
337 case 'wikitext':
338 $value += [
339 'text' => $msg->text(),
340 ApiResult::META_CONTENT => 'text',
341 ];
342 break;
343
344 case 'html':
345 $value += [
346 'html' => $msg->parse(),
347 ApiResult::META_CONTENT => 'html',
348 ];
349 break;
350
351 case 'raw':
352 $value += $this->formatRawMessage( $msg );
353 break;
354
355 case 'none':
356 break;
357 }
358 $data = $msg->getApiData();
359 if ( $data ) {
360 $value['data'] = $msg->getApiData() + [
361 ApiResult::META_TYPE => 'assoc',
362 ];
363 }
364 return $value;
365 }
366
367 /**
368 * Actually add the warning or error to the result
369 * @param string $tag 'warning' or 'error'
370 * @param string|null $modulePath
371 * @param ApiMessage|ApiRawMessage $msg
372 */
373 protected function addWarningOrError( $tag, $modulePath, $msg ) {
374 $value = $this->formatMessageInternal( $msg, $this->format );
375 if ( $modulePath !== null ) {
376 $value += [ 'module' => $modulePath ];
377 }
378
379 $path = [ $tag . 's' ];
380 $existing = $this->result->getResultData( $path );
381 if ( $existing === null || !in_array( $value, $existing ) ) {
382 $flags = ApiResult::NO_SIZE_CHECK;
383 if ( $existing === null ) {
384 $flags |= ApiResult::ADD_ON_TOP;
385 }
386 $this->result->addValue( $path, null, $value, $flags );
387 $this->result->addIndexedTagName( $path, $tag );
388 }
389 }
390 }
391
392 /**
393 * Format errors and warnings in the old style, for backwards compatibility.
394 * @since 1.25
395 * @deprecated Only for backwards compatibility, do not use
396 * @ingroup API
397 */
398 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
399 class ApiErrorFormatter_BackCompat extends ApiErrorFormatter {
400
401 /**
402 * @param ApiResult $result Into which data will be added
403 */
404 public function __construct( ApiResult $result ) {
405 parent::__construct( $result, Language::factory( 'en' ), 'none', false );
406 }
407
408 public function getFormat() {
409 return 'bc';
410 }
411
412 public function arrayFromStatus( StatusValue $status, $type = 'error', $format = null ) {
413 if ( $status->isGood() || !$status->getErrors() ) {
414 return [];
415 }
416
417 $result = [];
418 foreach ( $status->getErrorsByType( $type ) as $error ) {
419 $msg = ApiMessage::create( $error );
420 $error = [
421 'message' => $msg->getKey(),
422 'params' => $msg->getParams(),
423 'code' => $msg->getApiCode(),
424 ] + $error;
425 ApiResult::setIndexedTagName( $error['params'], 'param' );
426 $result[] = $error;
427 }
428 ApiResult::setIndexedTagName( $result, $type );
429
430 return $result;
431 }
432
433 protected function formatMessageInternal( $msg, $format ) {
434 return [
435 'code' => $msg->getApiCode(),
436 'info' => $msg->text(),
437 ] + $msg->getApiData();
438 }
439
440 /**
441 * Format an exception as an array
442 * @since 1.29
443 * @param Exception|Throwable $exception
444 * @param array $options See parent::formatException(), plus
445 * - bc: (bool) Return only the string, not an array
446 * @return array|string
447 */
448 public function formatException( $exception, array $options = [] ) {
449 $ret = parent::formatException( $exception, $options );
450 return empty( $options['bc'] ) ? $ret : $ret['info'];
451 }
452
453 protected function addWarningOrError( $tag, $modulePath, $msg ) {
454 $value = self::stripMarkup( $msg->text() );
455
456 if ( $tag === 'error' ) {
457 // In BC mode, only one error
458 $existingError = $this->result->getResultData( [ 'error' ] );
459 if ( !is_array( $existingError ) ||
460 !isset( $existingError['code'] ) || !isset( $existingError['info'] )
461 ) {
462 $value = [
463 'code' => $msg->getApiCode(),
464 'info' => $value,
465 ] + $msg->getApiData();
466 $this->result->addValue( null, 'error', $value,
467 ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
468 }
469 } else {
470 if ( $modulePath === null ) {
471 $moduleName = 'unknown';
472 } else {
473 $i = strrpos( $modulePath, '+' );
474 $moduleName = $i === false ? $modulePath : substr( $modulePath, $i + 1 );
475 }
476
477 // Don't add duplicate warnings
478 $tag .= 's';
479 $path = [ $tag, $moduleName ];
480 $oldWarning = $this->result->getResultData( [ $tag, $moduleName, $tag ] );
481 if ( $oldWarning !== null ) {
482 $warnPos = strpos( $oldWarning, $value );
483 // If $value was found in $oldWarning, check if it starts at 0 or after "\n"
484 if ( $warnPos !== false && ( $warnPos === 0 || $oldWarning[$warnPos - 1] === "\n" ) ) {
485 // Check if $value is followed by "\n" or the end of the $oldWarning
486 $warnPos += strlen( $value );
487 if ( strlen( $oldWarning ) <= $warnPos || $oldWarning[$warnPos] === "\n" ) {
488 return;
489 }
490 }
491 // If there is a warning already, append it to the existing one
492 $value = "$oldWarning\n$value";
493 }
494 $this->result->addContentValue( $path, $tag, $value,
495 ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
496 }
497 }
498 }