Implement extension registration from an extension.json file
[mediawiki.git] / includes / api / ApiBase.php
blob87c88fb0e72a1d2f50bd74b18e7afe2e7625a21d
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 {
43 // These constants allow modules to specify exactly how to treat incoming parameters.
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 /// @since 1.25
68 // Specify an alternative i18n message for this help parameter.
69 // Value is $msg for ApiBase::makeMessage()
70 const PARAM_HELP_MSG = 10;
71 /// @since 1.25
72 // Specify additional i18n messages to append to the normal message. Value
73 // is an array of $msg for ApiBase::makeMessage()
74 const PARAM_HELP_MSG_APPEND = 11;
75 /// @since 1.25
76 // Specify additional information tags for the parameter. Value is an array
77 // of arrays, with the first member being the 'tag' for the info and the
78 // remaining members being the values. In the help, this is formatted using
79 // apihelp-{$path}-paraminfo-{$tag}, which is passed $1 = count, $2 =
80 // comma-joined list of values, $3 = module prefix.
81 const PARAM_HELP_MSG_INFO = 12;
82 /// @since 1.25
83 // When PARAM_TYPE is an array, this may be an array mapping those values
84 // to page titles which will be linked in the help.
85 const PARAM_VALUE_LINKS = 13;
86 /// @since 1.25
87 // When PARAM_TYPE is an array, this is an array mapping those values to
88 // $msg for ApiBase::makeMessage(). Any value not having a mapping will use
89 // apihelp-{$path}-paramvalue-{$param}-{$value} is used.
90 const PARAM_HELP_MSG_PER_VALUE = 14;
92 const LIMIT_BIG1 = 500; // Fast query, std user limit
93 const LIMIT_BIG2 = 5000; // Fast query, bot/sysop limit
94 const LIMIT_SML1 = 50; // Slow query, std user limit
95 const LIMIT_SML2 = 500; // Slow query, bot/sysop limit
97 /**
98 * getAllowedParams() flag: When set, the result could take longer to generate,
99 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
100 * @since 1.21
102 const GET_VALUES_FOR_HELP = 1;
104 /** @var ApiMain */
105 private $mMainModule;
106 /** @var string */
107 private $mModuleName, $mModulePrefix;
108 private $mSlaveDB = null;
109 private $mParamCache = array();
112 * @param ApiMain $mainModule
113 * @param string $moduleName Name of this module
114 * @param string $modulePrefix Prefix to use for parameter names
116 public function __construct( ApiMain $mainModule, $moduleName, $modulePrefix = '' ) {
117 $this->mMainModule = $mainModule;
118 $this->mModuleName = $moduleName;
119 $this->mModulePrefix = $modulePrefix;
121 if ( !$this->isMain() ) {
122 $this->setContext( $mainModule->getContext() );
127 /************************************************************************//**
128 * @name Methods to implement
129 * @{
133 * Evaluates the parameters, performs the requested query, and sets up
134 * the result. Concrete implementations of ApiBase must override this
135 * method to provide whatever functionality their module offers.
136 * Implementations must not produce any output on their own and are not
137 * expected to handle any errors.
139 * The execute() method will be invoked directly by ApiMain immediately
140 * before the result of the module is output. Aside from the
141 * constructor, implementations should assume that no other methods
142 * will be called externally on the module before the result is
143 * processed.
145 * The result data should be stored in the ApiResult object available
146 * through getResult().
148 abstract public function execute();
151 * Get the module manager, or null if this module has no sub-modules
152 * @since 1.21
153 * @return ApiModuleManager
155 public function getModuleManager() {
156 return null;
160 * If the module may only be used with a certain format module,
161 * it should override this method to return an instance of that formatter.
162 * A value of null means the default format will be used.
163 * @return mixed Instance of a derived class of ApiFormatBase, or null
165 public function getCustomPrinter() {
166 return null;
170 * Returns usage examples for this module.
172 * Return value has query strings as keys, with values being either strings
173 * (message key), arrays (message key + parameter), or Message objects.
175 * Do not call this base class implementation when overriding this method.
177 * @since 1.25
178 * @return array
180 protected function getExamplesMessages() {
181 // Fall back to old non-localised method
182 $ret = array();
184 $examples = $this->getExamples();
185 if ( $examples ) {
186 if ( !is_array( $examples ) ) {
187 $examples = array( $examples );
188 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
189 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
190 !preg_match( '/^\s*api\.php\?/', $examples[0] )
192 // Fix up the ugly "even numbered elements are description, odd
193 // numbered elemts are the link" format (see doc for self::getExamples)
194 $tmp = array();
195 for ( $i = 0; $i < count( $examples ); $i += 2 ) {
196 $tmp[$examples[$i + 1]] = $examples[$i];
198 $examples = $tmp;
201 foreach ( $examples as $k => $v ) {
202 if ( is_numeric( $k ) ) {
203 $qs = $v;
204 $msg = '';
205 } else {
206 $qs = $k;
207 $msg = self::escapeWikiText( $v );
208 if ( is_array( $msg ) ) {
209 $msg = join( " ", $msg );
213 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
214 $ret[$qs] = $this->msg( 'api-help-fallback-example', array( $msg ) );
218 return $ret;
222 * Return links to more detailed help pages about the module.
223 * @since 1.25, returning boolean false is deprecated
224 * @return string|array
226 public function getHelpUrls() {
227 return array();
231 * Returns an array of allowed parameters (parameter name) => (default
232 * value) or (parameter name) => (array with PARAM_* constants as keys)
233 * Don't call this function directly: use getFinalParams() to allow
234 * hooks to modify parameters as needed.
236 * Some derived classes may choose to handle an integer $flags parameter
237 * in the overriding methods. Callers of this method can pass zero or
238 * more OR-ed flags like GET_VALUES_FOR_HELP.
240 * @return array
242 protected function getAllowedParams( /* $flags = 0 */ ) {
243 // int $flags is not declared because it causes "Strict standards"
244 // warning. Most derived classes do not implement it.
245 return array();
249 * Indicates if this module needs maxlag to be checked
250 * @return bool
252 public function shouldCheckMaxlag() {
253 return true;
257 * Indicates whether this module requires read rights
258 * @return bool
260 public function isReadMode() {
261 return true;
265 * Indicates whether this module requires write mode
266 * @return bool
268 public function isWriteMode() {
269 return false;
273 * Indicates whether this module must be called with a POST request
274 * @return bool
276 public function mustBePosted() {
277 return $this->needsToken() !== false;
281 * Indicates whether this module is deprecated
282 * @since 1.25
283 * @return bool
285 public function isDeprecated() {
286 return false;
290 * Indicates whether this module is "internal"
291 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
292 * @since 1.25
293 * @return bool
295 public function isInternal() {
296 return false;
300 * Returns the token type this module requires in order to execute.
302 * Modules are strongly encouraged to use the core 'csrf' type unless they
303 * have specialized security needs. If the token type is not one of the
304 * core types, you must use the ApiQueryTokensRegisterTypes hook to
305 * register it.
307 * Returning a non-falsey value here will force the addition of an
308 * appropriate 'token' parameter in self::getFinalParams(). Also,
309 * self::mustBePosted() must return true when tokens are used.
311 * In previous versions of MediaWiki, true was a valid return value.
312 * Returning true will generate errors indicating that the API module needs
313 * updating.
315 * @return string|false
317 public function needsToken() {
318 return false;
322 * Fetch the salt used in the Web UI corresponding to this module.
324 * Only override this if the Web UI uses a token with a non-constant salt.
326 * @since 1.24
327 * @param array $params All supplied parameters for the module
328 * @return string|array|null
330 protected function getWebUITokenSalt( array $params ) {
331 return null;
334 /**@}*/
336 /************************************************************************//**
337 * @name Data access methods
338 * @{
342 * Get the name of the module being executed by this instance
343 * @return string
345 public function getModuleName() {
346 return $this->mModuleName;
350 * Get parameter prefix (usually two letters or an empty string).
351 * @return string
353 public function getModulePrefix() {
354 return $this->mModulePrefix;
358 * Get the main module
359 * @return ApiMain
361 public function getMain() {
362 return $this->mMainModule;
366 * Returns true if this module is the main module ($this === $this->mMainModule),
367 * false otherwise.
368 * @return bool
370 public function isMain() {
371 return $this === $this->mMainModule;
375 * Get the parent of this module
376 * @since 1.25
377 * @return ApiBase|null
379 public function getParent() {
380 return $this->isMain() ? null : $this->getMain();
384 * Get the path to this module
386 * @since 1.25
387 * @return string
389 public function getModulePath() {
390 if ( $this->isMain() ) {
391 return 'main';
392 } elseif ( $this->getParent()->isMain() ) {
393 return $this->getModuleName();
394 } else {
395 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
400 * Get a module from its module path
402 * @since 1.25
403 * @param string $path
404 * @return ApiBase|null
405 * @throws UsageException
407 public function getModuleFromPath( $path ) {
408 $module = $this->getMain();
409 if ( $path === 'main' ) {
410 return $module;
413 $parts = explode( '+', $path );
414 if ( count( $parts ) === 1 ) {
415 // In case the '+' was typed into URL, it resolves as a space
416 $parts = explode( ' ', $path );
419 $count = count( $parts );
420 for ( $i = 0; $i < $count; $i++ ) {
421 $parent = $module;
422 $manager = $parent->getModuleManager();
423 if ( $manager === null ) {
424 $errorPath = join( '+', array_slice( $parts, 0, $i ) );
425 $this->dieUsage( "The module \"$errorPath\" has no submodules", 'badmodule' );
427 $module = $manager->getModule( $parts[$i] );
429 if ( $module === null ) {
430 $errorPath = $i ? join( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
431 $this->dieUsage(
432 "The module \"$errorPath\" does not have a submodule \"{$parts[$i]}\"",
433 'badmodule'
438 return $module;
442 * Get the result object
443 * @return ApiResult
445 public function getResult() {
446 // Main module has getResult() method overridden
447 // Safety - avoid infinite loop:
448 if ( $this->isMain() ) {
449 ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
452 return $this->getMain()->getResult();
456 * Get the result data array (read-only)
457 * @return array
459 public function getResultData() {
460 return $this->getResult()->getData();
464 * Gets a default slave database connection object
465 * @return DatabaseBase
467 protected function getDB() {
468 if ( !isset( $this->mSlaveDB ) ) {
469 $this->profileDBIn();
470 $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
471 $this->profileDBOut();
474 return $this->mSlaveDB;
477 /**@}*/
479 /************************************************************************//**
480 * @name Parameter handling
481 * @{
485 * This method mangles parameter name based on the prefix supplied to the constructor.
486 * Override this method to change parameter name during runtime
487 * @param string $paramName Parameter name
488 * @return string Prefixed parameter name
490 public function encodeParamName( $paramName ) {
491 return $this->mModulePrefix . $paramName;
495 * Using getAllowedParams(), this function makes an array of the values
496 * provided by the user, with key being the name of the variable, and
497 * value - validated value from user or default. limits will not be
498 * parsed if $parseLimit is set to false; use this when the max
499 * limit is not definitive yet, e.g. when getting revisions.
500 * @param bool $parseLimit True by default
501 * @return array
503 public function extractRequestParams( $parseLimit = true ) {
504 // Cache parameters, for performance and to avoid bug 24564.
505 if ( !isset( $this->mParamCache[$parseLimit] ) ) {
506 $params = $this->getFinalParams();
507 $results = array();
509 if ( $params ) { // getFinalParams() can return false
510 foreach ( $params as $paramName => $paramSettings ) {
511 $results[$paramName] = $this->getParameterFromSettings(
512 $paramName, $paramSettings, $parseLimit );
515 $this->mParamCache[$parseLimit] = $results;
518 return $this->mParamCache[$parseLimit];
522 * Get a value for the given parameter
523 * @param string $paramName Parameter name
524 * @param bool $parseLimit See extractRequestParams()
525 * @return mixed Parameter value
527 protected function getParameter( $paramName, $parseLimit = true ) {
528 $params = $this->getFinalParams();
529 $paramSettings = $params[$paramName];
531 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
535 * Die if none or more than one of a certain set of parameters is set and not false.
537 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
538 * @param string $required,... Names of parameters of which exactly one must be set
540 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
541 $required = func_get_args();
542 array_shift( $required );
543 $p = $this->getModulePrefix();
545 $intersection = array_intersect( array_keys( array_filter( $params,
546 array( $this, "parameterNotEmpty" ) ) ), $required );
548 if ( count( $intersection ) > 1 ) {
549 $this->dieUsage(
550 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
551 'invalidparammix' );
552 } elseif ( count( $intersection ) == 0 ) {
553 $this->dieUsage(
554 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
555 'missingparam'
561 * Die if more than one of a certain set of parameters is set and not false.
563 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
564 * @param string $required,... Names of parameters of which at most one must be set
566 public function requireMaxOneParameter( $params, $required /*...*/ ) {
567 $required = func_get_args();
568 array_shift( $required );
569 $p = $this->getModulePrefix();
571 $intersection = array_intersect( array_keys( array_filter( $params,
572 array( $this, "parameterNotEmpty" ) ) ), $required );
574 if ( count( $intersection ) > 1 ) {
575 $this->dieUsage(
576 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
577 'invalidparammix'
583 * Die if none of a certain set of parameters is set and not false.
585 * @since 1.23
586 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
587 * @param string $required,... Names of parameters of which at least one must be set
589 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
590 $required = func_get_args();
591 array_shift( $required );
592 $p = $this->getModulePrefix();
594 $intersection = array_intersect(
595 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
596 $required
599 if ( count( $intersection ) == 0 ) {
600 $this->dieUsage( "At least one of the parameters {$p}" .
601 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
606 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
608 * @param object $x Parameter to check is not null/false
609 * @return bool
611 private function parameterNotEmpty( $x ) {
612 return !is_null( $x ) && $x !== false;
616 * Get a WikiPage object from a title or pageid param, if possible.
617 * Can die, if no param is set or if the title or page id is not valid.
619 * @param array $params
620 * @param bool|string $load Whether load the object's state from the database:
621 * - false: don't load (if the pageid is given, it will still be loaded)
622 * - 'fromdb': load from a slave database
623 * - 'fromdbmaster': load from the master database
624 * @return WikiPage
626 public function getTitleOrPageId( $params, $load = false ) {
627 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
629 $pageObj = null;
630 if ( isset( $params['title'] ) ) {
631 $titleObj = Title::newFromText( $params['title'] );
632 if ( !$titleObj || $titleObj->isExternal() ) {
633 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
635 if ( !$titleObj->canExist() ) {
636 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
638 $pageObj = WikiPage::factory( $titleObj );
639 if ( $load !== false ) {
640 $pageObj->loadPageData( $load );
642 } elseif ( isset( $params['pageid'] ) ) {
643 if ( $load === false ) {
644 $load = 'fromdb';
646 $pageObj = WikiPage::newFromID( $params['pageid'], $load );
647 if ( !$pageObj ) {
648 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
652 return $pageObj;
656 * Return true if we're to watch the page, false if not, null if no change.
657 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
658 * @param Title $titleObj The page under consideration
659 * @param string $userOption The user option to consider when $watchlist=preferences.
660 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
661 * @return bool
663 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
665 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem::IGNORE_USER_RIGHTS );
667 switch ( $watchlist ) {
668 case 'watch':
669 return true;
671 case 'unwatch':
672 return false;
674 case 'preferences':
675 # If the user is already watching, don't bother checking
676 if ( $userWatching ) {
677 return true;
679 # If no user option was passed, use watchdefault and watchcreations
680 if ( is_null( $userOption ) ) {
681 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
682 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
685 # Watch the article based on the user preference
686 return $this->getUser()->getBoolOption( $userOption );
688 case 'nochange':
689 return $userWatching;
691 default:
692 return $userWatching;
697 * Using the settings determine the value for the given parameter
699 * @param string $paramName Parameter name
700 * @param array|mixed $paramSettings Default value or an array of settings
701 * using PARAM_* constants.
702 * @param bool $parseLimit Parse limit?
703 * @return mixed Parameter value
705 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
706 // Some classes may decide to change parameter names
707 $encParamName = $this->encodeParamName( $paramName );
709 if ( !is_array( $paramSettings ) ) {
710 $default = $paramSettings;
711 $multi = false;
712 $type = gettype( $paramSettings );
713 $dupes = false;
714 $deprecated = false;
715 $required = false;
716 } else {
717 $default = isset( $paramSettings[self::PARAM_DFLT] )
718 ? $paramSettings[self::PARAM_DFLT]
719 : null;
720 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
721 ? $paramSettings[self::PARAM_ISMULTI]
722 : false;
723 $type = isset( $paramSettings[self::PARAM_TYPE] )
724 ? $paramSettings[self::PARAM_TYPE]
725 : null;
726 $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] )
727 ? $paramSettings[self::PARAM_ALLOW_DUPLICATES]
728 : false;
729 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] )
730 ? $paramSettings[self::PARAM_DEPRECATED]
731 : false;
732 $required = isset( $paramSettings[self::PARAM_REQUIRED] )
733 ? $paramSettings[self::PARAM_REQUIRED]
734 : false;
736 // When type is not given, and no choices, the type is the same as $default
737 if ( !isset( $type ) ) {
738 if ( isset( $default ) ) {
739 $type = gettype( $default );
740 } else {
741 $type = 'NULL'; // allow everything
746 if ( $type == 'boolean' ) {
747 if ( isset( $default ) && $default !== false ) {
748 // Having a default value of anything other than 'false' is not allowed
749 ApiBase::dieDebug(
750 __METHOD__,
751 "Boolean param $encParamName's default is set to '$default'. " .
752 "Boolean parameters must default to false."
756 $value = $this->getMain()->getCheck( $encParamName );
757 } elseif ( $type == 'upload' ) {
758 if ( isset( $default ) ) {
759 // Having a default value is not allowed
760 ApiBase::dieDebug(
761 __METHOD__,
762 "File upload param $encParamName's default is set to " .
763 "'$default'. File upload parameters may not have a default." );
765 if ( $multi ) {
766 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
768 $value = $this->getMain()->getUpload( $encParamName );
769 if ( !$value->exists() ) {
770 // This will get the value without trying to normalize it
771 // (because trying to normalize a large binary file
772 // accidentally uploaded as a field fails spectacularly)
773 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
774 if ( $value !== null ) {
775 $this->dieUsage(
776 "File upload param $encParamName is not a file upload; " .
777 "be sure to use multipart/form-data for your POST and include " .
778 "a filename in the Content-Disposition header.",
779 "badupload_{$encParamName}"
783 } else {
784 $value = $this->getMain()->getVal( $encParamName, $default );
786 if ( isset( $value ) && $type == 'namespace' ) {
787 $type = MWNamespace::getValidNamespaces();
789 if ( isset( $value ) && $type == 'submodule' ) {
790 $type = $this->getModuleManager()->getNames( $paramName );
794 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
795 $value = $this->parseMultiValue(
796 $encParamName,
797 $value,
798 $multi,
799 is_array( $type ) ? $type : null
803 // More validation only when choices were not given
804 // choices were validated in parseMultiValue()
805 if ( isset( $value ) ) {
806 if ( !is_array( $type ) ) {
807 switch ( $type ) {
808 case 'NULL': // nothing to do
809 break;
810 case 'string':
811 if ( $required && $value === '' ) {
812 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
814 break;
815 case 'integer': // Force everything using intval() and optionally validate limits
816 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
817 $max = isset( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
818 $enforceLimits = isset( $paramSettings[self::PARAM_RANGE_ENFORCE] )
819 ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
821 if ( is_array( $value ) ) {
822 $value = array_map( 'intval', $value );
823 if ( !is_null( $min ) || !is_null( $max ) ) {
824 foreach ( $value as &$v ) {
825 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
828 } else {
829 $value = intval( $value );
830 if ( !is_null( $min ) || !is_null( $max ) ) {
831 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
834 break;
835 case 'limit':
836 if ( !$parseLimit ) {
837 // Don't do any validation whatsoever
838 break;
840 if ( !isset( $paramSettings[self::PARAM_MAX] )
841 || !isset( $paramSettings[self::PARAM_MAX2] )
843 ApiBase::dieDebug(
844 __METHOD__,
845 "MAX1 or MAX2 are not defined for the limit $encParamName"
848 if ( $multi ) {
849 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
851 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
852 if ( $value == 'max' ) {
853 $value = $this->getMain()->canApiHighLimits()
854 ? $paramSettings[self::PARAM_MAX2]
855 : $paramSettings[self::PARAM_MAX];
856 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
857 } else {
858 $value = intval( $value );
859 $this->validateLimit(
860 $paramName,
861 $value,
862 $min,
863 $paramSettings[self::PARAM_MAX],
864 $paramSettings[self::PARAM_MAX2]
867 break;
868 case 'boolean':
869 if ( $multi ) {
870 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
872 break;
873 case 'timestamp':
874 if ( is_array( $value ) ) {
875 foreach ( $value as $key => $val ) {
876 $value[$key] = $this->validateTimestamp( $val, $encParamName );
878 } else {
879 $value = $this->validateTimestamp( $value, $encParamName );
881 break;
882 case 'user':
883 if ( is_array( $value ) ) {
884 foreach ( $value as $key => $val ) {
885 $value[$key] = $this->validateUser( $val, $encParamName );
887 } else {
888 $value = $this->validateUser( $value, $encParamName );
890 break;
891 case 'upload': // nothing to do
892 break;
893 default:
894 ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
898 // Throw out duplicates if requested
899 if ( !$dupes && is_array( $value ) ) {
900 $value = array_unique( $value );
903 // Set a warning if a deprecated parameter has been passed
904 if ( $deprecated && $value !== false ) {
905 $this->setWarning( "The $encParamName parameter has been deprecated." );
907 } elseif ( $required ) {
908 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
911 return $value;
915 * Return an array of values that were given in a 'a|b|c' notation,
916 * after it optionally validates them against the list allowed values.
918 * @param string $valueName The name of the parameter (for error
919 * reporting)
920 * @param mixed $value The value being parsed
921 * @param bool $allowMultiple Can $value contain more than one value
922 * separated by '|'?
923 * @param string[]|null $allowedValues An array of values to check against. If
924 * null, all values are accepted.
925 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
927 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
928 if ( trim( $value ) === '' && $allowMultiple ) {
929 return array();
932 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
933 // because it unstubs $wgUser
934 $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 );
935 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits()
936 ? self::LIMIT_SML2
937 : self::LIMIT_SML1;
939 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
940 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
941 "the limit is $sizeLimit" );
944 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
945 // Bug 33482 - Allow entries with | in them for non-multiple values
946 if ( in_array( $value, $allowedValues, true ) ) {
947 return $value;
950 $possibleValues = is_array( $allowedValues )
951 ? "of '" . implode( "', '", $allowedValues ) . "'"
952 : '';
953 $this->dieUsage(
954 "Only one $possibleValues is allowed for parameter '$valueName'",
955 "multival_$valueName"
959 if ( is_array( $allowedValues ) ) {
960 // Check for unknown values
961 $unknown = array_diff( $valuesList, $allowedValues );
962 if ( count( $unknown ) ) {
963 if ( $allowMultiple ) {
964 $s = count( $unknown ) > 1 ? 's' : '';
965 $vals = implode( ", ", $unknown );
966 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
967 } else {
968 $this->dieUsage(
969 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
970 "unknown_$valueName"
974 // Now throw them out
975 $valuesList = array_intersect( $valuesList, $allowedValues );
978 return $allowMultiple ? $valuesList : $valuesList[0];
982 * Validate the value against the minimum and user/bot maximum limits.
983 * Prints usage info on failure.
984 * @param string $paramName Parameter name
985 * @param int $value Parameter value
986 * @param int|null $min Minimum value
987 * @param int|null $max Maximum value for users
988 * @param int $botMax Maximum value for sysops/bots
989 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
991 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
992 if ( !is_null( $min ) && $value < $min ) {
994 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
995 $this->warnOrDie( $msg, $enforceLimits );
996 $value = $min;
999 // Minimum is always validated, whereas maximum is checked only if not
1000 // running in internal call mode
1001 if ( $this->getMain()->isInternalMode() ) {
1002 return;
1005 // Optimization: do not check user's bot status unless really needed -- skips db query
1006 // assumes $botMax >= $max
1007 if ( !is_null( $max ) && $value > $max ) {
1008 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1009 if ( $value > $botMax ) {
1010 $msg = $this->encodeParamName( $paramName ) .
1011 " may not be over $botMax (set to $value) for bots or sysops";
1012 $this->warnOrDie( $msg, $enforceLimits );
1013 $value = $botMax;
1015 } else {
1016 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1017 $this->warnOrDie( $msg, $enforceLimits );
1018 $value = $max;
1024 * Validate and normalize of parameters of type 'timestamp'
1025 * @param string $value Parameter value
1026 * @param string $encParamName Parameter name
1027 * @return string Validated and normalized parameter
1029 protected function validateTimestamp( $value, $encParamName ) {
1030 $unixTimestamp = wfTimestamp( TS_UNIX, $value );
1031 if ( $unixTimestamp === false ) {
1032 $this->dieUsage(
1033 "Invalid value '$value' for timestamp parameter $encParamName",
1034 "badtimestamp_{$encParamName}"
1038 return wfTimestamp( TS_MW, $unixTimestamp );
1042 * Validate the supplied token.
1044 * @since 1.24
1045 * @param string $token Supplied token
1046 * @param array $params All supplied parameters for the module
1047 * @return bool
1048 * @throws MWException
1050 final public function validateToken( $token, array $params ) {
1051 $tokenType = $this->needsToken();
1052 $salts = ApiQueryTokens::getTokenTypeSalts();
1053 if ( !isset( $salts[$tokenType] ) ) {
1054 throw new MWException(
1055 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1056 'without registering it'
1060 if ( $this->getUser()->matchEditToken(
1061 $token,
1062 $salts[$tokenType],
1063 $this->getRequest()
1064 ) ) {
1065 return true;
1068 $webUiSalt = $this->getWebUITokenSalt( $params );
1069 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1070 $token,
1071 $webUiSalt,
1072 $this->getRequest()
1073 ) ) {
1074 return true;
1077 return false;
1081 * Validate and normalize of parameters of type 'user'
1082 * @param string $value Parameter value
1083 * @param string $encParamName Parameter name
1084 * @return string Validated and normalized parameter
1086 private function validateUser( $value, $encParamName ) {
1087 $title = Title::makeTitleSafe( NS_USER, $value );
1088 if ( $title === null ) {
1089 $this->dieUsage(
1090 "Invalid value '$value' for user parameter $encParamName",
1091 "baduser_{$encParamName}"
1095 return $title->getText();
1098 /**@}*/
1100 /************************************************************************//**
1101 * @name Utility methods
1102 * @{
1106 * Set a watch (or unwatch) based the based on a watchlist parameter.
1107 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1108 * @param Title $titleObj The article's title to change
1109 * @param string $userOption The user option to consider when $watch=preferences
1111 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1112 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1113 if ( $value === null ) {
1114 return;
1117 WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1121 * Truncate an array to a certain length.
1122 * @param array $arr Array to truncate
1123 * @param int $limit Maximum length
1124 * @return bool True if the array was truncated, false otherwise
1126 public static function truncateArray( &$arr, $limit ) {
1127 $modified = false;
1128 while ( count( $arr ) > $limit ) {
1129 array_pop( $arr );
1130 $modified = true;
1133 return $modified;
1137 * Gets the user for whom to get the watchlist
1139 * @param array $params
1140 * @return User
1142 public function getWatchlistUser( $params ) {
1143 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1144 $user = User::newFromName( $params['owner'], false );
1145 if ( !( $user && $user->getId() ) ) {
1146 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1148 $token = $user->getOption( 'watchlisttoken' );
1149 if ( $token == '' || $token != $params['token'] ) {
1150 $this->dieUsage(
1151 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1152 'bad_wltoken'
1155 } else {
1156 if ( !$this->getUser()->isLoggedIn() ) {
1157 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1159 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1160 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1162 $user = $this->getUser();
1165 return $user;
1169 * A subset of wfEscapeWikiText for BC texts
1171 * @since 1.25
1172 * @param string|array $v
1173 * @return string|array
1175 private static function escapeWikiText( $v ) {
1176 if ( is_array( $v ) ) {
1177 return array_map( 'self::escapeWikiText', $v );
1178 } else {
1179 return strtr( $v, array(
1180 '__' => '_&#95;', '{' => '&#123;', '}' => '&#125;',
1181 '[[Category:' => '[[:Category:',
1182 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1183 ) );
1188 * Create a Message from a string or array
1190 * A string is used as a message key. An array has the message key as the
1191 * first value and message parameters as subsequent values.
1193 * @since 1.25
1194 * @param string|array|Message $msg
1195 * @param IContextSource $context
1196 * @param array $params
1197 * @return Message|null
1199 public static function makeMessage( $msg, IContextSource $context, array $params = null ) {
1200 if ( is_string( $msg ) ) {
1201 $msg = wfMessage( $msg );
1202 } elseif ( is_array( $msg ) ) {
1203 $msg = call_user_func_array( 'wfMessage', $msg );
1205 if ( !$msg instanceof Message ) {
1206 return null;
1209 $msg->setContext( $context );
1210 if ( $params ) {
1211 $msg->params( $params );
1214 return $msg;
1217 /**@}*/
1219 /************************************************************************//**
1220 * @name Warning and error reporting
1221 * @{
1225 * Set warning section for this module. Users should monitor this
1226 * section to notice any changes in API. Multiple calls to this
1227 * function will result in the warning messages being separated by
1228 * newlines
1229 * @param string $warning Warning message
1231 public function setWarning( $warning ) {
1232 $result = $this->getResult();
1233 $data = $result->getData();
1234 $moduleName = $this->getModuleName();
1235 if ( isset( $data['warnings'][$moduleName] ) ) {
1236 // Don't add duplicate warnings
1237 $oldWarning = $data['warnings'][$moduleName]['*'];
1238 $warnPos = strpos( $oldWarning, $warning );
1239 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
1240 if ( $warnPos !== false && ( $warnPos === 0 || $oldWarning[$warnPos - 1] === "\n" ) ) {
1241 // Check if $warning is followed by "\n" or the end of the $oldWarning
1242 $warnPos += strlen( $warning );
1243 if ( strlen( $oldWarning ) <= $warnPos || $oldWarning[$warnPos] === "\n" ) {
1244 return;
1247 // If there is a warning already, append it to the existing one
1248 $warning = "$oldWarning\n$warning";
1250 $msg = array();
1251 ApiResult::setContent( $msg, $warning );
1252 $result->addValue( 'warnings', $moduleName,
1253 $msg, ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
1257 * Adds a warning to the output, else dies
1259 * @param string $msg Message to show as a warning, or error message if dying
1260 * @param bool $enforceLimits Whether this is an enforce (die)
1262 private function warnOrDie( $msg, $enforceLimits = false ) {
1263 if ( $enforceLimits ) {
1264 $this->dieUsage( $msg, 'integeroutofrange' );
1267 $this->setWarning( $msg );
1271 * Throw a UsageException, which will (if uncaught) call the main module's
1272 * error handler and die with an error message.
1274 * @param string $description One-line human-readable description of the
1275 * error condition, e.g., "The API requires a valid action parameter"
1276 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1277 * automated identification of the error, e.g., 'unknown_action'
1278 * @param int $httpRespCode HTTP response code
1279 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1280 * @throws UsageException
1282 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1283 Profiler::instance()->close();
1284 throw new UsageException(
1285 $description,
1286 $this->encodeParamName( $errorCode ),
1287 $httpRespCode,
1288 $extradata
1293 * Get error (as code, string) from a Status object.
1295 * @since 1.23
1296 * @param Status $status
1297 * @return array Array of code and error string
1298 * @throws MWException
1300 public function getErrorFromStatus( $status ) {
1301 if ( $status->isGood() ) {
1302 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1305 $errors = $status->getErrorsArray();
1306 if ( !$errors ) {
1307 // No errors? Assume the warnings should be treated as errors
1308 $errors = $status->getWarningsArray();
1310 if ( !$errors ) {
1311 // Still no errors? Punt
1312 $errors = array( array( 'unknownerror-nocode' ) );
1315 // Cannot use dieUsageMsg() because extensions might return custom
1316 // error messages.
1317 if ( $errors[0] instanceof Message ) {
1318 $msg = $errors[0];
1319 $code = $msg->getKey();
1320 } else {
1321 $code = array_shift( $errors[0] );
1322 $msg = wfMessage( $code, $errors[0] );
1324 if ( isset( ApiBase::$messageMap[$code] ) ) {
1325 // Translate message to code, for backwards compatibility
1326 $code = ApiBase::$messageMap[$code]['code'];
1329 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1333 * Throw a UsageException based on the errors in the Status object.
1335 * @since 1.22
1336 * @param Status $status
1337 * @throws MWException
1339 public function dieStatus( $status ) {
1341 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1342 $this->dieUsage( $msg, $code );
1345 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1347 * Array that maps message keys to error messages. $1 and friends are replaced.
1349 public static $messageMap = array(
1350 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1351 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1352 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1354 // Messages from Title::getUserPermissionsErrors()
1355 'ns-specialprotected' => array(
1356 'code' => 'unsupportednamespace',
1357 'info' => "Pages in the Special namespace can't be edited"
1359 'protectedinterface' => array(
1360 'code' => 'protectednamespace-interface',
1361 'info' => "You're not allowed to edit interface messages"
1363 'namespaceprotected' => array(
1364 'code' => 'protectednamespace',
1365 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1367 'customcssprotected' => array(
1368 'code' => 'customcssprotected',
1369 'info' => "You're not allowed to edit custom CSS pages"
1371 'customjsprotected' => array(
1372 'code' => 'customjsprotected',
1373 'info' => "You're not allowed to edit custom JavaScript pages"
1375 'cascadeprotected' => array(
1376 'code' => 'cascadeprotected',
1377 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1379 'protectedpagetext' => array(
1380 'code' => 'protectedpage',
1381 'info' => "The \"\$1\" right is required to edit this page"
1383 'protect-cantedit' => array(
1384 'code' => 'cantedit',
1385 'info' => "You can't protect this page because you can't edit it"
1387 'deleteprotected' => array(
1388 'code' => 'cantedit',
1389 'info' => "You can't delete this page because it has been protected"
1391 'badaccess-group0' => array(
1392 'code' => 'permissiondenied',
1393 'info' => "Permission denied"
1394 ), // Generic permission denied message
1395 'badaccess-groups' => array(
1396 'code' => 'permissiondenied',
1397 'info' => "Permission denied"
1399 'titleprotected' => array(
1400 'code' => 'protectedtitle',
1401 'info' => "This title has been protected from creation"
1403 'nocreate-loggedin' => array(
1404 'code' => 'cantcreate',
1405 'info' => "You don't have permission to create new pages"
1407 'nocreatetext' => array(
1408 'code' => 'cantcreate-anon',
1409 'info' => "Anonymous users can't create new pages"
1411 'movenologintext' => array(
1412 'code' => 'cantmove-anon',
1413 'info' => "Anonymous users can't move pages"
1415 'movenotallowed' => array(
1416 'code' => 'cantmove',
1417 'info' => "You don't have permission to move pages"
1419 'confirmedittext' => array(
1420 'code' => 'confirmemail',
1421 'info' => "You must confirm your email address before you can edit"
1423 'blockedtext' => array(
1424 'code' => 'blocked',
1425 'info' => "You have been blocked from editing"
1427 'autoblockedtext' => array(
1428 'code' => 'autoblocked',
1429 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1432 // Miscellaneous interface messages
1433 'actionthrottledtext' => array(
1434 'code' => 'ratelimited',
1435 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1437 'alreadyrolled' => array(
1438 'code' => 'alreadyrolled',
1439 'info' => "The page you tried to rollback was already rolled back"
1441 'cantrollback' => array(
1442 'code' => 'onlyauthor',
1443 'info' => "The page you tried to rollback only has one author"
1445 'readonlytext' => array(
1446 'code' => 'readonly',
1447 'info' => "The wiki is currently in read-only mode"
1449 'sessionfailure' => array(
1450 'code' => 'badtoken',
1451 'info' => "Invalid token" ),
1452 'cannotdelete' => array(
1453 'code' => 'cantdelete',
1454 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1456 'notanarticle' => array(
1457 'code' => 'missingtitle',
1458 'info' => "The page you requested doesn't exist"
1460 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1462 'immobile_namespace' => array(
1463 'code' => 'immobilenamespace',
1464 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1466 'articleexists' => array(
1467 'code' => 'articleexists',
1468 'info' => "The destination article already exists and is not a redirect to the source article"
1470 'protectedpage' => array(
1471 'code' => 'protectedpage',
1472 'info' => "You don't have permission to perform this move"
1474 'hookaborted' => array(
1475 'code' => 'hookaborted',
1476 'info' => "The modification you tried to make was aborted by an extension hook"
1478 'cantmove-titleprotected' => array(
1479 'code' => 'protectedtitle',
1480 'info' => "The destination article has been protected from creation"
1482 'imagenocrossnamespace' => array(
1483 'code' => 'nonfilenamespace',
1484 'info' => "Can't move a file to a non-file namespace"
1486 'imagetypemismatch' => array(
1487 'code' => 'filetypemismatch',
1488 'info' => "The new file extension doesn't match its type"
1490 // 'badarticleerror' => shouldn't happen
1491 // 'badtitletext' => shouldn't happen
1492 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1493 'range_block_disabled' => array(
1494 'code' => 'rangedisabled',
1495 'info' => "Blocking IP ranges has been disabled"
1497 'nosuchusershort' => array(
1498 'code' => 'nosuchuser',
1499 'info' => "The user you specified doesn't exist"
1501 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1502 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1503 'ipb_already_blocked' => array(
1504 'code' => 'alreadyblocked',
1505 'info' => "The user you tried to block was already blocked"
1507 'ipb_blocked_as_range' => array(
1508 'code' => 'blockedasrange',
1509 '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."
1511 'ipb_cant_unblock' => array(
1512 'code' => 'cantunblock',
1513 'info' => "The block you specified was not found. It may have been unblocked already"
1515 'mailnologin' => array(
1516 'code' => 'cantsend',
1517 '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"
1519 'ipbblocked' => array(
1520 'code' => 'ipbblocked',
1521 'info' => 'You cannot block or unblock users while you are yourself blocked'
1523 'ipbnounblockself' => array(
1524 'code' => 'ipbnounblockself',
1525 'info' => 'You are not allowed to unblock yourself'
1527 'usermaildisabled' => array(
1528 'code' => 'usermaildisabled',
1529 'info' => "User email has been disabled"
1531 'blockedemailuser' => array(
1532 'code' => 'blockedfrommail',
1533 'info' => "You have been blocked from sending email"
1535 'notarget' => array(
1536 'code' => 'notarget',
1537 'info' => "You have not specified a valid target for this action"
1539 'noemail' => array(
1540 'code' => 'noemail',
1541 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1543 'rcpatroldisabled' => array(
1544 'code' => 'patroldisabled',
1545 'info' => "Patrolling is disabled on this wiki"
1547 'markedaspatrollederror-noautopatrol' => array(
1548 'code' => 'noautopatrol',
1549 'info' => "You don't have permission to patrol your own changes"
1551 'delete-toobig' => array(
1552 'code' => 'bigdelete',
1553 'info' => "You can't delete this page because it has more than \$1 revisions"
1555 'movenotallowedfile' => array(
1556 'code' => 'cantmovefile',
1557 'info' => "You don't have permission to move files"
1559 'userrights-no-interwiki' => array(
1560 'code' => 'nointerwikiuserrights',
1561 'info' => "You don't have permission to change user rights on other wikis"
1563 'userrights-nodatabase' => array(
1564 'code' => 'nosuchdatabase',
1565 'info' => "Database \"\$1\" does not exist or is not local"
1567 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1568 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1569 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1570 'import-rootpage-invalid' => array(
1571 'code' => 'import-rootpage-invalid',
1572 'info' => 'Root page is an invalid title'
1574 'import-rootpage-nosubpage' => array(
1575 'code' => 'import-rootpage-nosubpage',
1576 'info' => 'Namespace "$1" of the root page does not allow subpages'
1579 // API-specific messages
1580 'readrequired' => array(
1581 'code' => 'readapidenied',
1582 'info' => "You need read permission to use this module"
1584 'writedisabled' => array(
1585 'code' => 'noapiwrite',
1586 '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"
1588 'writerequired' => array(
1589 'code' => 'writeapidenied',
1590 'info' => "You're not allowed to edit this wiki through the API"
1592 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1593 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1594 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1595 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1596 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1597 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1598 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1599 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1600 'create-titleexists' => array(
1601 'code' => 'create-titleexists',
1602 'info' => "Existing titles can't be protected with 'create'"
1604 'missingtitle-createonly' => array(
1605 'code' => 'missingtitle-createonly',
1606 'info' => "Missing titles can only be protected with 'create'"
1608 'cantblock' => array( 'code' => 'cantblock',
1609 'info' => "You don't have permission to block users"
1611 'canthide' => array(
1612 'code' => 'canthide',
1613 'info' => "You don't have permission to hide user names from the block log"
1615 'cantblock-email' => array(
1616 'code' => 'cantblock-email',
1617 'info' => "You don't have permission to block users from sending email through the wiki"
1619 'unblock-notarget' => array(
1620 'code' => 'notarget',
1621 'info' => "Either the id or the user parameter must be set"
1623 'unblock-idanduser' => array(
1624 'code' => 'idanduser',
1625 'info' => "The id and user parameters can't be used together"
1627 'cantunblock' => array(
1628 'code' => 'permissiondenied',
1629 'info' => "You don't have permission to unblock users"
1631 'cannotundelete' => array(
1632 'code' => 'cantundelete',
1633 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1635 'permdenied-undelete' => array(
1636 'code' => 'permissiondenied',
1637 'info' => "You don't have permission to restore deleted revisions"
1639 'createonly-exists' => array(
1640 'code' => 'articleexists',
1641 'info' => "The article you tried to create has been created already"
1643 'nocreate-missing' => array(
1644 'code' => 'missingtitle',
1645 'info' => "The article you tried to edit doesn't exist"
1647 'cantchangecontentmodel' => array(
1648 'code' => 'cantchangecontentmodel',
1649 'info' => "You don't have permission to change the content model of a page"
1651 'nosuchrcid' => array(
1652 'code' => 'nosuchrcid',
1653 'info' => "There is no change with rcid \"\$1\""
1655 'protect-invalidaction' => array(
1656 'code' => 'protect-invalidaction',
1657 'info' => "Invalid protection type \"\$1\""
1659 'protect-invalidlevel' => array(
1660 'code' => 'protect-invalidlevel',
1661 'info' => "Invalid protection level \"\$1\""
1663 'toofewexpiries' => array(
1664 'code' => 'toofewexpiries',
1665 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1667 'cantimport' => array(
1668 'code' => 'cantimport',
1669 'info' => "You don't have permission to import pages"
1671 'cantimport-upload' => array(
1672 'code' => 'cantimport-upload',
1673 'info' => "You don't have permission to import uploaded pages"
1675 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1676 'importuploaderrorsize' => array(
1677 'code' => 'filetoobig',
1678 'info' => 'The file you uploaded is bigger than the maximum upload size'
1680 'importuploaderrorpartial' => array(
1681 'code' => 'partialupload',
1682 'info' => 'The file was only partially uploaded'
1684 'importuploaderrortemp' => array(
1685 'code' => 'notempdir',
1686 'info' => 'The temporary upload directory is missing'
1688 'importcantopen' => array(
1689 'code' => 'cantopenfile',
1690 'info' => "Couldn't open the uploaded file"
1692 'import-noarticle' => array(
1693 'code' => 'badinterwiki',
1694 'info' => 'Invalid interwiki title specified'
1696 'importbadinterwiki' => array(
1697 'code' => 'badinterwiki',
1698 'info' => 'Invalid interwiki title specified'
1700 'import-unknownerror' => array(
1701 'code' => 'import-unknownerror',
1702 'info' => "Unknown error on import: \"\$1\""
1704 'cantoverwrite-sharedfile' => array(
1705 'code' => 'cantoverwrite-sharedfile',
1706 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1708 'sharedfile-exists' => array(
1709 'code' => 'fileexists-sharedrepo-perm',
1710 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1712 'mustbeposted' => array(
1713 'code' => 'mustbeposted',
1714 'info' => "The \$1 module requires a POST request"
1716 'show' => array(
1717 'code' => 'show',
1718 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1720 'specialpage-cantexecute' => array(
1721 'code' => 'specialpage-cantexecute',
1722 'info' => "You don't have permission to view the results of this special page"
1724 'invalidoldimage' => array(
1725 'code' => 'invalidoldimage',
1726 'info' => 'The oldimage parameter has invalid format'
1728 'nodeleteablefile' => array(
1729 'code' => 'nodeleteablefile',
1730 'info' => 'No such old version of the file'
1732 'fileexists-forbidden' => array(
1733 'code' => 'fileexists-forbidden',
1734 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1736 'fileexists-shared-forbidden' => array(
1737 'code' => 'fileexists-shared-forbidden',
1738 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1740 'filerevert-badversion' => array(
1741 'code' => 'filerevert-badversion',
1742 'info' => 'There is no previous local version of this file with the provided timestamp.'
1745 // ApiEditPage messages
1746 'noimageredirect-anon' => array(
1747 'code' => 'noimageredirect-anon',
1748 'info' => "Anonymous users can't create image redirects"
1750 'noimageredirect-logged' => array(
1751 'code' => 'noimageredirect',
1752 'info' => "You don't have permission to create image redirects"
1754 'spamdetected' => array(
1755 'code' => 'spamdetected',
1756 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1758 'contenttoobig' => array(
1759 'code' => 'contenttoobig',
1760 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1762 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1763 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1764 'wasdeleted' => array(
1765 'code' => 'pagedeleted',
1766 'info' => "The page has been deleted since you fetched its timestamp"
1768 'blankpage' => array(
1769 'code' => 'emptypage',
1770 'info' => "Creating new, empty pages is not allowed"
1772 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1773 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1774 'missingtext' => array(
1775 'code' => 'notext',
1776 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1778 'emptynewsection' => array(
1779 'code' => 'emptynewsection',
1780 'info' => 'Creating empty new sections is not possible.'
1782 'revwrongpage' => array(
1783 'code' => 'revwrongpage',
1784 'info' => "r\$1 is not a revision of \"\$2\""
1786 'undo-failure' => array(
1787 'code' => 'undofailure',
1788 'info' => 'Undo failed due to conflicting intermediate edits'
1790 'content-not-allowed-here' => array(
1791 'code' => 'contentnotallowedhere',
1792 'info' => 'Content model "$1" is not allowed at title "$2"'
1795 // Messages from WikiPage::doEit()
1796 'edit-hook-aborted' => array(
1797 'code' => 'edit-hook-aborted',
1798 'info' => "Your edit was aborted by an ArticleSave hook"
1800 'edit-gone-missing' => array(
1801 'code' => 'edit-gone-missing',
1802 'info' => "The page you tried to edit doesn't seem to exist anymore"
1804 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1805 'edit-already-exists' => array(
1806 'code' => 'edit-already-exists',
1807 'info' => 'It seems the page you tried to create already exist'
1810 // uploadMsgs
1811 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1812 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1813 'uploaddisabled' => array(
1814 'code' => 'uploaddisabled',
1815 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1817 'copyuploaddisabled' => array(
1818 'code' => 'copyuploaddisabled',
1819 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1821 'copyuploadbaddomain' => array(
1822 'code' => 'copyuploadbaddomain',
1823 'info' => 'Uploads by URL are not allowed from this domain.'
1825 'copyuploadbadurl' => array(
1826 'code' => 'copyuploadbadurl',
1827 'info' => 'Upload not allowed from this URL.'
1830 'filename-tooshort' => array(
1831 'code' => 'filename-tooshort',
1832 'info' => 'The filename is too short'
1834 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1835 'illegal-filename' => array(
1836 'code' => 'illegal-filename',
1837 'info' => 'The filename is not allowed'
1839 'filetype-missing' => array(
1840 'code' => 'filetype-missing',
1841 'info' => 'The file is missing an extension'
1844 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1846 // @codingStandardsIgnoreEnd
1849 * Helper function for readonly errors
1851 public function dieReadOnly() {
1852 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1853 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1854 array( 'readonlyreason' => wfReadOnlyReason() ) );
1858 * Output the error message related to a certain array
1859 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1861 public function dieUsageMsg( $error ) {
1862 # most of the time we send a 1 element, so we might as well send it as
1863 # a string and make this an array here.
1864 if ( is_string( $error ) ) {
1865 $error = array( $error );
1867 $parsed = $this->parseMsg( $error );
1868 $this->dieUsage( $parsed['info'], $parsed['code'] );
1872 * Will only set a warning instead of failing if the global $wgDebugAPI
1873 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1874 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1875 * @since 1.21
1877 public function dieUsageMsgOrDebug( $error ) {
1878 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1879 $this->dieUsageMsg( $error );
1882 if ( is_string( $error ) ) {
1883 $error = array( $error );
1885 $parsed = $this->parseMsg( $error );
1886 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1890 * Die with the $prefix.'badcontinue' error. This call is common enough to
1891 * make it into the base method.
1892 * @param bool $condition Will only die if this value is true
1893 * @since 1.21
1895 protected function dieContinueUsageIf( $condition ) {
1896 if ( $condition ) {
1897 $this->dieUsage(
1898 'Invalid continue param. You should pass the original value returned by the previous query',
1899 'badcontinue' );
1904 * Return the error message related to a certain array
1905 * @param array $error Element of a getUserPermissionsErrors()-style array
1906 * @return array('code' => code, 'info' => info)
1908 public function parseMsg( $error ) {
1909 $error = (array)$error; // It seems strings sometimes make their way in here
1910 $key = array_shift( $error );
1912 // Check whether the error array was nested
1913 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1914 if ( is_array( $key ) ) {
1915 $error = $key;
1916 $key = array_shift( $error );
1919 if ( isset( self::$messageMap[$key] ) ) {
1920 return array(
1921 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
1922 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
1926 // If the key isn't present, throw an "unknown error"
1927 return $this->parseMsg( array( 'unknownerror', $key ) );
1931 * Internal code errors should be reported with this method
1932 * @param string $method Method or function name
1933 * @param string $message Error message
1934 * @throws MWException
1936 protected static function dieDebug( $method, $message ) {
1937 throw new MWException( "Internal error in $method: $message" );
1940 /**@}*/
1942 /************************************************************************//**
1943 * @name Help message generation
1944 * @{
1948 * Return the description message.
1950 * @return string|array|Message
1952 protected function getDescriptionMessage() {
1953 return "apihelp-{$this->getModulePath()}-description";
1957 * Get final module description, after hooks have had a chance to tweak it as
1958 * needed.
1960 * @since 1.25, returns Message[] rather than string[]
1961 * @return Message[]
1963 public function getFinalDescription() {
1964 $desc = $this->getDescription();
1965 Hooks::run( 'APIGetDescription', array( &$this, &$desc ) );
1966 $desc = self::escapeWikiText( $desc );
1967 if ( is_array( $desc ) ) {
1968 $desc = join( "\n", $desc );
1969 } else {
1970 $desc = (string)$desc;
1973 $msg = ApiBase::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
1974 $this->getModulePrefix(),
1975 $this->getModuleName(),
1976 $this->getModulePath(),
1977 ) );
1978 if ( !$msg->exists() ) {
1979 $msg = $this->msg( 'api-help-fallback-description', $desc );
1981 $msgs = array( $msg );
1983 Hooks::run( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
1985 return $msgs;
1989 * Get final list of parameters, after hooks have had a chance to
1990 * tweak it as needed.
1992 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
1993 * @return array|bool False on no parameters
1994 * @since 1.21 $flags param added
1996 public function getFinalParams( $flags = 0 ) {
1997 $params = $this->getAllowedParams( $flags );
1998 if ( !$params ) {
1999 $params = array();
2002 if ( $this->needsToken() ) {
2003 $params['token'] = array(
2004 ApiBase::PARAM_TYPE => 'string',
2005 ApiBase::PARAM_REQUIRED => true,
2006 ApiBase::PARAM_HELP_MSG => array(
2007 'api-help-param-token',
2008 $this->needsToken(),
2010 ) + ( isset( $params['token'] ) ? $params['token'] : array() );
2013 Hooks::run( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2015 return $params;
2019 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2020 * needed.
2022 * @since 1.25, returns array of Message[] rather than array of string[]
2023 * @return array Keys are parameter names, values are arrays of Message objects
2025 public function getFinalParamDescription() {
2026 $prefix = $this->getModulePrefix();
2027 $name = $this->getModuleName();
2028 $path = $this->getModulePath();
2030 $desc = $this->getParamDescription();
2031 Hooks::run( 'APIGetParamDescription', array( &$this, &$desc ) );
2033 if ( !$desc ) {
2034 $desc = array();
2036 $desc = self::escapeWikiText( $desc );
2038 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
2039 $msgs = array();
2040 foreach ( $params as $param => $settings ) {
2041 if ( !is_array( $settings ) ) {
2042 $settings = array();
2045 $d = isset( $desc[$param] ) ? $desc[$param] : '';
2046 if ( is_array( $d ) ) {
2047 // Special handling for prop parameters
2048 $d = array_map( function ( $line ) {
2049 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2050 $line = "\n;{$m[1]}:{$m[2]}";
2052 return $line;
2053 }, $d );
2054 $d = join( ' ', $d );
2057 if ( isset( $settings[ApiBase::PARAM_HELP_MSG] ) ) {
2058 $msg = $settings[ApiBase::PARAM_HELP_MSG];
2059 } else {
2060 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2061 if ( !$msg->exists() ) {
2062 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2065 $msg = ApiBase::makeMessage( $msg, $this->getContext(),
2066 array( $prefix, $param, $name, $path ) );
2067 if ( !$msg ) {
2068 $this->dieDebug( __METHOD__,
2069 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2071 $msgs[$param] = array( $msg );
2073 if ( isset( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
2074 if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
2075 $this->dieDebug( __METHOD__,
2076 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2078 if ( !is_array( $settings[ApiBase::PARAM_TYPE] ) ) {
2079 $this->dieDebug( __METHOD__,
2080 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2081 'ApiBase::PARAM_TYPE is an array' );
2084 $valueMsgs = $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE];
2085 foreach ( $settings[ApiBase::PARAM_TYPE] as $value ) {
2086 if ( isset( $valueMsgs[$value] ) ) {
2087 $msg = $valueMsgs[$value];
2088 } else {
2089 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2091 $m = ApiBase::makeMessage( $msg, $this->getContext(),
2092 array( $prefix, $param, $name, $path, $value ) );
2093 if ( $m ) {
2094 $m = new ApiHelpParamValueMessage(
2095 $value,
2096 array( $m->getKey(), 'api-help-param-no-description' ),
2097 $m->getParams()
2099 $msgs[$param][] = $m->setContext( $this->getContext() );
2100 } else {
2101 $this->dieDebug( __METHOD__,
2102 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2107 if ( isset( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2108 if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2109 $this->dieDebug( __METHOD__,
2110 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2112 foreach ( $settings[ApiBase::PARAM_HELP_MSG_APPEND] as $m ) {
2113 $m = ApiBase::makeMessage( $m, $this->getContext(),
2114 array( $prefix, $param, $name, $path ) );
2115 if ( $m ) {
2116 $msgs[$param][] = $m;
2117 } else {
2118 $this->dieDebug( __METHOD__,
2119 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2125 Hooks::run( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2127 return $msgs;
2131 * Generates the list of flags for the help screen and for action=paraminfo
2133 * Corresponding messages: api-help-flag-deprecated,
2134 * api-help-flag-internal, api-help-flag-readrights,
2135 * api-help-flag-writerights, api-help-flag-mustbeposted
2137 * @return string[]
2139 protected function getHelpFlags() {
2140 $flags = array();
2142 if ( $this->isDeprecated() ) {
2143 $flags[] = 'deprecated';
2145 if ( $this->isInternal() ) {
2146 $flags[] = 'internal';
2148 if ( $this->isReadMode() ) {
2149 $flags[] = 'readrights';
2151 if ( $this->isWriteMode() ) {
2152 $flags[] = 'writerights';
2154 if ( $this->mustBePosted() ) {
2155 $flags[] = 'mustbeposted';
2158 return $flags;
2162 * Called from ApiHelp before the pieces are joined together and returned.
2164 * This exists mainly for ApiMain to add the Permissions and Credits
2165 * sections. Other modules probably don't need it.
2167 * @param string[] &$help Array of help data
2168 * @param array $options Options passed to ApiHelp::getHelp
2170 public function modifyHelp( array &$help, array $options ) {
2173 /**@}*/
2175 /************************************************************************//**
2176 * @name Profiling
2177 * @{
2181 * Profiling: total module execution time
2183 private $mTimeIn = 0, $mModuleTime = 0;
2186 * Get the name of the module as shown in the profiler log
2188 * @param DatabaseBase|bool $db
2190 * @return string
2192 public function getModuleProfileName( $db = false ) {
2193 if ( $db ) {
2194 return 'API:' . $this->mModuleName . '-DB';
2197 return 'API:' . $this->mModuleName;
2201 * Start module profiling
2203 public function profileIn() {
2204 if ( $this->mTimeIn !== 0 ) {
2205 ApiBase::dieDebug( __METHOD__, 'Called twice without calling profileOut()' );
2207 $this->mTimeIn = microtime( true );
2208 wfProfileIn( $this->getModuleProfileName() );
2212 * End module profiling
2214 public function profileOut() {
2215 if ( $this->mTimeIn === 0 ) {
2216 ApiBase::dieDebug( __METHOD__, 'Called without calling profileIn() first' );
2218 if ( $this->mDBTimeIn !== 0 ) {
2219 ApiBase::dieDebug(
2220 __METHOD__,
2221 'Must be called after database profiling is done with profileDBOut()'
2225 $this->mModuleTime += microtime( true ) - $this->mTimeIn;
2226 $this->mTimeIn = 0;
2227 wfProfileOut( $this->getModuleProfileName() );
2231 * When modules crash, sometimes it is needed to do a profileOut() regardless
2232 * of the profiling state the module was in. This method does such cleanup.
2234 public function safeProfileOut() {
2235 if ( $this->mTimeIn !== 0 ) {
2236 if ( $this->mDBTimeIn !== 0 ) {
2237 $this->profileDBOut();
2239 $this->profileOut();
2244 * Total time the module was executed
2245 * @return float
2247 public function getProfileTime() {
2248 if ( $this->mTimeIn !== 0 ) {
2249 ApiBase::dieDebug( __METHOD__, 'Called without calling profileOut() first' );
2252 return $this->mModuleTime;
2256 * Profiling: database execution time
2258 private $mDBTimeIn = 0, $mDBTime = 0;
2261 * Start module profiling
2263 public function profileDBIn() {
2264 if ( $this->mTimeIn === 0 ) {
2265 ApiBase::dieDebug(
2266 __METHOD__,
2267 'Must be called while profiling the entire module with profileIn()'
2270 if ( $this->mDBTimeIn !== 0 ) {
2271 ApiBase::dieDebug( __METHOD__, 'Called twice without calling profileDBOut()' );
2273 $this->mDBTimeIn = microtime( true );
2274 wfProfileIn( $this->getModuleProfileName( true ) );
2278 * End database profiling
2280 public function profileDBOut() {
2281 if ( $this->mTimeIn === 0 ) {
2282 ApiBase::dieDebug( __METHOD__, 'Must be called while profiling ' .
2283 'the entire module with profileIn()' );
2285 if ( $this->mDBTimeIn === 0 ) {
2286 ApiBase::dieDebug( __METHOD__, 'Called without calling profileDBIn() first' );
2289 $time = microtime( true ) - $this->mDBTimeIn;
2290 $this->mDBTimeIn = 0;
2292 $this->mDBTime += $time;
2293 $this->getMain()->mDBTime += $time;
2294 wfProfileOut( $this->getModuleProfileName( true ) );
2298 * Total time the module used the database
2299 * @return float
2301 public function getProfileDBTime() {
2302 if ( $this->mDBTimeIn !== 0 ) {
2303 ApiBase::dieDebug( __METHOD__, 'Called without calling profileDBOut() first' );
2306 return $this->mDBTime;
2310 * Write logging information for API features to a debug log, for usage
2311 * analysis.
2312 * @param string $feature Feature being used.
2314 protected function logFeatureUsage( $feature ) {
2315 $request = $this->getRequest();
2316 $s = '"' . addslashes( $feature ) . '"' .
2317 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2318 ' "' . $request->getIP() . '"' .
2319 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2320 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2321 wfDebugLog( 'api-feature-usage', $s, 'private' );
2324 /**@}*/
2326 /************************************************************************//**
2327 * @name Deprecated
2328 * @{
2331 /// @deprecated since 1.24
2332 const PROP_ROOT = 'ROOT';
2333 /// @deprecated since 1.24
2334 const PROP_LIST = 'LIST';
2335 /// @deprecated since 1.24
2336 const PROP_TYPE = 0;
2337 /// @deprecated since 1.24
2338 const PROP_NULLABLE = 1;
2341 * Formerly returned a string that identifies the version of the extending
2342 * class. Typically included the class name, the svn revision, timestamp,
2343 * and last author. Usually done with SVN's Id keyword
2345 * @deprecated since 1.21, version string is no longer supported
2346 * @return string
2348 public function getVersion() {
2349 wfDeprecated( __METHOD__, '1.21' );
2350 return '';
2354 * Formerly used to fetch a list of possible properites in the result,
2355 * somehow organized with respect to the prop parameter that causes them to
2356 * be returned. The specific semantics of the return value was never
2357 * specified. Since this was never possible to be accurately updated, it
2358 * has been removed.
2360 * @deprecated since 1.24
2361 * @return array|bool
2363 protected function getResultProperties() {
2364 wfDeprecated( __METHOD__, '1.24' );
2365 return false;
2369 * @see self::getResultProperties()
2370 * @deprecated since 1.24
2371 * @return array|bool
2373 public function getFinalResultProperties() {
2374 wfDeprecated( __METHOD__, '1.24' );
2375 return array();
2379 * @see self::getResultProperties()
2380 * @deprecated since 1.24
2382 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2383 wfDeprecated( __METHOD__, '1.24' );
2387 * @see self::getPossibleErrors()
2388 * @deprecated since 1.24
2389 * @return array
2391 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2392 wfDeprecated( __METHOD__, '1.24' );
2393 return array();
2397 * @see self::getPossibleErrors()
2398 * @deprecated since 1.24
2399 * @return array
2401 public function getRequireMaxOneParameterErrorMessages( $params ) {
2402 wfDeprecated( __METHOD__, '1.24' );
2403 return array();
2407 * @see self::getPossibleErrors()
2408 * @deprecated since 1.24
2409 * @return array
2411 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2412 wfDeprecated( __METHOD__, '1.24' );
2413 return array();
2417 * @see self::getPossibleErrors()
2418 * @deprecated since 1.24
2419 * @return array
2421 public function getTitleOrPageIdErrorMessage() {
2422 wfDeprecated( __METHOD__, '1.24' );
2423 return array();
2427 * This formerly attempted to return a list of all possible errors returned
2428 * by the module. However, this was impossible to maintain in many cases
2429 * since errors could come from other areas of MediaWiki and in some cases
2430 * from arbitrary extension hooks. Since a partial list claiming to be
2431 * comprehensive is unlikely to be useful, it was removed.
2433 * @deprecated since 1.24
2434 * @return array
2436 public function getPossibleErrors() {
2437 wfDeprecated( __METHOD__, '1.24' );
2438 return array();
2442 * @see self::getPossibleErrors()
2443 * @deprecated since 1.24
2444 * @return array
2446 public function getFinalPossibleErrors() {
2447 wfDeprecated( __METHOD__, '1.24' );
2448 return array();
2452 * @see self::getPossibleErrors()
2453 * @deprecated since 1.24
2454 * @return array
2456 public function parseErrors( $errors ) {
2457 wfDeprecated( __METHOD__, '1.24' );
2458 return array();
2462 * Returns the description string for this module
2464 * Ignored if an i18n message exists for
2465 * "apihelp-{$this->getModulePathString()}-description".
2467 * @deprecated since 1.25
2468 * @return Message|string|array
2470 protected function getDescription() {
2471 return false;
2475 * Returns an array of parameter descriptions.
2477 * For each parameter, ignored if an i18n message exists for the parameter.
2478 * By default that message is
2479 * "apihelp-{$this->getModulePathString()}-param-{$param}", but it may be
2480 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2481 * self::getFinalParams().
2483 * @deprecated since 1.25
2484 * @return array|bool False on no parameter descriptions
2486 protected function getParamDescription() {
2487 return array();
2491 * Returns usage examples for this module.
2493 * Return value as an array is either:
2494 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2495 * values
2496 * - sequential numeric keys with even-numbered keys being display-text
2497 * and odd-numbered keys being partial urls
2498 * - partial URLs as keys with display-text (string or array-to-be-joined)
2499 * as values
2500 * Return value as a string is the same as an array with a numeric key and
2501 * that value, and boolean false means "no examples".
2503 * @deprecated since 1.25, use getExamplesMessages() instead
2504 * @return bool|string|array
2506 protected function getExamples() {
2507 return false;
2511 * Generates help message for this module, or false if there is no description
2512 * @deprecated since 1.25
2513 * @return string|bool
2515 public function makeHelpMsg() {
2516 wfDeprecated( __METHOD__, '1.25' );
2517 static $lnPrfx = "\n ";
2519 $msg = $this->getFinalDescription();
2521 if ( $msg !== false ) {
2523 if ( !is_array( $msg ) ) {
2524 $msg = array(
2525 $msg
2528 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2530 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2532 if ( $this->isReadMode() ) {
2533 $msg .= "\nThis module requires read rights";
2535 if ( $this->isWriteMode() ) {
2536 $msg .= "\nThis module requires write rights";
2538 if ( $this->mustBePosted() ) {
2539 $msg .= "\nThis module only accepts POST requests";
2541 if ( $this->isReadMode() || $this->isWriteMode() ||
2542 $this->mustBePosted()
2544 $msg .= "\n";
2547 // Parameters
2548 $paramsMsg = $this->makeHelpMsgParameters();
2549 if ( $paramsMsg !== false ) {
2550 $msg .= "Parameters:\n$paramsMsg";
2553 $examples = $this->getExamples();
2554 if ( $examples ) {
2555 if ( !is_array( $examples ) ) {
2556 $examples = array(
2557 $examples
2560 $msg .= "Example" . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
2561 foreach ( $examples as $k => $v ) {
2562 if ( is_numeric( $k ) ) {
2563 $msg .= " $v\n";
2564 } else {
2565 if ( is_array( $v ) ) {
2566 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2567 } else {
2568 $msgExample = " $v";
2570 $msgExample .= ":";
2571 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2577 return $msg;
2581 * @deprecated since 1.25
2582 * @param string $item
2583 * @return string
2585 private function indentExampleText( $item ) {
2586 return " " . $item;
2590 * @deprecated since 1.25
2591 * @param string $prefix Text to split output items
2592 * @param string $title What is being output
2593 * @param string|array $input
2594 * @return string
2596 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2597 wfDeprecated( __METHOD__, '1.25' );
2598 if ( $input === false ) {
2599 return '';
2601 if ( !is_array( $input ) ) {
2602 $input = array( $input );
2605 if ( count( $input ) > 0 ) {
2606 if ( $title ) {
2607 $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n ";
2608 } else {
2609 $msg = ' ';
2611 $msg .= implode( $prefix, $input ) . "\n";
2613 return $msg;
2616 return '';
2620 * Generates the parameter descriptions for this module, to be displayed in the
2621 * module's help.
2622 * @deprecated since 1.25
2623 * @return string|bool
2625 public function makeHelpMsgParameters() {
2626 wfDeprecated( __METHOD__, '1.25' );
2627 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
2628 if ( $params ) {
2630 $paramsDescription = $this->getFinalParamDescription();
2631 $msg = '';
2632 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2633 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2634 foreach ( $params as $paramName => $paramSettings ) {
2635 $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
2636 if ( is_array( $desc ) ) {
2637 $desc = implode( $paramPrefix, $desc );
2640 //handle shorthand
2641 if ( !is_array( $paramSettings ) ) {
2642 $paramSettings = array(
2643 self::PARAM_DFLT => $paramSettings,
2647 //handle missing type
2648 if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) {
2649 $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] )
2650 ? $paramSettings[ApiBase::PARAM_DFLT]
2651 : null;
2652 if ( is_bool( $dflt ) ) {
2653 $paramSettings[ApiBase::PARAM_TYPE] = 'boolean';
2654 } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
2655 $paramSettings[ApiBase::PARAM_TYPE] = 'string';
2656 } elseif ( is_int( $dflt ) ) {
2657 $paramSettings[ApiBase::PARAM_TYPE] = 'integer';
2661 if ( isset( $paramSettings[self::PARAM_DEPRECATED] )
2662 && $paramSettings[self::PARAM_DEPRECATED]
2664 $desc = "DEPRECATED! $desc";
2667 if ( isset( $paramSettings[self::PARAM_REQUIRED] )
2668 && $paramSettings[self::PARAM_REQUIRED]
2670 $desc .= $paramPrefix . "This parameter is required";
2673 $type = isset( $paramSettings[self::PARAM_TYPE] )
2674 ? $paramSettings[self::PARAM_TYPE]
2675 : null;
2676 if ( isset( $type ) ) {
2677 $hintPipeSeparated = true;
2678 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
2679 ? $paramSettings[self::PARAM_ISMULTI]
2680 : false;
2681 if ( $multi ) {
2682 $prompt = 'Values (separate with \'|\'): ';
2683 } else {
2684 $prompt = 'One value: ';
2687 if ( $type === 'submodule' ) {
2688 $type = $this->getModuleManager()->getNames( $paramName );
2689 sort( $type );
2691 if ( is_array( $type ) ) {
2692 $choices = array();
2693 $nothingPrompt = '';
2694 foreach ( $type as $t ) {
2695 if ( $t === '' ) {
2696 $nothingPrompt = 'Can be empty, or ';
2697 } else {
2698 $choices[] = $t;
2701 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2702 $choicesstring = implode( ', ', $choices );
2703 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2704 $hintPipeSeparated = false;
2705 } else {
2706 switch ( $type ) {
2707 case 'namespace':
2708 // Special handling because namespaces are
2709 // type-limited, yet they are not given
2710 $desc .= $paramPrefix . $prompt;
2711 $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
2712 100, $descWordwrap );
2713 $hintPipeSeparated = false;
2714 break;
2715 case 'limit':
2716 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2717 if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
2718 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2720 $desc .= ' allowed';
2721 break;
2722 case 'integer':
2723 $s = $multi ? 's' : '';
2724 $hasMin = isset( $paramSettings[self::PARAM_MIN] );
2725 $hasMax = isset( $paramSettings[self::PARAM_MAX] );
2726 if ( $hasMin || $hasMax ) {
2727 if ( !$hasMax ) {
2728 $intRangeStr = "The value$s must be no less than " .
2729 "{$paramSettings[self::PARAM_MIN]}";
2730 } elseif ( !$hasMin ) {
2731 $intRangeStr = "The value$s must be no more than " .
2732 "{$paramSettings[self::PARAM_MAX]}";
2733 } else {
2734 $intRangeStr = "The value$s must be between " .
2735 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2738 $desc .= $paramPrefix . $intRangeStr;
2740 break;
2741 case 'upload':
2742 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2743 break;
2747 if ( $multi ) {
2748 if ( $hintPipeSeparated ) {
2749 $desc .= $paramPrefix . "Separate values with '|'";
2752 $isArray = is_array( $type );
2753 if ( !$isArray
2754 || $isArray && count( $type ) > self::LIMIT_SML1
2756 $desc .= $paramPrefix . "Maximum number of values " .
2757 self::LIMIT_SML1 . " (" . self::LIMIT_SML2 . " for bots)";
2762 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
2763 if ( !is_null( $default ) && $default !== false ) {
2764 $desc .= $paramPrefix . "Default: $default";
2767 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2770 return $msg;
2773 return false;
2776 /**@}*/
2780 * For really cool vim folding this needs to be at the end:
2781 * vim: foldmarker=@{,@} foldmethod=marker