Put some upper limit here
[mediawiki.git] / includes / api / ApiBase.php
blob0b496b90e00bfa3ce5a32e47de820459d2b7acf3
1 <?php
3 /*
4 * Created on Sep 5, 2006
6 * API for MediaWiki 1.8+
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 * http://www.gnu.org/copyleft/gpl.html
26 /**
27 * This abstract class implements many basic API functions, and is the base of all API classes.
28 * The class functions are divided into several areas of functionality:
30 * Module parameters: Derived classes can define getAllowedParams() to specify which parameters to expect,
31 * how to parse and validate them.
33 * Profiling: various methods to allow keeping tabs on various tasks and their time costs
35 * Self-documentation: code to allow api to document its own state.
37 * @addtogroup API
39 abstract class ApiBase {
41 // These constants allow modules to specify exactly how to treat incomming parameters.
43 const PARAM_DFLT = 0;
44 const PARAM_ISMULTI = 1;
45 const PARAM_TYPE = 2;
46 const PARAM_MAX = 3;
47 const PARAM_MAX2 = 4;
48 const PARAM_MIN = 5;
50 const LIMIT_BIG1 = 500; // Fast query, std user limit
51 const LIMIT_BIG2 = 5000; // Fast query, bot/sysop limit
52 const LIMIT_SML1 = 50; // Slow query, std user limit
53 const LIMIT_SML2 = 500; // Slow query, bot/sysop limit
55 private $mMainModule, $mModuleName, $mModulePrefix;
57 /**
58 * Constructor
60 public function __construct($mainModule, $moduleName, $modulePrefix = '') {
61 $this->mMainModule = $mainModule;
62 $this->mModuleName = $moduleName;
63 $this->mModulePrefix = $modulePrefix;
66 /*****************************************************************************
67 * ABSTRACT METHODS *
68 *****************************************************************************/
70 /**
71 * Evaluates the parameters, performs the requested query, and sets up the
72 * result. Concrete implementations of ApiBase must override this method to
73 * provide whatever functionality their module offers. Implementations must
74 * not produce any output on their own and are not expected to handle any
75 * errors.
77 * The execute method will be invoked directly by ApiMain immediately before
78 * the result of the module is output. Aside from the constructor, implementations
79 * should assume that no other methods will be called externally on the module
80 * before the result is processed.
82 * The result data should be stored in the result object referred to by
83 * "getResult()". Refer to ApiResult.php for details on populating a result
84 * object.
86 public abstract function execute();
88 /**
89 * Returns a String that identifies the version of the extending class. Typically
90 * includes the class name, the svn revision, timestamp, and last author. May
91 * be severely incorrect in many implementations!
93 public abstract function getVersion();
95 /**
96 * Get the name of the module being executed by this instance
98 public function getModuleName() {
99 return $this->mModuleName;
103 * Get parameter prefix (usually two letters or an empty string).
105 public function getModulePrefix() {
106 return $this->mModulePrefix;
110 * Get the name of the module as shown in the profiler log
112 public function getModuleProfileName($db = false) {
113 if ($db)
114 return 'API:' . $this->mModuleName . '-DB';
115 else
116 return 'API:' . $this->mModuleName;
120 * Get main module
122 public function getMain() {
123 return $this->mMainModule;
127 * Returns true if this module is the main module ($this === $this->mMainModule),
128 * false otherwise.
130 public function isMain() {
131 return $this === $this->mMainModule;
135 * Get the result object. Please refer to the documentation in ApiResult.php
136 * for details on populating and accessing data in a result object.
138 public function getResult() {
139 // Main module has getResult() method overriden
140 // Safety - avoid infinite loop:
141 if ($this->isMain())
142 ApiBase :: dieDebug(__METHOD__, 'base method was called on main module. ');
143 return $this->getMain()->getResult();
147 * Get the result data array
149 public function & getResultData() {
150 return $this->getResult()->getData();
154 * Set warning section for this module. Users should monitor this section to
155 * notice any changes in API.
157 public function setWarning($warning) {
158 $msg = array();
159 ApiResult :: setContent($msg, $warning);
160 $this->getResult()->addValue('warnings', $this->getModuleName(), $msg);
164 * If the module may only be used with a certain format module,
165 * it should override this method to return an instance of that formatter.
166 * A value of null means the default format will be used.
168 public function getCustomPrinter() {
169 return null;
173 * Generates help message for this module, or false if there is no description
175 public function makeHelpMsg() {
177 static $lnPrfx = "\n ";
179 $msg = $this->getDescription();
181 if ($msg !== false) {
183 if (!is_array($msg))
184 $msg = array (
185 $msg
187 $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
189 if ($this->mustBePosted())
190 $msg .= "\nThis module only accepts POST requests.\n";
192 // Parameters
193 $paramsMsg = $this->makeHelpMsgParameters();
194 if ($paramsMsg !== false) {
195 $msg .= "Parameters:\n$paramsMsg";
198 // Examples
199 $examples = $this->getExamples();
200 if ($examples !== false) {
201 if (!is_array($examples))
202 $examples = array (
203 $examples
205 $msg .= 'Example' . (count($examples) > 1 ? 's' : '') . ":\n ";
206 $msg .= implode($lnPrfx, $examples) . "\n";
209 if ($this->getMain()->getShowVersions()) {
210 $versions = $this->getVersion();
211 $pattern = '(\$.*) ([0-9a-z_]+\.php) (.*\$)';
212 $replacement = '\\0' . "\n " . 'http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/api/\\2';
214 if (is_array($versions)) {
215 foreach ($versions as &$v)
216 $v = eregi_replace($pattern, $replacement, $v);
217 $versions = implode("\n ", $versions);
219 else
220 $versions = eregi_replace($pattern, $replacement, $versions);
222 $msg .= "Version:\n $versions\n";
226 return $msg;
230 * Generates the parameter descriptions for this module, to be displayed in the
231 * module's help.
233 public function makeHelpMsgParameters() {
234 $params = $this->getAllowedParams();
235 if ($params !== false) {
237 $paramsDescription = $this->getParamDescription();
238 $msg = '';
239 $paramPrefix = "\n" . str_repeat(' ', 19);
240 foreach ($params as $paramName => $paramSettings) {
241 $desc = isset ($paramsDescription[$paramName]) ? $paramsDescription[$paramName] : '';
242 if (is_array($desc))
243 $desc = implode($paramPrefix, $desc);
245 $type = isset($paramSettings[self :: PARAM_TYPE])? $paramSettings[self :: PARAM_TYPE] : null;
246 if (isset ($type)) {
247 if (isset ($paramSettings[self :: PARAM_ISMULTI]))
248 $prompt = 'Values (separate with \'|\'): ';
249 else
250 $prompt = 'One value: ';
252 if (is_array($type)) {
253 $choices = array();
254 $nothingPrompt = false;
255 foreach ($type as $t)
256 if ($t=='')
257 $nothingPrompt = 'Can be empty, or ';
258 else
259 $choices[] = $t;
260 $desc .= $paramPrefix . $nothingPrompt . $prompt . implode(', ', $choices);
261 } else {
262 switch ($type) {
263 case 'namespace':
264 // Special handling because namespaces are type-limited, yet they are not given
265 $desc .= $paramPrefix . $prompt . implode(', ', ApiBase :: getValidNamespaces());
266 break;
267 case 'limit':
268 $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]} ({$paramSettings[self :: PARAM_MAX2]} for bots) allowed.";
269 break;
270 case 'integer':
271 $hasMin = isset($paramSettings[self :: PARAM_MIN]);
272 $hasMax = isset($paramSettings[self :: PARAM_MAX]);
273 if ($hasMin || $hasMax) {
274 if (!$hasMax)
275 $intRangeStr = "The value must be no less than {$paramSettings[self :: PARAM_MIN]}";
276 elseif (!$hasMin)
277 $intRangeStr = "The value must be no more than {$paramSettings[self :: PARAM_MAX]}";
278 else
279 $intRangeStr = "The value must be between {$paramSettings[self :: PARAM_MIN]} and {$paramSettings[self :: PARAM_MAX]}";
281 $desc .= $paramPrefix . $intRangeStr;
283 break;
288 $default = is_array($paramSettings) ? (isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null) : $paramSettings;
289 if (!is_null($default) && $default !== false)
290 $desc .= $paramPrefix . "Default: $default";
292 $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
294 return $msg;
296 } else
297 return false;
301 * Returns the description string for this module
303 protected function getDescription() {
304 return false;
308 * Returns usage examples for this module. Return null if no examples are available.
310 protected function getExamples() {
311 return false;
315 * Returns an array of allowed parameters (keys) => default value for that parameter
317 protected function getAllowedParams() {
318 return false;
322 * Returns the description string for the given parameter.
324 protected function getParamDescription() {
325 return false;
329 * This method mangles parameter name based on the prefix supplied to the constructor.
330 * Override this method to change parameter name during runtime
332 public function encodeParamName($paramName) {
333 return $this->mModulePrefix . $paramName;
337 * Using getAllowedParams(), makes an array of the values provided by the user,
338 * with key being the name of the variable, and value - validated value from user or default.
339 * This method can be used to generate local variables using extract().
340 * limit=max will not be parsed if $parseMaxLimit is set to false; use this
341 * when the max limit is not definite, e.g. when getting revisions.
343 public function extractRequestParams($parseMaxLimit = true) {
344 $params = $this->getAllowedParams();
345 $results = array ();
347 foreach ($params as $paramName => $paramSettings)
348 $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings, $parseMaxLimit);
350 return $results;
354 * Get a value for the given parameter
356 protected function getParameter($paramName, $parseMaxLimit = true) {
357 $params = $this->getAllowedParams();
358 $paramSettings = $params[$paramName];
359 return $this->getParameterFromSettings($paramName, $paramSettings, $parseMaxLimit);
363 * Returns an array of the namespaces (by integer id) that exist on the
364 * wiki. Used primarily in help documentation.
366 public static function getValidNamespaces() {
367 static $mValidNamespaces = null;
368 if (is_null($mValidNamespaces)) {
370 global $wgContLang;
371 $mValidNamespaces = array ();
372 foreach (array_keys($wgContLang->getNamespaces()) as $ns) {
373 if ($ns >= 0)
374 $mValidNamespaces[] = $ns;
377 return $mValidNamespaces;
381 * Using the settings determine the value for the given parameter
383 * @param $paramName String: parameter name
384 * @param $paramSettings Mixed: default value or an array of settings using PARAM_* constants.
385 * @param $parseMaxLimit Boolean: parse limit when max is given?
387 protected function getParameterFromSettings($paramName, $paramSettings, $parseMaxLimit) {
389 // Some classes may decide to change parameter names
390 $encParamName = $this->encodeParamName($paramName);
392 if (!is_array($paramSettings)) {
393 $default = $paramSettings;
394 $multi = false;
395 $type = gettype($paramSettings);
396 } else {
397 $default = isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null;
398 $multi = isset ($paramSettings[self :: PARAM_ISMULTI]) ? $paramSettings[self :: PARAM_ISMULTI] : false;
399 $type = isset ($paramSettings[self :: PARAM_TYPE]) ? $paramSettings[self :: PARAM_TYPE] : null;
401 // When type is not given, and no choices, the type is the same as $default
402 if (!isset ($type)) {
403 if (isset ($default))
404 $type = gettype($default);
405 else
406 $type = 'NULL'; // allow everything
410 if ($type == 'boolean') {
411 if (isset ($default) && $default !== false) {
412 // Having a default value of anything other than 'false' is pointless
413 ApiBase :: dieDebug(__METHOD__, "Boolean param $encParamName's default is set to '$default'");
416 $value = $this->getMain()->getRequest()->getCheck($encParamName);
417 } else {
418 $value = $this->getMain()->getRequest()->getVal($encParamName, $default);
420 if (isset ($value) && $type == 'namespace')
421 $type = ApiBase :: getValidNamespaces();
424 if (isset ($value) && ($multi || is_array($type)))
425 $value = $this->parseMultiValue($encParamName, $value, $multi, is_array($type) ? $type : null);
427 // More validation only when choices were not given
428 // choices were validated in parseMultiValue()
429 if (isset ($value)) {
430 if (!is_array($type)) {
431 switch ($type) {
432 case 'NULL' : // nothing to do
433 break;
434 case 'string' : // nothing to do
435 break;
436 case 'integer' : // Force everything using intval() and optionally validate limits
438 $value = is_array($value) ? array_map('intval', $value) : intval($value);
439 $min = isset ($paramSettings[self :: PARAM_MIN]) ? $paramSettings[self :: PARAM_MIN] : null;
440 $max = isset ($paramSettings[self :: PARAM_MAX]) ? $paramSettings[self :: PARAM_MAX] : null;
442 if (!is_null($min) || !is_null($max)) {
443 $values = is_array($value) ? $value : array($value);
444 foreach ($values as $v) {
445 $this->validateLimit($paramName, $v, $min, $max);
448 break;
449 case 'limit' :
450 if (!isset ($paramSettings[self :: PARAM_MAX]) || !isset ($paramSettings[self :: PARAM_MAX2]))
451 ApiBase :: dieDebug(__METHOD__, "MAX1 or MAX2 are not defined for the limit $encParamName");
452 if ($multi)
453 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
454 $min = isset ($paramSettings[self :: PARAM_MIN]) ? $paramSettings[self :: PARAM_MIN] : 0;
455 if( $value == 'max' ) {
456 if( $parseMaxLimit ) {
457 $value = $this->getMain()->canApiHighLimits() ? $paramSettings[self :: PARAM_MAX2] : $paramSettings[self :: PARAM_MAX];
458 $this->getResult()->addValue( 'limits', $this->getModuleName(), $value );
459 $this->validateLimit($paramName, $value, $min, $paramSettings[self :: PARAM_MAX], $paramSettings[self :: PARAM_MAX2]);
462 else {
463 $value = intval($value);
464 $this->validateLimit($paramName, $value, $min, $paramSettings[self :: PARAM_MAX], $paramSettings[self :: PARAM_MAX2]);
466 break;
467 case 'boolean' :
468 if ($multi)
469 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
470 break;
471 case 'timestamp' :
472 if ($multi)
473 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
474 $value = wfTimestamp(TS_UNIX, $value);
475 if ($value === 0)
476 $this->dieUsage("Invalid value '$value' for timestamp parameter $encParamName", "badtimestamp_{$encParamName}");
477 $value = wfTimestamp(TS_MW, $value);
478 break;
479 case 'user' :
480 $title = Title::makeTitleSafe( NS_USER, $value );
481 if ( is_null( $title ) )
482 $this->dieUsage("Invalid value for user parameter $encParamName", "baduser_{$encParamName}");
483 $value = $title->getText();
484 break;
485 default :
486 ApiBase :: dieDebug(__METHOD__, "Param $encParamName's type is unknown - $type");
490 // There should never be any duplicate values in a list
491 if (is_array($value))
492 $value = array_unique($value);
495 return $value;
499 * Return an array of values that were given in a 'a|b|c' notation,
500 * after it optionally validates them against the list allowed values.
502 * @param valueName - The name of the parameter (for error reporting)
503 * @param value - The value being parsed
504 * @param allowMultiple - Can $value contain more than one value separated by '|'?
505 * @param allowedValues - An array of values to check against. If null, all values are accepted.
506 * @return (allowMultiple ? an_array_of_values : a_single_value)
508 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
509 if( trim($value) === "" )
510 return array();
511 $valuesList = explode('|', $value,51); // some kind of limit is needed here!
512 if( count($valuesList) == 51 ) {
513 $junk = array_pop($valuesList); // kill last jumbled param
515 if (!$allowMultiple && count($valuesList) != 1) {
516 $possibleValues = is_array($allowedValues) ? "of '" . implode("', '", $allowedValues) . "'" : '';
517 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
519 if (is_array($allowedValues)) {
520 $unknownValues = array_diff($valuesList, $allowedValues);
521 if ($unknownValues) {
522 $this->dieUsage('Unrecognised value' . (count($unknownValues) > 1 ? "s" : "") . " for parameter '$valueName'", "unknown_$valueName");
526 return $allowMultiple ? $valuesList : $valuesList[0];
530 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
532 function validateLimit($paramName, $value, $min, $max, $botMax = null) {
533 if (!is_null($min) && $value < $min) {
534 $this->dieUsage($this->encodeParamName($paramName) . " may not be less than $min (set to $value)", $paramName);
537 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
538 if ($this->getMain()->isInternalMode())
539 return;
541 // Optimization: do not check user's bot status unless really needed -- skips db query
542 // assumes $botMax >= $max
543 if (!is_null($max) && $value > $max) {
544 if (!is_null($botMax) && $this->getMain()->canApiHighLimits()) {
545 if ($value > $botMax) {
546 $this->dieUsage($this->encodeParamName($paramName) . " may not be over $botMax (set to $value) for bots or sysops", $paramName);
548 } else {
549 $this->dieUsage($this->encodeParamName($paramName) . " may not be over $max (set to $value) for users", $paramName);
555 * Call main module's error handler
557 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
558 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
562 * Array that maps message keys to error messages. $1 and friends are replaced.
564 public static $messageMap = array(
565 // This one MUST be present, or dieUsageMsg() will recurse infinitely
566 'unknownerror' => array('code' => 'unknownerror', 'info' => "Unknown error: ``\$1''"),
567 'unknownerror-nocode' => array('code' => 'unknownerror', 'info' => 'Unknown error'),
569 // Messages from Title::getUserPermissionsErrors()
570 'ns-specialprotected' => array('code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited"),
571 'protectedinterface' => array('code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages"),
572 'namespaceprotected' => array('code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the ``\$1'' namespace"),
573 'customcssjsprotected' => array('code' => 'customcssjsprotected', 'info' => "You're not allowed to edit custom CSS and JavaScript pages"),
574 'cascadeprotected' => array('code' => 'cascadeprotected', 'info' =>"The page you're trying to edit is protected because it's included in a cascade-protected page"),
575 'protectedpagetext' => array('code' => 'protectedpage', 'info' => "The ``\$1'' right is required to edit this page"),
576 'protect-cantedit' => array('code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it"),
577 'badaccess-group0' => array('code' => 'permissiondenied', 'info' => "Permission denied"), // Generic permission denied message
578 'badaccess-group1' => array('code' => 'permissiondenied', 'info' => "Permission denied"), // Can't use the parameter 'cause it's wikilinked
579 'badaccess-group2' => array('code' => 'permissiondenied', 'info' => "Permission denied"),
580 'badaccess-groups' => array('code' => 'permissiondenied', 'info' => "Permission denied"),
581 'titleprotected' => array('code' => 'protectedtitle', 'info' => "This title has been protected from creation"),
582 'nocreate-loggedin' => array('code' => 'cantcreate', 'info' => "You don't have permission to create new pages"),
583 'nocreatetext' => array('code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages"),
584 'movenologintext' => array('code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages"),
585 'movenotallowed' => array('code' => 'cantmove', 'info' => "You don't have permission to move pages"),
586 'confirmedittext' => array('code' => 'confirmemail', 'info' => "You must confirm your e-mail address before you can edit"),
587 'blockedtext' => array('code' => 'blocked', 'info' => "You have been blocked from editing"),
588 'autoblockedtext' => array('code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"),
590 // Miscellaneous interface messages
591 'actionthrottledtext' => array('code' => 'ratelimited', 'info' => "You've exceeded your rate limit. Please wait some time and try again"),
592 'alreadyrolled' => array('code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back"),
593 'cantrollback' => array('code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author"),
594 'readonlytext' => array('code' => 'readonly', 'info' => "The wiki is currently in read-only mode"),
595 'sessionfailure' => array('code' => 'badtoken', 'info' => "Invalid token"),
596 'cannotdelete' => array('code' => 'cantdelete', 'info' => "Couldn't delete ``\$1''. Maybe it was deleted already by someone else"),
597 'notanarticle' => array('code' => 'missingtitle', 'info' => "The page you requested doesn't exist"),
598 'selfmove' => array('code' => 'selfmove', 'info' => "Can't move a page to itself"),
599 'immobile_namespace' => array('code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving"),
600 'articleexists' => array('code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article"),
601 'protectedpage' => array('code' => 'protectedpage', 'info' => "You don't have permission to perform this move"),
602 'hookaborted' => array('code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook"),
603 'cantmove-titleprotected' => array('code' => 'protectedtitle', 'info' => "The destination article has been protected from creation"),
604 // 'badarticleerror' => shouldn't happen
605 // 'badtitletext' => shouldn't happen
606 'ip_range_invalid' => array('code' => 'invalidrange', 'info' => "Invalid IP range"),
607 'range_block_disabled' => array('code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled"),
608 'nosuchusershort' => array('code' => 'nosuchuser', 'info' => "The user you specified doesn't exist"),
609 'badipaddress' => array('code' => 'invalidip', 'info' => "Invalid IP address specified"),
610 'ipb_expiry_invalid' => array('code' => 'invalidexpiry', 'info' => "Invalid expiry time"),
611 'ipb_already_blocked' => array('code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked"),
612 'ipb_blocked_as_range' => array('code' => 'blockedasrange', 'info' => "IP address ``\$1'' was blocked as part of range ``\$2''. You can't unblock the IP invidually, but you can unblock the range as a whole."),
613 'ipb_cant_unblock' => array('code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already"),
615 // API-specific messages
616 'missingparam' => array('code' => 'no$1', 'info' => "The \$1 parameter must be set"),
617 'invalidtitle' => array('code' => 'invalidtitle', 'info' => "Bad title ``\$1''"),
618 'invaliduser' => array('code' => 'invaliduser', 'info' => "Invalid username ``\$1''"),
619 'invalidexpiry' => array('code' => 'invalidexpiry', 'info' => "Invalid expiry time"),
620 'pastexpiry' => array('code' => 'pastexpiry', 'info' => "Expiry time is in the past"),
621 'create-titleexists' => array('code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'"),
622 'missingtitle-createonly' => array('code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'"),
623 'cantblock' => array('code' => 'cantblock', 'info' => "You don't have permission to block users"),
624 'canthide' => array('code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log"),
625 'cantblock-email' => array('code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending e-mail through the wiki"),
626 'unblock-notarget' => array('code' => 'notarget', 'info' => "Either the id or the user parameter must be set"),
627 'unblock-idanduser' => array('code' => 'idanduser', 'info' => "The id and user parameters can't be used together"),
628 'cantunblock' => array('code' => 'permissiondenied', 'info' => "You don't have permission to unblock users"),
629 'cannotundelete' => array('code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"),
630 'permdenied-undelete' => array('code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions"),
631 'createonly-exists' => array('code' => 'articleexists', 'info' => "The article you tried to create has been created already"),
633 // ApiEditPage messages
634 'noimageredirect-anon' => array('code' => 'noimageredirect-anon', 'info' => "Anonymous users can't create image redirects"),
635 'noimageredirect-logged' => array('code' => 'noimageredirect', 'info' => "You don't have permission to create image redirects"),
636 'spamdetected' => array('code' => 'spamdetected', 'info' => "Your edit was refused because it contained a spam fragment: ``\$1''"),
637 'filtered' => array('code' => 'filtered', 'info' => "The filter callback function refused your edit"),
638 'contenttoobig' => array('code' => 'contenttoobig', 'info' => "The content you supplied exceeds the article size limit of \$1 bytes"),
639 'noedit-anon' => array('code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages"),
640 'noedit' => array('code' => 'noedit', 'info' => "You don't have permission to edit pages"),
641 'wasdeleted' => array('code' => 'pagedeleted', 'info' => "The page has been deleted since you fetched its timestamp"),
642 'blankpage' => array('code' => 'emptypage', 'info' => "Creating new, empty pages is not allowed"),
643 'editconflict' => array('code' => 'editconflict', 'info' => "Edit conflict detected"),
647 * Output the error message related to a certain array
648 * @param array $error Element of a getUserPermissionsErrors()
650 public function dieUsageMsg($error) {
651 $key = array_shift($error);
652 if(isset(self::$messageMap[$key]))
653 $this->dieUsage(wfMsgReplaceArgs(self::$messageMap[$key]['info'], $error), wfMsgReplaceArgs(self::$messageMap[$key]['code'], $error));
654 // If the key isn't present, throw an "unknown error"
655 $this->dieUsageMsg(array('unknownerror', $key));
659 * Internal code errors should be reported with this method
661 protected static function dieDebug($method, $message) {
662 wfDebugDieBacktrace("Internal error in $method: $message");
666 * Indicates if API needs to check maxlag
668 public function shouldCheckMaxlag() {
669 return true;
673 * Indicates if this module requires edit mode
675 public function isEditMode() {
676 return false;
680 * Indicates whether this module must be called with a POST request
682 public function mustBePosted() {
683 return false;
688 * Profiling: total module execution time
690 private $mTimeIn = 0, $mModuleTime = 0;
693 * Start module profiling
695 public function profileIn() {
696 if ($this->mTimeIn !== 0)
697 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileOut()');
698 $this->mTimeIn = microtime(true);
699 wfProfileIn($this->getModuleProfileName());
703 * End module profiling
705 public function profileOut() {
706 if ($this->mTimeIn === 0)
707 ApiBase :: dieDebug(__METHOD__, 'called without calling profileIn() first');
708 if ($this->mDBTimeIn !== 0)
709 ApiBase :: dieDebug(__METHOD__, 'must be called after database profiling is done with profileDBOut()');
711 $this->mModuleTime += microtime(true) - $this->mTimeIn;
712 $this->mTimeIn = 0;
713 wfProfileOut($this->getModuleProfileName());
717 * When modules crash, sometimes it is needed to do a profileOut() regardless
718 * of the profiling state the module was in. This method does such cleanup.
720 public function safeProfileOut() {
721 if ($this->mTimeIn !== 0) {
722 if ($this->mDBTimeIn !== 0)
723 $this->profileDBOut();
724 $this->profileOut();
729 * Total time the module was executed
731 public function getProfileTime() {
732 if ($this->mTimeIn !== 0)
733 ApiBase :: dieDebug(__METHOD__, 'called without calling profileOut() first');
734 return $this->mModuleTime;
738 * Profiling: database execution time
740 private $mDBTimeIn = 0, $mDBTime = 0;
743 * Start module profiling
745 public function profileDBIn() {
746 if ($this->mTimeIn === 0)
747 ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
748 if ($this->mDBTimeIn !== 0)
749 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileDBOut()');
750 $this->mDBTimeIn = microtime(true);
751 wfProfileIn($this->getModuleProfileName(true));
755 * End database profiling
757 public function profileDBOut() {
758 if ($this->mTimeIn === 0)
759 ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
760 if ($this->mDBTimeIn === 0)
761 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBIn() first');
763 $time = microtime(true) - $this->mDBTimeIn;
764 $this->mDBTimeIn = 0;
766 $this->mDBTime += $time;
767 $this->getMain()->mDBTime += $time;
768 wfProfileOut($this->getModuleProfileName(true));
772 * Total time the module used the database
774 public function getProfileDBTime() {
775 if ($this->mDBTimeIn !== 0)
776 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBOut() first');
777 return $this->mDBTime;
780 public static function debugPrint($value, $name = 'unknown', $backtrace = false) {
781 print "\n\n<pre><b>Debuging value '$name':</b>\n\n";
782 var_export($value);
783 if ($backtrace)
784 print "\n" . wfBacktrace();
785 print "\n</pre>\n";
790 * Returns a String that identifies the version of this class.
792 public static function getBaseVersion() {
793 return __CLASS__ . ': $Id$';