Fixed spacing in db/debug/diff/externalstore/objectcache folder
[mediawiki.git] / includes / api / ApiBase.php
blobee5aa972087b83fbe082a48b94868c0bf164d0a7
1 <?php
2 /**
5 * Created on Sep 5, 2006
7 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
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.
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.
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
24 * @file
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:
32 * Module parameters: Derived classes can define getAllowedParams() to specify
33 * which parameters to expect, how to parse and validate them.
35 * Profiling: various methods to allow keeping tabs on various tasks and their
36 * time costs
38 * Self-documentation: code to allow the API to document its own state
40 * @ingroup API
42 abstract class ApiBase extends ContextSource {
44 // These constants allow modules to specify exactly how to treat incoming parameters.
46 const PARAM_DFLT = 0; // Default value of the parameter
47 const PARAM_ISMULTI = 1; // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
48 const PARAM_TYPE = 2; // Can be either a string type (e.g.: 'integer') or an array of allowed values
49 const PARAM_MAX = 3; // Max value allowed for a parameter. Only applies if TYPE='integer'
50 const PARAM_MAX2 = 4; // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
51 const PARAM_MIN = 5; // Lowest value allowed for a parameter. Only applies if TYPE='integer'
52 const PARAM_ALLOW_DUPLICATES = 6; // Boolean, do we allow the same value to be set more than once when ISMULTI=true
53 const PARAM_DEPRECATED = 7; // Boolean, is the parameter deprecated (will show a warning)
54 /// @since 1.17
55 const PARAM_REQUIRED = 8; // Boolean, is the parameter required?
56 /// @since 1.17
57 const PARAM_RANGE_ENFORCE = 9; // Boolean, if MIN/MAX are set, enforce (die) these? Only applies if TYPE='integer' Use with extreme caution
59 const PROP_ROOT = 'ROOT'; // Name of property group that is on the root element of the result, i.e. not part of a list
60 const PROP_LIST = 'LIST'; // Boolean, is the result multiple items? Defaults to true for query modules, to false for other modules
61 const PROP_TYPE = 0; // Type of the property, uses same format as PARAM_TYPE
62 const PROP_NULLABLE = 1; // Boolean, can the property be not included in the result? Defaults to false
64 const LIMIT_BIG1 = 500; // Fast query, std user limit
65 const LIMIT_BIG2 = 5000; // Fast query, bot/sysop limit
66 const LIMIT_SML1 = 50; // Slow query, std user limit
67 const LIMIT_SML2 = 500; // Slow query, bot/sysop limit
69 /**
70 * getAllowedParams() flag: When set, the result could take longer to generate,
71 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
72 * @since 1.21
74 const GET_VALUES_FOR_HELP = 1;
76 private $mMainModule, $mModuleName, $mModulePrefix;
77 private $mSlaveDB = null;
78 private $mParamCache = array();
80 /**
81 * Constructor
82 * @param $mainModule ApiMain object
83 * @param string $moduleName Name of this module
84 * @param string $modulePrefix Prefix to use for parameter names
86 public function __construct( $mainModule, $moduleName, $modulePrefix = '' ) {
87 $this->mMainModule = $mainModule;
88 $this->mModuleName = $moduleName;
89 $this->mModulePrefix = $modulePrefix;
91 if ( !$this->isMain() ) {
92 $this->setContext( $mainModule->getContext() );
96 /*****************************************************************************
97 * ABSTRACT METHODS *
98 *****************************************************************************/
101 * Evaluates the parameters, performs the requested query, and sets up
102 * the result. Concrete implementations of ApiBase must override this
103 * method to provide whatever functionality their module offers.
104 * Implementations must not produce any output on their own and are not
105 * expected to handle any errors.
107 * The execute() method will be invoked directly by ApiMain immediately
108 * before the result of the module is output. Aside from the
109 * constructor, implementations should assume that no other methods
110 * will be called externally on the module before the result is
111 * processed.
113 * The result data should be stored in the ApiResult object available
114 * through getResult().
116 abstract public function execute();
119 * Returns a string that identifies the version of the extending class.
120 * Typically includes the class name, the svn revision, timestamp, and
121 * last author. Usually done with SVN's Id keyword
122 * @return string
123 * @deprecated since 1.21, version string is no longer supported
125 public function getVersion() {
126 wfDeprecated( __METHOD__, '1.21' );
127 return '';
131 * Get the name of the module being executed by this instance
132 * @return string
134 public function getModuleName() {
135 return $this->mModuleName;
139 * Get the module manager, or null if this module has no sub-modules
140 * @since 1.21
141 * @return ApiModuleManager
143 public function getModuleManager() {
144 return null;
148 * Get parameter prefix (usually two letters or an empty string).
149 * @return string
151 public function getModulePrefix() {
152 return $this->mModulePrefix;
156 * Get the name of the module as shown in the profiler log
158 * @param $db DatabaseBase|bool
160 * @return string
162 public function getModuleProfileName( $db = false ) {
163 if ( $db ) {
164 return 'API:' . $this->mModuleName . '-DB';
165 } else {
166 return 'API:' . $this->mModuleName;
171 * Get the main module
172 * @return ApiMain object
174 public function getMain() {
175 return $this->mMainModule;
179 * Returns true if this module is the main module ($this === $this->mMainModule),
180 * false otherwise.
181 * @return bool
183 public function isMain() {
184 return $this === $this->mMainModule;
188 * Get the result object
189 * @return ApiResult
191 public function getResult() {
192 // Main module has getResult() method overridden
193 // Safety - avoid infinite loop:
194 if ( $this->isMain() ) {
195 ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
197 return $this->getMain()->getResult();
201 * Get the result data array (read-only)
202 * @return array
204 public function getResultData() {
205 return $this->getResult()->getData();
209 * Create a new RequestContext object to use e.g. for calls to other parts
210 * the software.
211 * The object will have the WebRequest and the User object set to the ones
212 * used in this instance.
214 * @deprecated since 1.19 use getContext to get the current context
215 * @return DerivativeContext
217 public function createContext() {
218 wfDeprecated( __METHOD__, '1.19' );
219 return new DerivativeContext( $this->getContext() );
223 * Set warning section for this module. Users should monitor this
224 * section to notice any changes in API. Multiple calls to this
225 * function will result in the warning messages being separated by
226 * newlines
227 * @param string $warning Warning message
229 public function setWarning( $warning ) {
230 $result = $this->getResult();
231 $data = $result->getData();
232 $moduleName = $this->getModuleName();
233 if ( isset( $data['warnings'][$moduleName] ) ) {
234 // Don't add duplicate warnings
235 $oldWarning = $data['warnings'][$moduleName]['*'];
236 $warnPos = strpos( $oldWarning, $warning );
237 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
238 if ( $warnPos !== false && ( $warnPos === 0 || $oldWarning[$warnPos - 1] === "\n" ) ) {
239 // Check if $warning is followed by "\n" or the end of the $oldWarning
240 $warnPos += strlen( $warning );
241 if ( strlen( $oldWarning ) <= $warnPos || $oldWarning[$warnPos] === "\n" ) {
242 return;
245 // If there is a warning already, append it to the existing one
246 $warning = "$oldWarning\n$warning";
248 $msg = array();
249 ApiResult::setContent( $msg, $warning );
250 $result->disableSizeCheck();
251 $result->addValue( 'warnings', $moduleName,
252 $msg, ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP );
253 $result->enableSizeCheck();
257 * If the module may only be used with a certain format module,
258 * it should override this method to return an instance of that formatter.
259 * A value of null means the default format will be used.
260 * @return mixed instance of a derived class of ApiFormatBase, or null
262 public function getCustomPrinter() {
263 return null;
267 * Generates help message for this module, or false if there is no description
268 * @return mixed string or false
270 public function makeHelpMsg() {
271 static $lnPrfx = "\n ";
273 $msg = $this->getFinalDescription();
275 if ( $msg !== false ) {
277 if ( !is_array( $msg ) ) {
278 $msg = array(
279 $msg
282 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
284 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
286 if ( $this->isReadMode() ) {
287 $msg .= "\nThis module requires read rights";
289 if ( $this->isWriteMode() ) {
290 $msg .= "\nThis module requires write rights";
292 if ( $this->mustBePosted() ) {
293 $msg .= "\nThis module only accepts POST requests";
295 if ( $this->isReadMode() || $this->isWriteMode() ||
296 $this->mustBePosted() ) {
297 $msg .= "\n";
300 // Parameters
301 $paramsMsg = $this->makeHelpMsgParameters();
302 if ( $paramsMsg !== false ) {
303 $msg .= "Parameters:\n$paramsMsg";
306 $examples = $this->getExamples();
307 if ( $examples !== false && $examples !== '' ) {
308 if ( !is_array( $examples ) ) {
309 $examples = array(
310 $examples
313 $msg .= "Example" . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
314 foreach ( $examples as $k => $v ) {
315 if ( is_numeric( $k ) ) {
316 $msg .= " $v\n";
317 } else {
318 if ( is_array( $v ) ) {
319 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
320 } else {
321 $msgExample = " $v";
323 $msgExample .= ":";
324 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
330 return $msg;
334 * @param $item string
335 * @return string
337 private function indentExampleText( $item ) {
338 return " " . $item;
342 * @param string $prefix Text to split output items
343 * @param string $title What is being output
344 * @param $input string|array
345 * @return string
347 protected function makeHelpArrayToString( $prefix, $title, $input ) {
348 if ( $input === false ) {
349 return '';
351 if ( !is_array( $input ) ) {
352 $input = array( $input );
355 if ( count( $input ) > 0 ) {
356 if ( $title ) {
357 $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n ";
358 } else {
359 $msg = ' ';
361 $msg .= implode( $prefix, $input ) . "\n";
362 return $msg;
364 return '';
368 * Generates the parameter descriptions for this module, to be displayed in the
369 * module's help.
370 * @return string or false
372 public function makeHelpMsgParameters() {
373 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
374 if ( $params ) {
376 $paramsDescription = $this->getFinalParamDescription();
377 $msg = '';
378 $paramPrefix = "\n" . str_repeat( ' ', 24 );
379 $descWordwrap = "\n" . str_repeat( ' ', 28 );
380 foreach ( $params as $paramName => $paramSettings ) {
381 $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
382 if ( is_array( $desc ) ) {
383 $desc = implode( $paramPrefix, $desc );
386 //handle shorthand
387 if ( !is_array( $paramSettings ) ) {
388 $paramSettings = array(
389 self::PARAM_DFLT => $paramSettings,
393 //handle missing type
394 if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) {
395 $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] ) ? $paramSettings[ApiBase::PARAM_DFLT] : null;
396 if ( is_bool( $dflt ) ) {
397 $paramSettings[ApiBase::PARAM_TYPE] = 'boolean';
398 } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
399 $paramSettings[ApiBase::PARAM_TYPE] = 'string';
400 } elseif ( is_int( $dflt ) ) {
401 $paramSettings[ApiBase::PARAM_TYPE] = 'integer';
405 if ( isset( $paramSettings[self::PARAM_DEPRECATED] ) && $paramSettings[self::PARAM_DEPRECATED] ) {
406 $desc = "DEPRECATED! $desc";
409 if ( isset( $paramSettings[self::PARAM_REQUIRED] ) && $paramSettings[self::PARAM_REQUIRED] ) {
410 $desc .= $paramPrefix . "This parameter is required";
413 $type = isset( $paramSettings[self::PARAM_TYPE] ) ? $paramSettings[self::PARAM_TYPE] : null;
414 if ( isset( $type ) ) {
415 $hintPipeSeparated = true;
416 $multi = isset( $paramSettings[self::PARAM_ISMULTI] ) ? $paramSettings[self::PARAM_ISMULTI] : false;
417 if ( $multi ) {
418 $prompt = 'Values (separate with \'|\'): ';
419 } else {
420 $prompt = 'One value: ';
423 if ( is_array( $type ) ) {
424 $choices = array();
425 $nothingPrompt = '';
426 foreach ( $type as $t ) {
427 if ( $t === '' ) {
428 $nothingPrompt = 'Can be empty, or ';
429 } else {
430 $choices[] = $t;
433 $desc .= $paramPrefix . $nothingPrompt . $prompt;
434 $choicesstring = implode( ', ', $choices );
435 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
436 $hintPipeSeparated = false;
437 } else {
438 switch ( $type ) {
439 case 'namespace':
440 // Special handling because namespaces are type-limited, yet they are not given
441 $desc .= $paramPrefix . $prompt;
442 $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
443 100, $descWordwrap );
444 $hintPipeSeparated = false;
445 break;
446 case 'limit':
447 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
448 if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
449 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
451 $desc .= ' allowed';
452 break;
453 case 'integer':
454 $s = $multi ? 's' : '';
455 $hasMin = isset( $paramSettings[self::PARAM_MIN] );
456 $hasMax = isset( $paramSettings[self::PARAM_MAX] );
457 if ( $hasMin || $hasMax ) {
458 if ( !$hasMax ) {
459 $intRangeStr = "The value$s must be no less than {$paramSettings[self::PARAM_MIN]}";
460 } elseif ( !$hasMin ) {
461 $intRangeStr = "The value$s must be no more than {$paramSettings[self::PARAM_MAX]}";
462 } else {
463 $intRangeStr = "The value$s must be between {$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
466 $desc .= $paramPrefix . $intRangeStr;
468 break;
469 case 'upload':
470 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
471 break;
475 if ( $multi ) {
476 if ( $hintPipeSeparated ) {
477 $desc .= $paramPrefix . "Separate values with '|'";
480 $isArray = is_array( $type );
481 if ( !$isArray
482 || $isArray && count( $type ) > self::LIMIT_SML1 ) {
483 $desc .= $paramPrefix . "Maximum number of values " .
484 self::LIMIT_SML1 . " (" . self::LIMIT_SML2 . " for bots)";
489 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
490 if ( !is_null( $default ) && $default !== false ) {
491 $desc .= $paramPrefix . "Default: $default";
494 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
496 return $msg;
498 } else {
499 return false;
504 * Returns the description string for this module
505 * @return mixed string or array of strings
507 protected function getDescription() {
508 return false;
512 * Returns usage examples for this module. Return false if no examples are available.
513 * @return bool|string|array
515 protected function getExamples() {
516 return false;
520 * Returns an array of allowed parameters (parameter name) => (default
521 * value) or (parameter name) => (array with PARAM_* constants as keys)
522 * Don't call this function directly: use getFinalParams() to allow
523 * hooks to modify parameters as needed.
525 * Some derived classes may choose to handle an integer $flags parameter
526 * in the overriding methods. Callers of this method can pass zero or
527 * more OR-ed flags like GET_VALUES_FOR_HELP.
529 * @return array|bool
531 protected function getAllowedParams( /* $flags = 0 */ ) {
532 // int $flags is not declared because it causes "Strict standards"
533 // warning. Most derived classes do not implement it.
534 return false;
538 * Returns an array of parameter descriptions.
539 * Don't call this function directly: use getFinalParamDescription() to
540 * allow hooks to modify descriptions as needed.
541 * @return array|bool False on no parameter descriptions
543 protected function getParamDescription() {
544 return false;
548 * Get final list of parameters, after hooks have had a chance to
549 * tweak it as needed.
551 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
552 * @return array|Bool False on no parameters
553 * @since 1.21 $flags param added
555 public function getFinalParams( $flags = 0 ) {
556 $params = $this->getAllowedParams( $flags );
557 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
558 return $params;
562 * Get final parameter descriptions, after hooks have had a chance to tweak it as
563 * needed.
565 * @return array|bool False on no parameter descriptions
567 public function getFinalParamDescription() {
568 $desc = $this->getParamDescription();
569 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
570 return $desc;
574 * Returns possible properties in the result, grouped by the value of the prop parameter
575 * that shows them.
577 * Properties that are shown always are in a group with empty string as a key.
578 * Properties that can be shown by several values of prop are included multiple times.
579 * If some properties are part of a list and some are on the root object (see ApiQueryQueryPage),
580 * those on the root object are under the key PROP_ROOT.
581 * The array can also contain a boolean under the key PROP_LIST,
582 * indicating whether the result is a list.
584 * Don't call this function directly: use getFinalResultProperties() to
585 * allow hooks to modify descriptions as needed.
587 * @return array|bool False on no properties
589 protected function getResultProperties() {
590 return false;
594 * Get final possible result properties, after hooks have had a chance to tweak it as
595 * needed.
597 * @return array
599 public function getFinalResultProperties() {
600 $properties = $this->getResultProperties();
601 wfRunHooks( 'APIGetResultProperties', array( $this, &$properties ) );
602 return $properties;
606 * Add token properties to the array used by getResultProperties,
607 * based on a token functions mapping.
609 protected static function addTokenProperties( &$props, $tokenFunctions ) {
610 foreach ( array_keys( $tokenFunctions ) as $token ) {
611 $props[''][$token . 'token'] = array(
612 ApiBase::PROP_TYPE => 'string',
613 ApiBase::PROP_NULLABLE => true
619 * Get final module description, after hooks have had a chance to tweak it as
620 * needed.
622 * @return array|bool False on no parameters
624 public function getFinalDescription() {
625 $desc = $this->getDescription();
626 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
627 return $desc;
631 * This method mangles parameter name based on the prefix supplied to the constructor.
632 * Override this method to change parameter name during runtime
633 * @param string $paramName Parameter name
634 * @return string Prefixed parameter name
636 public function encodeParamName( $paramName ) {
637 return $this->mModulePrefix . $paramName;
641 * Using getAllowedParams(), this function makes an array of the values
642 * provided by the user, with key being the name of the variable, and
643 * value - validated value from user or default. limits will not be
644 * parsed if $parseLimit is set to false; use this when the max
645 * limit is not definitive yet, e.g. when getting revisions.
646 * @param $parseLimit Boolean: true by default
647 * @return array
649 public function extractRequestParams( $parseLimit = true ) {
650 // Cache parameters, for performance and to avoid bug 24564.
651 if ( !isset( $this->mParamCache[$parseLimit] ) ) {
652 $params = $this->getFinalParams();
653 $results = array();
655 if ( $params ) { // getFinalParams() can return false
656 foreach ( $params as $paramName => $paramSettings ) {
657 $results[$paramName] = $this->getParameterFromSettings(
658 $paramName, $paramSettings, $parseLimit );
661 $this->mParamCache[$parseLimit] = $results;
663 return $this->mParamCache[$parseLimit];
667 * Get a value for the given parameter
668 * @param string $paramName Parameter name
669 * @param bool $parseLimit see extractRequestParams()
670 * @return mixed Parameter value
672 protected function getParameter( $paramName, $parseLimit = true ) {
673 $params = $this->getFinalParams();
674 $paramSettings = $params[$paramName];
675 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
679 * Die if none or more than one of a certain set of parameters is set and not false.
680 * @param array $params of parameter names
682 public function requireOnlyOneParameter( $params ) {
683 $required = func_get_args();
684 array_shift( $required );
685 $p = $this->getModulePrefix();
687 $intersection = array_intersect( array_keys( array_filter( $params,
688 array( $this, "parameterNotEmpty" ) ) ), $required );
690 if ( count( $intersection ) > 1 ) {
691 $this->dieUsage( "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together', "{$p}invalidparammix" );
692 } elseif ( count( $intersection ) == 0 ) {
693 $this->dieUsage( "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
698 * Generates the possible errors requireOnlyOneParameter() can die with
700 * @param $params array
701 * @return array
703 public function getRequireOnlyOneParameterErrorMessages( $params ) {
704 $p = $this->getModulePrefix();
705 $params = implode( ", {$p}", $params );
707 return array(
708 array( 'code' => "{$p}missingparam", 'info' => "One of the parameters {$p}{$params} is required" ),
709 array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
714 * Die if more than one of a certain set of parameters is set and not false.
716 * @param $params array
718 public function requireMaxOneParameter( $params ) {
719 $required = func_get_args();
720 array_shift( $required );
721 $p = $this->getModulePrefix();
723 $intersection = array_intersect( array_keys( array_filter( $params,
724 array( $this, "parameterNotEmpty" ) ) ), $required );
726 if ( count( $intersection ) > 1 ) {
727 $this->dieUsage( "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together', "{$p}invalidparammix" );
732 * Generates the possible error requireMaxOneParameter() can die with
734 * @param $params array
735 * @return array
737 public function getRequireMaxOneParameterErrorMessages( $params ) {
738 $p = $this->getModulePrefix();
739 $params = implode( ", {$p}", $params );
741 return array(
742 array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
747 * @param $params array
748 * @param bool|string $load Whether load the object's state from the database:
749 * - false: don't load (if the pageid is given, it will still be loaded)
750 * - 'fromdb': load from a slave database
751 * - 'fromdbmaster': load from the master database
752 * @return WikiPage
754 public function getTitleOrPageId( $params, $load = false ) {
755 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
757 $pageObj = null;
758 if ( isset( $params['title'] ) ) {
759 $titleObj = Title::newFromText( $params['title'] );
760 if ( !$titleObj || $titleObj->isExternal() ) {
761 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
763 if ( !$titleObj->canExist() ) {
764 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
766 $pageObj = WikiPage::factory( $titleObj );
767 if ( $load !== false ) {
768 $pageObj->loadPageData( $load );
770 } elseif ( isset( $params['pageid'] ) ) {
771 if ( $load === false ) {
772 $load = 'fromdb';
774 $pageObj = WikiPage::newFromID( $params['pageid'], $load );
775 if ( !$pageObj ) {
776 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
780 return $pageObj;
784 * @return array
786 public function getTitleOrPageIdErrorMessage() {
787 return array_merge(
788 $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ),
789 array(
790 array( 'invalidtitle', 'title' ),
791 array( 'nosuchpageid', 'pageid' ),
797 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
799 * @param $x object Parameter to check is not null/false
800 * @return bool
802 private function parameterNotEmpty( $x ) {
803 return !is_null( $x ) && $x !== false;
807 * @deprecated since 1.17 use MWNamespace::getValidNamespaces()
809 * @return array
811 public static function getValidNamespaces() {
812 wfDeprecated( __METHOD__, '1.17' );
813 return MWNamespace::getValidNamespaces();
817 * Return true if we're to watch the page, false if not, null if no change.
818 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
819 * @param $titleObj Title the page under consideration
820 * @param string $userOption The user option to consider when $watchlist=preferences.
821 * If not set will magically default to either watchdefault or watchcreations
822 * @return bool
824 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
826 $userWatching = $this->getUser()->isWatched( $titleObj );
828 switch ( $watchlist ) {
829 case 'watch':
830 return true;
832 case 'unwatch':
833 return false;
835 case 'preferences':
836 # If the user is already watching, don't bother checking
837 if ( $userWatching ) {
838 return true;
840 # If no user option was passed, use watchdefault or watchcreations
841 if ( is_null( $userOption ) ) {
842 $userOption = $titleObj->exists()
843 ? 'watchdefault' : 'watchcreations';
845 # Watch the article based on the user preference
846 return $this->getUser()->getBoolOption( $userOption );
848 case 'nochange':
849 return $userWatching;
851 default:
852 return $userWatching;
857 * Set a watch (or unwatch) based the based on a watchlist parameter.
858 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
859 * @param $titleObj Title the article's title to change
860 * @param string $userOption The user option to consider when $watch=preferences
862 protected function setWatch( $watch, $titleObj, $userOption = null ) {
863 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
864 if ( $value === null ) {
865 return;
868 $user = $this->getUser();
869 if ( $value ) {
870 WatchAction::doWatch( $titleObj, $user );
871 } else {
872 WatchAction::doUnwatch( $titleObj, $user );
877 * Using the settings determine the value for the given parameter
879 * @param string $paramName parameter name
880 * @param array|mixed $paramSettings default value or an array of settings
881 * using PARAM_* constants.
882 * @param $parseLimit Boolean: parse limit?
883 * @return mixed Parameter value
885 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
886 // Some classes may decide to change parameter names
887 $encParamName = $this->encodeParamName( $paramName );
889 if ( !is_array( $paramSettings ) ) {
890 $default = $paramSettings;
891 $multi = false;
892 $type = gettype( $paramSettings );
893 $dupes = false;
894 $deprecated = false;
895 $required = false;
896 } else {
897 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
898 $multi = isset( $paramSettings[self::PARAM_ISMULTI] ) ? $paramSettings[self::PARAM_ISMULTI] : false;
899 $type = isset( $paramSettings[self::PARAM_TYPE] ) ? $paramSettings[self::PARAM_TYPE] : null;
900 $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] ) ? $paramSettings[self::PARAM_ALLOW_DUPLICATES] : false;
901 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] ) ? $paramSettings[self::PARAM_DEPRECATED] : false;
902 $required = isset( $paramSettings[self::PARAM_REQUIRED] ) ? $paramSettings[self::PARAM_REQUIRED] : false;
904 // When type is not given, and no choices, the type is the same as $default
905 if ( !isset( $type ) ) {
906 if ( isset( $default ) ) {
907 $type = gettype( $default );
908 } else {
909 $type = 'NULL'; // allow everything
914 if ( $type == 'boolean' ) {
915 if ( isset( $default ) && $default !== false ) {
916 // Having a default value of anything other than 'false' is not allowed
917 ApiBase::dieDebug( __METHOD__, "Boolean param $encParamName's default is set to '$default'. Boolean parameters must default to false." );
920 $value = $this->getMain()->getCheck( $encParamName );
921 } elseif ( $type == 'upload' ) {
922 if ( isset( $default ) ) {
923 // Having a default value is not allowed
924 ApiBase::dieDebug( __METHOD__, "File upload param $encParamName's default is set to '$default'. File upload parameters may not have a default." );
926 if ( $multi ) {
927 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
929 $value = $this->getMain()->getUpload( $encParamName );
930 if ( !$value->exists() ) {
931 // This will get the value without trying to normalize it
932 // (because trying to normalize a large binary file
933 // accidentally uploaded as a field fails spectacularly)
934 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
935 if ( $value !== null ) {
936 $this->dieUsage(
937 "File upload param $encParamName is not a file upload; " .
938 "be sure to use multipart/form-data for your POST and include " .
939 "a filename in the Content-Disposition header.",
940 "badupload_{$encParamName}"
944 } else {
945 $value = $this->getMain()->getVal( $encParamName, $default );
947 if ( isset( $value ) && $type == 'namespace' ) {
948 $type = MWNamespace::getValidNamespaces();
952 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
953 $value = $this->parseMultiValue( $encParamName, $value, $multi, is_array( $type ) ? $type : null );
956 // More validation only when choices were not given
957 // choices were validated in parseMultiValue()
958 if ( isset( $value ) ) {
959 if ( !is_array( $type ) ) {
960 switch ( $type ) {
961 case 'NULL': // nothing to do
962 break;
963 case 'string':
964 if ( $required && $value === '' ) {
965 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
967 break;
968 case 'integer': // Force everything using intval() and optionally validate limits
969 $min = isset ( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
970 $max = isset ( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
971 $enforceLimits = isset ( $paramSettings[self::PARAM_RANGE_ENFORCE] )
972 ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
974 if ( is_array( $value ) ) {
975 $value = array_map( 'intval', $value );
976 if ( !is_null( $min ) || !is_null( $max ) ) {
977 foreach ( $value as &$v ) {
978 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
981 } else {
982 $value = intval( $value );
983 if ( !is_null( $min ) || !is_null( $max ) ) {
984 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
987 break;
988 case 'limit':
989 if ( !$parseLimit ) {
990 // Don't do any validation whatsoever
991 break;
993 if ( !isset( $paramSettings[self::PARAM_MAX] ) || !isset( $paramSettings[self::PARAM_MAX2] ) ) {
994 ApiBase::dieDebug( __METHOD__, "MAX1 or MAX2 are not defined for the limit $encParamName" );
996 if ( $multi ) {
997 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
999 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
1000 if ( $value == 'max' ) {
1001 $value = $this->getMain()->canApiHighLimits() ? $paramSettings[self::PARAM_MAX2] : $paramSettings[self::PARAM_MAX];
1002 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
1003 } else {
1004 $value = intval( $value );
1005 $this->validateLimit( $paramName, $value, $min, $paramSettings[self::PARAM_MAX], $paramSettings[self::PARAM_MAX2] );
1007 break;
1008 case 'boolean':
1009 if ( $multi ) {
1010 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1012 break;
1013 case 'timestamp':
1014 if ( is_array( $value ) ) {
1015 foreach ( $value as $key => $val ) {
1016 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1018 } else {
1019 $value = $this->validateTimestamp( $value, $encParamName );
1021 break;
1022 case 'user':
1023 if ( is_array( $value ) ) {
1024 foreach ( $value as $key => $val ) {
1025 $value[$key] = $this->validateUser( $val, $encParamName );
1027 } else {
1028 $value = $this->validateUser( $value, $encParamName );
1030 break;
1031 case 'upload': // nothing to do
1032 break;
1033 default:
1034 ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
1038 // Throw out duplicates if requested
1039 if ( !$dupes && is_array( $value ) ) {
1040 $value = array_unique( $value );
1043 // Set a warning if a deprecated parameter has been passed
1044 if ( $deprecated && $value !== false ) {
1045 $this->setWarning( "The $encParamName parameter has been deprecated." );
1047 } elseif ( $required ) {
1048 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1051 return $value;
1055 * Return an array of values that were given in a 'a|b|c' notation,
1056 * after it optionally validates them against the list allowed values.
1058 * @param string $valueName The name of the parameter (for error
1059 * reporting)
1060 * @param $value mixed The value being parsed
1061 * @param bool $allowMultiple Can $value contain more than one value
1062 * separated by '|'?
1063 * @param $allowedValues mixed An array of values to check against. If
1064 * null, all values are accepted.
1065 * @return mixed (allowMultiple ? an_array_of_values : a_single_value)
1067 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1068 if ( trim( $value ) === '' && $allowMultiple ) {
1069 return array();
1072 // This is a bit awkward, but we want to avoid calling canApiHighLimits() because it unstubs $wgUser
1073 $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 );
1074 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits() ?
1075 self::LIMIT_SML2 : self::LIMIT_SML1;
1077 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
1078 $this->setWarning( "Too many values supplied for parameter '$valueName': the limit is $sizeLimit" );
1081 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1082 // Bug 33482 - Allow entries with | in them for non-multiple values
1083 if ( in_array( $value, $allowedValues, true ) ) {
1084 return $value;
1087 $possibleValues = is_array( $allowedValues ) ? "of '" . implode( "', '", $allowedValues ) . "'" : '';
1088 $this->dieUsage( "Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName" );
1091 if ( is_array( $allowedValues ) ) {
1092 // Check for unknown values
1093 $unknown = array_diff( $valuesList, $allowedValues );
1094 if ( count( $unknown ) ) {
1095 if ( $allowMultiple ) {
1096 $s = count( $unknown ) > 1 ? 's' : '';
1097 $vals = implode( ", ", $unknown );
1098 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1099 } else {
1100 $this->dieUsage( "Unrecognized value for parameter '$valueName': {$valuesList[0]}", "unknown_$valueName" );
1103 // Now throw them out
1104 $valuesList = array_intersect( $valuesList, $allowedValues );
1107 return $allowMultiple ? $valuesList : $valuesList[0];
1111 * Validate the value against the minimum and user/bot maximum limits.
1112 * Prints usage info on failure.
1113 * @param string $paramName Parameter name
1114 * @param int $value Parameter value
1115 * @param int|null $min Minimum value
1116 * @param int|null $max Maximum value for users
1117 * @param int $botMax Maximum value for sysops/bots
1118 * @param $enforceLimits Boolean Whether to enforce (die) if value is outside limits
1120 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1121 if ( !is_null( $min ) && $value < $min ) {
1123 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1124 $this->warnOrDie( $msg, $enforceLimits );
1125 $value = $min;
1128 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
1129 if ( $this->getMain()->isInternalMode() ) {
1130 return;
1133 // Optimization: do not check user's bot status unless really needed -- skips db query
1134 // assumes $botMax >= $max
1135 if ( !is_null( $max ) && $value > $max ) {
1136 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1137 if ( $value > $botMax ) {
1138 $msg = $this->encodeParamName( $paramName ) . " may not be over $botMax (set to $value) for bots or sysops";
1139 $this->warnOrDie( $msg, $enforceLimits );
1140 $value = $botMax;
1142 } else {
1143 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1144 $this->warnOrDie( $msg, $enforceLimits );
1145 $value = $max;
1151 * Validate and normalize of parameters of type 'timestamp'
1152 * @param string $value Parameter value
1153 * @param string $encParamName Parameter name
1154 * @return string Validated and normalized parameter
1156 function validateTimestamp( $value, $encParamName ) {
1157 $unixTimestamp = wfTimestamp( TS_UNIX, $value );
1158 if ( $unixTimestamp === false ) {
1159 $this->dieUsage( "Invalid value '$value' for timestamp parameter $encParamName", "badtimestamp_{$encParamName}" );
1161 return wfTimestamp( TS_MW, $unixTimestamp );
1165 * Validate and normalize of parameters of type 'user'
1166 * @param string $value Parameter value
1167 * @param string $encParamName Parameter name
1168 * @return string Validated and normalized parameter
1170 private function validateUser( $value, $encParamName ) {
1171 $title = Title::makeTitleSafe( NS_USER, $value );
1172 if ( $title === null ) {
1173 $this->dieUsage( "Invalid value '$value' for user parameter $encParamName", "baduser_{$encParamName}" );
1175 return $title->getText();
1179 * Adds a warning to the output, else dies
1181 * @param $msg String Message to show as a warning, or error message if dying
1182 * @param $enforceLimits Boolean Whether this is an enforce (die)
1184 private function warnOrDie( $msg, $enforceLimits = false ) {
1185 if ( $enforceLimits ) {
1186 $this->dieUsage( $msg, 'integeroutofrange' );
1187 } else {
1188 $this->setWarning( $msg );
1193 * Truncate an array to a certain length.
1194 * @param array $arr Array to truncate
1195 * @param int $limit Maximum length
1196 * @return bool True if the array was truncated, false otherwise
1198 public static function truncateArray( &$arr, $limit ) {
1199 $modified = false;
1200 while ( count( $arr ) > $limit ) {
1201 array_pop( $arr );
1202 $modified = true;
1204 return $modified;
1208 * Throw a UsageException, which will (if uncaught) call the main module's
1209 * error handler and die with an error message.
1211 * @param string $description One-line human-readable description of the
1212 * error condition, e.g., "The API requires a valid action parameter"
1213 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1214 * automated identification of the error, e.g., 'unknown_action'
1215 * @param int $httpRespCode HTTP response code
1216 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1217 * @throws UsageException
1219 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1220 Profiler::instance()->close();
1221 throw new UsageException( $description, $this->encodeParamName( $errorCode ), $httpRespCode, $extradata );
1225 * Array that maps message keys to error messages. $1 and friends are replaced.
1227 public static $messageMap = array(
1228 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1229 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1230 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1232 // Messages from Title::getUserPermissionsErrors()
1233 'ns-specialprotected' => array( 'code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited" ),
1234 'protectedinterface' => array( 'code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages" ),
1235 'namespaceprotected' => array( 'code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the \"\$1\" namespace" ),
1236 'customcssprotected' => array( 'code' => 'customcssprotected', 'info' => "You're not allowed to edit custom CSS pages" ),
1237 'customjsprotected' => array( 'code' => 'customjsprotected', 'info' => "You're not allowed to edit custom JavaScript pages" ),
1238 'cascadeprotected' => array( 'code' => 'cascadeprotected', 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page" ),
1239 'protectedpagetext' => array( 'code' => 'protectedpage', 'info' => "The \"\$1\" right is required to edit this page" ),
1240 'protect-cantedit' => array( 'code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it" ),
1241 'badaccess-group0' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ), // Generic permission denied message
1242 'badaccess-groups' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ),
1243 'titleprotected' => array( 'code' => 'protectedtitle', 'info' => "This title has been protected from creation" ),
1244 'nocreate-loggedin' => array( 'code' => 'cantcreate', 'info' => "You don't have permission to create new pages" ),
1245 'nocreatetext' => array( 'code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages" ),
1246 'movenologintext' => array( 'code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages" ),
1247 'movenotallowed' => array( 'code' => 'cantmove', 'info' => "You don't have permission to move pages" ),
1248 'confirmedittext' => array( 'code' => 'confirmemail', 'info' => "You must confirm your email address before you can edit" ),
1249 'blockedtext' => array( 'code' => 'blocked', 'info' => "You have been blocked from editing" ),
1250 'autoblockedtext' => array( 'code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user" ),
1252 // Miscellaneous interface messages
1253 'actionthrottledtext' => array( 'code' => 'ratelimited', 'info' => "You've exceeded your rate limit. Please wait some time and try again" ),
1254 'alreadyrolled' => array( 'code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back" ),
1255 'cantrollback' => array( 'code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author" ),
1256 'readonlytext' => array( 'code' => 'readonly', 'info' => "The wiki is currently in read-only mode" ),
1257 'sessionfailure' => array( 'code' => 'badtoken', 'info' => "Invalid token" ),
1258 'cannotdelete' => array( 'code' => 'cantdelete', 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else" ),
1259 'notanarticle' => array( 'code' => 'missingtitle', 'info' => "The page you requested doesn't exist" ),
1260 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself" ),
1261 'immobile_namespace' => array( 'code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving" ),
1262 'articleexists' => array( 'code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article" ),
1263 'protectedpage' => array( 'code' => 'protectedpage', 'info' => "You don't have permission to perform this move" ),
1264 'hookaborted' => array( 'code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook" ),
1265 'cantmove-titleprotected' => array( 'code' => 'protectedtitle', 'info' => "The destination article has been protected from creation" ),
1266 'imagenocrossnamespace' => array( 'code' => 'nonfilenamespace', 'info' => "Can't move a file to a non-file namespace" ),
1267 'imagetypemismatch' => array( 'code' => 'filetypemismatch', 'info' => "The new file extension doesn't match its type" ),
1268 // 'badarticleerror' => shouldn't happen
1269 // 'badtitletext' => shouldn't happen
1270 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1271 'range_block_disabled' => array( 'code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled" ),
1272 'nosuchusershort' => array( 'code' => 'nosuchuser', 'info' => "The user you specified doesn't exist" ),
1273 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1274 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1275 'ipb_already_blocked' => array( 'code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked" ),
1276 'ipb_blocked_as_range' => array( 'code' => 'blockedasrange', '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." ),
1277 'ipb_cant_unblock' => array( 'code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already" ),
1278 'mailnologin' => array( 'code' => 'cantsend', '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" ),
1279 'ipbblocked' => array( 'code' => 'ipbblocked', 'info' => 'You cannot block or unblock users while you are yourself blocked' ),
1280 'ipbnounblockself' => array( 'code' => 'ipbnounblockself', 'info' => 'You are not allowed to unblock yourself' ),
1281 'usermaildisabled' => array( 'code' => 'usermaildisabled', 'info' => "User email has been disabled" ),
1282 'blockedemailuser' => array( 'code' => 'blockedfrommail', 'info' => "You have been blocked from sending email" ),
1283 'notarget' => array( 'code' => 'notarget', 'info' => "You have not specified a valid target for this action" ),
1284 'noemail' => array( 'code' => 'noemail', 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users" ),
1285 'rcpatroldisabled' => array( 'code' => 'patroldisabled', 'info' => "Patrolling is disabled on this wiki" ),
1286 'markedaspatrollederror-noautopatrol' => array( 'code' => 'noautopatrol', 'info' => "You don't have permission to patrol your own changes" ),
1287 'delete-toobig' => array( 'code' => 'bigdelete', 'info' => "You can't delete this page because it has more than \$1 revisions" ),
1288 'movenotallowedfile' => array( 'code' => 'cantmovefile', 'info' => "You don't have permission to move files" ),
1289 'userrights-no-interwiki' => array( 'code' => 'nointerwikiuserrights', 'info' => "You don't have permission to change user rights on other wikis" ),
1290 'userrights-nodatabase' => array( 'code' => 'nosuchdatabase', 'info' => "Database \"\$1\" does not exist or is not local" ),
1291 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1292 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1293 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1294 'import-rootpage-invalid' => array( 'code' => 'import-rootpage-invalid', 'info' => 'Root page is an invalid title' ),
1295 'import-rootpage-nosubpage' => array( 'code' => 'import-rootpage-nosubpage', 'info' => 'Namespace "$1" of the root page does not allow subpages' ),
1297 // API-specific messages
1298 'readrequired' => array( 'code' => 'readapidenied', 'info' => "You need read permission to use this module" ),
1299 'writedisabled' => array( 'code' => 'noapiwrite', '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" ),
1300 'writerequired' => array( 'code' => 'writeapidenied', 'info' => "You're not allowed to edit this wiki through the API" ),
1301 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1302 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1303 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1304 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1305 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1306 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1307 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1308 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1309 'create-titleexists' => array( 'code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'" ),
1310 'missingtitle-createonly' => array( 'code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'" ),
1311 'cantblock' => array( 'code' => 'cantblock', 'info' => "You don't have permission to block users" ),
1312 'canthide' => array( 'code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log" ),
1313 'cantblock-email' => array( 'code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending email through the wiki" ),
1314 'unblock-notarget' => array( 'code' => 'notarget', 'info' => "Either the id or the user parameter must be set" ),
1315 'unblock-idanduser' => array( 'code' => 'idanduser', 'info' => "The id and user parameters can't be used together" ),
1316 'cantunblock' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to unblock users" ),
1317 'cannotundelete' => array( 'code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already" ),
1318 'permdenied-undelete' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions" ),
1319 'createonly-exists' => array( 'code' => 'articleexists', 'info' => "The article you tried to create has been created already" ),
1320 'nocreate-missing' => array( 'code' => 'missingtitle', 'info' => "The article you tried to edit doesn't exist" ),
1321 'nosuchrcid' => array( 'code' => 'nosuchrcid', 'info' => "There is no change with rcid \"\$1\"" ),
1322 'protect-invalidaction' => array( 'code' => 'protect-invalidaction', 'info' => "Invalid protection type \"\$1\"" ),
1323 'protect-invalidlevel' => array( 'code' => 'protect-invalidlevel', 'info' => "Invalid protection level \"\$1\"" ),
1324 'toofewexpiries' => array( 'code' => 'toofewexpiries', 'info' => "\$1 expiry timestamps were provided where \$2 were needed" ),
1325 'cantimport' => array( 'code' => 'cantimport', 'info' => "You don't have permission to import pages" ),
1326 'cantimport-upload' => array( 'code' => 'cantimport-upload', 'info' => "You don't have permission to import uploaded pages" ),
1327 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1328 'importuploaderrorsize' => array( 'code' => 'filetoobig', 'info' => 'The file you uploaded is bigger than the maximum upload size' ),
1329 'importuploaderrorpartial' => array( 'code' => 'partialupload', 'info' => 'The file was only partially uploaded' ),
1330 'importuploaderrortemp' => array( 'code' => 'notempdir', 'info' => 'The temporary upload directory is missing' ),
1331 'importcantopen' => array( 'code' => 'cantopenfile', 'info' => "Couldn't open the uploaded file" ),
1332 'import-noarticle' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
1333 'importbadinterwiki' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
1334 'import-unknownerror' => array( 'code' => 'import-unknownerror', 'info' => "Unknown error on import: \"\$1\"" ),
1335 'cantoverwrite-sharedfile' => array( 'code' => 'cantoverwrite-sharedfile', 'info' => 'The target file exists on a shared repository and you do not have permission to override it' ),
1336 'sharedfile-exists' => array( 'code' => 'fileexists-sharedrepo-perm', 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.' ),
1337 'mustbeposted' => array( 'code' => 'mustbeposted', 'info' => "The \$1 module requires a POST request" ),
1338 'show' => array( 'code' => 'show', 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied' ),
1339 'specialpage-cantexecute' => array( 'code' => 'specialpage-cantexecute', 'info' => "You don't have permission to view the results of this special page" ),
1340 'invalidoldimage' => array( 'code' => 'invalidoldimage', 'info' => 'The oldimage parameter has invalid format' ),
1341 'nodeleteablefile' => array( 'code' => 'nodeleteablefile', 'info' => 'No such old version of the file' ),
1342 'fileexists-forbidden' => array( 'code' => 'fileexists-forbidden', 'info' => 'A file with name "$1" already exists, and cannot be overwritten.' ),
1343 'fileexists-shared-forbidden' => array( 'code' => 'fileexists-shared-forbidden', 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.' ),
1344 'filerevert-badversion' => array( 'code' => 'filerevert-badversion', 'info' => 'There is no previous local version of this file with the provided timestamp.' ),
1346 // ApiEditPage messages
1347 'noimageredirect-anon' => array( 'code' => 'noimageredirect-anon', 'info' => "Anonymous users can't create image redirects" ),
1348 'noimageredirect-logged' => array( 'code' => 'noimageredirect', 'info' => "You don't have permission to create image redirects" ),
1349 'spamdetected' => array( 'code' => 'spamdetected', 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\"" ),
1350 'contenttoobig' => array( 'code' => 'contenttoobig', 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes" ),
1351 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1352 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1353 'wasdeleted' => array( 'code' => 'pagedeleted', 'info' => "The page has been deleted since you fetched its timestamp" ),
1354 'blankpage' => array( 'code' => 'emptypage', 'info' => "Creating new, empty pages is not allowed" ),
1355 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1356 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1357 'missingtext' => array( 'code' => 'notext', 'info' => "One of the text, appendtext, prependtext and undo parameters must be set" ),
1358 'emptynewsection' => array( 'code' => 'emptynewsection', 'info' => 'Creating empty new sections is not possible.' ),
1359 'revwrongpage' => array( 'code' => 'revwrongpage', 'info' => "r\$1 is not a revision of \"\$2\"" ),
1360 'undo-failure' => array( 'code' => 'undofailure', 'info' => 'Undo failed due to conflicting intermediate edits' ),
1362 // Messages from WikiPage::doEit()
1363 'edit-hook-aborted' => array( 'code' => 'edit-hook-aborted', 'info' => "Your edit was aborted by an ArticleSave hook" ),
1364 'edit-gone-missing' => array( 'code' => 'edit-gone-missing', 'info' => "The page you tried to edit doesn't seem to exist anymore" ),
1365 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1366 'edit-already-exists' => array( 'code' => 'edit-already-exists', 'info' => "It seems the page you tried to create already exist" ),
1368 // uploadMsgs
1369 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1370 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1371 'uploaddisabled' => array( 'code' => 'uploaddisabled', 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true' ),
1372 'copyuploaddisabled' => array( 'code' => 'copyuploaddisabled', 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.' ),
1373 'copyuploadbaddomain' => array( 'code' => 'copyuploadbaddomain', 'info' => 'Uploads by URL are not allowed from this domain.' ),
1375 'filename-tooshort' => array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
1376 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1377 'illegal-filename' => array( 'code' => 'illegal-filename', 'info' => 'The filename is not allowed' ),
1378 'filetype-missing' => array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
1380 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1384 * Helper function for readonly errors
1386 public function dieReadOnly() {
1387 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1388 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1389 array( 'readonlyreason' => wfReadOnlyReason() ) );
1393 * Output the error message related to a certain array
1394 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1396 public function dieUsageMsg( $error ) {
1397 # most of the time we send a 1 element, so we might as well send it as
1398 # a string and make this an array here.
1399 if ( is_string( $error ) ) {
1400 $error = array( $error );
1402 $parsed = $this->parseMsg( $error );
1403 $this->dieUsage( $parsed['info'], $parsed['code'] );
1407 * Will only set a warning instead of failing if the global $wgDebugAPI
1408 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1409 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1410 * @since 1.21
1412 public function dieUsageMsgOrDebug( $error ) {
1413 global $wgDebugAPI;
1414 if ( $wgDebugAPI !== true ) {
1415 $this->dieUsageMsg( $error );
1416 } else {
1417 if ( is_string( $error ) ) {
1418 $error = array( $error );
1420 $parsed = $this->parseMsg( $error );
1421 $this->setWarning( '$wgDebugAPI: ' . $parsed['code']
1422 . ' - ' . $parsed['info'] );
1427 * Die with the $prefix.'badcontinue' error. This call is common enough to make it into the base method.
1428 * @param $condition boolean will only die if this value is true
1429 * @since 1.21
1431 protected function dieContinueUsageIf( $condition ) {
1432 if ( $condition ) {
1433 $this->dieUsage(
1434 'Invalid continue param. You should pass the original value returned by the previous query',
1435 'badcontinue' );
1440 * Return the error message related to a certain array
1441 * @param array $error Element of a getUserPermissionsErrors()-style array
1442 * @return array('code' => code, 'info' => info)
1444 public function parseMsg( $error ) {
1445 $error = (array)$error; // It seems strings sometimes make their way in here
1446 $key = array_shift( $error );
1448 // Check whether the error array was nested
1449 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1450 if ( is_array( $key ) ) {
1451 $error = $key;
1452 $key = array_shift( $error );
1455 if ( isset( self::$messageMap[$key] ) ) {
1456 return array(
1457 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
1458 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
1462 // If the key isn't present, throw an "unknown error"
1463 return $this->parseMsg( array( 'unknownerror', $key ) );
1467 * Internal code errors should be reported with this method
1468 * @param string $method Method or function name
1469 * @param string $message Error message
1471 protected static function dieDebug( $method, $message ) {
1472 wfDebugDieBacktrace( "Internal error in $method: $message" );
1476 * Indicates if this module needs maxlag to be checked
1477 * @return bool
1479 public function shouldCheckMaxlag() {
1480 return true;
1484 * Indicates whether this module requires read rights
1485 * @return bool
1487 public function isReadMode() {
1488 return true;
1491 * Indicates whether this module requires write mode
1492 * @return bool
1494 public function isWriteMode() {
1495 return false;
1499 * Indicates whether this module must be called with a POST request
1500 * @return bool
1502 public function mustBePosted() {
1503 return false;
1507 * Returns whether this module requires a token to execute
1508 * It is used to show possible errors in action=paraminfo
1509 * see bug 25248
1510 * @return bool
1512 public function needsToken() {
1513 return false;
1517 * Returns the token salt if there is one,
1518 * '' if the module doesn't require a salt,
1519 * else false if the module doesn't need a token
1520 * You have also to override needsToken()
1521 * Value is passed to User::getEditToken
1522 * @return bool|string|array
1524 public function getTokenSalt() {
1525 return false;
1529 * Gets the user for whom to get the watchlist
1531 * @param $params array
1532 * @return User
1534 public function getWatchlistUser( $params ) {
1535 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1536 $user = User::newFromName( $params['owner'], false );
1537 if ( !( $user && $user->getId() ) ) {
1538 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1540 $token = $user->getOption( 'watchlisttoken' );
1541 if ( $token == '' || $token != $params['token'] ) {
1542 $this->dieUsage( 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences', 'bad_wltoken' );
1544 } else {
1545 if ( !$this->getUser()->isLoggedIn() ) {
1546 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1548 $user = $this->getUser();
1550 return $user;
1554 * @return bool|string|array Returns a false if the module has no help url, else returns a (array of) string
1556 public function getHelpUrls() {
1557 return false;
1561 * Returns a list of all possible errors returned by the module
1563 * Don't call this function directly: use getFinalPossibleErrors() to allow
1564 * hooks to modify parameters as needed.
1566 * @return array in the format of array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1568 public function getPossibleErrors() {
1569 $ret = array();
1571 $params = $this->getFinalParams();
1572 if ( $params ) {
1573 foreach ( $params as $paramName => $paramSettings ) {
1574 if ( isset( $paramSettings[ApiBase::PARAM_REQUIRED] ) && $paramSettings[ApiBase::PARAM_REQUIRED] ) {
1575 $ret[] = array( 'missingparam', $paramName );
1578 if ( array_key_exists( 'continue', $params ) ) {
1579 $ret[] = array(
1580 array(
1581 'code' => 'badcontinue',
1582 'info' => 'Invalid continue param. You should pass the original value returned by the previous query'
1583 ) );
1587 if ( $this->mustBePosted() ) {
1588 $ret[] = array( 'mustbeposted', $this->getModuleName() );
1591 if ( $this->isReadMode() ) {
1592 $ret[] = array( 'readrequired' );
1595 if ( $this->isWriteMode() ) {
1596 $ret[] = array( 'writerequired' );
1597 $ret[] = array( 'writedisabled' );
1600 if ( $this->needsToken() ) {
1601 $ret[] = array( 'missingparam', 'token' );
1602 $ret[] = array( 'sessionfailure' );
1605 return $ret;
1609 * Get final list of possible errors, after hooks have had a chance to
1610 * tweak it as needed.
1612 * @return array
1613 * @since 1.22
1615 public function getFinalPossibleErrors() {
1616 $possibleErrors = $this->getPossibleErrors();
1617 wfRunHooks( 'APIGetPossibleErrors', array( $this, &$possibleErrors ) );
1618 return $possibleErrors;
1622 * Parses a list of errors into a standardised format
1623 * @param array $errors List of errors. Items can be in the for array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1624 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
1626 public function parseErrors( $errors ) {
1627 $ret = array();
1629 foreach ( $errors as $row ) {
1630 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
1631 $ret[] = $row;
1632 } else {
1633 $ret[] = $this->parseMsg( $row );
1636 return $ret;
1640 * Profiling: total module execution time
1642 private $mTimeIn = 0, $mModuleTime = 0;
1645 * Start module profiling
1647 public function profileIn() {
1648 if ( $this->mTimeIn !== 0 ) {
1649 ApiBase::dieDebug( __METHOD__, 'called twice without calling profileOut()' );
1651 $this->mTimeIn = microtime( true );
1652 wfProfileIn( $this->getModuleProfileName() );
1656 * End module profiling
1658 public function profileOut() {
1659 if ( $this->mTimeIn === 0 ) {
1660 ApiBase::dieDebug( __METHOD__, 'called without calling profileIn() first' );
1662 if ( $this->mDBTimeIn !== 0 ) {
1663 ApiBase::dieDebug( __METHOD__, 'must be called after database profiling is done with profileDBOut()' );
1666 $this->mModuleTime += microtime( true ) - $this->mTimeIn;
1667 $this->mTimeIn = 0;
1668 wfProfileOut( $this->getModuleProfileName() );
1672 * When modules crash, sometimes it is needed to do a profileOut() regardless
1673 * of the profiling state the module was in. This method does such cleanup.
1675 public function safeProfileOut() {
1676 if ( $this->mTimeIn !== 0 ) {
1677 if ( $this->mDBTimeIn !== 0 ) {
1678 $this->profileDBOut();
1680 $this->profileOut();
1685 * Total time the module was executed
1686 * @return float
1688 public function getProfileTime() {
1689 if ( $this->mTimeIn !== 0 ) {
1690 ApiBase::dieDebug( __METHOD__, 'called without calling profileOut() first' );
1692 return $this->mModuleTime;
1696 * Profiling: database execution time
1698 private $mDBTimeIn = 0, $mDBTime = 0;
1701 * Start module profiling
1703 public function profileDBIn() {
1704 if ( $this->mTimeIn === 0 ) {
1705 ApiBase::dieDebug( __METHOD__, 'must be called while profiling the entire module with profileIn()' );
1707 if ( $this->mDBTimeIn !== 0 ) {
1708 ApiBase::dieDebug( __METHOD__, 'called twice without calling profileDBOut()' );
1710 $this->mDBTimeIn = microtime( true );
1711 wfProfileIn( $this->getModuleProfileName( true ) );
1715 * End database profiling
1717 public function profileDBOut() {
1718 if ( $this->mTimeIn === 0 ) {
1719 ApiBase::dieDebug( __METHOD__, 'must be called while profiling the entire module with profileIn()' );
1721 if ( $this->mDBTimeIn === 0 ) {
1722 ApiBase::dieDebug( __METHOD__, 'called without calling profileDBIn() first' );
1725 $time = microtime( true ) - $this->mDBTimeIn;
1726 $this->mDBTimeIn = 0;
1728 $this->mDBTime += $time;
1729 $this->getMain()->mDBTime += $time;
1730 wfProfileOut( $this->getModuleProfileName( true ) );
1734 * Total time the module used the database
1735 * @return float
1737 public function getProfileDBTime() {
1738 if ( $this->mDBTimeIn !== 0 ) {
1739 ApiBase::dieDebug( __METHOD__, 'called without calling profileDBOut() first' );
1741 return $this->mDBTime;
1745 * Gets a default slave database connection object
1746 * @return DatabaseBase
1748 protected function getDB() {
1749 if ( !isset( $this->mSlaveDB ) ) {
1750 $this->profileDBIn();
1751 $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
1752 $this->profileDBOut();
1754 return $this->mSlaveDB;
1758 * Debugging function that prints a value and an optional backtrace
1759 * @param $value mixed Value to print
1760 * @param string $name Description of the printed value
1761 * @param bool $backtrace If true, print a backtrace
1763 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
1764 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
1765 var_export( $value );
1766 if ( $backtrace ) {
1767 print "\n" . wfBacktrace();
1769 print "\n</pre>\n";