Merge "Update docs/hooks.txt for ShowSearchHitTitle"
[mediawiki.git] / includes / api / ApiErrorFormatter.php
blob814004a67362e9aab242766984db2ceb2422b5da
1 <?php
2 /**
3 * This file contains the ApiErrorFormatter definition, plus implementations of
4 * specific formatters.
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
21 * @file
24 /**
25 * Formats errors and warnings for the API, and add them to the associated
26 * ApiResult.
27 * @since 1.25
28 * @ingroup API
30 class ApiErrorFormatter {
31 /** @var Title Dummy title to silence warnings from MessageCache::parse() */
32 private static $dummyTitle = null;
34 /** @var ApiResult */
35 protected $result;
37 /** @var Language */
38 protected $lang;
39 protected $useDB = false;
40 protected $format = 'none';
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.
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;
61 /**
62 * Fetch the Language for this formatter
63 * @since 1.29
64 * @return Language
66 public function getLanguage() {
67 return $this->lang;
70 /**
71 * Fetch a dummy title to set on Messages
72 * @return Title
74 protected function getDummyTitle() {
75 if ( self::$dummyTitle === null ) {
76 self::$dummyTitle = Title::makeTitle( NS_SPECIAL, 'Badtitle/' . __METHOD__ );
78 return self::$dummyTitle;
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().
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 );
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().
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 );
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'
117 public function addMessagesFromStatus(
118 $modulePath, StatusValue $status, $types = [ 'warning', 'error' ]
120 if ( $status->isGood() || !$status->getErrors() ) {
121 return;
124 $types = (array)$types;
125 foreach ( $status->getErrors() as $error ) {
126 if ( !in_array( $error['type'], $types, true ) ) {
127 continue;
130 if ( $error['type'] === 'error' ) {
131 $tag = 'error';
132 } else {
133 // Assume any unknown type is a warning
134 $tag = 'warning';
137 $msg = ApiMessage::create( $error )
138 ->inLanguage( $this->lang )
139 ->title( $this->getDummyTitle() )
140 ->useDatabase( $this->useDB );
141 $this->addWarningOrError( $tag, $modulePath, $msg );
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
157 public function getMessageFromException( $exception, array $options = [] ) {
158 $options += [ 'code' => null, 'data' => [] ];
160 if ( $exception instanceof ILocalizedException ) {
161 $msg = $exception->getMessageObject();
162 $params = [];
163 } else {
164 // Extract code and data from the exception, if applicable
165 if ( $exception instanceof UsageException ) {
166 $data = $exception->getMessageArray();
167 if ( !$options['code'] ) {
168 $options['code'] = $data['code'];
170 unset( $data['code'], $data['info'] );
171 $options['data'] = array_merge( $data, $options['data'] );
174 if ( isset( $options['wrap'] ) ) {
175 $msg = $options['wrap'];
176 } else {
177 $msg = new RawMessage( '$1' );
178 if ( !isset( $options['code'] ) ) {
179 $options['code'] = 'internal_api_error_' . get_class( $exception );
182 $params = [ wfEscapeWikiText( $exception->getMessage() ) ];
184 return ApiMessage::create( $msg, $options['code'], $options['data'] )
185 ->params( $params )
186 ->inLanguage( $this->lang )
187 ->title( $this->getDummyTitle() )
188 ->useDatabase( $this->useDB );
192 * Format an exception as an array
193 * @since 1.29
194 * @param Exception|Throwable $exception
195 * @param array $options See self::getMessageFromException(), plus
196 * - format: (string) Format override
197 * @return array
199 public function formatException( $exception, array $options = [] ) {
200 return $this->formatMessage(
201 $this->getMessageFromException( $exception, $options ),
202 isset( $options['format'] ) ? $options['format'] : null
207 * Format a message as an array
208 * @param Message|array|string $msg Message. See ApiMessage::create().
209 * @param string|null $format
210 * @return array
212 public function formatMessage( $msg, $format = null ) {
213 $msg = ApiMessage::create( $msg )
214 ->inLanguage( $this->lang )
215 ->title( $this->getDummyTitle() )
216 ->useDatabase( $this->useDB );
217 return $this->formatMessageInternal( $msg, $format ?: $this->format );
221 * Format messages from a StatusValue as an array
222 * @param StatusValue $status
223 * @param string $type 'warning' or 'error'
224 * @param string|null $format
225 * @return array
227 public function arrayFromStatus( StatusValue $status, $type = 'error', $format = null ) {
228 if ( $status->isGood() || !$status->getErrors() ) {
229 return [];
232 $result = new ApiResult( 1e6 );
233 $formatter = new ApiErrorFormatter(
234 $result, $this->lang, $format ?: $this->format, $this->useDB
236 $formatter->addMessagesFromStatus( null, $status, [ $type ] );
237 switch ( $type ) {
238 case 'error':
239 return (array)$result->getResultData( [ 'errors' ] );
240 case 'warning':
241 return (array)$result->getResultData( [ 'warnings' ] );
246 * Turn wikitext into something resembling plaintext
247 * @since 1.29
248 * @param string $text
249 * @return string
251 public static function stripMarkup( $text ) {
252 // Turn semantic quoting tags to quotes
253 $ret = preg_replace( '!</?(var|kbd|samp|code)>!', '"', $text );
255 // Strip tags and decode.
256 $ret = html_entity_decode( strip_tags( $ret ), ENT_QUOTES | ENT_HTML5 );
258 return $ret;
262 * Format a Message object for raw format
263 * @param MessageSpecifier $msg
264 * @return array
266 private function formatRawMessage( MessageSpecifier $msg ) {
267 $ret = [
268 'key' => $msg->getKey(),
269 'params' => $msg->getParams(),
271 ApiResult::setIndexedTagName( $ret['params'], 'param' );
273 // Transform Messages as parameters in the style of Message::fooParam().
274 foreach ( $ret['params'] as $i => $param ) {
275 if ( $param instanceof MessageSpecifier ) {
276 $ret['params'][$i] = [ 'message' => $this->formatRawMessage( $param ) ];
279 return $ret;
283 * Format a message as an array
284 * @since 1.29
285 * @param ApiMessage|ApiRawMessage $msg
286 * @param string|null $format
287 * @return array
289 protected function formatMessageInternal( $msg, $format ) {
290 $value = [ 'code' => $msg->getApiCode() ];
291 switch ( $format ) {
292 case 'plaintext':
293 $value += [
294 'text' => self::stripMarkup( $msg->text() ),
295 ApiResult::META_CONTENT => 'text',
297 break;
299 case 'wikitext':
300 $value += [
301 'text' => $msg->text(),
302 ApiResult::META_CONTENT => 'text',
304 break;
306 case 'html':
307 $value += [
308 'html' => $msg->parse(),
309 ApiResult::META_CONTENT => 'html',
311 break;
313 case 'raw':
314 $value += $this->formatRawMessage( $msg );
315 break;
317 case 'none':
318 break;
320 $data = $msg->getApiData();
321 if ( $data ) {
322 $value['data'] = $msg->getApiData() + [
323 ApiResult::META_TYPE => 'assoc',
326 return $value;
330 * Actually add the warning or error to the result
331 * @param string $tag 'warning' or 'error'
332 * @param string|null $modulePath
333 * @param ApiMessage|ApiRawMessage $msg
335 protected function addWarningOrError( $tag, $modulePath, $msg ) {
336 $value = $this->formatMessageInternal( $msg, $this->format );
337 if ( $modulePath !== null ) {
338 $value += [ 'module' => $modulePath ];
341 $path = [ $tag . 's' ];
342 $existing = $this->result->getResultData( $path );
343 if ( $existing === null || !in_array( $value, $existing ) ) {
344 $flags = ApiResult::NO_SIZE_CHECK;
345 if ( $existing === null ) {
346 $flags |= ApiResult::ADD_ON_TOP;
348 $this->result->addValue( $path, null, $value, $flags );
349 $this->result->addIndexedTagName( $path, $tag );
355 * Format errors and warnings in the old style, for backwards compatibility.
356 * @since 1.25
357 * @deprecated Only for backwards compatibility, do not use
358 * @ingroup API
360 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
361 class ApiErrorFormatter_BackCompat extends ApiErrorFormatter {
362 // @codingStandardsIgnoreEnd
365 * @param ApiResult $result Into which data will be added
367 public function __construct( ApiResult $result ) {
368 parent::__construct( $result, Language::factory( 'en' ), 'none', false );
371 public function arrayFromStatus( StatusValue $status, $type = 'error', $format = null ) {
372 if ( $status->isGood() || !$status->getErrors() ) {
373 return [];
376 $result = [];
377 foreach ( $status->getErrorsByType( $type ) as $error ) {
378 $msg = ApiMessage::create( $error );
379 $error = [
380 'message' => $msg->getKey(),
381 'params' => $msg->getParams(),
382 'code' => $msg->getApiCode(),
383 ] + $error;
384 ApiResult::setIndexedTagName( $error['params'], 'param' );
385 $result[] = $error;
387 ApiResult::setIndexedTagName( $result, $type );
389 return $result;
392 protected function formatMessageInternal( $msg, $format ) {
393 return [
394 'code' => $msg->getApiCode(),
395 'info' => $msg->text(),
396 ] + $msg->getApiData();
400 * Format an exception as an array
401 * @since 1.29
402 * @param Exception|Throwable $exception
403 * @param array $options See parent::formatException(), plus
404 * - bc: (bool) Return only the string, not an array
405 * @return array|string
407 public function formatException( $exception, array $options = [] ) {
408 $ret = parent::formatException( $exception, $options );
409 return empty( $options['bc'] ) ? $ret : $ret['info'];
412 protected function addWarningOrError( $tag, $modulePath, $msg ) {
413 $value = self::stripMarkup( $msg->text() );
415 if ( $tag === 'error' ) {
416 // In BC mode, only one error
417 $value = [
418 'code' => $msg->getApiCode(),
419 'info' => $value,
420 ] + $msg->getApiData();
421 $this->result->addValue( null, 'error', $value,
422 ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
423 } else {
424 if ( $modulePath === null ) {
425 $moduleName = 'unknown';
426 } else {
427 $i = strrpos( $modulePath, '+' );
428 $moduleName = $i === false ? $modulePath : substr( $modulePath, $i + 1 );
431 // Don't add duplicate warnings
432 $tag .= 's';
433 $path = [ $tag, $moduleName ];
434 $oldWarning = $this->result->getResultData( [ $tag, $moduleName, $tag ] );
435 if ( $oldWarning !== null ) {
436 $warnPos = strpos( $oldWarning, $value );
437 // If $value was found in $oldWarning, check if it starts at 0 or after "\n"
438 if ( $warnPos !== false && ( $warnPos === 0 || $oldWarning[$warnPos - 1] === "\n" ) ) {
439 // Check if $value is followed by "\n" or the end of the $oldWarning
440 $warnPos += strlen( $value );
441 if ( strlen( $oldWarning ) <= $warnPos || $oldWarning[$warnPos] === "\n" ) {
442 return;
445 // If there is a warning already, append it to the existing one
446 $value = "$oldWarning\n$value";
448 $this->result->addContentValue( $path, $tag, $value,
449 ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );