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