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
24 namespace MediaWiki\Api
;
26 use ILocalizedException
;
27 use MediaWiki\Language\Language
;
28 use MediaWiki\Language\RawMessage
;
29 use MediaWiki\Message\Message
;
30 use MediaWiki\Page\PageReference
;
31 use MediaWiki\Page\PageReferenceValue
;
32 use MediaWiki\Parser\Sanitizer
;
35 use Wikimedia\Message\MessageSpecifier
;
38 * Formats errors and warnings for the API, and add them to the associated
42 * @phan-file-suppress PhanUndeclaredMethod Undeclared methods in IApiMessage
44 class ApiErrorFormatter
{
45 /** @var PageReference Dummy title to silence warnings from MessageCache::parse() */
46 private static $dummyTitle = null;
53 /** @var PageReference|null page used for rendering error messages, or null to use the dummy title */
54 private $title = null;
56 protected $useDB = false;
58 protected $format = 'none';
61 * @param ApiResult $result Into which data will be added
62 * @param Language $lang Used for i18n
63 * @param string $format
64 * - plaintext: Error message as something vaguely like plaintext
65 * (it's basically wikitext with HTML tags stripped and entities decoded)
66 * - wikitext: Error message as wikitext
67 * - html: Error message as HTML
68 * - raw: Raw message key and parameters, no human-readable text
69 * - none: Code and data only, no human-readable text
70 * @param bool $useDB Whether to use local translations for errors and warnings.
72 public function __construct( ApiResult
$result, Language
$lang, $format, $useDB = false ) {
73 $this->result
= $result;
75 $this->useDB
= $useDB;
76 $this->format
= $format;
80 * Test whether a code is a valid API error code
82 * A valid code contains only ASCII letters, numbers, underscore, and
83 * hyphen and is not the empty string.
85 * For backwards compatibility, any code beginning 'internal_api_error_' is
91 public static function isValidApiCode( $code ) {
92 return is_string( $code ) && (
93 preg_match( '/^[a-zA-Z0-9_-]+$/', $code ) ||
94 // TODO: Deprecate this
95 preg_match( '/^internal_api_error_[^\0\r\n]+$/', $code )
100 * Return a formatter like this one but with a different format
103 * @param string $format New format.
104 * @return ApiErrorFormatter
106 public function newWithFormat( $format ) {
107 return new self( $this->result
, $this->lang
, $format, $this->useDB
);
111 * Fetch the format for this formatter
115 public function getFormat() {
116 return $this->format
;
120 * Fetch the Language for this formatter
124 public function getLanguage() {
129 * Fetch a dummy title to set on Messages
130 * @return PageReference
132 protected function getDummyTitle(): PageReference
{
133 if ( self
::$dummyTitle === null ) {
134 self
::$dummyTitle = PageReferenceValue
::localReference(
136 'Badtitle/' . __METHOD__
139 return self
::$dummyTitle;
143 * Get the page used for rendering error messages, e.g. for wikitext magic words like {{PAGENAME}}
145 * @return PageReference
147 public function getContextTitle(): PageReference
{
148 return $this->title ?
: $this->getDummyTitle();
152 * Set the page used for rendering error messages, e.g. for wikitext magic words like {{PAGENAME}}
154 * @param PageReference $title
156 public function setContextTitle( PageReference
$title ) {
157 $this->title
= $title;
161 * Add a warning to the result
162 * @param string|null $modulePath
163 * @param MessageSpecifier|array|string $msg Warning message. See ApiMessage::create().
164 * @param string|null $code See ApiMessage::create().
165 * @param array|null $data See ApiMessage::create().
167 public function addWarning( $modulePath, $msg, $code = null, $data = null ) {
168 $msg = ApiMessage
::create( $msg, $code, $data )
169 ->inLanguage( $this->lang
)
170 ->page( $this->getContextTitle() )
171 ->useDatabase( $this->useDB
);
172 $this->addWarningOrError( 'warning', $modulePath, $msg );
176 * Add an error to the result
177 * @param string|null $modulePath
178 * @param MessageSpecifier|array|string $msg Warning message. See ApiMessage::create().
179 * @param string|null $code See ApiMessage::create().
180 * @param array|null $data See ApiMessage::create().
182 public function addError( $modulePath, $msg, $code = null, $data = null ) {
183 $msg = ApiMessage
::create( $msg, $code, $data )
184 ->inLanguage( $this->lang
)
185 ->page( $this->getContextTitle() )
186 ->useDatabase( $this->useDB
);
187 $this->addWarningOrError( 'error', $modulePath, $msg );
191 * Add warnings and errors from a StatusValue object to the result
192 * @param string|null $modulePath
193 * @param StatusValue $status
194 * @param string[]|string $types 'warning' and/or 'error'
195 * @param string[] $filter Messages to filter out (since 1.33)
197 public function addMessagesFromStatus(
198 $modulePath, StatusValue
$status, $types = [ 'warning', 'error' ], array $filter = []
200 if ( $status->isGood() ) {
204 $types = array_unique( (array)$types );
205 foreach ( $types as $type ) {
206 foreach ( $status->getMessages( $type ) as $msg ) {
207 $msg = ApiMessage
::create( $msg )
208 ->inLanguage( $this->lang
)
209 ->page( $this->getContextTitle() )
210 ->useDatabase( $this->useDB
);
211 if ( !in_array( $msg->getKey(), $filter, true ) ) {
212 $this->addWarningOrError( $type, $modulePath, $msg );
219 * Get an ApiMessage from a throwable
221 * @param Throwable $exception
222 * @param array $options
223 * - wrap: (string|array|MessageSpecifier) Used to wrap the throwable's
224 * message if it's not an ILocalizedException. The throwable's message
225 * will be added as the final parameter.
226 * - code: (string) Default code
227 * - data: (array) Default extra data
228 * @return IApiMessage
230 public function getMessageFromException( Throwable
$exception, array $options = [] ) {
231 $options +
= [ 'code' => null, 'data' => [] ];
233 if ( $exception instanceof ILocalizedException
) {
234 $msg = $exception->getMessageObject();
236 } elseif ( $exception instanceof MessageSpecifier
) {
237 $msg = Message
::newFromSpecifier( $exception );
240 if ( isset( $options['wrap'] ) ) {
241 $msg = $options['wrap'];
243 $msg = new RawMessage( '$1' );
244 if ( !isset( $options['code'] ) ) {
245 $class = preg_replace( '#^Wikimedia\\\\Rdbms\\\\#', '', get_class( $exception ) );
246 $options['code'] = 'internal_api_error_' . $class;
247 $options['data']['errorclass'] = get_class( $exception );
250 $params = [ wfEscapeWikiText( $exception->getMessage() ) ];
252 return ApiMessage
::create( $msg, $options['code'], $options['data'] )
254 ->inLanguage( $this->lang
)
255 ->page( $this->getContextTitle() )
256 ->useDatabase( $this->useDB
);
260 * Format a throwable as an array
262 * @param Throwable $exception
263 * @param array $options See self::getMessageFromException(), plus
264 * - format: (string) Format override
267 public function formatException( Throwable
$exception, array $options = [] ) {
268 return $this->formatMessage(
269 // @phan-suppress-next-line PhanTypeMismatchArgument
270 $this->getMessageFromException( $exception, $options ),
271 $options['format'] ??
null
276 * Format a message as an array
277 * @param Message|array|string $msg Message. See ApiMessage::create().
278 * @param string|null $format
281 public function formatMessage( $msg, $format = null ) {
282 $msg = ApiMessage
::create( $msg )
283 ->inLanguage( $this->lang
)
284 ->page( $this->getContextTitle() )
285 ->useDatabase( $this->useDB
);
286 return $this->formatMessageInternal( $msg, $format ?
: $this->format
);
290 * Format messages from a StatusValue as an array
291 * @param StatusValue $status
292 * @param string $type 'warning' or 'error'
293 * @param string|null $format
296 public function arrayFromStatus( StatusValue
$status, $type = 'error', $format = null ) {
297 if ( $status->isGood() ||
!$status->getMessages() ) {
301 $result = new ApiResult( 1_000_000
);
302 $formatter = new ApiErrorFormatter(
303 $result, $this->lang
, $format ?
: $this->format
, $this->useDB
305 $formatter->addMessagesFromStatus( null, $status, [ $type ] );
308 return (array)$result->getResultData( [ 'errors' ] );
310 return (array)$result->getResultData( [ 'warnings' ] );
315 * Turn wikitext into something resembling plaintext
317 * @param string $text
320 public static function stripMarkup( $text ) {
321 // Turn semantic quoting tags to quotes
322 $ret = preg_replace( '!</?(var|kbd|samp|code)>!', '"', $text );
324 // Strip tags and decode.
325 return Sanitizer
::stripAllTags( $ret );
329 * Format a Message object for raw format
330 * @param MessageSpecifier $msg
333 private function formatRawMessage( MessageSpecifier
$msg ) {
335 'key' => $msg->getKey(),
336 'params' => $msg->getParams(),
338 ApiResult
::setIndexedTagName( $ret['params'], 'param' );
340 // Transform Messages as parameters in the style of Message::fooParam().
341 foreach ( $ret['params'] as $i => $param ) {
342 if ( $param instanceof MessageSpecifier
) {
343 $ret['params'][$i] = [ 'message' => $this->formatRawMessage( $param ) ];
350 * Format a message as an array
352 * @param ApiMessage|ApiRawMessage $msg
353 * @param string|null $format
356 protected function formatMessageInternal( $msg, $format ) {
357 $value = [ 'code' => $msg->getApiCode() ];
361 'text' => self
::stripMarkup( $msg->text() ),
362 ApiResult
::META_CONTENT
=> 'text',
368 'text' => $msg->text(),
369 ApiResult
::META_CONTENT
=> 'text',
375 'html' => $msg->parse(),
376 ApiResult
::META_CONTENT
=> 'html',
381 $value +
= $this->formatRawMessage( $msg );
387 $data = $msg->getApiData();
389 $value['data'] = $msg->getApiData() +
[
390 ApiResult
::META_TYPE
=> 'assoc',
397 * Actually add the warning or error to the result
398 * @param string $tag 'warning' or 'error'
399 * @param string|null $modulePath
400 * @param ApiMessage|ApiRawMessage $msg
402 protected function addWarningOrError( $tag, $modulePath, $msg ) {
403 $value = $this->formatMessageInternal( $msg, $this->format
);
404 if ( $modulePath !== null ) {
405 $value +
= [ 'module' => $modulePath ];
408 $path = [ $tag . 's' ];
409 $existing = $this->result
->getResultData( $path );
410 if ( $existing === null ||
!in_array( $value, $existing ) ) {
411 $flags = ApiResult
::NO_SIZE_CHECK
;
412 if ( $existing === null ) {
413 $flags |
= ApiResult
::ADD_ON_TOP
;
415 $this->result
->addValue( $path, null, $value, $flags );
416 $this->result
->addIndexedTagName( $path, $tag );
421 /** @deprecated class alias since 1.43 */
422 class_alias( ApiErrorFormatter
::class, 'ApiErrorFormatter' );