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