Debian Codegraph @

includes/Status/StatusFormatter.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Status;
22
23 use MediaWiki\Api\ApiMessage;
24 use MediaWiki\Language\Language;
25 use MediaWiki\Language\RawMessage;
26 use MediaWiki\Message\Message;
27 use MediaWiki\Parser\ParserOutput;
28 use MediaWiki\StubObject\StubUserLang;
29 use MessageCache;
30 use MessageLocalizer;
31 use Psr\Log\LoggerInterface;
32 use RuntimeException;
33 use StatusValue;
34 use UnexpectedValueException;
35 use Wikimedia\Message\MessageParam;
36 use Wikimedia\Message\MessageSpecifier;
37
38 /**
39 * Formatter for StatusValue objects.
40 *
41 * @since 1.42
42 *
43 * @see StatusValue
44 */
45 class StatusFormatter {
46
47 private MessageLocalizer $messageLocalizer;
48 private MessageCache $messageCache;
49 private LoggerInterface $logger;
50
51 public function __construct(
52 MessageLocalizer $messageLocalizer,
53 MessageCache $messageCache,
54 LoggerInterface $logger
55 ) {
56 $this->messageLocalizer = $messageLocalizer;
57 $this->messageCache = $messageCache;
58 $this->logger = $logger;
59 }
60
61 /**
62 * @param array $params
63 * @param array $options
64 *
65 * @return array
66 */
67 private function cleanParams( array $params, array $options = [] ) {
68 $cleanCallback = $options['cleanCallback'] ?? null;
69
70 if ( !$cleanCallback ) {
71 return $params;
72 }
73 $cleanParams = [];
74 foreach ( $params as $i => $param ) {
75 $cleanParams[$i] = call_user_func( $cleanCallback, $param );
76 }
77 return $cleanParams;
78 }
79
80 /**
81 * Get the error list as a wikitext formatted list
82 *
83 * All message parameters that were provided as strings will be escaped with wfEscapeWikiText.
84 * This is mostly a historical accident and often undesirable (T368821).
85 * - To avoid this behavior when producing the Status, pass MessageSpecifier objects to methods
86 * such as `$status->fatal()`, instead of separate key and params parameters.
87 * - To avoid this behavior when consuming the Status, use the `$status->getMessages()` method
88 * instead, and display each message separately (or combine then with `Message::listParams()`).
89 *
90 * @param StatusValue $status
91 * @param array $options An array of options, supporting the following keys:
92 * - 'shortContext' (string|false|null) A short enclosing context message name, to
93 * be used when there is a single error
94 * - 'longContext' (string|false|null) A long enclosing context message name, for a list
95 * - 'lang' (string|Language|StubUserLang|null) Language to use for processing messages
96 * - 'cleanCallback' (callable|null) A callback for sanitizing parameter values
97 *
98 * @return string
99 */
100 public function getWikiText( StatusValue $status, array $options = [] ) {
101 $shortContext = $options['shortContext'] ?? null;
102 $longContext = $options['longContext'] ?? null;
103 $lang = $options['lang'] ?? null;
104
105 $rawErrors = $status->getErrors();
106 if ( count( $rawErrors ) === 0 ) {
107 if ( $status->isOK() ) {
108 $errMsg = __METHOD__ . " called for a good result, this is incorrect\n";
109 } else {
110 $errMsg = __METHOD__ . ": Invalid result object: no error text but not OK\n";
111 }
112
113 $status->fatal(
114 'internalerror_info',
115 $errMsg
116 );
117
118 $this->logger->warning( $errMsg, [ 'exception' => new RuntimeException() ] );
119
120 $rawErrors = $status->getErrors(); // just added a fatal
121 }
122
123 if ( count( $rawErrors ) === 1 ) {
124 $s = $this->getErrorMessage( $rawErrors[0], $options )->plain();
125 if ( $shortContext ) {
126 $s = $this->msgInLang( $shortContext, $lang, $s )->plain();
127 } elseif ( $longContext ) {
128 $s = $this->msgInLang( $longContext, $lang, "* $s\n" )->plain();
129 }
130 } else {
131 $errors = $this->getErrorMessageArray( $rawErrors, $options );
132 foreach ( $errors as &$error ) {
133 $error = $error->plain();
134 }
135 $s = "<ul>\n<li>\n" . implode( "\n</li>\n<li>\n", $errors ) . "\n</li>\n</ul>\n";
136 if ( $longContext ) {
137 $s = $this->msgInLang( $longContext, $lang, $s )->plain();
138 } elseif ( $shortContext ) {
139 $s = $this->msgInLang( $shortContext, $lang, "\n$s\n" )->plain();
140 }
141 }
142 return $s;
143 }
144
145 /**
146 * Get a bullet list of the errors as a Message object.
147 *
148 * All message parameters that were provided as strings will be escaped with wfEscapeWikiText.
149 * This is mostly a historical accident and often undesirable (T368821).
150 * - To avoid this behavior when producing the Status, pass MessageSpecifier objects to methods
151 * such as `$status->fatal()`, instead of separate key and params parameters.
152 * - To avoid this behavior when consuming the Status, use the `$status->getMessages()` method
153 * instead, and display each message separately (or combine then with `Message::listParams()`).
154 *
155 * $shortContext and $longContext can be used to wrap the error list in some text.
156 * $shortContext will be preferred when there is a single error; $longContext will be
157 * preferred when there are multiple ones. In either case, $1 will be replaced with
158 * the list of errors.
159 *
160 * $shortContext is assumed to use $1 as an inline parameter: if there is a single item,
161 * it will not be made into a list; if there are multiple items, newlines will be inserted
162 * around the list.
163 * $longContext is assumed to use $1 as a standalone parameter; it will always receive a list.
164 *
165 * If both parameters are missing, and there is only one error, no bullet will be added.
166 *
167 * @param StatusValue $status
168 * @param array $options An array of options, supporting the following keys:
169 * - 'shortContext' (string|false|null) A short enclosing context message name, to
170 * be used when there is a single error
171 * - 'longContext' (string|false|null) A long enclosing context message name, for a list
172 * - 'lang' (string|Language|StubUserLang|null) Language to use for processing messages
173 * - 'cleanCallback' (callable|null) A callback for sanitizing parameter values
174 *
175 * @return Message
176 */
177 public function getMessage( StatusValue $status, array $options = [] ) {
178 $shortContext = $options['shortContext'] ?? null;
179 $longContext = $options['longContext'] ?? null;
180 $lang = $options['lang'] ?? null;
181
182 $rawErrors = $status->getErrors();
183 if ( count( $rawErrors ) === 0 ) {
184 if ( $status->isOK() ) {
185 $errMsg = __METHOD__ . " called for a good result, this is incorrect\n";
186 } else {
187 $errMsg = __METHOD__ . ": Invalid result object: no error text but not OK\n";
188 }
189
190 $status->fatal(
191 'internalerror_info',
192 $errMsg
193 );
194
195 $this->logger->warning( $errMsg, [ 'exception' => new RuntimeException() ] );
196
197 $rawErrors = $status->getErrors(); // just added a fatal
198 }
199 if ( count( $rawErrors ) === 1 ) {
200 $s = $this->getErrorMessage( $rawErrors[0], $options );
201 if ( $shortContext ) {
202 $s = $this->msgInLang( $shortContext, $lang, $s );
203 } elseif ( $longContext ) {
204 $wrapper = new RawMessage( "* \$1\n" );
205 $wrapper->params( $s )->parse();
206 $s = $this->msgInLang( $longContext, $lang, $wrapper );
207 }
208 } else {
209 $msgs = $this->getErrorMessageArray( $rawErrors, $options );
210 $msgCount = count( $msgs );
211
212 $s = new RawMessage( '* $' . implode( "\n* \$", range( 1, $msgCount ) ) );
213 $s->params( $msgs )->parse();
214
215 if ( $longContext ) {
216 $s = $this->msgInLang( $longContext, $lang, $s );
217 } elseif ( $shortContext ) {
218 $wrapper = new RawMessage( "\n\$1\n", [ $s ] );
219 $wrapper->parse();
220 $s = $this->msgInLang( $shortContext, $lang, $wrapper );
221 }
222 }
223
224 return $s;
225 }
226
227 /**
228 * Try to convert the status to a PSR-3 friendly format. The output will be similar to
229 * getWikiText( false, false, 'en' ), but message parameters will be extracted into the
230 * context array with parameter names 'parameter1' etc. when possible.
231 *
232 * @return array A pair of (message, context) suitable for passing to a PSR-3 logger.
233 * @phan-return array{0:string,1:(int|float|string)[]}
234 */
235 public function getPsr3MessageAndContext( StatusValue $status ): array {
236 $options = [ 'lang' => 'en' ];
237 $errors = $status->getErrors();
238
239 if ( count( $errors ) === 1 ) {
240 // identical to getMessage( false, false, 'en' ) when there's just one error
241 $message = $this->getErrorMessage( $errors[0], [ 'lang' => 'en' ] );
242
243 if ( in_array( get_class( $message ), [ Message::class, ApiMessage::class ], true ) ) {
244 // Fall back to getWikiText for rawmessage, which is just a placeholder for non-translated text.
245 // Turning the entire message into a context parameter wouldn't be useful.
246 if ( $message->getKey() === 'rawmessage' ) {
247 return [ $this->getWikiText( $status, $options ), [] ];
248 }
249 // $1,$2... will be left as-is when no parameters are provided.
250 $text = $this->msgInLang( $message->getKey(), 'en' )->plain();
251 $params = $message->getParams();
252 } elseif ( $message instanceof RawMessage ) {
253 $text = $message->getTextOfRawMessage();
254 $params = $message->getParamsOfRawMessage();
255 } else {
256 // Unknown Message subclass, we can't be sure how it marks parameters. Fall back to getWikiText.
257 return [ $this->getWikiText( $status, $options ), [] ];
258 }
259
260 $context = [];
261 $i = 1;
262 foreach ( $params as $param ) {
263 if ( $param instanceof MessageParam ) {
264 $param = $param->getValue();
265 }
266 if ( is_int( $param ) || is_float( $param ) || is_string( $param ) ) {
267 $context["parameter$i"] = $param;
268 } else {
269 // Parameter is not of a safe type, fall back to getWikiText.
270 return [ $this->getWikiText( $status, $options ), [] ];
271 }
272
273 $text = str_replace( "\$$i", "{parameter$i}", $text );
274
275 $i++;
276 }
277
278 return [ $text, $context ];
279 }
280 // Parameters cannot be easily extracted, fall back to getWikiText,
281 return [ $this->getWikiText( $status, $options ), [] ];
282 }
283
284 /**
285 * Return the message for a single error
286 *
287 * The code string can be used a message key with per-language versions.
288 * If $error is an array, the "params" field is a list of parameters for the message.
289 *
290 * @param array|string $error Code string or (key: code string, params: string[]) map
291 * @param array $options
292 * @return Message
293 */
294 private function getErrorMessage( $error, array $options = [] ) {
295 $lang = $options['lang'] ?? null;
296
297 if ( is_array( $error ) ) {
298 if ( isset( $error['message'] ) && $error['message'] instanceof Message ) {
299 // Apply context from MessageLocalizer even if we have a Message object already
300 $msg = $this->msg( $error['message'] );
301 } elseif ( isset( $error['message'] ) && isset( $error['params'] ) ) {
302 $msg = $this->msg(
303 $error['message'],
304 array_map( static function ( $param ) {
305 return is_string( $param ) ? wfEscapeWikiText( $param ) : $param;
306 }, $this->cleanParams( $error['params'], $options ) )
307 );
308 } else {
309 $msgName = array_shift( $error );
310 $msg = $this->msg(
311 $msgName,
312 array_map( static function ( $param ) {
313 return is_string( $param ) ? wfEscapeWikiText( $param ) : $param;
314 }, $this->cleanParams( $error, $options ) )
315 );
316 }
317 } elseif ( is_string( $error ) ) {
318 $msg = $this->msg( $error );
319 } else {
320 throw new UnexpectedValueException( 'Got ' . get_class( $error ) . ' for key.' );
321 }
322
323 if ( $lang ) {
324 $msg->inLanguage( $lang );
325 }
326 return $msg;
327 }
328
329 /**
330 * Get the error message as HTML. This is done by parsing the wikitext error message
331 *
332 * All message parameters that were provided as strings will be escaped with wfEscapeWikiText.
333 * This is mostly a historical accident and often undesirable (T368821).
334 * - To avoid this behavior when producing the Status, pass MessageSpecifier objects to methods
335 * such as `$status->fatal()`, instead of separate key and params parameters.
336 * - To avoid this behavior when consuming the Status, use the `$status->getMessages()` method
337 * instead, and display each message separately (or combine then with `Message::listParams()`).
338 *
339 * @param StatusValue $status
340 * @param array $options An array of options, supporting the following keys:
341 * - 'shortContext' (string|false|null) A short enclosing context message name, to
342 * be used when there is a single error
343 * - 'longContext' (string|false|null) A long enclosing context message name, for a list
344 * - 'lang' (string|Language|StubUserLang|null) Language to use for processing messages
345 * - 'cleanCallback' (callable|null) A callback for sanitizing parameter values
346 *
347 * @return string
348 */
349 public function getHTML( StatusValue $status, array $options = [] ) {
350 $lang = $options['lang'] ?? null;
351
352 $text = $this->getWikiText( $status, $options );
353 $out = $this->messageCache->parse( $text, null, true, true, $lang );
354
355 return $out instanceof ParserOutput
356 ? $out->getText( [ 'enableSectionEditLinks' => false ] )
357 : $out;
358 }
359
360 /**
361 * Return an array with a Message object for each error.
362 *
363 * @param array $errors
364 * @param array $options
365 *
366 * @return Message[]
367 */
368 private function getErrorMessageArray( $errors, array $options = [] ) {
369 return array_map( function ( $e ) use ( $options ) {
370 return $this->getErrorMessage( $e, $options );
371 }, $errors );
372 }
373
374 /**
375 * @param string|MessageSpecifier $key
376 * @param string|string[] ...$params
377 * @return Message
378 */
379 private function msg( $key, ...$params ): Message {
380 return $this->messageLocalizer->msg( $key, ...$params );
381 }
382
383 /**
384 * @param string|MessageSpecifier $key
385 * @param string|Language|StubUserLang|null $lang
386 * @param mixed ...$params
387 * @return Message
388 */
389 private function msgInLang( $key, $lang, ...$params ): Message {
390 $msg = $this->msg( $key, ...$params );
391 if ( $lang ) {
392 $msg->inLanguage( $lang );
393 }
394 return $msg;
395 }
396 }