Throw exception on invalid RecentChange types
[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 // These constants allow modules to specify exactly how to treat incoming parameters.
44
45 // Default value of the parameter
46 const PARAM_DFLT = 0;
47 // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
48 const PARAM_ISMULTI = 1;
49 // Can be either a string type (e.g.: 'integer') or an array of allowed values
50 const PARAM_TYPE = 2;
51 // Max value allowed for a parameter. Only applies if TYPE='integer'
52 const PARAM_MAX = 3;
53 // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
54 const PARAM_MAX2 = 4;
55 // Lowest value allowed for a parameter. Only applies if TYPE='integer'
56 const PARAM_MIN = 5;
57 // Boolean, do we allow the same value to be set more than once when ISMULTI=true
58 const PARAM_ALLOW_DUPLICATES = 6;
59 // Boolean, is the parameter deprecated (will show a warning)
60 const PARAM_DEPRECATED = 7;
61 /// @since 1.17
62 const PARAM_REQUIRED = 8; // Boolean, is the parameter required?
63 /// @since 1.17
64 // Boolean, if MIN/MAX are set, enforce (die) these?
65 // Only applies if TYPE='integer' Use with extreme caution
66 const PARAM_RANGE_ENFORCE = 9;
67
68 // Name of property group that is on the root element of the result,
69 // i.e. not part of a list
70 const PROP_ROOT = 'ROOT';
71 // Boolean, is the result multiple items? Defaults to true for query modules,
72 // to false for other modules
73 const PROP_LIST = 'LIST';
74 const PROP_TYPE = 0; // Type of the property, uses same format as PARAM_TYPE
75 // Boolean, can the property be not included in the result? Defaults to false
76 const PROP_NULLABLE = 1;
77
78 const LIMIT_BIG1 = 500; // Fast query, std user limit
79 const LIMIT_BIG2 = 5000; // Fast query, bot/sysop limit
80 const LIMIT_SML1 = 50; // Slow query, std user limit
81 const LIMIT_SML2 = 500; // Slow query, bot/sysop limit
82
83 /**
84 * getAllowedParams() flag: When set, the result could take longer to generate,
85 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
86 * @since 1.21
87 */
88 const GET_VALUES_FOR_HELP = 1;
89
90 private $mMainModule, $mModuleName, $mModulePrefix;
91 private $mSlaveDB = null;
92 private $mParamCache = array();
93
94 /**
95 * Constructor
96 * @param $mainModule ApiMain object
97 * @param string $moduleName Name of this module
98 * @param string $modulePrefix Prefix to use for parameter names
99 */
100 public function __construct( $mainModule, $moduleName, $modulePrefix = '' ) {
101 $this->mMainModule = $mainModule;
102 $this->mModuleName = $moduleName;
103 $this->mModulePrefix = $modulePrefix;
104
105 if ( !$this->isMain() ) {
106 $this->setContext( $mainModule->getContext() );
107 }
108 }
109
110 /*****************************************************************************
111 * ABSTRACT METHODS *
112 *****************************************************************************/
113
114 /**
115 * Evaluates the parameters, performs the requested query, and sets up
116 * the result. Concrete implementations of ApiBase must override this
117 * method to provide whatever functionality their module offers.
118 * Implementations must not produce any output on their own and are not
119 * expected to handle any errors.
120 *
121 * The execute() method will be invoked directly by ApiMain immediately
122 * before the result of the module is output. Aside from the
123 * constructor, implementations should assume that no other methods
124 * will be called externally on the module before the result is
125 * processed.
126 *
127 * The result data should be stored in the ApiResult object available
128 * through getResult().
129 */
130 abstract public function execute();
131
132 /**
133 * Returns a string that identifies the version of the extending class.
134 * Typically includes the class name, the svn revision, timestamp, and
135 * last author. Usually done with SVN's Id keyword
136 * @return string
137 * @deprecated since 1.21, version string is no longer supported
138 */
139 public function getVersion() {
140 wfDeprecated( __METHOD__, '1.21' );
141
142 return '';
143 }
144
145 /**
146 * Get the name of the module being executed by this instance
147 * @return string
148 */
149 public function getModuleName() {
150 return $this->mModuleName;
151 }
152
153 /**
154 * Get the module manager, or null if this module has no sub-modules
155 * @since 1.21
156 * @return ApiModuleManager
157 */
158 public function getModuleManager() {
159 return null;
160 }
161
162 /**
163 * Get parameter prefix (usually two letters or an empty string).
164 * @return string
165 */
166 public function getModulePrefix() {
167 return $this->mModulePrefix;
168 }
169
170 /**
171 * Get the name of the module as shown in the profiler log
172 *
173 * @param $db DatabaseBase|bool
174 *
175 * @return string
176 */
177 public function getModuleProfileName( $db = false ) {
178 if ( $db ) {
179 return 'API:' . $this->mModuleName . '-DB';
180 }
181
182 return 'API:' . $this->mModuleName;
183 }
184
185 /**
186 * Get the main module
187 * @return ApiMain object
188 */
189 public function getMain() {
190 return $this->mMainModule;
191 }
192
193 /**
194 * Returns true if this module is the main module ($this === $this->mMainModule),
195 * false otherwise.
196 * @return bool
197 */
198 public function isMain() {
199 return $this === $this->mMainModule;
200 }
201
202 /**
203 * Get the result object
204 * @return ApiResult
205 */
206 public function getResult() {
207 // Main module has getResult() method overridden
208 // Safety - avoid infinite loop:
209 if ( $this->isMain() ) {
210 ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
211 }
212
213 return $this->getMain()->getResult();
214 }
215
216 /**
217 * Get the result data array (read-only)
218 * @return array
219 */
220 public function getResultData() {
221 return $this->getResult()->getData();
222 }
223
224 /**
225 * Create a new RequestContext object to use e.g. for calls to other parts
226 * the software.
227 * The object will have the WebRequest and the User object set to the ones
228 * used in this instance.
229 *
230 * @deprecated since 1.19 use getContext to get the current context
231 * @return DerivativeContext
232 */
233 public function createContext() {
234 wfDeprecated( __METHOD__, '1.19' );
235
236 return new DerivativeContext( $this->getContext() );
237 }
238
239 /**
240 * Set warning section for this module. Users should monitor this
241 * section to notice any changes in API. Multiple calls to this
242 * function will result in the warning messages being separated by
243 * newlines
244 * @param string $warning Warning message
245 */
246 public function setWarning( $warning ) {
247 $result = $this->getResult();
248 $data = $result->getData();
249 $moduleName = $this->getModuleName();
250 if ( isset( $data['warnings'][$moduleName] ) ) {
251 // Don't add duplicate warnings
252 $oldWarning = $data['warnings'][$moduleName]['*'];
253 $warnPos = strpos( $oldWarning, $warning );
254 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
255 if ( $warnPos !== false && ( $warnPos === 0 || $oldWarning[$warnPos - 1] === "\n" ) ) {
256 // Check if $warning is followed by "\n" or the end of the $oldWarning
257 $warnPos += strlen( $warning );
258 if ( strlen( $oldWarning ) <= $warnPos || $oldWarning[$warnPos] === "\n" ) {
259 return;
260 }
261 }
262 // If there is a warning already, append it to the existing one
263 $warning = "$oldWarning\n$warning";
264 }
265 $msg = array();
266 ApiResult::setContent( $msg, $warning );
267 $result->disableSizeCheck();
268 $result->addValue( 'warnings', $moduleName,
269 $msg, ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP );
270 $result->enableSizeCheck();
271 }
272
273 /**
274 * If the module may only be used with a certain format module,
275 * it should override this method to return an instance of that formatter.
276 * A value of null means the default format will be used.
277 * @return mixed instance of a derived class of ApiFormatBase, or null
278 */
279 public function getCustomPrinter() {
280 return null;
281 }
282
283 /**
284 * Generates help message for this module, or false if there is no description
285 * @return mixed string or false
286 */
287 public function makeHelpMsg() {
288 static $lnPrfx = "\n ";
289
290 $msg = $this->getFinalDescription();
291
292 if ( $msg !== false ) {
293
294 if ( !is_array( $msg ) ) {
295 $msg = array(
296 $msg
297 );
298 }
299 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
300
301 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
302
303 if ( $this->isReadMode() ) {
304 $msg .= "\nThis module requires read rights";
305 }
306 if ( $this->isWriteMode() ) {
307 $msg .= "\nThis module requires write rights";
308 }
309 if ( $this->mustBePosted() ) {
310 $msg .= "\nThis module only accepts POST requests";
311 }
312 if ( $this->isReadMode() || $this->isWriteMode() ||
313 $this->mustBePosted()
314 ) {
315 $msg .= "\n";
316 }
317
318 // Parameters
319 $paramsMsg = $this->makeHelpMsgParameters();
320 if ( $paramsMsg !== false ) {
321 $msg .= "Parameters:\n$paramsMsg";
322 }
323
324 $examples = $this->getExamples();
325 if ( $examples ) {
326 if ( !is_array( $examples ) ) {
327 $examples = array(
328 $examples
329 );
330 }
331 $msg .= "Example" . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
332 foreach ( $examples as $k => $v ) {
333 if ( is_numeric( $k ) ) {
334 $msg .= " $v\n";
335 } else {
336 if ( is_array( $v ) ) {
337 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
338 } else {
339 $msgExample = " $v";
340 }
341 $msgExample .= ":";
342 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
343 }
344 }
345 }
346 }
347
348 return $msg;
349 }
350
351 /**
352 * @param $item string
353 * @return string
354 */
355 private function indentExampleText( $item ) {
356 return " " . $item;
357 }
358
359 /**
360 * @param string $prefix Text to split output items
361 * @param string $title What is being output
362 * @param $input string|array
363 * @return string
364 */
365 protected function makeHelpArrayToString( $prefix, $title, $input ) {
366 if ( $input === false ) {
367 return '';
368 }
369 if ( !is_array( $input ) ) {
370 $input = array( $input );
371 }
372
373 if ( count( $input ) > 0 ) {
374 if ( $title ) {
375 $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n ";
376 } else {
377 $msg = ' ';
378 }
379 $msg .= implode( $prefix, $input ) . "\n";
380
381 return $msg;
382 }
383
384 return '';
385 }
386
387 /**
388 * Generates the parameter descriptions for this module, to be displayed in the
389 * module's help.
390 * @return string or false
391 */
392 public function makeHelpMsgParameters() {
393 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
394 if ( $params ) {
395
396 $paramsDescription = $this->getFinalParamDescription();
397 $msg = '';
398 $paramPrefix = "\n" . str_repeat( ' ', 24 );
399 $descWordwrap = "\n" . str_repeat( ' ', 28 );
400 foreach ( $params as $paramName => $paramSettings ) {
401 $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
402 if ( is_array( $desc ) ) {
403 $desc = implode( $paramPrefix, $desc );
404 }
405
406 //handle shorthand
407 if ( !is_array( $paramSettings ) ) {
408 $paramSettings = array(
409 self::PARAM_DFLT => $paramSettings,
410 );
411 }
412
413 //handle missing type
414 if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) {
415 $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] )
416 ? $paramSettings[ApiBase::PARAM_DFLT]
417 : null;
418 if ( is_bool( $dflt ) ) {
419 $paramSettings[ApiBase::PARAM_TYPE] = 'boolean';
420 } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
421 $paramSettings[ApiBase::PARAM_TYPE] = 'string';
422 } elseif ( is_int( $dflt ) ) {
423 $paramSettings[ApiBase::PARAM_TYPE] = 'integer';
424 }
425 }
426
427 if ( isset( $paramSettings[self::PARAM_DEPRECATED] )
428 && $paramSettings[self::PARAM_DEPRECATED]
429 ) {
430 $desc = "DEPRECATED! $desc";
431 }
432
433 if ( isset( $paramSettings[self::PARAM_REQUIRED] )
434 && $paramSettings[self::PARAM_REQUIRED]
435 ) {
436 $desc .= $paramPrefix . "This parameter is required";
437 }
438
439 $type = isset( $paramSettings[self::PARAM_TYPE] )
440 ? $paramSettings[self::PARAM_TYPE]
441 : null;
442 if ( isset( $type ) ) {
443 $hintPipeSeparated = true;
444 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
445 ? $paramSettings[self::PARAM_ISMULTI]
446 : false;
447 if ( $multi ) {
448 $prompt = 'Values (separate with \'|\'): ';
449 } else {
450 $prompt = 'One value: ';
451 }
452
453 if ( is_array( $type ) ) {
454 $choices = array();
455 $nothingPrompt = '';
456 foreach ( $type as $t ) {
457 if ( $t === '' ) {
458 $nothingPrompt = 'Can be empty, or ';
459 } else {
460 $choices[] = $t;
461 }
462 }
463 $desc .= $paramPrefix . $nothingPrompt . $prompt;
464 $choicesstring = implode( ', ', $choices );
465 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
466 $hintPipeSeparated = false;
467 } else {
468 switch ( $type ) {
469 case 'namespace':
470 // Special handling because namespaces are
471 // type-limited, yet they are not given
472 $desc .= $paramPrefix . $prompt;
473 $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
474 100, $descWordwrap );
475 $hintPipeSeparated = false;
476 break;
477 case 'limit':
478 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
479 if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
480 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
481 }
482 $desc .= ' allowed';
483 break;
484 case 'integer':
485 $s = $multi ? 's' : '';
486 $hasMin = isset( $paramSettings[self::PARAM_MIN] );
487 $hasMax = isset( $paramSettings[self::PARAM_MAX] );
488 if ( $hasMin || $hasMax ) {
489 if ( !$hasMax ) {
490 $intRangeStr = "The value$s must be no less than " .
491 "{$paramSettings[self::PARAM_MIN]}";
492 } elseif ( !$hasMin ) {
493 $intRangeStr = "The value$s must be no more than " .
494 "{$paramSettings[self::PARAM_MAX]}";
495 } else {
496 $intRangeStr = "The value$s must be between " .
497 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
498 }
499
500 $desc .= $paramPrefix . $intRangeStr;
501 }
502 break;
503 case 'upload':
504 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
505 break;
506 }
507 }
508
509 if ( $multi ) {
510 if ( $hintPipeSeparated ) {
511 $desc .= $paramPrefix . "Separate values with '|'";
512 }
513
514 $isArray = is_array( $type );
515 if ( !$isArray
516 || $isArray && count( $type ) > self::LIMIT_SML1
517 ) {
518 $desc .= $paramPrefix . "Maximum number of values " .
519 self::LIMIT_SML1 . " (" . self::LIMIT_SML2 . " for bots)";
520 }
521 }
522 }
523
524 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
525 if ( !is_null( $default ) && $default !== false ) {
526 $desc .= $paramPrefix . "Default: $default";
527 }
528
529 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
530 }
531
532 return $msg;
533 }
534
535 return false;
536 }
537
538 /**
539 * Returns the description string for this module
540 * @return mixed string or array of strings
541 */
542 protected function getDescription() {
543 return false;
544 }
545
546 /**
547 * Returns usage examples for this module. Return false if no examples are available.
548 * @return bool|string|array
549 */
550 protected function getExamples() {
551 return false;
552 }
553
554 /**
555 * Returns an array of allowed parameters (parameter name) => (default
556 * value) or (parameter name) => (array with PARAM_* constants as keys)
557 * Don't call this function directly: use getFinalParams() to allow
558 * hooks to modify parameters as needed.
559 *
560 * Some derived classes may choose to handle an integer $flags parameter
561 * in the overriding methods. Callers of this method can pass zero or
562 * more OR-ed flags like GET_VALUES_FOR_HELP.
563 *
564 * @return array|bool
565 */
566 protected function getAllowedParams( /* $flags = 0 */ ) {
567 // int $flags is not declared because it causes "Strict standards"
568 // warning. Most derived classes do not implement it.
569 return false;
570 }
571
572 /**
573 * Returns an array of parameter descriptions.
574 * Don't call this function directly: use getFinalParamDescription() to
575 * allow hooks to modify descriptions as needed.
576 * @return array|bool False on no parameter descriptions
577 */
578 protected function getParamDescription() {
579 return false;
580 }
581
582 /**
583 * Get final list of parameters, after hooks have had a chance to
584 * tweak it as needed.
585 *
586 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
587 * @return array|Bool False on no parameters
588 * @since 1.21 $flags param added
589 */
590 public function getFinalParams( $flags = 0 ) {
591 $params = $this->getAllowedParams( $flags );
592 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
593
594 return $params;
595 }
596
597 /**
598 * Get final parameter descriptions, after hooks have had a chance to tweak it as
599 * needed.
600 *
601 * @return array|bool False on no parameter descriptions
602 */
603 public function getFinalParamDescription() {
604 $desc = $this->getParamDescription();
605 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
606
607 return $desc;
608 }
609
610 /**
611 * Returns possible properties in the result, grouped by the value of the prop parameter
612 * that shows them.
613 *
614 * Properties that are shown always are in a group with empty string as a key.
615 * Properties that can be shown by several values of prop are included multiple times.
616 * If some properties are part of a list and some are on the root object (see ApiQueryQueryPage),
617 * those on the root object are under the key PROP_ROOT.
618 * The array can also contain a boolean under the key PROP_LIST,
619 * indicating whether the result is a list.
620 *
621 * Don't call this function directly: use getFinalResultProperties() to
622 * allow hooks to modify descriptions as needed.
623 *
624 * @return array|bool False on no properties
625 */
626 protected function getResultProperties() {
627 return false;
628 }
629
630 /**
631 * Get final possible result properties, after hooks have had a chance to tweak it as
632 * needed.
633 *
634 * @return array
635 */
636 public function getFinalResultProperties() {
637 $properties = $this->getResultProperties();
638 wfRunHooks( 'APIGetResultProperties', array( $this, &$properties ) );
639
640 return $properties;
641 }
642
643 /**
644 * Add token properties to the array used by getResultProperties,
645 * based on a token functions mapping.
646 */
647 protected static function addTokenProperties( &$props, $tokenFunctions ) {
648 foreach ( array_keys( $tokenFunctions ) as $token ) {
649 $props[''][$token . 'token'] = array(
650 ApiBase::PROP_TYPE => 'string',
651 ApiBase::PROP_NULLABLE => true
652 );
653 }
654 }
655
656 /**
657 * Get final module description, after hooks have had a chance to tweak it as
658 * needed.
659 *
660 * @return array|bool False on no parameters
661 */
662 public function getFinalDescription() {
663 $desc = $this->getDescription();
664 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
665
666 return $desc;
667 }
668
669 /**
670 * This method mangles parameter name based on the prefix supplied to the constructor.
671 * Override this method to change parameter name during runtime
672 * @param string $paramName Parameter name
673 * @return string Prefixed parameter name
674 */
675 public function encodeParamName( $paramName ) {
676 return $this->mModulePrefix . $paramName;
677 }
678
679 /**
680 * Using getAllowedParams(), this function makes an array of the values
681 * provided by the user, with key being the name of the variable, and
682 * value - validated value from user or default. limits will not be
683 * parsed if $parseLimit is set to false; use this when the max
684 * limit is not definitive yet, e.g. when getting revisions.
685 * @param $parseLimit Boolean: true by default
686 * @return array
687 */
688 public function extractRequestParams( $parseLimit = true ) {
689 // Cache parameters, for performance and to avoid bug 24564.
690 if ( !isset( $this->mParamCache[$parseLimit] ) ) {
691 $params = $this->getFinalParams();
692 $results = array();
693
694 if ( $params ) { // getFinalParams() can return false
695 foreach ( $params as $paramName => $paramSettings ) {
696 $results[$paramName] = $this->getParameterFromSettings(
697 $paramName, $paramSettings, $parseLimit );
698 }
699 }
700 $this->mParamCache[$parseLimit] = $results;
701 }
702
703 return $this->mParamCache[$parseLimit];
704 }
705
706 /**
707 * Get a value for the given parameter
708 * @param string $paramName Parameter name
709 * @param bool $parseLimit see extractRequestParams()
710 * @return mixed Parameter value
711 */
712 protected function getParameter( $paramName, $parseLimit = true ) {
713 $params = $this->getFinalParams();
714 $paramSettings = $params[$paramName];
715
716 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
717 }
718
719 /**
720 * Die if none or more than one of a certain set of parameters is set and not false.
721 * @param array $params of parameter names
722 */
723 public function requireOnlyOneParameter( $params ) {
724 $required = func_get_args();
725 array_shift( $required );
726 $p = $this->getModulePrefix();
727
728 $intersection = array_intersect( array_keys( array_filter( $params,
729 array( $this, "parameterNotEmpty" ) ) ), $required );
730
731 if ( count( $intersection ) > 1 ) {
732 $this->dieUsage(
733 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
734 'invalidparammix' );
735 } elseif ( count( $intersection ) == 0 ) {
736 $this->dieUsage(
737 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
738 'missingparam'
739 );
740 }
741 }
742
743 /**
744 * Generates the possible errors requireOnlyOneParameter() can die with
745 *
746 * @param $params array
747 * @return array
748 */
749 public function getRequireOnlyOneParameterErrorMessages( $params ) {
750 $p = $this->getModulePrefix();
751 $params = implode( ", {$p}", $params );
752
753 return array(
754 array(
755 'code' => "{$p}missingparam",
756 'info' => "One of the parameters {$p}{$params} is required"
757 ),
758 array(
759 'code' => "{$p}invalidparammix",
760 'info' => "The parameters {$p}{$params} can not be used together"
761 )
762 );
763 }
764
765 /**
766 * Die if more than one of a certain set of parameters is set and not false.
767 *
768 * @param $params array
769 */
770 public function requireMaxOneParameter( $params ) {
771 $required = func_get_args();
772 array_shift( $required );
773 $p = $this->getModulePrefix();
774
775 $intersection = array_intersect( array_keys( array_filter( $params,
776 array( $this, "parameterNotEmpty" ) ) ), $required );
777
778 if ( count( $intersection ) > 1 ) {
779 $this->dieUsage(
780 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
781 'invalidparammix'
782 );
783 }
784 }
785
786 /**
787 * Generates the possible error requireMaxOneParameter() can die with
788 *
789 * @param $params array
790 * @return array
791 */
792 public function getRequireMaxOneParameterErrorMessages( $params ) {
793 $p = $this->getModulePrefix();
794 $params = implode( ", {$p}", $params );
795
796 return array(
797 array(
798 'code' => "{$p}invalidparammix",
799 'info' => "The parameters {$p}{$params} can not be used together"
800 )
801 );
802 }
803
804 /**
805 * @param $params array
806 * @param bool|string $load Whether load the object's state from the database:
807 * - false: don't load (if the pageid is given, it will still be loaded)
808 * - 'fromdb': load from a slave database
809 * - 'fromdbmaster': load from the master database
810 * @return WikiPage
811 */
812 public function getTitleOrPageId( $params, $load = false ) {
813 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
814
815 $pageObj = null;
816 if ( isset( $params['title'] ) ) {
817 $titleObj = Title::newFromText( $params['title'] );
818 if ( !$titleObj || $titleObj->isExternal() ) {
819 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
820 }
821 if ( !$titleObj->canExist() ) {
822 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
823 }
824 $pageObj = WikiPage::factory( $titleObj );
825 if ( $load !== false ) {
826 $pageObj->loadPageData( $load );
827 }
828 } elseif ( isset( $params['pageid'] ) ) {
829 if ( $load === false ) {
830 $load = 'fromdb';
831 }
832 $pageObj = WikiPage::newFromID( $params['pageid'], $load );
833 if ( !$pageObj ) {
834 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
835 }
836 }
837
838 return $pageObj;
839 }
840
841 /**
842 * @return array
843 */
844 public function getTitleOrPageIdErrorMessage() {
845 return array_merge(
846 $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ),
847 array(
848 array( 'invalidtitle', 'title' ),
849 array( 'nosuchpageid', 'pageid' ),
850 )
851 );
852 }
853
854 /**
855 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
856 *
857 * @param $x object Parameter to check is not null/false
858 * @return bool
859 */
860 private function parameterNotEmpty( $x ) {
861 return !is_null( $x ) && $x !== false;
862 }
863
864 /**
865 * @deprecated since 1.17 use MWNamespace::getValidNamespaces()
866 *
867 * @return array
868 */
869 public static function getValidNamespaces() {
870 wfDeprecated( __METHOD__, '1.17' );
871
872 return MWNamespace::getValidNamespaces();
873 }
874
875 /**
876 * Return true if we're to watch the page, false if not, null if no change.
877 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
878 * @param $titleObj Title the page under consideration
879 * @param string $userOption The user option to consider when $watchlist=preferences.
880 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
881 * @return bool
882 */
883 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
884
885 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem::IGNORE_USER_RIGHTS );
886
887 switch ( $watchlist ) {
888 case 'watch':
889 return true;
890
891 case 'unwatch':
892 return false;
893
894 case 'preferences':
895 # If the user is already watching, don't bother checking
896 if ( $userWatching ) {
897 return true;
898 }
899 # If no user option was passed, use watchdefault and watchcreations
900 if ( is_null( $userOption ) ) {
901 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
902 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
903 }
904
905 # Watch the article based on the user preference
906 return $this->getUser()->getBoolOption( $userOption );
907
908 case 'nochange':
909 return $userWatching;
910
911 default:
912 return $userWatching;
913 }
914 }
915
916 /**
917 * Set a watch (or unwatch) based the based on a watchlist parameter.
918 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
919 * @param $titleObj Title the article's title to change
920 * @param string $userOption The user option to consider when $watch=preferences
921 */
922 protected function setWatch( $watch, $titleObj, $userOption = null ) {
923 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
924 if ( $value === null ) {
925 return;
926 }
927
928 WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
929 }
930
931 /**
932 * Using the settings determine the value for the given parameter
933 *
934 * @param string $paramName parameter name
935 * @param array|mixed $paramSettings default value or an array of settings
936 * using PARAM_* constants.
937 * @param $parseLimit Boolean: parse limit?
938 * @return mixed Parameter value
939 */
940 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
941 // Some classes may decide to change parameter names
942 $encParamName = $this->encodeParamName( $paramName );
943
944 if ( !is_array( $paramSettings ) ) {
945 $default = $paramSettings;
946 $multi = false;
947 $type = gettype( $paramSettings );
948 $dupes = false;
949 $deprecated = false;
950 $required = false;
951 } else {
952 $default = isset( $paramSettings[self::PARAM_DFLT] )
953 ? $paramSettings[self::PARAM_DFLT]
954 : null;
955 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
956 ? $paramSettings[self::PARAM_ISMULTI]
957 : false;
958 $type = isset( $paramSettings[self::PARAM_TYPE] )
959 ? $paramSettings[self::PARAM_TYPE]
960 : null;
961 $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] )
962 ? $paramSettings[self::PARAM_ALLOW_DUPLICATES]
963 : false;
964 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] )
965 ? $paramSettings[self::PARAM_DEPRECATED]
966 : false;
967 $required = isset( $paramSettings[self::PARAM_REQUIRED] )
968 ? $paramSettings[self::PARAM_REQUIRED]
969 : false;
970
971 // When type is not given, and no choices, the type is the same as $default
972 if ( !isset( $type ) ) {
973 if ( isset( $default ) ) {
974 $type = gettype( $default );
975 } else {
976 $type = 'NULL'; // allow everything
977 }
978 }
979 }
980
981 if ( $type == 'boolean' ) {
982 if ( isset( $default ) && $default !== false ) {
983 // Having a default value of anything other than 'false' is not allowed
984 ApiBase::dieDebug(
985 __METHOD__,
986 "Boolean param $encParamName's default is set to '$default'. " .
987 "Boolean parameters must default to false."
988 );
989 }
990
991 $value = $this->getMain()->getCheck( $encParamName );
992 } elseif ( $type == 'upload' ) {
993 if ( isset( $default ) ) {
994 // Having a default value is not allowed
995 ApiBase::dieDebug(
996 __METHOD__,
997 "File upload param $encParamName's default is set to " .
998 "'$default'. File upload parameters may not have a default." );
999 }
1000 if ( $multi ) {
1001 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1002 }
1003 $value = $this->getMain()->getUpload( $encParamName );
1004 if ( !$value->exists() ) {
1005 // This will get the value without trying to normalize it
1006 // (because trying to normalize a large binary file
1007 // accidentally uploaded as a field fails spectacularly)
1008 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1009 if ( $value !== null ) {
1010 $this->dieUsage(
1011 "File upload param $encParamName is not a file upload; " .
1012 "be sure to use multipart/form-data for your POST and include " .
1013 "a filename in the Content-Disposition header.",
1014 "badupload_{$encParamName}"
1015 );
1016 }
1017 }
1018 } else {
1019 $value = $this->getMain()->getVal( $encParamName, $default );
1020
1021 if ( isset( $value ) && $type == 'namespace' ) {
1022 $type = MWNamespace::getValidNamespaces();
1023 }
1024 }
1025
1026 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
1027 $value = $this->parseMultiValue(
1028 $encParamName,
1029 $value,
1030 $multi,
1031 is_array( $type ) ? $type : null
1032 );
1033 }
1034
1035 // More validation only when choices were not given
1036 // choices were validated in parseMultiValue()
1037 if ( isset( $value ) ) {
1038 if ( !is_array( $type ) ) {
1039 switch ( $type ) {
1040 case 'NULL': // nothing to do
1041 break;
1042 case 'string':
1043 if ( $required && $value === '' ) {
1044 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1045 }
1046 break;
1047 case 'integer': // Force everything using intval() and optionally validate limits
1048 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
1049 $max = isset( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
1050 $enforceLimits = isset( $paramSettings[self::PARAM_RANGE_ENFORCE] )
1051 ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
1052
1053 if ( is_array( $value ) ) {
1054 $value = array_map( 'intval', $value );
1055 if ( !is_null( $min ) || !is_null( $max ) ) {
1056 foreach ( $value as &$v ) {
1057 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1058 }
1059 }
1060 } else {
1061 $value = intval( $value );
1062 if ( !is_null( $min ) || !is_null( $max ) ) {
1063 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1064 }
1065 }
1066 break;
1067 case 'limit':
1068 if ( !$parseLimit ) {
1069 // Don't do any validation whatsoever
1070 break;
1071 }
1072 if ( !isset( $paramSettings[self::PARAM_MAX] )
1073 || !isset( $paramSettings[self::PARAM_MAX2] )
1074 ) {
1075 ApiBase::dieDebug(
1076 __METHOD__,
1077 "MAX1 or MAX2 are not defined for the limit $encParamName"
1078 );
1079 }
1080 if ( $multi ) {
1081 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1082 }
1083 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
1084 if ( $value == 'max' ) {
1085 $value = $this->getMain()->canApiHighLimits()
1086 ? $paramSettings[self::PARAM_MAX2]
1087 : $paramSettings[self::PARAM_MAX];
1088 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
1089 } else {
1090 $value = intval( $value );
1091 $this->validateLimit(
1092 $paramName,
1093 $value,
1094 $min,
1095 $paramSettings[self::PARAM_MAX],
1096 $paramSettings[self::PARAM_MAX2]
1097 );
1098 }
1099 break;
1100 case 'boolean':
1101 if ( $multi ) {
1102 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1103 }
1104 break;
1105 case 'timestamp':
1106 if ( is_array( $value ) ) {
1107 foreach ( $value as $key => $val ) {
1108 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1109 }
1110 } else {
1111 $value = $this->validateTimestamp( $value, $encParamName );
1112 }
1113 break;
1114 case 'user':
1115 if ( is_array( $value ) ) {
1116 foreach ( $value as $key => $val ) {
1117 $value[$key] = $this->validateUser( $val, $encParamName );
1118 }
1119 } else {
1120 $value = $this->validateUser( $value, $encParamName );
1121 }
1122 break;
1123 case 'upload': // nothing to do
1124 break;
1125 default:
1126 ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
1127 }
1128 }
1129
1130 // Throw out duplicates if requested
1131 if ( !$dupes && is_array( $value ) ) {
1132 $value = array_unique( $value );
1133 }
1134
1135 // Set a warning if a deprecated parameter has been passed
1136 if ( $deprecated && $value !== false ) {
1137 $this->setWarning( "The $encParamName parameter has been deprecated." );
1138 }
1139 } elseif ( $required ) {
1140 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1141 }
1142
1143 return $value;
1144 }
1145
1146 /**
1147 * Return an array of values that were given in a 'a|b|c' notation,
1148 * after it optionally validates them against the list allowed values.
1149 *
1150 * @param string $valueName The name of the parameter (for error
1151 * reporting)
1152 * @param $value mixed The value being parsed
1153 * @param bool $allowMultiple Can $value contain more than one value
1154 * separated by '|'?
1155 * @param $allowedValues mixed An array of values to check against. If
1156 * null, all values are accepted.
1157 * @return mixed (allowMultiple ? an_array_of_values : a_single_value)
1158 */
1159 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1160 if ( trim( $value ) === '' && $allowMultiple ) {
1161 return array();
1162 }
1163
1164 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1165 // because it unstubs $wgUser
1166 $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 );
1167 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits()
1168 ? self::LIMIT_SML2
1169 : self::LIMIT_SML1;
1170
1171 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
1172 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1173 "the limit is $sizeLimit" );
1174 }
1175
1176 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1177 // Bug 33482 - Allow entries with | in them for non-multiple values
1178 if ( in_array( $value, $allowedValues, true ) ) {
1179 return $value;
1180 }
1181
1182 $possibleValues = is_array( $allowedValues )
1183 ? "of '" . implode( "', '", $allowedValues ) . "'"
1184 : '';
1185 $this->dieUsage(
1186 "Only one $possibleValues is allowed for parameter '$valueName'",
1187 "multival_$valueName"
1188 );
1189 }
1190
1191 if ( is_array( $allowedValues ) ) {
1192 // Check for unknown values
1193 $unknown = array_diff( $valuesList, $allowedValues );
1194 if ( count( $unknown ) ) {
1195 if ( $allowMultiple ) {
1196 $s = count( $unknown ) > 1 ? 's' : '';
1197 $vals = implode( ", ", $unknown );
1198 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1199 } else {
1200 $this->dieUsage(
1201 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1202 "unknown_$valueName"
1203 );
1204 }
1205 }
1206 // Now throw them out
1207 $valuesList = array_intersect( $valuesList, $allowedValues );
1208 }
1209
1210 return $allowMultiple ? $valuesList : $valuesList[0];
1211 }
1212
1213 /**
1214 * Validate the value against the minimum and user/bot maximum limits.
1215 * Prints usage info on failure.
1216 * @param string $paramName Parameter name
1217 * @param int $value Parameter value
1218 * @param int|null $min Minimum value
1219 * @param int|null $max Maximum value for users
1220 * @param int $botMax Maximum value for sysops/bots
1221 * @param $enforceLimits Boolean Whether to enforce (die) if value is outside limits
1222 */
1223 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1224 if ( !is_null( $min ) && $value < $min ) {
1225
1226 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1227 $this->warnOrDie( $msg, $enforceLimits );
1228 $value = $min;
1229 }
1230
1231 // Minimum is always validated, whereas maximum is checked only if not
1232 // running in internal call mode
1233 if ( $this->getMain()->isInternalMode() ) {
1234 return;
1235 }
1236
1237 // Optimization: do not check user's bot status unless really needed -- skips db query
1238 // assumes $botMax >= $max
1239 if ( !is_null( $max ) && $value > $max ) {
1240 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1241 if ( $value > $botMax ) {
1242 $msg = $this->encodeParamName( $paramName ) .
1243 " may not be over $botMax (set to $value) for bots or sysops";
1244 $this->warnOrDie( $msg, $enforceLimits );
1245 $value = $botMax;
1246 }
1247 } else {
1248 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1249 $this->warnOrDie( $msg, $enforceLimits );
1250 $value = $max;
1251 }
1252 }
1253 }
1254
1255 /**
1256 * Validate and normalize of parameters of type 'timestamp'
1257 * @param string $value Parameter value
1258 * @param string $encParamName Parameter name
1259 * @return string Validated and normalized parameter
1260 */
1261 function validateTimestamp( $value, $encParamName ) {
1262 $unixTimestamp = wfTimestamp( TS_UNIX, $value );
1263 if ( $unixTimestamp === false ) {
1264 $this->dieUsage(
1265 "Invalid value '$value' for timestamp parameter $encParamName",
1266 "badtimestamp_{$encParamName}"
1267 );
1268 }
1269
1270 return wfTimestamp( TS_MW, $unixTimestamp );
1271 }
1272
1273 /**
1274 * Validate and normalize of parameters of type 'user'
1275 * @param string $value Parameter value
1276 * @param string $encParamName Parameter name
1277 * @return string Validated and normalized parameter
1278 */
1279 private function validateUser( $value, $encParamName ) {
1280 $title = Title::makeTitleSafe( NS_USER, $value );
1281 if ( $title === null ) {
1282 $this->dieUsage(
1283 "Invalid value '$value' for user parameter $encParamName",
1284 "baduser_{$encParamName}"
1285 );
1286 }
1287
1288 return $title->getText();
1289 }
1290
1291 /**
1292 * Adds a warning to the output, else dies
1293 *
1294 * @param $msg String Message to show as a warning, or error message if dying
1295 * @param $enforceLimits Boolean Whether this is an enforce (die)
1296 */
1297 private function warnOrDie( $msg, $enforceLimits = false ) {
1298 if ( $enforceLimits ) {
1299 $this->dieUsage( $msg, 'integeroutofrange' );
1300 }
1301
1302 $this->setWarning( $msg );
1303 }
1304
1305 /**
1306 * Truncate an array to a certain length.
1307 * @param array $arr Array to truncate
1308 * @param int $limit Maximum length
1309 * @return bool True if the array was truncated, false otherwise
1310 */
1311 public static function truncateArray( &$arr, $limit ) {
1312 $modified = false;
1313 while ( count( $arr ) > $limit ) {
1314 array_pop( $arr );
1315 $modified = true;
1316 }
1317
1318 return $modified;
1319 }
1320
1321 /**
1322 * Throw a UsageException, which will (if uncaught) call the main module's
1323 * error handler and die with an error message.
1324 *
1325 * @param string $description One-line human-readable description of the
1326 * error condition, e.g., "The API requires a valid action parameter"
1327 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1328 * automated identification of the error, e.g., 'unknown_action'
1329 * @param int $httpRespCode HTTP response code
1330 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1331 * @throws UsageException
1332 */
1333 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1334 Profiler::instance()->close();
1335 throw new UsageException(
1336 $description,
1337 $this->encodeParamName( $errorCode ),
1338 $httpRespCode,
1339 $extradata
1340 );
1341 }
1342
1343 /**
1344 * Throw a UsageException based on the errors in the Status object.
1345 *
1346 * @since 1.22
1347 * @param Status $status Status object
1348 * @throws MWException
1349 */
1350 public function dieStatus( $status ) {
1351 if ( $status->isGood() ) {
1352 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1353 }
1354
1355 $errors = $status->getErrorsArray();
1356 if ( !$errors ) {
1357 // No errors? Assume the warnings should be treated as errors
1358 $errors = $status->getWarningsArray();
1359 }
1360 if ( !$errors ) {
1361 // Still no errors? Punt
1362 $errors = array( array( 'unknownerror-nocode' ) );
1363 }
1364
1365 // Cannot use dieUsageMsg() because extensions might return custom
1366 // error messages.
1367 if ( $errors[0] instanceof Message ) {
1368 $msg = $errors[0];
1369 $code = $msg->getKey();
1370 } else {
1371 $code = array_shift( $errors[0] );
1372 $msg = wfMessage( $code, $errors[0] );
1373 }
1374 if ( isset( ApiBase::$messageMap[$code] ) ) {
1375 // Translate message to code, for backwards compatability
1376 $code = ApiBase::$messageMap[$code]['code'];
1377 }
1378 $this->dieUsage( $msg->inLanguage( 'en' )->useDatabase( false )->plain(), $code );
1379 }
1380
1381 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1382 /**
1383 * Array that maps message keys to error messages. $1 and friends are replaced.
1384 */
1385 public static $messageMap = array(
1386 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1387 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1388 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1389
1390 // Messages from Title::getUserPermissionsErrors()
1391 'ns-specialprotected' => array(
1392 'code' => 'unsupportednamespace',
1393 'info' => "Pages in the Special namespace can't be edited"
1394 ),
1395 'protectedinterface' => array(
1396 'code' => 'protectednamespace-interface',
1397 'info' => "You're not allowed to edit interface messages"
1398 ),
1399 'namespaceprotected' => array(
1400 'code' => 'protectednamespace',
1401 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1402 ),
1403 'customcssprotected' => array(
1404 'code' => 'customcssprotected',
1405 'info' => "You're not allowed to edit custom CSS pages"
1406 ),
1407 'customjsprotected' => array(
1408 'code' => 'customjsprotected',
1409 'info' => "You're not allowed to edit custom JavaScript pages"
1410 ),
1411 'cascadeprotected' => array(
1412 'code' => 'cascadeprotected',
1413 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1414 ),
1415 'protectedpagetext' => array(
1416 'code' => 'protectedpage',
1417 'info' => "The \"\$1\" right is required to edit this page"
1418 ),
1419 'protect-cantedit' => array(
1420 'code' => 'cantedit',
1421 'info' => "You can't protect this page because you can't edit it"
1422 ),
1423 'badaccess-group0' => array(
1424 'code' => 'permissiondenied',
1425 'info' => "Permission denied"
1426 ), // Generic permission denied message
1427 'badaccess-groups' => array(
1428 'code' => 'permissiondenied',
1429 'info' => "Permission denied"
1430 ),
1431 'titleprotected' => array(
1432 'code' => 'protectedtitle',
1433 'info' => "This title has been protected from creation"
1434 ),
1435 'nocreate-loggedin' => array(
1436 'code' => 'cantcreate',
1437 'info' => "You don't have permission to create new pages"
1438 ),
1439 'nocreatetext' => array(
1440 'code' => 'cantcreate-anon',
1441 'info' => "Anonymous users can't create new pages"
1442 ),
1443 'movenologintext' => array(
1444 'code' => 'cantmove-anon',
1445 'info' => "Anonymous users can't move pages"
1446 ),
1447 'movenotallowed' => array(
1448 'code' => 'cantmove',
1449 'info' => "You don't have permission to move pages"
1450 ),
1451 'confirmedittext' => array(
1452 'code' => 'confirmemail',
1453 'info' => "You must confirm your email address before you can edit"
1454 ),
1455 'blockedtext' => array(
1456 'code' => 'blocked',
1457 'info' => "You have been blocked from editing"
1458 ),
1459 'autoblockedtext' => array(
1460 'code' => 'autoblocked',
1461 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1462 ),
1463
1464 // Miscellaneous interface messages
1465 'actionthrottledtext' => array(
1466 'code' => 'ratelimited',
1467 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1468 ),
1469 'alreadyrolled' => array(
1470 'code' => 'alreadyrolled',
1471 'info' => "The page you tried to rollback was already rolled back"
1472 ),
1473 'cantrollback' => array(
1474 'code' => 'onlyauthor',
1475 'info' => "The page you tried to rollback only has one author"
1476 ),
1477 'readonlytext' => array(
1478 'code' => 'readonly',
1479 'info' => "The wiki is currently in read-only mode"
1480 ),
1481 'sessionfailure' => array(
1482 'code' => 'badtoken',
1483 'info' => "Invalid token" ),
1484 'cannotdelete' => array(
1485 'code' => 'cantdelete',
1486 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1487 ),
1488 'notanarticle' => array(
1489 'code' => 'missingtitle',
1490 'info' => "The page you requested doesn't exist"
1491 ),
1492 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1493 ),
1494 'immobile_namespace' => array(
1495 'code' => 'immobilenamespace',
1496 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1497 ),
1498 'articleexists' => array(
1499 'code' => 'articleexists',
1500 'info' => "The destination article already exists and is not a redirect to the source article"
1501 ),
1502 'protectedpage' => array(
1503 'code' => 'protectedpage',
1504 'info' => "You don't have permission to perform this move"
1505 ),
1506 'hookaborted' => array(
1507 'code' => 'hookaborted',
1508 'info' => "The modification you tried to make was aborted by an extension hook"
1509 ),
1510 'cantmove-titleprotected' => array(
1511 'code' => 'protectedtitle',
1512 'info' => "The destination article has been protected from creation"
1513 ),
1514 'imagenocrossnamespace' => array(
1515 'code' => 'nonfilenamespace',
1516 'info' => "Can't move a file to a non-file namespace"
1517 ),
1518 'imagetypemismatch' => array(
1519 'code' => 'filetypemismatch',
1520 'info' => "The new file extension doesn't match its type"
1521 ),
1522 // 'badarticleerror' => shouldn't happen
1523 // 'badtitletext' => shouldn't happen
1524 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1525 'range_block_disabled' => array(
1526 'code' => 'rangedisabled',
1527 'info' => "Blocking IP ranges has been disabled"
1528 ),
1529 'nosuchusershort' => array(
1530 'code' => 'nosuchuser',
1531 'info' => "The user you specified doesn't exist"
1532 ),
1533 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1534 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1535 'ipb_already_blocked' => array(
1536 'code' => 'alreadyblocked',
1537 'info' => "The user you tried to block was already blocked"
1538 ),
1539 'ipb_blocked_as_range' => array(
1540 'code' => 'blockedasrange',
1541 'info' => "IP address \"\$1\" was blocked as part of range \"\$2\". You can't unblock the IP individually, but you can unblock the range as a whole."
1542 ),
1543 'ipb_cant_unblock' => array(
1544 'code' => 'cantunblock',
1545 'info' => "The block you specified was not found. It may have been unblocked already"
1546 ),
1547 'mailnologin' => array(
1548 'code' => 'cantsend',
1549 'info' => "You are not logged in, you do not have a confirmed email address, or you are not allowed to send email to other users, so you cannot send email"
1550 ),
1551 'ipbblocked' => array(
1552 'code' => 'ipbblocked',
1553 'info' => 'You cannot block or unblock users while you are yourself blocked'
1554 ),
1555 'ipbnounblockself' => array(
1556 'code' => 'ipbnounblockself',
1557 'info' => 'You are not allowed to unblock yourself'
1558 ),
1559 'usermaildisabled' => array(
1560 'code' => 'usermaildisabled',
1561 'info' => "User email has been disabled"
1562 ),
1563 'blockedemailuser' => array(
1564 'code' => 'blockedfrommail',
1565 'info' => "You have been blocked from sending email"
1566 ),
1567 'notarget' => array(
1568 'code' => 'notarget',
1569 'info' => "You have not specified a valid target for this action"
1570 ),
1571 'noemail' => array(
1572 'code' => 'noemail',
1573 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1574 ),
1575 'rcpatroldisabled' => array(
1576 'code' => 'patroldisabled',
1577 'info' => "Patrolling is disabled on this wiki"
1578 ),
1579 'markedaspatrollederror-noautopatrol' => array(
1580 'code' => 'noautopatrol',
1581 'info' => "You don't have permission to patrol your own changes"
1582 ),
1583 'delete-toobig' => array(
1584 'code' => 'bigdelete',
1585 'info' => "You can't delete this page because it has more than \$1 revisions"
1586 ),
1587 'movenotallowedfile' => array(
1588 'code' => 'cantmovefile',
1589 'info' => "You don't have permission to move files"
1590 ),
1591 'userrights-no-interwiki' => array(
1592 'code' => 'nointerwikiuserrights',
1593 'info' => "You don't have permission to change user rights on other wikis"
1594 ),
1595 'userrights-nodatabase' => array(
1596 'code' => 'nosuchdatabase',
1597 'info' => "Database \"\$1\" does not exist or is not local"
1598 ),
1599 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1600 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1601 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1602 'import-rootpage-invalid' => array(
1603 'code' => 'import-rootpage-invalid',
1604 'info' => 'Root page is an invalid title'
1605 ),
1606 'import-rootpage-nosubpage' => array(
1607 'code' => 'import-rootpage-nosubpage',
1608 'info' => 'Namespace "$1" of the root page does not allow subpages'
1609 ),
1610
1611 // API-specific messages
1612 'readrequired' => array(
1613 'code' => 'readapidenied',
1614 'info' => "You need read permission to use this module"
1615 ),
1616 'writedisabled' => array(
1617 'code' => 'noapiwrite',
1618 '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"
1619 ),
1620 'writerequired' => array(
1621 'code' => 'writeapidenied',
1622 'info' => "You're not allowed to edit this wiki through the API"
1623 ),
1624 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1625 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1626 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1627 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1628 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1629 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1630 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1631 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1632 'create-titleexists' => array(
1633 'code' => 'create-titleexists',
1634 'info' => "Existing titles can't be protected with 'create'"
1635 ),
1636 'missingtitle-createonly' => array(
1637 'code' => 'missingtitle-createonly',
1638 'info' => "Missing titles can only be protected with 'create'"
1639 ),
1640 'cantblock' => array( 'code' => 'cantblock',
1641 'info' => "You don't have permission to block users"
1642 ),
1643 'canthide' => array(
1644 'code' => 'canthide',
1645 'info' => "You don't have permission to hide user names from the block log"
1646 ),
1647 'cantblock-email' => array(
1648 'code' => 'cantblock-email',
1649 'info' => "You don't have permission to block users from sending email through the wiki"
1650 ),
1651 'unblock-notarget' => array(
1652 'code' => 'notarget',
1653 'info' => "Either the id or the user parameter must be set"
1654 ),
1655 'unblock-idanduser' => array(
1656 'code' => 'idanduser',
1657 'info' => "The id and user parameters can't be used together"
1658 ),
1659 'cantunblock' => array(
1660 'code' => 'permissiondenied',
1661 'info' => "You don't have permission to unblock users"
1662 ),
1663 'cannotundelete' => array(
1664 'code' => 'cantundelete',
1665 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1666 ),
1667 'permdenied-undelete' => array(
1668 'code' => 'permissiondenied',
1669 'info' => "You don't have permission to restore deleted revisions"
1670 ),
1671 'createonly-exists' => array(
1672 'code' => 'articleexists',
1673 'info' => "The article you tried to create has been created already"
1674 ),
1675 'nocreate-missing' => array(
1676 'code' => 'missingtitle',
1677 'info' => "The article you tried to edit doesn't exist"
1678 ),
1679 'nosuchrcid' => array(
1680 'code' => 'nosuchrcid',
1681 'info' => "There is no change with rcid \"\$1\""
1682 ),
1683 'protect-invalidaction' => array(
1684 'code' => 'protect-invalidaction',
1685 'info' => "Invalid protection type \"\$1\""
1686 ),
1687 'protect-invalidlevel' => array(
1688 'code' => 'protect-invalidlevel',
1689 'info' => "Invalid protection level \"\$1\""
1690 ),
1691 'toofewexpiries' => array(
1692 'code' => 'toofewexpiries',
1693 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1694 ),
1695 'cantimport' => array(
1696 'code' => 'cantimport',
1697 'info' => "You don't have permission to import pages"
1698 ),
1699 'cantimport-upload' => array(
1700 'code' => 'cantimport-upload',
1701 'info' => "You don't have permission to import uploaded pages"
1702 ),
1703 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1704 'importuploaderrorsize' => array(
1705 'code' => 'filetoobig',
1706 'info' => 'The file you uploaded is bigger than the maximum upload size'
1707 ),
1708 'importuploaderrorpartial' => array(
1709 'code' => 'partialupload',
1710 'info' => 'The file was only partially uploaded'
1711 ),
1712 'importuploaderrortemp' => array(
1713 'code' => 'notempdir',
1714 'info' => 'The temporary upload directory is missing'
1715 ),
1716 'importcantopen' => array(
1717 'code' => 'cantopenfile',
1718 'info' => "Couldn't open the uploaded file"
1719 ),
1720 'import-noarticle' => array(
1721 'code' => 'badinterwiki',
1722 'info' => 'Invalid interwiki title specified'
1723 ),
1724 'importbadinterwiki' => array(
1725 'code' => 'badinterwiki',
1726 'info' => 'Invalid interwiki title specified'
1727 ),
1728 'import-unknownerror' => array(
1729 'code' => 'import-unknownerror',
1730 'info' => "Unknown error on import: \"\$1\""
1731 ),
1732 'cantoverwrite-sharedfile' => array(
1733 'code' => 'cantoverwrite-sharedfile',
1734 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1735 ),
1736 'sharedfile-exists' => array(
1737 'code' => 'fileexists-sharedrepo-perm',
1738 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1739 ),
1740 'mustbeposted' => array(
1741 'code' => 'mustbeposted',
1742 'info' => "The \$1 module requires a POST request"
1743 ),
1744 'show' => array(
1745 'code' => 'show',
1746 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1747 ),
1748 'specialpage-cantexecute' => array(
1749 'code' => 'specialpage-cantexecute',
1750 'info' => "You don't have permission to view the results of this special page"
1751 ),
1752 'invalidoldimage' => array(
1753 'code' => 'invalidoldimage',
1754 'info' => 'The oldimage parameter has invalid format'
1755 ),
1756 'nodeleteablefile' => array(
1757 'code' => 'nodeleteablefile',
1758 'info' => 'No such old version of the file'
1759 ),
1760 'fileexists-forbidden' => array(
1761 'code' => 'fileexists-forbidden',
1762 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1763 ),
1764 'fileexists-shared-forbidden' => array(
1765 'code' => 'fileexists-shared-forbidden',
1766 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1767 ),
1768 'filerevert-badversion' => array(
1769 'code' => 'filerevert-badversion',
1770 'info' => 'There is no previous local version of this file with the provided timestamp.'
1771 ),
1772
1773 // ApiEditPage messages
1774 'noimageredirect-anon' => array(
1775 'code' => 'noimageredirect-anon',
1776 'info' => "Anonymous users can't create image redirects"
1777 ),
1778 'noimageredirect-logged' => array(
1779 'code' => 'noimageredirect',
1780 'info' => "You don't have permission to create image redirects"
1781 ),
1782 'spamdetected' => array(
1783 'code' => 'spamdetected',
1784 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1785 ),
1786 'contenttoobig' => array(
1787 'code' => 'contenttoobig',
1788 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1789 ),
1790 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1791 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1792 'wasdeleted' => array(
1793 'code' => 'pagedeleted',
1794 'info' => "The page has been deleted since you fetched its timestamp"
1795 ),
1796 'blankpage' => array(
1797 'code' => 'emptypage',
1798 'info' => "Creating new, empty pages is not allowed"
1799 ),
1800 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1801 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1802 'missingtext' => array(
1803 'code' => 'notext',
1804 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1805 ),
1806 'emptynewsection' => array(
1807 'code' => 'emptynewsection',
1808 'info' => 'Creating empty new sections is not possible.'
1809 ),
1810 'revwrongpage' => array(
1811 'code' => 'revwrongpage',
1812 'info' => "r\$1 is not a revision of \"\$2\""
1813 ),
1814 'undo-failure' => array(
1815 'code' => 'undofailure',
1816 'info' => 'Undo failed due to conflicting intermediate edits'
1817 ),
1818
1819 // Messages from WikiPage::doEit()
1820 'edit-hook-aborted' => array(
1821 'code' => 'edit-hook-aborted',
1822 'info' => "Your edit was aborted by an ArticleSave hook"
1823 ),
1824 'edit-gone-missing' => array(
1825 'code' => 'edit-gone-missing',
1826 'info' => "The page you tried to edit doesn't seem to exist anymore"
1827 ),
1828 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1829 'edit-already-exists' => array(
1830 'code' => 'edit-already-exists',
1831 'info' => 'It seems the page you tried to create already exist'
1832 ),
1833
1834 // uploadMsgs
1835 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1836 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1837 'uploaddisabled' => array(
1838 'code' => 'uploaddisabled',
1839 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1840 ),
1841 'copyuploaddisabled' => array(
1842 'code' => 'copyuploaddisabled',
1843 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1844 ),
1845 'copyuploadbaddomain' => array(
1846 'code' => 'copyuploadbaddomain',
1847 'info' => 'Uploads by URL are not allowed from this domain.'
1848 ),
1849 'copyuploadbadurl' => array(
1850 'code' => 'copyuploadbadurl',
1851 'info' => 'Upload not allowed from this URL.'
1852 ),
1853
1854 'filename-tooshort' => array(
1855 'code' => 'filename-tooshort',
1856 'info' => 'The filename is too short'
1857 ),
1858 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1859 'illegal-filename' => array(
1860 'code' => 'illegal-filename',
1861 'info' => 'The filename is not allowed'
1862 ),
1863 'filetype-missing' => array(
1864 'code' => 'filetype-missing',
1865 'info' => 'The file is missing an extension'
1866 ),
1867
1868 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1869 );
1870 // @codingStandardsIgnoreEnd
1871
1872 /**
1873 * Helper function for readonly errors
1874 */
1875 public function dieReadOnly() {
1876 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1877 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1878 array( 'readonlyreason' => wfReadOnlyReason() ) );
1879 }
1880
1881 /**
1882 * Output the error message related to a certain array
1883 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1884 */
1885 public function dieUsageMsg( $error ) {
1886 # most of the time we send a 1 element, so we might as well send it as
1887 # a string and make this an array here.
1888 if ( is_string( $error ) ) {
1889 $error = array( $error );
1890 }
1891 $parsed = $this->parseMsg( $error );
1892 $this->dieUsage( $parsed['info'], $parsed['code'] );
1893 }
1894
1895 /**
1896 * Will only set a warning instead of failing if the global $wgDebugAPI
1897 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1898 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1899 * @since 1.21
1900 */
1901 public function dieUsageMsgOrDebug( $error ) {
1902 global $wgDebugAPI;
1903 if ( $wgDebugAPI !== true ) {
1904 $this->dieUsageMsg( $error );
1905 }
1906
1907 if ( is_string( $error ) ) {
1908 $error = array( $error );
1909 }
1910
1911 $parsed = $this->parseMsg( $error );
1912 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1913 }
1914
1915 /**
1916 * Die with the $prefix.'badcontinue' error. This call is common enough to
1917 * make it into the base method.
1918 * @param $condition boolean will only die if this value is true
1919 * @since 1.21
1920 */
1921 protected function dieContinueUsageIf( $condition ) {
1922 if ( $condition ) {
1923 $this->dieUsage(
1924 'Invalid continue param. You should pass the original value returned by the previous query',
1925 'badcontinue' );
1926 }
1927 }
1928
1929 /**
1930 * Return the error message related to a certain array
1931 * @param array $error Element of a getUserPermissionsErrors()-style array
1932 * @return array('code' => code, 'info' => info)
1933 */
1934 public function parseMsg( $error ) {
1935 $error = (array)$error; // It seems strings sometimes make their way in here
1936 $key = array_shift( $error );
1937
1938 // Check whether the error array was nested
1939 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1940 if ( is_array( $key ) ) {
1941 $error = $key;
1942 $key = array_shift( $error );
1943 }
1944
1945 if ( isset( self::$messageMap[$key] ) ) {
1946 return array(
1947 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
1948 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
1949 );
1950 }
1951
1952 // If the key isn't present, throw an "unknown error"
1953 return $this->parseMsg( array( 'unknownerror', $key ) );
1954 }
1955
1956 /**
1957 * Internal code errors should be reported with this method
1958 * @param string $method Method or function name
1959 * @param string $message Error message
1960 * @throws MWException
1961 */
1962 protected static function dieDebug( $method, $message ) {
1963 throw new MWException( "Internal error in $method: $message" );
1964 }
1965
1966 /**
1967 * Indicates if this module needs maxlag to be checked
1968 * @return bool
1969 */
1970 public function shouldCheckMaxlag() {
1971 return true;
1972 }
1973
1974 /**
1975 * Indicates whether this module requires read rights
1976 * @return bool
1977 */
1978 public function isReadMode() {
1979 return true;
1980 }
1981
1982 /**
1983 * Indicates whether this module requires write mode
1984 * @return bool
1985 */
1986 public function isWriteMode() {
1987 return false;
1988 }
1989
1990 /**
1991 * Indicates whether this module must be called with a POST request
1992 * @return bool
1993 */
1994 public function mustBePosted() {
1995 return false;
1996 }
1997
1998 /**
1999 * Returns whether this module requires a token to execute
2000 * It is used to show possible errors in action=paraminfo
2001 * see bug 25248
2002 * @return bool
2003 */
2004 public function needsToken() {
2005 return false;
2006 }
2007
2008 /**
2009 * Returns the token salt if there is one,
2010 * '' if the module doesn't require a salt,
2011 * else false if the module doesn't need a token
2012 * You have also to override needsToken()
2013 * Value is passed to User::getEditToken
2014 * @return bool|string|array
2015 */
2016 public function getTokenSalt() {
2017 return false;
2018 }
2019
2020 /**
2021 * Gets the user for whom to get the watchlist
2022 *
2023 * @param $params array
2024 * @return User
2025 */
2026 public function getWatchlistUser( $params ) {
2027 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
2028 $user = User::newFromName( $params['owner'], false );
2029 if ( !( $user && $user->getId() ) ) {
2030 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
2031 }
2032 $token = $user->getOption( 'watchlisttoken' );
2033 if ( $token == '' || $token != $params['token'] ) {
2034 $this->dieUsage(
2035 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
2036 'bad_wltoken'
2037 );
2038 }
2039 } else {
2040 if ( !$this->getUser()->isLoggedIn() ) {
2041 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
2042 }
2043 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
2044 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
2045 }
2046 $user = $this->getUser();
2047 }
2048
2049 return $user;
2050 }
2051
2052 /**
2053 * @return bool|string|array Returns a false if the module has no help URL,
2054 * else returns a (array of) string
2055 */
2056 public function getHelpUrls() {
2057 return false;
2058 }
2059
2060 /**
2061 * Returns a list of all possible errors returned by the module
2062 *
2063 * Don't call this function directly: use getFinalPossibleErrors() to allow
2064 * hooks to modify parameters as needed.
2065 *
2066 * @return array in the format of array( key, param1, param2, ... )
2067 * or array( 'code' => ..., 'info' => ... )
2068 */
2069 public function getPossibleErrors() {
2070 $ret = array();
2071
2072 $params = $this->getFinalParams();
2073 if ( $params ) {
2074 foreach ( $params as $paramName => $paramSettings ) {
2075 if ( isset( $paramSettings[ApiBase::PARAM_REQUIRED] )
2076 && $paramSettings[ApiBase::PARAM_REQUIRED]
2077 ) {
2078 $ret[] = array( 'missingparam', $paramName );
2079 }
2080 }
2081 if ( array_key_exists( 'continue', $params ) ) {
2082 $ret[] = array(
2083 'code' => 'badcontinue',
2084 'info' => 'Invalid continue param. You should pass the ' .
2085 'original value returned by the previous query'
2086 );
2087 }
2088 }
2089
2090 if ( $this->mustBePosted() ) {
2091 $ret[] = array( 'mustbeposted', $this->getModuleName() );
2092 }
2093
2094 if ( $this->isReadMode() ) {
2095 $ret[] = array( 'readrequired' );
2096 }
2097
2098 if ( $this->isWriteMode() ) {
2099 $ret[] = array( 'writerequired' );
2100 $ret[] = array( 'writedisabled' );
2101 }
2102
2103 if ( $this->needsToken() ) {
2104 if ( !isset( $params['token'][ApiBase::PARAM_REQUIRED] )
2105 || !$params['token'][ApiBase::PARAM_REQUIRED]
2106 ) {
2107 // Add token as possible missing parameter, if not already done
2108 $ret[] = array( 'missingparam', 'token' );
2109 }
2110 $ret[] = array( 'sessionfailure' );
2111 }
2112
2113 return $ret;
2114 }
2115
2116 /**
2117 * Get final list of possible errors, after hooks have had a chance to
2118 * tweak it as needed.
2119 *
2120 * @return array
2121 * @since 1.22
2122 */
2123 public function getFinalPossibleErrors() {
2124 $possibleErrors = $this->getPossibleErrors();
2125 wfRunHooks( 'APIGetPossibleErrors', array( $this, &$possibleErrors ) );
2126
2127 return $possibleErrors;
2128 }
2129
2130 /**
2131 * Parses a list of errors into a standardised format
2132 * @param array $errors List of errors. Items can be in the for
2133 * array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
2134 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
2135 */
2136 public function parseErrors( $errors ) {
2137 $ret = array();
2138
2139 foreach ( $errors as $row ) {
2140 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
2141 $ret[] = $row;
2142 } else {
2143 $ret[] = $this->parseMsg( $row );
2144 }
2145 }
2146
2147 return $ret;
2148 }
2149
2150 /**
2151 * Profiling: total module execution time
2152 */
2153 private $mTimeIn = 0, $mModuleTime = 0;
2154
2155 /**
2156 * Start module profiling
2157 */
2158 public function profileIn() {
2159 if ( $this->mTimeIn !== 0 ) {
2160 ApiBase::dieDebug( __METHOD__, 'Called twice without calling profileOut()' );
2161 }
2162 $this->mTimeIn = microtime( true );
2163 wfProfileIn( $this->getModuleProfileName() );
2164 }
2165
2166 /**
2167 * End module profiling
2168 */
2169 public function profileOut() {
2170 if ( $this->mTimeIn === 0 ) {
2171 ApiBase::dieDebug( __METHOD__, 'Called without calling profileIn() first' );
2172 }
2173 if ( $this->mDBTimeIn !== 0 ) {
2174 ApiBase::dieDebug(
2175 __METHOD__,
2176 'Must be called after database profiling is done with profileDBOut()'
2177 );
2178 }
2179
2180 $this->mModuleTime += microtime( true ) - $this->mTimeIn;
2181 $this->mTimeIn = 0;
2182 wfProfileOut( $this->getModuleProfileName() );
2183 }
2184
2185 /**
2186 * When modules crash, sometimes it is needed to do a profileOut() regardless
2187 * of the profiling state the module was in. This method does such cleanup.
2188 */
2189 public function safeProfileOut() {
2190 if ( $this->mTimeIn !== 0 ) {
2191 if ( $this->mDBTimeIn !== 0 ) {
2192 $this->profileDBOut();
2193 }
2194 $this->profileOut();
2195 }
2196 }
2197
2198 /**
2199 * Total time the module was executed
2200 * @return float
2201 */
2202 public function getProfileTime() {
2203 if ( $this->mTimeIn !== 0 ) {
2204 ApiBase::dieDebug( __METHOD__, 'Called without calling profileOut() first' );
2205 }
2206
2207 return $this->mModuleTime;
2208 }
2209
2210 /**
2211 * Profiling: database execution time
2212 */
2213 private $mDBTimeIn = 0, $mDBTime = 0;
2214
2215 /**
2216 * Start module profiling
2217 */
2218 public function profileDBIn() {
2219 if ( $this->mTimeIn === 0 ) {
2220 ApiBase::dieDebug(
2221 __METHOD__,
2222 'Must be called while profiling the entire module with profileIn()'
2223 );
2224 }
2225 if ( $this->mDBTimeIn !== 0 ) {
2226 ApiBase::dieDebug( __METHOD__, 'Called twice without calling profileDBOut()' );
2227 }
2228 $this->mDBTimeIn = microtime( true );
2229 wfProfileIn( $this->getModuleProfileName( true ) );
2230 }
2231
2232 /**
2233 * End database profiling
2234 */
2235 public function profileDBOut() {
2236 if ( $this->mTimeIn === 0 ) {
2237 ApiBase::dieDebug( __METHOD__, 'Must be called while profiling ' .
2238 'the entire module with profileIn()' );
2239 }
2240 if ( $this->mDBTimeIn === 0 ) {
2241 ApiBase::dieDebug( __METHOD__, 'Called without calling profileDBIn() first' );
2242 }
2243
2244 $time = microtime( true ) - $this->mDBTimeIn;
2245 $this->mDBTimeIn = 0;
2246
2247 $this->mDBTime += $time;
2248 $this->getMain()->mDBTime += $time;
2249 wfProfileOut( $this->getModuleProfileName( true ) );
2250 }
2251
2252 /**
2253 * Total time the module used the database
2254 * @return float
2255 */
2256 public function getProfileDBTime() {
2257 if ( $this->mDBTimeIn !== 0 ) {
2258 ApiBase::dieDebug( __METHOD__, 'Called without calling profileDBOut() first' );
2259 }
2260
2261 return $this->mDBTime;
2262 }
2263
2264 /**
2265 * Gets a default slave database connection object
2266 * @return DatabaseBase
2267 */
2268 protected function getDB() {
2269 if ( !isset( $this->mSlaveDB ) ) {
2270 $this->profileDBIn();
2271 $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
2272 $this->profileDBOut();
2273 }
2274
2275 return $this->mSlaveDB;
2276 }
2277
2278 /**
2279 * Debugging function that prints a value and an optional backtrace
2280 * @param $value mixed Value to print
2281 * @param string $name Description of the printed value
2282 * @param bool $backtrace If true, print a backtrace
2283 */
2284 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
2285 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
2286 var_export( $value );
2287 if ( $backtrace ) {
2288 print "\n" . wfBacktrace();
2289 }
2290 print "\n</pre>\n";
2291 }
2292 }