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