API: Rename dontcreate to createonly, which actually makes sense
[lhc/web/wiklou.git] / includes / api / ApiBase.php
1 <?php
2
3 /*
4 * Created on Sep 5, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 *
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.
14 *
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.
19 *
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
24 */
25
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:
29 *
30 * Module parameters: Derived classes can define getAllowedParams() to specify which parameters to expect,
31 * how to parse and validate them.
32 *
33 * Profiling: various methods to allow keeping tabs on various tasks and their time costs
34 *
35 * Self-documentation: code to allow api to document its own state.
36 *
37 * @addtogroup API
38 */
39 abstract class ApiBase {
40
41 // These constants allow modules to specify exactly how to treat incomming parameters.
42
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;
49
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
54
55 private $mMainModule, $mModuleName, $mModulePrefix;
56
57 /**
58 * Constructor
59 */
60 public function __construct($mainModule, $moduleName, $modulePrefix = '') {
61 $this->mMainModule = $mainModule;
62 $this->mModuleName = $moduleName;
63 $this->mModulePrefix = $modulePrefix;
64 }
65
66 /*****************************************************************************
67 * ABSTRACT METHODS *
68 *****************************************************************************/
69
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.
76 *
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.
81 *
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.
85 */
86 public abstract function execute();
87
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!
92 */
93 public abstract function getVersion();
94
95 /**
96 * Get the name of the module being executed by this instance
97 */
98 public function getModuleName() {
99 return $this->mModuleName;
100 }
101
102 /**
103 * Get parameter prefix (usually two letters or an empty string).
104 */
105 public function getModulePrefix() {
106 return $this->mModulePrefix;
107 }
108
109 /**
110 * Get the name of the module as shown in the profiler log
111 */
112 public function getModuleProfileName($db = false) {
113 if ($db)
114 return 'API:' . $this->mModuleName . '-DB';
115 else
116 return 'API:' . $this->mModuleName;
117 }
118
119 /**
120 * Get main module
121 */
122 public function getMain() {
123 return $this->mMainModule;
124 }
125
126 /**
127 * Returns true if this module is the main module ($this === $this->mMainModule),
128 * false otherwise.
129 */
130 public function isMain() {
131 return $this === $this->mMainModule;
132 }
133
134 /**
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.
137 */
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();
144 }
145
146 /**
147 * Get the result data array
148 */
149 public function & getResultData() {
150 return $this->getResult()->getData();
151 }
152
153 /**
154 * Set warning section for this module. Users should monitor this section to
155 * notice any changes in API.
156 */
157 public function setWarning($warning) {
158 $msg = array();
159 ApiResult :: setContent($msg, $warning);
160 $this->getResult()->addValue('warnings', $this->getModuleName(), $msg);
161 }
162
163 /**
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.
167 */
168 public function getCustomPrinter() {
169 return null;
170 }
171
172 /**
173 * Generates help message for this module, or false if there is no description
174 */
175 public function makeHelpMsg() {
176
177 static $lnPrfx = "\n ";
178
179 $msg = $this->getDescription();
180
181 if ($msg !== false) {
182
183 if (!is_array($msg))
184 $msg = array (
185 $msg
186 );
187 $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
188
189 if ($this->mustBePosted())
190 $msg .= "\nThis module only accepts POST requests.\n";
191
192 // Parameters
193 $paramsMsg = $this->makeHelpMsgParameters();
194 if ($paramsMsg !== false) {
195 $msg .= "Parameters:\n$paramsMsg";
196 }
197
198 // Examples
199 $examples = $this->getExamples();
200 if ($examples !== false) {
201 if (!is_array($examples))
202 $examples = array (
203 $examples
204 );
205 $msg .= 'Example' . (count($examples) > 1 ? 's' : '') . ":\n ";
206 $msg .= implode($lnPrfx, $examples) . "\n";
207 }
208
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';
213
214 if (is_array($versions)) {
215 foreach ($versions as &$v)
216 $v = eregi_replace($pattern, $replacement, $v);
217 $versions = implode("\n ", $versions);
218 }
219 else
220 $versions = eregi_replace($pattern, $replacement, $versions);
221
222 $msg .= "Version:\n $versions\n";
223 }
224 }
225
226 return $msg;
227 }
228
229 /**
230 * Generates the parameter descriptions for this module, to be displayed in the
231 * module's help.
232 */
233 public function makeHelpMsgParameters() {
234 $params = $this->getAllowedParams();
235 if ($params !== false) {
236
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);
244
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: ';
251
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]}";
280
281 $desc .= $paramPrefix . $intRangeStr;
282 }
283 break;
284 }
285 }
286 }
287
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";
291
292 $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
293 }
294 return $msg;
295
296 } else
297 return false;
298 }
299
300 /**
301 * Returns the description string for this module
302 */
303 protected function getDescription() {
304 return false;
305 }
306
307 /**
308 * Returns usage examples for this module. Return null if no examples are available.
309 */
310 protected function getExamples() {
311 return false;
312 }
313
314 /**
315 * Returns an array of allowed parameters (keys) => default value for that parameter
316 */
317 protected function getAllowedParams() {
318 return false;
319 }
320
321 /**
322 * Returns the description string for the given parameter.
323 */
324 protected function getParamDescription() {
325 return false;
326 }
327
328 /**
329 * This method mangles parameter name based on the prefix supplied to the constructor.
330 * Override this method to change parameter name during runtime
331 */
332 public function encodeParamName($paramName) {
333 return $this->mModulePrefix . $paramName;
334 }
335
336 /**
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.
342 */
343 public function extractRequestParams($parseMaxLimit = true) {
344 $params = $this->getAllowedParams();
345 $results = array ();
346
347 foreach ($params as $paramName => $paramSettings)
348 $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings, $parseMaxLimit);
349
350 return $results;
351 }
352
353 /**
354 * Get a value for the given parameter
355 */
356 protected function getParameter($paramName) {
357 $params = $this->getAllowedParams();
358 $paramSettings = $params[$paramName];
359 return $this->getParameterFromSettings($paramName, $paramSettings);
360 }
361
362 /**
363 * Returns an array of the namespaces (by integer id) that exist on the
364 * wiki. Used primarily in help documentation.
365 */
366 public static function getValidNamespaces() {
367 static $mValidNamespaces = null;
368 if (is_null($mValidNamespaces)) {
369
370 global $wgContLang;
371 $mValidNamespaces = array ();
372 foreach (array_keys($wgContLang->getNamespaces()) as $ns) {
373 if ($ns >= 0)
374 $mValidNamespaces[] = $ns;
375 }
376 }
377 return $mValidNamespaces;
378 }
379
380 /**
381 * Using the settings determine the value for the given parameter
382 *
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?
386 */
387 protected function getParameterFromSettings($paramName, $paramSettings, $parseMaxLimit) {
388
389 // Some classes may decide to change parameter names
390 $encParamName = $this->encodeParamName($paramName);
391
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;
400
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
407 }
408 }
409
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'");
414 }
415
416 $value = $this->getMain()->getRequest()->getCheck($encParamName);
417 } else {
418 $value = $this->getMain()->getRequest()->getVal($encParamName, $default);
419
420 if (isset ($value) && $type == 'namespace')
421 $type = ApiBase :: getValidNamespaces();
422 }
423
424 if (isset ($value) && ($multi || is_array($type)))
425 $value = $this->parseMultiValue($encParamName, $value, $multi, is_array($type) ? $type : null);
426
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
437
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;
441
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);
446 }
447 }
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]);
460 }
461 }
462 else {
463 $value = intval($value);
464 $this->validateLimit($paramName, $value, $min, $paramSettings[self :: PARAM_MAX], $paramSettings[self :: PARAM_MAX2]);
465 }
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");
487 }
488 }
489
490 // There should never be any duplicate values in a list
491 if (is_array($value))
492 $value = array_unique($value);
493 }
494
495 return $value;
496 }
497
498 /**
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.
501 *
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)
507 */
508 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
509 if( trim($value) === "" )
510 return array();
511 $valuesList = explode('|', $value);
512 if (!$allowMultiple && count($valuesList) != 1) {
513 $possibleValues = is_array($allowedValues) ? "of '" . implode("', '", $allowedValues) . "'" : '';
514 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
515 }
516 if (is_array($allowedValues)) {
517 $unknownValues = array_diff($valuesList, $allowedValues);
518 if ($unknownValues) {
519 $this->dieUsage('Unrecognised value' . (count($unknownValues) > 1 ? "s" : "") . " for parameter '$valueName'", "unknown_$valueName");
520 }
521 }
522
523 return $allowMultiple ? $valuesList : $valuesList[0];
524 }
525
526 /**
527 * Validate the value against the minimum and user/bot maximum limits. Prints usage info on failure.
528 */
529 function validateLimit($paramName, $value, $min, $max, $botMax = null) {
530 if (!is_null($min) && $value < $min) {
531 $this->dieUsage($this->encodeParamName($paramName) . " may not be less than $min (set to $value)", $paramName);
532 }
533
534 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
535 if ($this->getMain()->isInternalMode())
536 return;
537
538 // Optimization: do not check user's bot status unless really needed -- skips db query
539 // assumes $botMax >= $max
540 if (!is_null($max) && $value > $max) {
541 if (!is_null($botMax) && $this->getMain()->canApiHighLimits()) {
542 if ($value > $botMax) {
543 $this->dieUsage($this->encodeParamName($paramName) . " may not be over $botMax (set to $value) for bots or sysops", $paramName);
544 }
545 } else {
546 $this->dieUsage($this->encodeParamName($paramName) . " may not be over $max (set to $value) for users", $paramName);
547 }
548 }
549 }
550
551 /**
552 * Call main module's error handler
553 */
554 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
555 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
556 }
557
558 /**
559 * Array that maps message keys to error messages. $1 and friends are replaced.
560 */
561 public static $messageMap = array(
562 // This one MUST be present, or dieUsageMsg() will recurse infinitely
563 'unknownerror' => array('code' => 'unknownerror', 'info' => "Unknown error: ``\$1''"),
564 'unknownerror-nocode' => array('code' => 'unknownerror', 'info' => 'Unknown error'),
565
566 // Messages from Title::getUserPermissionsErrors()
567 'ns-specialprotected' => array('code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited"),
568 'protectedinterface' => array('code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages"),
569 'namespaceprotected' => array('code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the ``\$1'' namespace"),
570 'customcssjsprotected' => array('code' => 'customcssjsprotected', 'info' => "You're not allowed to edit custom CSS and JavaScript pages"),
571 'cascadeprotected' => array('code' => 'cascadeprotected', 'info' =>"The page you're trying to edit is protected because it's included in a cascade-protected page"),
572 'protectedpagetext' => array('code' => 'protectedpage', 'info' => "The ``\$1'' right is required to edit this page"),
573 'protect-cantedit' => array('code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it"),
574 'badaccess-group0' => array('code' => 'permissiondenied', 'info' => "Permission denied"), // Generic permission denied message
575 'badaccess-group1' => array('code' => 'permissiondenied', 'info' => "Permission denied"), // Can't use the parameter 'cause it's wikilinked
576 'badaccess-group2' => array('code' => 'permissiondenied', 'info' => "Permission denied"),
577 'badaccess-groups' => array('code' => 'permissiondenied', 'info' => "Permission denied"),
578 'titleprotected' => array('code' => 'protectedtitle', 'info' => "This title has been protected from creation"),
579 'nocreate-loggedin' => array('code' => 'cantcreate', 'info' => "You don't have permission to create new pages"),
580 'nocreatetext' => array('code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages"),
581 'movenologintext' => array('code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages"),
582 'movenotallowed' => array('code' => 'cantmove', 'info' => "You don't have permission to move pages"),
583 'confirmedittext' => array('code' => 'confirmemail', 'info' => "You must confirm your e-mail address before you can edit"),
584 'blockedtext' => array('code' => 'blocked', 'info' => "You have been blocked from editing"),
585 'autoblockedtext' => array('code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"),
586
587 // Miscellaneous interface messages
588 'actionthrottledtext' => array('code' => 'ratelimited', 'info' => "You've exceeded your rate limit. Please wait some time and try again"),
589 'alreadyrolled' => array('code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back"),
590 'cantrollback' => array('code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author"),
591 'readonlytext' => array('code' => 'readonly', 'info' => "The wiki is currently in read-only mode"),
592 'sessionfailure' => array('code' => 'badtoken', 'info' => "Invalid token"),
593 'cannotdelete' => array('code' => 'cantdelete', 'info' => "Couldn't delete ``\$1''. Maybe it was deleted already by someone else"),
594 'notanarticle' => array('code' => 'missingtitle', 'info' => "The page you requested doesn't exist"),
595 'selfmove' => array('code' => 'selfmove', 'info' => "Can't move a page to itself"),
596 'immobile_namespace' => array('code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving"),
597 'articleexists' => array('code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article"),
598 'protectedpage' => array('code' => 'protectedpage', 'info' => "You don't have permission to perform this move"),
599 'hookaborted' => array('code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook"),
600 'cantmove-titleprotected' => array('code' => 'protectedtitle', 'info' => "The destination article has been protected from creation"),
601 // 'badarticleerror' => shouldn't happen
602 // 'badtitletext' => shouldn't happen
603 'ip_range_invalid' => array('code' => 'invalidrange', 'info' => "Invalid IP range"),
604 'range_block_disabled' => array('code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled"),
605 'nosuchusershort' => array('code' => 'nosuchuser', 'info' => "The user you specified doesn't exist"),
606 'badipaddress' => array('code' => 'invalidip', 'info' => "Invalid IP address specified"),
607 'ipb_expiry_invalid' => array('code' => 'invalidexpiry', 'info' => "Invalid expiry time"),
608 'ipb_already_blocked' => array('code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked"),
609 '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."),
610 'ipb_cant_unblock' => array('code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already"),
611
612 // API-specific messages
613 'missingparam' => array('code' => 'no$1', 'info' => "The \$1 parameter must be set"),
614 'invalidtitle' => array('code' => 'invalidtitle', 'info' => "Bad title ``\$1''"),
615 'invaliduser' => array('code' => 'invaliduser', 'info' => "Invalid username ``\$1''"),
616 'invalidexpiry' => array('code' => 'invalidexpiry', 'info' => "Invalid expiry time"),
617 'pastexpiry' => array('code' => 'pastexpiry', 'info' => "Expiry time is in the past"),
618 'create-titleexists' => array('code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'"),
619 'missingtitle-createonly' => array('code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'"),
620 'cantblock' => array('code' => 'cantblock', 'info' => "You don't have permission to block users"),
621 'canthide' => array('code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log"),
622 'cantblock-email' => array('code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending e-mail through the wiki"),
623 'unblock-notarget' => array('code' => 'notarget', 'info' => "Either the id or the user parameter must be set"),
624 'unblock-idanduser' => array('code' => 'idanduser', 'info' => "The id and user parameters can\'t be used together"),
625 'cantunblock' => array('code' => 'permissiondenied', 'info' => "You don't have permission to unblock users"),
626 'cannotundelete' => array('code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"),
627 'permdenied-undelete' => array('code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions"),
628 'createonly-exists' => array('code' => 'articleexists', 'info' => "The article you tried to create has been created already"),
629 );
630
631 /**
632 * Output the error message related to a certain array
633 * @param array $error Element of a getUserPermissionsErrors()
634 */
635 public function dieUsageMsg($error) {
636 $key = array_shift($error);
637 if(isset(self::$messageMap[$key]))
638 $this->dieUsage(wfMsgReplaceArgs(self::$messageMap[$key]['info'], $error), wfMsgReplaceArgs(self::$messageMap[$key]['code'], $error));
639 // If the key isn't present, throw an "unknown error"
640 $this->dieUsageMsg(array('unknownerror', $key));
641 }
642
643 /**
644 * Internal code errors should be reported with this method
645 */
646 protected static function dieDebug($method, $message) {
647 wfDebugDieBacktrace("Internal error in $method: $message");
648 }
649
650 /**
651 * Indicates if API needs to check maxlag
652 */
653 public function shouldCheckMaxlag() {
654 return true;
655 }
656
657 /**
658 * Indicates if this module requires edit mode
659 */
660 public function isEditMode() {
661 return false;
662 }
663
664 /**
665 * Indicates whether this module must be called with a POST request
666 */
667 public function mustBePosted() {
668 return false;
669 }
670
671
672 /**
673 * Profiling: total module execution time
674 */
675 private $mTimeIn = 0, $mModuleTime = 0;
676
677 /**
678 * Start module profiling
679 */
680 public function profileIn() {
681 if ($this->mTimeIn !== 0)
682 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileOut()');
683 $this->mTimeIn = microtime(true);
684 wfProfileIn($this->getModuleProfileName());
685 }
686
687 /**
688 * End module profiling
689 */
690 public function profileOut() {
691 if ($this->mTimeIn === 0)
692 ApiBase :: dieDebug(__METHOD__, 'called without calling profileIn() first');
693 if ($this->mDBTimeIn !== 0)
694 ApiBase :: dieDebug(__METHOD__, 'must be called after database profiling is done with profileDBOut()');
695
696 $this->mModuleTime += microtime(true) - $this->mTimeIn;
697 $this->mTimeIn = 0;
698 wfProfileOut($this->getModuleProfileName());
699 }
700
701 /**
702 * When modules crash, sometimes it is needed to do a profileOut() regardless
703 * of the profiling state the module was in. This method does such cleanup.
704 */
705 public function safeProfileOut() {
706 if ($this->mTimeIn !== 0) {
707 if ($this->mDBTimeIn !== 0)
708 $this->profileDBOut();
709 $this->profileOut();
710 }
711 }
712
713 /**
714 * Total time the module was executed
715 */
716 public function getProfileTime() {
717 if ($this->mTimeIn !== 0)
718 ApiBase :: dieDebug(__METHOD__, 'called without calling profileOut() first');
719 return $this->mModuleTime;
720 }
721
722 /**
723 * Profiling: database execution time
724 */
725 private $mDBTimeIn = 0, $mDBTime = 0;
726
727 /**
728 * Start module profiling
729 */
730 public function profileDBIn() {
731 if ($this->mTimeIn === 0)
732 ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
733 if ($this->mDBTimeIn !== 0)
734 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileDBOut()');
735 $this->mDBTimeIn = microtime(true);
736 wfProfileIn($this->getModuleProfileName(true));
737 }
738
739 /**
740 * End database profiling
741 */
742 public function profileDBOut() {
743 if ($this->mTimeIn === 0)
744 ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
745 if ($this->mDBTimeIn === 0)
746 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBIn() first');
747
748 $time = microtime(true) - $this->mDBTimeIn;
749 $this->mDBTimeIn = 0;
750
751 $this->mDBTime += $time;
752 $this->getMain()->mDBTime += $time;
753 wfProfileOut($this->getModuleProfileName(true));
754 }
755
756 /**
757 * Total time the module used the database
758 */
759 public function getProfileDBTime() {
760 if ($this->mDBTimeIn !== 0)
761 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBOut() first');
762 return $this->mDBTime;
763 }
764
765 public static function debugPrint($value, $name = 'unknown', $backtrace = false) {
766 print "\n\n<pre><b>Debuging value '$name':</b>\n\n";
767 var_export($value);
768 if ($backtrace)
769 print "\n" . wfBacktrace();
770 print "\n</pre>\n";
771 }
772
773
774 /**
775 * Returns a String that identifies the version of this class.
776 */
777 public static function getBaseVersion() {
778 return __CLASS__ . ': $Id$';
779 }
780 }
781