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
29 * @phan-file-suppress PhanUndeclaredMethod Undeclared methods in IApiMessage
31 class ApiErrorFormatter
{
32 /** @var Title Dummy title to silence warnings from MessageCache::parse() */
33 private static $dummyTitle = null;
40 protected $useDB = false;
41 protected $format = 'none';
44 * @param ApiResult $result Into which data will be added
45 * @param Language $lang Used for i18n
46 * @param string $format
47 * - plaintext: Error message as something vaguely like plaintext
48 * (it's basically wikitext with HTML tags stripped and entities decoded)
49 * - wikitext: Error message as wikitext
50 * - html: Error message as HTML
51 * - raw: Raw message key and parameters, no human-readable text
52 * - none: Code and data only, no human-readable text
53 * @param bool $useDB Whether to use local translations for errors and warnings.
55 public function __construct( ApiResult
$result, Language
$lang, $format, $useDB = false ) {
56 $this->result
= $result;
58 $this->useDB
= $useDB;
59 $this->format
= $format;
63 * Test whether a code is a valid API error code
65 * A valid code contains only ASCII letters, numbers, underscore, and
66 * hyphen and is not the empty string.
68 * For backwards compatibility, any code beginning 'internal_api_error_' is
74 public static function isValidApiCode( $code ) {
75 return is_string( $code ) && (
76 preg_match( '/^[a-zA-Z0-9_-]+$/', $code ) ||
77 // TODO: Deprecate this
78 preg_match( '/^internal_api_error_[^\0\r\n]+$/', $code )
83 * Return a formatter like this one but with a different format
86 * @param string $format New format.
87 * @return ApiErrorFormatter
89 public function newWithFormat( $format ) {
90 return new self( $this->result
, $this->lang
, $format, $this->useDB
);
94 * Fetch the format for this formatter
98 public function getFormat() {
103 * Fetch the Language for this formatter
107 public function getLanguage() {
112 * Fetch a dummy title to set on Messages
115 protected function getDummyTitle() {
116 if ( self
::$dummyTitle === null ) {
117 self
::$dummyTitle = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/' . __METHOD__
);
119 return self
::$dummyTitle;
123 * Add a warning to the result
124 * @param string|null $modulePath
125 * @param Message|array|string $msg Warning message. See ApiMessage::create().
126 * @param string|null $code See ApiMessage::create().
127 * @param array|null $data See ApiMessage::create().
129 public function addWarning( $modulePath, $msg, $code = null, $data = null ) {
130 $msg = ApiMessage
::create( $msg, $code, $data )
131 ->inLanguage( $this->lang
)
132 ->title( $this->getDummyTitle() )
133 ->useDatabase( $this->useDB
);
134 $this->addWarningOrError( 'warning', $modulePath, $msg );
138 * Add an error to the result
139 * @param string|null $modulePath
140 * @param Message|array|string $msg Warning message. See ApiMessage::create().
141 * @param string|null $code See ApiMessage::create().
142 * @param array|null $data See ApiMessage::create().
144 public function addError( $modulePath, $msg, $code = null, $data = null ) {
145 $msg = ApiMessage
::create( $msg, $code, $data )
146 ->inLanguage( $this->lang
)
147 ->title( $this->getDummyTitle() )
148 ->useDatabase( $this->useDB
);
149 $this->addWarningOrError( 'error', $modulePath, $msg );
153 * Add warnings and errors from a StatusValue object to the result
154 * @param string|null $modulePath
155 * @param StatusValue $status
156 * @param string[]|string $types 'warning' and/or 'error'
157 * @param string[] $filter Messages to filter out (since 1.33)
159 public function addMessagesFromStatus(
160 $modulePath, StatusValue
$status, $types = [ 'warning', 'error' ], array $filter = []
162 if ( $status->isGood() ||
!$status->getErrors() ) {
166 $types = (array)$types;
167 foreach ( $status->getErrors() as $error ) {
168 if ( !in_array( $error['type'], $types, true ) ) {
172 if ( $error['type'] === 'error' ) {
175 // Assume any unknown type is a warning
179 $msg = ApiMessage
::create( $error )
180 ->inLanguage( $this->lang
)
181 ->title( $this->getDummyTitle() )
182 ->useDatabase( $this->useDB
);
183 if ( !in_array( $msg->getKey(), $filter, true ) ) {
184 $this->addWarningOrError( $tag, $modulePath, $msg );
190 * Get an ApiMessage from an exception
192 * @param Exception|Throwable $exception
193 * @param array $options
194 * - wrap: (string|array|MessageSpecifier) Used to wrap the exception's
195 * message if it's not an ILocalizedException. The exception's message
196 * will be added as the final parameter.
197 * - code: (string) Default code
198 * - data: (array) Default extra data
199 * @return IApiMessage
201 public function getMessageFromException( $exception, array $options = [] ) {
202 $options +
= [ 'code' => null, 'data' => [] ];
204 if ( $exception instanceof ILocalizedException
) {
205 $msg = $exception->getMessageObject();
207 } elseif ( $exception instanceof MessageSpecifier
) {
208 $msg = Message
::newFromSpecifier( $exception );
211 if ( isset( $options['wrap'] ) ) {
212 $msg = $options['wrap'];
214 $msg = new RawMessage( '$1' );
215 if ( !isset( $options['code'] ) ) {
216 $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $exception ) );
217 $options['code'] = 'internal_api_error_' . $class;
218 $options['data']['errorclass'] = get_class( $exception );
221 $params = [ wfEscapeWikiText( $exception->getMessage() ) ];
223 return ApiMessage
::create( $msg, $options['code'], $options['data'] )
225 ->inLanguage( $this->lang
)
226 ->title( $this->getDummyTitle() )
227 ->useDatabase( $this->useDB
);
231 * Format an exception as an array
233 * @param Exception|Throwable $exception
234 * @param array $options See self::getMessageFromException(), plus
235 * - format: (string) Format override
238 public function formatException( $exception, array $options = [] ) {
239 return $this->formatMessage(
240 $this->getMessageFromException( $exception, $options ),
241 $options['format'] ??
null
246 * Format a message as an array
247 * @param Message|array|string $msg Message. See ApiMessage::create().
248 * @param string|null $format
251 public function formatMessage( $msg, $format = null ) {
252 $msg = ApiMessage
::create( $msg )
253 ->inLanguage( $this->lang
)
254 ->title( $this->getDummyTitle() )
255 ->useDatabase( $this->useDB
);
256 return $this->formatMessageInternal( $msg, $format ?
: $this->format
);
260 * Format messages from a StatusValue as an array
261 * @param StatusValue $status
262 * @param string $type 'warning' or 'error'
263 * @param string|null $format
266 public function arrayFromStatus( StatusValue
$status, $type = 'error', $format = null ) {
267 if ( $status->isGood() ||
!$status->getErrors() ) {
271 $result = new ApiResult( 1e6
);
272 $formatter = new ApiErrorFormatter(
273 $result, $this->lang
, $format ?
: $this->format
, $this->useDB
275 $formatter->addMessagesFromStatus( null, $status, [ $type ] );
278 return (array)$result->getResultData( [ 'errors' ] );
280 return (array)$result->getResultData( [ 'warnings' ] );
285 * Turn wikitext into something resembling plaintext
287 * @param string $text
290 public static function stripMarkup( $text ) {
291 // Turn semantic quoting tags to quotes
292 $ret = preg_replace( '!</?(var|kbd|samp|code)>!', '"', $text );
294 // Strip tags and decode.
295 $ret = Sanitizer
::stripAllTags( $ret );
301 * Format a Message object for raw format
302 * @param MessageSpecifier $msg
305 private function formatRawMessage( MessageSpecifier
$msg ) {
307 'key' => $msg->getKey(),
308 'params' => $msg->getParams(),
310 ApiResult
::setIndexedTagName( $ret['params'], 'param' );
312 // Transform Messages as parameters in the style of Message::fooParam().
313 foreach ( $ret['params'] as $i => $param ) {
314 if ( $param instanceof MessageSpecifier
) {
315 $ret['params'][$i] = [ 'message' => $this->formatRawMessage( $param ) ];
322 * Format a message as an array
324 * @param ApiMessage|ApiRawMessage $msg
325 * @param string|null $format
328 protected function formatMessageInternal( $msg, $format ) {
329 $value = [ 'code' => $msg->getApiCode() ];
333 'text' => self
::stripMarkup( $msg->text() ),
334 ApiResult
::META_CONTENT
=> 'text',
340 'text' => $msg->text(),
341 ApiResult
::META_CONTENT
=> 'text',
347 'html' => $msg->parse(),
348 ApiResult
::META_CONTENT
=> 'html',
353 $value +
= $this->formatRawMessage( $msg );
359 $data = $msg->getApiData();
361 $value['data'] = $msg->getApiData() +
[
362 ApiResult
::META_TYPE
=> 'assoc',
369 * Actually add the warning or error to the result
370 * @param string $tag 'warning' or 'error'
371 * @param string|null $modulePath
372 * @param ApiMessage|ApiRawMessage $msg
374 protected function addWarningOrError( $tag, $modulePath, $msg ) {
375 $value = $this->formatMessageInternal( $msg, $this->format
);
376 if ( $modulePath !== null ) {
377 $value +
= [ 'module' => $modulePath ];
380 $path = [ $tag . 's' ];
381 $existing = $this->result
->getResultData( $path );
382 if ( $existing === null ||
!in_array( $value, $existing ) ) {
383 $flags = ApiResult
::NO_SIZE_CHECK
;
384 if ( $existing === null ) {
385 $flags |
= ApiResult
::ADD_ON_TOP
;
387 $this->result
->addValue( $path, null, $value, $flags );
388 $this->result
->addIndexedTagName( $path, $tag );