Add ILocalizedException interface
[lhc/web/wiklou.git] / includes / api / ApiErrorFormatter.php
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 /**
25 * Formats errors and warnings for the API, and add them to the associated
26 * ApiResult.
27 * @since 1.25
28 * @ingroup API
29 */
30 class ApiErrorFormatter {
31 /** @var Title Dummy title to silence warnings from MessageCache::parse() */
32 private static $dummyTitle = null;
33
34 /** @var ApiResult */
35 protected $result;
36
37 /** @var Language */
38 protected $lang;
39 protected $useDB = false;
40 protected $format = 'none';
41
42 /**
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.
53 */
54 public function __construct( ApiResult $result, Language $lang, $format, $useDB = false ) {
55 $this->result = $result;
56 $this->lang = $lang;
57 $this->useDB = $useDB;
58 $this->format = $format;
59 }
60
61 /**
62 * Fetch the Language for this formatter
63 * @since 1.29
64 * @return Language
65 */
66 public function getLanguage() {
67 return $this->lang;
68 }
69
70 /**
71 * Fetch a dummy title to set on Messages
72 * @return Title
73 */
74 protected function getDummyTitle() {
75 if ( self::$dummyTitle === null ) {
76 self::$dummyTitle = Title::makeTitle( NS_SPECIAL, 'Badtitle/' . __METHOD__ );
77 }
78 return self::$dummyTitle;
79 }
80
81 /**
82 * Add a warning to the result
83 * @param string|null $modulePath
84 * @param Message|array|string $msg Warning message. See ApiMessage::create().
85 * @param string|null $code See ApiMessage::create().
86 * @param array|null $data See ApiMessage::create().
87 */
88 public function addWarning( $modulePath, $msg, $code = null, $data = null ) {
89 $msg = ApiMessage::create( $msg, $code, $data )
90 ->inLanguage( $this->lang )
91 ->title( $this->getDummyTitle() )
92 ->useDatabase( $this->useDB );
93 $this->addWarningOrError( 'warning', $modulePath, $msg );
94 }
95
96 /**
97 * Add an error to the result
98 * @param string|null $modulePath
99 * @param Message|array|string $msg Warning message. See ApiMessage::create().
100 * @param string|null $code See ApiMessage::create().
101 * @param array|null $data See ApiMessage::create().
102 */
103 public function addError( $modulePath, $msg, $code = null, $data = null ) {
104 $msg = ApiMessage::create( $msg, $code, $data )
105 ->inLanguage( $this->lang )
106 ->title( $this->getDummyTitle() )
107 ->useDatabase( $this->useDB );
108 $this->addWarningOrError( 'error', $modulePath, $msg );
109 }
110
111 /**
112 * Add warnings and errors from a StatusValue object to the result
113 * @param string|null $modulePath
114 * @param StatusValue $status
115 * @param string[] $types 'warning' and/or 'error'
116 */
117 public function addMessagesFromStatus(
118 $modulePath, StatusValue $status, $types = [ 'warning', 'error' ]
119 ) {
120 if ( $status->isGood() || !$status->getErrors() ) {
121 return;
122 }
123
124 $types = (array)$types;
125 foreach ( $status->getErrors() as $error ) {
126 if ( !in_array( $error['type'], $types, true ) ) {
127 continue;
128 }
129
130 if ( $error['type'] === 'error' ) {
131 $tag = 'error';
132 } else {
133 // Assume any unknown type is a warning
134 $tag = 'warning';
135 }
136
137 $msg = ApiMessage::create( $error )
138 ->inLanguage( $this->lang )
139 ->title( $this->getDummyTitle() )
140 ->useDatabase( $this->useDB );
141 $this->addWarningOrError( $tag, $modulePath, $msg );
142 }
143 }
144
145 /**
146 * Get an ApiMessage from an exception
147 * @since 1.29
148 * @param Exception|Throwable $exception
149 * @param array $options
150 * - wrap: (string|array|MessageSpecifier) Used to wrap the exception's
151 * message. The exception's message will be added as the final parameter.
152 * - code: (string) Default code
153 * - data: (array) Extra data
154 * @return ApiMessage
155 */
156 public function getMessageFromException( $exception, array $options = [] ) {
157 $options += [ 'code' => null, 'data' => [] ];
158
159 if ( $exception instanceof ILocalizedException ) {
160 $msg = $exception->getMessageObject();
161 $params = [];
162 } else {
163 // Extract code and data from the exception, if applicable
164 if ( $exception instanceof UsageException ) {
165 $data = $exception->getMessageArray();
166 if ( !isset( $options['code'] ) ) {
167 $options['code'] = $data['code'];
168 }
169 unset( $data['code'], $data['info'] );
170 $options['data'] = array_merge( $data['code'], $options['data'] );
171 }
172
173 if ( isset( $options['wrap'] ) ) {
174 $msg = $options['wrap'];
175 } else {
176 $msg = new RawMessage( '$1' );
177 if ( !isset( $options['code'] ) ) {
178 $options['code'] = 'internal_api_error_' . get_class( $exception );
179 }
180 }
181 $params = [ wfEscapeWikiText( $exception->getMessage() ) ];
182 }
183 return ApiMessage::create( $msg, $options['code'], $options['data'] )
184 ->params( $params )
185 ->inLanguage( $this->lang )
186 ->title( $this->getDummyTitle() )
187 ->useDatabase( $this->useDB );
188 }
189
190 /**
191 * Format an exception as an array
192 * @since 1.29
193 * @param Exception|Throwable $exception
194 * @param array $options See self::getMessageFromException(), plus
195 * - format: (string) Format override
196 * @return array
197 */
198 public function formatException( $exception, array $options = [] ) {
199 return $this->formatMessage(
200 $this->getMessageFromException( $exception, $options ),
201 isset( $options['format'] ) ? $options['format'] : null
202 );
203 }
204
205 /**
206 * Format a message as an array
207 * @param Message|array|string $msg Message. See ApiMessage::create().
208 * @param string|null $format
209 * @return array
210 */
211 public function formatMessage( $msg, $format = null ) {
212 $msg = ApiMessage::create( $msg )
213 ->inLanguage( $this->lang )
214 ->title( $this->getDummyTitle() )
215 ->useDatabase( $this->useDB );
216 return $this->formatMessageInternal( $msg, $format ?: $this->format );
217 }
218
219 /**
220 * Format messages from a StatusValue as an array
221 * @param StatusValue $status
222 * @param string $type 'warning' or 'error'
223 * @param string|null $format
224 * @return array
225 */
226 public function arrayFromStatus( StatusValue $status, $type = 'error', $format = null ) {
227 if ( $status->isGood() || !$status->getErrors() ) {
228 return [];
229 }
230
231 $result = new ApiResult( 1e6 );
232 $formatter = new ApiErrorFormatter(
233 $result, $this->lang, $format ?: $this->format, $this->useDB
234 );
235 $formatter->addMessagesFromStatus( null, $status, [ $type ] );
236 switch ( $type ) {
237 case 'error':
238 return (array)$result->getResultData( [ 'errors' ] );
239 case 'warning':
240 return (array)$result->getResultData( [ 'warnings' ] );
241 }
242 }
243
244 /**
245 * Turn wikitext into something resembling plaintext
246 * @since 1.29
247 * @param string $text
248 * @return string
249 */
250 public static function stripMarkup( $text ) {
251 // Turn semantic quoting tags to quotes
252 $ret = preg_replace( '!</?(var|kbd|samp|code)>!', '"', $text );
253
254 // Strip tags and decode.
255 $ret = html_entity_decode( strip_tags( $ret ), ENT_QUOTES | ENT_HTML5 );
256
257 return $ret;
258 }
259
260 /**
261 * Format a Message object for raw format
262 * @param MessageSpecifier $msg
263 * @return array
264 */
265 private function formatRawMessage( MessageSpecifier $msg ) {
266 $ret = [
267 'key' => $msg->getKey(),
268 'params' => $msg->getParams(),
269 ];
270 ApiResult::setIndexedTagName( $ret['params'], 'param' );
271
272 // Transform Messages as parameters in the style of Message::fooParam().
273 foreach ( $ret['params'] as $i => $param ) {
274 if ( $param instanceof MessageSpecifier ) {
275 $ret['params'][$i] = [ 'message' => $this->formatRawMessage( $param ) ];
276 }
277 }
278 return $ret;
279 }
280
281 /**
282 * Format a message as an array
283 * @since 1.29
284 * @param ApiMessage|ApiRawMessage $msg
285 * @param string|null $format
286 * @return array
287 */
288 protected function formatMessageInternal( $msg, $format ) {
289 $value = [ 'code' => $msg->getApiCode() ];
290 switch ( $format ) {
291 case 'plaintext':
292 $value += [
293 'text' => self::stripMarkup( $msg->text() ),
294 ApiResult::META_CONTENT => 'text',
295 ];
296 break;
297
298 case 'wikitext':
299 $value += [
300 'text' => $msg->text(),
301 ApiResult::META_CONTENT => 'text',
302 ];
303 break;
304
305 case 'html':
306 $value += [
307 'html' => $msg->parse(),
308 ApiResult::META_CONTENT => 'html',
309 ];
310 break;
311
312 case 'raw':
313 $value += $this->formatRawMessage( $msg );
314 break;
315
316 case 'none':
317 break;
318 }
319 $data = $msg->getApiData();
320 if ( $data ) {
321 $value['data'] = $msg->getApiData() + [
322 ApiResult::META_TYPE => 'assoc',
323 ];
324 }
325 return $value;
326 }
327
328 /**
329 * Actually add the warning or error to the result
330 * @param string $tag 'warning' or 'error'
331 * @param string|null $modulePath
332 * @param ApiMessage|ApiRawMessage $msg
333 */
334 protected function addWarningOrError( $tag, $modulePath, $msg ) {
335 $value = $this->formatMessageInternal( $msg, $this->format );
336 if ( $modulePath !== null ) {
337 $value += [ 'module' => $modulePath ];
338 }
339
340 $path = [ $tag . 's' ];
341 $existing = $this->result->getResultData( $path );
342 if ( $existing === null || !in_array( $value, $existing ) ) {
343 $flags = ApiResult::NO_SIZE_CHECK;
344 if ( $existing === null ) {
345 $flags |= ApiResult::ADD_ON_TOP;
346 }
347 $this->result->addValue( $path, null, $value, $flags );
348 $this->result->addIndexedTagName( $path, $tag );
349 }
350 }
351 }
352
353 /**
354 * Format errors and warnings in the old style, for backwards compatibility.
355 * @since 1.25
356 * @deprecated Only for backwards compatibility, do not use
357 * @ingroup API
358 */
359 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
360 class ApiErrorFormatter_BackCompat extends ApiErrorFormatter {
361 // @codingStandardsIgnoreEnd
362
363 /**
364 * @param ApiResult $result Into which data will be added
365 */
366 public function __construct( ApiResult $result ) {
367 parent::__construct( $result, Language::factory( 'en' ), 'none', false );
368 }
369
370 public function arrayFromStatus( StatusValue $status, $type = 'error', $format = null ) {
371 if ( $status->isGood() || !$status->getErrors() ) {
372 return [];
373 }
374
375 $result = [];
376 foreach ( $status->getErrorsByType( $type ) as $error ) {
377 $msg = ApiMessage::create( $error );
378 $error = [
379 'message' => $msg->getKey(),
380 'params' => $msg->getParams(),
381 'code' => $msg->getApiCode(),
382 ] + $error;
383 ApiResult::setIndexedTagName( $error['params'], 'param' );
384 $result[] = $error;
385 }
386 ApiResult::setIndexedTagName( $result, $type );
387
388 return $result;
389 }
390
391 protected function formatMessageInternal( $msg, $format ) {
392 return [
393 'code' => $msg->getApiCode(),
394 'info' => $msg->text(),
395 ] + $msg->getApiData();
396 }
397
398 /**
399 * Format an exception as an array
400 * @since 1.29
401 * @param Exception|Throwable $exception
402 * @param array $options See parent::formatException(), plus
403 * - bc: (bool) Return only the string, not an array
404 * @return array|string
405 */
406 public function formatException( $exception, array $options = [] ) {
407 $ret = parent::formatException( $exception, $options );
408 return empty( $options['bc'] ) ? $ret : $ret['info'];
409 }
410
411 protected function addWarningOrError( $tag, $modulePath, $msg ) {
412 $value = self::stripMarkup( $msg->text() );
413
414 if ( $tag === 'error' ) {
415 // In BC mode, only one error
416 $value = [
417 'code' => $msg->getApiCode(),
418 'info' => $value,
419 ] + $msg->getApiData();
420 $this->result->addValue( null, 'error', $value,
421 ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
422 } else {
423 if ( $modulePath === null ) {
424 $moduleName = 'unknown';
425 } else {
426 $i = strrpos( $modulePath, '+' );
427 $moduleName = $i === false ? $modulePath : substr( $modulePath, $i + 1 );
428 }
429
430 // Don't add duplicate warnings
431 $tag .= 's';
432 $path = [ $tag, $moduleName ];
433 $oldWarning = $this->result->getResultData( [ $tag, $moduleName, $tag ] );
434 if ( $oldWarning !== null ) {
435 $warnPos = strpos( $oldWarning, $value );
436 // If $value was found in $oldWarning, check if it starts at 0 or after "\n"
437 if ( $warnPos !== false && ( $warnPos === 0 || $oldWarning[$warnPos - 1] === "\n" ) ) {
438 // Check if $value is followed by "\n" or the end of the $oldWarning
439 $warnPos += strlen( $value );
440 if ( strlen( $oldWarning ) <= $warnPos || $oldWarning[$warnPos] === "\n" ) {
441 return;
442 }
443 }
444 // If there is a warning already, append it to the existing one
445 $value = "$oldWarning\n$value";
446 }
447 $this->result->addContentValue( $path, $tag, $value,
448 ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
449 }
450 }
451 }