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