Merge "Escape return path extra params to php mail()"
[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 * Format a message as an array
147 * @param Message|array|string $msg Message. See ApiMessage::create().
148 * @param string|null $format
149 * @return array
150 */
151 public function formatMessage( $msg, $format = null ) {
152 $msg = ApiMessage::create( $msg )
153 ->inLanguage( $this->lang )
154 ->title( $this->getDummyTitle() )
155 ->useDatabase( $this->useDB );
156 return $this->formatMessageInternal( $msg, $format ?: $this->format );
157 }
158
159 /**
160 * Format messages from a StatusValue as an array
161 * @param StatusValue $status
162 * @param string $type 'warning' or 'error'
163 * @param string|null $format
164 * @return array
165 */
166 public function arrayFromStatus( StatusValue $status, $type = 'error', $format = null ) {
167 if ( $status->isGood() || !$status->getErrors() ) {
168 return [];
169 }
170
171 $result = new ApiResult( 1e6 );
172 $formatter = new ApiErrorFormatter(
173 $result, $this->lang, $format ?: $this->format, $this->useDB
174 );
175 $formatter->addMessagesFromStatus( null, $status, [ $type ] );
176 switch ( $type ) {
177 case 'error':
178 return (array)$result->getResultData( [ 'errors' ] );
179 case 'warning':
180 return (array)$result->getResultData( [ 'warnings' ] );
181 }
182 }
183
184 /**
185 * Turn wikitext into something resembling plaintext
186 * @since 1.29
187 * @param string $text
188 * @return string
189 */
190 public static function stripMarkup( $text ) {
191 // Turn semantic quoting tags to quotes
192 $ret = preg_replace( '!</?(var|kbd|samp|code)>!', '"', $text );
193
194 // Strip tags and decode.
195 $ret = html_entity_decode( strip_tags( $ret ), ENT_QUOTES | ENT_HTML5 );
196
197 return $ret;
198 }
199
200 /**
201 * Format a Message object for raw format
202 * @param MessageSpecifier $msg
203 * @return array
204 */
205 private function formatRawMessage( MessageSpecifier $msg ) {
206 $ret = [
207 'key' => $msg->getKey(),
208 'params' => $msg->getParams(),
209 ];
210 ApiResult::setIndexedTagName( $ret['params'], 'param' );
211
212 // Transform Messages as parameters in the style of Message::fooParam().
213 foreach ( $ret['params'] as $i => $param ) {
214 if ( $param instanceof MessageSpecifier ) {
215 $ret['params'][$i] = [ 'message' => $this->formatRawMessage( $param ) ];
216 }
217 }
218 return $ret;
219 }
220
221 /**
222 * Format a message as an array
223 * @since 1.29
224 * @param ApiMessage|ApiRawMessage $msg
225 * @param string|null $format
226 * @return array
227 */
228 protected function formatMessageInternal( $msg, $format ) {
229 $value = [ 'code' => $msg->getApiCode() ];
230 switch ( $format ) {
231 case 'plaintext':
232 $value += [
233 'text' => self::stripMarkup( $msg->text() ),
234 ApiResult::META_CONTENT => 'text',
235 ];
236 break;
237
238 case 'wikitext':
239 $value += [
240 'text' => $msg->text(),
241 ApiResult::META_CONTENT => 'text',
242 ];
243 break;
244
245 case 'html':
246 $value += [
247 'html' => $msg->parse(),
248 ApiResult::META_CONTENT => 'html',
249 ];
250 break;
251
252 case 'raw':
253 $value += $this->formatRawMessage( $msg );
254 break;
255
256 case 'none':
257 break;
258 }
259 $data = $msg->getApiData();
260 if ( $data ) {
261 $value['data'] = $msg->getApiData() + [
262 ApiResult::META_TYPE => 'assoc',
263 ];
264 }
265 return $value;
266 }
267
268 /**
269 * Actually add the warning or error to the result
270 * @param string $tag 'warning' or 'error'
271 * @param string|null $modulePath
272 * @param ApiMessage|ApiRawMessage $msg
273 */
274 protected function addWarningOrError( $tag, $modulePath, $msg ) {
275 $value = $this->formatMessageInternal( $msg, $this->format );
276 if ( $modulePath !== null ) {
277 $value += [ 'module' => $modulePath ];
278 }
279
280 $path = [ $tag . 's' ];
281 $existing = $this->result->getResultData( $path );
282 if ( $existing === null || !in_array( $value, $existing ) ) {
283 $flags = ApiResult::NO_SIZE_CHECK;
284 if ( $existing === null ) {
285 $flags |= ApiResult::ADD_ON_TOP;
286 }
287 $this->result->addValue( $path, null, $value, $flags );
288 $this->result->addIndexedTagName( $path, $tag );
289 }
290 }
291 }
292
293 /**
294 * Format errors and warnings in the old style, for backwards compatibility.
295 * @since 1.25
296 * @deprecated Only for backwards compatibility, do not use
297 * @ingroup API
298 */
299 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
300 class ApiErrorFormatter_BackCompat extends ApiErrorFormatter {
301 // @codingStandardsIgnoreEnd
302
303 /**
304 * @param ApiResult $result Into which data will be added
305 */
306 public function __construct( ApiResult $result ) {
307 parent::__construct( $result, Language::factory( 'en' ), 'none', false );
308 }
309
310 public function arrayFromStatus( StatusValue $status, $type = 'error', $format = null ) {
311 if ( $status->isGood() || !$status->getErrors() ) {
312 return [];
313 }
314
315 $result = [];
316 foreach ( $status->getErrorsByType( $type ) as $error ) {
317 $msg = ApiMessage::create( $error );
318 $error = [
319 'message' => $msg->getKey(),
320 'params' => $msg->getParams(),
321 'code' => $msg->getApiCode(),
322 ] + $error;
323 ApiResult::setIndexedTagName( $error['params'], 'param' );
324 $result[] = $error;
325 }
326 ApiResult::setIndexedTagName( $result, $type );
327
328 return $result;
329 }
330
331 protected function formatMessageInternal( $msg, $format ) {
332 return [
333 'code' => $msg->getApiCode(),
334 'info' => $msg->text(),
335 ] + $msg->getApiData();
336 }
337
338 protected function addWarningOrError( $tag, $modulePath, $msg ) {
339 $value = self::stripMarkup( $msg->text() );
340
341 if ( $tag === 'error' ) {
342 // In BC mode, only one error
343 $value = [
344 'code' => $msg->getApiCode(),
345 'info' => $value,
346 ] + $msg->getApiData();
347 $this->result->addValue( null, 'error', $value,
348 ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
349 } else {
350 if ( $modulePath === null ) {
351 $moduleName = 'unknown';
352 } else {
353 $i = strrpos( $modulePath, '+' );
354 $moduleName = $i === false ? $modulePath : substr( $modulePath, $i + 1 );
355 }
356
357 // Don't add duplicate warnings
358 $tag .= 's';
359 $path = [ $tag, $moduleName ];
360 $oldWarning = $this->result->getResultData( [ $tag, $moduleName, $tag ] );
361 if ( $oldWarning !== null ) {
362 $warnPos = strpos( $oldWarning, $value );
363 // If $value was found in $oldWarning, check if it starts at 0 or after "\n"
364 if ( $warnPos !== false && ( $warnPos === 0 || $oldWarning[$warnPos - 1] === "\n" ) ) {
365 // Check if $value is followed by "\n" or the end of the $oldWarning
366 $warnPos += strlen( $value );
367 if ( strlen( $oldWarning ) <= $warnPos || $oldWarning[$warnPos] === "\n" ) {
368 return;
369 }
370 }
371 // If there is a warning already, append it to the existing one
372 $value = "$oldWarning\n$value";
373 }
374 $this->result->addContentValue( $path, $tag, $value,
375 ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
376 }
377 }
378 }