Debian Codegraph @

includes/api/ApiErrorFormatter.php

raw symbols SCIP
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 namespace MediaWiki\Api;
25
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;
33 use StatusValue;
34 use Throwable;
35 use Wikimedia\Message\MessageSpecifier;
36
37 /**
38 * Formats errors and warnings for the API, and add them to the associated
39 * ApiResult.
40 * @since 1.25
41 * @ingroup API
42 * @phan-file-suppress PhanUndeclaredMethod Undeclared methods in IApiMessage
43 */
44 class ApiErrorFormatter {
45 /** @var PageReference Dummy title to silence warnings from MessageCache::parse() */
46 private static $dummyTitle = null;
47
48 /** @var ApiResult */
49 protected $result;
50
51 /** @var Language */
52 protected $lang;
53 /** @var PageReference|null page used for rendering error messages, or null to use the dummy title */
54 private $title = null;
55 /** @var bool */
56 protected $useDB = false;
57 /** @var string */
58 protected $format = 'none';
59
60 /**
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.
71 */
72 public function __construct( ApiResult $result, Language $lang, $format, $useDB = false ) {
73 $this->result = $result;
74 $this->lang = $lang;
75 $this->useDB = $useDB;
76 $this->format = $format;
77 }
78
79 /**
80 * Test whether a code is a valid API error code
81 *
82 * A valid code contains only ASCII letters, numbers, underscore, and
83 * hyphen and is not the empty string.
84 *
85 * For backwards compatibility, any code beginning 'internal_api_error_' is
86 * also allowed.
87 *
88 * @param string $code
89 * @return bool
90 */
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 )
96 );
97 }
98
99 /**
100 * Return a formatter like this one but with a different format
101 *
102 * @since 1.32
103 * @param string $format New format.
104 * @return ApiErrorFormatter
105 */
106 public function newWithFormat( $format ) {
107 return new self( $this->result, $this->lang, $format, $this->useDB );
108 }
109
110 /**
111 * Fetch the format for this formatter
112 * @since 1.32
113 * @return string
114 */
115 public function getFormat() {
116 return $this->format;
117 }
118
119 /**
120 * Fetch the Language for this formatter
121 * @since 1.29
122 * @return Language
123 */
124 public function getLanguage() {
125 return $this->lang;
126 }
127
128 /**
129 * Fetch a dummy title to set on Messages
130 * @return PageReference
131 */
132 protected function getDummyTitle(): PageReference {
133 if ( self::$dummyTitle === null ) {
134 self::$dummyTitle = PageReferenceValue::localReference(
135 NS_SPECIAL,
136 'Badtitle/' . __METHOD__
137 );
138 }
139 return self::$dummyTitle;
140 }
141
142 /**
143 * Get the page used for rendering error messages, e.g. for wikitext magic words like {{PAGENAME}}
144 * @since 1.37
145 * @return PageReference
146 */
147 public function getContextTitle(): PageReference {
148 return $this->title ?: $this->getDummyTitle();
149 }
150
151 /**
152 * Set the page used for rendering error messages, e.g. for wikitext magic words like {{PAGENAME}}
153 * @since 1.37
154 * @param PageReference $title
155 */
156 public function setContextTitle( PageReference $title ) {
157 $this->title = $title;
158 }
159
160 /**
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().
166 */
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 );
173 }
174
175 /**
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().
181 */
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 );
188 }
189
190 /**
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)
196 */
197 public function addMessagesFromStatus(
198 $modulePath, StatusValue $status, $types = [ 'warning', 'error' ], array $filter = []
199 ) {
200 if ( $status->isGood() ) {
201 return;
202 }
203
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 );
213 }
214 }
215 }
216 }
217
218 /**
219 * Get an ApiMessage from a throwable
220 * @since 1.29
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
229 */
230 public function getMessageFromException( Throwable $exception, array $options = [] ) {
231 $options += [ 'code' => null, 'data' => [] ];
232
233 if ( $exception instanceof ILocalizedException ) {
234 $msg = $exception->getMessageObject();
235 $params = [];
236 } elseif ( $exception instanceof MessageSpecifier ) {
237 $msg = Message::newFromSpecifier( $exception );
238 $params = [];
239 } else {
240 if ( isset( $options['wrap'] ) ) {
241 $msg = $options['wrap'];
242 } else {
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 );
248 }
249 }
250 $params = [ wfEscapeWikiText( $exception->getMessage() ) ];
251 }
252 return ApiMessage::create( $msg, $options['code'], $options['data'] )
253 ->params( $params )
254 ->inLanguage( $this->lang )
255 ->page( $this->getContextTitle() )
256 ->useDatabase( $this->useDB );
257 }
258
259 /**
260 * Format a throwable as an array
261 * @since 1.29
262 * @param Throwable $exception
263 * @param array $options See self::getMessageFromException(), plus
264 * - format: (string) Format override
265 * @return array
266 */
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
272 );
273 }
274
275 /**
276 * Format a message as an array
277 * @param Message|array|string $msg Message. See ApiMessage::create().
278 * @param string|null $format
279 * @return array
280 */
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 );
287 }
288
289 /**
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
294 * @return array
295 */
296 public function arrayFromStatus( StatusValue $status, $type = 'error', $format = null ) {
297 if ( $status->isGood() || !$status->getMessages() ) {
298 return [];
299 }
300
301 $result = new ApiResult( 1_000_000 );
302 $formatter = new ApiErrorFormatter(
303 $result, $this->lang, $format ?: $this->format, $this->useDB
304 );
305 $formatter->addMessagesFromStatus( null, $status, [ $type ] );
306 switch ( $type ) {
307 case 'error':
308 return (array)$result->getResultData( [ 'errors' ] );
309 case 'warning':
310 return (array)$result->getResultData( [ 'warnings' ] );
311 }
312 }
313
314 /**
315 * Turn wikitext into something resembling plaintext
316 * @since 1.29
317 * @param string $text
318 * @return string
319 */
320 public static function stripMarkup( $text ) {
321 // Turn semantic quoting tags to quotes
322 $ret = preg_replace( '!</?(var|kbd|samp|code)>!', '"', $text );
323
324 // Strip tags and decode.
325 return Sanitizer::stripAllTags( $ret );
326 }
327
328 /**
329 * Format a Message object for raw format
330 * @param MessageSpecifier $msg
331 * @return array
332 */
333 private function formatRawMessage( MessageSpecifier $msg ) {
334 $ret = [
335 'key' => $msg->getKey(),
336 'params' => $msg->getParams(),
337 ];
338 ApiResult::setIndexedTagName( $ret['params'], 'param' );
339
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 ) ];
344 }
345 }
346 return $ret;
347 }
348
349 /**
350 * Format a message as an array
351 * @since 1.29
352 * @param ApiMessage|ApiRawMessage $msg
353 * @param string|null $format
354 * @return array
355 */
356 protected function formatMessageInternal( $msg, $format ) {
357 $value = [ 'code' => $msg->getApiCode() ];
358 switch ( $format ) {
359 case 'plaintext':
360 $value += [
361 'text' => self::stripMarkup( $msg->text() ),
362 ApiResult::META_CONTENT => 'text',
363 ];
364 break;
365
366 case 'wikitext':
367 $value += [
368 'text' => $msg->text(),
369 ApiResult::META_CONTENT => 'text',
370 ];
371 break;
372
373 case 'html':
374 $value += [
375 'html' => $msg->parse(),
376 ApiResult::META_CONTENT => 'html',
377 ];
378 break;
379
380 case 'raw':
381 $value += $this->formatRawMessage( $msg );
382 break;
383
384 case 'none':
385 break;
386 }
387 $data = $msg->getApiData();
388 if ( $data ) {
389 $value['data'] = $msg->getApiData() + [
390 ApiResult::META_TYPE => 'assoc',
391 ];
392 }
393 return $value;
394 }
395
396 /**
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
401 */
402 protected function addWarningOrError( $tag, $modulePath, $msg ) {
403 $value = $this->formatMessageInternal( $msg, $this->format );
404 if ( $modulePath !== null ) {
405 $value += [ 'module' => $modulePath ];
406 }
407
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;
414 }
415 $this->result->addValue( $path, null, $value, $flags );
416 $this->result->addIndexedTagName( $path, $tag );
417 }
418 }
419 }
420
421 /** @deprecated class alias since 1.43 */
422 class_alias( ApiErrorFormatter::class, 'ApiErrorFormatter' );