3 * This file contains the ApiErrorFormatter definition, plus implementations of
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.
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.
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
25 * Formats errors and warnings for the API, and add them to the associated
30 class ApiErrorFormatter
{
31 /** @var Title Dummy title to silence warnings from MessageCache::parse() */
32 private static $dummyTitle = null;
39 protected $useDB = false;
40 protected $format = 'none';
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.
54 public function __construct( ApiResult
$result, Language
$lang, $format, $useDB = false ) {
55 $this->result
= $result;
57 $this->useDB
= $useDB;
58 $this->format
= $format;
62 * Test whether a code is a valid API error code
64 * A valid code contains only ASCII letters, numbers, underscore, and
65 * hyphen and is not the empty string.
67 * For backwards compatibility, any code beginning 'internal_api_error_' is
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 )
82 * Return a formatter like this one but with a different format
85 * @param string $format New format.
86 * @return ApiErrorFormatter
88 public function newWithFormat( $format ) {
89 return new self( $this->result
, $this->lang
, $format, $this->useDB
);
93 * Fetch the format for this formatter
97 public function getFormat() {
102 * Fetch the Language for this formatter
106 public function getLanguage() {
111 * Fetch a dummy title to set on Messages
114 protected function getDummyTitle() {
115 if ( self
::$dummyTitle === null ) {
116 self
::$dummyTitle = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/' . __METHOD__
);
118 return self
::$dummyTitle;
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().
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 );
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().
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 );
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'
157 public function addMessagesFromStatus(
158 $modulePath, StatusValue
$status, $types = [ 'warning', 'error' ]
160 if ( $status->isGood() ||
!$status->getErrors() ) {
164 $types = (array)$types;
165 foreach ( $status->getErrors() as $error ) {
166 if ( !in_array( $error['type'], $types, true ) ) {
170 if ( $error['type'] === 'error' ) {
173 // Assume any unknown type is a warning
177 $msg = ApiMessage
::create( $error )
178 ->inLanguage( $this->lang
)
179 ->title( $this->getDummyTitle() )
180 ->useDatabase( $this->useDB
);
181 $this->addWarningOrError( $tag, $modulePath, $msg );
186 * Get an ApiMessage from an exception
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
197 public function getMessageFromException( $exception, array $options = [] ) {
198 $options +
= [ 'code' => null, 'data' => [] ];
200 if ( $exception instanceof ILocalizedException
) {
201 $msg = $exception->getMessageObject();
203 } elseif ( $exception instanceof MessageSpecifier
) {
204 $msg = Message
::newFromSpecifier( $exception );
207 if ( isset( $options['wrap'] ) ) {
208 $msg = $options['wrap'];
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 $options['data']['errorclass'] = get_class( $exception );
217 $params = [ wfEscapeWikiText( $exception->getMessage() ) ];
219 return ApiMessage
::create( $msg, $options['code'], $options['data'] )
221 ->inLanguage( $this->lang
)
222 ->title( $this->getDummyTitle() )
223 ->useDatabase( $this->useDB
);
227 * Format an exception as an array
229 * @param Exception|Throwable $exception
230 * @param array $options See self::getMessageFromException(), plus
231 * - format: (string) Format override
234 public function formatException( $exception, array $options = [] ) {
235 return $this->formatMessage(
236 $this->getMessageFromException( $exception, $options ),
237 $options['format'] ??
null
242 * Format a message as an array
243 * @param Message|array|string $msg Message. See ApiMessage::create().
244 * @param string|null $format
247 public function formatMessage( $msg, $format = null ) {
248 $msg = ApiMessage
::create( $msg )
249 ->inLanguage( $this->lang
)
250 ->title( $this->getDummyTitle() )
251 ->useDatabase( $this->useDB
);
252 return $this->formatMessageInternal( $msg, $format ?
: $this->format
);
256 * Format messages from a StatusValue as an array
257 * @param StatusValue $status
258 * @param string $type 'warning' or 'error'
259 * @param string|null $format
262 public function arrayFromStatus( StatusValue
$status, $type = 'error', $format = null ) {
263 if ( $status->isGood() ||
!$status->getErrors() ) {
267 $result = new ApiResult( 1e6
);
268 $formatter = new ApiErrorFormatter(
269 $result, $this->lang
, $format ?
: $this->format
, $this->useDB
271 $formatter->addMessagesFromStatus( null, $status, [ $type ] );
274 return (array)$result->getResultData( [ 'errors' ] );
276 return (array)$result->getResultData( [ 'warnings' ] );
281 * Turn wikitext into something resembling plaintext
283 * @param string $text
286 public static function stripMarkup( $text ) {
287 // Turn semantic quoting tags to quotes
288 $ret = preg_replace( '!</?(var|kbd|samp|code)>!', '"', $text );
290 // Strip tags and decode.
291 $ret = Sanitizer
::stripAllTags( $ret );
297 * Format a Message object for raw format
298 * @param MessageSpecifier $msg
301 private function formatRawMessage( MessageSpecifier
$msg ) {
303 'key' => $msg->getKey(),
304 'params' => $msg->getParams(),
306 ApiResult
::setIndexedTagName( $ret['params'], 'param' );
308 // Transform Messages as parameters in the style of Message::fooParam().
309 foreach ( $ret['params'] as $i => $param ) {
310 if ( $param instanceof MessageSpecifier
) {
311 $ret['params'][$i] = [ 'message' => $this->formatRawMessage( $param ) ];
318 * Format a message as an array
320 * @param ApiMessage|ApiRawMessage $msg
321 * @param string|null $format
324 protected function formatMessageInternal( $msg, $format ) {
325 $value = [ 'code' => $msg->getApiCode() ];
329 'text' => self
::stripMarkup( $msg->text() ),
330 ApiResult
::META_CONTENT
=> 'text',
336 'text' => $msg->text(),
337 ApiResult
::META_CONTENT
=> 'text',
343 'html' => $msg->parse(),
344 ApiResult
::META_CONTENT
=> 'html',
349 $value +
= $this->formatRawMessage( $msg );
355 $data = $msg->getApiData();
357 $value['data'] = $msg->getApiData() +
[
358 ApiResult
::META_TYPE
=> 'assoc',
365 * Actually add the warning or error to the result
366 * @param string $tag 'warning' or 'error'
367 * @param string|null $modulePath
368 * @param ApiMessage|ApiRawMessage $msg
370 protected function addWarningOrError( $tag, $modulePath, $msg ) {
371 $value = $this->formatMessageInternal( $msg, $this->format
);
372 if ( $modulePath !== null ) {
373 $value +
= [ 'module' => $modulePath ];
376 $path = [ $tag . 's' ];
377 $existing = $this->result
->getResultData( $path );
378 if ( $existing === null ||
!in_array( $value, $existing ) ) {
379 $flags = ApiResult
::NO_SIZE_CHECK
;
380 if ( $existing === null ) {
381 $flags |
= ApiResult
::ADD_ON_TOP
;
383 $this->result
->addValue( $path, null, $value, $flags );
384 $this->result
->addIndexedTagName( $path, $tag );
390 * Format errors and warnings in the old style, for backwards compatibility.
392 * @deprecated Only for backwards compatibility, do not use
395 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
396 class ApiErrorFormatter_BackCompat
extends ApiErrorFormatter
{
399 * @param ApiResult $result Into which data will be added
401 public function __construct( ApiResult
$result ) {
402 parent
::__construct( $result, Language
::factory( 'en' ), 'none', false );
405 public function getFormat() {
409 public function arrayFromStatus( StatusValue
$status, $type = 'error', $format = null ) {
410 if ( $status->isGood() ||
!$status->getErrors() ) {
415 foreach ( $status->getErrorsByType( $type ) as $error ) {
416 $msg = ApiMessage
::create( $error );
418 'message' => $msg->getKey(),
419 'params' => $msg->getParams(),
420 'code' => $msg->getApiCode(),
422 ApiResult
::setIndexedTagName( $error['params'], 'param' );
425 ApiResult
::setIndexedTagName( $result, $type );
430 protected function formatMessageInternal( $msg, $format ) {
432 'code' => $msg->getApiCode(),
433 'info' => $msg->text(),
434 ] +
$msg->getApiData();
438 * Format an exception as an array
440 * @param Exception|Throwable $exception
441 * @param array $options See parent::formatException(), plus
442 * - bc: (bool) Return only the string, not an array
443 * @return array|string
445 public function formatException( $exception, array $options = [] ) {
446 $ret = parent
::formatException( $exception, $options );
447 return empty( $options['bc'] ) ?
$ret : $ret['info'];
450 protected function addWarningOrError( $tag, $modulePath, $msg ) {
451 $value = self
::stripMarkup( $msg->text() );
453 if ( $tag === 'error' ) {
454 // In BC mode, only one error
455 $existingError = $this->result
->getResultData( [ 'error' ] );
456 if ( !is_array( $existingError ) ||
457 !isset( $existingError['code'] ) ||
!isset( $existingError['info'] )
460 'code' => $msg->getApiCode(),
462 ] +
$msg->getApiData();
463 $this->result
->addValue( null, 'error', $value,
464 ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP | ApiResult
::NO_SIZE_CHECK
);
467 if ( $modulePath === null ) {
468 $moduleName = 'unknown';
470 $i = strrpos( $modulePath, '+' );
471 $moduleName = $i === false ?
$modulePath : substr( $modulePath, $i +
1 );
474 // Don't add duplicate warnings
476 $path = [ $tag, $moduleName ];
477 $oldWarning = $this->result
->getResultData( [ $tag, $moduleName, $tag ] );
478 if ( $oldWarning !== null ) {
479 $warnPos = strpos( $oldWarning, $value );
480 // If $value was found in $oldWarning, check if it starts at 0 or after "\n"
481 if ( $warnPos !== false && ( $warnPos === 0 ||
$oldWarning[$warnPos - 1] === "\n" ) ) {
482 // Check if $value is followed by "\n" or the end of the $oldWarning
483 $warnPos +
= strlen( $value );
484 if ( strlen( $oldWarning ) <= $warnPos ||
$oldWarning[$warnPos] === "\n" ) {
488 // If there is a warning already, append it to the existing one
489 $value = "$oldWarning\n$value";
491 $this->result
->addContentValue( $path, $tag, $value,
492 ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP | ApiResult
::NO_SIZE_CHECK
);