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