Merge "JSDuck-ify /resources/mediawiki.action/*"
[mediawiki.git] / includes / api / ApiBase.php
blobe451f2a1b88d600150f54bf9e39babf3f4a6c8dc
1 <?php
2 /**
5 * Created on Sep 5, 2006
7 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
24 * @file
27 /**
28 * This abstract class implements many basic API functions, and is the base of
29 * all API classes.
30 * The class functions are divided into several areas of functionality:
32 * Module parameters: Derived classes can define getAllowedParams() to specify
33 * which parameters to expect, how to parse and validate them.
35 * Profiling: various methods to allow keeping tabs on various tasks and their
36 * time costs
38 * Self-documentation: code to allow the API to document its own state
40 * @ingroup API
42 abstract class ApiBase extends ContextSource {
43 // These constants allow modules to specify exactly how to treat incoming parameters.
45 // Default value of the parameter
46 const PARAM_DFLT = 0;
47 // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
48 const PARAM_ISMULTI = 1;
49 // Can be either a string type (e.g.: 'integer') or an array of allowed values
50 const PARAM_TYPE = 2;
51 // Max value allowed for a parameter. Only applies if TYPE='integer'
52 const PARAM_MAX = 3;
53 // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
54 const PARAM_MAX2 = 4;
55 // Lowest value allowed for a parameter. Only applies if TYPE='integer'
56 const PARAM_MIN = 5;
57 // Boolean, do we allow the same value to be set more than once when ISMULTI=true
58 const PARAM_ALLOW_DUPLICATES = 6;
59 // Boolean, is the parameter deprecated (will show a warning)
60 const PARAM_DEPRECATED = 7;
61 /// @since 1.17
62 const PARAM_REQUIRED = 8; // Boolean, is the parameter required?
63 /// @since 1.17
64 // Boolean, if MIN/MAX are set, enforce (die) these?
65 // Only applies if TYPE='integer' Use with extreme caution
66 const PARAM_RANGE_ENFORCE = 9;
68 // Name of property group that is on the root element of the result,
69 // i.e. not part of a list
70 const PROP_ROOT = 'ROOT';
71 // Boolean, is the result multiple items? Defaults to true for query modules,
72 // to false for other modules
73 const PROP_LIST = 'LIST';
74 const PROP_TYPE = 0; // Type of the property, uses same format as PARAM_TYPE
75 // Boolean, can the property be not included in the result? Defaults to false
76 const PROP_NULLABLE = 1;
78 const LIMIT_BIG1 = 500; // Fast query, std user limit
79 const LIMIT_BIG2 = 5000; // Fast query, bot/sysop limit
80 const LIMIT_SML1 = 50; // Slow query, std user limit
81 const LIMIT_SML2 = 500; // Slow query, bot/sysop limit
83 /**
84 * getAllowedParams() flag: When set, the result could take longer to generate,
85 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
86 * @since 1.21
88 const GET_VALUES_FOR_HELP = 1;
90 private $mMainModule, $mModuleName, $mModulePrefix;
91 private $mSlaveDB = null;
92 private $mParamCache = array();
94 /**
95 * Constructor
96 * @param ApiMain $mainModule
97 * @param string $moduleName Name of this module
98 * @param string $modulePrefix Prefix to use for parameter names
100 public function __construct( $mainModule, $moduleName, $modulePrefix = '' ) {
101 $this->mMainModule = $mainModule;
102 $this->mModuleName = $moduleName;
103 $this->mModulePrefix = $modulePrefix;
105 if ( !$this->isMain() ) {
106 $this->setContext( $mainModule->getContext() );
110 /*****************************************************************************
111 * ABSTRACT METHODS *
112 *****************************************************************************/
115 * Evaluates the parameters, performs the requested query, and sets up
116 * the result. Concrete implementations of ApiBase must override this
117 * method to provide whatever functionality their module offers.
118 * Implementations must not produce any output on their own and are not
119 * expected to handle any errors.
121 * The execute() method will be invoked directly by ApiMain immediately
122 * before the result of the module is output. Aside from the
123 * constructor, implementations should assume that no other methods
124 * will be called externally on the module before the result is
125 * processed.
127 * The result data should be stored in the ApiResult object available
128 * through getResult().
130 abstract public function execute();
133 * Returns a string that identifies the version of the extending class.
134 * Typically includes the class name, the svn revision, timestamp, and
135 * last author. Usually done with SVN's Id keyword
136 * @return string
137 * @deprecated since 1.21, version string is no longer supported
139 public function getVersion() {
140 wfDeprecated( __METHOD__, '1.21' );
142 return '';
146 * Get the name of the module being executed by this instance
147 * @return string
149 public function getModuleName() {
150 return $this->mModuleName;
154 * Get the module manager, or null if this module has no sub-modules
155 * @since 1.21
156 * @return ApiModuleManager
158 public function getModuleManager() {
159 return null;
163 * Get parameter prefix (usually two letters or an empty string).
164 * @return string
166 public function getModulePrefix() {
167 return $this->mModulePrefix;
171 * Get the name of the module as shown in the profiler log
173 * @param DatabaseBase|bool $db
175 * @return string
177 public function getModuleProfileName( $db = false ) {
178 if ( $db ) {
179 return 'API:' . $this->mModuleName . '-DB';
182 return 'API:' . $this->mModuleName;
186 * Get the main module
187 * @return ApiMain
189 public function getMain() {
190 return $this->mMainModule;
194 * Returns true if this module is the main module ($this === $this->mMainModule),
195 * false otherwise.
196 * @return bool
198 public function isMain() {
199 return $this === $this->mMainModule;
203 * Get the result object
204 * @return ApiResult
206 public function getResult() {
207 // Main module has getResult() method overridden
208 // Safety - avoid infinite loop:
209 if ( $this->isMain() ) {
210 ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
213 return $this->getMain()->getResult();
217 * Get the result data array (read-only)
218 * @return array
220 public function getResultData() {
221 return $this->getResult()->getData();
225 * Create a new RequestContext object to use e.g. for calls to other parts
226 * the software.
227 * The object will have the WebRequest and the User object set to the ones
228 * used in this instance.
230 * @deprecated since 1.19 use getContext to get the current context
231 * @return DerivativeContext
233 public function createContext() {
234 wfDeprecated( __METHOD__, '1.19' );
236 return new DerivativeContext( $this->getContext() );
240 * Set warning section for this module. Users should monitor this
241 * section to notice any changes in API. Multiple calls to this
242 * function will result in the warning messages being separated by
243 * newlines
244 * @param string $warning Warning message
246 public function setWarning( $warning ) {
247 $result = $this->getResult();
248 $data = $result->getData();
249 $moduleName = $this->getModuleName();
250 if ( isset( $data['warnings'][$moduleName] ) ) {
251 // Don't add duplicate warnings
252 $oldWarning = $data['warnings'][$moduleName]['*'];
253 $warnPos = strpos( $oldWarning, $warning );
254 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
255 if ( $warnPos !== false && ( $warnPos === 0 || $oldWarning[$warnPos - 1] === "\n" ) ) {
256 // Check if $warning is followed by "\n" or the end of the $oldWarning
257 $warnPos += strlen( $warning );
258 if ( strlen( $oldWarning ) <= $warnPos || $oldWarning[$warnPos] === "\n" ) {
259 return;
262 // If there is a warning already, append it to the existing one
263 $warning = "$oldWarning\n$warning";
265 $msg = array();
266 ApiResult::setContent( $msg, $warning );
267 $result->disableSizeCheck();
268 $result->addValue( 'warnings', $moduleName,
269 $msg, ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP );
270 $result->enableSizeCheck();
274 * If the module may only be used with a certain format module,
275 * it should override this method to return an instance of that formatter.
276 * A value of null means the default format will be used.
277 * @return mixed Instance of a derived class of ApiFormatBase, or null
279 public function getCustomPrinter() {
280 return null;
284 * Generates help message for this module, or false if there is no description
285 * @return string|bool
287 public function makeHelpMsg() {
288 static $lnPrfx = "\n ";
290 $msg = $this->getFinalDescription();
292 if ( $msg !== false ) {
294 if ( !is_array( $msg ) ) {
295 $msg = array(
296 $msg
299 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
301 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
303 if ( $this->isReadMode() ) {
304 $msg .= "\nThis module requires read rights";
306 if ( $this->isWriteMode() ) {
307 $msg .= "\nThis module requires write rights";
309 if ( $this->mustBePosted() ) {
310 $msg .= "\nThis module only accepts POST requests";
312 if ( $this->isReadMode() || $this->isWriteMode() ||
313 $this->mustBePosted()
315 $msg .= "\n";
318 // Parameters
319 $paramsMsg = $this->makeHelpMsgParameters();
320 if ( $paramsMsg !== false ) {
321 $msg .= "Parameters:\n$paramsMsg";
324 $examples = $this->getExamples();
325 if ( $examples ) {
326 if ( !is_array( $examples ) ) {
327 $examples = array(
328 $examples
331 $msg .= "Example" . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
332 foreach ( $examples as $k => $v ) {
333 if ( is_numeric( $k ) ) {
334 $msg .= " $v\n";
335 } else {
336 if ( is_array( $v ) ) {
337 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
338 } else {
339 $msgExample = " $v";
341 $msgExample .= ":";
342 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
348 return $msg;
352 * @param string $item
353 * @return string
355 private function indentExampleText( $item ) {
356 return " " . $item;
360 * @param string $prefix Text to split output items
361 * @param string $title What is being output
362 * @param string|array $input
363 * @return string
365 protected function makeHelpArrayToString( $prefix, $title, $input ) {
366 if ( $input === false ) {
367 return '';
369 if ( !is_array( $input ) ) {
370 $input = array( $input );
373 if ( count( $input ) > 0 ) {
374 if ( $title ) {
375 $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n ";
376 } else {
377 $msg = ' ';
379 $msg .= implode( $prefix, $input ) . "\n";
381 return $msg;
384 return '';
388 * Generates the parameter descriptions for this module, to be displayed in the
389 * module's help.
390 * @return string|bool
392 public function makeHelpMsgParameters() {
393 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
394 if ( $params ) {
396 $paramsDescription = $this->getFinalParamDescription();
397 $msg = '';
398 $paramPrefix = "\n" . str_repeat( ' ', 24 );
399 $descWordwrap = "\n" . str_repeat( ' ', 28 );
400 foreach ( $params as $paramName => $paramSettings ) {
401 $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
402 if ( is_array( $desc ) ) {
403 $desc = implode( $paramPrefix, $desc );
406 //handle shorthand
407 if ( !is_array( $paramSettings ) ) {
408 $paramSettings = array(
409 self::PARAM_DFLT => $paramSettings,
413 //handle missing type
414 if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) {
415 $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] )
416 ? $paramSettings[ApiBase::PARAM_DFLT]
417 : null;
418 if ( is_bool( $dflt ) ) {
419 $paramSettings[ApiBase::PARAM_TYPE] = 'boolean';
420 } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
421 $paramSettings[ApiBase::PARAM_TYPE] = 'string';
422 } elseif ( is_int( $dflt ) ) {
423 $paramSettings[ApiBase::PARAM_TYPE] = 'integer';
427 if ( isset( $paramSettings[self::PARAM_DEPRECATED] )
428 && $paramSettings[self::PARAM_DEPRECATED]
430 $desc = "DEPRECATED! $desc";
433 if ( isset( $paramSettings[self::PARAM_REQUIRED] )
434 && $paramSettings[self::PARAM_REQUIRED]
436 $desc .= $paramPrefix . "This parameter is required";
439 $type = isset( $paramSettings[self::PARAM_TYPE] )
440 ? $paramSettings[self::PARAM_TYPE]
441 : null;
442 if ( isset( $type ) ) {
443 $hintPipeSeparated = true;
444 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
445 ? $paramSettings[self::PARAM_ISMULTI]
446 : false;
447 if ( $multi ) {
448 $prompt = 'Values (separate with \'|\'): ';
449 } else {
450 $prompt = 'One value: ';
453 if ( is_array( $type ) ) {
454 $choices = array();
455 $nothingPrompt = '';
456 foreach ( $type as $t ) {
457 if ( $t === '' ) {
458 $nothingPrompt = 'Can be empty, or ';
459 } else {
460 $choices[] = $t;
463 $desc .= $paramPrefix . $nothingPrompt . $prompt;
464 $choicesstring = implode( ', ', $choices );
465 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
466 $hintPipeSeparated = false;
467 } else {
468 switch ( $type ) {
469 case 'namespace':
470 // Special handling because namespaces are
471 // type-limited, yet they are not given
472 $desc .= $paramPrefix . $prompt;
473 $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
474 100, $descWordwrap );
475 $hintPipeSeparated = false;
476 break;
477 case 'limit':
478 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
479 if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
480 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
482 $desc .= ' allowed';
483 break;
484 case 'integer':
485 $s = $multi ? 's' : '';
486 $hasMin = isset( $paramSettings[self::PARAM_MIN] );
487 $hasMax = isset( $paramSettings[self::PARAM_MAX] );
488 if ( $hasMin || $hasMax ) {
489 if ( !$hasMax ) {
490 $intRangeStr = "The value$s must be no less than " .
491 "{$paramSettings[self::PARAM_MIN]}";
492 } elseif ( !$hasMin ) {
493 $intRangeStr = "The value$s must be no more than " .
494 "{$paramSettings[self::PARAM_MAX]}";
495 } else {
496 $intRangeStr = "The value$s must be between " .
497 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
500 $desc .= $paramPrefix . $intRangeStr;
502 break;
503 case 'upload':
504 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
505 break;
509 if ( $multi ) {
510 if ( $hintPipeSeparated ) {
511 $desc .= $paramPrefix . "Separate values with '|'";
514 $isArray = is_array( $type );
515 if ( !$isArray
516 || $isArray && count( $type ) > self::LIMIT_SML1
518 $desc .= $paramPrefix . "Maximum number of values " .
519 self::LIMIT_SML1 . " (" . self::LIMIT_SML2 . " for bots)";
524 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
525 if ( !is_null( $default ) && $default !== false ) {
526 $desc .= $paramPrefix . "Default: $default";
529 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
532 return $msg;
535 return false;
539 * Returns the description string for this module
540 * @return string|array
542 protected function getDescription() {
543 return false;
547 * Returns usage examples for this module. Return false if no examples are available.
548 * @return bool|string|array
550 protected function getExamples() {
551 return false;
555 * Returns an array of allowed parameters (parameter name) => (default
556 * value) or (parameter name) => (array with PARAM_* constants as keys)
557 * Don't call this function directly: use getFinalParams() to allow
558 * hooks to modify parameters as needed.
560 * Some derived classes may choose to handle an integer $flags parameter
561 * in the overriding methods. Callers of this method can pass zero or
562 * more OR-ed flags like GET_VALUES_FOR_HELP.
564 * @return array|bool
566 protected function getAllowedParams( /* $flags = 0 */ ) {
567 // int $flags is not declared because it causes "Strict standards"
568 // warning. Most derived classes do not implement it.
569 return false;
573 * Returns an array of parameter descriptions.
574 * Don't call this function directly: use getFinalParamDescription() to
575 * allow hooks to modify descriptions as needed.
576 * @return array|bool False on no parameter descriptions
578 protected function getParamDescription() {
579 return false;
583 * Get final list of parameters, after hooks have had a chance to
584 * tweak it as needed.
586 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
587 * @return array|bool False on no parameters
588 * @since 1.21 $flags param added
590 public function getFinalParams( $flags = 0 ) {
591 $params = $this->getAllowedParams( $flags );
592 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
594 return $params;
598 * Get final parameter descriptions, after hooks have had a chance to tweak it as
599 * needed.
601 * @return array|bool False on no parameter descriptions
603 public function getFinalParamDescription() {
604 $desc = $this->getParamDescription();
605 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
607 return $desc;
611 * Returns possible properties in the result, grouped by the value of the prop parameter
612 * that shows them.
614 * Properties that are shown always are in a group with empty string as a key.
615 * Properties that can be shown by several values of prop are included multiple times.
616 * If some properties are part of a list and some are on the root object (see ApiQueryQueryPage),
617 * those on the root object are under the key PROP_ROOT.
618 * The array can also contain a boolean under the key PROP_LIST,
619 * indicating whether the result is a list.
621 * Don't call this function directly: use getFinalResultProperties() to
622 * allow hooks to modify descriptions as needed.
624 * @return array|bool False on no properties
626 protected function getResultProperties() {
627 return false;
631 * Get final possible result properties, after hooks have had a chance to tweak it as
632 * needed.
634 * @return array
636 public function getFinalResultProperties() {
637 $properties = $this->getResultProperties();
638 wfRunHooks( 'APIGetResultProperties', array( $this, &$properties ) );
640 return $properties;
644 * Add token properties to the array used by getResultProperties,
645 * based on a token functions mapping.
646 * @param array $props
647 * @param array $tokenFunctions
649 protected static function addTokenProperties( &$props, $tokenFunctions ) {
650 foreach ( array_keys( $tokenFunctions ) as $token ) {
651 $props[''][$token . 'token'] = array(
652 ApiBase::PROP_TYPE => 'string',
653 ApiBase::PROP_NULLABLE => true
659 * Get final module description, after hooks have had a chance to tweak it as
660 * needed.
662 * @return array|bool False on no parameters
664 public function getFinalDescription() {
665 $desc = $this->getDescription();
666 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
668 return $desc;
672 * This method mangles parameter name based on the prefix supplied to the constructor.
673 * Override this method to change parameter name during runtime
674 * @param string $paramName Parameter name
675 * @return string Prefixed parameter name
677 public function encodeParamName( $paramName ) {
678 return $this->mModulePrefix . $paramName;
682 * Using getAllowedParams(), this function makes an array of the values
683 * provided by the user, with key being the name of the variable, and
684 * value - validated value from user or default. limits will not be
685 * parsed if $parseLimit is set to false; use this when the max
686 * limit is not definitive yet, e.g. when getting revisions.
687 * @param bool $parseLimit True by default
688 * @return array
690 public function extractRequestParams( $parseLimit = true ) {
691 // Cache parameters, for performance and to avoid bug 24564.
692 if ( !isset( $this->mParamCache[$parseLimit] ) ) {
693 $params = $this->getFinalParams();
694 $results = array();
696 if ( $params ) { // getFinalParams() can return false
697 foreach ( $params as $paramName => $paramSettings ) {
698 $results[$paramName] = $this->getParameterFromSettings(
699 $paramName, $paramSettings, $parseLimit );
702 $this->mParamCache[$parseLimit] = $results;
705 return $this->mParamCache[$parseLimit];
709 * Get a value for the given parameter
710 * @param string $paramName Parameter name
711 * @param bool $parseLimit See extractRequestParams()
712 * @return mixed Parameter value
714 protected function getParameter( $paramName, $parseLimit = true ) {
715 $params = $this->getFinalParams();
716 $paramSettings = $params[$paramName];
718 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
722 * Die if none or more than one of a certain set of parameters is set and not false.
723 * @param array $params Array of parameter names
725 public function requireOnlyOneParameter( $params ) {
726 $required = func_get_args();
727 array_shift( $required );
728 $p = $this->getModulePrefix();
730 $intersection = array_intersect( array_keys( array_filter( $params,
731 array( $this, "parameterNotEmpty" ) ) ), $required );
733 if ( count( $intersection ) > 1 ) {
734 $this->dieUsage(
735 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
736 'invalidparammix' );
737 } elseif ( count( $intersection ) == 0 ) {
738 $this->dieUsage(
739 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
740 'missingparam'
746 * Generates the possible errors requireOnlyOneParameter() can die with
748 * @param array $params
749 * @return array
751 public function getRequireOnlyOneParameterErrorMessages( $params ) {
752 $p = $this->getModulePrefix();
753 $params = implode( ", {$p}", $params );
755 return array(
756 array(
757 'code' => "{$p}missingparam",
758 'info' => "One of the parameters {$p}{$params} is required"
760 array(
761 'code' => "{$p}invalidparammix",
762 'info' => "The parameters {$p}{$params} can not be used together"
768 * Die if more than one of a certain set of parameters is set and not false.
770 * @param array $params
772 public function requireMaxOneParameter( $params ) {
773 $required = func_get_args();
774 array_shift( $required );
775 $p = $this->getModulePrefix();
777 $intersection = array_intersect( array_keys( array_filter( $params,
778 array( $this, "parameterNotEmpty" ) ) ), $required );
780 if ( count( $intersection ) > 1 ) {
781 $this->dieUsage(
782 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
783 'invalidparammix'
789 * Generates the possible error requireMaxOneParameter() can die with
791 * @param array $params
792 * @return array
794 public function getRequireMaxOneParameterErrorMessages( $params ) {
795 $p = $this->getModulePrefix();
796 $params = implode( ", {$p}", $params );
798 return array(
799 array(
800 'code' => "{$p}invalidparammix",
801 'info' => "The parameters {$p}{$params} can not be used together"
807 * Die if none of a certain set of parameters is set and not false.
809 * @since 1.23
810 * @param array $params User provided set of parameters
811 * @param string ... List of parameter names to check
813 public function requireAtLeastOneParameter( $params ) {
814 $required = func_get_args();
815 array_shift( $required );
816 $p = $this->getModulePrefix();
818 $intersection = array_intersect(
819 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
820 $required
823 if ( count( $intersection ) == 0 ) {
824 $this->dieUsage( "At least one of the parameters {$p}" .
825 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
830 * Generates the possible errors requireAtLeastOneParameter() can die with
832 * @since 1.23
833 * @param array $params Array of parameter key names
834 * @return array
836 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
837 $p = $this->getModulePrefix();
838 $params = implode( ", {$p}", $params );
840 return array(
841 array(
842 'code' => "{$p}missingparam",
843 'info' => "At least one of the parameters {$p}{$params} is required",
849 * @param array $params
850 * @param bool|string $load Whether load the object's state from the database:
851 * - false: don't load (if the pageid is given, it will still be loaded)
852 * - 'fromdb': load from a slave database
853 * - 'fromdbmaster': load from the master database
854 * @return WikiPage
856 public function getTitleOrPageId( $params, $load = false ) {
857 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
859 $pageObj = null;
860 if ( isset( $params['title'] ) ) {
861 $titleObj = Title::newFromText( $params['title'] );
862 if ( !$titleObj || $titleObj->isExternal() ) {
863 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
865 if ( !$titleObj->canExist() ) {
866 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
868 $pageObj = WikiPage::factory( $titleObj );
869 if ( $load !== false ) {
870 $pageObj->loadPageData( $load );
872 } elseif ( isset( $params['pageid'] ) ) {
873 if ( $load === false ) {
874 $load = 'fromdb';
876 $pageObj = WikiPage::newFromID( $params['pageid'], $load );
877 if ( !$pageObj ) {
878 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
882 return $pageObj;
886 * @return array
888 public function getTitleOrPageIdErrorMessage() {
889 return array_merge(
890 $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ),
891 array(
892 array( 'invalidtitle', 'title' ),
893 array( 'nosuchpageid', 'pageid' ),
899 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
901 * @param object $x Parameter to check is not null/false
902 * @return bool
904 private function parameterNotEmpty( $x ) {
905 return !is_null( $x ) && $x !== false;
909 * Return true if we're to watch the page, false if not, null if no change.
910 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
911 * @param Title $titleObj The page under consideration
912 * @param string $userOption The user option to consider when $watchlist=preferences.
913 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
914 * @return bool
916 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
918 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem::IGNORE_USER_RIGHTS );
920 switch ( $watchlist ) {
921 case 'watch':
922 return true;
924 case 'unwatch':
925 return false;
927 case 'preferences':
928 # If the user is already watching, don't bother checking
929 if ( $userWatching ) {
930 return true;
932 # If no user option was passed, use watchdefault and watchcreations
933 if ( is_null( $userOption ) ) {
934 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
935 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
938 # Watch the article based on the user preference
939 return $this->getUser()->getBoolOption( $userOption );
941 case 'nochange':
942 return $userWatching;
944 default:
945 return $userWatching;
950 * Set a watch (or unwatch) based the based on a watchlist parameter.
951 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
952 * @param Title $titleObj The article's title to change
953 * @param string $userOption The user option to consider when $watch=preferences
955 protected function setWatch( $watch, $titleObj, $userOption = null ) {
956 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
957 if ( $value === null ) {
958 return;
961 WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
965 * Using the settings determine the value for the given parameter
967 * @param string $paramName Parameter name
968 * @param array|mixed $paramSettings Default value or an array of settings
969 * using PARAM_* constants.
970 * @param bool $parseLimit Parse limit?
971 * @return mixed Parameter value
973 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
974 // Some classes may decide to change parameter names
975 $encParamName = $this->encodeParamName( $paramName );
977 if ( !is_array( $paramSettings ) ) {
978 $default = $paramSettings;
979 $multi = false;
980 $type = gettype( $paramSettings );
981 $dupes = false;
982 $deprecated = false;
983 $required = false;
984 } else {
985 $default = isset( $paramSettings[self::PARAM_DFLT] )
986 ? $paramSettings[self::PARAM_DFLT]
987 : null;
988 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
989 ? $paramSettings[self::PARAM_ISMULTI]
990 : false;
991 $type = isset( $paramSettings[self::PARAM_TYPE] )
992 ? $paramSettings[self::PARAM_TYPE]
993 : null;
994 $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] )
995 ? $paramSettings[self::PARAM_ALLOW_DUPLICATES]
996 : false;
997 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] )
998 ? $paramSettings[self::PARAM_DEPRECATED]
999 : false;
1000 $required = isset( $paramSettings[self::PARAM_REQUIRED] )
1001 ? $paramSettings[self::PARAM_REQUIRED]
1002 : false;
1004 // When type is not given, and no choices, the type is the same as $default
1005 if ( !isset( $type ) ) {
1006 if ( isset( $default ) ) {
1007 $type = gettype( $default );
1008 } else {
1009 $type = 'NULL'; // allow everything
1014 if ( $type == 'boolean' ) {
1015 if ( isset( $default ) && $default !== false ) {
1016 // Having a default value of anything other than 'false' is not allowed
1017 ApiBase::dieDebug(
1018 __METHOD__,
1019 "Boolean param $encParamName's default is set to '$default'. " .
1020 "Boolean parameters must default to false."
1024 $value = $this->getMain()->getCheck( $encParamName );
1025 } elseif ( $type == 'upload' ) {
1026 if ( isset( $default ) ) {
1027 // Having a default value is not allowed
1028 ApiBase::dieDebug(
1029 __METHOD__,
1030 "File upload param $encParamName's default is set to " .
1031 "'$default'. File upload parameters may not have a default." );
1033 if ( $multi ) {
1034 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1036 $value = $this->getMain()->getUpload( $encParamName );
1037 if ( !$value->exists() ) {
1038 // This will get the value without trying to normalize it
1039 // (because trying to normalize a large binary file
1040 // accidentally uploaded as a field fails spectacularly)
1041 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1042 if ( $value !== null ) {
1043 $this->dieUsage(
1044 "File upload param $encParamName is not a file upload; " .
1045 "be sure to use multipart/form-data for your POST and include " .
1046 "a filename in the Content-Disposition header.",
1047 "badupload_{$encParamName}"
1051 } else {
1052 $value = $this->getMain()->getVal( $encParamName, $default );
1054 if ( isset( $value ) && $type == 'namespace' ) {
1055 $type = MWNamespace::getValidNamespaces();
1059 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
1060 $value = $this->parseMultiValue(
1061 $encParamName,
1062 $value,
1063 $multi,
1064 is_array( $type ) ? $type : null
1068 // More validation only when choices were not given
1069 // choices were validated in parseMultiValue()
1070 if ( isset( $value ) ) {
1071 if ( !is_array( $type ) ) {
1072 switch ( $type ) {
1073 case 'NULL': // nothing to do
1074 break;
1075 case 'string':
1076 if ( $required && $value === '' ) {
1077 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1079 break;
1080 case 'integer': // Force everything using intval() and optionally validate limits
1081 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
1082 $max = isset( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
1083 $enforceLimits = isset( $paramSettings[self::PARAM_RANGE_ENFORCE] )
1084 ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
1086 if ( is_array( $value ) ) {
1087 $value = array_map( 'intval', $value );
1088 if ( !is_null( $min ) || !is_null( $max ) ) {
1089 foreach ( $value as &$v ) {
1090 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1093 } else {
1094 $value = intval( $value );
1095 if ( !is_null( $min ) || !is_null( $max ) ) {
1096 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1099 break;
1100 case 'limit':
1101 if ( !$parseLimit ) {
1102 // Don't do any validation whatsoever
1103 break;
1105 if ( !isset( $paramSettings[self::PARAM_MAX] )
1106 || !isset( $paramSettings[self::PARAM_MAX2] )
1108 ApiBase::dieDebug(
1109 __METHOD__,
1110 "MAX1 or MAX2 are not defined for the limit $encParamName"
1113 if ( $multi ) {
1114 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1116 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
1117 if ( $value == 'max' ) {
1118 $value = $this->getMain()->canApiHighLimits()
1119 ? $paramSettings[self::PARAM_MAX2]
1120 : $paramSettings[self::PARAM_MAX];
1121 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
1122 } else {
1123 $value = intval( $value );
1124 $this->validateLimit(
1125 $paramName,
1126 $value,
1127 $min,
1128 $paramSettings[self::PARAM_MAX],
1129 $paramSettings[self::PARAM_MAX2]
1132 break;
1133 case 'boolean':
1134 if ( $multi ) {
1135 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1137 break;
1138 case 'timestamp':
1139 if ( is_array( $value ) ) {
1140 foreach ( $value as $key => $val ) {
1141 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1143 } else {
1144 $value = $this->validateTimestamp( $value, $encParamName );
1146 break;
1147 case 'user':
1148 if ( is_array( $value ) ) {
1149 foreach ( $value as $key => $val ) {
1150 $value[$key] = $this->validateUser( $val, $encParamName );
1152 } else {
1153 $value = $this->validateUser( $value, $encParamName );
1155 break;
1156 case 'upload': // nothing to do
1157 break;
1158 default:
1159 ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
1163 // Throw out duplicates if requested
1164 if ( !$dupes && is_array( $value ) ) {
1165 $value = array_unique( $value );
1168 // Set a warning if a deprecated parameter has been passed
1169 if ( $deprecated && $value !== false ) {
1170 $this->setWarning( "The $encParamName parameter has been deprecated." );
1172 } elseif ( $required ) {
1173 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1176 return $value;
1180 * Return an array of values that were given in a 'a|b|c' notation,
1181 * after it optionally validates them against the list allowed values.
1183 * @param string $valueName The name of the parameter (for error
1184 * reporting)
1185 * @param mixed $value The value being parsed
1186 * @param bool $allowMultiple Can $value contain more than one value
1187 * separated by '|'?
1188 * @param mixed $allowedValues An array of values to check against. If
1189 * null, all values are accepted.
1190 * @return mixed (allowMultiple ? an_array_of_values : a_single_value)
1192 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1193 if ( trim( $value ) === '' && $allowMultiple ) {
1194 return array();
1197 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1198 // because it unstubs $wgUser
1199 $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 );
1200 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits()
1201 ? self::LIMIT_SML2
1202 : self::LIMIT_SML1;
1204 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
1205 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1206 "the limit is $sizeLimit" );
1209 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1210 // Bug 33482 - Allow entries with | in them for non-multiple values
1211 if ( in_array( $value, $allowedValues, true ) ) {
1212 return $value;
1215 $possibleValues = is_array( $allowedValues )
1216 ? "of '" . implode( "', '", $allowedValues ) . "'"
1217 : '';
1218 $this->dieUsage(
1219 "Only one $possibleValues is allowed for parameter '$valueName'",
1220 "multival_$valueName"
1224 if ( is_array( $allowedValues ) ) {
1225 // Check for unknown values
1226 $unknown = array_diff( $valuesList, $allowedValues );
1227 if ( count( $unknown ) ) {
1228 if ( $allowMultiple ) {
1229 $s = count( $unknown ) > 1 ? 's' : '';
1230 $vals = implode( ", ", $unknown );
1231 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1232 } else {
1233 $this->dieUsage(
1234 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1235 "unknown_$valueName"
1239 // Now throw them out
1240 $valuesList = array_intersect( $valuesList, $allowedValues );
1243 return $allowMultiple ? $valuesList : $valuesList[0];
1247 * Validate the value against the minimum and user/bot maximum limits.
1248 * Prints usage info on failure.
1249 * @param string $paramName Parameter name
1250 * @param int $value Parameter value
1251 * @param int|null $min Minimum value
1252 * @param int|null $max Maximum value for users
1253 * @param int $botMax Maximum value for sysops/bots
1254 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1256 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1257 if ( !is_null( $min ) && $value < $min ) {
1259 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1260 $this->warnOrDie( $msg, $enforceLimits );
1261 $value = $min;
1264 // Minimum is always validated, whereas maximum is checked only if not
1265 // running in internal call mode
1266 if ( $this->getMain()->isInternalMode() ) {
1267 return;
1270 // Optimization: do not check user's bot status unless really needed -- skips db query
1271 // assumes $botMax >= $max
1272 if ( !is_null( $max ) && $value > $max ) {
1273 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1274 if ( $value > $botMax ) {
1275 $msg = $this->encodeParamName( $paramName ) .
1276 " may not be over $botMax (set to $value) for bots or sysops";
1277 $this->warnOrDie( $msg, $enforceLimits );
1278 $value = $botMax;
1280 } else {
1281 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1282 $this->warnOrDie( $msg, $enforceLimits );
1283 $value = $max;
1289 * Validate and normalize of parameters of type 'timestamp'
1290 * @param string $value Parameter value
1291 * @param string $encParamName Parameter name
1292 * @return string Validated and normalized parameter
1294 function validateTimestamp( $value, $encParamName ) {
1295 $unixTimestamp = wfTimestamp( TS_UNIX, $value );
1296 if ( $unixTimestamp === false ) {
1297 $this->dieUsage(
1298 "Invalid value '$value' for timestamp parameter $encParamName",
1299 "badtimestamp_{$encParamName}"
1303 return wfTimestamp( TS_MW, $unixTimestamp );
1307 * Validate and normalize of parameters of type 'user'
1308 * @param string $value Parameter value
1309 * @param string $encParamName Parameter name
1310 * @return string Validated and normalized parameter
1312 private function validateUser( $value, $encParamName ) {
1313 $title = Title::makeTitleSafe( NS_USER, $value );
1314 if ( $title === null ) {
1315 $this->dieUsage(
1316 "Invalid value '$value' for user parameter $encParamName",
1317 "baduser_{$encParamName}"
1321 return $title->getText();
1325 * Adds a warning to the output, else dies
1327 * @param string $msg Message to show as a warning, or error message if dying
1328 * @param bool $enforceLimits Whether this is an enforce (die)
1330 private function warnOrDie( $msg, $enforceLimits = false ) {
1331 if ( $enforceLimits ) {
1332 $this->dieUsage( $msg, 'integeroutofrange' );
1335 $this->setWarning( $msg );
1339 * Truncate an array to a certain length.
1340 * @param array $arr Array to truncate
1341 * @param int $limit Maximum length
1342 * @return bool True if the array was truncated, false otherwise
1344 public static function truncateArray( &$arr, $limit ) {
1345 $modified = false;
1346 while ( count( $arr ) > $limit ) {
1347 array_pop( $arr );
1348 $modified = true;
1351 return $modified;
1355 * Throw a UsageException, which will (if uncaught) call the main module's
1356 * error handler and die with an error message.
1358 * @param string $description One-line human-readable description of the
1359 * error condition, e.g., "The API requires a valid action parameter"
1360 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1361 * automated identification of the error, e.g., 'unknown_action'
1362 * @param int $httpRespCode HTTP response code
1363 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1364 * @throws UsageException
1366 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1367 Profiler::instance()->close();
1368 throw new UsageException(
1369 $description,
1370 $this->encodeParamName( $errorCode ),
1371 $httpRespCode,
1372 $extradata
1377 * Get error (as code, string) from a Status object.
1379 * @since 1.23
1380 * @param Status $status
1381 * @return array Array of code and error string
1383 public function getErrorFromStatus( $status ) {
1384 if ( $status->isGood() ) {
1385 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1388 $errors = $status->getErrorsArray();
1389 if ( !$errors ) {
1390 // No errors? Assume the warnings should be treated as errors
1391 $errors = $status->getWarningsArray();
1393 if ( !$errors ) {
1394 // Still no errors? Punt
1395 $errors = array( array( 'unknownerror-nocode' ) );
1398 // Cannot use dieUsageMsg() because extensions might return custom
1399 // error messages.
1400 if ( $errors[0] instanceof Message ) {
1401 $msg = $errors[0];
1402 $code = $msg->getKey();
1403 } else {
1404 $code = array_shift( $errors[0] );
1405 $msg = wfMessage( $code, $errors[0] );
1407 if ( isset( ApiBase::$messageMap[$code] ) ) {
1408 // Translate message to code, for backwards compatability
1409 $code = ApiBase::$messageMap[$code]['code'];
1412 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1416 * Throw a UsageException based on the errors in the Status object.
1418 * @since 1.22
1419 * @param Status $status
1420 * @throws MWException
1422 public function dieStatus( $status ) {
1424 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1425 $this->dieUsage( $msg, $code );
1428 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1430 * Array that maps message keys to error messages. $1 and friends are replaced.
1432 public static $messageMap = array(
1433 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1434 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1435 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1437 // Messages from Title::getUserPermissionsErrors()
1438 'ns-specialprotected' => array(
1439 'code' => 'unsupportednamespace',
1440 'info' => "Pages in the Special namespace can't be edited"
1442 'protectedinterface' => array(
1443 'code' => 'protectednamespace-interface',
1444 'info' => "You're not allowed to edit interface messages"
1446 'namespaceprotected' => array(
1447 'code' => 'protectednamespace',
1448 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1450 'customcssprotected' => array(
1451 'code' => 'customcssprotected',
1452 'info' => "You're not allowed to edit custom CSS pages"
1454 'customjsprotected' => array(
1455 'code' => 'customjsprotected',
1456 'info' => "You're not allowed to edit custom JavaScript pages"
1458 'cascadeprotected' => array(
1459 'code' => 'cascadeprotected',
1460 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1462 'protectedpagetext' => array(
1463 'code' => 'protectedpage',
1464 'info' => "The \"\$1\" right is required to edit this page"
1466 'protect-cantedit' => array(
1467 'code' => 'cantedit',
1468 'info' => "You can't protect this page because you can't edit it"
1470 'badaccess-group0' => array(
1471 'code' => 'permissiondenied',
1472 'info' => "Permission denied"
1473 ), // Generic permission denied message
1474 'badaccess-groups' => array(
1475 'code' => 'permissiondenied',
1476 'info' => "Permission denied"
1478 'titleprotected' => array(
1479 'code' => 'protectedtitle',
1480 'info' => "This title has been protected from creation"
1482 'nocreate-loggedin' => array(
1483 'code' => 'cantcreate',
1484 'info' => "You don't have permission to create new pages"
1486 'nocreatetext' => array(
1487 'code' => 'cantcreate-anon',
1488 'info' => "Anonymous users can't create new pages"
1490 'movenologintext' => array(
1491 'code' => 'cantmove-anon',
1492 'info' => "Anonymous users can't move pages"
1494 'movenotallowed' => array(
1495 'code' => 'cantmove',
1496 'info' => "You don't have permission to move pages"
1498 'confirmedittext' => array(
1499 'code' => 'confirmemail',
1500 'info' => "You must confirm your email address before you can edit"
1502 'blockedtext' => array(
1503 'code' => 'blocked',
1504 'info' => "You have been blocked from editing"
1506 'autoblockedtext' => array(
1507 'code' => 'autoblocked',
1508 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1511 // Miscellaneous interface messages
1512 'actionthrottledtext' => array(
1513 'code' => 'ratelimited',
1514 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1516 'alreadyrolled' => array(
1517 'code' => 'alreadyrolled',
1518 'info' => "The page you tried to rollback was already rolled back"
1520 'cantrollback' => array(
1521 'code' => 'onlyauthor',
1522 'info' => "The page you tried to rollback only has one author"
1524 'readonlytext' => array(
1525 'code' => 'readonly',
1526 'info' => "The wiki is currently in read-only mode"
1528 'sessionfailure' => array(
1529 'code' => 'badtoken',
1530 'info' => "Invalid token" ),
1531 'cannotdelete' => array(
1532 'code' => 'cantdelete',
1533 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1535 'notanarticle' => array(
1536 'code' => 'missingtitle',
1537 'info' => "The page you requested doesn't exist"
1539 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1541 'immobile_namespace' => array(
1542 'code' => 'immobilenamespace',
1543 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1545 'articleexists' => array(
1546 'code' => 'articleexists',
1547 'info' => "The destination article already exists and is not a redirect to the source article"
1549 'protectedpage' => array(
1550 'code' => 'protectedpage',
1551 'info' => "You don't have permission to perform this move"
1553 'hookaborted' => array(
1554 'code' => 'hookaborted',
1555 'info' => "The modification you tried to make was aborted by an extension hook"
1557 'cantmove-titleprotected' => array(
1558 'code' => 'protectedtitle',
1559 'info' => "The destination article has been protected from creation"
1561 'imagenocrossnamespace' => array(
1562 'code' => 'nonfilenamespace',
1563 'info' => "Can't move a file to a non-file namespace"
1565 'imagetypemismatch' => array(
1566 'code' => 'filetypemismatch',
1567 'info' => "The new file extension doesn't match its type"
1569 // 'badarticleerror' => shouldn't happen
1570 // 'badtitletext' => shouldn't happen
1571 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1572 'range_block_disabled' => array(
1573 'code' => 'rangedisabled',
1574 'info' => "Blocking IP ranges has been disabled"
1576 'nosuchusershort' => array(
1577 'code' => 'nosuchuser',
1578 'info' => "The user you specified doesn't exist"
1580 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1581 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1582 'ipb_already_blocked' => array(
1583 'code' => 'alreadyblocked',
1584 'info' => "The user you tried to block was already blocked"
1586 'ipb_blocked_as_range' => array(
1587 'code' => 'blockedasrange',
1588 'info' => "IP address \"\$1\" was blocked as part of range \"\$2\". You can't unblock the IP individually, but you can unblock the range as a whole."
1590 'ipb_cant_unblock' => array(
1591 'code' => 'cantunblock',
1592 'info' => "The block you specified was not found. It may have been unblocked already"
1594 'mailnologin' => array(
1595 'code' => 'cantsend',
1596 'info' => "You are not logged in, you do not have a confirmed email address, or you are not allowed to send email to other users, so you cannot send email"
1598 'ipbblocked' => array(
1599 'code' => 'ipbblocked',
1600 'info' => 'You cannot block or unblock users while you are yourself blocked'
1602 'ipbnounblockself' => array(
1603 'code' => 'ipbnounblockself',
1604 'info' => 'You are not allowed to unblock yourself'
1606 'usermaildisabled' => array(
1607 'code' => 'usermaildisabled',
1608 'info' => "User email has been disabled"
1610 'blockedemailuser' => array(
1611 'code' => 'blockedfrommail',
1612 'info' => "You have been blocked from sending email"
1614 'notarget' => array(
1615 'code' => 'notarget',
1616 'info' => "You have not specified a valid target for this action"
1618 'noemail' => array(
1619 'code' => 'noemail',
1620 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1622 'rcpatroldisabled' => array(
1623 'code' => 'patroldisabled',
1624 'info' => "Patrolling is disabled on this wiki"
1626 'markedaspatrollederror-noautopatrol' => array(
1627 'code' => 'noautopatrol',
1628 'info' => "You don't have permission to patrol your own changes"
1630 'delete-toobig' => array(
1631 'code' => 'bigdelete',
1632 'info' => "You can't delete this page because it has more than \$1 revisions"
1634 'movenotallowedfile' => array(
1635 'code' => 'cantmovefile',
1636 'info' => "You don't have permission to move files"
1638 'userrights-no-interwiki' => array(
1639 'code' => 'nointerwikiuserrights',
1640 'info' => "You don't have permission to change user rights on other wikis"
1642 'userrights-nodatabase' => array(
1643 'code' => 'nosuchdatabase',
1644 'info' => "Database \"\$1\" does not exist or is not local"
1646 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1647 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1648 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1649 'import-rootpage-invalid' => array(
1650 'code' => 'import-rootpage-invalid',
1651 'info' => 'Root page is an invalid title'
1653 'import-rootpage-nosubpage' => array(
1654 'code' => 'import-rootpage-nosubpage',
1655 'info' => 'Namespace "$1" of the root page does not allow subpages'
1658 // API-specific messages
1659 'readrequired' => array(
1660 'code' => 'readapidenied',
1661 'info' => "You need read permission to use this module"
1663 'writedisabled' => array(
1664 'code' => 'noapiwrite',
1665 'info' => "Editing of this wiki through the API is disabled. Make sure the \$wgEnableWriteAPI=true; statement is included in the wiki's LocalSettings.php file"
1667 'writerequired' => array(
1668 'code' => 'writeapidenied',
1669 'info' => "You're not allowed to edit this wiki through the API"
1671 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1672 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1673 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1674 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1675 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1676 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1677 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1678 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1679 'create-titleexists' => array(
1680 'code' => 'create-titleexists',
1681 'info' => "Existing titles can't be protected with 'create'"
1683 'missingtitle-createonly' => array(
1684 'code' => 'missingtitle-createonly',
1685 'info' => "Missing titles can only be protected with 'create'"
1687 'cantblock' => array( 'code' => 'cantblock',
1688 'info' => "You don't have permission to block users"
1690 'canthide' => array(
1691 'code' => 'canthide',
1692 'info' => "You don't have permission to hide user names from the block log"
1694 'cantblock-email' => array(
1695 'code' => 'cantblock-email',
1696 'info' => "You don't have permission to block users from sending email through the wiki"
1698 'unblock-notarget' => array(
1699 'code' => 'notarget',
1700 'info' => "Either the id or the user parameter must be set"
1702 'unblock-idanduser' => array(
1703 'code' => 'idanduser',
1704 'info' => "The id and user parameters can't be used together"
1706 'cantunblock' => array(
1707 'code' => 'permissiondenied',
1708 'info' => "You don't have permission to unblock users"
1710 'cannotundelete' => array(
1711 'code' => 'cantundelete',
1712 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1714 'permdenied-undelete' => array(
1715 'code' => 'permissiondenied',
1716 'info' => "You don't have permission to restore deleted revisions"
1718 'createonly-exists' => array(
1719 'code' => 'articleexists',
1720 'info' => "The article you tried to create has been created already"
1722 'nocreate-missing' => array(
1723 'code' => 'missingtitle',
1724 'info' => "The article you tried to edit doesn't exist"
1726 'nosuchrcid' => array(
1727 'code' => 'nosuchrcid',
1728 'info' => "There is no change with rcid \"\$1\""
1730 'protect-invalidaction' => array(
1731 'code' => 'protect-invalidaction',
1732 'info' => "Invalid protection type \"\$1\""
1734 'protect-invalidlevel' => array(
1735 'code' => 'protect-invalidlevel',
1736 'info' => "Invalid protection level \"\$1\""
1738 'toofewexpiries' => array(
1739 'code' => 'toofewexpiries',
1740 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1742 'cantimport' => array(
1743 'code' => 'cantimport',
1744 'info' => "You don't have permission to import pages"
1746 'cantimport-upload' => array(
1747 'code' => 'cantimport-upload',
1748 'info' => "You don't have permission to import uploaded pages"
1750 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1751 'importuploaderrorsize' => array(
1752 'code' => 'filetoobig',
1753 'info' => 'The file you uploaded is bigger than the maximum upload size'
1755 'importuploaderrorpartial' => array(
1756 'code' => 'partialupload',
1757 'info' => 'The file was only partially uploaded'
1759 'importuploaderrortemp' => array(
1760 'code' => 'notempdir',
1761 'info' => 'The temporary upload directory is missing'
1763 'importcantopen' => array(
1764 'code' => 'cantopenfile',
1765 'info' => "Couldn't open the uploaded file"
1767 'import-noarticle' => array(
1768 'code' => 'badinterwiki',
1769 'info' => 'Invalid interwiki title specified'
1771 'importbadinterwiki' => array(
1772 'code' => 'badinterwiki',
1773 'info' => 'Invalid interwiki title specified'
1775 'import-unknownerror' => array(
1776 'code' => 'import-unknownerror',
1777 'info' => "Unknown error on import: \"\$1\""
1779 'cantoverwrite-sharedfile' => array(
1780 'code' => 'cantoverwrite-sharedfile',
1781 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1783 'sharedfile-exists' => array(
1784 'code' => 'fileexists-sharedrepo-perm',
1785 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1787 'mustbeposted' => array(
1788 'code' => 'mustbeposted',
1789 'info' => "The \$1 module requires a POST request"
1791 'show' => array(
1792 'code' => 'show',
1793 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1795 'specialpage-cantexecute' => array(
1796 'code' => 'specialpage-cantexecute',
1797 'info' => "You don't have permission to view the results of this special page"
1799 'invalidoldimage' => array(
1800 'code' => 'invalidoldimage',
1801 'info' => 'The oldimage parameter has invalid format'
1803 'nodeleteablefile' => array(
1804 'code' => 'nodeleteablefile',
1805 'info' => 'No such old version of the file'
1807 'fileexists-forbidden' => array(
1808 'code' => 'fileexists-forbidden',
1809 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1811 'fileexists-shared-forbidden' => array(
1812 'code' => 'fileexists-shared-forbidden',
1813 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1815 'filerevert-badversion' => array(
1816 'code' => 'filerevert-badversion',
1817 'info' => 'There is no previous local version of this file with the provided timestamp.'
1820 // ApiEditPage messages
1821 'noimageredirect-anon' => array(
1822 'code' => 'noimageredirect-anon',
1823 'info' => "Anonymous users can't create image redirects"
1825 'noimageredirect-logged' => array(
1826 'code' => 'noimageredirect',
1827 'info' => "You don't have permission to create image redirects"
1829 'spamdetected' => array(
1830 'code' => 'spamdetected',
1831 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1833 'contenttoobig' => array(
1834 'code' => 'contenttoobig',
1835 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1837 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1838 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1839 'wasdeleted' => array(
1840 'code' => 'pagedeleted',
1841 'info' => "The page has been deleted since you fetched its timestamp"
1843 'blankpage' => array(
1844 'code' => 'emptypage',
1845 'info' => "Creating new, empty pages is not allowed"
1847 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1848 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1849 'missingtext' => array(
1850 'code' => 'notext',
1851 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1853 'emptynewsection' => array(
1854 'code' => 'emptynewsection',
1855 'info' => 'Creating empty new sections is not possible.'
1857 'revwrongpage' => array(
1858 'code' => 'revwrongpage',
1859 'info' => "r\$1 is not a revision of \"\$2\""
1861 'undo-failure' => array(
1862 'code' => 'undofailure',
1863 'info' => 'Undo failed due to conflicting intermediate edits'
1866 // Messages from WikiPage::doEit()
1867 'edit-hook-aborted' => array(
1868 'code' => 'edit-hook-aborted',
1869 'info' => "Your edit was aborted by an ArticleSave hook"
1871 'edit-gone-missing' => array(
1872 'code' => 'edit-gone-missing',
1873 'info' => "The page you tried to edit doesn't seem to exist anymore"
1875 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1876 'edit-already-exists' => array(
1877 'code' => 'edit-already-exists',
1878 'info' => 'It seems the page you tried to create already exist'
1881 // uploadMsgs
1882 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1883 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1884 'uploaddisabled' => array(
1885 'code' => 'uploaddisabled',
1886 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1888 'copyuploaddisabled' => array(
1889 'code' => 'copyuploaddisabled',
1890 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1892 'copyuploadbaddomain' => array(
1893 'code' => 'copyuploadbaddomain',
1894 'info' => 'Uploads by URL are not allowed from this domain.'
1896 'copyuploadbadurl' => array(
1897 'code' => 'copyuploadbadurl',
1898 'info' => 'Upload not allowed from this URL.'
1901 'filename-tooshort' => array(
1902 'code' => 'filename-tooshort',
1903 'info' => 'The filename is too short'
1905 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1906 'illegal-filename' => array(
1907 'code' => 'illegal-filename',
1908 'info' => 'The filename is not allowed'
1910 'filetype-missing' => array(
1911 'code' => 'filetype-missing',
1912 'info' => 'The file is missing an extension'
1915 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1917 // @codingStandardsIgnoreEnd
1920 * Helper function for readonly errors
1922 public function dieReadOnly() {
1923 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1924 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1925 array( 'readonlyreason' => wfReadOnlyReason() ) );
1929 * Output the error message related to a certain array
1930 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1932 public function dieUsageMsg( $error ) {
1933 # most of the time we send a 1 element, so we might as well send it as
1934 # a string and make this an array here.
1935 if ( is_string( $error ) ) {
1936 $error = array( $error );
1938 $parsed = $this->parseMsg( $error );
1939 $this->dieUsage( $parsed['info'], $parsed['code'] );
1943 * Will only set a warning instead of failing if the global $wgDebugAPI
1944 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1945 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1946 * @since 1.21
1948 public function dieUsageMsgOrDebug( $error ) {
1949 global $wgDebugAPI;
1950 if ( $wgDebugAPI !== true ) {
1951 $this->dieUsageMsg( $error );
1954 if ( is_string( $error ) ) {
1955 $error = array( $error );
1958 $parsed = $this->parseMsg( $error );
1959 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1963 * Die with the $prefix.'badcontinue' error. This call is common enough to
1964 * make it into the base method.
1965 * @param bool $condition Will only die if this value is true
1966 * @since 1.21
1968 protected function dieContinueUsageIf( $condition ) {
1969 if ( $condition ) {
1970 $this->dieUsage(
1971 'Invalid continue param. You should pass the original value returned by the previous query',
1972 'badcontinue' );
1977 * Return the error message related to a certain array
1978 * @param array $error Element of a getUserPermissionsErrors()-style array
1979 * @return array('code' => code, 'info' => info)
1981 public function parseMsg( $error ) {
1982 $error = (array)$error; // It seems strings sometimes make their way in here
1983 $key = array_shift( $error );
1985 // Check whether the error array was nested
1986 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1987 if ( is_array( $key ) ) {
1988 $error = $key;
1989 $key = array_shift( $error );
1992 if ( isset( self::$messageMap[$key] ) ) {
1993 return array(
1994 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
1995 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
1999 // If the key isn't present, throw an "unknown error"
2000 return $this->parseMsg( array( 'unknownerror', $key ) );
2004 * Internal code errors should be reported with this method
2005 * @param string $method Method or function name
2006 * @param string $message Error message
2007 * @throws MWException
2009 protected static function dieDebug( $method, $message ) {
2010 throw new MWException( "Internal error in $method: $message" );
2014 * Indicates if this module needs maxlag to be checked
2015 * @return bool
2017 public function shouldCheckMaxlag() {
2018 return true;
2022 * Indicates whether this module requires read rights
2023 * @return bool
2025 public function isReadMode() {
2026 return true;
2030 * Indicates whether this module requires write mode
2031 * @return bool
2033 public function isWriteMode() {
2034 return false;
2038 * Indicates whether this module must be called with a POST request
2039 * @return bool
2041 public function mustBePosted() {
2042 return false;
2046 * Returns whether this module requires a token to execute
2047 * It is used to show possible errors in action=paraminfo
2048 * see bug 25248
2049 * @return bool
2051 public function needsToken() {
2052 return false;
2056 * Returns the token salt if there is one,
2057 * '' if the module doesn't require a salt,
2058 * else false if the module doesn't need a token
2059 * You have also to override needsToken()
2060 * Value is passed to User::getEditToken
2061 * @return bool|string|array
2063 public function getTokenSalt() {
2064 return false;
2068 * Gets the user for whom to get the watchlist
2070 * @param array $params
2071 * @return User
2073 public function getWatchlistUser( $params ) {
2074 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
2075 $user = User::newFromName( $params['owner'], false );
2076 if ( !( $user && $user->getId() ) ) {
2077 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
2079 $token = $user->getOption( 'watchlisttoken' );
2080 if ( $token == '' || $token != $params['token'] ) {
2081 $this->dieUsage(
2082 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
2083 'bad_wltoken'
2086 } else {
2087 if ( !$this->getUser()->isLoggedIn() ) {
2088 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
2090 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
2091 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
2093 $user = $this->getUser();
2096 return $user;
2100 * @return bool|string|array Returns a false if the module has no help URL,
2101 * else returns a (array of) string
2103 public function getHelpUrls() {
2104 return false;
2108 * Returns a list of all possible errors returned by the module
2110 * Don't call this function directly: use getFinalPossibleErrors() to allow
2111 * hooks to modify parameters as needed.
2113 * @return array Array in the format of array( key, param1, param2, ... )
2114 * or array( 'code' => ..., 'info' => ... )
2116 public function getPossibleErrors() {
2117 $ret = array();
2119 $params = $this->getFinalParams();
2120 if ( $params ) {
2121 foreach ( $params as $paramName => $paramSettings ) {
2122 if ( isset( $paramSettings[ApiBase::PARAM_REQUIRED] )
2123 && $paramSettings[ApiBase::PARAM_REQUIRED]
2125 $ret[] = array( 'missingparam', $paramName );
2128 if ( array_key_exists( 'continue', $params ) ) {
2129 $ret[] = array(
2130 'code' => 'badcontinue',
2131 'info' => 'Invalid continue param. You should pass the ' .
2132 'original value returned by the previous query'
2137 if ( $this->mustBePosted() ) {
2138 $ret[] = array( 'mustbeposted', $this->getModuleName() );
2141 if ( $this->isReadMode() ) {
2142 $ret[] = array( 'readrequired' );
2145 if ( $this->isWriteMode() ) {
2146 $ret[] = array( 'writerequired' );
2147 $ret[] = array( 'writedisabled' );
2150 if ( $this->needsToken() ) {
2151 if ( !isset( $params['token'][ApiBase::PARAM_REQUIRED] )
2152 || !$params['token'][ApiBase::PARAM_REQUIRED]
2154 // Add token as possible missing parameter, if not already done
2155 $ret[] = array( 'missingparam', 'token' );
2157 $ret[] = array( 'sessionfailure' );
2160 return $ret;
2164 * Get final list of possible errors, after hooks have had a chance to
2165 * tweak it as needed.
2167 * @return array
2168 * @since 1.22
2170 public function getFinalPossibleErrors() {
2171 $possibleErrors = $this->getPossibleErrors();
2172 wfRunHooks( 'APIGetPossibleErrors', array( $this, &$possibleErrors ) );
2174 return $possibleErrors;
2178 * Parses a list of errors into a standardised format
2179 * @param array $errors List of errors. Items can be in the for
2180 * array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
2181 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
2183 public function parseErrors( $errors ) {
2184 $ret = array();
2186 foreach ( $errors as $row ) {
2187 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
2188 $ret[] = $row;
2189 } else {
2190 $ret[] = $this->parseMsg( $row );
2194 return $ret;
2198 * Profiling: total module execution time
2200 private $mTimeIn = 0, $mModuleTime = 0;
2203 * Start module profiling
2205 public function profileIn() {
2206 if ( $this->mTimeIn !== 0 ) {
2207 ApiBase::dieDebug( __METHOD__, 'Called twice without calling profileOut()' );
2209 $this->mTimeIn = microtime( true );
2210 wfProfileIn( $this->getModuleProfileName() );
2214 * End module profiling
2216 public function profileOut() {
2217 if ( $this->mTimeIn === 0 ) {
2218 ApiBase::dieDebug( __METHOD__, 'Called without calling profileIn() first' );
2220 if ( $this->mDBTimeIn !== 0 ) {
2221 ApiBase::dieDebug(
2222 __METHOD__,
2223 'Must be called after database profiling is done with profileDBOut()'
2227 $this->mModuleTime += microtime( true ) - $this->mTimeIn;
2228 $this->mTimeIn = 0;
2229 wfProfileOut( $this->getModuleProfileName() );
2233 * When modules crash, sometimes it is needed to do a profileOut() regardless
2234 * of the profiling state the module was in. This method does such cleanup.
2236 public function safeProfileOut() {
2237 if ( $this->mTimeIn !== 0 ) {
2238 if ( $this->mDBTimeIn !== 0 ) {
2239 $this->profileDBOut();
2241 $this->profileOut();
2246 * Total time the module was executed
2247 * @return float
2249 public function getProfileTime() {
2250 if ( $this->mTimeIn !== 0 ) {
2251 ApiBase::dieDebug( __METHOD__, 'Called without calling profileOut() first' );
2254 return $this->mModuleTime;
2258 * Profiling: database execution time
2260 private $mDBTimeIn = 0, $mDBTime = 0;
2263 * Start module profiling
2265 public function profileDBIn() {
2266 if ( $this->mTimeIn === 0 ) {
2267 ApiBase::dieDebug(
2268 __METHOD__,
2269 'Must be called while profiling the entire module with profileIn()'
2272 if ( $this->mDBTimeIn !== 0 ) {
2273 ApiBase::dieDebug( __METHOD__, 'Called twice without calling profileDBOut()' );
2275 $this->mDBTimeIn = microtime( true );
2276 wfProfileIn( $this->getModuleProfileName( true ) );
2280 * End database profiling
2282 public function profileDBOut() {
2283 if ( $this->mTimeIn === 0 ) {
2284 ApiBase::dieDebug( __METHOD__, 'Must be called while profiling ' .
2285 'the entire module with profileIn()' );
2287 if ( $this->mDBTimeIn === 0 ) {
2288 ApiBase::dieDebug( __METHOD__, 'Called without calling profileDBIn() first' );
2291 $time = microtime( true ) - $this->mDBTimeIn;
2292 $this->mDBTimeIn = 0;
2294 $this->mDBTime += $time;
2295 $this->getMain()->mDBTime += $time;
2296 wfProfileOut( $this->getModuleProfileName( true ) );
2300 * Total time the module used the database
2301 * @return float
2303 public function getProfileDBTime() {
2304 if ( $this->mDBTimeIn !== 0 ) {
2305 ApiBase::dieDebug( __METHOD__, 'Called without calling profileDBOut() first' );
2308 return $this->mDBTime;
2312 * Gets a default slave database connection object
2313 * @return DatabaseBase
2315 protected function getDB() {
2316 if ( !isset( $this->mSlaveDB ) ) {
2317 $this->profileDBIn();
2318 $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
2319 $this->profileDBOut();
2322 return $this->mSlaveDB;
2326 * Debugging function that prints a value and an optional backtrace
2327 * @param mixed $value Value to print
2328 * @param string $name Description of the printed value
2329 * @param bool $backtrace If true, print a backtrace
2331 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
2332 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
2333 var_export( $value );
2334 if ( $backtrace ) {
2335 print "\n" . wfBacktrace();
2337 print "\n</pre>\n";