Tweak/add some documentation as hints for some code analysis
[lhc/web/wiklou.git] / includes / api / ApiBase.php
1 <?php
2 /**
3 * API for MediaWiki 1.8+
4 *
5 * Created on Sep 5, 2006
6 *
7 * Copyright © 2006, 2010 Yuri Astrakhan <Firstname><Lastname>@gmail.com
8 *
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.
13 *
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.
18 *
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
23 *
24 * @file
25 */
26
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:
31 *
32 * Module parameters: Derived classes can define getAllowedParams() to specify
33 * which parameters to expect,h ow to parse and validate them.
34 *
35 * Profiling: various methods to allow keeping tabs on various tasks and their
36 * time costs
37 *
38 * Self-documentation: code to allow the API to document its own state
39 *
40 * @ingroup API
41 */
42 abstract class ApiBase {
43
44 // These constants allow modules to specify exactly how to treat incoming parameters.
45
46 const PARAM_DFLT = 0; // Default value of the parameter
47 const PARAM_ISMULTI = 1; // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
48 const PARAM_TYPE = 2; // Can be either a string type (e.g.: 'integer') or an array of allowed values
49 const PARAM_MAX = 3; // Max value allowed for a parameter. Only applies if TYPE='integer'
50 const PARAM_MAX2 = 4; // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
51 const PARAM_MIN = 5; // Lowest value allowed for a parameter. Only applies if TYPE='integer'
52 const PARAM_ALLOW_DUPLICATES = 6; // Boolean, do we allow the same value to be set more than once when ISMULTI=true
53 const PARAM_DEPRECATED = 7; // Boolean, is the parameter deprecated (will show a warning)
54 const PARAM_REQUIRED = 8; // Boolean, is the parameter required?
55
56 const LIMIT_BIG1 = 500; // Fast query, std user limit
57 const LIMIT_BIG2 = 5000; // Fast query, bot/sysop limit
58 const LIMIT_SML1 = 50; // Slow query, std user limit
59 const LIMIT_SML2 = 500; // Slow query, bot/sysop limit
60
61 private $mMainModule, $mModuleName, $mModulePrefix;
62 private $mParamCache = array();
63
64 /**
65 * Constructor
66 * @param $mainModule ApiMain object
67 * @param $moduleName string Name of this module
68 * @param $modulePrefix string Prefix to use for parameter names
69 */
70 public function __construct( $mainModule, $moduleName, $modulePrefix = '' ) {
71 $this->mMainModule = $mainModule;
72 $this->mModuleName = $moduleName;
73 $this->mModulePrefix = $modulePrefix;
74 }
75
76 /*****************************************************************************
77 * ABSTRACT METHODS *
78 *****************************************************************************/
79
80 /**
81 * Evaluates the parameters, performs the requested query, and sets up
82 * the result. Concrete implementations of ApiBase must override this
83 * method to provide whatever functionality their module offers.
84 * Implementations must not produce any output on their own and are not
85 * expected to handle any errors.
86 *
87 * The execute() method will be invoked directly by ApiMain immediately
88 * before the result of the module is output. Aside from the
89 * constructor, implementations should assume that no other methods
90 * will be called externally on the module before the result is
91 * processed.
92 *
93 * The result data should be stored in the ApiResult object available
94 * through getResult().
95 */
96 public abstract function execute();
97
98 /**
99 * Returns a string that identifies the version of the extending class.
100 * Typically includes the class name, the svn revision, timestamp, and
101 * last author. Usually done with SVN's Id keyword
102 * @return string
103 */
104 public abstract function getVersion();
105
106 /**
107 * Get the name of the module being executed by this instance
108 * @return string
109 */
110 public function getModuleName() {
111 return $this->mModuleName;
112 }
113
114 /**
115 * Get parameter prefix (usually two letters or an empty string).
116 * @return string
117 */
118 public function getModulePrefix() {
119 return $this->mModulePrefix;
120 }
121
122 /**
123 * Get the name of the module as shown in the profiler log
124 * @return string
125 */
126 public function getModuleProfileName( $db = false ) {
127 if ( $db ) {
128 return 'API:' . $this->mModuleName . '-DB';
129 } else {
130 return 'API:' . $this->mModuleName;
131 }
132 }
133
134 /**
135 * Get the main module
136 * @return ApiMain object
137 */
138 public function getMain() {
139 return $this->mMainModule;
140 }
141
142 /**
143 * Returns true if this module is the main module ($this === $this->mMainModule),
144 * false otherwise.
145 * @return bool
146 */
147 public function isMain() {
148 return $this === $this->mMainModule;
149 }
150
151 /**
152 * Get the result object
153 * @return ApiResult
154 */
155 public function getResult() {
156 // Main module has getResult() method overriden
157 // Safety - avoid infinite loop:
158 if ( $this->isMain() ) {
159 ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
160 }
161 return $this->getMain()->getResult();
162 }
163
164 /**
165 * Get the result data array (read-only)
166 * @return array
167 */
168 public function getResultData() {
169 return $this->getResult()->getData();
170 }
171
172 /**
173 * Set warning section for this module. Users should monitor this
174 * section to notice any changes in API. Multiple calls to this
175 * function will result in the warning messages being separated by
176 * newlines
177 * @param $warning string Warning message
178 */
179 public function setWarning( $warning ) {
180 $data = $this->getResult()->getData();
181 if ( isset( $data['warnings'][$this->getModuleName()] ) ) {
182 // Don't add duplicate warnings
183 $warn_regex = preg_quote( $warning, '/' );
184 if ( preg_match( "/{$warn_regex}(\\n|$)/", $data['warnings'][$this->getModuleName()]['*'] ) ) {
185 return;
186 }
187 $oldwarning = $data['warnings'][$this->getModuleName()]['*'];
188 // If there is a warning already, append it to the existing one
189 $warning = "$oldwarning\n$warning";
190 $this->getResult()->unsetValue( 'warnings', $this->getModuleName() );
191 }
192 $msg = array();
193 ApiResult::setContent( $msg, $warning );
194 $this->getResult()->disableSizeCheck();
195 $this->getResult()->addValue( 'warnings', $this->getModuleName(), $msg );
196 $this->getResult()->enableSizeCheck();
197 }
198
199 /**
200 * If the module may only be used with a certain format module,
201 * it should override this method to return an instance of that formatter.
202 * A value of null means the default format will be used.
203 * @return mixed instance of a derived class of ApiFormatBase, or null
204 */
205 public function getCustomPrinter() {
206 return null;
207 }
208
209 /**
210 * Generates help message for this module, or false if there is no description
211 * @return mixed string or false
212 */
213 public function makeHelpMsg() {
214 static $lnPrfx = "\n ";
215
216 $msg = $this->getDescription();
217
218 if ( $msg !== false ) {
219
220 if ( !is_array( $msg ) ) {
221 $msg = array(
222 $msg
223 );
224 }
225 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
226
227 if ( $this->isReadMode() ) {
228 $msg .= "\nThis module requires read rights";
229 }
230 if ( $this->isWriteMode() ) {
231 $msg .= "\nThis module requires write rights";
232 }
233 if ( $this->mustBePosted() ) {
234 $msg .= "\nThis module only accepts POST requests";
235 }
236 if ( $this->isReadMode() || $this->isWriteMode() ||
237 $this->mustBePosted() )
238 {
239 $msg .= "\n";
240 }
241
242 // Parameters
243 $paramsMsg = $this->makeHelpMsgParameters();
244 if ( $paramsMsg !== false ) {
245 $msg .= "Parameters:\n$paramsMsg";
246 }
247
248 // Examples
249 $examples = $this->getExamples();
250 if ( $examples !== false ) {
251 if ( !is_array( $examples ) ) {
252 $examples = array(
253 $examples
254 );
255 }
256
257 if ( count( $examples ) > 0 ) {
258 $msg .= 'Example' . ( count( $examples ) > 1 ? 's' : '' ) . ":\n ";
259 $msg .= implode( $lnPrfx, $examples ) . "\n";
260 }
261 }
262
263 if ( $this->getMain()->getShowVersions() ) {
264 $versions = $this->getVersion();
265 $pattern = '/(\$.*) ([0-9a-z_]+\.php) (.*\$)/i';
266 $callback = array( $this, 'makeHelpMsg_callback' );
267
268 if ( is_array( $versions ) ) {
269 foreach ( $versions as &$v ) {
270 $v = preg_replace_callback( $pattern, $callback, $v );
271 }
272 $versions = implode( "\n ", $versions );
273 } else {
274 $versions = preg_replace_callback( $pattern, $callback, $versions );
275 }
276
277 $msg .= "Version:\n $versions\n";
278 }
279 }
280
281 return $msg;
282 }
283
284 /**
285 * Generates the parameter descriptions for this module, to be displayed in the
286 * module's help.
287 * @return string
288 */
289 public function makeHelpMsgParameters() {
290 $params = $this->getFinalParams();
291 if ( $params ) {
292
293 $paramsDescription = $this->getFinalParamDescription();
294 $msg = '';
295 $paramPrefix = "\n" . str_repeat( ' ', 19 );
296 foreach ( $params as $paramName => $paramSettings ) {
297 $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
298 if ( is_array( $desc ) ) {
299 $desc = implode( $paramPrefix, $desc );
300 }
301
302 if ( !is_array( $paramSettings ) ) {
303 $paramSettings = array(
304 self::PARAM_DFLT => $paramSettings,
305 );
306 }
307
308 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] ) ?
309 $paramSettings[self::PARAM_DEPRECATED] : false;
310 if ( $deprecated ) {
311 $desc = "DEPRECATED! $desc";
312 }
313
314 $required = isset( $paramSettings[self::PARAM_REQUIRED] ) ?
315 $paramSettings[self::PARAM_REQUIRED] : false;
316 if ( $required ) {
317 $desc .= $paramPrefix . "This parameter is required";
318 }
319
320 $type = isset( $paramSettings[self::PARAM_TYPE] ) ? $paramSettings[self::PARAM_TYPE] : null;
321 if ( isset( $type ) ) {
322 if ( isset( $paramSettings[self::PARAM_ISMULTI] ) ) {
323 $prompt = 'Values (separate with \'|\'): ';
324 } else {
325 $prompt = 'One value: ';
326 }
327
328 if ( is_array( $type ) ) {
329 $choices = array();
330 $nothingPrompt = false;
331 foreach ( $type as $t ) {
332 if ( $t === '' ) {
333 $nothingPrompt = 'Can be empty, or ';
334 } else {
335 $choices[] = $t;
336 }
337 }
338 $desc .= $paramPrefix . $nothingPrompt . $prompt . implode( ', ', $choices );
339 } else {
340 switch ( $type ) {
341 case 'namespace':
342 // Special handling because namespaces are type-limited, yet they are not given
343 $desc .= $paramPrefix . $prompt . implode( ', ', MWNamespace::getValidNamespaces() );
344 break;
345 case 'limit':
346 $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]}";
347 if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
348 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
349 }
350 $desc .= ' allowed';
351 break;
352 case 'integer':
353 $hasMin = isset( $paramSettings[self::PARAM_MIN] );
354 $hasMax = isset( $paramSettings[self::PARAM_MAX] );
355 if ( $hasMin || $hasMax ) {
356 if ( !$hasMax ) {
357 $intRangeStr = "The value must be no less than {$paramSettings[self::PARAM_MIN]}";
358 } elseif ( !$hasMin ) {
359 $intRangeStr = "The value must be no more than {$paramSettings[self::PARAM_MAX]}";
360 } else {
361 $intRangeStr = "The value must be between {$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
362 }
363
364 $desc .= $paramPrefix . $intRangeStr;
365 }
366 break;
367 }
368 }
369 }
370
371 $default = is_array( $paramSettings ) ? ( isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null ) : $paramSettings;
372 if ( !is_null( $default ) && $default !== false ) {
373 $desc .= $paramPrefix . "Default: $default";
374 }
375
376 $msg .= sprintf( " %-14s - %s\n", $this->encodeParamName( $paramName ), $desc );
377 }
378 return $msg;
379
380 } else {
381 return false;
382 }
383 }
384
385 /**
386 * Callback for preg_replace_callback() call in makeHelpMsg().
387 * Replaces a source file name with a link to ViewVC
388 */
389 public function makeHelpMsg_callback( $matches ) {
390 global $wgAutoloadClasses, $wgAutoloadLocalClasses;
391 if ( isset( $wgAutoloadLocalClasses[get_class( $this )] ) ) {
392 $file = $wgAutoloadLocalClasses[get_class( $this )];
393 } elseif ( isset( $wgAutoloadClasses[get_class( $this )] ) ) {
394 $file = $wgAutoloadClasses[get_class( $this )];
395 }
396
397 // Do some guesswork here
398 $path = strstr( $file, 'includes/api/' );
399 if ( $path === false ) {
400 $path = strstr( $file, 'extensions/' );
401 } else {
402 $path = 'phase3/' . $path;
403 }
404
405 // Get the filename from $matches[2] instead of $file
406 // If they're not the same file, they're assumed to be in the
407 // same directory
408 // This is necessary to make stuff like ApiMain::getVersion()
409 // returning the version string for ApiBase work
410 if ( $path ) {
411 return "{$matches[0]}\n http://svn.wikimedia.org/" .
412 "viewvc/mediawiki/trunk/" . dirname( $path ) .
413 "/{$matches[2]}";
414 }
415 return $matches[0];
416 }
417
418 /**
419 * Returns the description string for this module
420 * @return mixed string or array of strings
421 */
422 protected function getDescription() {
423 return false;
424 }
425
426 /**
427 * Returns usage examples for this module. Return null if no examples are available.
428 * @return mixed string or array of strings
429 */
430 protected function getExamples() {
431 return false;
432 }
433
434 /**
435 * Returns an array of allowed parameters (parameter name) => (default
436 * value) or (parameter name) => (array with PARAM_* constants as keys)
437 * Don't call this function directly: use getFinalParams() to allow
438 * hooks to modify parameters as needed.
439 * @return array
440 */
441 protected function getAllowedParams() {
442 return false;
443 }
444
445 /**
446 * Returns an array of parameter descriptions.
447 * Don't call this functon directly: use getFinalParamDescription() to
448 * allow hooks to modify descriptions as needed.
449 * @return array
450 */
451 protected function getParamDescription() {
452 return false;
453 }
454
455 /**
456 * Get final list of parameters, after hooks have had a chance to
457 * tweak it as needed.
458 * @return array
459 */
460 public function getFinalParams() {
461 $params = $this->getAllowedParams();
462 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params ) );
463 return $params;
464 }
465
466 /**
467 * Get final description, after hooks have had a chance to tweak it as
468 * needed.
469 * @return array
470 */
471 public function getFinalParamDescription() {
472 $desc = $this->getParamDescription();
473 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
474 return $desc;
475 }
476
477 /**
478 * This method mangles parameter name based on the prefix supplied to the constructor.
479 * Override this method to change parameter name during runtime
480 * @param $paramName string Parameter name
481 * @return string Prefixed parameter name
482 */
483 public function encodeParamName( $paramName ) {
484 return $this->mModulePrefix . $paramName;
485 }
486
487 /**
488 * Using getAllowedParams(), this function makes an array of the values
489 * provided by the user, with key being the name of the variable, and
490 * value - validated value from user or default. limits will not be
491 * parsed if $parseLimit is set to false; use this when the max
492 * limit is not definitive yet, e.g. when getting revisions.
493 * @param $parseLimit Boolean: true by default
494 * @return array
495 */
496 public function extractRequestParams( $parseLimit = true ) {
497 // Cache parameters, for performance and to avoid bug 24564.
498 if ( !isset( $this->mParamCache[$parseLimit] ) ) {
499 $params = $this->getFinalParams();
500 $results = array();
501
502 if ( $params ) { // getFinalParams() can return false
503 foreach ( $params as $paramName => $paramSettings ) {
504 $results[$paramName] = $this->getParameterFromSettings(
505 $paramName, $paramSettings, $parseLimit );
506 }
507 }
508 $this->mParamCache[$parseLimit] = $results;
509 }
510 return $this->mParamCache[$parseLimit];
511 }
512
513 /**
514 * Get a value for the given parameter
515 * @param $paramName string Parameter name
516 * @param $parseLimit bool see extractRequestParams()
517 * @return mixed Parameter value
518 */
519 protected function getParameter( $paramName, $parseLimit = true ) {
520 $params = $this->getFinalParams();
521 $paramSettings = $params[$paramName];
522 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
523 }
524
525 /**
526 * Die if none or more than one of a certain set of parameters is set and not false.
527 * @param $params array of parameter names
528 */
529 public function requireOnlyOneParameter( $params ) {
530 $required = func_get_args();
531 array_shift( $required );
532
533 $intersection = array_intersect( array_keys( array_filter( $params,
534 create_function( '$x', 'return !is_null($x) && $x !== false;' )
535 ) ), $required );
536 if ( count( $intersection ) > 1 ) {
537 $this->dieUsage( 'The parameters ' . implode( ', ', $intersection ) . ' can not be used together', 'invalidparammix' );
538 } elseif ( count( $intersection ) == 0 ) {
539 $this->dieUsage( 'One of the parameters ' . implode( ', ', $required ) . ' is required', 'missingparam' );
540 }
541 }
542
543 /**
544 * @deprecated use MWNamespace::getValidNamespaces()
545 */
546 public static function getValidNamespaces() {
547 return MWNamespace::getValidNamespaces();
548 }
549
550 /**
551 * Return true if we're to watch the page, false if not, null if no change.
552 * @param $watchlist String Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
553 * @param $titleObj Title the page under consideration
554 * @param $userOption String The user option to consider when $watchlist=preferences.
555 * If not set will magically default to either watchdefault or watchcreations
556 * @returns mixed
557 */
558 protected function getWatchlistValue ( $watchlist, $titleObj, $userOption = null ) {
559 global $wgUser;
560 switch ( $watchlist ) {
561 case 'watch':
562 return true;
563
564 case 'unwatch':
565 return false;
566
567 case 'preferences':
568 # If the user is already watching, don't bother checking
569 if ( $titleObj->userIsWatching() ) {
570 return null;
571 }
572 # If no user option was passed, use watchdefault or watchcreation
573 if ( is_null( $userOption ) ) {
574 $userOption = $titleObj->exists()
575 ? 'watchdefault' : 'watchcreations';
576 }
577 # If the corresponding user option is true, watch, else no change
578 return $wgUser->getOption( $userOption ) ? true : null;
579
580 case 'nochange':
581 return null;
582
583 default:
584 return null;
585 }
586 }
587
588 /**
589 * Set a watch (or unwatch) based the based on a watchlist parameter.
590 * @param $watch String Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
591 * @param $titleObj Title the article's title to change
592 * @param $userOption String The user option to consider when $watch=preferences
593 */
594 protected function setWatch ( $watch, $titleObj, $userOption = null ) {
595 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
596 if ( $value === null ) {
597 return;
598 }
599
600 $articleObj = new Article( $titleObj );
601 if ( $value ) {
602 $articleObj->doWatch();
603 } else {
604 $articleObj->doUnwatch();
605 }
606 }
607
608 /**
609 * Using the settings determine the value for the given parameter
610 *
611 * @param $paramName String: parameter name
612 * @param $paramSettings Mixed: default value or an array of settings
613 * using PARAM_* constants.
614 * @param $parseLimit Boolean: parse limit?
615 * @return mixed Parameter value
616 */
617 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
618 // Some classes may decide to change parameter names
619 $encParamName = $this->encodeParamName( $paramName );
620
621 if ( !is_array( $paramSettings ) ) {
622 $default = $paramSettings;
623 $multi = false;
624 $type = gettype( $paramSettings );
625 $dupes = false;
626 $deprecated = false;
627 $required = false;
628 } else {
629 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
630 $multi = isset( $paramSettings[self::PARAM_ISMULTI] ) ? $paramSettings[self::PARAM_ISMULTI] : false;
631 $type = isset( $paramSettings[self::PARAM_TYPE] ) ? $paramSettings[self::PARAM_TYPE] : null;
632 $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] ) ? $paramSettings[self::PARAM_ALLOW_DUPLICATES] : false;
633 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] ) ? $paramSettings[self::PARAM_DEPRECATED] : false;
634 $required = isset( $paramSettings[self::PARAM_REQUIRED] ) ? $paramSettings[self::PARAM_REQUIRED] : false;
635
636 // When type is not given, and no choices, the type is the same as $default
637 if ( !isset( $type ) ) {
638 if ( isset( $default ) ) {
639 $type = gettype( $default );
640 } else {
641 $type = 'NULL'; // allow everything
642 }
643 }
644 }
645
646 if ( $type == 'boolean' ) {
647 if ( isset( $default ) && $default !== false ) {
648 // Having a default value of anything other than 'false' is pointless
649 ApiBase::dieDebug( __METHOD__, "Boolean param $encParamName's default is set to '$default'" );
650 }
651
652 $value = $this->getMain()->getRequest()->getCheck( $encParamName );
653 } else {
654 $value = $this->getMain()->getRequest()->getVal( $encParamName, $default );
655
656 if ( isset( $value ) && $type == 'namespace' ) {
657 $type = MWNamespace::getValidNamespaces();
658 }
659 }
660
661 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
662 $value = $this->parseMultiValue( $encParamName, $value, $multi, is_array( $type ) ? $type : null );
663 }
664
665 // More validation only when choices were not given
666 // choices were validated in parseMultiValue()
667 if ( isset( $value ) ) {
668 if ( !is_array( $type ) ) {
669 switch ( $type ) {
670 case 'NULL': // nothing to do
671 break;
672 case 'string':
673 if ( $required && $value === '' ) {
674 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
675 }
676
677 break;
678 case 'integer': // Force everything using intval() and optionally validate limits
679
680 $value = is_array( $value ) ? array_map( 'intval', $value ) : intval( $value );
681 $min = isset ( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
682 $max = isset ( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
683
684 if ( !is_null( $min ) || !is_null( $max ) ) {
685 $values = is_array( $value ) ? $value : array( $value );
686 foreach ( $values as &$v ) {
687 $this->validateLimit( $paramName, $v, $min, $max );
688 }
689 }
690 break;
691 case 'limit':
692 if ( !$parseLimit ) {
693 // Don't do any validation whatsoever
694 break;
695 }
696 if ( !isset( $paramSettings[self::PARAM_MAX] ) || !isset( $paramSettings[self::PARAM_MAX2] ) ) {
697 ApiBase::dieDebug( __METHOD__, "MAX1 or MAX2 are not defined for the limit $encParamName" );
698 }
699 if ( $multi ) {
700 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
701 }
702 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
703 if ( $value == 'max' ) {
704 $value = $this->getMain()->canApiHighLimits() ? $paramSettings[self::PARAM_MAX2] : $paramSettings[self::PARAM_MAX];
705 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
706 } else {
707 $value = intval( $value );
708 $this->validateLimit( $paramName, $value, $min, $paramSettings[self::PARAM_MAX], $paramSettings[self::PARAM_MAX2] );
709 }
710 break;
711 case 'boolean':
712 if ( $multi ) {
713 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
714 }
715 break;
716 case 'timestamp':
717 if ( $multi ) {
718 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
719 }
720 $value = wfTimestamp( TS_UNIX, $value );
721 if ( $value === 0 ) {
722 $this->dieUsage( "Invalid value '$value' for timestamp parameter $encParamName", "badtimestamp_{$encParamName}" );
723 }
724 $value = wfTimestamp( TS_MW, $value );
725 break;
726 case 'user':
727 if ( !is_array( $value ) ) {
728 $value = array( $value );
729 }
730
731 foreach ( $value as $key => $val ) {
732 $title = Title::makeTitleSafe( NS_USER, $val );
733 if ( is_null( $title ) ) {
734 $this->dieUsage( "Invalid value for user parameter $encParamName", "baduser_{$encParamName}" );
735 }
736 $value[$key] = $title->getText();
737 }
738
739 if ( !$multi ) {
740 $value = $value[0];
741 }
742 break;
743 default:
744 ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
745 }
746 }
747
748 // Throw out duplicates if requested
749 if ( is_array( $value ) && !$dupes ) {
750 $value = array_unique( $value );
751 }
752
753 // Set a warning if a deprecated parameter has been passed
754 if ( $deprecated && $value !== false ) {
755 $this->setWarning( "The $encParamName parameter has been deprecated." );
756 }
757 } else if ( $required ) {
758 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
759 }
760
761 return $value;
762 }
763
764 /**
765 * Return an array of values that were given in a 'a|b|c' notation,
766 * after it optionally validates them against the list allowed values.
767 *
768 * @param $valueName string The name of the parameter (for error
769 * reporting)
770 * @param $value mixed The value being parsed
771 * @param $allowMultiple bool Can $value contain more than one value
772 * separated by '|'?
773 * @param $allowedValues mixed An array of values to check against. If
774 * null, all values are accepted.
775 * @return mixed (allowMultiple ? an_array_of_values : a_single_value)
776 */
777 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
778 if ( trim( $value ) === '' && $allowMultiple ) {
779 return array();
780 }
781
782 // This is a bit awkward, but we want to avoid calling canApiHighLimits() because it unstubs $wgUser
783 $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 );
784 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits() ?
785 self::LIMIT_SML2 : self::LIMIT_SML1;
786
787 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
788 $this->setWarning( "Too many values supplied for parameter '$valueName': the limit is $sizeLimit" );
789 }
790
791 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
792 $possibleValues = is_array( $allowedValues ) ? "of '" . implode( "', '", $allowedValues ) . "'" : '';
793 $this->dieUsage( "Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName" );
794 }
795
796 if ( is_array( $allowedValues ) ) {
797 // Check for unknown values
798 $unknown = array_diff( $valuesList, $allowedValues );
799 if ( count( $unknown ) ) {
800 if ( $allowMultiple ) {
801 $s = count( $unknown ) > 1 ? 's' : '';
802 $vals = implode( ", ", $unknown );
803 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
804 } else {
805 $this->dieUsage( "Unrecognized value for parameter '$valueName': {$valuesList[0]}", "unknown_$valueName" );
806 }
807 }
808 // Now throw them out
809 $valuesList = array_intersect( $valuesList, $allowedValues );
810 }
811
812 return $allowMultiple ? $valuesList : $valuesList[0];
813 }
814
815 /**
816 * Validate the value against the minimum and user/bot maximum limits.
817 * Prints usage info on failure.
818 * @param $paramName string Parameter name
819 * @param $value int Parameter value
820 * @param $min int Minimum value
821 * @param $max int Maximum value for users
822 * @param $botMax int Maximum value for sysops/bots
823 */
824 function validateLimit( $paramName, &$value, $min, $max, $botMax = null ) {
825 if ( !is_null( $min ) && $value < $min ) {
826 $this->setWarning( $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)" );
827 $value = $min;
828 }
829
830 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
831 if ( $this->getMain()->isInternalMode() ) {
832 return;
833 }
834
835 // Optimization: do not check user's bot status unless really needed -- skips db query
836 // assumes $botMax >= $max
837 if ( !is_null( $max ) && $value > $max ) {
838 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
839 if ( $value > $botMax ) {
840 $this->setWarning( $this->encodeParamName( $paramName ) . " may not be over $botMax (set to $value) for bots or sysops" );
841 $value = $botMax;
842 }
843 } else {
844 $this->setWarning( $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users" );
845 $value = $max;
846 }
847 }
848 }
849
850 /**
851 * Truncate an array to a certain length.
852 * @param $arr array Array to truncate
853 * @param $limit int Maximum length
854 * @return bool True if the array was truncated, false otherwise
855 */
856 public static function truncateArray( &$arr, $limit ) {
857 $modified = false;
858 while ( count( $arr ) > $limit ) {
859 array_pop( $arr );
860 $modified = true;
861 }
862 return $modified;
863 }
864
865 /**
866 * Throw a UsageException, which will (if uncaught) call the main module's
867 * error handler and die with an error message.
868 *
869 * @param $description string One-line human-readable description of the
870 * error condition, e.g., "The API requires a valid action parameter"
871 * @param $errorCode string Brief, arbitrary, stable string to allow easy
872 * automated identification of the error, e.g., 'unknown_action'
873 * @param $httpRespCode int HTTP response code
874 * @param $extradata array Data to add to the <error> element; array in ApiResult format
875 */
876 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
877 wfProfileClose();
878 throw new UsageException( $description, $this->encodeParamName( $errorCode ), $httpRespCode, $extradata );
879 }
880
881 /**
882 * Array that maps message keys to error messages. $1 and friends are replaced.
883 */
884 public static $messageMap = array(
885 // This one MUST be present, or dieUsageMsg() will recurse infinitely
886 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: ``\$1''" ),
887 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
888
889 // Messages from Title::getUserPermissionsErrors()
890 'ns-specialprotected' => array( 'code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited" ),
891 'protectedinterface' => array( 'code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages" ),
892 'namespaceprotected' => array( 'code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the ``\$1'' namespace" ),
893 'customcssjsprotected' => array( 'code' => 'customcssjsprotected', 'info' => "You're not allowed to edit custom CSS and JavaScript pages" ),
894 'cascadeprotected' => array( 'code' => 'cascadeprotected', 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page" ),
895 'protectedpagetext' => array( 'code' => 'protectedpage', 'info' => "The ``\$1'' right is required to edit this page" ),
896 'protect-cantedit' => array( 'code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it" ),
897 'badaccess-group0' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ), // Generic permission denied message
898 'badaccess-groups' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ),
899 'titleprotected' => array( 'code' => 'protectedtitle', 'info' => "This title has been protected from creation" ),
900 'nocreate-loggedin' => array( 'code' => 'cantcreate', 'info' => "You don't have permission to create new pages" ),
901 'nocreatetext' => array( 'code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages" ),
902 'movenologintext' => array( 'code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages" ),
903 'movenotallowed' => array( 'code' => 'cantmove', 'info' => "You don't have permission to move pages" ),
904 'confirmedittext' => array( 'code' => 'confirmemail', 'info' => "You must confirm your e-mail address before you can edit" ),
905 'blockedtext' => array( 'code' => 'blocked', 'info' => "You have been blocked from editing" ),
906 'autoblockedtext' => array( 'code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user" ),
907
908 // Miscellaneous interface messages
909 'actionthrottledtext' => array( 'code' => 'ratelimited', 'info' => "You've exceeded your rate limit. Please wait some time and try again" ),
910 'alreadyrolled' => array( 'code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back" ),
911 'cantrollback' => array( 'code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author" ),
912 'readonlytext' => array( 'code' => 'readonly', 'info' => "The wiki is currently in read-only mode" ),
913 'sessionfailure' => array( 'code' => 'badtoken', 'info' => "Invalid token" ),
914 'cannotdelete' => array( 'code' => 'cantdelete', 'info' => "Couldn't delete ``\$1''. Maybe it was deleted already by someone else" ),
915 'notanarticle' => array( 'code' => 'missingtitle', 'info' => "The page you requested doesn't exist" ),
916 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself" ),
917 'immobile_namespace' => array( 'code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving" ),
918 'articleexists' => array( 'code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article" ),
919 'protectedpage' => array( 'code' => 'protectedpage', 'info' => "You don't have permission to perform this move" ),
920 'hookaborted' => array( 'code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook" ),
921 'cantmove-titleprotected' => array( 'code' => 'protectedtitle', 'info' => "The destination article has been protected from creation" ),
922 'imagenocrossnamespace' => array( 'code' => 'nonfilenamespace', 'info' => "Can't move a file to a non-file namespace" ),
923 'imagetypemismatch' => array( 'code' => 'filetypemismatch', 'info' => "The new file extension doesn't match its type" ),
924 // 'badarticleerror' => shouldn't happen
925 // 'badtitletext' => shouldn't happen
926 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
927 'range_block_disabled' => array( 'code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled" ),
928 'nosuchusershort' => array( 'code' => 'nosuchuser', 'info' => "The user you specified doesn't exist" ),
929 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
930 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
931 'ipb_already_blocked' => array( 'code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked" ),
932 '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." ),
933 'ipb_cant_unblock' => array( 'code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already" ),
934 'mailnologin' => array( 'code' => 'cantsend', 'info' => "You are not logged in, you do not have a confirmed e-mail address, or you are not allowed to send e-mail to other users, so you cannot send e-mail" ),
935 'ipbblocked' => array( 'code' => 'ipbblocked', 'info' => 'You cannot block or unblock users while you are yourself blocked' ),
936 'ipbnounblockself' => array( 'code' => 'ipbnounblockself', 'info' => 'You are not allowed to unblock yourself' ),
937 'usermaildisabled' => array( 'code' => 'usermaildisabled', 'info' => "User email has been disabled" ),
938 'blockedemailuser' => array( 'code' => 'blockedfrommail', 'info' => "You have been blocked from sending e-mail" ),
939 'notarget' => array( 'code' => 'notarget', 'info' => "You have not specified a valid target for this action" ),
940 'noemail' => array( 'code' => 'noemail', 'info' => "The user has not specified a valid e-mail address, or has chosen not to receive e-mail from other users" ),
941 'rcpatroldisabled' => array( 'code' => 'patroldisabled', 'info' => "Patrolling is disabled on this wiki" ),
942 'markedaspatrollederror-noautopatrol' => array( 'code' => 'noautopatrol', 'info' => "You don't have permission to patrol your own changes" ),
943 'delete-toobig' => array( 'code' => 'bigdelete', 'info' => "You can't delete this page because it has more than \$1 revisions" ),
944 'movenotallowedfile' => array( 'code' => 'cantmovefile', 'info' => "You don't have permission to move files" ),
945 'userrights-no-interwiki' => array( 'code' => 'nointerwikiuserrights', 'info' => "You don't have permission to change user rights on other wikis" ),
946 'userrights-nodatabase' => array( 'code' => 'nosuchdatabase', 'info' => "Database ``\$1'' does not exist or is not local" ),
947 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username ``\$1''" ),
948 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username ``\$1''" ),
949 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
950
951 // API-specific messages
952 'readrequired' => array( 'code' => 'readapidenied', 'info' => "You need read permission to use this module" ),
953 'writedisabled' => array( 'code' => 'noapiwrite', '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" ),
954 'writerequired' => array( 'code' => 'writeapidenied', 'info' => "You're not allowed to edit this wiki through the API" ),
955 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
956 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title ``\$1''" ),
957 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
958 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
959 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User ``\$1'' doesn't exist" ),
960 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username ``\$1''" ),
961 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time ``\$1''" ),
962 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time ``\$1'' is in the past" ),
963 'create-titleexists' => array( 'code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'" ),
964 'missingtitle-createonly' => array( 'code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'" ),
965 'cantblock' => array( 'code' => 'cantblock', 'info' => "You don't have permission to block users" ),
966 'canthide' => array( 'code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log" ),
967 'cantblock-email' => array( 'code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending e-mail through the wiki" ),
968 'unblock-notarget' => array( 'code' => 'notarget', 'info' => "Either the id or the user parameter must be set" ),
969 'unblock-idanduser' => array( 'code' => 'idanduser', 'info' => "The id and user parameters can't be used together" ),
970 'cantunblock' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to unblock users" ),
971 'cannotundelete' => array( 'code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already" ),
972 'permdenied-undelete' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions" ),
973 'createonly-exists' => array( 'code' => 'articleexists', 'info' => "The article you tried to create has been created already" ),
974 'nocreate-missing' => array( 'code' => 'missingtitle', 'info' => "The article you tried to edit doesn't exist" ),
975 'nosuchrcid' => array( 'code' => 'nosuchrcid', 'info' => "There is no change with rcid ``\$1''" ),
976 'cantpurge' => array( 'code' => 'cantpurge', 'info' => "Only users with the 'purge' right can purge pages via the API" ),
977 'protect-invalidaction' => array( 'code' => 'protect-invalidaction', 'info' => "Invalid protection type ``\$1''" ),
978 'protect-invalidlevel' => array( 'code' => 'protect-invalidlevel', 'info' => "Invalid protection level ``\$1''" ),
979 'toofewexpiries' => array( 'code' => 'toofewexpiries', 'info' => "\$1 expiry timestamps were provided where \$2 were needed" ),
980 'cantimport' => array( 'code' => 'cantimport', 'info' => "You don't have permission to import pages" ),
981 'cantimport-upload' => array( 'code' => 'cantimport-upload', 'info' => "You don't have permission to import uploaded pages" ),
982 'nouploadmodule' => array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
983 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
984 'importuploaderrorsize' => array( 'code' => 'filetoobig', 'info' => 'The file you uploaded is bigger than the maximum upload size' ),
985 'importuploaderrorpartial' => array( 'code' => 'partialupload', 'info' => 'The file was only partially uploaded' ),
986 'importuploaderrortemp' => array( 'code' => 'notempdir', 'info' => 'The temporary upload directory is missing' ),
987 'importcantopen' => array( 'code' => 'cantopenfile', 'info' => "Couldn't open the uploaded file" ),
988 'import-noarticle' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
989 'importbadinterwiki' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
990 'import-unknownerror' => array( 'code' => 'import-unknownerror', 'info' => "Unknown error on import: ``\$1''" ),
991 'cantoverwrite-sharedfile' => array( 'code' => 'cantoverwrite-sharedfile', 'info' => 'The target file exists on a shared repository and you do not have permission to override it' ),
992 'sharedfile-exists' => array( 'code' => 'fileexists-sharedrepo-perm', 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.' ),
993 'mustbeposted' => array( 'code' => 'mustbeposted', 'info' => "The \$1 module requires a POST request" ),
994 'show' => array( 'code' => 'show', 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied' ),
995
996 // ApiEditPage messages
997 'noimageredirect-anon' => array( 'code' => 'noimageredirect-anon', 'info' => "Anonymous users can't create image redirects" ),
998 'noimageredirect-logged' => array( 'code' => 'noimageredirect', 'info' => "You don't have permission to create image redirects" ),
999 'spamdetected' => array( 'code' => 'spamdetected', 'info' => "Your edit was refused because it contained a spam fragment: ``\$1''" ),
1000 'filtered' => array( 'code' => 'filtered', 'info' => "The filter callback function refused your edit" ),
1001 'contenttoobig' => array( 'code' => 'contenttoobig', 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes" ),
1002 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1003 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1004 'wasdeleted' => array( 'code' => 'pagedeleted', 'info' => "The page has been deleted since you fetched its timestamp" ),
1005 'blankpage' => array( 'code' => 'emptypage', 'info' => "Creating new, empty pages is not allowed" ),
1006 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1007 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1008 'missingtext' => array( 'code' => 'notext', 'info' => "One of the text, appendtext, prependtext and undo parameters must be set" ),
1009 'emptynewsection' => array( 'code' => 'emptynewsection', 'info' => 'Creating empty new sections is not possible.' ),
1010 'revwrongpage' => array( 'code' => 'revwrongpage', 'info' => "r\$1 is not a revision of ``\$2''" ),
1011 'undo-failure' => array( 'code' => 'undofailure', 'info' => 'Undo failed due to conflicting intermediate edits' ),
1012
1013 // uploadMsgs
1014 'invalid-session-key' => array( 'code' => 'invalid-session-key', 'info' => 'Not a valid session key' ),
1015 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1016 'uploaddisabled' => array( 'code' => 'uploaddisabled', 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true' ),
1017 'copyuploaddisabled' => array( 'code' => 'copyuploaddisabled', 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.' ),
1018 );
1019
1020 /**
1021 * Helper function for readonly errors
1022 */
1023 public function dieReadOnly() {
1024 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1025 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1026 array( 'readonlyreason' => wfReadOnlyReason() ) );
1027 }
1028
1029 /**
1030 * Output the error message related to a certain array
1031 * @param $error array Element of a getUserPermissionsErrors()-style array
1032 */
1033 public function dieUsageMsg( $error ) {
1034 $parsed = $this->parseMsg( $error );
1035 $this->dieUsage( $parsed['info'], $parsed['code'] );
1036 }
1037
1038 /**
1039 * Return the error message related to a certain array
1040 * @param $error array Element of a getUserPermissionsErrors()-style array
1041 * @return array('code' => code, 'info' => info)
1042 */
1043 public function parseMsg( $error ) {
1044 $key = array_shift( $error );
1045 if ( isset( self::$messageMap[$key] ) ) {
1046 return array( 'code' =>
1047 wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
1048 'info' =>
1049 wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
1050 );
1051 }
1052 // If the key isn't present, throw an "unknown error"
1053 return $this->parseMsg( array( 'unknownerror', $key ) );
1054 }
1055
1056 /**
1057 * Internal code errors should be reported with this method
1058 * @param $method string Method or function name
1059 * @param $message string Error message
1060 */
1061 protected static function dieDebug( $method, $message ) {
1062 wfDebugDieBacktrace( "Internal error in $method: $message" );
1063 }
1064
1065 /**
1066 * Indicates if this module needs maxlag to be checked
1067 * @return bool
1068 */
1069 public function shouldCheckMaxlag() {
1070 return true;
1071 }
1072
1073 /**
1074 * Indicates whether this module requires read rights
1075 * @return bool
1076 */
1077 public function isReadMode() {
1078 return true;
1079 }
1080 /**
1081 * Indicates whether this module requires write mode
1082 * @return bool
1083 */
1084 public function isWriteMode() {
1085 return false;
1086 }
1087
1088 /**
1089 * Indicates whether this module must be called with a POST request
1090 * @return bool
1091 */
1092 public function mustBePosted() {
1093 return false;
1094 }
1095
1096 /**
1097 * Returns the token salt if there is one, '' if the module doesn't require a salt, else false if the module doesn't need a token
1098 * @returns bool
1099 */
1100 public function getTokenSalt() {
1101 return false;
1102 }
1103
1104 /**
1105 * Gets the user for whom to get the watchlist
1106 *
1107 * @returns User
1108 */
1109 public function getWatchlistUser( $params ) {
1110 global $wgUser;
1111 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1112 $user = User::newFromName( $params['owner'], false );
1113 if ( !$user->getId() ) {
1114 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1115 }
1116 $token = $user->getOption( 'watchlisttoken' );
1117 if ( $token == '' || $token != $params['token'] ) {
1118 $this->dieUsage( 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences', 'bad_wltoken' );
1119 }
1120 } else {
1121 if ( !$wgUser->isLoggedIn() ) {
1122 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1123 }
1124 $user = $wgUser;
1125 }
1126 return $user;
1127 }
1128
1129 /**
1130 * Returns a list of all possible errors returned by the module
1131 * @return array in the format of array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1132 */
1133 public function getPossibleErrors() {
1134 $ret = array();
1135
1136 $params = $this->getFinalParams();
1137 if ( $params ) {
1138 foreach ( $params as $paramName => $paramSettings ) {
1139 if ( isset( $paramSettings[ApiBase::PARAM_REQUIRED] ) ) {
1140 $ret[] = array( 'missingparam', $paramName );
1141 }
1142 }
1143 }
1144
1145 if ( $this->mustBePosted() ) {
1146 $ret[] = array( 'mustbeposted', $this->getModuleName() );
1147 }
1148
1149 if ( $this->isReadMode() ) {
1150 $ret[] = array( 'readrequired' );
1151 }
1152
1153 if ( $this->isWriteMode() ) {
1154 $ret[] = array( 'writerequired' );
1155 $ret[] = array( 'writedisabled' );
1156 }
1157
1158 if ( $this->getTokenSalt() !== false ) {
1159 $ret[] = array( 'missingparam', 'token' );
1160 $ret[] = array( 'sessionfailure' );
1161 }
1162
1163 return $ret;
1164 }
1165
1166 /**
1167 * Parses a list of errors into a standardised format
1168 * @param $errors array List of errors. Items can be in the for array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1169 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
1170 */
1171 public function parseErrors( $errors ) {
1172 $ret = array();
1173
1174 foreach ( $errors as $row ) {
1175 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
1176 $ret[] = $row;
1177 } else {
1178 $ret[] = $this->parseMsg( $row );
1179 }
1180 }
1181 return $ret;
1182 }
1183
1184 /**
1185 * Profiling: total module execution time
1186 */
1187 private $mTimeIn = 0, $mModuleTime = 0;
1188
1189 /**
1190 * Start module profiling
1191 */
1192 public function profileIn() {
1193 if ( $this->mTimeIn !== 0 ) {
1194 ApiBase::dieDebug( __METHOD__, 'called twice without calling profileOut()' );
1195 }
1196 $this->mTimeIn = microtime( true );
1197 wfProfileIn( $this->getModuleProfileName() );
1198 }
1199
1200 /**
1201 * End module profiling
1202 */
1203 public function profileOut() {
1204 if ( $this->mTimeIn === 0 ) {
1205 ApiBase::dieDebug( __METHOD__, 'called without calling profileIn() first' );
1206 }
1207 if ( $this->mDBTimeIn !== 0 ) {
1208 ApiBase::dieDebug( __METHOD__, 'must be called after database profiling is done with profileDBOut()' );
1209 }
1210
1211 $this->mModuleTime += microtime( true ) - $this->mTimeIn;
1212 $this->mTimeIn = 0;
1213 wfProfileOut( $this->getModuleProfileName() );
1214 }
1215
1216 /**
1217 * When modules crash, sometimes it is needed to do a profileOut() regardless
1218 * of the profiling state the module was in. This method does such cleanup.
1219 */
1220 public function safeProfileOut() {
1221 if ( $this->mTimeIn !== 0 ) {
1222 if ( $this->mDBTimeIn !== 0 ) {
1223 $this->profileDBOut();
1224 }
1225 $this->profileOut();
1226 }
1227 }
1228
1229 /**
1230 * Total time the module was executed
1231 * @return float
1232 */
1233 public function getProfileTime() {
1234 if ( $this->mTimeIn !== 0 ) {
1235 ApiBase::dieDebug( __METHOD__, 'called without calling profileOut() first' );
1236 }
1237 return $this->mModuleTime;
1238 }
1239
1240 /**
1241 * Profiling: database execution time
1242 */
1243 private $mDBTimeIn = 0, $mDBTime = 0;
1244
1245 /**
1246 * Start module profiling
1247 */
1248 public function profileDBIn() {
1249 if ( $this->mTimeIn === 0 ) {
1250 ApiBase::dieDebug( __METHOD__, 'must be called while profiling the entire module with profileIn()' );
1251 }
1252 if ( $this->mDBTimeIn !== 0 ) {
1253 ApiBase::dieDebug( __METHOD__, 'called twice without calling profileDBOut()' );
1254 }
1255 $this->mDBTimeIn = microtime( true );
1256 wfProfileIn( $this->getModuleProfileName( true ) );
1257 }
1258
1259 /**
1260 * End database profiling
1261 */
1262 public function profileDBOut() {
1263 if ( $this->mTimeIn === 0 ) {
1264 ApiBase::dieDebug( __METHOD__, 'must be called while profiling the entire module with profileIn()' );
1265 }
1266 if ( $this->mDBTimeIn === 0 ) {
1267 ApiBase::dieDebug( __METHOD__, 'called without calling profileDBIn() first' );
1268 }
1269
1270 $time = microtime( true ) - $this->mDBTimeIn;
1271 $this->mDBTimeIn = 0;
1272
1273 $this->mDBTime += $time;
1274 $this->getMain()->mDBTime += $time;
1275 wfProfileOut( $this->getModuleProfileName( true ) );
1276 }
1277
1278 /**
1279 * Total time the module used the database
1280 * @return float
1281 */
1282 public function getProfileDBTime() {
1283 if ( $this->mDBTimeIn !== 0 ) {
1284 ApiBase::dieDebug( __METHOD__, 'called without calling profileDBOut() first' );
1285 }
1286 return $this->mDBTime;
1287 }
1288
1289 /**
1290 * Debugging function that prints a value and an optional backtrace
1291 * @param $value mixed Value to print
1292 * @param $name string Description of the printed value
1293 * @param $backtrace bool If true, print a backtrace
1294 */
1295 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
1296 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
1297 var_export( $value );
1298 if ( $backtrace ) {
1299 print "\n" . wfBacktrace();
1300 }
1301 print "\n</pre>\n";
1302 }
1303
1304 /**
1305 * Returns a string that identifies the version of this class.
1306 * @return string
1307 */
1308 public static function getBaseVersion() {
1309 return __CLASS__ . ': $Id$';
1310 }
1311 }