Add config for serving main Page from the domain root
[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 * @phan-file-suppress PhanUndeclaredMethod Undeclared methods in IApiMessage
30 */
31 class ApiErrorFormatter {
32 /** @var Title Dummy title to silence warnings from MessageCache::parse() */
33 private static $dummyTitle = null;
34
35 /** @var ApiResult */
36 protected $result;
37
38 /** @var Language */
39 protected $lang;
40 protected $useDB = false;
41 protected $format = 'none';
42
43 /**
44 * @param ApiResult $result Into which data will be added
45 * @param Language $lang Used for i18n
46 * @param string $format
47 * - plaintext: Error message as something vaguely like plaintext
48 * (it's basically wikitext with HTML tags stripped and entities decoded)
49 * - wikitext: Error message as wikitext
50 * - html: Error message as HTML
51 * - raw: Raw message key and parameters, no human-readable text
52 * - none: Code and data only, no human-readable text
53 * @param bool $useDB Whether to use local translations for errors and warnings.
54 */
55 public function __construct( ApiResult $result, Language $lang, $format, $useDB = false ) {
56 $this->result = $result;
57 $this->lang = $lang;
58 $this->useDB = $useDB;
59 $this->format = $format;
60 }
61
62 /**
63 * Test whether a code is a valid API error code
64 *
65 * A valid code contains only ASCII letters, numbers, underscore, and
66 * hyphen and is not the empty string.
67 *
68 * For backwards compatibility, any code beginning 'internal_api_error_' is
69 * also allowed.
70 *
71 * @param string $code
72 * @return bool
73 */
74 public static function isValidApiCode( $code ) {
75 return is_string( $code ) && (
76 preg_match( '/^[a-zA-Z0-9_-]+$/', $code ) ||
77 // TODO: Deprecate this
78 preg_match( '/^internal_api_error_[^\0\r\n]+$/', $code )
79 );
80 }
81
82 /**
83 * Return a formatter like this one but with a different format
84 *
85 * @since 1.32
86 * @param string $format New format.
87 * @return ApiErrorFormatter
88 */
89 public function newWithFormat( $format ) {
90 return new self( $this->result, $this->lang, $format, $this->useDB );
91 }
92
93 /**
94 * Fetch the format for this formatter
95 * @since 1.32
96 * @return string
97 */
98 public function getFormat() {
99 return $this->format;
100 }
101
102 /**
103 * Fetch the Language for this formatter
104 * @since 1.29
105 * @return Language
106 */
107 public function getLanguage() {
108 return $this->lang;
109 }
110
111 /**
112 * Fetch a dummy title to set on Messages
113 * @return Title
114 */
115 protected function getDummyTitle() {
116 if ( self::$dummyTitle === null ) {
117 self::$dummyTitle = Title::makeTitle( NS_SPECIAL, 'Badtitle/' . __METHOD__ );
118 }
119 return self::$dummyTitle;
120 }
121
122 /**
123 * Add a warning to the result
124 * @param string|null $modulePath
125 * @param Message|array|string $msg Warning message. See ApiMessage::create().
126 * @param string|null $code See ApiMessage::create().
127 * @param array|null $data See ApiMessage::create().
128 */
129 public function addWarning( $modulePath, $msg, $code = null, $data = null ) {
130 $msg = ApiMessage::create( $msg, $code, $data )
131 ->inLanguage( $this->lang )
132 ->title( $this->getDummyTitle() )
133 ->useDatabase( $this->useDB );
134 $this->addWarningOrError( 'warning', $modulePath, $msg );
135 }
136
137 /**
138 * Add an error to the result
139 * @param string|null $modulePath
140 * @param Message|array|string $msg Warning message. See ApiMessage::create().
141 * @param string|null $code See ApiMessage::create().
142 * @param array|null $data See ApiMessage::create().
143 */
144 public function addError( $modulePath, $msg, $code = null, $data = null ) {
145 $msg = ApiMessage::create( $msg, $code, $data )
146 ->inLanguage( $this->lang )
147 ->title( $this->getDummyTitle() )
148 ->useDatabase( $this->useDB );
149 $this->addWarningOrError( 'error', $modulePath, $msg );
150 }
151
152 /**
153 * Add warnings and errors from a StatusValue object to the result
154 * @param string|null $modulePath
155 * @param StatusValue $status
156 * @param string[]|string $types 'warning' and/or 'error'
157 * @param string[] $filter Messages to filter out (since 1.33)
158 */
159 public function addMessagesFromStatus(
160 $modulePath, StatusValue $status, $types = [ 'warning', 'error' ], array $filter = []
161 ) {
162 if ( $status->isGood() || !$status->getErrors() ) {
163 return;
164 }
165
166 $types = (array)$types;
167 foreach ( $status->getErrors() as $error ) {
168 if ( !in_array( $error['type'], $types, true ) ) {
169 continue;
170 }
171
172 if ( $error['type'] === 'error' ) {
173 $tag = 'error';
174 } else {
175 // Assume any unknown type is a warning
176 $tag = 'warning';
177 }
178
179 $msg = ApiMessage::create( $error )
180 ->inLanguage( $this->lang )
181 ->title( $this->getDummyTitle() )
182 ->useDatabase( $this->useDB );
183 if ( !in_array( $msg->getKey(), $filter, true ) ) {
184 $this->addWarningOrError( $tag, $modulePath, $msg );
185 }
186 }
187 }
188
189 /**
190 * Get an ApiMessage from an exception
191 * @since 1.29
192 * @param Exception|Throwable $exception
193 * @param array $options
194 * - wrap: (string|array|MessageSpecifier) Used to wrap the exception's
195 * message if it's not an ILocalizedException. The exception's message
196 * will be added as the final parameter.
197 * - code: (string) Default code
198 * - data: (array) Default extra data
199 * @return IApiMessage
200 */
201 public function getMessageFromException( $exception, array $options = [] ) {
202 $options += [ 'code' => null, 'data' => [] ];
203
204 if ( $exception instanceof ILocalizedException ) {
205 $msg = $exception->getMessageObject();
206 $params = [];
207 } elseif ( $exception instanceof MessageSpecifier ) {
208 $msg = Message::newFromSpecifier( $exception );
209 $params = [];
210 } else {
211 if ( isset( $options['wrap'] ) ) {
212 $msg = $options['wrap'];
213 } else {
214 $msg = new RawMessage( '$1' );
215 if ( !isset( $options['code'] ) ) {
216 $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $exception ) );
217 $options['code'] = 'internal_api_error_' . $class;
218 $options['data']['errorclass'] = get_class( $exception );
219 }
220 }
221 $params = [ wfEscapeWikiText( $exception->getMessage() ) ];
222 }
223 return ApiMessage::create( $msg, $options['code'], $options['data'] )
224 ->params( $params )
225 ->inLanguage( $this->lang )
226 ->title( $this->getDummyTitle() )
227 ->useDatabase( $this->useDB );
228 }
229
230 /**
231 * Format an exception as an array
232 * @since 1.29
233 * @param Exception|Throwable $exception
234 * @param array $options See self::getMessageFromException(), plus
235 * - format: (string) Format override
236 * @return array
237 */
238 public function formatException( $exception, array $options = [] ) {
239 return $this->formatMessage(
240 $this->getMessageFromException( $exception, $options ),
241 $options['format'] ?? null
242 );
243 }
244
245 /**
246 * Format a message as an array
247 * @param Message|array|string $msg Message. See ApiMessage::create().
248 * @param string|null $format
249 * @return array
250 */
251 public function formatMessage( $msg, $format = null ) {
252 $msg = ApiMessage::create( $msg )
253 ->inLanguage( $this->lang )
254 ->title( $this->getDummyTitle() )
255 ->useDatabase( $this->useDB );
256 return $this->formatMessageInternal( $msg, $format ?: $this->format );
257 }
258
259 /**
260 * Format messages from a StatusValue as an array
261 * @param StatusValue $status
262 * @param string $type 'warning' or 'error'
263 * @param string|null $format
264 * @return array
265 */
266 public function arrayFromStatus( StatusValue $status, $type = 'error', $format = null ) {
267 if ( $status->isGood() || !$status->getErrors() ) {
268 return [];
269 }
270
271 $result = new ApiResult( 1e6 );
272 $formatter = new ApiErrorFormatter(
273 $result, $this->lang, $format ?: $this->format, $this->useDB
274 );
275 $formatter->addMessagesFromStatus( null, $status, [ $type ] );
276 switch ( $type ) {
277 case 'error':
278 return (array)$result->getResultData( [ 'errors' ] );
279 case 'warning':
280 return (array)$result->getResultData( [ 'warnings' ] );
281 }
282 }
283
284 /**
285 * Turn wikitext into something resembling plaintext
286 * @since 1.29
287 * @param string $text
288 * @return string
289 */
290 public static function stripMarkup( $text ) {
291 // Turn semantic quoting tags to quotes
292 $ret = preg_replace( '!</?(var|kbd|samp|code)>!', '"', $text );
293
294 // Strip tags and decode.
295 $ret = Sanitizer::stripAllTags( $ret );
296
297 return $ret;
298 }
299
300 /**
301 * Format a Message object for raw format
302 * @param MessageSpecifier $msg
303 * @return array
304 */
305 private function formatRawMessage( MessageSpecifier $msg ) {
306 $ret = [
307 'key' => $msg->getKey(),
308 'params' => $msg->getParams(),
309 ];
310 ApiResult::setIndexedTagName( $ret['params'], 'param' );
311
312 // Transform Messages as parameters in the style of Message::fooParam().
313 foreach ( $ret['params'] as $i => $param ) {
314 if ( $param instanceof MessageSpecifier ) {
315 $ret['params'][$i] = [ 'message' => $this->formatRawMessage( $param ) ];
316 }
317 }
318 return $ret;
319 }
320
321 /**
322 * Format a message as an array
323 * @since 1.29
324 * @param ApiMessage|ApiRawMessage $msg
325 * @param string|null $format
326 * @return array
327 */
328 protected function formatMessageInternal( $msg, $format ) {
329 $value = [ 'code' => $msg->getApiCode() ];
330 switch ( $format ) {
331 case 'plaintext':
332 $value += [
333 'text' => self::stripMarkup( $msg->text() ),
334 ApiResult::META_CONTENT => 'text',
335 ];
336 break;
337
338 case 'wikitext':
339 $value += [
340 'text' => $msg->text(),
341 ApiResult::META_CONTENT => 'text',
342 ];
343 break;
344
345 case 'html':
346 $value += [
347 'html' => $msg->parse(),
348 ApiResult::META_CONTENT => 'html',
349 ];
350 break;
351
352 case 'raw':
353 $value += $this->formatRawMessage( $msg );
354 break;
355
356 case 'none':
357 break;
358 }
359 $data = $msg->getApiData();
360 if ( $data ) {
361 $value['data'] = $msg->getApiData() + [
362 ApiResult::META_TYPE => 'assoc',
363 ];
364 }
365 return $value;
366 }
367
368 /**
369 * Actually add the warning or error to the result
370 * @param string $tag 'warning' or 'error'
371 * @param string|null $modulePath
372 * @param ApiMessage|ApiRawMessage $msg
373 */
374 protected function addWarningOrError( $tag, $modulePath, $msg ) {
375 $value = $this->formatMessageInternal( $msg, $this->format );
376 if ( $modulePath !== null ) {
377 $value += [ 'module' => $modulePath ];
378 }
379
380 $path = [ $tag . 's' ];
381 $existing = $this->result->getResultData( $path );
382 if ( $existing === null || !in_array( $value, $existing ) ) {
383 $flags = ApiResult::NO_SIZE_CHECK;
384 if ( $existing === null ) {
385 $flags |= ApiResult::ADD_ON_TOP;
386 }
387 $this->result->addValue( $path, null, $value, $flags );
388 $this->result->addIndexedTagName( $path, $tag );
389 }
390 }
391 }