Merge "Remove perf tracking code that was moved to WikimediaEvents in Ib300af5c"
[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 if it's not an ILocalizedException. The exception's message
152 * will be added as the final parameter.
153 * - code: (string) Default code
154 * - data: (array) Default extra data
155 * @return IApiMessage
156 */
157 public function getMessageFromException( $exception, array $options = [] ) {
158 $options += [ 'code' => null, 'data' => [] ];
159
160 if ( $exception instanceof ILocalizedException ) {
161 $msg = $exception->getMessageObject();
162 $params = [];
163 } elseif ( $exception instanceof MessageSpecifier ) {
164 $msg = Message::newFromSpecifier( $exception );
165 $params = [];
166 } else {
167 // Extract code and data from the exception, if applicable
168 if ( $exception instanceof UsageException ) {
169 $data = $exception->getMessageArray();
170 if ( !$options['code'] ) {
171 $options['code'] = $data['code'];
172 }
173 unset( $data['code'], $data['info'] );
174 $options['data'] = array_merge( $data, $options['data'] );
175 }
176
177 if ( isset( $options['wrap'] ) ) {
178 $msg = $options['wrap'];
179 } else {
180 $msg = new RawMessage( '$1' );
181 if ( !isset( $options['code'] ) ) {
182 $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $exception ) );
183 $options['code'] = 'internal_api_error_' . $class;
184 }
185 }
186 $params = [ wfEscapeWikiText( $exception->getMessage() ) ];
187 }
188 return ApiMessage::create( $msg, $options['code'], $options['data'] )
189 ->params( $params )
190 ->inLanguage( $this->lang )
191 ->title( $this->getDummyTitle() )
192 ->useDatabase( $this->useDB );
193 }
194
195 /**
196 * Format an exception as an array
197 * @since 1.29
198 * @param Exception|Throwable $exception
199 * @param array $options See self::getMessageFromException(), plus
200 * - format: (string) Format override
201 * @return array
202 */
203 public function formatException( $exception, array $options = [] ) {
204 return $this->formatMessage(
205 $this->getMessageFromException( $exception, $options ),
206 isset( $options['format'] ) ? $options['format'] : null
207 );
208 }
209
210 /**
211 * Format a message as an array
212 * @param Message|array|string $msg Message. See ApiMessage::create().
213 * @param string|null $format
214 * @return array
215 */
216 public function formatMessage( $msg, $format = null ) {
217 $msg = ApiMessage::create( $msg )
218 ->inLanguage( $this->lang )
219 ->title( $this->getDummyTitle() )
220 ->useDatabase( $this->useDB );
221 return $this->formatMessageInternal( $msg, $format ?: $this->format );
222 }
223
224 /**
225 * Format messages from a StatusValue as an array
226 * @param StatusValue $status
227 * @param string $type 'warning' or 'error'
228 * @param string|null $format
229 * @return array
230 */
231 public function arrayFromStatus( StatusValue $status, $type = 'error', $format = null ) {
232 if ( $status->isGood() || !$status->getErrors() ) {
233 return [];
234 }
235
236 $result = new ApiResult( 1e6 );
237 $formatter = new ApiErrorFormatter(
238 $result, $this->lang, $format ?: $this->format, $this->useDB
239 );
240 $formatter->addMessagesFromStatus( null, $status, [ $type ] );
241 switch ( $type ) {
242 case 'error':
243 return (array)$result->getResultData( [ 'errors' ] );
244 case 'warning':
245 return (array)$result->getResultData( [ 'warnings' ] );
246 }
247 }
248
249 /**
250 * Turn wikitext into something resembling plaintext
251 * @since 1.29
252 * @param string $text
253 * @return string
254 */
255 public static function stripMarkup( $text ) {
256 // Turn semantic quoting tags to quotes
257 $ret = preg_replace( '!</?(var|kbd|samp|code)>!', '"', $text );
258
259 // Strip tags and decode.
260 $ret = Sanitizer::stripAllTags( $ret );
261
262 return $ret;
263 }
264
265 /**
266 * Format a Message object for raw format
267 * @param MessageSpecifier $msg
268 * @return array
269 */
270 private function formatRawMessage( MessageSpecifier $msg ) {
271 $ret = [
272 'key' => $msg->getKey(),
273 'params' => $msg->getParams(),
274 ];
275 ApiResult::setIndexedTagName( $ret['params'], 'param' );
276
277 // Transform Messages as parameters in the style of Message::fooParam().
278 foreach ( $ret['params'] as $i => $param ) {
279 if ( $param instanceof MessageSpecifier ) {
280 $ret['params'][$i] = [ 'message' => $this->formatRawMessage( $param ) ];
281 }
282 }
283 return $ret;
284 }
285
286 /**
287 * Format a message as an array
288 * @since 1.29
289 * @param ApiMessage|ApiRawMessage $msg
290 * @param string|null $format
291 * @return array
292 */
293 protected function formatMessageInternal( $msg, $format ) {
294 $value = [ 'code' => $msg->getApiCode() ];
295 switch ( $format ) {
296 case 'plaintext':
297 $value += [
298 'text' => self::stripMarkup( $msg->text() ),
299 ApiResult::META_CONTENT => 'text',
300 ];
301 break;
302
303 case 'wikitext':
304 $value += [
305 'text' => $msg->text(),
306 ApiResult::META_CONTENT => 'text',
307 ];
308 break;
309
310 case 'html':
311 $value += [
312 'html' => $msg->parse(),
313 ApiResult::META_CONTENT => 'html',
314 ];
315 break;
316
317 case 'raw':
318 $value += $this->formatRawMessage( $msg );
319 break;
320
321 case 'none':
322 break;
323 }
324 $data = $msg->getApiData();
325 if ( $data ) {
326 $value['data'] = $msg->getApiData() + [
327 ApiResult::META_TYPE => 'assoc',
328 ];
329 }
330 return $value;
331 }
332
333 /**
334 * Actually add the warning or error to the result
335 * @param string $tag 'warning' or 'error'
336 * @param string|null $modulePath
337 * @param ApiMessage|ApiRawMessage $msg
338 */
339 protected function addWarningOrError( $tag, $modulePath, $msg ) {
340 $value = $this->formatMessageInternal( $msg, $this->format );
341 if ( $modulePath !== null ) {
342 $value += [ 'module' => $modulePath ];
343 }
344
345 $path = [ $tag . 's' ];
346 $existing = $this->result->getResultData( $path );
347 if ( $existing === null || !in_array( $value, $existing ) ) {
348 $flags = ApiResult::NO_SIZE_CHECK;
349 if ( $existing === null ) {
350 $flags |= ApiResult::ADD_ON_TOP;
351 }
352 $this->result->addValue( $path, null, $value, $flags );
353 $this->result->addIndexedTagName( $path, $tag );
354 }
355 }
356 }
357
358 /**
359 * Format errors and warnings in the old style, for backwards compatibility.
360 * @since 1.25
361 * @deprecated Only for backwards compatibility, do not use
362 * @ingroup API
363 */
364 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
365 class ApiErrorFormatter_BackCompat extends ApiErrorFormatter {
366 // @codingStandardsIgnoreEnd
367
368 /**
369 * @param ApiResult $result Into which data will be added
370 */
371 public function __construct( ApiResult $result ) {
372 parent::__construct( $result, Language::factory( 'en' ), 'none', false );
373 }
374
375 public function arrayFromStatus( StatusValue $status, $type = 'error', $format = null ) {
376 if ( $status->isGood() || !$status->getErrors() ) {
377 return [];
378 }
379
380 $result = [];
381 foreach ( $status->getErrorsByType( $type ) as $error ) {
382 $msg = ApiMessage::create( $error );
383 $error = [
384 'message' => $msg->getKey(),
385 'params' => $msg->getParams(),
386 'code' => $msg->getApiCode(),
387 ] + $error;
388 ApiResult::setIndexedTagName( $error['params'], 'param' );
389 $result[] = $error;
390 }
391 ApiResult::setIndexedTagName( $result, $type );
392
393 return $result;
394 }
395
396 protected function formatMessageInternal( $msg, $format ) {
397 return [
398 'code' => $msg->getApiCode(),
399 'info' => $msg->text(),
400 ] + $msg->getApiData();
401 }
402
403 /**
404 * Format an exception as an array
405 * @since 1.29
406 * @param Exception|Throwable $exception
407 * @param array $options See parent::formatException(), plus
408 * - bc: (bool) Return only the string, not an array
409 * @return array|string
410 */
411 public function formatException( $exception, array $options = [] ) {
412 $ret = parent::formatException( $exception, $options );
413 return empty( $options['bc'] ) ? $ret : $ret['info'];
414 }
415
416 protected function addWarningOrError( $tag, $modulePath, $msg ) {
417 $value = self::stripMarkup( $msg->text() );
418
419 if ( $tag === 'error' ) {
420 // In BC mode, only one error
421 $existingError = $this->result->getResultData( [ 'error' ] );
422 if ( !is_array( $existingError ) ||
423 !isset( $existingError['code'] ) || !isset( $existingError['info'] )
424 ) {
425 $value = [
426 'code' => $msg->getApiCode(),
427 'info' => $value,
428 ] + $msg->getApiData();
429 $this->result->addValue( null, 'error', $value,
430 ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
431 }
432 } else {
433 if ( $modulePath === null ) {
434 $moduleName = 'unknown';
435 } else {
436 $i = strrpos( $modulePath, '+' );
437 $moduleName = $i === false ? $modulePath : substr( $modulePath, $i + 1 );
438 }
439
440 // Don't add duplicate warnings
441 $tag .= 's';
442 $path = [ $tag, $moduleName ];
443 $oldWarning = $this->result->getResultData( [ $tag, $moduleName, $tag ] );
444 if ( $oldWarning !== null ) {
445 $warnPos = strpos( $oldWarning, $value );
446 // If $value was found in $oldWarning, check if it starts at 0 or after "\n"
447 if ( $warnPos !== false && ( $warnPos === 0 || $oldWarning[$warnPos - 1] === "\n" ) ) {
448 // Check if $value is followed by "\n" or the end of the $oldWarning
449 $warnPos += strlen( $value );
450 if ( strlen( $oldWarning ) <= $warnPos || $oldWarning[$warnPos] === "\n" ) {
451 return;
452 }
453 }
454 // If there is a warning already, append it to the existing one
455 $value = "$oldWarning\n$value";
456 }
457 $this->result->addContentValue( $path, $tag, $value,
458 ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
459 }
460 }
461 }