auth: Follow up on e907d4328dc3e
[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 * Return a formatter like this one but with a different format
63 *
64 * @since 1.32
65 * @param string $format New format.
66 * @return ApiErrorFormatter
67 */
68 public function newWithFormat( $format ) {
69 return new self( $this->result, $this->lang, $format, $this->useDB );
70 }
71
72 /**
73 * Fetch the format for this formatter
74 * @since 1.32
75 * @return string
76 */
77 public function getFormat() {
78 return $this->format;
79 }
80
81 /**
82 * Fetch the Language for this formatter
83 * @since 1.29
84 * @return Language
85 */
86 public function getLanguage() {
87 return $this->lang;
88 }
89
90 /**
91 * Fetch a dummy title to set on Messages
92 * @return Title
93 */
94 protected function getDummyTitle() {
95 if ( self::$dummyTitle === null ) {
96 self::$dummyTitle = Title::makeTitle( NS_SPECIAL, 'Badtitle/' . __METHOD__ );
97 }
98 return self::$dummyTitle;
99 }
100
101 /**
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().
107 */
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 );
114 }
115
116 /**
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().
122 */
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 );
129 }
130
131 /**
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'
136 */
137 public function addMessagesFromStatus(
138 $modulePath, StatusValue $status, $types = [ 'warning', 'error' ]
139 ) {
140 if ( $status->isGood() || !$status->getErrors() ) {
141 return;
142 }
143
144 $types = (array)$types;
145 foreach ( $status->getErrors() as $error ) {
146 if ( !in_array( $error['type'], $types, true ) ) {
147 continue;
148 }
149
150 if ( $error['type'] === 'error' ) {
151 $tag = 'error';
152 } else {
153 // Assume any unknown type is a warning
154 $tag = 'warning';
155 }
156
157 $msg = ApiMessage::create( $error )
158 ->inLanguage( $this->lang )
159 ->title( $this->getDummyTitle() )
160 ->useDatabase( $this->useDB );
161 $this->addWarningOrError( $tag, $modulePath, $msg );
162 }
163 }
164
165 /**
166 * Get an ApiMessage from an exception
167 * @since 1.29
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
176 */
177 public function getMessageFromException( $exception, array $options = [] ) {
178 $options += [ 'code' => null, 'data' => [] ];
179
180 if ( $exception instanceof ILocalizedException ) {
181 $msg = $exception->getMessageObject();
182 $params = [];
183 } elseif ( $exception instanceof MessageSpecifier ) {
184 $msg = Message::newFromSpecifier( $exception );
185 $params = [];
186 } else {
187 if ( isset( $options['wrap'] ) ) {
188 $msg = $options['wrap'];
189 } else {
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;
194 }
195 }
196 $params = [ wfEscapeWikiText( $exception->getMessage() ) ];
197 }
198 return ApiMessage::create( $msg, $options['code'], $options['data'] )
199 ->params( $params )
200 ->inLanguage( $this->lang )
201 ->title( $this->getDummyTitle() )
202 ->useDatabase( $this->useDB );
203 }
204
205 /**
206 * Format an exception as an array
207 * @since 1.29
208 * @param Exception|Throwable $exception
209 * @param array $options See self::getMessageFromException(), plus
210 * - format: (string) Format override
211 * @return array
212 */
213 public function formatException( $exception, array $options = [] ) {
214 return $this->formatMessage(
215 $this->getMessageFromException( $exception, $options ),
216 $options['format'] ?? null
217 );
218 }
219
220 /**
221 * Format a message as an array
222 * @param Message|array|string $msg Message. See ApiMessage::create().
223 * @param string|null $format
224 * @return array
225 */
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 );
232 }
233
234 /**
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
239 * @return array
240 */
241 public function arrayFromStatus( StatusValue $status, $type = 'error', $format = null ) {
242 if ( $status->isGood() || !$status->getErrors() ) {
243 return [];
244 }
245
246 $result = new ApiResult( 1e6 );
247 $formatter = new ApiErrorFormatter(
248 $result, $this->lang, $format ?: $this->format, $this->useDB
249 );
250 $formatter->addMessagesFromStatus( null, $status, [ $type ] );
251 switch ( $type ) {
252 case 'error':
253 return (array)$result->getResultData( [ 'errors' ] );
254 case 'warning':
255 return (array)$result->getResultData( [ 'warnings' ] );
256 }
257 }
258
259 /**
260 * Turn wikitext into something resembling plaintext
261 * @since 1.29
262 * @param string $text
263 * @return string
264 */
265 public static function stripMarkup( $text ) {
266 // Turn semantic quoting tags to quotes
267 $ret = preg_replace( '!</?(var|kbd|samp|code)>!', '"', $text );
268
269 // Strip tags and decode.
270 $ret = Sanitizer::stripAllTags( $ret );
271
272 return $ret;
273 }
274
275 /**
276 * Format a Message object for raw format
277 * @param MessageSpecifier $msg
278 * @return array
279 */
280 private function formatRawMessage( MessageSpecifier $msg ) {
281 $ret = [
282 'key' => $msg->getKey(),
283 'params' => $msg->getParams(),
284 ];
285 ApiResult::setIndexedTagName( $ret['params'], 'param' );
286
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 ) ];
291 }
292 }
293 return $ret;
294 }
295
296 /**
297 * Format a message as an array
298 * @since 1.29
299 * @param ApiMessage|ApiRawMessage $msg
300 * @param string|null $format
301 * @return array
302 */
303 protected function formatMessageInternal( $msg, $format ) {
304 $value = [ 'code' => $msg->getApiCode() ];
305 switch ( $format ) {
306 case 'plaintext':
307 $value += [
308 'text' => self::stripMarkup( $msg->text() ),
309 ApiResult::META_CONTENT => 'text',
310 ];
311 break;
312
313 case 'wikitext':
314 $value += [
315 'text' => $msg->text(),
316 ApiResult::META_CONTENT => 'text',
317 ];
318 break;
319
320 case 'html':
321 $value += [
322 'html' => $msg->parse(),
323 ApiResult::META_CONTENT => 'html',
324 ];
325 break;
326
327 case 'raw':
328 $value += $this->formatRawMessage( $msg );
329 break;
330
331 case 'none':
332 break;
333 }
334 $data = $msg->getApiData();
335 if ( $data ) {
336 $value['data'] = $msg->getApiData() + [
337 ApiResult::META_TYPE => 'assoc',
338 ];
339 }
340 return $value;
341 }
342
343 /**
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
348 */
349 protected function addWarningOrError( $tag, $modulePath, $msg ) {
350 $value = $this->formatMessageInternal( $msg, $this->format );
351 if ( $modulePath !== null ) {
352 $value += [ 'module' => $modulePath ];
353 }
354
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;
361 }
362 $this->result->addValue( $path, null, $value, $flags );
363 $this->result->addIndexedTagName( $path, $tag );
364 }
365 }
366 }
367
368 /**
369 * Format errors and warnings in the old style, for backwards compatibility.
370 * @since 1.25
371 * @deprecated Only for backwards compatibility, do not use
372 * @ingroup API
373 */
374 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
375 class ApiErrorFormatter_BackCompat extends ApiErrorFormatter {
376
377 /**
378 * @param ApiResult $result Into which data will be added
379 */
380 public function __construct( ApiResult $result ) {
381 parent::__construct( $result, Language::factory( 'en' ), 'none', false );
382 }
383
384 public function getFormat() {
385 return 'bc';
386 }
387
388 public function arrayFromStatus( StatusValue $status, $type = 'error', $format = null ) {
389 if ( $status->isGood() || !$status->getErrors() ) {
390 return [];
391 }
392
393 $result = [];
394 foreach ( $status->getErrorsByType( $type ) as $error ) {
395 $msg = ApiMessage::create( $error );
396 $error = [
397 'message' => $msg->getKey(),
398 'params' => $msg->getParams(),
399 'code' => $msg->getApiCode(),
400 ] + $error;
401 ApiResult::setIndexedTagName( $error['params'], 'param' );
402 $result[] = $error;
403 }
404 ApiResult::setIndexedTagName( $result, $type );
405
406 return $result;
407 }
408
409 protected function formatMessageInternal( $msg, $format ) {
410 return [
411 'code' => $msg->getApiCode(),
412 'info' => $msg->text(),
413 ] + $msg->getApiData();
414 }
415
416 /**
417 * Format an exception as an array
418 * @since 1.29
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
423 */
424 public function formatException( $exception, array $options = [] ) {
425 $ret = parent::formatException( $exception, $options );
426 return empty( $options['bc'] ) ? $ret : $ret['info'];
427 }
428
429 protected function addWarningOrError( $tag, $modulePath, $msg ) {
430 $value = self::stripMarkup( $msg->text() );
431
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'] )
437 ) {
438 $value = [
439 'code' => $msg->getApiCode(),
440 'info' => $value,
441 ] + $msg->getApiData();
442 $this->result->addValue( null, 'error', $value,
443 ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
444 }
445 } else {
446 if ( $modulePath === null ) {
447 $moduleName = 'unknown';
448 } else {
449 $i = strrpos( $modulePath, '+' );
450 $moduleName = $i === false ? $modulePath : substr( $modulePath, $i + 1 );
451 }
452
453 // Don't add duplicate warnings
454 $tag .= 's';
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" ) {
464 return;
465 }
466 }
467 // If there is a warning already, append it to the existing one
468 $value = "$oldWarning\n$value";
469 }
470 $this->result->addContentValue( $path, $tag, $value,
471 ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
472 }
473 }
474 }