Do not insert page titles into querycache.qc_value
[lhc/web/wiklou.git] / includes / Status.php
1 <?php
2 /**
3 * Generic operation result.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * Generic operation result class
25 * Has warning/error list, boolean status and arbitrary value
26 *
27 * "Good" means the operation was completed with no warnings or errors.
28 *
29 * "OK" means the operation was partially or wholly completed.
30 *
31 * An operation which is not OK should have errors so that the user can be
32 * informed as to what went wrong. Calling the fatal() function sets an error
33 * message and simultaneously switches off the OK flag.
34 *
35 * The recommended pattern for Status objects is to return a Status object
36 * unconditionally, i.e. both on success and on failure -- so that the
37 * developer of the calling code is reminded that the function can fail, and
38 * so that a lack of error-handling will be explicit.
39 */
40 class Status extends StatusValue {
41 /** @var callable|false */
42 public $cleanCallback = false;
43
44 /**
45 * Succinct helper method to wrap a StatusValue
46 *
47 * This is is useful when formatting StatusValue objects:
48 * @code
49 * $this->getOutput()->addHtml( Status::wrap( $sv )->getHTML() );
50 * @endcode
51 *
52 * @param StatusValue|Status $sv
53 * @return Status
54 */
55 public static function wrap( $sv ) {
56 if ( $sv instanceof static ) {
57 return $sv;
58 }
59
60 $result = new static();
61 $result->ok =& $sv->ok;
62 $result->errors =& $sv->errors;
63 $result->value =& $sv->value;
64 $result->successCount =& $sv->successCount;
65 $result->failCount =& $sv->failCount;
66 $result->success =& $sv->success;
67
68 return $result;
69 }
70
71 /**
72 * Backwards compatibility logic
73 *
74 * @param string $name
75 * @return mixed
76 * @throws RuntimeException
77 */
78 function __get( $name ) {
79 if ( $name === 'ok' ) {
80 return $this->isOK();
81 }
82 if ( $name === 'errors' ) {
83 return $this->getErrors();
84 }
85
86 throw new RuntimeException( "Cannot get '$name' property." );
87 }
88
89 /**
90 * Change operation result
91 * Backwards compatibility logic
92 *
93 * @param string $name
94 * @param mixed $value
95 * @throws RuntimeException
96 */
97 function __set( $name, $value ) {
98 if ( $name === 'ok' ) {
99 $this->setOK( $value );
100 } elseif ( !property_exists( $this, $name ) ) {
101 // Caller is using undeclared ad-hoc properties
102 $this->$name = $value;
103 } else {
104 throw new RuntimeException( "Cannot set '$name' property." );
105 }
106 }
107
108 /**
109 * Splits this Status object into two new Status objects, one which contains only
110 * the error messages, and one that contains the warnings, only. The returned array is
111 * defined as:
112 * [
113 * 0 => object(Status) # The Status with error messages, only
114 * 1 => object(Status) # The Status with warning messages, only
115 * ]
116 *
117 * @return Status[]
118 * @suppress PhanUndeclaredProperty Status vs StatusValue
119 */
120 public function splitByErrorType() {
121 list( $errorsOnlyStatus, $warningsOnlyStatus ) = parent::splitByErrorType();
122 $errorsOnlyStatus->cleanCallback =
123 $warningsOnlyStatus->cleanCallback = $this->cleanCallback;
124
125 return [ $errorsOnlyStatus, $warningsOnlyStatus ];
126 }
127
128 /**
129 * Returns the wrapped StatusValue object
130 * @return StatusValue
131 * @since 1.27
132 */
133 public function getStatusValue() {
134 return $this;
135 }
136
137 /**
138 * @param array $params
139 * @return array
140 */
141 protected function cleanParams( array $params ) {
142 if ( !$this->cleanCallback ) {
143 return $params;
144 }
145 $cleanParams = [];
146 foreach ( $params as $i => $param ) {
147 $cleanParams[$i] = call_user_func( $this->cleanCallback, $param );
148 }
149 return $cleanParams;
150 }
151
152 /**
153 * @param string|Language|null|StubUserLang $lang Language to use for processing
154 * messages, or null to default to the user language.
155 * @return Language|StubUserLang
156 */
157 protected function languageFromParam( $lang ) {
158 if ( $lang === null ) {
159 return RequestContext::getMain()->getLanguage();
160 }
161 if ( $lang instanceof Language || $lang instanceof StubUserLang ) {
162 return $lang;
163 }
164 return Language::factory( $lang );
165 }
166
167 /**
168 * Get the error list as a wikitext formatted list
169 *
170 * @param string|bool $shortContext A short enclosing context message name, to
171 * be used when there is a single error
172 * @param string|bool $longContext A long enclosing context message name, for a list
173 * @param string|Language|null|StubUserLang $lang Language to use for processing messages
174 * @return string
175 */
176 public function getWikiText( $shortContext = false, $longContext = false, $lang = null ) {
177 $lang = $this->languageFromParam( $lang );
178
179 $rawErrors = $this->getErrors();
180 if ( count( $rawErrors ) === 0 ) {
181 if ( $this->isOK() ) {
182 $this->fatal( 'internalerror_info',
183 __METHOD__ . " called for a good result, this is incorrect\n" );
184 } else {
185 $this->fatal( 'internalerror_info',
186 __METHOD__ . ": Invalid result object: no error text but not OK\n" );
187 }
188 $rawErrors = $this->getErrors(); // just added a fatal
189 }
190 if ( count( $rawErrors ) === 1 ) {
191 $s = $this->getErrorMessage( $rawErrors[0], $lang )->plain();
192 if ( $shortContext ) {
193 $s = wfMessage( $shortContext, $s )->inLanguage( $lang )->plain();
194 } elseif ( $longContext ) {
195 $s = wfMessage( $longContext, "* $s\n" )->inLanguage( $lang )->plain();
196 }
197 } else {
198 $errors = $this->getErrorMessageArray( $rawErrors, $lang );
199 foreach ( $errors as &$error ) {
200 $error = $error->plain();
201 }
202 $s = '* ' . implode( "\n* ", $errors ) . "\n";
203 if ( $longContext ) {
204 $s = wfMessage( $longContext, $s )->inLanguage( $lang )->plain();
205 } elseif ( $shortContext ) {
206 $s = wfMessage( $shortContext, "\n$s\n" )->inLanguage( $lang )->plain();
207 }
208 }
209 return $s;
210 }
211
212 /**
213 * Get a bullet list of the errors as a Message object.
214 *
215 * $shortContext and $longContext can be used to wrap the error list in some text.
216 * $shortContext will be preferred when there is a single error; $longContext will be
217 * preferred when there are multiple ones. In either case, $1 will be replaced with
218 * the list of errors.
219 *
220 * $shortContext is assumed to use $1 as an inline parameter: if there is a single item,
221 * it will not be made into a list; if there are multiple items, newlines will be inserted
222 * around the list.
223 * $longContext is assumed to use $1 as a standalone parameter; it will always receive a list.
224 *
225 * If both parameters are missing, and there is only one error, no bullet will be added.
226 *
227 * @param string|string[]|bool $shortContext A message name or an array of message names.
228 * @param string|string[]|bool $longContext A message name or an array of message names.
229 * @param string|Language|null $lang Language to use for processing messages
230 * @return Message
231 */
232 public function getMessage( $shortContext = false, $longContext = false, $lang = null ) {
233 $lang = $this->languageFromParam( $lang );
234
235 $rawErrors = $this->getErrors();
236 if ( count( $rawErrors ) === 0 ) {
237 if ( $this->isOK() ) {
238 $this->fatal( 'internalerror_info',
239 __METHOD__ . " called for a good result, this is incorrect\n" );
240 } else {
241 $this->fatal( 'internalerror_info',
242 __METHOD__ . ": Invalid result object: no error text but not OK\n" );
243 }
244 $rawErrors = $this->getErrors(); // just added a fatal
245 }
246 if ( count( $rawErrors ) === 1 ) {
247 $s = $this->getErrorMessage( $rawErrors[0], $lang );
248 if ( $shortContext ) {
249 $s = wfMessage( $shortContext, $s )->inLanguage( $lang );
250 } elseif ( $longContext ) {
251 $wrapper = new RawMessage( "* \$1\n" );
252 $wrapper->params( $s )->parse();
253 $s = wfMessage( $longContext, $wrapper )->inLanguage( $lang );
254 }
255 } else {
256 $msgs = $this->getErrorMessageArray( $rawErrors, $lang );
257 $msgCount = count( $msgs );
258
259 $s = new RawMessage( '* $' . implode( "\n* \$", range( 1, $msgCount ) ) );
260 $s->params( $msgs )->parse();
261
262 if ( $longContext ) {
263 $s = wfMessage( $longContext, $s )->inLanguage( $lang );
264 } elseif ( $shortContext ) {
265 $wrapper = new RawMessage( "\n\$1\n", [ $s ] );
266 $wrapper->parse();
267 $s = wfMessage( $shortContext, $wrapper )->inLanguage( $lang );
268 }
269 }
270
271 return $s;
272 }
273
274 /**
275 * Return the message for a single error
276 *
277 * The code string can be used a message key with per-language versions.
278 * If $error is an array, the "params" field is a list of parameters for the message.
279 *
280 * @param array|string $error Code string or (key: code string, params: string[]) map
281 * @param string|Language|null $lang Language to use for processing messages
282 * @return Message
283 */
284 protected function getErrorMessage( $error, $lang = null ) {
285 if ( is_array( $error ) ) {
286 if ( isset( $error['message'] ) && $error['message'] instanceof Message ) {
287 $msg = $error['message'];
288 } elseif ( isset( $error['message'] ) && isset( $error['params'] ) ) {
289 $msg = wfMessage( $error['message'],
290 array_map( 'wfEscapeWikiText', $this->cleanParams( $error['params'] ) ) );
291 } else {
292 $msgName = array_shift( $error );
293 $msg = wfMessage( $msgName,
294 array_map( 'wfEscapeWikiText', $this->cleanParams( $error ) ) );
295 }
296 } elseif ( is_string( $error ) ) {
297 $msg = wfMessage( $error );
298 } else {
299 throw new UnexpectedValueException( 'Got ' . get_class( $error ) . ' for key.' );
300 }
301
302 $msg->inLanguage( $this->languageFromParam( $lang ) );
303 return $msg;
304 }
305
306 /**
307 * Get the error message as HTML. This is done by parsing the wikitext error message
308 * @param string|bool $shortContext A short enclosing context message name, to
309 * be used when there is a single error
310 * @param string|bool $longContext A long enclosing context message name, for a list
311 * @param string|Language|null $lang Language to use for processing messages
312 * @return string
313 */
314 public function getHTML( $shortContext = false, $longContext = false, $lang = null ) {
315 $lang = $this->languageFromParam( $lang );
316 $text = $this->getWikiText( $shortContext, $longContext, $lang );
317 $out = MessageCache::singleton()->parse( $text, null, true, true, $lang );
318 return $out instanceof ParserOutput
319 ? $out->getText( [ 'enableSectionEditLinks' => false ] )
320 : $out;
321 }
322
323 /**
324 * Return an array with a Message object for each error.
325 * @param array $errors
326 * @param string|Language|null $lang Language to use for processing messages
327 * @return Message[]
328 */
329 protected function getErrorMessageArray( $errors, $lang = null ) {
330 $lang = $this->languageFromParam( $lang );
331 return array_map( function ( $e ) use ( $lang ) {
332 return $this->getErrorMessage( $e, $lang );
333 }, $errors );
334 }
335
336 /**
337 * Get the list of errors (but not warnings)
338 *
339 * @return array A list in which each entry is an array with a message key as its first element.
340 * The remaining array elements are the message parameters.
341 * @deprecated since 1.25
342 */
343 public function getErrorsArray() {
344 return $this->getStatusArray( 'error' );
345 }
346
347 /**
348 * Get the list of warnings (but not errors)
349 *
350 * @return array A list in which each entry is an array with a message key as its first element.
351 * The remaining array elements are the message parameters.
352 * @deprecated since 1.25
353 */
354 public function getWarningsArray() {
355 return $this->getStatusArray( 'warning' );
356 }
357
358 /**
359 * Returns a list of status messages of the given type (or all if false)
360 *
361 * @note this handles RawMessage poorly
362 *
363 * @param string|bool $type
364 * @return array
365 */
366 protected function getStatusArray( $type = false ) {
367 $result = [];
368
369 foreach ( $this->getErrors() as $error ) {
370 if ( $type === false || $error['type'] === $type ) {
371 if ( $error['message'] instanceof MessageSpecifier ) {
372 $result[] = array_merge(
373 [ $error['message']->getKey() ],
374 $error['message']->getParams()
375 );
376 } elseif ( $error['params'] ) {
377 $result[] = array_merge( [ $error['message'] ], $error['params'] );
378 } else {
379 $result[] = [ $error['message'] ];
380 }
381 }
382 }
383
384 return $result;
385 }
386
387 /**
388 * Don't save the callback when serializing, because Closures can't be
389 * serialized and we're going to clear it in __wakeup anyway.
390 * @return array
391 */
392 function __sleep() {
393 $keys = array_keys( get_object_vars( $this ) );
394 return array_diff( $keys, [ 'cleanCallback' ] );
395 }
396
397 /**
398 * Sanitize the callback parameter on wakeup, to avoid arbitrary execution.
399 */
400 function __wakeup() {
401 $this->cleanCallback = false;
402 }
403 }