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