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