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 * Return a formatter like this one but with a different format
65 * @param string $format New format.
66 * @return ApiErrorFormatter
68 public function newWithFormat( $format ) {
69 return new self( $this->result
, $this->lang
, $format, $this->useDB
);
73 * Fetch the format for this formatter
77 public function getFormat() {
82 * Fetch the Language for this formatter
86 public function getLanguage() {
91 * Fetch a dummy title to set on Messages
94 protected function getDummyTitle() {
95 if ( self
::$dummyTitle === null ) {
96 self
::$dummyTitle = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/' . __METHOD__
);
98 return self
::$dummyTitle;
102 * Add a warning to the result
103 * @param string|null $modulePath
104 * @param Message|array|string $msg Warning message. See ApiMessage::create().
105 * @param string|null $code See ApiMessage::create().
106 * @param array|null $data See ApiMessage::create().
108 public function addWarning( $modulePath, $msg, $code = null, $data = null ) {
109 $msg = ApiMessage
::create( $msg, $code, $data )
110 ->inLanguage( $this->lang
)
111 ->title( $this->getDummyTitle() )
112 ->useDatabase( $this->useDB
);
113 $this->addWarningOrError( 'warning', $modulePath, $msg );
117 * Add an error to the result
118 * @param string|null $modulePath
119 * @param Message|array|string $msg Warning message. See ApiMessage::create().
120 * @param string|null $code See ApiMessage::create().
121 * @param array|null $data See ApiMessage::create().
123 public function addError( $modulePath, $msg, $code = null, $data = null ) {
124 $msg = ApiMessage
::create( $msg, $code, $data )
125 ->inLanguage( $this->lang
)
126 ->title( $this->getDummyTitle() )
127 ->useDatabase( $this->useDB
);
128 $this->addWarningOrError( 'error', $modulePath, $msg );
132 * Add warnings and errors from a StatusValue object to the result
133 * @param string|null $modulePath
134 * @param StatusValue $status
135 * @param string[]|string $types 'warning' and/or 'error'
137 public function addMessagesFromStatus(
138 $modulePath, StatusValue
$status, $types = [ 'warning', 'error' ]
140 if ( $status->isGood() ||
!$status->getErrors() ) {
144 $types = (array)$types;
145 foreach ( $status->getErrors() as $error ) {
146 if ( !in_array( $error['type'], $types, true ) ) {
150 if ( $error['type'] === 'error' ) {
153 // Assume any unknown type is a warning
157 $msg = ApiMessage
::create( $error )
158 ->inLanguage( $this->lang
)
159 ->title( $this->getDummyTitle() )
160 ->useDatabase( $this->useDB
);
161 $this->addWarningOrError( $tag, $modulePath, $msg );
166 * Get an ApiMessage from an exception
168 * @param Exception|Throwable $exception
169 * @param array $options
170 * - wrap: (string|array|MessageSpecifier) Used to wrap the exception's
171 * message if it's not an ILocalizedException. The exception's message
172 * will be added as the final parameter.
173 * - code: (string) Default code
174 * - data: (array) Default extra data
175 * @return IApiMessage
177 public function getMessageFromException( $exception, array $options = [] ) {
178 $options +
= [ 'code' => null, 'data' => [] ];
180 if ( $exception instanceof ILocalizedException
) {
181 $msg = $exception->getMessageObject();
183 } elseif ( $exception instanceof MessageSpecifier
) {
184 $msg = Message
::newFromSpecifier( $exception );
187 if ( isset( $options['wrap'] ) ) {
188 $msg = $options['wrap'];
190 $msg = new RawMessage( '$1' );
191 if ( !isset( $options['code'] ) ) {
192 $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $exception ) );
193 $options['code'] = 'internal_api_error_' . $class;
196 $params = [ wfEscapeWikiText( $exception->getMessage() ) ];
198 return ApiMessage
::create( $msg, $options['code'], $options['data'] )
200 ->inLanguage( $this->lang
)
201 ->title( $this->getDummyTitle() )
202 ->useDatabase( $this->useDB
);
206 * Format an exception as an array
208 * @param Exception|Throwable $exception
209 * @param array $options See self::getMessageFromException(), plus
210 * - format: (string) Format override
213 public function formatException( $exception, array $options = [] ) {
214 return $this->formatMessage(
215 $this->getMessageFromException( $exception, $options ),
216 $options['format'] ??
null
221 * Format a message as an array
222 * @param Message|array|string $msg Message. See ApiMessage::create().
223 * @param string|null $format
226 public function formatMessage( $msg, $format = null ) {
227 $msg = ApiMessage
::create( $msg )
228 ->inLanguage( $this->lang
)
229 ->title( $this->getDummyTitle() )
230 ->useDatabase( $this->useDB
);
231 return $this->formatMessageInternal( $msg, $format ?
: $this->format
);
235 * Format messages from a StatusValue as an array
236 * @param StatusValue $status
237 * @param string $type 'warning' or 'error'
238 * @param string|null $format
241 public function arrayFromStatus( StatusValue
$status, $type = 'error', $format = null ) {
242 if ( $status->isGood() ||
!$status->getErrors() ) {
246 $result = new ApiResult( 1e6
);
247 $formatter = new ApiErrorFormatter(
248 $result, $this->lang
, $format ?
: $this->format
, $this->useDB
250 $formatter->addMessagesFromStatus( null, $status, [ $type ] );
253 return (array)$result->getResultData( [ 'errors' ] );
255 return (array)$result->getResultData( [ 'warnings' ] );
260 * Turn wikitext into something resembling plaintext
262 * @param string $text
265 public static function stripMarkup( $text ) {
266 // Turn semantic quoting tags to quotes
267 $ret = preg_replace( '!</?(var|kbd|samp|code)>!', '"', $text );
269 // Strip tags and decode.
270 $ret = Sanitizer
::stripAllTags( $ret );
276 * Format a Message object for raw format
277 * @param MessageSpecifier $msg
280 private function formatRawMessage( MessageSpecifier
$msg ) {
282 'key' => $msg->getKey(),
283 'params' => $msg->getParams(),
285 ApiResult
::setIndexedTagName( $ret['params'], 'param' );
287 // Transform Messages as parameters in the style of Message::fooParam().
288 foreach ( $ret['params'] as $i => $param ) {
289 if ( $param instanceof MessageSpecifier
) {
290 $ret['params'][$i] = [ 'message' => $this->formatRawMessage( $param ) ];
297 * Format a message as an array
299 * @param ApiMessage|ApiRawMessage $msg
300 * @param string|null $format
303 protected function formatMessageInternal( $msg, $format ) {
304 $value = [ 'code' => $msg->getApiCode() ];
308 'text' => self
::stripMarkup( $msg->text() ),
309 ApiResult
::META_CONTENT
=> 'text',
315 'text' => $msg->text(),
316 ApiResult
::META_CONTENT
=> 'text',
322 'html' => $msg->parse(),
323 ApiResult
::META_CONTENT
=> 'html',
328 $value +
= $this->formatRawMessage( $msg );
334 $data = $msg->getApiData();
336 $value['data'] = $msg->getApiData() +
[
337 ApiResult
::META_TYPE
=> 'assoc',
344 * Actually add the warning or error to the result
345 * @param string $tag 'warning' or 'error'
346 * @param string|null $modulePath
347 * @param ApiMessage|ApiRawMessage $msg
349 protected function addWarningOrError( $tag, $modulePath, $msg ) {
350 $value = $this->formatMessageInternal( $msg, $this->format
);
351 if ( $modulePath !== null ) {
352 $value +
= [ 'module' => $modulePath ];
355 $path = [ $tag . 's' ];
356 $existing = $this->result
->getResultData( $path );
357 if ( $existing === null ||
!in_array( $value, $existing ) ) {
358 $flags = ApiResult
::NO_SIZE_CHECK
;
359 if ( $existing === null ) {
360 $flags |
= ApiResult
::ADD_ON_TOP
;
362 $this->result
->addValue( $path, null, $value, $flags );
363 $this->result
->addIndexedTagName( $path, $tag );
369 * Format errors and warnings in the old style, for backwards compatibility.
371 * @deprecated Only for backwards compatibility, do not use
374 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
375 class ApiErrorFormatter_BackCompat
extends ApiErrorFormatter
{
378 * @param ApiResult $result Into which data will be added
380 public function __construct( ApiResult
$result ) {
381 parent
::__construct( $result, Language
::factory( 'en' ), 'none', false );
384 public function getFormat() {
388 public function arrayFromStatus( StatusValue
$status, $type = 'error', $format = null ) {
389 if ( $status->isGood() ||
!$status->getErrors() ) {
394 foreach ( $status->getErrorsByType( $type ) as $error ) {
395 $msg = ApiMessage
::create( $error );
397 'message' => $msg->getKey(),
398 'params' => $msg->getParams(),
399 'code' => $msg->getApiCode(),
401 ApiResult
::setIndexedTagName( $error['params'], 'param' );
404 ApiResult
::setIndexedTagName( $result, $type );
409 protected function formatMessageInternal( $msg, $format ) {
411 'code' => $msg->getApiCode(),
412 'info' => $msg->text(),
413 ] +
$msg->getApiData();
417 * Format an exception as an array
419 * @param Exception|Throwable $exception
420 * @param array $options See parent::formatException(), plus
421 * - bc: (bool) Return only the string, not an array
422 * @return array|string
424 public function formatException( $exception, array $options = [] ) {
425 $ret = parent
::formatException( $exception, $options );
426 return empty( $options['bc'] ) ?
$ret : $ret['info'];
429 protected function addWarningOrError( $tag, $modulePath, $msg ) {
430 $value = self
::stripMarkup( $msg->text() );
432 if ( $tag === 'error' ) {
433 // In BC mode, only one error
434 $existingError = $this->result
->getResultData( [ 'error' ] );
435 if ( !is_array( $existingError ) ||
436 !isset( $existingError['code'] ) ||
!isset( $existingError['info'] )
439 'code' => $msg->getApiCode(),
441 ] +
$msg->getApiData();
442 $this->result
->addValue( null, 'error', $value,
443 ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP | ApiResult
::NO_SIZE_CHECK
);
446 if ( $modulePath === null ) {
447 $moduleName = 'unknown';
449 $i = strrpos( $modulePath, '+' );
450 $moduleName = $i === false ?
$modulePath : substr( $modulePath, $i +
1 );
453 // Don't add duplicate warnings
455 $path = [ $tag, $moduleName ];
456 $oldWarning = $this->result
->getResultData( [ $tag, $moduleName, $tag ] );
457 if ( $oldWarning !== null ) {
458 $warnPos = strpos( $oldWarning, $value );
459 // If $value was found in $oldWarning, check if it starts at 0 or after "\n"
460 if ( $warnPos !== false && ( $warnPos === 0 ||
$oldWarning[$warnPos - 1] === "\n" ) ) {
461 // Check if $value is followed by "\n" or the end of the $oldWarning
462 $warnPos +
= strlen( $value );
463 if ( strlen( $oldWarning ) <= $warnPos ||
$oldWarning[$warnPos] === "\n" ) {
467 // If there is a warning already, append it to the existing one
468 $value = "$oldWarning\n$value";
470 $this->result
->addContentValue( $path, $tag, $value,
471 ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP | ApiResult
::NO_SIZE_CHECK
);