Merge "Separate select() parameter summary from detail"
[lhc/web/wiklou.git] / includes / api / ApiBase.php
1 <?php
2 /**
3 *
4 *
5 * Created on Sep 5, 2006
6 *
7 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26
27 /**
28 * This abstract class implements many basic API functions, and is the base of
29 * all API classes.
30 * The class functions are divided into several areas of functionality:
31 *
32 * Module parameters: Derived classes can define getAllowedParams() to specify
33 * which parameters to expect, how to parse and validate them.
34 *
35 * Profiling: various methods to allow keeping tabs on various tasks and their
36 * time costs
37 *
38 * Self-documentation: code to allow the API to document its own state
39 *
40 * @ingroup API
41 */
42 abstract class ApiBase extends ContextSource {
43 // These constants allow modules to specify exactly how to treat incoming parameters.
44
45 // Default value of the parameter
46 const PARAM_DFLT = 0;
47 // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
48 const PARAM_ISMULTI = 1;
49 // Can be either a string type (e.g.: 'integer') or an array of allowed values
50 const PARAM_TYPE = 2;
51 // Max value allowed for a parameter. Only applies if TYPE='integer'
52 const PARAM_MAX = 3;
53 // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
54 const PARAM_MAX2 = 4;
55 // Lowest value allowed for a parameter. Only applies if TYPE='integer'
56 const PARAM_MIN = 5;
57 // Boolean, do we allow the same value to be set more than once when ISMULTI=true
58 const PARAM_ALLOW_DUPLICATES = 6;
59 // Boolean, is the parameter deprecated (will show a warning)
60 const PARAM_DEPRECATED = 7;
61 /// @since 1.17
62 const PARAM_REQUIRED = 8; // Boolean, is the parameter required?
63 /// @since 1.17
64 // Boolean, if MIN/MAX are set, enforce (die) these?
65 // Only applies if TYPE='integer' Use with extreme caution
66 const PARAM_RANGE_ENFORCE = 9;
67
68 // Name of property group that is on the root element of the result,
69 // i.e. not part of a list
70 const PROP_ROOT = 'ROOT';
71 // Boolean, is the result multiple items? Defaults to true for query modules,
72 // to false for other modules
73 const PROP_LIST = 'LIST';
74 const PROP_TYPE = 0; // Type of the property, uses same format as PARAM_TYPE
75 // Boolean, can the property be not included in the result? Defaults to false
76 const PROP_NULLABLE = 1;
77
78 const LIMIT_BIG1 = 500; // Fast query, std user limit
79 const LIMIT_BIG2 = 5000; // Fast query, bot/sysop limit
80 const LIMIT_SML1 = 50; // Slow query, std user limit
81 const LIMIT_SML2 = 500; // Slow query, bot/sysop limit
82
83 /**
84 * getAllowedParams() flag: When set, the result could take longer to generate,
85 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
86 * @since 1.21
87 */
88 const GET_VALUES_FOR_HELP = 1;
89
90 /** @var ApiMain */
91 private $mMainModule;
92 /** @var string */
93 private $mModuleName, $mModulePrefix;
94 private $mSlaveDB = null;
95 private $mParamCache = array();
96
97 /**
98 * @param ApiMain $mainModule
99 * @param string $moduleName Name of this module
100 * @param string $modulePrefix Prefix to use for parameter names
101 */
102 public function __construct( ApiMain $mainModule, $moduleName, $modulePrefix = '' ) {
103 $this->mMainModule = $mainModule;
104 $this->mModuleName = $moduleName;
105 $this->mModulePrefix = $modulePrefix;
106
107 if ( !$this->isMain() ) {
108 $this->setContext( $mainModule->getContext() );
109 }
110 }
111
112 /*****************************************************************************
113 * ABSTRACT METHODS *
114 *****************************************************************************/
115
116 /**
117 * Evaluates the parameters, performs the requested query, and sets up
118 * the result. Concrete implementations of ApiBase must override this
119 * method to provide whatever functionality their module offers.
120 * Implementations must not produce any output on their own and are not
121 * expected to handle any errors.
122 *
123 * The execute() method will be invoked directly by ApiMain immediately
124 * before the result of the module is output. Aside from the
125 * constructor, implementations should assume that no other methods
126 * will be called externally on the module before the result is
127 * processed.
128 *
129 * The result data should be stored in the ApiResult object available
130 * through getResult().
131 */
132 abstract public function execute();
133
134 /**
135 * Returns a string that identifies the version of the extending class.
136 * Typically includes the class name, the svn revision, timestamp, and
137 * last author. Usually done with SVN's Id keyword
138 * @return string
139 * @deprecated since 1.21, version string is no longer supported
140 */
141 public function getVersion() {
142 wfDeprecated( __METHOD__, '1.21' );
143
144 return '';
145 }
146
147 /**
148 * Get the name of the module being executed by this instance
149 * @return string
150 */
151 public function getModuleName() {
152 return $this->mModuleName;
153 }
154
155 /**
156 * Get the module manager, or null if this module has no sub-modules
157 * @since 1.21
158 * @return ApiModuleManager
159 */
160 public function getModuleManager() {
161 return null;
162 }
163
164 /**
165 * Get parameter prefix (usually two letters or an empty string).
166 * @return string
167 */
168 public function getModulePrefix() {
169 return $this->mModulePrefix;
170 }
171
172 /**
173 * Get the name of the module as shown in the profiler log
174 *
175 * @param DatabaseBase|bool $db
176 *
177 * @return string
178 */
179 public function getModuleProfileName( $db = false ) {
180 if ( $db ) {
181 return 'API:' . $this->mModuleName . '-DB';
182 }
183
184 return 'API:' . $this->mModuleName;
185 }
186
187 /**
188 * Get the main module
189 * @return ApiMain
190 */
191 public function getMain() {
192 return $this->mMainModule;
193 }
194
195 /**
196 * Returns true if this module is the main module ($this === $this->mMainModule),
197 * false otherwise.
198 * @return bool
199 */
200 public function isMain() {
201 return $this === $this->mMainModule;
202 }
203
204 /**
205 * Get the result object
206 * @return ApiResult
207 */
208 public function getResult() {
209 // Main module has getResult() method overridden
210 // Safety - avoid infinite loop:
211 if ( $this->isMain() ) {
212 ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
213 }
214
215 return $this->getMain()->getResult();
216 }
217
218 /**
219 * Get the result data array (read-only)
220 * @return array
221 */
222 public function getResultData() {
223 return $this->getResult()->getData();
224 }
225
226 /**
227 * Set warning section for this module. Users should monitor this
228 * section to notice any changes in API. Multiple calls to this
229 * function will result in the warning messages being separated by
230 * newlines
231 * @param string $warning Warning message
232 */
233 public function setWarning( $warning ) {
234 $result = $this->getResult();
235 $data = $result->getData();
236 $moduleName = $this->getModuleName();
237 if ( isset( $data['warnings'][$moduleName] ) ) {
238 // Don't add duplicate warnings
239 $oldWarning = $data['warnings'][$moduleName]['*'];
240 $warnPos = strpos( $oldWarning, $warning );
241 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
242 if ( $warnPos !== false && ( $warnPos === 0 || $oldWarning[$warnPos - 1] === "\n" ) ) {
243 // Check if $warning is followed by "\n" or the end of the $oldWarning
244 $warnPos += strlen( $warning );
245 if ( strlen( $oldWarning ) <= $warnPos || $oldWarning[$warnPos] === "\n" ) {
246 return;
247 }
248 }
249 // If there is a warning already, append it to the existing one
250 $warning = "$oldWarning\n$warning";
251 }
252 $msg = array();
253 ApiResult::setContent( $msg, $warning );
254 $result->addValue( 'warnings', $moduleName,
255 $msg, ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
256 }
257
258 /**
259 * If the module may only be used with a certain format module,
260 * it should override this method to return an instance of that formatter.
261 * A value of null means the default format will be used.
262 * @return mixed Instance of a derived class of ApiFormatBase, or null
263 */
264 public function getCustomPrinter() {
265 return null;
266 }
267
268 /**
269 * Generates help message for this module, or false if there is no description
270 * @return string|bool
271 */
272 public function makeHelpMsg() {
273 static $lnPrfx = "\n ";
274
275 $msg = $this->getFinalDescription();
276
277 if ( $msg !== false ) {
278
279 if ( !is_array( $msg ) ) {
280 $msg = array(
281 $msg
282 );
283 }
284 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
285
286 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
287
288 if ( $this->isReadMode() ) {
289 $msg .= "\nThis module requires read rights";
290 }
291 if ( $this->isWriteMode() ) {
292 $msg .= "\nThis module requires write rights";
293 }
294 if ( $this->mustBePosted() ) {
295 $msg .= "\nThis module only accepts POST requests";
296 }
297 if ( $this->isReadMode() || $this->isWriteMode() ||
298 $this->mustBePosted()
299 ) {
300 $msg .= "\n";
301 }
302
303 // Parameters
304 $paramsMsg = $this->makeHelpMsgParameters();
305 if ( $paramsMsg !== false ) {
306 $msg .= "Parameters:\n$paramsMsg";
307 }
308
309 $examples = $this->getExamples();
310 if ( $examples ) {
311 if ( !is_array( $examples ) ) {
312 $examples = array(
313 $examples
314 );
315 }
316 $msg .= "Example" . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
317 foreach ( $examples as $k => $v ) {
318 if ( is_numeric( $k ) ) {
319 $msg .= " $v\n";
320 } else {
321 if ( is_array( $v ) ) {
322 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
323 } else {
324 $msgExample = " $v";
325 }
326 $msgExample .= ":";
327 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
328 }
329 }
330 }
331 }
332
333 return $msg;
334 }
335
336 /**
337 * @param string $item
338 * @return string
339 */
340 private function indentExampleText( $item ) {
341 return " " . $item;
342 }
343
344 /**
345 * @param string $prefix Text to split output items
346 * @param string $title What is being output
347 * @param string|array $input
348 * @return string
349 */
350 protected function makeHelpArrayToString( $prefix, $title, $input ) {
351 if ( $input === false ) {
352 return '';
353 }
354 if ( !is_array( $input ) ) {
355 $input = array( $input );
356 }
357
358 if ( count( $input ) > 0 ) {
359 if ( $title ) {
360 $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n ";
361 } else {
362 $msg = ' ';
363 }
364 $msg .= implode( $prefix, $input ) . "\n";
365
366 return $msg;
367 }
368
369 return '';
370 }
371
372 /**
373 * Generates the parameter descriptions for this module, to be displayed in the
374 * module's help.
375 * @return string|bool
376 */
377 public function makeHelpMsgParameters() {
378 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
379 if ( $params ) {
380
381 $paramsDescription = $this->getFinalParamDescription();
382 $msg = '';
383 $paramPrefix = "\n" . str_repeat( ' ', 24 );
384 $descWordwrap = "\n" . str_repeat( ' ', 28 );
385 foreach ( $params as $paramName => $paramSettings ) {
386 $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
387 if ( is_array( $desc ) ) {
388 $desc = implode( $paramPrefix, $desc );
389 }
390
391 //handle shorthand
392 if ( !is_array( $paramSettings ) ) {
393 $paramSettings = array(
394 self::PARAM_DFLT => $paramSettings,
395 );
396 }
397
398 //handle missing type
399 if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) {
400 $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] )
401 ? $paramSettings[ApiBase::PARAM_DFLT]
402 : null;
403 if ( is_bool( $dflt ) ) {
404 $paramSettings[ApiBase::PARAM_TYPE] = 'boolean';
405 } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
406 $paramSettings[ApiBase::PARAM_TYPE] = 'string';
407 } elseif ( is_int( $dflt ) ) {
408 $paramSettings[ApiBase::PARAM_TYPE] = 'integer';
409 }
410 }
411
412 if ( isset( $paramSettings[self::PARAM_DEPRECATED] )
413 && $paramSettings[self::PARAM_DEPRECATED]
414 ) {
415 $desc = "DEPRECATED! $desc";
416 }
417
418 if ( isset( $paramSettings[self::PARAM_REQUIRED] )
419 && $paramSettings[self::PARAM_REQUIRED]
420 ) {
421 $desc .= $paramPrefix . "This parameter is required";
422 }
423
424 $type = isset( $paramSettings[self::PARAM_TYPE] )
425 ? $paramSettings[self::PARAM_TYPE]
426 : null;
427 if ( isset( $type ) ) {
428 $hintPipeSeparated = true;
429 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
430 ? $paramSettings[self::PARAM_ISMULTI]
431 : false;
432 if ( $multi ) {
433 $prompt = 'Values (separate with \'|\'): ';
434 } else {
435 $prompt = 'One value: ';
436 }
437
438 if ( is_array( $type ) ) {
439 $choices = array();
440 $nothingPrompt = '';
441 foreach ( $type as $t ) {
442 if ( $t === '' ) {
443 $nothingPrompt = 'Can be empty, or ';
444 } else {
445 $choices[] = $t;
446 }
447 }
448 $desc .= $paramPrefix . $nothingPrompt . $prompt;
449 $choicesstring = implode( ', ', $choices );
450 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
451 $hintPipeSeparated = false;
452 } else {
453 switch ( $type ) {
454 case 'namespace':
455 // Special handling because namespaces are
456 // type-limited, yet they are not given
457 $desc .= $paramPrefix . $prompt;
458 $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
459 100, $descWordwrap );
460 $hintPipeSeparated = false;
461 break;
462 case 'limit':
463 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
464 if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
465 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
466 }
467 $desc .= ' allowed';
468 break;
469 case 'integer':
470 $s = $multi ? 's' : '';
471 $hasMin = isset( $paramSettings[self::PARAM_MIN] );
472 $hasMax = isset( $paramSettings[self::PARAM_MAX] );
473 if ( $hasMin || $hasMax ) {
474 if ( !$hasMax ) {
475 $intRangeStr = "The value$s must be no less than " .
476 "{$paramSettings[self::PARAM_MIN]}";
477 } elseif ( !$hasMin ) {
478 $intRangeStr = "The value$s must be no more than " .
479 "{$paramSettings[self::PARAM_MAX]}";
480 } else {
481 $intRangeStr = "The value$s must be between " .
482 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
483 }
484
485 $desc .= $paramPrefix . $intRangeStr;
486 }
487 break;
488 case 'upload':
489 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
490 break;
491 }
492 }
493
494 if ( $multi ) {
495 if ( $hintPipeSeparated ) {
496 $desc .= $paramPrefix . "Separate values with '|'";
497 }
498
499 $isArray = is_array( $type );
500 if ( !$isArray
501 || $isArray && count( $type ) > self::LIMIT_SML1
502 ) {
503 $desc .= $paramPrefix . "Maximum number of values " .
504 self::LIMIT_SML1 . " (" . self::LIMIT_SML2 . " for bots)";
505 }
506 }
507 }
508
509 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
510 if ( !is_null( $default ) && $default !== false ) {
511 $desc .= $paramPrefix . "Default: $default";
512 }
513
514 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
515 }
516
517 return $msg;
518 }
519
520 return false;
521 }
522
523 /**
524 * Returns the description string for this module
525 * @return string|array
526 */
527 protected function getDescription() {
528 return false;
529 }
530
531 /**
532 * Returns usage examples for this module. Return false if no examples are available.
533 * @return bool|string|array
534 */
535 protected function getExamples() {
536 return false;
537 }
538
539 /**
540 * Returns an array of allowed parameters (parameter name) => (default
541 * value) or (parameter name) => (array with PARAM_* constants as keys)
542 * Don't call this function directly: use getFinalParams() to allow
543 * hooks to modify parameters as needed.
544 *
545 * Some derived classes may choose to handle an integer $flags parameter
546 * in the overriding methods. Callers of this method can pass zero or
547 * more OR-ed flags like GET_VALUES_FOR_HELP.
548 *
549 * @return array|bool
550 */
551 protected function getAllowedParams( /* $flags = 0 */ ) {
552 // int $flags is not declared because it causes "Strict standards"
553 // warning. Most derived classes do not implement it.
554 return false;
555 }
556
557 /**
558 * Returns an array of parameter descriptions.
559 * Don't call this function directly: use getFinalParamDescription() to
560 * allow hooks to modify descriptions as needed.
561 * @return array|bool False on no parameter descriptions
562 */
563 protected function getParamDescription() {
564 return false;
565 }
566
567 /**
568 * Get final list of parameters, after hooks have had a chance to
569 * tweak it as needed.
570 *
571 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
572 * @return array|bool False on no parameters
573 * @since 1.21 $flags param added
574 */
575 public function getFinalParams( $flags = 0 ) {
576 $params = $this->getAllowedParams( $flags );
577 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
578
579 return $params;
580 }
581
582 /**
583 * Get final parameter descriptions, after hooks have had a chance to tweak it as
584 * needed.
585 *
586 * @return array|bool False on no parameter descriptions
587 */
588 public function getFinalParamDescription() {
589 $desc = $this->getParamDescription();
590 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
591
592 return $desc;
593 }
594
595 /**
596 * Returns possible properties in the result, grouped by the value of the prop parameter
597 * that shows them.
598 *
599 * Properties that are shown always are in a group with empty string as a key.
600 * Properties that can be shown by several values of prop are included multiple times.
601 * If some properties are part of a list and some are on the root object (see ApiQueryQueryPage),
602 * those on the root object are under the key PROP_ROOT.
603 * The array can also contain a boolean under the key PROP_LIST,
604 * indicating whether the result is a list.
605 *
606 * Don't call this function directly: use getFinalResultProperties() to
607 * allow hooks to modify descriptions as needed.
608 *
609 * @return array|bool False on no properties
610 */
611 protected function getResultProperties() {
612 return false;
613 }
614
615 /**
616 * Get final possible result properties, after hooks have had a chance to tweak it as
617 * needed.
618 *
619 * @return array
620 */
621 public function getFinalResultProperties() {
622 $properties = $this->getResultProperties();
623 wfRunHooks( 'APIGetResultProperties', array( $this, &$properties ) );
624
625 return $properties;
626 }
627
628 /**
629 * Add token properties to the array used by getResultProperties,
630 * based on a token functions mapping.
631 * @param array $props
632 * @param array $tokenFunctions
633 */
634 protected static function addTokenProperties( &$props, $tokenFunctions ) {
635 foreach ( array_keys( $tokenFunctions ) as $token ) {
636 $props[''][$token . 'token'] = array(
637 ApiBase::PROP_TYPE => 'string',
638 ApiBase::PROP_NULLABLE => true
639 );
640 }
641 }
642
643 /**
644 * Get final module description, after hooks have had a chance to tweak it as
645 * needed.
646 *
647 * @return array|bool False on no parameters
648 */
649 public function getFinalDescription() {
650 $desc = $this->getDescription();
651 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
652
653 return $desc;
654 }
655
656 /**
657 * This method mangles parameter name based on the prefix supplied to the constructor.
658 * Override this method to change parameter name during runtime
659 * @param string $paramName Parameter name
660 * @return string Prefixed parameter name
661 */
662 public function encodeParamName( $paramName ) {
663 return $this->mModulePrefix . $paramName;
664 }
665
666 /**
667 * Using getAllowedParams(), this function makes an array of the values
668 * provided by the user, with key being the name of the variable, and
669 * value - validated value from user or default. limits will not be
670 * parsed if $parseLimit is set to false; use this when the max
671 * limit is not definitive yet, e.g. when getting revisions.
672 * @param bool $parseLimit True by default
673 * @return array
674 */
675 public function extractRequestParams( $parseLimit = true ) {
676 // Cache parameters, for performance and to avoid bug 24564.
677 if ( !isset( $this->mParamCache[$parseLimit] ) ) {
678 $params = $this->getFinalParams();
679 $results = array();
680
681 if ( $params ) { // getFinalParams() can return false
682 foreach ( $params as $paramName => $paramSettings ) {
683 $results[$paramName] = $this->getParameterFromSettings(
684 $paramName, $paramSettings, $parseLimit );
685 }
686 }
687 $this->mParamCache[$parseLimit] = $results;
688 }
689
690 return $this->mParamCache[$parseLimit];
691 }
692
693 /**
694 * Get a value for the given parameter
695 * @param string $paramName Parameter name
696 * @param bool $parseLimit See extractRequestParams()
697 * @return mixed Parameter value
698 */
699 protected function getParameter( $paramName, $parseLimit = true ) {
700 $params = $this->getFinalParams();
701 $paramSettings = $params[$paramName];
702
703 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
704 }
705
706 /**
707 * Die if none or more than one of a certain set of parameters is set and not false.
708 *
709 * Call getRequireOnlyOneParameterErrorMessages() to get a list of possible errors.
710 *
711 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
712 * @param string $required,... Names of parameters of which exactly one must be set
713 */
714 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
715 $required = func_get_args();
716 array_shift( $required );
717 $p = $this->getModulePrefix();
718
719 $intersection = array_intersect( array_keys( array_filter( $params,
720 array( $this, "parameterNotEmpty" ) ) ), $required );
721
722 if ( count( $intersection ) > 1 ) {
723 $this->dieUsage(
724 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
725 'invalidparammix' );
726 } elseif ( count( $intersection ) == 0 ) {
727 $this->dieUsage(
728 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
729 'missingparam'
730 );
731 }
732 }
733
734 /**
735 * Generates the possible errors requireOnlyOneParameter() can die with
736 *
737 * @param array $params
738 * @return array
739 */
740 public function getRequireOnlyOneParameterErrorMessages( $params ) {
741 $p = $this->getModulePrefix();
742 $params = implode( ", {$p}", $params );
743
744 return array(
745 array(
746 'code' => "{$p}missingparam",
747 'info' => "One of the parameters {$p}{$params} is required"
748 ),
749 array(
750 'code' => "{$p}invalidparammix",
751 'info' => "The parameters {$p}{$params} can not be used together"
752 )
753 );
754 }
755
756 /**
757 * Die if more than one of a certain set of parameters is set and not false.
758 *
759 * Call getRequireMaxOneParameterErrorMessages() to get a list of possible errors.
760 *
761 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
762 * @param string $required,... Names of parameters of which at most one must be set
763 */
764 public function requireMaxOneParameter( $params, $required /*...*/ ) {
765 $required = func_get_args();
766 array_shift( $required );
767 $p = $this->getModulePrefix();
768
769 $intersection = array_intersect( array_keys( array_filter( $params,
770 array( $this, "parameterNotEmpty" ) ) ), $required );
771
772 if ( count( $intersection ) > 1 ) {
773 $this->dieUsage(
774 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
775 'invalidparammix'
776 );
777 }
778 }
779
780 /**
781 * Generates the possible error requireMaxOneParameter() can die with
782 *
783 * @param array $params
784 * @return array
785 */
786 public function getRequireMaxOneParameterErrorMessages( $params ) {
787 $p = $this->getModulePrefix();
788 $params = implode( ", {$p}", $params );
789
790 return array(
791 array(
792 'code' => "{$p}invalidparammix",
793 'info' => "The parameters {$p}{$params} can not be used together"
794 )
795 );
796 }
797
798 /**
799 * Die if none of a certain set of parameters is set and not false.
800 *
801 * Call getRequireAtLeastOneParameterErrorMessages() to get a list of possible errors.
802 *
803 * @since 1.23
804 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
805 * @param string $required,... Names of parameters of which at least one must be set
806 */
807 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
808 $required = func_get_args();
809 array_shift( $required );
810 $p = $this->getModulePrefix();
811
812 $intersection = array_intersect(
813 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
814 $required
815 );
816
817 if ( count( $intersection ) == 0 ) {
818 $this->dieUsage( "At least one of the parameters {$p}" .
819 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
820 }
821 }
822
823 /**
824 * Generates the possible errors requireAtLeastOneParameter() can die with
825 *
826 * @since 1.23
827 * @param array $params Array of parameter key names
828 * @return array
829 */
830 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
831 $p = $this->getModulePrefix();
832 $params = implode( ", {$p}", $params );
833
834 return array(
835 array(
836 'code' => "{$p}missingparam",
837 'info' => "At least one of the parameters {$p}{$params} is required",
838 ),
839 );
840 }
841
842 /**
843 * Get a WikiPage object from a title or pageid param, if possible.
844 * Can die, if no param is set or if the title or page id is not valid.
845 *
846 * Call getTitleOrPageIdErrorMessage() to get a list of possible errors.
847 *
848 * @param array $params
849 * @param bool|string $load Whether load the object's state from the database:
850 * - false: don't load (if the pageid is given, it will still be loaded)
851 * - 'fromdb': load from a slave database
852 * - 'fromdbmaster': load from the master database
853 * @return WikiPage
854 */
855 public function getTitleOrPageId( $params, $load = false ) {
856 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
857
858 $pageObj = null;
859 if ( isset( $params['title'] ) ) {
860 $titleObj = Title::newFromText( $params['title'] );
861 if ( !$titleObj || $titleObj->isExternal() ) {
862 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
863 }
864 if ( !$titleObj->canExist() ) {
865 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
866 }
867 $pageObj = WikiPage::factory( $titleObj );
868 if ( $load !== false ) {
869 $pageObj->loadPageData( $load );
870 }
871 } elseif ( isset( $params['pageid'] ) ) {
872 if ( $load === false ) {
873 $load = 'fromdb';
874 }
875 $pageObj = WikiPage::newFromID( $params['pageid'], $load );
876 if ( !$pageObj ) {
877 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
878 }
879 }
880
881 return $pageObj;
882 }
883
884 /**
885 * Generates the possible error getTitleOrPageId() can die with
886 *
887 * @return array
888 */
889 public function getTitleOrPageIdErrorMessage() {
890 return array_merge(
891 $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ),
892 array(
893 array( 'invalidtitle', 'title' ),
894 array( 'nosuchpageid', 'pageid' ),
895 array( 'code' => 'pagecannotexist', 'info' => "Namespace doesn't allow actual pages" ),
896 )
897 );
898 }
899
900 /**
901 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
902 *
903 * @param object $x Parameter to check is not null/false
904 * @return bool
905 */
906 private function parameterNotEmpty( $x ) {
907 return !is_null( $x ) && $x !== false;
908 }
909
910 /**
911 * Return true if we're to watch the page, false if not, null if no change.
912 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
913 * @param Title $titleObj The page under consideration
914 * @param string $userOption The user option to consider when $watchlist=preferences.
915 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
916 * @return bool
917 */
918 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
919
920 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem::IGNORE_USER_RIGHTS );
921
922 switch ( $watchlist ) {
923 case 'watch':
924 return true;
925
926 case 'unwatch':
927 return false;
928
929 case 'preferences':
930 # If the user is already watching, don't bother checking
931 if ( $userWatching ) {
932 return true;
933 }
934 # If no user option was passed, use watchdefault and watchcreations
935 if ( is_null( $userOption ) ) {
936 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
937 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
938 }
939
940 # Watch the article based on the user preference
941 return $this->getUser()->getBoolOption( $userOption );
942
943 case 'nochange':
944 return $userWatching;
945
946 default:
947 return $userWatching;
948 }
949 }
950
951 /**
952 * Set a watch (or unwatch) based the based on a watchlist parameter.
953 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
954 * @param Title $titleObj The article's title to change
955 * @param string $userOption The user option to consider when $watch=preferences
956 */
957 protected function setWatch( $watch, $titleObj, $userOption = null ) {
958 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
959 if ( $value === null ) {
960 return;
961 }
962
963 WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
964 }
965
966 /**
967 * Using the settings determine the value for the given parameter
968 *
969 * @param string $paramName Parameter name
970 * @param array|mixed $paramSettings Default value or an array of settings
971 * using PARAM_* constants.
972 * @param bool $parseLimit Parse limit?
973 * @return mixed Parameter value
974 */
975 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
976 // Some classes may decide to change parameter names
977 $encParamName = $this->encodeParamName( $paramName );
978
979 if ( !is_array( $paramSettings ) ) {
980 $default = $paramSettings;
981 $multi = false;
982 $type = gettype( $paramSettings );
983 $dupes = false;
984 $deprecated = false;
985 $required = false;
986 } else {
987 $default = isset( $paramSettings[self::PARAM_DFLT] )
988 ? $paramSettings[self::PARAM_DFLT]
989 : null;
990 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
991 ? $paramSettings[self::PARAM_ISMULTI]
992 : false;
993 $type = isset( $paramSettings[self::PARAM_TYPE] )
994 ? $paramSettings[self::PARAM_TYPE]
995 : null;
996 $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] )
997 ? $paramSettings[self::PARAM_ALLOW_DUPLICATES]
998 : false;
999 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] )
1000 ? $paramSettings[self::PARAM_DEPRECATED]
1001 : false;
1002 $required = isset( $paramSettings[self::PARAM_REQUIRED] )
1003 ? $paramSettings[self::PARAM_REQUIRED]
1004 : false;
1005
1006 // When type is not given, and no choices, the type is the same as $default
1007 if ( !isset( $type ) ) {
1008 if ( isset( $default ) ) {
1009 $type = gettype( $default );
1010 } else {
1011 $type = 'NULL'; // allow everything
1012 }
1013 }
1014 }
1015
1016 if ( $type == 'boolean' ) {
1017 if ( isset( $default ) && $default !== false ) {
1018 // Having a default value of anything other than 'false' is not allowed
1019 ApiBase::dieDebug(
1020 __METHOD__,
1021 "Boolean param $encParamName's default is set to '$default'. " .
1022 "Boolean parameters must default to false."
1023 );
1024 }
1025
1026 $value = $this->getMain()->getCheck( $encParamName );
1027 } elseif ( $type == 'upload' ) {
1028 if ( isset( $default ) ) {
1029 // Having a default value is not allowed
1030 ApiBase::dieDebug(
1031 __METHOD__,
1032 "File upload param $encParamName's default is set to " .
1033 "'$default'. File upload parameters may not have a default." );
1034 }
1035 if ( $multi ) {
1036 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1037 }
1038 $value = $this->getMain()->getUpload( $encParamName );
1039 if ( !$value->exists() ) {
1040 // This will get the value without trying to normalize it
1041 // (because trying to normalize a large binary file
1042 // accidentally uploaded as a field fails spectacularly)
1043 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1044 if ( $value !== null ) {
1045 $this->dieUsage(
1046 "File upload param $encParamName is not a file upload; " .
1047 "be sure to use multipart/form-data for your POST and include " .
1048 "a filename in the Content-Disposition header.",
1049 "badupload_{$encParamName}"
1050 );
1051 }
1052 }
1053 } else {
1054 $value = $this->getMain()->getVal( $encParamName, $default );
1055
1056 if ( isset( $value ) && $type == 'namespace' ) {
1057 $type = MWNamespace::getValidNamespaces();
1058 }
1059 }
1060
1061 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
1062 $value = $this->parseMultiValue(
1063 $encParamName,
1064 $value,
1065 $multi,
1066 is_array( $type ) ? $type : null
1067 );
1068 }
1069
1070 // More validation only when choices were not given
1071 // choices were validated in parseMultiValue()
1072 if ( isset( $value ) ) {
1073 if ( !is_array( $type ) ) {
1074 switch ( $type ) {
1075 case 'NULL': // nothing to do
1076 break;
1077 case 'string':
1078 if ( $required && $value === '' ) {
1079 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1080 }
1081 break;
1082 case 'integer': // Force everything using intval() and optionally validate limits
1083 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
1084 $max = isset( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
1085 $enforceLimits = isset( $paramSettings[self::PARAM_RANGE_ENFORCE] )
1086 ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
1087
1088 if ( is_array( $value ) ) {
1089 $value = array_map( 'intval', $value );
1090 if ( !is_null( $min ) || !is_null( $max ) ) {
1091 foreach ( $value as &$v ) {
1092 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1093 }
1094 }
1095 } else {
1096 $value = intval( $value );
1097 if ( !is_null( $min ) || !is_null( $max ) ) {
1098 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1099 }
1100 }
1101 break;
1102 case 'limit':
1103 if ( !$parseLimit ) {
1104 // Don't do any validation whatsoever
1105 break;
1106 }
1107 if ( !isset( $paramSettings[self::PARAM_MAX] )
1108 || !isset( $paramSettings[self::PARAM_MAX2] )
1109 ) {
1110 ApiBase::dieDebug(
1111 __METHOD__,
1112 "MAX1 or MAX2 are not defined for the limit $encParamName"
1113 );
1114 }
1115 if ( $multi ) {
1116 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1117 }
1118 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
1119 if ( $value == 'max' ) {
1120 $value = $this->getMain()->canApiHighLimits()
1121 ? $paramSettings[self::PARAM_MAX2]
1122 : $paramSettings[self::PARAM_MAX];
1123 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
1124 } else {
1125 $value = intval( $value );
1126 $this->validateLimit(
1127 $paramName,
1128 $value,
1129 $min,
1130 $paramSettings[self::PARAM_MAX],
1131 $paramSettings[self::PARAM_MAX2]
1132 );
1133 }
1134 break;
1135 case 'boolean':
1136 if ( $multi ) {
1137 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1138 }
1139 break;
1140 case 'timestamp':
1141 if ( is_array( $value ) ) {
1142 foreach ( $value as $key => $val ) {
1143 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1144 }
1145 } else {
1146 $value = $this->validateTimestamp( $value, $encParamName );
1147 }
1148 break;
1149 case 'user':
1150 if ( is_array( $value ) ) {
1151 foreach ( $value as $key => $val ) {
1152 $value[$key] = $this->validateUser( $val, $encParamName );
1153 }
1154 } else {
1155 $value = $this->validateUser( $value, $encParamName );
1156 }
1157 break;
1158 case 'upload': // nothing to do
1159 break;
1160 default:
1161 ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
1162 }
1163 }
1164
1165 // Throw out duplicates if requested
1166 if ( !$dupes && is_array( $value ) ) {
1167 $value = array_unique( $value );
1168 }
1169
1170 // Set a warning if a deprecated parameter has been passed
1171 if ( $deprecated && $value !== false ) {
1172 $this->setWarning( "The $encParamName parameter has been deprecated." );
1173 }
1174 } elseif ( $required ) {
1175 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1176 }
1177
1178 return $value;
1179 }
1180
1181 /**
1182 * Return an array of values that were given in a 'a|b|c' notation,
1183 * after it optionally validates them against the list allowed values.
1184 *
1185 * @param string $valueName The name of the parameter (for error
1186 * reporting)
1187 * @param mixed $value The value being parsed
1188 * @param bool $allowMultiple Can $value contain more than one value
1189 * separated by '|'?
1190 * @param string[]|null $allowedValues An array of values to check against. If
1191 * null, all values are accepted.
1192 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1193 */
1194 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1195 if ( trim( $value ) === '' && $allowMultiple ) {
1196 return array();
1197 }
1198
1199 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1200 // because it unstubs $wgUser
1201 $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 );
1202 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits()
1203 ? self::LIMIT_SML2
1204 : self::LIMIT_SML1;
1205
1206 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
1207 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1208 "the limit is $sizeLimit" );
1209 }
1210
1211 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1212 // Bug 33482 - Allow entries with | in them for non-multiple values
1213 if ( in_array( $value, $allowedValues, true ) ) {
1214 return $value;
1215 }
1216
1217 $possibleValues = is_array( $allowedValues )
1218 ? "of '" . implode( "', '", $allowedValues ) . "'"
1219 : '';
1220 $this->dieUsage(
1221 "Only one $possibleValues is allowed for parameter '$valueName'",
1222 "multival_$valueName"
1223 );
1224 }
1225
1226 if ( is_array( $allowedValues ) ) {
1227 // Check for unknown values
1228 $unknown = array_diff( $valuesList, $allowedValues );
1229 if ( count( $unknown ) ) {
1230 if ( $allowMultiple ) {
1231 $s = count( $unknown ) > 1 ? 's' : '';
1232 $vals = implode( ", ", $unknown );
1233 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1234 } else {
1235 $this->dieUsage(
1236 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1237 "unknown_$valueName"
1238 );
1239 }
1240 }
1241 // Now throw them out
1242 $valuesList = array_intersect( $valuesList, $allowedValues );
1243 }
1244
1245 return $allowMultiple ? $valuesList : $valuesList[0];
1246 }
1247
1248 /**
1249 * Validate the value against the minimum and user/bot maximum limits.
1250 * Prints usage info on failure.
1251 * @param string $paramName Parameter name
1252 * @param int $value Parameter value
1253 * @param int|null $min Minimum value
1254 * @param int|null $max Maximum value for users
1255 * @param int $botMax Maximum value for sysops/bots
1256 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1257 */
1258 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1259 if ( !is_null( $min ) && $value < $min ) {
1260
1261 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1262 $this->warnOrDie( $msg, $enforceLimits );
1263 $value = $min;
1264 }
1265
1266 // Minimum is always validated, whereas maximum is checked only if not
1267 // running in internal call mode
1268 if ( $this->getMain()->isInternalMode() ) {
1269 return;
1270 }
1271
1272 // Optimization: do not check user's bot status unless really needed -- skips db query
1273 // assumes $botMax >= $max
1274 if ( !is_null( $max ) && $value > $max ) {
1275 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1276 if ( $value > $botMax ) {
1277 $msg = $this->encodeParamName( $paramName ) .
1278 " may not be over $botMax (set to $value) for bots or sysops";
1279 $this->warnOrDie( $msg, $enforceLimits );
1280 $value = $botMax;
1281 }
1282 } else {
1283 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1284 $this->warnOrDie( $msg, $enforceLimits );
1285 $value = $max;
1286 }
1287 }
1288 }
1289
1290 /**
1291 * Validate and normalize of parameters of type 'timestamp'
1292 * @param string $value Parameter value
1293 * @param string $encParamName Parameter name
1294 * @return string Validated and normalized parameter
1295 */
1296 function validateTimestamp( $value, $encParamName ) {
1297 $unixTimestamp = wfTimestamp( TS_UNIX, $value );
1298 if ( $unixTimestamp === false ) {
1299 $this->dieUsage(
1300 "Invalid value '$value' for timestamp parameter $encParamName",
1301 "badtimestamp_{$encParamName}"
1302 );
1303 }
1304
1305 return wfTimestamp( TS_MW, $unixTimestamp );
1306 }
1307
1308 /**
1309 * Validate and normalize of parameters of type 'user'
1310 * @param string $value Parameter value
1311 * @param string $encParamName Parameter name
1312 * @return string Validated and normalized parameter
1313 */
1314 private function validateUser( $value, $encParamName ) {
1315 $title = Title::makeTitleSafe( NS_USER, $value );
1316 if ( $title === null ) {
1317 $this->dieUsage(
1318 "Invalid value '$value' for user parameter $encParamName",
1319 "baduser_{$encParamName}"
1320 );
1321 }
1322
1323 return $title->getText();
1324 }
1325
1326 /**
1327 * Adds a warning to the output, else dies
1328 *
1329 * @param string $msg Message to show as a warning, or error message if dying
1330 * @param bool $enforceLimits Whether this is an enforce (die)
1331 */
1332 private function warnOrDie( $msg, $enforceLimits = false ) {
1333 if ( $enforceLimits ) {
1334 $this->dieUsage( $msg, 'integeroutofrange' );
1335 }
1336
1337 $this->setWarning( $msg );
1338 }
1339
1340 /**
1341 * Truncate an array to a certain length.
1342 * @param array $arr Array to truncate
1343 * @param int $limit Maximum length
1344 * @return bool True if the array was truncated, false otherwise
1345 */
1346 public static function truncateArray( &$arr, $limit ) {
1347 $modified = false;
1348 while ( count( $arr ) > $limit ) {
1349 array_pop( $arr );
1350 $modified = true;
1351 }
1352
1353 return $modified;
1354 }
1355
1356 /**
1357 * Throw a UsageException, which will (if uncaught) call the main module's
1358 * error handler and die with an error message.
1359 *
1360 * @param string $description One-line human-readable description of the
1361 * error condition, e.g., "The API requires a valid action parameter"
1362 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1363 * automated identification of the error, e.g., 'unknown_action'
1364 * @param int $httpRespCode HTTP response code
1365 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1366 * @throws UsageException
1367 */
1368 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1369 Profiler::instance()->close();
1370 throw new UsageException(
1371 $description,
1372 $this->encodeParamName( $errorCode ),
1373 $httpRespCode,
1374 $extradata
1375 );
1376 }
1377
1378 /**
1379 * Get error (as code, string) from a Status object.
1380 *
1381 * @since 1.23
1382 * @param Status $status
1383 * @return array Array of code and error string
1384 */
1385 public function getErrorFromStatus( $status ) {
1386 if ( $status->isGood() ) {
1387 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1388 }
1389
1390 $errors = $status->getErrorsArray();
1391 if ( !$errors ) {
1392 // No errors? Assume the warnings should be treated as errors
1393 $errors = $status->getWarningsArray();
1394 }
1395 if ( !$errors ) {
1396 // Still no errors? Punt
1397 $errors = array( array( 'unknownerror-nocode' ) );
1398 }
1399
1400 // Cannot use dieUsageMsg() because extensions might return custom
1401 // error messages.
1402 if ( $errors[0] instanceof Message ) {
1403 $msg = $errors[0];
1404 $code = $msg->getKey();
1405 } else {
1406 $code = array_shift( $errors[0] );
1407 $msg = wfMessage( $code, $errors[0] );
1408 }
1409 if ( isset( ApiBase::$messageMap[$code] ) ) {
1410 // Translate message to code, for backwards compatability
1411 $code = ApiBase::$messageMap[$code]['code'];
1412 }
1413
1414 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1415 }
1416
1417 /**
1418 * Throw a UsageException based on the errors in the Status object.
1419 *
1420 * @since 1.22
1421 * @param Status $status
1422 * @throws MWException
1423 */
1424 public function dieStatus( $status ) {
1425
1426 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1427 $this->dieUsage( $msg, $code );
1428 }
1429
1430 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1431 /**
1432 * Array that maps message keys to error messages. $1 and friends are replaced.
1433 */
1434 public static $messageMap = array(
1435 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1436 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1437 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1438
1439 // Messages from Title::getUserPermissionsErrors()
1440 'ns-specialprotected' => array(
1441 'code' => 'unsupportednamespace',
1442 'info' => "Pages in the Special namespace can't be edited"
1443 ),
1444 'protectedinterface' => array(
1445 'code' => 'protectednamespace-interface',
1446 'info' => "You're not allowed to edit interface messages"
1447 ),
1448 'namespaceprotected' => array(
1449 'code' => 'protectednamespace',
1450 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1451 ),
1452 'customcssprotected' => array(
1453 'code' => 'customcssprotected',
1454 'info' => "You're not allowed to edit custom CSS pages"
1455 ),
1456 'customjsprotected' => array(
1457 'code' => 'customjsprotected',
1458 'info' => "You're not allowed to edit custom JavaScript pages"
1459 ),
1460 'cascadeprotected' => array(
1461 'code' => 'cascadeprotected',
1462 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1463 ),
1464 'protectedpagetext' => array(
1465 'code' => 'protectedpage',
1466 'info' => "The \"\$1\" right is required to edit this page"
1467 ),
1468 'protect-cantedit' => array(
1469 'code' => 'cantedit',
1470 'info' => "You can't protect this page because you can't edit it"
1471 ),
1472 'badaccess-group0' => array(
1473 'code' => 'permissiondenied',
1474 'info' => "Permission denied"
1475 ), // Generic permission denied message
1476 'badaccess-groups' => array(
1477 'code' => 'permissiondenied',
1478 'info' => "Permission denied"
1479 ),
1480 'titleprotected' => array(
1481 'code' => 'protectedtitle',
1482 'info' => "This title has been protected from creation"
1483 ),
1484 'nocreate-loggedin' => array(
1485 'code' => 'cantcreate',
1486 'info' => "You don't have permission to create new pages"
1487 ),
1488 'nocreatetext' => array(
1489 'code' => 'cantcreate-anon',
1490 'info' => "Anonymous users can't create new pages"
1491 ),
1492 'movenologintext' => array(
1493 'code' => 'cantmove-anon',
1494 'info' => "Anonymous users can't move pages"
1495 ),
1496 'movenotallowed' => array(
1497 'code' => 'cantmove',
1498 'info' => "You don't have permission to move pages"
1499 ),
1500 'confirmedittext' => array(
1501 'code' => 'confirmemail',
1502 'info' => "You must confirm your email address before you can edit"
1503 ),
1504 'blockedtext' => array(
1505 'code' => 'blocked',
1506 'info' => "You have been blocked from editing"
1507 ),
1508 'autoblockedtext' => array(
1509 'code' => 'autoblocked',
1510 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1511 ),
1512
1513 // Miscellaneous interface messages
1514 'actionthrottledtext' => array(
1515 'code' => 'ratelimited',
1516 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1517 ),
1518 'alreadyrolled' => array(
1519 'code' => 'alreadyrolled',
1520 'info' => "The page you tried to rollback was already rolled back"
1521 ),
1522 'cantrollback' => array(
1523 'code' => 'onlyauthor',
1524 'info' => "The page you tried to rollback only has one author"
1525 ),
1526 'readonlytext' => array(
1527 'code' => 'readonly',
1528 'info' => "The wiki is currently in read-only mode"
1529 ),
1530 'sessionfailure' => array(
1531 'code' => 'badtoken',
1532 'info' => "Invalid token" ),
1533 'cannotdelete' => array(
1534 'code' => 'cantdelete',
1535 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1536 ),
1537 'notanarticle' => array(
1538 'code' => 'missingtitle',
1539 'info' => "The page you requested doesn't exist"
1540 ),
1541 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1542 ),
1543 'immobile_namespace' => array(
1544 'code' => 'immobilenamespace',
1545 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1546 ),
1547 'articleexists' => array(
1548 'code' => 'articleexists',
1549 'info' => "The destination article already exists and is not a redirect to the source article"
1550 ),
1551 'protectedpage' => array(
1552 'code' => 'protectedpage',
1553 'info' => "You don't have permission to perform this move"
1554 ),
1555 'hookaborted' => array(
1556 'code' => 'hookaborted',
1557 'info' => "The modification you tried to make was aborted by an extension hook"
1558 ),
1559 'cantmove-titleprotected' => array(
1560 'code' => 'protectedtitle',
1561 'info' => "The destination article has been protected from creation"
1562 ),
1563 'imagenocrossnamespace' => array(
1564 'code' => 'nonfilenamespace',
1565 'info' => "Can't move a file to a non-file namespace"
1566 ),
1567 'imagetypemismatch' => array(
1568 'code' => 'filetypemismatch',
1569 'info' => "The new file extension doesn't match its type"
1570 ),
1571 // 'badarticleerror' => shouldn't happen
1572 // 'badtitletext' => shouldn't happen
1573 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1574 'range_block_disabled' => array(
1575 'code' => 'rangedisabled',
1576 'info' => "Blocking IP ranges has been disabled"
1577 ),
1578 'nosuchusershort' => array(
1579 'code' => 'nosuchuser',
1580 'info' => "The user you specified doesn't exist"
1581 ),
1582 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1583 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1584 'ipb_already_blocked' => array(
1585 'code' => 'alreadyblocked',
1586 'info' => "The user you tried to block was already blocked"
1587 ),
1588 'ipb_blocked_as_range' => array(
1589 'code' => 'blockedasrange',
1590 'info' => "IP address \"\$1\" was blocked as part of range \"\$2\". You can't unblock the IP individually, but you can unblock the range as a whole."
1591 ),
1592 'ipb_cant_unblock' => array(
1593 'code' => 'cantunblock',
1594 'info' => "The block you specified was not found. It may have been unblocked already"
1595 ),
1596 'mailnologin' => array(
1597 'code' => 'cantsend',
1598 'info' => "You are not logged in, you do not have a confirmed email address, or you are not allowed to send email to other users, so you cannot send email"
1599 ),
1600 'ipbblocked' => array(
1601 'code' => 'ipbblocked',
1602 'info' => 'You cannot block or unblock users while you are yourself blocked'
1603 ),
1604 'ipbnounblockself' => array(
1605 'code' => 'ipbnounblockself',
1606 'info' => 'You are not allowed to unblock yourself'
1607 ),
1608 'usermaildisabled' => array(
1609 'code' => 'usermaildisabled',
1610 'info' => "User email has been disabled"
1611 ),
1612 'blockedemailuser' => array(
1613 'code' => 'blockedfrommail',
1614 'info' => "You have been blocked from sending email"
1615 ),
1616 'notarget' => array(
1617 'code' => 'notarget',
1618 'info' => "You have not specified a valid target for this action"
1619 ),
1620 'noemail' => array(
1621 'code' => 'noemail',
1622 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1623 ),
1624 'rcpatroldisabled' => array(
1625 'code' => 'patroldisabled',
1626 'info' => "Patrolling is disabled on this wiki"
1627 ),
1628 'markedaspatrollederror-noautopatrol' => array(
1629 'code' => 'noautopatrol',
1630 'info' => "You don't have permission to patrol your own changes"
1631 ),
1632 'delete-toobig' => array(
1633 'code' => 'bigdelete',
1634 'info' => "You can't delete this page because it has more than \$1 revisions"
1635 ),
1636 'movenotallowedfile' => array(
1637 'code' => 'cantmovefile',
1638 'info' => "You don't have permission to move files"
1639 ),
1640 'userrights-no-interwiki' => array(
1641 'code' => 'nointerwikiuserrights',
1642 'info' => "You don't have permission to change user rights on other wikis"
1643 ),
1644 'userrights-nodatabase' => array(
1645 'code' => 'nosuchdatabase',
1646 'info' => "Database \"\$1\" does not exist or is not local"
1647 ),
1648 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1649 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1650 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1651 'import-rootpage-invalid' => array(
1652 'code' => 'import-rootpage-invalid',
1653 'info' => 'Root page is an invalid title'
1654 ),
1655 'import-rootpage-nosubpage' => array(
1656 'code' => 'import-rootpage-nosubpage',
1657 'info' => 'Namespace "$1" of the root page does not allow subpages'
1658 ),
1659
1660 // API-specific messages
1661 'readrequired' => array(
1662 'code' => 'readapidenied',
1663 'info' => "You need read permission to use this module"
1664 ),
1665 'writedisabled' => array(
1666 'code' => 'noapiwrite',
1667 'info' => "Editing of this wiki through the API is disabled. Make sure the \$wgEnableWriteAPI=true; statement is included in the wiki's LocalSettings.php file"
1668 ),
1669 'writerequired' => array(
1670 'code' => 'writeapidenied',
1671 'info' => "You're not allowed to edit this wiki through the API"
1672 ),
1673 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1674 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1675 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1676 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1677 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1678 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1679 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1680 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1681 'create-titleexists' => array(
1682 'code' => 'create-titleexists',
1683 'info' => "Existing titles can't be protected with 'create'"
1684 ),
1685 'missingtitle-createonly' => array(
1686 'code' => 'missingtitle-createonly',
1687 'info' => "Missing titles can only be protected with 'create'"
1688 ),
1689 'cantblock' => array( 'code' => 'cantblock',
1690 'info' => "You don't have permission to block users"
1691 ),
1692 'canthide' => array(
1693 'code' => 'canthide',
1694 'info' => "You don't have permission to hide user names from the block log"
1695 ),
1696 'cantblock-email' => array(
1697 'code' => 'cantblock-email',
1698 'info' => "You don't have permission to block users from sending email through the wiki"
1699 ),
1700 'unblock-notarget' => array(
1701 'code' => 'notarget',
1702 'info' => "Either the id or the user parameter must be set"
1703 ),
1704 'unblock-idanduser' => array(
1705 'code' => 'idanduser',
1706 'info' => "The id and user parameters can't be used together"
1707 ),
1708 'cantunblock' => array(
1709 'code' => 'permissiondenied',
1710 'info' => "You don't have permission to unblock users"
1711 ),
1712 'cannotundelete' => array(
1713 'code' => 'cantundelete',
1714 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1715 ),
1716 'permdenied-undelete' => array(
1717 'code' => 'permissiondenied',
1718 'info' => "You don't have permission to restore deleted revisions"
1719 ),
1720 'createonly-exists' => array(
1721 'code' => 'articleexists',
1722 'info' => "The article you tried to create has been created already"
1723 ),
1724 'nocreate-missing' => array(
1725 'code' => 'missingtitle',
1726 'info' => "The article you tried to edit doesn't exist"
1727 ),
1728 'nosuchrcid' => array(
1729 'code' => 'nosuchrcid',
1730 'info' => "There is no change with rcid \"\$1\""
1731 ),
1732 'protect-invalidaction' => array(
1733 'code' => 'protect-invalidaction',
1734 'info' => "Invalid protection type \"\$1\""
1735 ),
1736 'protect-invalidlevel' => array(
1737 'code' => 'protect-invalidlevel',
1738 'info' => "Invalid protection level \"\$1\""
1739 ),
1740 'toofewexpiries' => array(
1741 'code' => 'toofewexpiries',
1742 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1743 ),
1744 'cantimport' => array(
1745 'code' => 'cantimport',
1746 'info' => "You don't have permission to import pages"
1747 ),
1748 'cantimport-upload' => array(
1749 'code' => 'cantimport-upload',
1750 'info' => "You don't have permission to import uploaded pages"
1751 ),
1752 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1753 'importuploaderrorsize' => array(
1754 'code' => 'filetoobig',
1755 'info' => 'The file you uploaded is bigger than the maximum upload size'
1756 ),
1757 'importuploaderrorpartial' => array(
1758 'code' => 'partialupload',
1759 'info' => 'The file was only partially uploaded'
1760 ),
1761 'importuploaderrortemp' => array(
1762 'code' => 'notempdir',
1763 'info' => 'The temporary upload directory is missing'
1764 ),
1765 'importcantopen' => array(
1766 'code' => 'cantopenfile',
1767 'info' => "Couldn't open the uploaded file"
1768 ),
1769 'import-noarticle' => array(
1770 'code' => 'badinterwiki',
1771 'info' => 'Invalid interwiki title specified'
1772 ),
1773 'importbadinterwiki' => array(
1774 'code' => 'badinterwiki',
1775 'info' => 'Invalid interwiki title specified'
1776 ),
1777 'import-unknownerror' => array(
1778 'code' => 'import-unknownerror',
1779 'info' => "Unknown error on import: \"\$1\""
1780 ),
1781 'cantoverwrite-sharedfile' => array(
1782 'code' => 'cantoverwrite-sharedfile',
1783 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1784 ),
1785 'sharedfile-exists' => array(
1786 'code' => 'fileexists-sharedrepo-perm',
1787 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1788 ),
1789 'mustbeposted' => array(
1790 'code' => 'mustbeposted',
1791 'info' => "The \$1 module requires a POST request"
1792 ),
1793 'show' => array(
1794 'code' => 'show',
1795 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1796 ),
1797 'specialpage-cantexecute' => array(
1798 'code' => 'specialpage-cantexecute',
1799 'info' => "You don't have permission to view the results of this special page"
1800 ),
1801 'invalidoldimage' => array(
1802 'code' => 'invalidoldimage',
1803 'info' => 'The oldimage parameter has invalid format'
1804 ),
1805 'nodeleteablefile' => array(
1806 'code' => 'nodeleteablefile',
1807 'info' => 'No such old version of the file'
1808 ),
1809 'fileexists-forbidden' => array(
1810 'code' => 'fileexists-forbidden',
1811 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1812 ),
1813 'fileexists-shared-forbidden' => array(
1814 'code' => 'fileexists-shared-forbidden',
1815 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1816 ),
1817 'filerevert-badversion' => array(
1818 'code' => 'filerevert-badversion',
1819 'info' => 'There is no previous local version of this file with the provided timestamp.'
1820 ),
1821
1822 // ApiEditPage messages
1823 'noimageredirect-anon' => array(
1824 'code' => 'noimageredirect-anon',
1825 'info' => "Anonymous users can't create image redirects"
1826 ),
1827 'noimageredirect-logged' => array(
1828 'code' => 'noimageredirect',
1829 'info' => "You don't have permission to create image redirects"
1830 ),
1831 'spamdetected' => array(
1832 'code' => 'spamdetected',
1833 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1834 ),
1835 'contenttoobig' => array(
1836 'code' => 'contenttoobig',
1837 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1838 ),
1839 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1840 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1841 'wasdeleted' => array(
1842 'code' => 'pagedeleted',
1843 'info' => "The page has been deleted since you fetched its timestamp"
1844 ),
1845 'blankpage' => array(
1846 'code' => 'emptypage',
1847 'info' => "Creating new, empty pages is not allowed"
1848 ),
1849 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1850 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1851 'missingtext' => array(
1852 'code' => 'notext',
1853 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1854 ),
1855 'emptynewsection' => array(
1856 'code' => 'emptynewsection',
1857 'info' => 'Creating empty new sections is not possible.'
1858 ),
1859 'revwrongpage' => array(
1860 'code' => 'revwrongpage',
1861 'info' => "r\$1 is not a revision of \"\$2\""
1862 ),
1863 'undo-failure' => array(
1864 'code' => 'undofailure',
1865 'info' => 'Undo failed due to conflicting intermediate edits'
1866 ),
1867
1868 // Messages from WikiPage::doEit()
1869 'edit-hook-aborted' => array(
1870 'code' => 'edit-hook-aborted',
1871 'info' => "Your edit was aborted by an ArticleSave hook"
1872 ),
1873 'edit-gone-missing' => array(
1874 'code' => 'edit-gone-missing',
1875 'info' => "The page you tried to edit doesn't seem to exist anymore"
1876 ),
1877 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1878 'edit-already-exists' => array(
1879 'code' => 'edit-already-exists',
1880 'info' => 'It seems the page you tried to create already exist'
1881 ),
1882
1883 // uploadMsgs
1884 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1885 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1886 'uploaddisabled' => array(
1887 'code' => 'uploaddisabled',
1888 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1889 ),
1890 'copyuploaddisabled' => array(
1891 'code' => 'copyuploaddisabled',
1892 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1893 ),
1894 'copyuploadbaddomain' => array(
1895 'code' => 'copyuploadbaddomain',
1896 'info' => 'Uploads by URL are not allowed from this domain.'
1897 ),
1898 'copyuploadbadurl' => array(
1899 'code' => 'copyuploadbadurl',
1900 'info' => 'Upload not allowed from this URL.'
1901 ),
1902
1903 'filename-tooshort' => array(
1904 'code' => 'filename-tooshort',
1905 'info' => 'The filename is too short'
1906 ),
1907 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1908 'illegal-filename' => array(
1909 'code' => 'illegal-filename',
1910 'info' => 'The filename is not allowed'
1911 ),
1912 'filetype-missing' => array(
1913 'code' => 'filetype-missing',
1914 'info' => 'The file is missing an extension'
1915 ),
1916
1917 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1918 );
1919 // @codingStandardsIgnoreEnd
1920
1921 /**
1922 * Helper function for readonly errors
1923 */
1924 public function dieReadOnly() {
1925 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1926 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1927 array( 'readonlyreason' => wfReadOnlyReason() ) );
1928 }
1929
1930 /**
1931 * Output the error message related to a certain array
1932 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1933 */
1934 public function dieUsageMsg( $error ) {
1935 # most of the time we send a 1 element, so we might as well send it as
1936 # a string and make this an array here.
1937 if ( is_string( $error ) ) {
1938 $error = array( $error );
1939 }
1940 $parsed = $this->parseMsg( $error );
1941 $this->dieUsage( $parsed['info'], $parsed['code'] );
1942 }
1943
1944 /**
1945 * Will only set a warning instead of failing if the global $wgDebugAPI
1946 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1947 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1948 * @since 1.21
1949 */
1950 public function dieUsageMsgOrDebug( $error ) {
1951 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1952 $this->dieUsageMsg( $error );
1953 }
1954
1955 if ( is_string( $error ) ) {
1956 $error = array( $error );
1957 }
1958 $parsed = $this->parseMsg( $error );
1959 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1960 }
1961
1962 /**
1963 * Die with the $prefix.'badcontinue' error. This call is common enough to
1964 * make it into the base method.
1965 * @param bool $condition Will only die if this value is true
1966 * @since 1.21
1967 */
1968 protected function dieContinueUsageIf( $condition ) {
1969 if ( $condition ) {
1970 $this->dieUsage(
1971 'Invalid continue param. You should pass the original value returned by the previous query',
1972 'badcontinue' );
1973 }
1974 }
1975
1976 /**
1977 * Return the error message related to a certain array
1978 * @param array $error Element of a getUserPermissionsErrors()-style array
1979 * @return array('code' => code, 'info' => info)
1980 */
1981 public function parseMsg( $error ) {
1982 $error = (array)$error; // It seems strings sometimes make their way in here
1983 $key = array_shift( $error );
1984
1985 // Check whether the error array was nested
1986 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1987 if ( is_array( $key ) ) {
1988 $error = $key;
1989 $key = array_shift( $error );
1990 }
1991
1992 if ( isset( self::$messageMap[$key] ) ) {
1993 return array(
1994 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
1995 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
1996 );
1997 }
1998
1999 // If the key isn't present, throw an "unknown error"
2000 return $this->parseMsg( array( 'unknownerror', $key ) );
2001 }
2002
2003 /**
2004 * Internal code errors should be reported with this method
2005 * @param string $method Method or function name
2006 * @param string $message Error message
2007 * @throws MWException
2008 */
2009 protected static function dieDebug( $method, $message ) {
2010 throw new MWException( "Internal error in $method: $message" );
2011 }
2012
2013 /**
2014 * Indicates if this module needs maxlag to be checked
2015 * @return bool
2016 */
2017 public function shouldCheckMaxlag() {
2018 return true;
2019 }
2020
2021 /**
2022 * Indicates whether this module requires read rights
2023 * @return bool
2024 */
2025 public function isReadMode() {
2026 return true;
2027 }
2028
2029 /**
2030 * Indicates whether this module requires write mode
2031 * @return bool
2032 */
2033 public function isWriteMode() {
2034 return false;
2035 }
2036
2037 /**
2038 * Indicates whether this module must be called with a POST request
2039 * @return bool
2040 */
2041 public function mustBePosted() {
2042 return false;
2043 }
2044
2045 /**
2046 * Returns whether this module requires a token to execute
2047 * It is used to show possible errors in action=paraminfo
2048 * see bug 25248
2049 * @return bool
2050 */
2051 public function needsToken() {
2052 return false;
2053 }
2054
2055 /**
2056 * Returns the token salt if there is one,
2057 * '' if the module doesn't require a salt,
2058 * else false if the module doesn't need a token
2059 * You have also to override needsToken()
2060 * Value is passed to User::getEditToken
2061 * @return bool|string|array
2062 */
2063 public function getTokenSalt() {
2064 return false;
2065 }
2066
2067 /**
2068 * Gets the user for whom to get the watchlist
2069 *
2070 * @param array $params
2071 * @return User
2072 */
2073 public function getWatchlistUser( $params ) {
2074 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
2075 $user = User::newFromName( $params['owner'], false );
2076 if ( !( $user && $user->getId() ) ) {
2077 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
2078 }
2079 $token = $user->getOption( 'watchlisttoken' );
2080 if ( $token == '' || $token != $params['token'] ) {
2081 $this->dieUsage(
2082 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
2083 'bad_wltoken'
2084 );
2085 }
2086 } else {
2087 if ( !$this->getUser()->isLoggedIn() ) {
2088 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
2089 }
2090 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
2091 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
2092 }
2093 $user = $this->getUser();
2094 }
2095
2096 return $user;
2097 }
2098
2099 /**
2100 * @return bool|string|array Returns a false if the module has no help URL,
2101 * else returns a (array of) string
2102 */
2103 public function getHelpUrls() {
2104 return false;
2105 }
2106
2107 /**
2108 * Returns a list of all possible errors returned by the module
2109 *
2110 * Don't call this function directly: use getFinalPossibleErrors() to allow
2111 * hooks to modify parameters as needed.
2112 *
2113 * @return array Array in the format of array( key, param1, param2, ... )
2114 * or array( 'code' => ..., 'info' => ... )
2115 */
2116 public function getPossibleErrors() {
2117 $ret = array();
2118
2119 $params = $this->getFinalParams();
2120 if ( $params ) {
2121 foreach ( $params as $paramName => $paramSettings ) {
2122 if ( isset( $paramSettings[ApiBase::PARAM_REQUIRED] )
2123 && $paramSettings[ApiBase::PARAM_REQUIRED]
2124 ) {
2125 $ret[] = array( 'missingparam', $paramName );
2126 }
2127 }
2128 if ( array_key_exists( 'continue', $params ) ) {
2129 $ret[] = array(
2130 'code' => 'badcontinue',
2131 'info' => 'Invalid continue param. You should pass the ' .
2132 'original value returned by the previous query'
2133 );
2134 }
2135 }
2136
2137 if ( $this->mustBePosted() ) {
2138 $ret[] = array( 'mustbeposted', $this->getModuleName() );
2139 }
2140
2141 if ( $this->isReadMode() ) {
2142 $ret[] = array( 'readrequired' );
2143 }
2144
2145 if ( $this->isWriteMode() ) {
2146 $ret[] = array( 'writerequired' );
2147 $ret[] = array( 'writedisabled' );
2148 }
2149
2150 if ( $this->needsToken() ) {
2151 if ( !isset( $params['token'][ApiBase::PARAM_REQUIRED] )
2152 || !$params['token'][ApiBase::PARAM_REQUIRED]
2153 ) {
2154 // Add token as possible missing parameter, if not already done
2155 $ret[] = array( 'missingparam', 'token' );
2156 }
2157 $ret[] = array( 'sessionfailure' );
2158 }
2159
2160 return $ret;
2161 }
2162
2163 /**
2164 * Get final list of possible errors, after hooks have had a chance to
2165 * tweak it as needed.
2166 *
2167 * @return array
2168 * @since 1.22
2169 */
2170 public function getFinalPossibleErrors() {
2171 $possibleErrors = $this->getPossibleErrors();
2172 wfRunHooks( 'APIGetPossibleErrors', array( $this, &$possibleErrors ) );
2173
2174 return $possibleErrors;
2175 }
2176
2177 /**
2178 * Parses a list of errors into a standardised format
2179 * @param array $errors List of errors. Items can be in the for
2180 * array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
2181 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
2182 */
2183 public function parseErrors( $errors ) {
2184 $ret = array();
2185
2186 foreach ( $errors as $row ) {
2187 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
2188 $ret[] = $row;
2189 } else {
2190 $ret[] = $this->parseMsg( $row );
2191 }
2192 }
2193
2194 return $ret;
2195 }
2196
2197 /**
2198 * Profiling: total module execution time
2199 */
2200 private $mTimeIn = 0, $mModuleTime = 0;
2201
2202 /**
2203 * Start module profiling
2204 */
2205 public function profileIn() {
2206 if ( $this->mTimeIn !== 0 ) {
2207 ApiBase::dieDebug( __METHOD__, 'Called twice without calling profileOut()' );
2208 }
2209 $this->mTimeIn = microtime( true );
2210 wfProfileIn( $this->getModuleProfileName() );
2211 }
2212
2213 /**
2214 * End module profiling
2215 */
2216 public function profileOut() {
2217 if ( $this->mTimeIn === 0 ) {
2218 ApiBase::dieDebug( __METHOD__, 'Called without calling profileIn() first' );
2219 }
2220 if ( $this->mDBTimeIn !== 0 ) {
2221 ApiBase::dieDebug(
2222 __METHOD__,
2223 'Must be called after database profiling is done with profileDBOut()'
2224 );
2225 }
2226
2227 $this->mModuleTime += microtime( true ) - $this->mTimeIn;
2228 $this->mTimeIn = 0;
2229 wfProfileOut( $this->getModuleProfileName() );
2230 }
2231
2232 /**
2233 * When modules crash, sometimes it is needed to do a profileOut() regardless
2234 * of the profiling state the module was in. This method does such cleanup.
2235 */
2236 public function safeProfileOut() {
2237 if ( $this->mTimeIn !== 0 ) {
2238 if ( $this->mDBTimeIn !== 0 ) {
2239 $this->profileDBOut();
2240 }
2241 $this->profileOut();
2242 }
2243 }
2244
2245 /**
2246 * Total time the module was executed
2247 * @return float
2248 */
2249 public function getProfileTime() {
2250 if ( $this->mTimeIn !== 0 ) {
2251 ApiBase::dieDebug( __METHOD__, 'Called without calling profileOut() first' );
2252 }
2253
2254 return $this->mModuleTime;
2255 }
2256
2257 /**
2258 * Profiling: database execution time
2259 */
2260 private $mDBTimeIn = 0, $mDBTime = 0;
2261
2262 /**
2263 * Start module profiling
2264 */
2265 public function profileDBIn() {
2266 if ( $this->mTimeIn === 0 ) {
2267 ApiBase::dieDebug(
2268 __METHOD__,
2269 'Must be called while profiling the entire module with profileIn()'
2270 );
2271 }
2272 if ( $this->mDBTimeIn !== 0 ) {
2273 ApiBase::dieDebug( __METHOD__, 'Called twice without calling profileDBOut()' );
2274 }
2275 $this->mDBTimeIn = microtime( true );
2276 wfProfileIn( $this->getModuleProfileName( true ) );
2277 }
2278
2279 /**
2280 * End database profiling
2281 */
2282 public function profileDBOut() {
2283 if ( $this->mTimeIn === 0 ) {
2284 ApiBase::dieDebug( __METHOD__, 'Must be called while profiling ' .
2285 'the entire module with profileIn()' );
2286 }
2287 if ( $this->mDBTimeIn === 0 ) {
2288 ApiBase::dieDebug( __METHOD__, 'Called without calling profileDBIn() first' );
2289 }
2290
2291 $time = microtime( true ) - $this->mDBTimeIn;
2292 $this->mDBTimeIn = 0;
2293
2294 $this->mDBTime += $time;
2295 $this->getMain()->mDBTime += $time;
2296 wfProfileOut( $this->getModuleProfileName( true ) );
2297 }
2298
2299 /**
2300 * Total time the module used the database
2301 * @return float
2302 */
2303 public function getProfileDBTime() {
2304 if ( $this->mDBTimeIn !== 0 ) {
2305 ApiBase::dieDebug( __METHOD__, 'Called without calling profileDBOut() first' );
2306 }
2307
2308 return $this->mDBTime;
2309 }
2310
2311 /**
2312 * Gets a default slave database connection object
2313 * @return DatabaseBase
2314 */
2315 protected function getDB() {
2316 if ( !isset( $this->mSlaveDB ) ) {
2317 $this->profileDBIn();
2318 $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
2319 $this->profileDBOut();
2320 }
2321
2322 return $this->mSlaveDB;
2323 }
2324
2325 /**
2326 * Debugging function that prints a value and an optional backtrace
2327 * @param mixed $value Value to print
2328 * @param string $name Description of the printed value
2329 * @param bool $backtrace If true, print a backtrace
2330 */
2331 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
2332 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
2333 var_export( $value );
2334 if ( $backtrace ) {
2335 print "\n" . wfBacktrace();
2336 }
2337 print "\n</pre>\n";
2338 }
2339 }