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