ApiPageSet: Use processTitlesArray() in getRedirectTargets()
[mediawiki.git] / includes / api / ApiBase.php
blobc03faf05135d0eca3cfd4e794bd072f4df8359fd
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 * Self-documentation: code to allow the API to document its own state
37 * @ingroup API
39 abstract class ApiBase extends ContextSource {
41 /**
42 * @name Constants for ::getAllowedParams() arrays
43 * These constants are keys in the arrays returned by ::getAllowedParams()
44 * and accepted by ::getParameterFromSettings() that define how the
45 * parameters coming in from the request are to be interpreted.
46 * @{
49 /** (null|boolean|integer|string) Default value of the parameter. */
50 const PARAM_DFLT = 0;
52 /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
53 const PARAM_ISMULTI = 1;
55 /**
56 * (string|string[]) Either an array of allowed value strings, or a string
57 * type as described below. If not specified, will be determined from the
58 * type of PARAM_DFLT.
60 * Supported string types are:
61 * - boolean: A boolean parameter, returned as false if the parameter is
62 * omitted and true if present (even with a falsey value, i.e. it works
63 * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
64 * Cannot be used with PARAM_ISMULTI.
65 * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
66 * PARAM_RANGE_ENFORCE.
67 * - limit: An integer or the string 'max'. Default lower limit is 0 (but
68 * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
69 * specified. Cannot be used with PARAM_ISMULTI.
70 * - namespace: An integer representing a MediaWiki namespace. Forces PARAM_ALL = true to
71 * support easily specifying all namespaces.
72 * - NULL: Any string.
73 * - password: Any non-empty string. Input value is private or sensitive.
74 * <input type="password"> would be an appropriate HTML form field.
75 * - string: Any non-empty string, not expected to be very long or contain newlines.
76 * <input type="text"> would be an appropriate HTML form field.
77 * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
78 * - tags: A string naming an existing, explicitly-defined tag. Should usually be
79 * used with PARAM_ISMULTI.
80 * - text: Any non-empty string, expected to be very long or contain newlines.
81 * <textarea> would be an appropriate HTML form field.
82 * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
83 * string 'now' representing the current timestamp. Will be returned in
84 * TS_MW format.
85 * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
86 * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
87 * Cannot be used with PARAM_ISMULTI.
89 const PARAM_TYPE = 2;
91 /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
92 const PARAM_MAX = 3;
94 /**
95 * (integer) Max value allowed for the parameter for users with the
96 * apihighlimits right, for PARAM_TYPE 'limit'.
98 const PARAM_MAX2 = 4;
100 /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
101 const PARAM_MIN = 5;
103 /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
104 const PARAM_ALLOW_DUPLICATES = 6;
106 /** (boolean) Is the parameter deprecated (will show a warning)? */
107 const PARAM_DEPRECATED = 7;
110 * (boolean) Is the parameter required?
111 * @since 1.17
113 const PARAM_REQUIRED = 8;
116 * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
117 * @since 1.17
119 const PARAM_RANGE_ENFORCE = 9;
122 * (string|array|Message) Specify an alternative i18n documentation message
123 * for this parameter. Default is apihelp-{$path}-param-{$param}.
124 * @since 1.25
126 const PARAM_HELP_MSG = 10;
129 * ((string|array|Message)[]) Specify additional i18n messages to append to
130 * the normal message for this parameter.
131 * @since 1.25
133 const PARAM_HELP_MSG_APPEND = 11;
136 * (array) Specify additional information tags for the parameter. Value is
137 * an array of arrays, with the first member being the 'tag' for the info
138 * and the remaining members being the values. In the help, this is
139 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
140 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
141 * @since 1.25
143 const PARAM_HELP_MSG_INFO = 12;
146 * (string[]) When PARAM_TYPE is an array, this may be an array mapping
147 * those values to page titles which will be linked in the help.
148 * @since 1.25
150 const PARAM_VALUE_LINKS = 13;
153 * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
154 * mapping those values to $msg for ApiBase::makeMessage(). Any value not
155 * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
156 * @since 1.25
158 const PARAM_HELP_MSG_PER_VALUE = 14;
161 * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
162 * submodule paths. Default is to use all modules in
163 * $this->getModuleManager() in the group matching the parameter name.
164 * @since 1.26
166 const PARAM_SUBMODULE_MAP = 15;
169 * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
170 * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
171 * @since 1.26
173 const PARAM_SUBMODULE_PARAM_PREFIX = 16;
176 * (boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,
177 * this allows for an asterisk ('*') to be passed in place of a pipe-separated list of
178 * every possible value. If a string is set, it will be used in place of the asterisk.
179 * @since 1.29
181 const PARAM_ALL = 17;
184 * (int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
185 * @since 1.29
187 const PARAM_EXTRA_NAMESPACES = 18;
189 /**@}*/
191 const ALL_DEFAULT_STRING = '*';
193 /** Fast query, standard limit. */
194 const LIMIT_BIG1 = 500;
195 /** Fast query, apihighlimits limit. */
196 const LIMIT_BIG2 = 5000;
197 /** Slow query, standard limit. */
198 const LIMIT_SML1 = 50;
199 /** Slow query, apihighlimits limit. */
200 const LIMIT_SML2 = 500;
203 * getAllowedParams() flag: When set, the result could take longer to generate,
204 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
205 * @since 1.21
207 const GET_VALUES_FOR_HELP = 1;
209 /** @var array Maps extension paths to info arrays */
210 private static $extensionInfo = null;
212 /** @var ApiMain */
213 private $mMainModule;
214 /** @var string */
215 private $mModuleName, $mModulePrefix;
216 private $mSlaveDB = null;
217 private $mParamCache = [];
218 /** @var array|null|bool */
219 private $mModuleSource = false;
222 * @param ApiMain $mainModule
223 * @param string $moduleName Name of this module
224 * @param string $modulePrefix Prefix to use for parameter names
226 public function __construct( ApiMain $mainModule, $moduleName, $modulePrefix = '' ) {
227 $this->mMainModule = $mainModule;
228 $this->mModuleName = $moduleName;
229 $this->mModulePrefix = $modulePrefix;
231 if ( !$this->isMain() ) {
232 $this->setContext( $mainModule->getContext() );
236 /************************************************************************//**
237 * @name Methods to implement
238 * @{
242 * Evaluates the parameters, performs the requested query, and sets up
243 * the result. Concrete implementations of ApiBase must override this
244 * method to provide whatever functionality their module offers.
245 * Implementations must not produce any output on their own and are not
246 * expected to handle any errors.
248 * The execute() method will be invoked directly by ApiMain immediately
249 * before the result of the module is output. Aside from the
250 * constructor, implementations should assume that no other methods
251 * will be called externally on the module before the result is
252 * processed.
254 * The result data should be stored in the ApiResult object available
255 * through getResult().
257 abstract public function execute();
260 * Get the module manager, or null if this module has no sub-modules
261 * @since 1.21
262 * @return ApiModuleManager
264 public function getModuleManager() {
265 return null;
269 * If the module may only be used with a certain format module,
270 * it should override this method to return an instance of that formatter.
271 * A value of null means the default format will be used.
272 * @note Do not use this just because you don't want to support non-json
273 * formats. This should be used only when there is a fundamental
274 * requirement for a specific format.
275 * @return mixed Instance of a derived class of ApiFormatBase, or null
277 public function getCustomPrinter() {
278 return null;
282 * Returns usage examples for this module.
284 * Return value has query strings as keys, with values being either strings
285 * (message key), arrays (message key + parameter), or Message objects.
287 * Do not call this base class implementation when overriding this method.
289 * @since 1.25
290 * @return array
292 protected function getExamplesMessages() {
293 // Fall back to old non-localised method
294 $ret = [];
296 $examples = $this->getExamples();
297 if ( $examples ) {
298 if ( !is_array( $examples ) ) {
299 $examples = [ $examples ];
300 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
301 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
302 !preg_match( '/^\s*api\.php\?/', $examples[0] )
304 // Fix up the ugly "even numbered elements are description, odd
305 // numbered elemts are the link" format (see doc for self::getExamples)
306 $tmp = [];
307 $examplesCount = count( $examples );
308 for ( $i = 0; $i < $examplesCount; $i += 2 ) {
309 $tmp[$examples[$i + 1]] = $examples[$i];
311 $examples = $tmp;
314 foreach ( $examples as $k => $v ) {
315 if ( is_numeric( $k ) ) {
316 $qs = $v;
317 $msg = '';
318 } else {
319 $qs = $k;
320 $msg = self::escapeWikiText( $v );
321 if ( is_array( $msg ) ) {
322 $msg = implode( ' ', $msg );
326 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
327 $ret[$qs] = $this->msg( 'api-help-fallback-example', [ $msg ] );
331 return $ret;
335 * Return links to more detailed help pages about the module.
336 * @since 1.25, returning boolean false is deprecated
337 * @return string|array
339 public function getHelpUrls() {
340 return [];
344 * Returns an array of allowed parameters (parameter name) => (default
345 * value) or (parameter name) => (array with PARAM_* constants as keys)
346 * Don't call this function directly: use getFinalParams() to allow
347 * hooks to modify parameters as needed.
349 * Some derived classes may choose to handle an integer $flags parameter
350 * in the overriding methods. Callers of this method can pass zero or
351 * more OR-ed flags like GET_VALUES_FOR_HELP.
353 * @return array
355 protected function getAllowedParams( /* $flags = 0 */ ) {
356 // int $flags is not declared because it causes "Strict standards"
357 // warning. Most derived classes do not implement it.
358 return [];
362 * Indicates if this module needs maxlag to be checked
363 * @return bool
365 public function shouldCheckMaxlag() {
366 return true;
370 * Indicates whether this module requires read rights
371 * @return bool
373 public function isReadMode() {
374 return true;
378 * Indicates whether this module requires write mode
379 * @return bool
381 public function isWriteMode() {
382 return false;
386 * Indicates whether this module must be called with a POST request
387 * @return bool
389 public function mustBePosted() {
390 return $this->needsToken() !== false;
394 * Indicates whether this module is deprecated
395 * @since 1.25
396 * @return bool
398 public function isDeprecated() {
399 return false;
403 * Indicates whether this module is "internal"
404 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
405 * @since 1.25
406 * @return bool
408 public function isInternal() {
409 return false;
413 * Returns the token type this module requires in order to execute.
415 * Modules are strongly encouraged to use the core 'csrf' type unless they
416 * have specialized security needs. If the token type is not one of the
417 * core types, you must use the ApiQueryTokensRegisterTypes hook to
418 * register it.
420 * Returning a non-falsey value here will force the addition of an
421 * appropriate 'token' parameter in self::getFinalParams(). Also,
422 * self::mustBePosted() must return true when tokens are used.
424 * In previous versions of MediaWiki, true was a valid return value.
425 * Returning true will generate errors indicating that the API module needs
426 * updating.
428 * @return string|false
430 public function needsToken() {
431 return false;
435 * Fetch the salt used in the Web UI corresponding to this module.
437 * Only override this if the Web UI uses a token with a non-constant salt.
439 * @since 1.24
440 * @param array $params All supplied parameters for the module
441 * @return string|array|null
443 protected function getWebUITokenSalt( array $params ) {
444 return null;
448 * Returns data for HTTP conditional request mechanisms.
450 * @since 1.26
451 * @param string $condition Condition being queried:
452 * - last-modified: Return a timestamp representing the maximum of the
453 * last-modified dates for all resources involved in the request. See
454 * RFC 7232 § 2.2 for semantics.
455 * - etag: Return an entity-tag representing the state of all resources involved
456 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
457 * @return string|bool|null As described above, or null if no value is available.
459 public function getConditionalRequestData( $condition ) {
460 return null;
463 /**@}*/
465 /************************************************************************//**
466 * @name Data access methods
467 * @{
471 * Get the name of the module being executed by this instance
472 * @return string
474 public function getModuleName() {
475 return $this->mModuleName;
479 * Get parameter prefix (usually two letters or an empty string).
480 * @return string
482 public function getModulePrefix() {
483 return $this->mModulePrefix;
487 * Get the main module
488 * @return ApiMain
490 public function getMain() {
491 return $this->mMainModule;
495 * Returns true if this module is the main module ($this === $this->mMainModule),
496 * false otherwise.
497 * @return bool
499 public function isMain() {
500 return $this === $this->mMainModule;
504 * Get the parent of this module
505 * @since 1.25
506 * @return ApiBase|null
508 public function getParent() {
509 return $this->isMain() ? null : $this->getMain();
513 * Returns true if the current request breaks the same-origin policy.
515 * For example, json with callbacks.
517 * https://en.wikipedia.org/wiki/Same-origin_policy
519 * @since 1.25
520 * @return bool
522 public function lacksSameOriginSecurity() {
523 // Main module has this method overridden
524 // Safety - avoid infinite loop:
525 if ( $this->isMain() ) {
526 ApiBase::dieDebug( __METHOD__, 'base method was called on main module.' );
529 return $this->getMain()->lacksSameOriginSecurity();
533 * Get the path to this module
535 * @since 1.25
536 * @return string
538 public function getModulePath() {
539 if ( $this->isMain() ) {
540 return 'main';
541 } elseif ( $this->getParent()->isMain() ) {
542 return $this->getModuleName();
543 } else {
544 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
549 * Get a module from its module path
551 * @since 1.25
552 * @param string $path
553 * @return ApiBase|null
554 * @throws ApiUsageException
556 public function getModuleFromPath( $path ) {
557 $module = $this->getMain();
558 if ( $path === 'main' ) {
559 return $module;
562 $parts = explode( '+', $path );
563 if ( count( $parts ) === 1 ) {
564 // In case the '+' was typed into URL, it resolves as a space
565 $parts = explode( ' ', $path );
568 $count = count( $parts );
569 for ( $i = 0; $i < $count; $i++ ) {
570 $parent = $module;
571 $manager = $parent->getModuleManager();
572 if ( $manager === null ) {
573 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
574 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
576 $module = $manager->getModule( $parts[$i] );
578 if ( $module === null ) {
579 $errorPath = $i ? implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
580 $this->dieWithError(
581 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
582 'badmodule'
587 return $module;
591 * Get the result object
592 * @return ApiResult
594 public function getResult() {
595 // Main module has getResult() method overridden
596 // Safety - avoid infinite loop:
597 if ( $this->isMain() ) {
598 ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
601 return $this->getMain()->getResult();
605 * Get the error formatter
606 * @return ApiErrorFormatter
608 public function getErrorFormatter() {
609 // Main module has getErrorFormatter() method overridden
610 // Safety - avoid infinite loop:
611 if ( $this->isMain() ) {
612 ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
615 return $this->getMain()->getErrorFormatter();
619 * Gets a default replica DB connection object
620 * @return Database
622 protected function getDB() {
623 if ( !isset( $this->mSlaveDB ) ) {
624 $this->mSlaveDB = wfGetDB( DB_REPLICA, 'api' );
627 return $this->mSlaveDB;
631 * Get the continuation manager
632 * @return ApiContinuationManager|null
634 public function getContinuationManager() {
635 // Main module has getContinuationManager() method overridden
636 // Safety - avoid infinite loop:
637 if ( $this->isMain() ) {
638 ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
641 return $this->getMain()->getContinuationManager();
645 * Set the continuation manager
646 * @param ApiContinuationManager|null
648 public function setContinuationManager( $manager ) {
649 // Main module has setContinuationManager() method overridden
650 // Safety - avoid infinite loop:
651 if ( $this->isMain() ) {
652 ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
655 $this->getMain()->setContinuationManager( $manager );
658 /**@}*/
660 /************************************************************************//**
661 * @name Parameter handling
662 * @{
666 * Indicate if the module supports dynamically-determined parameters that
667 * cannot be included in self::getAllowedParams().
668 * @return string|array|Message|null Return null if the module does not
669 * support additional dynamic parameters, otherwise return a message
670 * describing them.
672 public function dynamicParameterDocumentation() {
673 return null;
677 * This method mangles parameter name based on the prefix supplied to the constructor.
678 * Override this method to change parameter name during runtime
679 * @param string|string[] $paramName Parameter name
680 * @return string|string[] Prefixed parameter name
681 * @since 1.29 accepts an array of strings
683 public function encodeParamName( $paramName ) {
684 if ( is_array( $paramName ) ) {
685 return array_map( function ( $name ) {
686 return $this->mModulePrefix . $name;
687 }, $paramName );
688 } else {
689 return $this->mModulePrefix . $paramName;
694 * Using getAllowedParams(), this function makes an array of the values
695 * provided by the user, with key being the name of the variable, and
696 * value - validated value from user or default. limits will not be
697 * parsed if $parseLimit is set to false; use this when the max
698 * limit is not definitive yet, e.g. when getting revisions.
699 * @param bool $parseLimit True by default
700 * @return array
702 public function extractRequestParams( $parseLimit = true ) {
703 // Cache parameters, for performance and to avoid T26564.
704 if ( !isset( $this->mParamCache[$parseLimit] ) ) {
705 $params = $this->getFinalParams();
706 $results = [];
708 if ( $params ) { // getFinalParams() can return false
709 foreach ( $params as $paramName => $paramSettings ) {
710 $results[$paramName] = $this->getParameterFromSettings(
711 $paramName, $paramSettings, $parseLimit );
714 $this->mParamCache[$parseLimit] = $results;
717 return $this->mParamCache[$parseLimit];
721 * Get a value for the given parameter
722 * @param string $paramName Parameter name
723 * @param bool $parseLimit See extractRequestParams()
724 * @return mixed Parameter value
726 protected function getParameter( $paramName, $parseLimit = true ) {
727 $paramSettings = $this->getFinalParams()[$paramName];
729 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
733 * Die if none or more than one of a certain set of parameters is set and not false.
735 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
736 * @param string $required,... Names of parameters of which exactly one must be set
738 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
739 $required = func_get_args();
740 array_shift( $required );
742 $intersection = array_intersect( array_keys( array_filter( $params,
743 [ $this, 'parameterNotEmpty' ] ) ), $required );
745 if ( count( $intersection ) > 1 ) {
746 $this->dieWithError( [
747 'apierror-invalidparammix',
748 Message::listParam( array_map(
749 function ( $p ) {
750 return '<var>' . $this->encodeParamName( $p ) . '</var>';
752 array_values( $intersection )
753 ) ),
754 count( $intersection ),
755 ] );
756 } elseif ( count( $intersection ) == 0 ) {
757 $this->dieWithError( [
758 'apierror-missingparam-one-of',
759 Message::listParam( array_map(
760 function ( $p ) {
761 return '<var>' . $this->encodeParamName( $p ) . '</var>';
763 array_values( $required )
764 ) ),
765 count( $required ),
766 ], 'missingparam' );
771 * Die if more than one of a certain set of parameters is set and not false.
773 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
774 * @param string $required,... Names of parameters of which at most one must be set
776 public function requireMaxOneParameter( $params, $required /*...*/ ) {
777 $required = func_get_args();
778 array_shift( $required );
780 $intersection = array_intersect( array_keys( array_filter( $params,
781 [ $this, 'parameterNotEmpty' ] ) ), $required );
783 if ( count( $intersection ) > 1 ) {
784 $this->dieWithError( [
785 'apierror-invalidparammix',
786 Message::listParam( array_map(
787 function ( $p ) {
788 return '<var>' . $this->encodeParamName( $p ) . '</var>';
790 array_values( $intersection )
791 ) ),
792 count( $intersection ),
793 ] );
798 * Die if none of a certain set of parameters is set and not false.
800 * @since 1.23
801 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
802 * @param string $required,... Names of parameters of which at least one must be set
804 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
805 $required = func_get_args();
806 array_shift( $required );
808 $intersection = array_intersect(
809 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
810 $required
813 if ( count( $intersection ) == 0 ) {
814 $this->dieWithError( [
815 'apierror-missingparam-at-least-one-of',
816 Message::listParam( array_map(
817 function ( $p ) {
818 return '<var>' . $this->encodeParamName( $p ) . '</var>';
820 array_values( $required )
821 ) ),
822 count( $required ),
823 ], 'missingparam' );
828 * Die if any of the specified parameters were found in the query part of
829 * the URL rather than the post body.
830 * @since 1.28
831 * @param string[] $params Parameters to check
832 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
834 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
835 // Skip if $wgDebugAPI is set or we're in internal mode
836 if ( $this->getConfig()->get( 'DebugAPI' ) || $this->getMain()->isInternalMode() ) {
837 return;
840 $queryValues = $this->getRequest()->getQueryValues();
841 $badParams = [];
842 foreach ( $params as $param ) {
843 if ( $prefix !== 'noprefix' ) {
844 $param = $this->encodeParamName( $param );
846 if ( array_key_exists( $param, $queryValues ) ) {
847 $badParams[] = $param;
851 if ( $badParams ) {
852 $this->dieWithError(
853 [ 'apierror-mustpostparams', join( ', ', $badParams ), count( $badParams ) ]
859 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
861 * @param object $x Parameter to check is not null/false
862 * @return bool
864 private function parameterNotEmpty( $x ) {
865 return !is_null( $x ) && $x !== false;
869 * Get a WikiPage object from a title or pageid param, if possible.
870 * Can die, if no param is set or if the title or page id is not valid.
872 * @param array $params
873 * @param bool|string $load Whether load the object's state from the database:
874 * - false: don't load (if the pageid is given, it will still be loaded)
875 * - 'fromdb': load from a replica DB
876 * - 'fromdbmaster': load from the master database
877 * @return WikiPage
879 public function getTitleOrPageId( $params, $load = false ) {
880 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
882 $pageObj = null;
883 if ( isset( $params['title'] ) ) {
884 $titleObj = Title::newFromText( $params['title'] );
885 if ( !$titleObj || $titleObj->isExternal() ) {
886 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
888 if ( !$titleObj->canExist() ) {
889 $this->dieWithError( 'apierror-pagecannotexist' );
891 $pageObj = WikiPage::factory( $titleObj );
892 if ( $load !== false ) {
893 $pageObj->loadPageData( $load );
895 } elseif ( isset( $params['pageid'] ) ) {
896 if ( $load === false ) {
897 $load = 'fromdb';
899 $pageObj = WikiPage::newFromID( $params['pageid'], $load );
900 if ( !$pageObj ) {
901 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
905 return $pageObj;
909 * Get a Title object from a title or pageid param, if possible.
910 * Can die, if no param is set or if the title or page id is not valid.
912 * @since 1.29
913 * @param array $params
914 * @return Title
916 public function getTitleFromTitleOrPageId( $params ) {
917 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
919 $titleObj = null;
920 if ( isset( $params['title'] ) ) {
921 $titleObj = Title::newFromText( $params['title'] );
922 if ( !$titleObj || $titleObj->isExternal() ) {
923 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
925 return $titleObj;
926 } elseif ( isset( $params['pageid'] ) ) {
927 $titleObj = Title::newFromID( $params['pageid'] );
928 if ( !$titleObj ) {
929 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
933 return $titleObj;
937 * Return true if we're to watch the page, false if not, null if no change.
938 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
939 * @param Title $titleObj The page under consideration
940 * @param string $userOption The user option to consider when $watchlist=preferences.
941 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
942 * @return bool
944 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
946 $userWatching = $this->getUser()->isWatched( $titleObj, User::IGNORE_USER_RIGHTS );
948 switch ( $watchlist ) {
949 case 'watch':
950 return true;
952 case 'unwatch':
953 return false;
955 case 'preferences':
956 # If the user is already watching, don't bother checking
957 if ( $userWatching ) {
958 return true;
960 # If no user option was passed, use watchdefault and watchcreations
961 if ( is_null( $userOption ) ) {
962 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
963 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
966 # Watch the article based on the user preference
967 return $this->getUser()->getBoolOption( $userOption );
969 case 'nochange':
970 return $userWatching;
972 default:
973 return $userWatching;
978 * Using the settings determine the value for the given parameter
980 * @param string $paramName Parameter name
981 * @param array|mixed $paramSettings Default value or an array of settings
982 * using PARAM_* constants.
983 * @param bool $parseLimit Parse limit?
984 * @return mixed Parameter value
986 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
987 // Some classes may decide to change parameter names
988 $encParamName = $this->encodeParamName( $paramName );
990 // Shorthand
991 if ( !is_array( $paramSettings ) ) {
992 $paramSettings = [
993 self::PARAM_DFLT => $paramSettings,
997 $default = isset( $paramSettings[self::PARAM_DFLT] )
998 ? $paramSettings[self::PARAM_DFLT]
999 : null;
1000 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
1001 ? $paramSettings[self::PARAM_ISMULTI]
1002 : false;
1003 $type = isset( $paramSettings[self::PARAM_TYPE] )
1004 ? $paramSettings[self::PARAM_TYPE]
1005 : null;
1006 $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] )
1007 ? $paramSettings[self::PARAM_ALLOW_DUPLICATES]
1008 : false;
1009 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] )
1010 ? $paramSettings[self::PARAM_DEPRECATED]
1011 : false;
1012 $required = isset( $paramSettings[self::PARAM_REQUIRED] )
1013 ? $paramSettings[self::PARAM_REQUIRED]
1014 : false;
1015 $allowAll = isset( $paramSettings[self::PARAM_ALL] )
1016 ? $paramSettings[self::PARAM_ALL]
1017 : false;
1019 // When type is not given, and no choices, the type is the same as $default
1020 if ( !isset( $type ) ) {
1021 if ( isset( $default ) ) {
1022 $type = gettype( $default );
1023 } else {
1024 $type = 'NULL'; // allow everything
1028 if ( $type == 'boolean' ) {
1029 if ( isset( $default ) && $default !== false ) {
1030 // Having a default value of anything other than 'false' is not allowed
1031 ApiBase::dieDebug(
1032 __METHOD__,
1033 "Boolean param $encParamName's default is set to '$default'. " .
1034 'Boolean parameters must default to false.'
1038 $value = $this->getMain()->getCheck( $encParamName );
1039 } elseif ( $type == 'upload' ) {
1040 if ( isset( $default ) ) {
1041 // Having a default value is not allowed
1042 ApiBase::dieDebug(
1043 __METHOD__,
1044 "File upload param $encParamName's default is set to " .
1045 "'$default'. File upload parameters may not have a default." );
1047 if ( $multi ) {
1048 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1050 $value = $this->getMain()->getUpload( $encParamName );
1051 if ( !$value->exists() ) {
1052 // This will get the value without trying to normalize it
1053 // (because trying to normalize a large binary file
1054 // accidentally uploaded as a field fails spectacularly)
1055 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1056 if ( $value !== null ) {
1057 $this->dieWithError(
1058 [ 'apierror-badupload', $encParamName ],
1059 "badupload_{$encParamName}"
1063 } else {
1064 $value = $this->getMain()->getVal( $encParamName, $default );
1066 if ( isset( $value ) && $type == 'namespace' ) {
1067 $type = MWNamespace::getValidNamespaces();
1068 if ( isset( $paramSettings[self::PARAM_EXTRA_NAMESPACES] ) &&
1069 is_array( $paramSettings[self::PARAM_EXTRA_NAMESPACES] )
1071 $type = array_merge( $type, $paramSettings[self::PARAM_EXTRA_NAMESPACES] );
1073 // By default, namespace parameters allow ALL_DEFAULT_STRING to be used to specify
1074 // all namespaces.
1075 $allowAll = true;
1077 if ( isset( $value ) && $type == 'submodule' ) {
1078 if ( isset( $paramSettings[self::PARAM_SUBMODULE_MAP] ) ) {
1079 $type = array_keys( $paramSettings[self::PARAM_SUBMODULE_MAP] );
1080 } else {
1081 $type = $this->getModuleManager()->getNames( $paramName );
1085 $request = $this->getMain()->getRequest();
1086 $rawValue = $request->getRawVal( $encParamName );
1087 if ( $rawValue === null ) {
1088 $rawValue = $default;
1091 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1092 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1093 if ( $multi ) {
1094 // This loses the potential $wgContLang->checkTitleEncoding() transformation
1095 // done by WebRequest for $_GET. Let's call that a feature.
1096 $value = join( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1097 } else {
1098 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1102 // Check for NFC normalization, and warn
1103 if ( $rawValue !== $value ) {
1104 $this->handleParamNormalization( $paramName, $value, $rawValue );
1108 $allSpecifier = ( is_string( $allowAll ) ? $allowAll : self::ALL_DEFAULT_STRING );
1109 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1110 ApiBase::dieDebug(
1111 __METHOD__,
1112 "For param $encParamName, PARAM_ALL collides with a possible value" );
1114 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
1115 $value = $this->parseMultiValue(
1116 $encParamName,
1117 $value,
1118 $multi,
1119 is_array( $type ) ? $type : null,
1120 $allowAll ? $allSpecifier : null
1124 // More validation only when choices were not given
1125 // choices were validated in parseMultiValue()
1126 if ( isset( $value ) ) {
1127 if ( !is_array( $type ) ) {
1128 switch ( $type ) {
1129 case 'NULL': // nothing to do
1130 break;
1131 case 'string':
1132 case 'text':
1133 case 'password':
1134 if ( $required && $value === '' ) {
1135 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1137 break;
1138 case 'integer': // Force everything using intval() and optionally validate limits
1139 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
1140 $max = isset( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
1141 $enforceLimits = isset( $paramSettings[self::PARAM_RANGE_ENFORCE] )
1142 ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
1144 if ( is_array( $value ) ) {
1145 $value = array_map( 'intval', $value );
1146 if ( !is_null( $min ) || !is_null( $max ) ) {
1147 foreach ( $value as &$v ) {
1148 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1151 } else {
1152 $value = intval( $value );
1153 if ( !is_null( $min ) || !is_null( $max ) ) {
1154 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1157 break;
1158 case 'limit':
1159 if ( !$parseLimit ) {
1160 // Don't do any validation whatsoever
1161 break;
1163 if ( !isset( $paramSettings[self::PARAM_MAX] )
1164 || !isset( $paramSettings[self::PARAM_MAX2] )
1166 ApiBase::dieDebug(
1167 __METHOD__,
1168 "MAX1 or MAX2 are not defined for the limit $encParamName"
1171 if ( $multi ) {
1172 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1174 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
1175 if ( $value == 'max' ) {
1176 $value = $this->getMain()->canApiHighLimits()
1177 ? $paramSettings[self::PARAM_MAX2]
1178 : $paramSettings[self::PARAM_MAX];
1179 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1180 } else {
1181 $value = intval( $value );
1182 $this->validateLimit(
1183 $paramName,
1184 $value,
1185 $min,
1186 $paramSettings[self::PARAM_MAX],
1187 $paramSettings[self::PARAM_MAX2]
1190 break;
1191 case 'boolean':
1192 if ( $multi ) {
1193 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1195 break;
1196 case 'timestamp':
1197 if ( is_array( $value ) ) {
1198 foreach ( $value as $key => $val ) {
1199 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1201 } else {
1202 $value = $this->validateTimestamp( $value, $encParamName );
1204 break;
1205 case 'user':
1206 if ( is_array( $value ) ) {
1207 foreach ( $value as $key => $val ) {
1208 $value[$key] = $this->validateUser( $val, $encParamName );
1210 } else {
1211 $value = $this->validateUser( $value, $encParamName );
1213 break;
1214 case 'upload': // nothing to do
1215 break;
1216 case 'tags':
1217 // If change tagging was requested, check that the tags are valid.
1218 if ( !is_array( $value ) && !$multi ) {
1219 $value = [ $value ];
1221 $tagsStatus = ChangeTags::canAddTagsAccompanyingChange( $value );
1222 if ( !$tagsStatus->isGood() ) {
1223 $this->dieStatus( $tagsStatus );
1225 break;
1226 default:
1227 ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
1231 // Throw out duplicates if requested
1232 if ( !$dupes && is_array( $value ) ) {
1233 $value = array_unique( $value );
1236 // Set a warning if a deprecated parameter has been passed
1237 if ( $deprecated && $value !== false ) {
1238 $feature = $encParamName;
1239 $m = $this;
1240 while ( !$m->isMain() ) {
1241 $p = $m->getParent();
1242 $name = $m->getModuleName();
1243 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1244 $feature = "{$param}={$name}&{$feature}";
1245 $m = $p;
1247 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1249 } elseif ( $required ) {
1250 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1253 return $value;
1257 * Handle when a parameter was Unicode-normalized
1258 * @since 1.28
1259 * @param string $paramName Unprefixed parameter name
1260 * @param string $value Input that will be used.
1261 * @param string $rawValue Input before normalization.
1263 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1264 $encParamName = $this->encodeParamName( $paramName );
1265 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1269 * Split a multi-valued parameter string, like explode()
1270 * @since 1.28
1271 * @param string $value
1272 * @param int $limit
1273 * @return string[]
1275 protected function explodeMultiValue( $value, $limit ) {
1276 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1277 $sep = "\x1f";
1278 $value = substr( $value, 1 );
1279 } else {
1280 $sep = '|';
1283 return explode( $sep, $value, $limit );
1287 * Return an array of values that were given in a 'a|b|c' notation,
1288 * after it optionally validates them against the list allowed values.
1290 * @param string $valueName The name of the parameter (for error
1291 * reporting)
1292 * @param mixed $value The value being parsed
1293 * @param bool $allowMultiple Can $value contain more than one value
1294 * separated by '|'?
1295 * @param string[]|null $allowedValues An array of values to check against. If
1296 * null, all values are accepted.
1297 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1298 * if this behavior should not be allowed
1299 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1301 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1302 $allSpecifier = null
1304 if ( ( trim( $value ) === '' || trim( $value ) === "\x1f" ) && $allowMultiple ) {
1305 return [];
1308 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1309 // because it unstubs $wgUser
1310 $valuesList = $this->explodeMultiValue( $value, self::LIMIT_SML2 + 1 );
1311 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits()
1312 ? self::LIMIT_SML2
1313 : self::LIMIT_SML1;
1315 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1316 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1318 return $allowedValues;
1321 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
1322 $this->addDeprecation(
1323 [ 'apiwarn-toomanyvalues', $valueName, $sizeLimit ],
1324 "too-many-$valueName-for-{$this->getModulePath()}"
1328 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1329 // T35482 - Allow entries with | in them for non-multiple values
1330 if ( in_array( $value, $allowedValues, true ) ) {
1331 return $value;
1334 if ( is_array( $allowedValues ) ) {
1335 $values = array_map( function ( $v ) {
1336 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1337 }, $allowedValues );
1338 $this->dieWithError( [
1339 'apierror-multival-only-one-of',
1340 $valueName,
1341 Message::listParam( $values ),
1342 count( $values ),
1343 ], "multival_$valueName" );
1344 } else {
1345 $this->dieWithError( [
1346 'apierror-multival-only-one',
1347 $valueName,
1348 ], "multival_$valueName" );
1352 if ( is_array( $allowedValues ) ) {
1353 // Check for unknown values
1354 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1355 if ( count( $unknown ) ) {
1356 if ( $allowMultiple ) {
1357 $this->addWarning( [
1358 'apiwarn-unrecognizedvalues',
1359 $valueName,
1360 Message::listParam( $unknown, 'comma' ),
1361 count( $unknown ),
1362 ] );
1363 } else {
1364 $this->dieWithError(
1365 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1366 "unknown_$valueName"
1370 // Now throw them out
1371 $valuesList = array_intersect( $valuesList, $allowedValues );
1374 return $allowMultiple ? $valuesList : $valuesList[0];
1378 * Validate the value against the minimum and user/bot maximum limits.
1379 * Prints usage info on failure.
1380 * @param string $paramName Parameter name
1381 * @param int $value Parameter value
1382 * @param int|null $min Minimum value
1383 * @param int|null $max Maximum value for users
1384 * @param int $botMax Maximum value for sysops/bots
1385 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1387 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1388 $enforceLimits = false
1390 if ( !is_null( $min ) && $value < $min ) {
1391 $msg = ApiMessage::create(
1392 [ 'apierror-integeroutofrange-belowminimum',
1393 $this->encodeParamName( $paramName ), $min, $value ],
1394 'integeroutofrange',
1395 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
1397 $this->warnOrDie( $msg, $enforceLimits );
1398 $value = $min;
1401 // Minimum is always validated, whereas maximum is checked only if not
1402 // running in internal call mode
1403 if ( $this->getMain()->isInternalMode() ) {
1404 return;
1407 // Optimization: do not check user's bot status unless really needed -- skips db query
1408 // assumes $botMax >= $max
1409 if ( !is_null( $max ) && $value > $max ) {
1410 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1411 if ( $value > $botMax ) {
1412 $msg = ApiMessage::create(
1413 [ 'apierror-integeroutofrange-abovebotmax',
1414 $this->encodeParamName( $paramName ), $botMax, $value ],
1415 'integeroutofrange',
1416 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
1418 $this->warnOrDie( $msg, $enforceLimits );
1419 $value = $botMax;
1421 } else {
1422 $msg = ApiMessage::create(
1423 [ 'apierror-integeroutofrange-abovemax',
1424 $this->encodeParamName( $paramName ), $max, $value ],
1425 'integeroutofrange',
1426 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
1428 $this->warnOrDie( $msg, $enforceLimits );
1429 $value = $max;
1435 * Validate and normalize of parameters of type 'timestamp'
1436 * @param string $value Parameter value
1437 * @param string $encParamName Parameter name
1438 * @return string Validated and normalized parameter
1440 protected function validateTimestamp( $value, $encParamName ) {
1441 // Confusing synonyms for the current time accepted by wfTimestamp()
1442 // (wfTimestamp() also accepts various non-strings and the string of 14
1443 // ASCII NUL bytes, but those can't get here)
1444 if ( !$value ) {
1445 $this->addDeprecation(
1446 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1447 'unclear-"now"-timestamp'
1449 return wfTimestamp( TS_MW );
1452 // Explicit synonym for the current time
1453 if ( $value === 'now' ) {
1454 return wfTimestamp( TS_MW );
1457 $unixTimestamp = wfTimestamp( TS_UNIX, $value );
1458 if ( $unixTimestamp === false ) {
1459 $this->dieWithError(
1460 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1461 "badtimestamp_{$encParamName}"
1465 return wfTimestamp( TS_MW, $unixTimestamp );
1469 * Validate the supplied token.
1471 * @since 1.24
1472 * @param string $token Supplied token
1473 * @param array $params All supplied parameters for the module
1474 * @return bool
1475 * @throws MWException
1477 final public function validateToken( $token, array $params ) {
1478 $tokenType = $this->needsToken();
1479 $salts = ApiQueryTokens::getTokenTypeSalts();
1480 if ( !isset( $salts[$tokenType] ) ) {
1481 throw new MWException(
1482 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1483 'without registering it'
1487 $tokenObj = ApiQueryTokens::getToken(
1488 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1490 if ( $tokenObj->match( $token ) ) {
1491 return true;
1494 $webUiSalt = $this->getWebUITokenSalt( $params );
1495 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1496 $token,
1497 $webUiSalt,
1498 $this->getRequest()
1499 ) ) {
1500 return true;
1503 return false;
1507 * Validate and normalize of parameters of type 'user'
1508 * @param string $value Parameter value
1509 * @param string $encParamName Parameter name
1510 * @return string Validated and normalized parameter
1512 private function validateUser( $value, $encParamName ) {
1513 $title = Title::makeTitleSafe( NS_USER, $value );
1514 if ( $title === null || $title->hasFragment() ) {
1515 $this->dieWithError(
1516 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1517 "baduser_{$encParamName}"
1521 return $title->getText();
1524 /**@}*/
1526 /************************************************************************//**
1527 * @name Utility methods
1528 * @{
1532 * Set a watch (or unwatch) based the based on a watchlist parameter.
1533 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1534 * @param Title $titleObj The article's title to change
1535 * @param string $userOption The user option to consider when $watch=preferences
1537 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1538 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1539 if ( $value === null ) {
1540 return;
1543 WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1547 * Truncate an array to a certain length.
1548 * @param array $arr Array to truncate
1549 * @param int $limit Maximum length
1550 * @return bool True if the array was truncated, false otherwise
1552 public static function truncateArray( &$arr, $limit ) {
1553 $modified = false;
1554 while ( count( $arr ) > $limit ) {
1555 array_pop( $arr );
1556 $modified = true;
1559 return $modified;
1563 * Gets the user for whom to get the watchlist
1565 * @param array $params
1566 * @return User
1568 public function getWatchlistUser( $params ) {
1569 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1570 $user = User::newFromName( $params['owner'], false );
1571 if ( !( $user && $user->getId() ) ) {
1572 $this->dieWithError(
1573 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1576 $token = $user->getOption( 'watchlisttoken' );
1577 if ( $token == '' || !hash_equals( $token, $params['token'] ) ) {
1578 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1580 } else {
1581 if ( !$this->getUser()->isLoggedIn() ) {
1582 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1584 $this->checkUserRightsAny( 'viewmywatchlist' );
1585 $user = $this->getUser();
1588 return $user;
1592 * A subset of wfEscapeWikiText for BC texts
1594 * @since 1.25
1595 * @param string|array $v
1596 * @return string|array
1598 private static function escapeWikiText( $v ) {
1599 if ( is_array( $v ) ) {
1600 return array_map( 'self::escapeWikiText', $v );
1601 } else {
1602 return strtr( $v, [
1603 '__' => '_&#95;', '{' => '&#123;', '}' => '&#125;',
1604 '[[Category:' => '[[:Category:',
1605 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1606 ] );
1611 * Create a Message from a string or array
1613 * A string is used as a message key. An array has the message key as the
1614 * first value and message parameters as subsequent values.
1616 * @since 1.25
1617 * @param string|array|Message $msg
1618 * @param IContextSource $context
1619 * @param array $params
1620 * @return Message|null
1622 public static function makeMessage( $msg, IContextSource $context, array $params = null ) {
1623 if ( is_string( $msg ) ) {
1624 $msg = wfMessage( $msg );
1625 } elseif ( is_array( $msg ) ) {
1626 $msg = call_user_func_array( 'wfMessage', $msg );
1628 if ( !$msg instanceof Message ) {
1629 return null;
1632 $msg->setContext( $context );
1633 if ( $params ) {
1634 $msg->params( $params );
1637 return $msg;
1641 * Turn an array of message keys or key+param arrays into a Status
1642 * @since 1.29
1643 * @param array $errors
1644 * @param User|null $user
1645 * @return Status
1647 public function errorArrayToStatus( array $errors, User $user = null ) {
1648 if ( $user === null ) {
1649 $user = $this->getUser();
1652 $status = Status::newGood();
1653 foreach ( $errors as $error ) {
1654 if ( is_array( $error ) && $error[0] === 'blockedtext' && $user->getBlock() ) {
1655 $status->fatal( ApiMessage::create(
1656 'apierror-blocked',
1657 'blocked',
1658 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
1659 ) );
1660 } elseif ( is_array( $error ) && $error[0] === 'autoblockedtext' && $user->getBlock() ) {
1661 $status->fatal( ApiMessage::create(
1662 'apierror-autoblocked',
1663 'autoblocked',
1664 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
1665 ) );
1666 } elseif ( is_array( $error ) && $error[0] === 'systemblockedtext' && $user->getBlock() ) {
1667 $status->fatal( ApiMessage::create(
1668 'apierror-systemblocked',
1669 'blocked',
1670 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
1671 ) );
1672 } else {
1673 call_user_func_array( [ $status, 'fatal' ], (array)$error );
1676 return $status;
1679 /**@}*/
1681 /************************************************************************//**
1682 * @name Warning and error reporting
1683 * @{
1687 * Add a warning for this module.
1689 * Users should monitor this section to notice any changes in API. Multiple
1690 * calls to this function will result in multiple warning messages.
1692 * If $msg is not an ApiMessage, the message code will be derived from the
1693 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1695 * @since 1.29
1696 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1697 * @param string|null $code See ApiErrorFormatter::addWarning()
1698 * @param array|null $data See ApiErrorFormatter::addWarning()
1700 public function addWarning( $msg, $code = null, $data = null ) {
1701 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1705 * Add a deprecation warning for this module.
1707 * A combination of $this->addWarning() and $this->logFeatureUsage()
1709 * @since 1.29
1710 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1711 * @param string|null $feature See ApiBase::logFeatureUsage()
1712 * @param array|null $data See ApiErrorFormatter::addWarning()
1714 public function addDeprecation( $msg, $feature, $data = [] ) {
1715 $data = (array)$data;
1716 if ( $feature !== null ) {
1717 $data['feature'] = $feature;
1718 $this->logFeatureUsage( $feature );
1720 $this->addWarning( $msg, 'deprecation', $data );
1722 // No real need to deduplicate here, ApiErrorFormatter does that for
1723 // us (assuming the hook is deterministic).
1724 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1725 Hooks::run( 'ApiDeprecationHelp', [ &$msgs ] );
1726 if ( count( $msgs ) > 1 ) {
1727 $key = '$' . join( ' $', range( 1, count( $msgs ) ) );
1728 $msg = ( new RawMessage( $key ) )->params( $msgs );
1729 } else {
1730 $msg = reset( $msgs );
1732 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1736 * Add an error for this module without aborting
1738 * If $msg is not an ApiMessage, the message code will be derived from the
1739 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1741 * @note If you want to abort processing, use self::dieWithError() instead.
1742 * @since 1.29
1743 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1744 * @param string|null $code See ApiErrorFormatter::addError()
1745 * @param array|null $data See ApiErrorFormatter::addError()
1747 public function addError( $msg, $code = null, $data = null ) {
1748 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1752 * Add warnings and/or errors from a Status
1754 * @note If you want to abort processing, use self::dieStatus() instead.
1755 * @since 1.29
1756 * @param StatusValue $status
1757 * @param string[] $types 'warning' and/or 'error'
1759 public function addMessagesFromStatus( StatusValue $status, $types = [ 'warning', 'error' ] ) {
1760 $this->getErrorFormatter()->addMessagesFromStatus( $this->getModulePath(), $status, $types );
1764 * Abort execution with an error
1766 * If $msg is not an ApiMessage, the message code will be derived from the
1767 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1769 * @since 1.29
1770 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1771 * @param string|null $code See ApiErrorFormatter::addError()
1772 * @param array|null $data See ApiErrorFormatter::addError()
1773 * @param int|null $httpCode HTTP error code to use
1774 * @throws ApiUsageException always
1776 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1777 throw ApiUsageException::newWithMessage( $this, $msg, $code, $data, $httpCode );
1781 * Abort execution with an error derived from an exception
1783 * @since 1.29
1784 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
1785 * @param array $options See ApiErrorFormatter::getMessageFromException()
1786 * @throws ApiUsageException always
1788 public function dieWithException( $exception, array $options = [] ) {
1789 $this->dieWithError(
1790 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
1795 * Adds a warning to the output, else dies
1797 * @param ApiMessage $msg Message to show as a warning, or error message if dying
1798 * @param bool $enforceLimits Whether this is an enforce (die)
1800 private function warnOrDie( ApiMessage $msg, $enforceLimits = false ) {
1801 if ( $enforceLimits ) {
1802 $this->dieWithError( $msg );
1803 } else {
1804 $this->addWarning( $msg );
1809 * Throw an ApiUsageException, which will (if uncaught) call the main module's
1810 * error handler and die with an error message including block info.
1812 * @since 1.27
1813 * @param Block $block The block used to generate the ApiUsageException
1814 * @throws ApiUsageException always
1816 public function dieBlocked( Block $block ) {
1817 // Die using the appropriate message depending on block type
1818 if ( $block->getType() == Block::TYPE_AUTO ) {
1819 $this->dieWithError(
1820 'apierror-autoblocked',
1821 'autoblocked',
1822 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ]
1824 } else {
1825 $this->dieWithError(
1826 'apierror-blocked',
1827 'blocked',
1828 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ]
1834 * Throw an ApiUsageException based on the Status object.
1836 * @since 1.22
1837 * @since 1.29 Accepts a StatusValue
1838 * @param StatusValue $status
1839 * @throws ApiUsageException always
1841 public function dieStatus( StatusValue $status ) {
1842 if ( $status->isGood() ) {
1843 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1846 throw new ApiUsageException( $this, $status );
1850 * Helper function for readonly errors
1852 * @throws ApiUsageException always
1854 public function dieReadOnly() {
1855 $this->dieWithError(
1856 'apierror-readonly',
1857 'readonly',
1858 [ 'readonlyreason' => wfReadOnlyReason() ]
1863 * Helper function for permission-denied errors
1864 * @since 1.29
1865 * @param string|string[] $rights
1866 * @param User|null $user
1867 * @throws ApiUsageException if the user doesn't have any of the rights.
1868 * The error message is based on $rights[0].
1870 public function checkUserRightsAny( $rights, $user = null ) {
1871 if ( !$user ) {
1872 $user = $this->getUser();
1874 $rights = (array)$rights;
1875 if ( !call_user_func_array( [ $user, 'isAllowedAny' ], $rights ) ) {
1876 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
1881 * Helper function for permission-denied errors
1882 * @since 1.29
1883 * @param Title $title
1884 * @param string|string[] $actions
1885 * @param User|null $user
1886 * @throws ApiUsageException if the user doesn't have all of the rights.
1888 public function checkTitleUserPermissions( Title $title, $actions, $user = null ) {
1889 if ( !$user ) {
1890 $user = $this->getUser();
1893 $errors = [];
1894 foreach ( (array)$actions as $action ) {
1895 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
1897 if ( $errors ) {
1898 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
1903 * Will only set a warning instead of failing if the global $wgDebugAPI
1904 * is set to true. Otherwise behaves exactly as self::dieWithError().
1906 * @since 1.29
1907 * @param string|array|Message $msg
1908 * @param string|null $code
1909 * @param array|null $data
1910 * @param int|null $httpCode
1911 * @throws ApiUsageException
1913 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
1914 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1915 $this->dieWithError( $msg, $code, $data, $httpCode );
1916 } else {
1917 $this->addWarning( $msg, $code, $data );
1922 * Die with the 'badcontinue' error.
1924 * This call is common enough to make it into the base method.
1926 * @param bool $condition Will only die if this value is true
1927 * @throws ApiUsageException
1928 * @since 1.21
1930 protected function dieContinueUsageIf( $condition ) {
1931 if ( $condition ) {
1932 $this->dieWithError( 'apierror-badcontinue' );
1937 * Internal code errors should be reported with this method
1938 * @param string $method Method or function name
1939 * @param string $message Error message
1940 * @throws MWException always
1942 protected static function dieDebug( $method, $message ) {
1943 throw new MWException( "Internal error in $method: $message" );
1947 * Write logging information for API features to a debug log, for usage
1948 * analysis.
1949 * @note Consider using $this->addDeprecation() instead to both warn and log.
1950 * @param string $feature Feature being used.
1952 public function logFeatureUsage( $feature ) {
1953 $request = $this->getRequest();
1954 $s = '"' . addslashes( $feature ) . '"' .
1955 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
1956 ' "' . $request->getIP() . '"' .
1957 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
1958 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
1959 wfDebugLog( 'api-feature-usage', $s, 'private' );
1962 /**@}*/
1964 /************************************************************************//**
1965 * @name Help message generation
1966 * @{
1970 * Return the description message.
1972 * @return string|array|Message
1974 protected function getDescriptionMessage() {
1975 return "apihelp-{$this->getModulePath()}-description";
1979 * Get final module description, after hooks have had a chance to tweak it as
1980 * needed.
1982 * @since 1.25, returns Message[] rather than string[]
1983 * @return Message[]
1985 public function getFinalDescription() {
1986 $desc = $this->getDescription();
1988 // Avoid PHP 7.1 warning of passing $this by reference
1989 $apiModule = $this;
1990 Hooks::run( 'APIGetDescription', [ &$apiModule, &$desc ] );
1991 $desc = self::escapeWikiText( $desc );
1992 if ( is_array( $desc ) ) {
1993 $desc = implode( "\n", $desc );
1994 } else {
1995 $desc = (string)$desc;
1998 $msg = ApiBase::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
1999 $this->getModulePrefix(),
2000 $this->getModuleName(),
2001 $this->getModulePath(),
2002 ] );
2003 if ( !$msg->exists() ) {
2004 $msg = $this->msg( 'api-help-fallback-description', $desc );
2006 $msgs = [ $msg ];
2008 Hooks::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2010 return $msgs;
2014 * Get final list of parameters, after hooks have had a chance to
2015 * tweak it as needed.
2017 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2018 * @return array|bool False on no parameters
2019 * @since 1.21 $flags param added
2021 public function getFinalParams( $flags = 0 ) {
2022 $params = $this->getAllowedParams( $flags );
2023 if ( !$params ) {
2024 $params = [];
2027 if ( $this->needsToken() ) {
2028 $params['token'] = [
2029 ApiBase::PARAM_TYPE => 'string',
2030 ApiBase::PARAM_REQUIRED => true,
2031 ApiBase::PARAM_HELP_MSG => [
2032 'api-help-param-token',
2033 $this->needsToken(),
2035 ] + ( isset( $params['token'] ) ? $params['token'] : [] );
2038 // Avoid PHP 7.1 warning of passing $this by reference
2039 $apiModule = $this;
2040 Hooks::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2042 return $params;
2046 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2047 * needed.
2049 * @since 1.25, returns array of Message[] rather than array of string[]
2050 * @return array Keys are parameter names, values are arrays of Message objects
2052 public function getFinalParamDescription() {
2053 $prefix = $this->getModulePrefix();
2054 $name = $this->getModuleName();
2055 $path = $this->getModulePath();
2057 $desc = $this->getParamDescription();
2059 // Avoid PHP 7.1 warning of passing $this by reference
2060 $apiModule = $this;
2061 Hooks::run( 'APIGetParamDescription', [ &$apiModule, &$desc ] );
2063 if ( !$desc ) {
2064 $desc = [];
2066 $desc = self::escapeWikiText( $desc );
2068 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
2069 $msgs = [];
2070 foreach ( $params as $param => $settings ) {
2071 if ( !is_array( $settings ) ) {
2072 $settings = [];
2075 $d = isset( $desc[$param] ) ? $desc[$param] : '';
2076 if ( is_array( $d ) ) {
2077 // Special handling for prop parameters
2078 $d = array_map( function ( $line ) {
2079 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2080 $line = "\n;{$m[1]}:{$m[2]}";
2082 return $line;
2083 }, $d );
2084 $d = implode( ' ', $d );
2087 if ( isset( $settings[ApiBase::PARAM_HELP_MSG] ) ) {
2088 $msg = $settings[ApiBase::PARAM_HELP_MSG];
2089 } else {
2090 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2091 if ( !$msg->exists() ) {
2092 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2095 $msg = ApiBase::makeMessage( $msg, $this->getContext(),
2096 [ $prefix, $param, $name, $path ] );
2097 if ( !$msg ) {
2098 self::dieDebug( __METHOD__,
2099 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2101 $msgs[$param] = [ $msg ];
2103 if ( isset( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
2104 if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
2105 self::dieDebug( __METHOD__,
2106 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2108 if ( !is_array( $settings[ApiBase::PARAM_TYPE] ) ) {
2109 self::dieDebug( __METHOD__,
2110 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2111 'ApiBase::PARAM_TYPE is an array' );
2114 $valueMsgs = $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE];
2115 foreach ( $settings[ApiBase::PARAM_TYPE] as $value ) {
2116 if ( isset( $valueMsgs[$value] ) ) {
2117 $msg = $valueMsgs[$value];
2118 } else {
2119 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2121 $m = ApiBase::makeMessage( $msg, $this->getContext(),
2122 [ $prefix, $param, $name, $path, $value ] );
2123 if ( $m ) {
2124 $m = new ApiHelpParamValueMessage(
2125 $value,
2126 [ $m->getKey(), 'api-help-param-no-description' ],
2127 $m->getParams()
2129 $msgs[$param][] = $m->setContext( $this->getContext() );
2130 } else {
2131 self::dieDebug( __METHOD__,
2132 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2137 if ( isset( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2138 if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2139 self::dieDebug( __METHOD__,
2140 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2142 foreach ( $settings[ApiBase::PARAM_HELP_MSG_APPEND] as $m ) {
2143 $m = ApiBase::makeMessage( $m, $this->getContext(),
2144 [ $prefix, $param, $name, $path ] );
2145 if ( $m ) {
2146 $msgs[$param][] = $m;
2147 } else {
2148 self::dieDebug( __METHOD__,
2149 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2155 Hooks::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2157 return $msgs;
2161 * Generates the list of flags for the help screen and for action=paraminfo
2163 * Corresponding messages: api-help-flag-deprecated,
2164 * api-help-flag-internal, api-help-flag-readrights,
2165 * api-help-flag-writerights, api-help-flag-mustbeposted
2167 * @return string[]
2169 protected function getHelpFlags() {
2170 $flags = [];
2172 if ( $this->isDeprecated() ) {
2173 $flags[] = 'deprecated';
2175 if ( $this->isInternal() ) {
2176 $flags[] = 'internal';
2178 if ( $this->isReadMode() ) {
2179 $flags[] = 'readrights';
2181 if ( $this->isWriteMode() ) {
2182 $flags[] = 'writerights';
2184 if ( $this->mustBePosted() ) {
2185 $flags[] = 'mustbeposted';
2188 return $flags;
2192 * Returns information about the source of this module, if known
2194 * Returned array is an array with the following keys:
2195 * - path: Install path
2196 * - name: Extension name, or "MediaWiki" for core
2197 * - namemsg: (optional) i18n message key for a display name
2198 * - license-name: (optional) Name of license
2200 * @return array|null
2202 protected function getModuleSourceInfo() {
2203 global $IP;
2205 if ( $this->mModuleSource !== false ) {
2206 return $this->mModuleSource;
2209 // First, try to find where the module comes from...
2210 $rClass = new ReflectionClass( $this );
2211 $path = $rClass->getFileName();
2212 if ( !$path ) {
2213 // No path known?
2214 $this->mModuleSource = null;
2215 return null;
2217 $path = realpath( $path ) ?: $path;
2219 // Build map of extension directories to extension info
2220 if ( self::$extensionInfo === null ) {
2221 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2222 self::$extensionInfo = [
2223 realpath( __DIR__ ) ?: __DIR__ => [
2224 'path' => $IP,
2225 'name' => 'MediaWiki',
2226 'license-name' => 'GPL-2.0+',
2228 realpath( "$IP/extensions" ) ?: "$IP/extensions" => null,
2229 realpath( $extDir ) ?: $extDir => null,
2231 $keep = [
2232 'path' => null,
2233 'name' => null,
2234 'namemsg' => null,
2235 'license-name' => null,
2237 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2238 foreach ( $group as $ext ) {
2239 if ( !isset( $ext['path'] ) || !isset( $ext['name'] ) ) {
2240 // This shouldn't happen, but does anyway.
2241 continue;
2244 $extpath = $ext['path'];
2245 if ( !is_dir( $extpath ) ) {
2246 $extpath = dirname( $extpath );
2248 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2249 array_intersect_key( $ext, $keep );
2252 foreach ( ExtensionRegistry::getInstance()->getAllThings() as $ext ) {
2253 $extpath = $ext['path'];
2254 if ( !is_dir( $extpath ) ) {
2255 $extpath = dirname( $extpath );
2257 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2258 array_intersect_key( $ext, $keep );
2262 // Now traverse parent directories until we find a match or run out of
2263 // parents.
2264 do {
2265 if ( array_key_exists( $path, self::$extensionInfo ) ) {
2266 // Found it!
2267 $this->mModuleSource = self::$extensionInfo[$path];
2268 return $this->mModuleSource;
2271 $oldpath = $path;
2272 $path = dirname( $path );
2273 } while ( $path !== $oldpath );
2275 // No idea what extension this might be.
2276 $this->mModuleSource = null;
2277 return null;
2281 * Called from ApiHelp before the pieces are joined together and returned.
2283 * This exists mainly for ApiMain to add the Permissions and Credits
2284 * sections. Other modules probably don't need it.
2286 * @param string[] &$help Array of help data
2287 * @param array $options Options passed to ApiHelp::getHelp
2288 * @param array &$tocData If a TOC is being generated, this array has keys
2289 * as anchors in the page and values as for Linker::generateTOC().
2291 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2294 /**@}*/
2296 /************************************************************************//**
2297 * @name Deprecated
2298 * @{
2302 * Returns the description string for this module
2304 * Ignored if an i18n message exists for
2305 * "apihelp-{$this->getModulePath()}-description".
2307 * @deprecated since 1.25
2308 * @return Message|string|array|false
2310 protected function getDescription() {
2311 return false;
2315 * Returns an array of parameter descriptions.
2317 * For each parameter, ignored if an i18n message exists for the parameter.
2318 * By default that message is
2319 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2320 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2321 * self::getFinalParams().
2323 * @deprecated since 1.25
2324 * @return array|bool False on no parameter descriptions
2326 protected function getParamDescription() {
2327 return [];
2331 * Returns usage examples for this module.
2333 * Return value as an array is either:
2334 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2335 * values
2336 * - sequential numeric keys with even-numbered keys being display-text
2337 * and odd-numbered keys being partial urls
2338 * - partial URLs as keys with display-text (string or array-to-be-joined)
2339 * as values
2340 * Return value as a string is the same as an array with a numeric key and
2341 * that value, and boolean false means "no examples".
2343 * @deprecated since 1.25, use getExamplesMessages() instead
2344 * @return bool|string|array
2346 protected function getExamples() {
2347 return false;
2351 * @deprecated since 1.25, always returns empty string
2352 * @param IDatabase|bool $db
2353 * @return string
2355 public function getModuleProfileName( $db = false ) {
2356 wfDeprecated( __METHOD__, '1.25' );
2357 return '';
2361 * @deprecated since 1.25
2363 public function profileIn() {
2364 // No wfDeprecated() yet because extensions call this and might need to
2365 // keep doing so for BC.
2369 * @deprecated since 1.25
2371 public function profileOut() {
2372 // No wfDeprecated() yet because extensions call this and might need to
2373 // keep doing so for BC.
2377 * @deprecated since 1.25
2379 public function safeProfileOut() {
2380 wfDeprecated( __METHOD__, '1.25' );
2384 * @deprecated since 1.25, always returns 0
2385 * @return float
2387 public function getProfileTime() {
2388 wfDeprecated( __METHOD__, '1.25' );
2389 return 0;
2393 * @deprecated since 1.25
2395 public function profileDBIn() {
2396 wfDeprecated( __METHOD__, '1.25' );
2400 * @deprecated since 1.25
2402 public function profileDBOut() {
2403 wfDeprecated( __METHOD__, '1.25' );
2407 * @deprecated since 1.25, always returns 0
2408 * @return float
2410 public function getProfileDBTime() {
2411 wfDeprecated( __METHOD__, '1.25' );
2412 return 0;
2416 * Call wfTransactionalTimeLimit() if this request was POSTed
2417 * @since 1.26
2419 protected function useTransactionalTimeLimit() {
2420 if ( $this->getRequest()->wasPosted() ) {
2421 wfTransactionalTimeLimit();
2426 * @deprecated since 1.29, use ApiBase::addWarning() instead
2427 * @param string $warning Warning message
2429 public function setWarning( $warning ) {
2430 $msg = new ApiRawMessage( $warning, 'warning' );
2431 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg );
2435 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2436 * error handler and die with an error message.
2438 * @deprecated since 1.29, use self::dieWithError() instead
2439 * @param string $description One-line human-readable description of the
2440 * error condition, e.g., "The API requires a valid action parameter"
2441 * @param string $errorCode Brief, arbitrary, stable string to allow easy
2442 * automated identification of the error, e.g., 'unknown_action'
2443 * @param int $httpRespCode HTTP response code
2444 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
2445 * @throws ApiUsageException always
2447 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
2448 $this->dieWithError(
2449 new RawMessage( '$1', [ $description ] ),
2450 $errorCode,
2451 $extradata,
2452 $httpRespCode
2457 * Get error (as code, string) from a Status object.
2459 * @since 1.23
2460 * @deprecated since 1.29, use ApiErrorFormatter::arrayFromStatus instead
2461 * @param Status $status
2462 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
2463 * @return array Array of code and error string
2464 * @throws MWException
2466 public function getErrorFromStatus( $status, &$extraData = null ) {
2467 if ( $status->isGood() ) {
2468 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2471 $errors = $status->getErrorsByType( 'error' );
2472 if ( !$errors ) {
2473 // No errors? Assume the warnings should be treated as errors
2474 $errors = $status->getErrorsByType( 'warning' );
2476 if ( !$errors ) {
2477 // Still no errors? Punt
2478 $errors = [ [ 'message' => 'unknownerror-nocode', 'params' => [] ] ];
2481 if ( $errors[0]['message'] instanceof MessageSpecifier ) {
2482 $msg = $errors[0]['message'];
2483 } else {
2484 $msg = new Message( $errors[0]['message'], $errors[0]['params'] );
2486 if ( !$msg instanceof IApiMessage ) {
2487 $key = $msg->getKey();
2488 $params = $msg->getParams();
2489 array_unshift( $params, isset( self::$messageMap[$key] ) ? self::$messageMap[$key] : $key );
2490 $msg = ApiMessage::create( $params );
2493 return [
2494 $msg->getApiCode(),
2495 ApiErrorFormatter::stripMarkup( $msg->inLanguage( 'en' )->useDatabase( false )->text() )
2500 * @deprecated since 1.29. Prior to 1.29, this was a public mapping from
2501 * arbitrary strings (often message keys used elsewhere in MediaWiki) to
2502 * API codes and message texts, and a few interfaces required poking
2503 * something in here. Now we're repurposing it to map those same strings
2504 * to i18n messages, and declaring that any interface that requires poking
2505 * at this is broken and needs replacing ASAP.
2507 private static $messageMap = [
2508 'unknownerror' => 'apierror-unknownerror',
2509 'unknownerror-nocode' => 'apierror-unknownerror-nocode',
2510 'ns-specialprotected' => 'ns-specialprotected',
2511 'protectedinterface' => 'protectedinterface',
2512 'namespaceprotected' => 'namespaceprotected',
2513 'customcssprotected' => 'customcssprotected',
2514 'customjsprotected' => 'customjsprotected',
2515 'cascadeprotected' => 'cascadeprotected',
2516 'protectedpagetext' => 'protectedpagetext',
2517 'protect-cantedit' => 'protect-cantedit',
2518 'deleteprotected' => 'deleteprotected',
2519 'badaccess-group0' => 'badaccess-group0',
2520 'badaccess-groups' => 'badaccess-groups',
2521 'titleprotected' => 'titleprotected',
2522 'nocreate-loggedin' => 'nocreate-loggedin',
2523 'nocreatetext' => 'nocreatetext',
2524 'movenologintext' => 'movenologintext',
2525 'movenotallowed' => 'movenotallowed',
2526 'confirmedittext' => 'confirmedittext',
2527 'blockedtext' => 'apierror-blocked',
2528 'autoblockedtext' => 'apierror-autoblocked',
2529 'systemblockedtext' => 'apierror-systemblocked',
2530 'actionthrottledtext' => 'apierror-ratelimited',
2531 'alreadyrolled' => 'alreadyrolled',
2532 'cantrollback' => 'cantrollback',
2533 'readonlytext' => 'readonlytext',
2534 'sessionfailure' => 'sessionfailure',
2535 'cannotdelete' => 'cannotdelete',
2536 'notanarticle' => 'apierror-missingtitle',
2537 'selfmove' => 'selfmove',
2538 'immobile_namespace' => 'apierror-immobilenamespace',
2539 'articleexists' => 'articleexists',
2540 'hookaborted' => 'hookaborted',
2541 'cantmove-titleprotected' => 'cantmove-titleprotected',
2542 'imagenocrossnamespace' => 'imagenocrossnamespace',
2543 'imagetypemismatch' => 'imagetypemismatch',
2544 'ip_range_invalid' => 'ip_range_invalid',
2545 'range_block_disabled' => 'range_block_disabled',
2546 'nosuchusershort' => 'nosuchusershort',
2547 'badipaddress' => 'badipaddress',
2548 'ipb_expiry_invalid' => 'ipb_expiry_invalid',
2549 'ipb_already_blocked' => 'ipb_already_blocked',
2550 'ipb_blocked_as_range' => 'ipb_blocked_as_range',
2551 'ipb_cant_unblock' => 'ipb_cant_unblock',
2552 'mailnologin' => 'apierror-cantsend',
2553 'ipbblocked' => 'ipbblocked',
2554 'ipbnounblockself' => 'ipbnounblockself',
2555 'usermaildisabled' => 'usermaildisabled',
2556 'blockedemailuser' => 'apierror-blockedfrommail',
2557 'notarget' => 'apierror-notarget',
2558 'noemail' => 'noemail',
2559 'rcpatroldisabled' => 'rcpatroldisabled',
2560 'markedaspatrollederror-noautopatrol' => 'markedaspatrollederror-noautopatrol',
2561 'delete-toobig' => 'delete-toobig',
2562 'movenotallowedfile' => 'movenotallowedfile',
2563 'userrights-no-interwiki' => 'userrights-no-interwiki',
2564 'userrights-nodatabase' => 'userrights-nodatabase',
2565 'nouserspecified' => 'nouserspecified',
2566 'noname' => 'noname',
2567 'summaryrequired' => 'apierror-summaryrequired',
2568 'import-rootpage-invalid' => 'import-rootpage-invalid',
2569 'import-rootpage-nosubpage' => 'import-rootpage-nosubpage',
2570 'readrequired' => 'apierror-readapidenied',
2571 'writedisabled' => 'apierror-noapiwrite',
2572 'writerequired' => 'apierror-writeapidenied',
2573 'missingparam' => 'apierror-missingparam',
2574 'invalidtitle' => 'apierror-invalidtitle',
2575 'nosuchpageid' => 'apierror-nosuchpageid',
2576 'nosuchrevid' => 'apierror-nosuchrevid',
2577 'nosuchuser' => 'nosuchusershort',
2578 'invaliduser' => 'apierror-invaliduser',
2579 'invalidexpiry' => 'apierror-invalidexpiry',
2580 'pastexpiry' => 'apierror-pastexpiry',
2581 'create-titleexists' => 'apierror-create-titleexists',
2582 'missingtitle-createonly' => 'apierror-missingtitle-createonly',
2583 'cantblock' => 'apierror-cantblock',
2584 'canthide' => 'apierror-canthide',
2585 'cantblock-email' => 'apierror-cantblock-email',
2586 'cantunblock' => 'apierror-permissiondenied-generic',
2587 'cannotundelete' => 'cannotundelete',
2588 'permdenied-undelete' => 'apierror-permissiondenied-generic',
2589 'createonly-exists' => 'apierror-articleexists',
2590 'nocreate-missing' => 'apierror-missingtitle',
2591 'cantchangecontentmodel' => 'apierror-cantchangecontentmodel',
2592 'nosuchrcid' => 'apierror-nosuchrcid',
2593 'nosuchlogid' => 'apierror-nosuchlogid',
2594 'protect-invalidaction' => 'apierror-protect-invalidaction',
2595 'protect-invalidlevel' => 'apierror-protect-invalidlevel',
2596 'toofewexpiries' => 'apierror-toofewexpiries',
2597 'cantimport' => 'apierror-cantimport',
2598 'cantimport-upload' => 'apierror-cantimport-upload',
2599 'importnofile' => 'importnofile',
2600 'importuploaderrorsize' => 'importuploaderrorsize',
2601 'importuploaderrorpartial' => 'importuploaderrorpartial',
2602 'importuploaderrortemp' => 'importuploaderrortemp',
2603 'importcantopen' => 'importcantopen',
2604 'import-noarticle' => 'import-noarticle',
2605 'importbadinterwiki' => 'importbadinterwiki',
2606 'import-unknownerror' => 'apierror-import-unknownerror',
2607 'cantoverwrite-sharedfile' => 'apierror-cantoverwrite-sharedfile',
2608 'sharedfile-exists' => 'apierror-fileexists-sharedrepo-perm',
2609 'mustbeposted' => 'apierror-mustbeposted',
2610 'show' => 'apierror-show',
2611 'specialpage-cantexecute' => 'apierror-specialpage-cantexecute',
2612 'invalidoldimage' => 'apierror-invalidoldimage',
2613 'nodeleteablefile' => 'apierror-nodeleteablefile',
2614 'fileexists-forbidden' => 'fileexists-forbidden',
2615 'fileexists-shared-forbidden' => 'fileexists-shared-forbidden',
2616 'filerevert-badversion' => 'filerevert-badversion',
2617 'noimageredirect-anon' => 'apierror-noimageredirect-anon',
2618 'noimageredirect-logged' => 'apierror-noimageredirect',
2619 'spamdetected' => 'apierror-spamdetected',
2620 'contenttoobig' => 'apierror-contenttoobig',
2621 'noedit-anon' => 'apierror-noedit-anon',
2622 'noedit' => 'apierror-noedit',
2623 'wasdeleted' => 'apierror-pagedeleted',
2624 'blankpage' => 'apierror-emptypage',
2625 'editconflict' => 'editconflict',
2626 'hashcheckfailed' => 'apierror-badmd5',
2627 'missingtext' => 'apierror-notext',
2628 'emptynewsection' => 'apierror-emptynewsection',
2629 'revwrongpage' => 'apierror-revwrongpage',
2630 'undo-failure' => 'undo-failure',
2631 'content-not-allowed-here' => 'content-not-allowed-here',
2632 'edit-hook-aborted' => 'edit-hook-aborted',
2633 'edit-gone-missing' => 'edit-gone-missing',
2634 'edit-conflict' => 'edit-conflict',
2635 'edit-already-exists' => 'edit-already-exists',
2636 'invalid-file-key' => 'apierror-invalid-file-key',
2637 'nouploadmodule' => 'apierror-nouploadmodule',
2638 'uploaddisabled' => 'uploaddisabled',
2639 'copyuploaddisabled' => 'copyuploaddisabled',
2640 'copyuploadbaddomain' => 'apierror-copyuploadbaddomain',
2641 'copyuploadbadurl' => 'apierror-copyuploadbadurl',
2642 'filename-tooshort' => 'filename-tooshort',
2643 'filename-toolong' => 'filename-toolong',
2644 'illegal-filename' => 'illegal-filename',
2645 'filetype-missing' => 'filetype-missing',
2646 'mustbeloggedin' => 'apierror-mustbeloggedin',
2650 * @deprecated do not use
2651 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2652 * @return ApiMessage
2654 private function parseMsgInternal( $error ) {
2655 $msg = Message::newFromSpecifier( $error );
2656 if ( !$msg instanceof IApiMessage ) {
2657 $key = $msg->getKey();
2658 if ( isset( self::$messageMap[$key] ) ) {
2659 $params = $msg->getParams();
2660 array_unshift( $params, self::$messageMap[$key] );
2661 } else {
2662 $params = [ 'apierror-unknownerror', wfEscapeWikiText( $key ) ];
2664 $msg = ApiMessage::create( $params );
2666 return $msg;
2670 * Return the error message related to a certain array
2671 * @deprecated since 1.29
2672 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2673 * @return [ 'code' => code, 'info' => info ]
2675 public function parseMsg( $error ) {
2676 // Check whether someone passed the whole array, instead of one element as
2677 // documented. This breaks if it's actually an array of fallback keys, but
2678 // that's long-standing misbehavior introduced in r87627 to incorrectly
2679 // fix T30797.
2680 if ( is_array( $error ) ) {
2681 $first = reset( $error );
2682 if ( is_array( $first ) ) {
2683 wfDebug( __METHOD__ . ' was passed an array of arrays. ' . wfGetAllCallers( 5 ) );
2684 $error = $first;
2688 $msg = $this->parseMsgInternal( $error );
2689 return [
2690 'code' => $msg->getApiCode(),
2691 'info' => ApiErrorFormatter::stripMarkup(
2692 $msg->inLanguage( 'en' )->useDatabase( false )->text()
2694 'data' => $msg->getApiData()
2699 * Output the error message related to a certain array
2700 * @deprecated since 1.29, use ApiBase::dieWithError() instead
2701 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2702 * @throws ApiUsageException always
2704 public function dieUsageMsg( $error ) {
2705 $this->dieWithError( $this->parseMsgInternal( $error ) );
2709 * Will only set a warning instead of failing if the global $wgDebugAPI
2710 * is set to true. Otherwise behaves exactly as dieUsageMsg().
2711 * @deprecated since 1.29, use ApiBase::dieWithErrorOrDebug() instead
2712 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2713 * @throws ApiUsageException
2714 * @since 1.21
2716 public function dieUsageMsgOrDebug( $error ) {
2717 $this->dieWithErrorOrDebug( $this->parseMsgInternal( $error ) );
2720 /**@}*/
2724 * For really cool vim folding this needs to be at the end:
2725 * vim: foldmarker=@{,@} foldmethod=marker