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