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
27 use Wikimedia\Rdbms\IDatabase
;
30 * This abstract class implements many basic API functions, and is the base of
32 * The class functions are divided into several areas of functionality:
34 * Module parameters: Derived classes can define getAllowedParams() to specify
35 * which parameters to expect, how to parse and validate them.
37 * Self-documentation: code to allow the API to document its own state
41 abstract class ApiBase
extends ContextSource
{
44 * @name Constants for ::getAllowedParams() arrays
45 * These constants are keys in the arrays returned by ::getAllowedParams()
46 * and accepted by ::getParameterFromSettings() that define how the
47 * parameters coming in from the request are to be interpreted.
51 /** (null|boolean|integer|string) Default value of the parameter. */
54 /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
55 const PARAM_ISMULTI
= 1;
58 * (string|string[]) Either an array of allowed value strings, or a string
59 * type as described below. If not specified, will be determined from the
62 * Supported string types are:
63 * - boolean: A boolean parameter, returned as false if the parameter is
64 * omitted and true if present (even with a falsey value, i.e. it works
65 * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
66 * Cannot be used with PARAM_ISMULTI.
67 * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
68 * PARAM_RANGE_ENFORCE.
69 * - limit: An integer or the string 'max'. Default lower limit is 0 (but
70 * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
71 * specified. Cannot be used with PARAM_ISMULTI.
72 * - namespace: An integer representing a MediaWiki namespace. Forces PARAM_ALL = true to
73 * support easily specifying all namespaces.
75 * - password: Any non-empty string. Input value is private or sensitive.
76 * <input type="password"> would be an appropriate HTML form field.
77 * - string: Any non-empty string, not expected to be very long or contain newlines.
78 * <input type="text"> would be an appropriate HTML form field.
79 * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
80 * - tags: A string naming an existing, explicitly-defined tag. Should usually be
81 * used with PARAM_ISMULTI.
82 * - text: Any non-empty string, expected to be very long or contain newlines.
83 * <textarea> would be an appropriate HTML form field.
84 * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
85 * string 'now' representing the current timestamp. Will be returned in
87 * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
88 * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
89 * Cannot be used with PARAM_ISMULTI.
93 /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
97 * (integer) Max value allowed for the parameter for users with the
98 * apihighlimits right, for PARAM_TYPE 'limit'.
100 const PARAM_MAX2
= 4;
102 /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
105 /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
106 const PARAM_ALLOW_DUPLICATES
= 6;
108 /** (boolean) Is the parameter deprecated (will show a warning)? */
109 const PARAM_DEPRECATED
= 7;
112 * (boolean) Is the parameter required?
115 const PARAM_REQUIRED
= 8;
118 * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
121 const PARAM_RANGE_ENFORCE
= 9;
124 * (string|array|Message) Specify an alternative i18n documentation message
125 * for this parameter. Default is apihelp-{$path}-param-{$param}.
128 const PARAM_HELP_MSG
= 10;
131 * ((string|array|Message)[]) Specify additional i18n messages to append to
132 * the normal message for this parameter.
135 const PARAM_HELP_MSG_APPEND
= 11;
138 * (array) Specify additional information tags for the parameter. Value is
139 * an array of arrays, with the first member being the 'tag' for the info
140 * and the remaining members being the values. In the help, this is
141 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
142 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
145 const PARAM_HELP_MSG_INFO
= 12;
148 * (string[]) When PARAM_TYPE is an array, this may be an array mapping
149 * those values to page titles which will be linked in the help.
152 const PARAM_VALUE_LINKS
= 13;
155 * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
156 * mapping those values to $msg for ApiBase::makeMessage(). Any value not
157 * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
160 const PARAM_HELP_MSG_PER_VALUE
= 14;
163 * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
164 * submodule paths. Default is to use all modules in
165 * $this->getModuleManager() in the group matching the parameter name.
168 const PARAM_SUBMODULE_MAP
= 15;
171 * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
172 * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
175 const PARAM_SUBMODULE_PARAM_PREFIX
= 16;
178 * (boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,
179 * this allows for an asterisk ('*') to be passed in place of a pipe-separated list of
180 * every possible value. If a string is set, it will be used in place of the asterisk.
183 const PARAM_ALL
= 17;
186 * (int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
189 const PARAM_EXTRA_NAMESPACES
= 18;
192 * (boolean) Is the parameter sensitive? Note 'password'-type fields are
193 * always sensitive regardless of the value of this field.
196 const PARAM_SENSITIVE
= 19;
199 * (array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
200 * Keys are the deprecated parameter values, values define the warning
201 * message to emit: either boolean true (to use a default message) or a
202 * $msg for ApiBase::makeMessage().
205 const PARAM_DEPRECATED_VALUES
= 20;
209 const ALL_DEFAULT_STRING
= '*';
211 /** Fast query, standard limit. */
212 const LIMIT_BIG1
= 500;
213 /** Fast query, apihighlimits limit. */
214 const LIMIT_BIG2
= 5000;
215 /** Slow query, standard limit. */
216 const LIMIT_SML1
= 50;
217 /** Slow query, apihighlimits limit. */
218 const LIMIT_SML2
= 500;
221 * getAllowedParams() flag: When set, the result could take longer to generate,
222 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
225 const GET_VALUES_FOR_HELP
= 1;
227 /** @var array Maps extension paths to info arrays */
228 private static $extensionInfo = null;
231 private $mMainModule;
233 private $mModuleName, $mModulePrefix;
234 private $mSlaveDB = null;
235 private $mParamCache = [];
236 /** @var array|null|bool */
237 private $mModuleSource = false;
240 * @param ApiMain $mainModule
241 * @param string $moduleName Name of this module
242 * @param string $modulePrefix Prefix to use for parameter names
244 public function __construct( ApiMain
$mainModule, $moduleName, $modulePrefix = '' ) {
245 $this->mMainModule
= $mainModule;
246 $this->mModuleName
= $moduleName;
247 $this->mModulePrefix
= $modulePrefix;
249 if ( !$this->isMain() ) {
250 $this->setContext( $mainModule->getContext() );
254 /************************************************************************//**
255 * @name Methods to implement
260 * Evaluates the parameters, performs the requested query, and sets up
261 * the result. Concrete implementations of ApiBase must override this
262 * method to provide whatever functionality their module offers.
263 * Implementations must not produce any output on their own and are not
264 * expected to handle any errors.
266 * The execute() method will be invoked directly by ApiMain immediately
267 * before the result of the module is output. Aside from the
268 * constructor, implementations should assume that no other methods
269 * will be called externally on the module before the result is
272 * The result data should be stored in the ApiResult object available
273 * through getResult().
275 abstract public function execute();
278 * Get the module manager, or null if this module has no sub-modules
280 * @return ApiModuleManager
282 public function getModuleManager() {
287 * If the module may only be used with a certain format module,
288 * it should override this method to return an instance of that formatter.
289 * A value of null means the default format will be used.
290 * @note Do not use this just because you don't want to support non-json
291 * formats. This should be used only when there is a fundamental
292 * requirement for a specific format.
293 * @return mixed Instance of a derived class of ApiFormatBase, or null
295 public function getCustomPrinter() {
300 * Returns usage examples for this module.
302 * Return value has query strings as keys, with values being either strings
303 * (message key), arrays (message key + parameter), or Message objects.
305 * Do not call this base class implementation when overriding this method.
310 protected function getExamplesMessages() {
311 // Fall back to old non-localised method
314 $examples = $this->getExamples();
316 if ( !is_array( $examples ) ) {
317 $examples = [ $examples ];
318 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
319 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
320 !preg_match( '/^\s*api\.php\?/', $examples[0] )
322 // Fix up the ugly "even numbered elements are description, odd
323 // numbered elemts are the link" format (see doc for self::getExamples)
325 $examplesCount = count( $examples );
326 for ( $i = 0; $i < $examplesCount; $i +
= 2 ) {
327 $tmp[$examples[$i +
1]] = $examples[$i];
332 foreach ( $examples as $k => $v ) {
333 if ( is_numeric( $k ) ) {
338 $msg = self
::escapeWikiText( $v );
339 if ( is_array( $msg ) ) {
340 $msg = implode( ' ', $msg );
344 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
345 $ret[$qs] = $this->msg( 'api-help-fallback-example', [ $msg ] );
353 * Return links to more detailed help pages about the module.
354 * @since 1.25, returning boolean false is deprecated
355 * @return string|array
357 public function getHelpUrls() {
362 * Returns an array of allowed parameters (parameter name) => (default
363 * value) or (parameter name) => (array with PARAM_* constants as keys)
364 * Don't call this function directly: use getFinalParams() to allow
365 * hooks to modify parameters as needed.
367 * Some derived classes may choose to handle an integer $flags parameter
368 * in the overriding methods. Callers of this method can pass zero or
369 * more OR-ed flags like GET_VALUES_FOR_HELP.
373 protected function getAllowedParams( /* $flags = 0 */ ) {
374 // int $flags is not declared because it causes "Strict standards"
375 // warning. Most derived classes do not implement it.
380 * Indicates if this module needs maxlag to be checked
383 public function shouldCheckMaxlag() {
388 * Indicates whether this module requires read rights
391 public function isReadMode() {
396 * Indicates whether this module requires write mode
398 * This should return true for modules that may require synchronous database writes.
399 * Modules that do not need such writes should also not rely on master database access,
400 * since only read queries are needed and each master DB is a single point of failure.
401 * Additionally, requests that only need replica DBs can be efficiently routed to any
402 * datacenter via the Promise-Non-Write-API-Action header.
406 public function isWriteMode() {
411 * Indicates whether this module must be called with a POST request
414 public function mustBePosted() {
415 return $this->needsToken() !== false;
419 * Indicates whether this module is deprecated
423 public function isDeprecated() {
428 * Indicates whether this module is "internal"
429 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
433 public function isInternal() {
438 * Returns the token type this module requires in order to execute.
440 * Modules are strongly encouraged to use the core 'csrf' type unless they
441 * have specialized security needs. If the token type is not one of the
442 * core types, you must use the ApiQueryTokensRegisterTypes hook to
445 * Returning a non-falsey value here will force the addition of an
446 * appropriate 'token' parameter in self::getFinalParams(). Also,
447 * self::mustBePosted() must return true when tokens are used.
449 * In previous versions of MediaWiki, true was a valid return value.
450 * Returning true will generate errors indicating that the API module needs
453 * @return string|false
455 public function needsToken() {
460 * Fetch the salt used in the Web UI corresponding to this module.
462 * Only override this if the Web UI uses a token with a non-constant salt.
465 * @param array $params All supplied parameters for the module
466 * @return string|array|null
468 protected function getWebUITokenSalt( array $params ) {
473 * Returns data for HTTP conditional request mechanisms.
476 * @param string $condition Condition being queried:
477 * - last-modified: Return a timestamp representing the maximum of the
478 * last-modified dates for all resources involved in the request. See
479 * RFC 7232 § 2.2 for semantics.
480 * - etag: Return an entity-tag representing the state of all resources involved
481 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
482 * @return string|bool|null As described above, or null if no value is available.
484 public function getConditionalRequestData( $condition ) {
490 /************************************************************************//**
491 * @name Data access methods
496 * Get the name of the module being executed by this instance
499 public function getModuleName() {
500 return $this->mModuleName
;
504 * Get parameter prefix (usually two letters or an empty string).
507 public function getModulePrefix() {
508 return $this->mModulePrefix
;
512 * Get the main module
515 public function getMain() {
516 return $this->mMainModule
;
520 * Returns true if this module is the main module ($this === $this->mMainModule),
524 public function isMain() {
525 return $this === $this->mMainModule
;
529 * Get the parent of this module
531 * @return ApiBase|null
533 public function getParent() {
534 return $this->isMain() ?
null : $this->getMain();
538 * Returns true if the current request breaks the same-origin policy.
540 * For example, json with callbacks.
542 * https://en.wikipedia.org/wiki/Same-origin_policy
547 public function lacksSameOriginSecurity() {
548 // Main module has this method overridden
549 // Safety - avoid infinite loop:
550 if ( $this->isMain() ) {
551 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module.' );
554 return $this->getMain()->lacksSameOriginSecurity();
558 * Get the path to this module
563 public function getModulePath() {
564 if ( $this->isMain() ) {
566 } elseif ( $this->getParent()->isMain() ) {
567 return $this->getModuleName();
569 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
574 * Get a module from its module path
577 * @param string $path
578 * @return ApiBase|null
579 * @throws ApiUsageException
581 public function getModuleFromPath( $path ) {
582 $module = $this->getMain();
583 if ( $path === 'main' ) {
587 $parts = explode( '+', $path );
588 if ( count( $parts ) === 1 ) {
589 // In case the '+' was typed into URL, it resolves as a space
590 $parts = explode( ' ', $path );
593 $count = count( $parts );
594 for ( $i = 0; $i < $count; $i++
) {
596 $manager = $parent->getModuleManager();
597 if ( $manager === null ) {
598 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
599 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
601 $module = $manager->getModule( $parts[$i] );
603 if ( $module === null ) {
604 $errorPath = $i ?
implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
606 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
616 * Get the result object
619 public function getResult() {
620 // Main module has getResult() method overridden
621 // Safety - avoid infinite loop:
622 if ( $this->isMain() ) {
623 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
626 return $this->getMain()->getResult();
630 * Get the error formatter
631 * @return ApiErrorFormatter
633 public function getErrorFormatter() {
634 // Main module has getErrorFormatter() method overridden
635 // Safety - avoid infinite loop:
636 if ( $this->isMain() ) {
637 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
640 return $this->getMain()->getErrorFormatter();
644 * Gets a default replica DB connection object
647 protected function getDB() {
648 if ( !isset( $this->mSlaveDB
) ) {
649 $this->mSlaveDB
= wfGetDB( DB_REPLICA
, 'api' );
652 return $this->mSlaveDB
;
656 * Get the continuation manager
657 * @return ApiContinuationManager|null
659 public function getContinuationManager() {
660 // Main module has getContinuationManager() method overridden
661 // Safety - avoid infinite loop:
662 if ( $this->isMain() ) {
663 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
666 return $this->getMain()->getContinuationManager();
670 * Set the continuation manager
671 * @param ApiContinuationManager|null
673 public function setContinuationManager( $manager ) {
674 // Main module has setContinuationManager() method overridden
675 // Safety - avoid infinite loop:
676 if ( $this->isMain() ) {
677 ApiBase
::dieDebug( __METHOD__
, 'base method was called on main module. ' );
680 $this->getMain()->setContinuationManager( $manager );
685 /************************************************************************//**
686 * @name Parameter handling
691 * Indicate if the module supports dynamically-determined parameters that
692 * cannot be included in self::getAllowedParams().
693 * @return string|array|Message|null Return null if the module does not
694 * support additional dynamic parameters, otherwise return a message
697 public function dynamicParameterDocumentation() {
702 * This method mangles parameter name based on the prefix supplied to the constructor.
703 * Override this method to change parameter name during runtime
704 * @param string|string[] $paramName Parameter name
705 * @return string|string[] Prefixed parameter name
706 * @since 1.29 accepts an array of strings
708 public function encodeParamName( $paramName ) {
709 if ( is_array( $paramName ) ) {
710 return array_map( function ( $name ) {
711 return $this->mModulePrefix
. $name;
714 return $this->mModulePrefix
. $paramName;
719 * Using getAllowedParams(), this function makes an array of the values
720 * provided by the user, with key being the name of the variable, and
721 * value - validated value from user or default. limits will not be
722 * parsed if $parseLimit is set to false; use this when the max
723 * limit is not definitive yet, e.g. when getting revisions.
724 * @param bool $parseLimit True by default
727 public function extractRequestParams( $parseLimit = true ) {
728 // Cache parameters, for performance and to avoid T26564.
729 if ( !isset( $this->mParamCache
[$parseLimit] ) ) {
730 $params = $this->getFinalParams();
733 if ( $params ) { // getFinalParams() can return false
734 foreach ( $params as $paramName => $paramSettings ) {
735 $results[$paramName] = $this->getParameterFromSettings(
736 $paramName, $paramSettings, $parseLimit );
739 $this->mParamCache
[$parseLimit] = $results;
742 return $this->mParamCache
[$parseLimit];
746 * Get a value for the given parameter
747 * @param string $paramName Parameter name
748 * @param bool $parseLimit See extractRequestParams()
749 * @return mixed Parameter value
751 protected function getParameter( $paramName, $parseLimit = true ) {
752 $paramSettings = $this->getFinalParams()[$paramName];
754 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
758 * Die if none or more than one of a certain set of parameters is set and not false.
760 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
761 * @param string $required,... Names of parameters of which exactly one must be set
763 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
764 $required = func_get_args();
765 array_shift( $required );
767 $intersection = array_intersect( array_keys( array_filter( $params,
768 [ $this, 'parameterNotEmpty' ] ) ), $required );
770 if ( count( $intersection ) > 1 ) {
771 $this->dieWithError( [
772 'apierror-invalidparammix',
773 Message
::listParam( array_map(
775 return '<var>' . $this->encodeParamName( $p ) . '</var>';
777 array_values( $intersection )
779 count( $intersection ),
781 } elseif ( count( $intersection ) == 0 ) {
782 $this->dieWithError( [
783 'apierror-missingparam-one-of',
784 Message
::listParam( array_map(
786 return '<var>' . $this->encodeParamName( $p ) . '</var>';
788 array_values( $required )
796 * Die if more than one of a certain set of parameters is set and not false.
798 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
799 * @param string $required,... Names of parameters of which at most one must be set
801 public function requireMaxOneParameter( $params, $required /*...*/ ) {
802 $required = func_get_args();
803 array_shift( $required );
805 $intersection = array_intersect( array_keys( array_filter( $params,
806 [ $this, 'parameterNotEmpty' ] ) ), $required );
808 if ( count( $intersection ) > 1 ) {
809 $this->dieWithError( [
810 'apierror-invalidparammix',
811 Message
::listParam( array_map(
813 return '<var>' . $this->encodeParamName( $p ) . '</var>';
815 array_values( $intersection )
817 count( $intersection ),
823 * Die if none of a certain set of parameters is set and not false.
826 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
827 * @param string $required,... Names of parameters of which at least one must be set
829 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
830 $required = func_get_args();
831 array_shift( $required );
833 $intersection = array_intersect(
834 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
838 if ( count( $intersection ) == 0 ) {
839 $this->dieWithError( [
840 'apierror-missingparam-at-least-one-of',
841 Message
::listParam( array_map(
843 return '<var>' . $this->encodeParamName( $p ) . '</var>';
845 array_values( $required )
853 * Die if any of the specified parameters were found in the query part of
854 * the URL rather than the post body.
856 * @param string[] $params Parameters to check
857 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
859 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
860 // Skip if $wgDebugAPI is set or we're in internal mode
861 if ( $this->getConfig()->get( 'DebugAPI' ) ||
$this->getMain()->isInternalMode() ) {
865 $queryValues = $this->getRequest()->getQueryValues();
867 foreach ( $params as $param ) {
868 if ( $prefix !== 'noprefix' ) {
869 $param = $this->encodeParamName( $param );
871 if ( array_key_exists( $param, $queryValues ) ) {
872 $badParams[] = $param;
878 [ 'apierror-mustpostparams', join( ', ', $badParams ), count( $badParams ) ]
884 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
886 * @param object $x Parameter to check is not null/false
889 private function parameterNotEmpty( $x ) {
890 return !is_null( $x ) && $x !== false;
894 * Get a WikiPage object from a title or pageid param, if possible.
895 * Can die, if no param is set or if the title or page id is not valid.
897 * @param array $params
898 * @param bool|string $load Whether load the object's state from the database:
899 * - false: don't load (if the pageid is given, it will still be loaded)
900 * - 'fromdb': load from a replica DB
901 * - 'fromdbmaster': load from the master database
904 public function getTitleOrPageId( $params, $load = false ) {
905 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
908 if ( isset( $params['title'] ) ) {
909 $titleObj = Title
::newFromText( $params['title'] );
910 if ( !$titleObj ||
$titleObj->isExternal() ) {
911 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
913 if ( !$titleObj->canExist() ) {
914 $this->dieWithError( 'apierror-pagecannotexist' );
916 $pageObj = WikiPage
::factory( $titleObj );
917 if ( $load !== false ) {
918 $pageObj->loadPageData( $load );
920 } elseif ( isset( $params['pageid'] ) ) {
921 if ( $load === false ) {
924 $pageObj = WikiPage
::newFromID( $params['pageid'], $load );
926 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
934 * Get a Title object from a title or pageid param, if possible.
935 * Can die, if no param is set or if the title or page id is not valid.
938 * @param array $params
941 public function getTitleFromTitleOrPageId( $params ) {
942 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
945 if ( isset( $params['title'] ) ) {
946 $titleObj = Title
::newFromText( $params['title'] );
947 if ( !$titleObj ||
$titleObj->isExternal() ) {
948 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
951 } elseif ( isset( $params['pageid'] ) ) {
952 $titleObj = Title
::newFromID( $params['pageid'] );
954 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
962 * Return true if we're to watch the page, false if not, null if no change.
963 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
964 * @param Title $titleObj The page under consideration
965 * @param string $userOption The user option to consider when $watchlist=preferences.
966 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
969 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
971 $userWatching = $this->getUser()->isWatched( $titleObj, User
::IGNORE_USER_RIGHTS
);
973 switch ( $watchlist ) {
981 # If the user is already watching, don't bother checking
982 if ( $userWatching ) {
985 # If no user option was passed, use watchdefault and watchcreations
986 if ( is_null( $userOption ) ) {
987 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
988 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
991 # Watch the article based on the user preference
992 return $this->getUser()->getBoolOption( $userOption );
995 return $userWatching;
998 return $userWatching;
1003 * Using the settings determine the value for the given parameter
1005 * @param string $paramName Parameter name
1006 * @param array|mixed $paramSettings Default value or an array of settings
1007 * using PARAM_* constants.
1008 * @param bool $parseLimit Parse limit?
1009 * @return mixed Parameter value
1011 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
1012 // Some classes may decide to change parameter names
1013 $encParamName = $this->encodeParamName( $paramName );
1016 if ( !is_array( $paramSettings ) ) {
1018 self
::PARAM_DFLT
=> $paramSettings,
1022 $default = isset( $paramSettings[self
::PARAM_DFLT
] )
1023 ?
$paramSettings[self
::PARAM_DFLT
]
1025 $multi = isset( $paramSettings[self
::PARAM_ISMULTI
] )
1026 ?
$paramSettings[self
::PARAM_ISMULTI
]
1028 $type = isset( $paramSettings[self
::PARAM_TYPE
] )
1029 ?
$paramSettings[self
::PARAM_TYPE
]
1031 $dupes = isset( $paramSettings[self
::PARAM_ALLOW_DUPLICATES
] )
1032 ?
$paramSettings[self
::PARAM_ALLOW_DUPLICATES
]
1034 $deprecated = isset( $paramSettings[self
::PARAM_DEPRECATED
] )
1035 ?
$paramSettings[self
::PARAM_DEPRECATED
]
1037 $deprecatedValues = isset( $paramSettings[self
::PARAM_DEPRECATED_VALUES
] )
1038 ?
$paramSettings[self
::PARAM_DEPRECATED_VALUES
]
1040 $required = isset( $paramSettings[self
::PARAM_REQUIRED
] )
1041 ?
$paramSettings[self
::PARAM_REQUIRED
]
1043 $allowAll = isset( $paramSettings[self
::PARAM_ALL
] )
1044 ?
$paramSettings[self
::PARAM_ALL
]
1047 // When type is not given, and no choices, the type is the same as $default
1048 if ( !isset( $type ) ) {
1049 if ( isset( $default ) ) {
1050 $type = gettype( $default );
1052 $type = 'NULL'; // allow everything
1055 if ( $type == 'password' ||
!empty( $paramSettings[self
::PARAM_SENSITIVE
] ) ) {
1056 $this->getMain()->markParamsSensitive( $encParamName );
1060 if ( $type == 'boolean' ) {
1061 if ( isset( $default ) && $default !== false ) {
1062 // Having a default value of anything other than 'false' is not allowed
1065 "Boolean param $encParamName's default is set to '$default'. " .
1066 'Boolean parameters must default to false.'
1070 $value = $this->getMain()->getCheck( $encParamName );
1071 } elseif ( $type == 'upload' ) {
1072 if ( isset( $default ) ) {
1073 // Having a default value is not allowed
1076 "File upload param $encParamName's default is set to " .
1077 "'$default'. File upload parameters may not have a default." );
1080 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1082 $value = $this->getMain()->getUpload( $encParamName );
1083 if ( !$value->exists() ) {
1084 // This will get the value without trying to normalize it
1085 // (because trying to normalize a large binary file
1086 // accidentally uploaded as a field fails spectacularly)
1087 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1088 if ( $value !== null ) {
1089 $this->dieWithError(
1090 [ 'apierror-badupload', $encParamName ],
1091 "badupload_{$encParamName}"
1096 $value = $this->getMain()->getVal( $encParamName, $default );
1098 if ( isset( $value ) && $type == 'namespace' ) {
1099 $type = MWNamespace
::getValidNamespaces();
1100 if ( isset( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] ) &&
1101 is_array( $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] )
1103 $type = array_merge( $type, $paramSettings[self
::PARAM_EXTRA_NAMESPACES
] );
1105 // By default, namespace parameters allow ALL_DEFAULT_STRING to be used to specify
1109 if ( isset( $value ) && $type == 'submodule' ) {
1110 if ( isset( $paramSettings[self
::PARAM_SUBMODULE_MAP
] ) ) {
1111 $type = array_keys( $paramSettings[self
::PARAM_SUBMODULE_MAP
] );
1113 $type = $this->getModuleManager()->getNames( $paramName );
1117 $request = $this->getMain()->getRequest();
1118 $rawValue = $request->getRawVal( $encParamName );
1119 if ( $rawValue === null ) {
1120 $rawValue = $default;
1123 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1124 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1126 // This loses the potential $wgContLang->checkTitleEncoding() transformation
1127 // done by WebRequest for $_GET. Let's call that a feature.
1128 $value = join( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1130 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1134 // Check for NFC normalization, and warn
1135 if ( $rawValue !== $value ) {
1136 $this->handleParamNormalization( $paramName, $value, $rawValue );
1140 $allSpecifier = ( is_string( $allowAll ) ?
$allowAll : self
::ALL_DEFAULT_STRING
);
1141 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1144 "For param $encParamName, PARAM_ALL collides with a possible value" );
1146 if ( isset( $value ) && ( $multi ||
is_array( $type ) ) ) {
1147 $value = $this->parseMultiValue(
1151 is_array( $type ) ?
$type : null,
1152 $allowAll ?
$allSpecifier : null
1156 // More validation only when choices were not given
1157 // choices were validated in parseMultiValue()
1158 if ( isset( $value ) ) {
1159 if ( !is_array( $type ) ) {
1161 case 'NULL': // nothing to do
1166 if ( $required && $value === '' ) {
1167 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1170 case 'integer': // Force everything using intval() and optionally validate limits
1171 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : null;
1172 $max = isset( $paramSettings[self
::PARAM_MAX
] ) ?
$paramSettings[self
::PARAM_MAX
] : null;
1173 $enforceLimits = isset( $paramSettings[self
::PARAM_RANGE_ENFORCE
] )
1174 ?
$paramSettings[self
::PARAM_RANGE_ENFORCE
] : false;
1176 if ( is_array( $value ) ) {
1177 $value = array_map( 'intval', $value );
1178 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1179 foreach ( $value as &$v ) {
1180 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1184 $value = intval( $value );
1185 if ( !is_null( $min ) ||
!is_null( $max ) ) {
1186 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1191 if ( !$parseLimit ) {
1192 // Don't do any validation whatsoever
1195 if ( !isset( $paramSettings[self
::PARAM_MAX
] )
1196 ||
!isset( $paramSettings[self
::PARAM_MAX2
] )
1200 "MAX1 or MAX2 are not defined for the limit $encParamName"
1204 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1206 $min = isset( $paramSettings[self
::PARAM_MIN
] ) ?
$paramSettings[self
::PARAM_MIN
] : 0;
1207 if ( $value == 'max' ) {
1208 $value = $this->getMain()->canApiHighLimits()
1209 ?
$paramSettings[self
::PARAM_MAX2
]
1210 : $paramSettings[self
::PARAM_MAX
];
1211 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1213 $value = intval( $value );
1214 $this->validateLimit(
1218 $paramSettings[self
::PARAM_MAX
],
1219 $paramSettings[self
::PARAM_MAX2
]
1225 ApiBase
::dieDebug( __METHOD__
, "Multi-values not supported for $encParamName" );
1229 if ( is_array( $value ) ) {
1230 foreach ( $value as $key => $val ) {
1231 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1234 $value = $this->validateTimestamp( $value, $encParamName );
1238 if ( is_array( $value ) ) {
1239 foreach ( $value as $key => $val ) {
1240 $value[$key] = $this->validateUser( $val, $encParamName );
1243 $value = $this->validateUser( $value, $encParamName );
1246 case 'upload': // nothing to do
1249 // If change tagging was requested, check that the tags are valid.
1250 if ( !is_array( $value ) && !$multi ) {
1251 $value = [ $value ];
1253 $tagsStatus = ChangeTags
::canAddTagsAccompanyingChange( $value );
1254 if ( !$tagsStatus->isGood() ) {
1255 $this->dieStatus( $tagsStatus );
1259 ApiBase
::dieDebug( __METHOD__
, "Param $encParamName's type is unknown - $type" );
1263 // Throw out duplicates if requested
1264 if ( !$dupes && is_array( $value ) ) {
1265 $value = array_unique( $value );
1268 // Set a warning if a deprecated parameter has been passed
1269 if ( $deprecated && $value !== false ) {
1270 $feature = $encParamName;
1272 while ( !$m->isMain() ) {
1273 $p = $m->getParent();
1274 $name = $m->getModuleName();
1275 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1276 $feature = "{$param}={$name}&{$feature}";
1279 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1282 // Set a warning if a deprecated parameter value has been passed
1283 $usedDeprecatedValues = $deprecatedValues && $value !== false
1284 ?
array_intersect( array_keys( $deprecatedValues ), (array)$value )
1286 if ( $usedDeprecatedValues ) {
1287 $feature = "$encParamName=";
1289 while ( !$m->isMain() ) {
1290 $p = $m->getParent();
1291 $name = $m->getModuleName();
1292 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1293 $feature = "{$param}={$name}&{$feature}";
1296 foreach ( $usedDeprecatedValues as $v ) {
1297 $msg = $deprecatedValues[$v];
1298 if ( $msg === true ) {
1299 $msg = [ 'apiwarn-deprecation-parameter', "$encParamName=$v" ];
1301 $this->addDeprecation( $msg, "$feature$v" );
1304 } elseif ( $required ) {
1305 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1312 * Handle when a parameter was Unicode-normalized
1314 * @param string $paramName Unprefixed parameter name
1315 * @param string $value Input that will be used.
1316 * @param string $rawValue Input before normalization.
1318 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1319 $encParamName = $this->encodeParamName( $paramName );
1320 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1324 * Split a multi-valued parameter string, like explode()
1326 * @param string $value
1330 protected function explodeMultiValue( $value, $limit ) {
1331 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1333 $value = substr( $value, 1 );
1338 return explode( $sep, $value, $limit );
1342 * Return an array of values that were given in a 'a|b|c' notation,
1343 * after it optionally validates them against the list allowed values.
1345 * @param string $valueName The name of the parameter (for error
1347 * @param mixed $value The value being parsed
1348 * @param bool $allowMultiple Can $value contain more than one value
1350 * @param string[]|null $allowedValues An array of values to check against. If
1351 * null, all values are accepted.
1352 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1353 * if this behavior should not be allowed
1354 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1356 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1357 $allSpecifier = null
1359 if ( ( trim( $value ) === '' ||
trim( $value ) === "\x1f" ) && $allowMultiple ) {
1363 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1364 // because it unstubs $wgUser
1365 $valuesList = $this->explodeMultiValue( $value, self
::LIMIT_SML2 +
1 );
1366 $sizeLimit = count( $valuesList ) > self
::LIMIT_SML1
&& $this->mMainModule
->canApiHighLimits()
1370 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1371 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1373 return $allowedValues;
1376 if ( self
::truncateArray( $valuesList, $sizeLimit ) ) {
1377 $this->addDeprecation(
1378 [ 'apiwarn-toomanyvalues', $valueName, $sizeLimit ],
1379 "too-many-$valueName-for-{$this->getModulePath()}"
1383 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1384 // T35482 - Allow entries with | in them for non-multiple values
1385 if ( in_array( $value, $allowedValues, true ) ) {
1389 if ( is_array( $allowedValues ) ) {
1390 $values = array_map( function ( $v ) {
1391 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1392 }, $allowedValues );
1393 $this->dieWithError( [
1394 'apierror-multival-only-one-of',
1396 Message
::listParam( $values ),
1398 ], "multival_$valueName" );
1400 $this->dieWithError( [
1401 'apierror-multival-only-one',
1403 ], "multival_$valueName" );
1407 if ( is_array( $allowedValues ) ) {
1408 // Check for unknown values
1409 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1410 if ( count( $unknown ) ) {
1411 if ( $allowMultiple ) {
1412 $this->addWarning( [
1413 'apiwarn-unrecognizedvalues',
1415 Message
::listParam( $unknown, 'comma' ),
1419 $this->dieWithError(
1420 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1421 "unknown_$valueName"
1425 // Now throw them out
1426 $valuesList = array_intersect( $valuesList, $allowedValues );
1429 return $allowMultiple ?
$valuesList : $valuesList[0];
1433 * Validate the value against the minimum and user/bot maximum limits.
1434 * Prints usage info on failure.
1435 * @param string $paramName Parameter name
1436 * @param int $value Parameter value
1437 * @param int|null $min Minimum value
1438 * @param int|null $max Maximum value for users
1439 * @param int $botMax Maximum value for sysops/bots
1440 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1442 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1443 $enforceLimits = false
1445 if ( !is_null( $min ) && $value < $min ) {
1446 $msg = ApiMessage
::create(
1447 [ 'apierror-integeroutofrange-belowminimum',
1448 $this->encodeParamName( $paramName ), $min, $value ],
1449 'integeroutofrange',
1450 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1452 $this->warnOrDie( $msg, $enforceLimits );
1456 // Minimum is always validated, whereas maximum is checked only if not
1457 // running in internal call mode
1458 if ( $this->getMain()->isInternalMode() ) {
1462 // Optimization: do not check user's bot status unless really needed -- skips db query
1463 // assumes $botMax >= $max
1464 if ( !is_null( $max ) && $value > $max ) {
1465 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1466 if ( $value > $botMax ) {
1467 $msg = ApiMessage
::create(
1468 [ 'apierror-integeroutofrange-abovebotmax',
1469 $this->encodeParamName( $paramName ), $botMax, $value ],
1470 'integeroutofrange',
1471 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1473 $this->warnOrDie( $msg, $enforceLimits );
1477 $msg = ApiMessage
::create(
1478 [ 'apierror-integeroutofrange-abovemax',
1479 $this->encodeParamName( $paramName ), $max, $value ],
1480 'integeroutofrange',
1481 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?
: $max ]
1483 $this->warnOrDie( $msg, $enforceLimits );
1490 * Validate and normalize of parameters of type 'timestamp'
1491 * @param string $value Parameter value
1492 * @param string $encParamName Parameter name
1493 * @return string Validated and normalized parameter
1495 protected function validateTimestamp( $value, $encParamName ) {
1496 // Confusing synonyms for the current time accepted by wfTimestamp()
1497 // (wfTimestamp() also accepts various non-strings and the string of 14
1498 // ASCII NUL bytes, but those can't get here)
1500 $this->addDeprecation(
1501 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1502 'unclear-"now"-timestamp'
1504 return wfTimestamp( TS_MW
);
1507 // Explicit synonym for the current time
1508 if ( $value === 'now' ) {
1509 return wfTimestamp( TS_MW
);
1512 $unixTimestamp = wfTimestamp( TS_UNIX
, $value );
1513 if ( $unixTimestamp === false ) {
1514 $this->dieWithError(
1515 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1516 "badtimestamp_{$encParamName}"
1520 return wfTimestamp( TS_MW
, $unixTimestamp );
1524 * Validate the supplied token.
1527 * @param string $token Supplied token
1528 * @param array $params All supplied parameters for the module
1530 * @throws MWException
1532 final public function validateToken( $token, array $params ) {
1533 $tokenType = $this->needsToken();
1534 $salts = ApiQueryTokens
::getTokenTypeSalts();
1535 if ( !isset( $salts[$tokenType] ) ) {
1536 throw new MWException(
1537 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1538 'without registering it'
1542 $tokenObj = ApiQueryTokens
::getToken(
1543 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1545 if ( $tokenObj->match( $token ) ) {
1549 $webUiSalt = $this->getWebUITokenSalt( $params );
1550 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1562 * Validate and normalize of parameters of type 'user'
1563 * @param string $value Parameter value
1564 * @param string $encParamName Parameter name
1565 * @return string Validated and normalized parameter
1567 private function validateUser( $value, $encParamName ) {
1568 $title = Title
::makeTitleSafe( NS_USER
, $value );
1569 if ( $title === null ||
$title->hasFragment() ) {
1570 $this->dieWithError(
1571 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1572 "baduser_{$encParamName}"
1576 return $title->getText();
1581 /************************************************************************//**
1582 * @name Utility methods
1587 * Set a watch (or unwatch) based the based on a watchlist parameter.
1588 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1589 * @param Title $titleObj The article's title to change
1590 * @param string $userOption The user option to consider when $watch=preferences
1592 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1593 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1594 if ( $value === null ) {
1598 WatchAction
::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1602 * Truncate an array to a certain length.
1603 * @param array $arr Array to truncate
1604 * @param int $limit Maximum length
1605 * @return bool True if the array was truncated, false otherwise
1607 public static function truncateArray( &$arr, $limit ) {
1609 while ( count( $arr ) > $limit ) {
1618 * Gets the user for whom to get the watchlist
1620 * @param array $params
1623 public function getWatchlistUser( $params ) {
1624 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1625 $user = User
::newFromName( $params['owner'], false );
1626 if ( !( $user && $user->getId() ) ) {
1627 $this->dieWithError(
1628 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1631 $token = $user->getOption( 'watchlisttoken' );
1632 if ( $token == '' ||
!hash_equals( $token, $params['token'] ) ) {
1633 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1636 if ( !$this->getUser()->isLoggedIn() ) {
1637 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1639 $this->checkUserRightsAny( 'viewmywatchlist' );
1640 $user = $this->getUser();
1647 * A subset of wfEscapeWikiText for BC texts
1650 * @param string|array $v
1651 * @return string|array
1653 private static function escapeWikiText( $v ) {
1654 if ( is_array( $v ) ) {
1655 return array_map( 'self::escapeWikiText', $v );
1658 '__' => '__', '{' => '{', '}' => '}',
1659 '[[Category:' => '[[:Category:',
1660 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1666 * Create a Message from a string or array
1668 * A string is used as a message key. An array has the message key as the
1669 * first value and message parameters as subsequent values.
1672 * @param string|array|Message $msg
1673 * @param IContextSource $context
1674 * @param array $params
1675 * @return Message|null
1677 public static function makeMessage( $msg, IContextSource
$context, array $params = null ) {
1678 if ( is_string( $msg ) ) {
1679 $msg = wfMessage( $msg );
1680 } elseif ( is_array( $msg ) ) {
1681 $msg = call_user_func_array( 'wfMessage', $msg );
1683 if ( !$msg instanceof Message
) {
1687 $msg->setContext( $context );
1689 $msg->params( $params );
1696 * Turn an array of message keys or key+param arrays into a Status
1698 * @param array $errors
1699 * @param User|null $user
1702 public function errorArrayToStatus( array $errors, User
$user = null ) {
1703 if ( $user === null ) {
1704 $user = $this->getUser();
1707 $status = Status
::newGood();
1708 foreach ( $errors as $error ) {
1709 if ( is_array( $error ) && $error[0] === 'blockedtext' && $user->getBlock() ) {
1710 $status->fatal( ApiMessage
::create(
1713 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1715 } elseif ( is_array( $error ) && $error[0] === 'autoblockedtext' && $user->getBlock() ) {
1716 $status->fatal( ApiMessage
::create(
1717 'apierror-autoblocked',
1719 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1721 } elseif ( is_array( $error ) && $error[0] === 'systemblockedtext' && $user->getBlock() ) {
1722 $status->fatal( ApiMessage
::create(
1723 'apierror-systemblocked',
1725 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
1728 call_user_func_array( [ $status, 'fatal' ], (array)$error );
1736 /************************************************************************//**
1737 * @name Warning and error reporting
1742 * Add a warning for this module.
1744 * Users should monitor this section to notice any changes in API. Multiple
1745 * calls to this function will result in multiple warning messages.
1747 * If $msg is not an ApiMessage, the message code will be derived from the
1748 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1751 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1752 * @param string|null $code See ApiErrorFormatter::addWarning()
1753 * @param array|null $data See ApiErrorFormatter::addWarning()
1755 public function addWarning( $msg, $code = null, $data = null ) {
1756 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1760 * Add a deprecation warning for this module.
1762 * A combination of $this->addWarning() and $this->logFeatureUsage()
1765 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1766 * @param string|null $feature See ApiBase::logFeatureUsage()
1767 * @param array|null $data See ApiErrorFormatter::addWarning()
1769 public function addDeprecation( $msg, $feature, $data = [] ) {
1770 $data = (array)$data;
1771 if ( $feature !== null ) {
1772 $data['feature'] = $feature;
1773 $this->logFeatureUsage( $feature );
1775 $this->addWarning( $msg, 'deprecation', $data );
1777 // No real need to deduplicate here, ApiErrorFormatter does that for
1778 // us (assuming the hook is deterministic).
1779 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1780 Hooks
::run( 'ApiDeprecationHelp', [ &$msgs ] );
1781 if ( count( $msgs ) > 1 ) {
1782 $key = '$' . join( ' $', range( 1, count( $msgs ) ) );
1783 $msg = ( new RawMessage( $key ) )->params( $msgs );
1785 $msg = reset( $msgs );
1787 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1791 * Add an error for this module without aborting
1793 * If $msg is not an ApiMessage, the message code will be derived from the
1794 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1796 * @note If you want to abort processing, use self::dieWithError() instead.
1798 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1799 * @param string|null $code See ApiErrorFormatter::addError()
1800 * @param array|null $data See ApiErrorFormatter::addError()
1802 public function addError( $msg, $code = null, $data = null ) {
1803 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1807 * Add warnings and/or errors from a Status
1809 * @note If you want to abort processing, use self::dieStatus() instead.
1811 * @param StatusValue $status
1812 * @param string[] $types 'warning' and/or 'error'
1814 public function addMessagesFromStatus( StatusValue
$status, $types = [ 'warning', 'error' ] ) {
1815 $this->getErrorFormatter()->addMessagesFromStatus( $this->getModulePath(), $status, $types );
1819 * Abort execution with an error
1821 * If $msg is not an ApiMessage, the message code will be derived from the
1822 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1825 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1826 * @param string|null $code See ApiErrorFormatter::addError()
1827 * @param array|null $data See ApiErrorFormatter::addError()
1828 * @param int|null $httpCode HTTP error code to use
1829 * @throws ApiUsageException always
1831 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1832 throw ApiUsageException
::newWithMessage( $this, $msg, $code, $data, $httpCode );
1836 * Abort execution with an error derived from an exception
1839 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
1840 * @param array $options See ApiErrorFormatter::getMessageFromException()
1841 * @throws ApiUsageException always
1843 public function dieWithException( $exception, array $options = [] ) {
1844 $this->dieWithError(
1845 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
1850 * Adds a warning to the output, else dies
1852 * @param ApiMessage $msg Message to show as a warning, or error message if dying
1853 * @param bool $enforceLimits Whether this is an enforce (die)
1855 private function warnOrDie( ApiMessage
$msg, $enforceLimits = false ) {
1856 if ( $enforceLimits ) {
1857 $this->dieWithError( $msg );
1859 $this->addWarning( $msg );
1864 * Throw an ApiUsageException, which will (if uncaught) call the main module's
1865 * error handler and die with an error message including block info.
1868 * @param Block $block The block used to generate the ApiUsageException
1869 * @throws ApiUsageException always
1871 public function dieBlocked( Block
$block ) {
1872 // Die using the appropriate message depending on block type
1873 if ( $block->getType() == Block
::TYPE_AUTO
) {
1874 $this->dieWithError(
1875 'apierror-autoblocked',
1877 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1880 $this->dieWithError(
1883 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $block ) ]
1889 * Throw an ApiUsageException based on the Status object.
1892 * @since 1.29 Accepts a StatusValue
1893 * @param StatusValue $status
1894 * @throws ApiUsageException always
1896 public function dieStatus( StatusValue
$status ) {
1897 if ( $status->isGood() ) {
1898 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1901 // ApiUsageException needs a fatal status, but this method has
1902 // historically accepted any non-good status. Convert it if necessary.
1903 $status->setOK( false );
1904 if ( !$status->getErrorsByType( 'error' ) ) {
1905 $newStatus = Status
::newGood();
1906 foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
1907 call_user_func_array(
1908 [ $newStatus, 'fatal' ],
1909 array_merge( [ $err['message'] ], $err['params'] )
1912 if ( !$newStatus->getErrorsByType( 'error' ) ) {
1913 $newStatus->fatal( 'unknownerror-nocode' );
1915 $status = $newStatus;
1918 throw new ApiUsageException( $this, $status );
1922 * Helper function for readonly errors
1924 * @throws ApiUsageException always
1926 public function dieReadOnly() {
1927 $this->dieWithError(
1928 'apierror-readonly',
1930 [ 'readonlyreason' => wfReadOnlyReason() ]
1935 * Helper function for permission-denied errors
1937 * @param string|string[] $rights
1938 * @param User|null $user
1939 * @throws ApiUsageException if the user doesn't have any of the rights.
1940 * The error message is based on $rights[0].
1942 public function checkUserRightsAny( $rights, $user = null ) {
1944 $user = $this->getUser();
1946 $rights = (array)$rights;
1947 if ( !call_user_func_array( [ $user, 'isAllowedAny' ], $rights ) ) {
1948 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
1953 * Helper function for permission-denied errors
1955 * @param Title $title
1956 * @param string|string[] $actions
1957 * @param User|null $user
1958 * @throws ApiUsageException if the user doesn't have all of the rights.
1960 public function checkTitleUserPermissions( Title
$title, $actions, $user = null ) {
1962 $user = $this->getUser();
1966 foreach ( (array)$actions as $action ) {
1967 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
1970 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
1975 * Will only set a warning instead of failing if the global $wgDebugAPI
1976 * is set to true. Otherwise behaves exactly as self::dieWithError().
1979 * @param string|array|Message $msg
1980 * @param string|null $code
1981 * @param array|null $data
1982 * @param int|null $httpCode
1983 * @throws ApiUsageException
1985 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
1986 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1987 $this->dieWithError( $msg, $code, $data, $httpCode );
1989 $this->addWarning( $msg, $code, $data );
1994 * Die with the 'badcontinue' error.
1996 * This call is common enough to make it into the base method.
1998 * @param bool $condition Will only die if this value is true
1999 * @throws ApiUsageException
2002 protected function dieContinueUsageIf( $condition ) {
2004 $this->dieWithError( 'apierror-badcontinue' );
2009 * Internal code errors should be reported with this method
2010 * @param string $method Method or function name
2011 * @param string $message Error message
2012 * @throws MWException always
2014 protected static function dieDebug( $method, $message ) {
2015 throw new MWException( "Internal error in $method: $message" );
2019 * Write logging information for API features to a debug log, for usage
2021 * @note Consider using $this->addDeprecation() instead to both warn and log.
2022 * @param string $feature Feature being used.
2024 public function logFeatureUsage( $feature ) {
2025 $request = $this->getRequest();
2026 $s = '"' . addslashes( $feature ) . '"' .
2027 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2028 ' "' . $request->getIP() . '"' .
2029 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2030 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2031 wfDebugLog( 'api-feature-usage', $s, 'private' );
2036 /************************************************************************//**
2037 * @name Help message generation
2042 * Return the summary message.
2044 * This is a one-line description of the module, suitable for display in a
2048 * @return string|array|Message
2050 protected function getSummaryMessage() {
2051 return "apihelp-{$this->getModulePath()}-summary";
2055 * Return the extended help text message.
2057 * This is additional text to display at the top of the help section, below
2061 * @return string|array|Message
2063 protected function getExtendedDescription() {
2065 "apihelp-{$this->getModulePath()}-extended-description",
2066 'api-help-no-extended-description',
2071 * Get final module summary
2073 * Ideally this will just be the getSummaryMessage(). However, for
2074 * backwards compatibility, if that message does not exist then the first
2075 * line of wikitext from the description message will be used instead.
2080 public function getFinalSummary() {
2081 $msg = ApiBase
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2082 $this->getModulePrefix(),
2083 $this->getModuleName(),
2084 $this->getModulePath(),
2086 if ( !$msg->exists() ) {
2087 wfDeprecated( 'API help "description" messages', '1.30' );
2088 $msg = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2089 $this->getModulePrefix(),
2090 $this->getModuleName(),
2091 $this->getModulePath(),
2093 $msg = ApiBase
::makeMessage( 'rawmessage', $this->getContext(), [
2094 preg_replace( '/\n.*/s', '', $msg->text() )
2101 * Get final module description, after hooks have had a chance to tweak it as
2104 * @since 1.25, returns Message[] rather than string[]
2107 public function getFinalDescription() {
2108 $desc = $this->getDescription();
2110 // Avoid PHP 7.1 warning of passing $this by reference
2112 Hooks
::run( 'APIGetDescription', [ &$apiModule, &$desc ] );
2113 $desc = self
::escapeWikiText( $desc );
2114 if ( is_array( $desc ) ) {
2115 $desc = implode( "\n", $desc );
2117 $desc = (string)$desc;
2120 $summary = ApiBase
::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2121 $this->getModulePrefix(),
2122 $this->getModuleName(),
2123 $this->getModulePath(),
2125 $extendedDescription = ApiBase
::makeMessage(
2126 $this->getExtendedDescription(), $this->getContext(), [
2127 $this->getModulePrefix(),
2128 $this->getModuleName(),
2129 $this->getModulePath(),
2133 if ( $summary->exists() ) {
2134 $msgs = [ $summary, $extendedDescription ];
2136 wfDeprecated( 'API help "description" messages', '1.30' );
2137 $description = ApiBase
::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2138 $this->getModulePrefix(),
2139 $this->getModuleName(),
2140 $this->getModulePath(),
2142 if ( !$description->exists() ) {
2143 $description = $this->msg( 'api-help-fallback-description', $desc );
2145 $msgs = [ $description ];
2148 Hooks
::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2154 * Get final list of parameters, after hooks have had a chance to
2155 * tweak it as needed.
2157 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2158 * @return array|bool False on no parameters
2159 * @since 1.21 $flags param added
2161 public function getFinalParams( $flags = 0 ) {
2162 $params = $this->getAllowedParams( $flags );
2167 if ( $this->needsToken() ) {
2168 $params['token'] = [
2169 ApiBase
::PARAM_TYPE
=> 'string',
2170 ApiBase
::PARAM_REQUIRED
=> true,
2171 ApiBase
::PARAM_SENSITIVE
=> true,
2172 ApiBase
::PARAM_HELP_MSG
=> [
2173 'api-help-param-token',
2174 $this->needsToken(),
2176 ] +
( isset( $params['token'] ) ?
$params['token'] : [] );
2179 // Avoid PHP 7.1 warning of passing $this by reference
2181 Hooks
::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2187 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2190 * @since 1.25, returns array of Message[] rather than array of string[]
2191 * @return array Keys are parameter names, values are arrays of Message objects
2193 public function getFinalParamDescription() {
2194 $prefix = $this->getModulePrefix();
2195 $name = $this->getModuleName();
2196 $path = $this->getModulePath();
2198 $desc = $this->getParamDescription();
2200 // Avoid PHP 7.1 warning of passing $this by reference
2202 Hooks
::run( 'APIGetParamDescription', [ &$apiModule, &$desc ] );
2207 $desc = self
::escapeWikiText( $desc );
2209 $params = $this->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
2211 foreach ( $params as $param => $settings ) {
2212 if ( !is_array( $settings ) ) {
2216 $d = isset( $desc[$param] ) ?
$desc[$param] : '';
2217 if ( is_array( $d ) ) {
2218 // Special handling for prop parameters
2219 $d = array_map( function ( $line ) {
2220 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2221 $line = "\n;{$m[1]}:{$m[2]}";
2225 $d = implode( ' ', $d );
2228 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
2229 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
2231 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2232 if ( !$msg->exists() ) {
2233 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2236 $msg = ApiBase
::makeMessage( $msg, $this->getContext(),
2237 [ $prefix, $param, $name, $path ] );
2239 self
::dieDebug( __METHOD__
,
2240 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2242 $msgs[$param] = [ $msg ];
2244 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2245 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
2246 self
::dieDebug( __METHOD__
,
2247 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2249 if ( !is_array( $settings[ApiBase
::PARAM_TYPE
] ) ) {
2250 self
::dieDebug( __METHOD__
,
2251 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2252 'ApiBase::PARAM_TYPE is an array' );
2255 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
2256 $deprecatedValues = isset( $settings[ApiBase
::PARAM_DEPRECATED_VALUES
] )
2257 ?
$settings[ApiBase
::PARAM_DEPRECATED_VALUES
]
2260 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
2261 if ( isset( $valueMsgs[$value] ) ) {
2262 $msg = $valueMsgs[$value];
2264 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2266 $m = ApiBase
::makeMessage( $msg, $this->getContext(),
2267 [ $prefix, $param, $name, $path, $value ] );
2269 $m = new ApiHelpParamValueMessage(
2271 [ $m->getKey(), 'api-help-param-no-description' ],
2273 isset( $deprecatedValues[$value] )
2275 $msgs[$param][] = $m->setContext( $this->getContext() );
2277 self
::dieDebug( __METHOD__
,
2278 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2283 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2284 if ( !is_array( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
2285 self
::dieDebug( __METHOD__
,
2286 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2288 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $m ) {
2289 $m = ApiBase
::makeMessage( $m, $this->getContext(),
2290 [ $prefix, $param, $name, $path ] );
2292 $msgs[$param][] = $m;
2294 self
::dieDebug( __METHOD__
,
2295 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2301 Hooks
::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2307 * Generates the list of flags for the help screen and for action=paraminfo
2309 * Corresponding messages: api-help-flag-deprecated,
2310 * api-help-flag-internal, api-help-flag-readrights,
2311 * api-help-flag-writerights, api-help-flag-mustbeposted
2315 protected function getHelpFlags() {
2318 if ( $this->isDeprecated() ) {
2319 $flags[] = 'deprecated';
2321 if ( $this->isInternal() ) {
2322 $flags[] = 'internal';
2324 if ( $this->isReadMode() ) {
2325 $flags[] = 'readrights';
2327 if ( $this->isWriteMode() ) {
2328 $flags[] = 'writerights';
2330 if ( $this->mustBePosted() ) {
2331 $flags[] = 'mustbeposted';
2338 * Returns information about the source of this module, if known
2340 * Returned array is an array with the following keys:
2341 * - path: Install path
2342 * - name: Extension name, or "MediaWiki" for core
2343 * - namemsg: (optional) i18n message key for a display name
2344 * - license-name: (optional) Name of license
2346 * @return array|null
2348 protected function getModuleSourceInfo() {
2351 if ( $this->mModuleSource
!== false ) {
2352 return $this->mModuleSource
;
2355 // First, try to find where the module comes from...
2356 $rClass = new ReflectionClass( $this );
2357 $path = $rClass->getFileName();
2360 $this->mModuleSource
= null;
2363 $path = realpath( $path ) ?
: $path;
2365 // Build map of extension directories to extension info
2366 if ( self
::$extensionInfo === null ) {
2367 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2368 self
::$extensionInfo = [
2369 realpath( __DIR__
) ?
: __DIR__
=> [
2371 'name' => 'MediaWiki',
2372 'license-name' => 'GPL-2.0+',
2374 realpath( "$IP/extensions" ) ?
: "$IP/extensions" => null,
2375 realpath( $extDir ) ?
: $extDir => null,
2381 'license-name' => null,
2383 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2384 foreach ( $group as $ext ) {
2385 if ( !isset( $ext['path'] ) ||
!isset( $ext['name'] ) ) {
2386 // This shouldn't happen, but does anyway.
2390 $extpath = $ext['path'];
2391 if ( !is_dir( $extpath ) ) {
2392 $extpath = dirname( $extpath );
2394 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2395 array_intersect_key( $ext, $keep );
2398 foreach ( ExtensionRegistry
::getInstance()->getAllThings() as $ext ) {
2399 $extpath = $ext['path'];
2400 if ( !is_dir( $extpath ) ) {
2401 $extpath = dirname( $extpath );
2403 self
::$extensionInfo[realpath( $extpath ) ?
: $extpath] =
2404 array_intersect_key( $ext, $keep );
2408 // Now traverse parent directories until we find a match or run out of
2411 if ( array_key_exists( $path, self
::$extensionInfo ) ) {
2413 $this->mModuleSource
= self
::$extensionInfo[$path];
2414 return $this->mModuleSource
;
2418 $path = dirname( $path );
2419 } while ( $path !== $oldpath );
2421 // No idea what extension this might be.
2422 $this->mModuleSource
= null;
2427 * Called from ApiHelp before the pieces are joined together and returned.
2429 * This exists mainly for ApiMain to add the Permissions and Credits
2430 * sections. Other modules probably don't need it.
2432 * @param string[] &$help Array of help data
2433 * @param array $options Options passed to ApiHelp::getHelp
2434 * @param array &$tocData If a TOC is being generated, this array has keys
2435 * as anchors in the page and values as for Linker::generateTOC().
2437 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2442 /************************************************************************//**
2448 * Returns the description string for this module
2450 * Ignored if an i18n message exists for
2451 * "apihelp-{$this->getModulePath()}-description".
2453 * @deprecated since 1.25
2454 * @return Message|string|array|false
2456 protected function getDescription() {
2461 * Returns an array of parameter descriptions.
2463 * For each parameter, ignored if an i18n message exists for the parameter.
2464 * By default that message is
2465 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2466 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2467 * self::getFinalParams().
2469 * @deprecated since 1.25
2470 * @return array|bool False on no parameter descriptions
2472 protected function getParamDescription() {
2477 * Returns usage examples for this module.
2479 * Return value as an array is either:
2480 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2482 * - sequential numeric keys with even-numbered keys being display-text
2483 * and odd-numbered keys being partial urls
2484 * - partial URLs as keys with display-text (string or array-to-be-joined)
2486 * Return value as a string is the same as an array with a numeric key and
2487 * that value, and boolean false means "no examples".
2489 * @deprecated since 1.25, use getExamplesMessages() instead
2490 * @return bool|string|array
2492 protected function getExamples() {
2497 * @deprecated since 1.25, always returns empty string
2498 * @param IDatabase|bool $db
2501 public function getModuleProfileName( $db = false ) {
2502 wfDeprecated( __METHOD__
, '1.25' );
2507 * @deprecated since 1.25
2509 public function profileIn() {
2510 // No wfDeprecated() yet because extensions call this and might need to
2511 // keep doing so for BC.
2515 * @deprecated since 1.25
2517 public function profileOut() {
2518 // No wfDeprecated() yet because extensions call this and might need to
2519 // keep doing so for BC.
2523 * @deprecated since 1.25
2525 public function safeProfileOut() {
2526 wfDeprecated( __METHOD__
, '1.25' );
2530 * @deprecated since 1.25, always returns 0
2533 public function getProfileTime() {
2534 wfDeprecated( __METHOD__
, '1.25' );
2539 * @deprecated since 1.25
2541 public function profileDBIn() {
2542 wfDeprecated( __METHOD__
, '1.25' );
2546 * @deprecated since 1.25
2548 public function profileDBOut() {
2549 wfDeprecated( __METHOD__
, '1.25' );
2553 * @deprecated since 1.25, always returns 0
2556 public function getProfileDBTime() {
2557 wfDeprecated( __METHOD__
, '1.25' );
2562 * Call wfTransactionalTimeLimit() if this request was POSTed
2565 protected function useTransactionalTimeLimit() {
2566 if ( $this->getRequest()->wasPosted() ) {
2567 wfTransactionalTimeLimit();
2572 * @deprecated since 1.29, use ApiBase::addWarning() instead
2573 * @param string $warning Warning message
2575 public function setWarning( $warning ) {
2576 $msg = new ApiRawMessage( $warning, 'warning' );
2577 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg );
2581 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2582 * error handler and die with an error message.
2584 * @deprecated since 1.29, use self::dieWithError() instead
2585 * @param string $description One-line human-readable description of the
2586 * error condition, e.g., "The API requires a valid action parameter"
2587 * @param string $errorCode Brief, arbitrary, stable string to allow easy
2588 * automated identification of the error, e.g., 'unknown_action'
2589 * @param int $httpRespCode HTTP response code
2590 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
2591 * @throws ApiUsageException always
2593 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
2594 $this->dieWithError(
2595 new RawMessage( '$1', [ $description ] ),
2603 * Get error (as code, string) from a Status object.
2606 * @deprecated since 1.29, use ApiErrorFormatter::arrayFromStatus instead
2607 * @param Status $status
2608 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
2609 * @return array Array of code and error string
2610 * @throws MWException
2612 public function getErrorFromStatus( $status, &$extraData = null ) {
2613 if ( $status->isGood() ) {
2614 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2617 $errors = $status->getErrorsByType( 'error' );
2619 // No errors? Assume the warnings should be treated as errors
2620 $errors = $status->getErrorsByType( 'warning' );
2623 // Still no errors? Punt
2624 $errors = [ [ 'message' => 'unknownerror-nocode', 'params' => [] ] ];
2627 if ( $errors[0]['message'] instanceof MessageSpecifier
) {
2628 $msg = $errors[0]['message'];
2630 $msg = new Message( $errors[0]['message'], $errors[0]['params'] );
2632 if ( !$msg instanceof IApiMessage
) {
2633 $key = $msg->getKey();
2634 $params = $msg->getParams();
2635 array_unshift( $params, isset( self
::$messageMap[$key] ) ? self
::$messageMap[$key] : $key );
2636 $msg = ApiMessage
::create( $params );
2641 ApiErrorFormatter
::stripMarkup( $msg->inLanguage( 'en' )->useDatabase( false )->text() )
2646 * @deprecated since 1.29. Prior to 1.29, this was a public mapping from
2647 * arbitrary strings (often message keys used elsewhere in MediaWiki) to
2648 * API codes and message texts, and a few interfaces required poking
2649 * something in here. Now we're repurposing it to map those same strings
2650 * to i18n messages, and declaring that any interface that requires poking
2651 * at this is broken and needs replacing ASAP.
2653 private static $messageMap = [
2654 'unknownerror' => 'apierror-unknownerror',
2655 'unknownerror-nocode' => 'apierror-unknownerror-nocode',
2656 'ns-specialprotected' => 'ns-specialprotected',
2657 'protectedinterface' => 'protectedinterface',
2658 'namespaceprotected' => 'namespaceprotected',
2659 'customcssprotected' => 'customcssprotected',
2660 'customjsprotected' => 'customjsprotected',
2661 'cascadeprotected' => 'cascadeprotected',
2662 'protectedpagetext' => 'protectedpagetext',
2663 'protect-cantedit' => 'protect-cantedit',
2664 'deleteprotected' => 'deleteprotected',
2665 'badaccess-group0' => 'badaccess-group0',
2666 'badaccess-groups' => 'badaccess-groups',
2667 'titleprotected' => 'titleprotected',
2668 'nocreate-loggedin' => 'nocreate-loggedin',
2669 'nocreatetext' => 'nocreatetext',
2670 'movenologintext' => 'movenologintext',
2671 'movenotallowed' => 'movenotallowed',
2672 'confirmedittext' => 'confirmedittext',
2673 'blockedtext' => 'apierror-blocked',
2674 'autoblockedtext' => 'apierror-autoblocked',
2675 'systemblockedtext' => 'apierror-systemblocked',
2676 'actionthrottledtext' => 'apierror-ratelimited',
2677 'alreadyrolled' => 'alreadyrolled',
2678 'cantrollback' => 'cantrollback',
2679 'readonlytext' => 'readonlytext',
2680 'sessionfailure' => 'sessionfailure',
2681 'cannotdelete' => 'cannotdelete',
2682 'notanarticle' => 'apierror-missingtitle',
2683 'selfmove' => 'selfmove',
2684 'immobile_namespace' => 'apierror-immobilenamespace',
2685 'articleexists' => 'articleexists',
2686 'hookaborted' => 'hookaborted',
2687 'cantmove-titleprotected' => 'cantmove-titleprotected',
2688 'imagenocrossnamespace' => 'imagenocrossnamespace',
2689 'imagetypemismatch' => 'imagetypemismatch',
2690 'ip_range_invalid' => 'ip_range_invalid',
2691 'range_block_disabled' => 'range_block_disabled',
2692 'nosuchusershort' => 'nosuchusershort',
2693 'badipaddress' => 'badipaddress',
2694 'ipb_expiry_invalid' => 'ipb_expiry_invalid',
2695 'ipb_already_blocked' => 'ipb_already_blocked',
2696 'ipb_blocked_as_range' => 'ipb_blocked_as_range',
2697 'ipb_cant_unblock' => 'ipb_cant_unblock',
2698 'mailnologin' => 'apierror-cantsend',
2699 'ipbblocked' => 'ipbblocked',
2700 'ipbnounblockself' => 'ipbnounblockself',
2701 'usermaildisabled' => 'usermaildisabled',
2702 'blockedemailuser' => 'apierror-blockedfrommail',
2703 'notarget' => 'apierror-notarget',
2704 'noemail' => 'noemail',
2705 'rcpatroldisabled' => 'rcpatroldisabled',
2706 'markedaspatrollederror-noautopatrol' => 'markedaspatrollederror-noautopatrol',
2707 'delete-toobig' => 'delete-toobig',
2708 'movenotallowedfile' => 'movenotallowedfile',
2709 'userrights-no-interwiki' => 'userrights-no-interwiki',
2710 'userrights-nodatabase' => 'userrights-nodatabase',
2711 'nouserspecified' => 'nouserspecified',
2712 'noname' => 'noname',
2713 'summaryrequired' => 'apierror-summaryrequired',
2714 'import-rootpage-invalid' => 'import-rootpage-invalid',
2715 'import-rootpage-nosubpage' => 'import-rootpage-nosubpage',
2716 'readrequired' => 'apierror-readapidenied',
2717 'writedisabled' => 'apierror-noapiwrite',
2718 'writerequired' => 'apierror-writeapidenied',
2719 'missingparam' => 'apierror-missingparam',
2720 'invalidtitle' => 'apierror-invalidtitle',
2721 'nosuchpageid' => 'apierror-nosuchpageid',
2722 'nosuchrevid' => 'apierror-nosuchrevid',
2723 'nosuchuser' => 'nosuchusershort',
2724 'invaliduser' => 'apierror-invaliduser',
2725 'invalidexpiry' => 'apierror-invalidexpiry',
2726 'pastexpiry' => 'apierror-pastexpiry',
2727 'create-titleexists' => 'apierror-create-titleexists',
2728 'missingtitle-createonly' => 'apierror-missingtitle-createonly',
2729 'cantblock' => 'apierror-cantblock',
2730 'canthide' => 'apierror-canthide',
2731 'cantblock-email' => 'apierror-cantblock-email',
2732 'cantunblock' => 'apierror-permissiondenied-generic',
2733 'cannotundelete' => 'cannotundelete',
2734 'permdenied-undelete' => 'apierror-permissiondenied-generic',
2735 'createonly-exists' => 'apierror-articleexists',
2736 'nocreate-missing' => 'apierror-missingtitle',
2737 'cantchangecontentmodel' => 'apierror-cantchangecontentmodel',
2738 'nosuchrcid' => 'apierror-nosuchrcid',
2739 'nosuchlogid' => 'apierror-nosuchlogid',
2740 'protect-invalidaction' => 'apierror-protect-invalidaction',
2741 'protect-invalidlevel' => 'apierror-protect-invalidlevel',
2742 'toofewexpiries' => 'apierror-toofewexpiries',
2743 'cantimport' => 'apierror-cantimport',
2744 'cantimport-upload' => 'apierror-cantimport-upload',
2745 'importnofile' => 'importnofile',
2746 'importuploaderrorsize' => 'importuploaderrorsize',
2747 'importuploaderrorpartial' => 'importuploaderrorpartial',
2748 'importuploaderrortemp' => 'importuploaderrortemp',
2749 'importcantopen' => 'importcantopen',
2750 'import-noarticle' => 'import-noarticle',
2751 'importbadinterwiki' => 'importbadinterwiki',
2752 'import-unknownerror' => 'apierror-import-unknownerror',
2753 'cantoverwrite-sharedfile' => 'apierror-cantoverwrite-sharedfile',
2754 'sharedfile-exists' => 'apierror-fileexists-sharedrepo-perm',
2755 'mustbeposted' => 'apierror-mustbeposted',
2756 'show' => 'apierror-show',
2757 'specialpage-cantexecute' => 'apierror-specialpage-cantexecute',
2758 'invalidoldimage' => 'apierror-invalidoldimage',
2759 'nodeleteablefile' => 'apierror-nodeleteablefile',
2760 'fileexists-forbidden' => 'fileexists-forbidden',
2761 'fileexists-shared-forbidden' => 'fileexists-shared-forbidden',
2762 'filerevert-badversion' => 'filerevert-badversion',
2763 'noimageredirect-anon' => 'apierror-noimageredirect-anon',
2764 'noimageredirect-logged' => 'apierror-noimageredirect',
2765 'spamdetected' => 'apierror-spamdetected',
2766 'contenttoobig' => 'apierror-contenttoobig',
2767 'noedit-anon' => 'apierror-noedit-anon',
2768 'noedit' => 'apierror-noedit',
2769 'wasdeleted' => 'apierror-pagedeleted',
2770 'blankpage' => 'apierror-emptypage',
2771 'editconflict' => 'editconflict',
2772 'hashcheckfailed' => 'apierror-badmd5',
2773 'missingtext' => 'apierror-notext',
2774 'emptynewsection' => 'apierror-emptynewsection',
2775 'revwrongpage' => 'apierror-revwrongpage',
2776 'undo-failure' => 'undo-failure',
2777 'content-not-allowed-here' => 'content-not-allowed-here',
2778 'edit-hook-aborted' => 'edit-hook-aborted',
2779 'edit-gone-missing' => 'edit-gone-missing',
2780 'edit-conflict' => 'edit-conflict',
2781 'edit-already-exists' => 'edit-already-exists',
2782 'invalid-file-key' => 'apierror-invalid-file-key',
2783 'nouploadmodule' => 'apierror-nouploadmodule',
2784 'uploaddisabled' => 'uploaddisabled',
2785 'copyuploaddisabled' => 'copyuploaddisabled',
2786 'copyuploadbaddomain' => 'apierror-copyuploadbaddomain',
2787 'copyuploadbadurl' => 'apierror-copyuploadbadurl',
2788 'filename-tooshort' => 'filename-tooshort',
2789 'filename-toolong' => 'filename-toolong',
2790 'illegal-filename' => 'illegal-filename',
2791 'filetype-missing' => 'filetype-missing',
2792 'mustbeloggedin' => 'apierror-mustbeloggedin',
2796 * @deprecated do not use
2797 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2798 * @return ApiMessage
2800 private function parseMsgInternal( $error ) {
2801 $msg = Message
::newFromSpecifier( $error );
2802 if ( !$msg instanceof IApiMessage
) {
2803 $key = $msg->getKey();
2804 if ( isset( self
::$messageMap[$key] ) ) {
2805 $params = $msg->getParams();
2806 array_unshift( $params, self
::$messageMap[$key] );
2808 $params = [ 'apierror-unknownerror', wfEscapeWikiText( $key ) ];
2810 $msg = ApiMessage
::create( $params );
2816 * Return the error message related to a certain array
2817 * @deprecated since 1.29
2818 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2819 * @return [ 'code' => code, 'info' => info ]
2821 public function parseMsg( $error ) {
2822 // Check whether someone passed the whole array, instead of one element as
2823 // documented. This breaks if it's actually an array of fallback keys, but
2824 // that's long-standing misbehavior introduced in r87627 to incorrectly
2826 if ( is_array( $error ) ) {
2827 $first = reset( $error );
2828 if ( is_array( $first ) ) {
2829 wfDebug( __METHOD__
. ' was passed an array of arrays. ' . wfGetAllCallers( 5 ) );
2834 $msg = $this->parseMsgInternal( $error );
2836 'code' => $msg->getApiCode(),
2837 'info' => ApiErrorFormatter
::stripMarkup(
2838 $msg->inLanguage( 'en' )->useDatabase( false )->text()
2840 'data' => $msg->getApiData()
2845 * Output the error message related to a certain array
2846 * @deprecated since 1.29, use ApiBase::dieWithError() instead
2847 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2848 * @throws ApiUsageException always
2850 public function dieUsageMsg( $error ) {
2851 $this->dieWithError( $this->parseMsgInternal( $error ) );
2855 * Will only set a warning instead of failing if the global $wgDebugAPI
2856 * is set to true. Otherwise behaves exactly as dieUsageMsg().
2857 * @deprecated since 1.29, use ApiBase::dieWithErrorOrDebug() instead
2858 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2859 * @throws ApiUsageException
2862 public function dieUsageMsgOrDebug( $error ) {
2863 $this->dieWithErrorOrDebug( $this->parseMsgInternal( $error ) );
2867 * Return the description message.
2869 * This is additional text to display on the help page after the summary.
2871 * @deprecated since 1.30
2872 * @return string|array|Message
2874 protected function getDescriptionMessage() {
2876 "apihelp-{$this->getModulePath()}-description",
2877 "apihelp-{$this->getModulePath()}-summary",
2885 * For really cool vim folding this needs to be at the end:
2886 * vim: foldmarker=@{,@} foldmethod=marker