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