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