Add PreferencesFormPreSave hook
[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 * Die if none of a certain set of parameters is set and not false.
806 * @param array $params of parameter names
807 */
808 public function requireAtLeastOneParameter( $params ) {
809 $required = func_get_args();
810 array_shift( $required );
811 $p = $this->getModulePrefix();
812
813 $intersection = array_intersect( array_keys( array_filter( $params,
814 array( $this, "parameterNotEmpty" ) ) ), $required );
815
816 if ( count( $intersection ) == 0 ) {
817 $this->dieUsage( "At least one of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
818 }
819 }
820
821 /**
822 * Generates the possible errors requireAtLeastOneParameter() can die with
823 *
824 * @param $params array
825 * @return array
826 */
827 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
828 $p = $this->getModulePrefix();
829 $params = implode( ", {$p}", $params );
830
831 return array(
832 array( 'code' => "{$p}missingparam", 'info' => "At least one of the parameters {$p}{$params} is required" ),
833 );
834 }
835
836 /**
837 * @param $params array
838 * @param bool|string $load Whether load the object's state from the database:
839 * - false: don't load (if the pageid is given, it will still be loaded)
840 * - 'fromdb': load from a slave database
841 * - 'fromdbmaster': load from the master database
842 * @return WikiPage
843 */
844 public function getTitleOrPageId( $params, $load = false ) {
845 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
846
847 $pageObj = null;
848 if ( isset( $params['title'] ) ) {
849 $titleObj = Title::newFromText( $params['title'] );
850 if ( !$titleObj || $titleObj->isExternal() ) {
851 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
852 }
853 if ( !$titleObj->canExist() ) {
854 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
855 }
856 $pageObj = WikiPage::factory( $titleObj );
857 if ( $load !== false ) {
858 $pageObj->loadPageData( $load );
859 }
860 } elseif ( isset( $params['pageid'] ) ) {
861 if ( $load === false ) {
862 $load = 'fromdb';
863 }
864 $pageObj = WikiPage::newFromID( $params['pageid'], $load );
865 if ( !$pageObj ) {
866 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
867 }
868 }
869
870 return $pageObj;
871 }
872
873 /**
874 * @return array
875 */
876 public function getTitleOrPageIdErrorMessage() {
877 return array_merge(
878 $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ),
879 array(
880 array( 'invalidtitle', 'title' ),
881 array( 'nosuchpageid', 'pageid' ),
882 )
883 );
884 }
885
886 /**
887 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
888 *
889 * @param $x object Parameter to check is not null/false
890 * @return bool
891 */
892 private function parameterNotEmpty( $x ) {
893 return !is_null( $x ) && $x !== false;
894 }
895
896 /**
897 * Return true if we're to watch the page, false if not, null if no change.
898 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
899 * @param $titleObj Title the page under consideration
900 * @param string $userOption The user option to consider when $watchlist=preferences.
901 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
902 * @return bool
903 */
904 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
905
906 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem::IGNORE_USER_RIGHTS );
907
908 switch ( $watchlist ) {
909 case 'watch':
910 return true;
911
912 case 'unwatch':
913 return false;
914
915 case 'preferences':
916 # If the user is already watching, don't bother checking
917 if ( $userWatching ) {
918 return true;
919 }
920 # If no user option was passed, use watchdefault and watchcreations
921 if ( is_null( $userOption ) ) {
922 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
923 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
924 }
925
926 # Watch the article based on the user preference
927 return $this->getUser()->getBoolOption( $userOption );
928
929 case 'nochange':
930 return $userWatching;
931
932 default:
933 return $userWatching;
934 }
935 }
936
937 /**
938 * Set a watch (or unwatch) based the based on a watchlist parameter.
939 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
940 * @param $titleObj Title the article's title to change
941 * @param string $userOption The user option to consider when $watch=preferences
942 */
943 protected function setWatch( $watch, $titleObj, $userOption = null ) {
944 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
945 if ( $value === null ) {
946 return;
947 }
948
949 WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
950 }
951
952 /**
953 * Using the settings determine the value for the given parameter
954 *
955 * @param string $paramName parameter name
956 * @param array|mixed $paramSettings default value or an array of settings
957 * using PARAM_* constants.
958 * @param $parseLimit Boolean: parse limit?
959 * @return mixed Parameter value
960 */
961 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
962 // Some classes may decide to change parameter names
963 $encParamName = $this->encodeParamName( $paramName );
964
965 if ( !is_array( $paramSettings ) ) {
966 $default = $paramSettings;
967 $multi = false;
968 $type = gettype( $paramSettings );
969 $dupes = false;
970 $deprecated = false;
971 $required = false;
972 } else {
973 $default = isset( $paramSettings[self::PARAM_DFLT] )
974 ? $paramSettings[self::PARAM_DFLT]
975 : null;
976 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
977 ? $paramSettings[self::PARAM_ISMULTI]
978 : false;
979 $type = isset( $paramSettings[self::PARAM_TYPE] )
980 ? $paramSettings[self::PARAM_TYPE]
981 : null;
982 $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] )
983 ? $paramSettings[self::PARAM_ALLOW_DUPLICATES]
984 : false;
985 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] )
986 ? $paramSettings[self::PARAM_DEPRECATED]
987 : false;
988 $required = isset( $paramSettings[self::PARAM_REQUIRED] )
989 ? $paramSettings[self::PARAM_REQUIRED]
990 : false;
991
992 // When type is not given, and no choices, the type is the same as $default
993 if ( !isset( $type ) ) {
994 if ( isset( $default ) ) {
995 $type = gettype( $default );
996 } else {
997 $type = 'NULL'; // allow everything
998 }
999 }
1000 }
1001
1002 if ( $type == 'boolean' ) {
1003 if ( isset( $default ) && $default !== false ) {
1004 // Having a default value of anything other than 'false' is not allowed
1005 ApiBase::dieDebug(
1006 __METHOD__,
1007 "Boolean param $encParamName's default is set to '$default'. " .
1008 "Boolean parameters must default to false."
1009 );
1010 }
1011
1012 $value = $this->getMain()->getCheck( $encParamName );
1013 } elseif ( $type == 'upload' ) {
1014 if ( isset( $default ) ) {
1015 // Having a default value is not allowed
1016 ApiBase::dieDebug(
1017 __METHOD__,
1018 "File upload param $encParamName's default is set to " .
1019 "'$default'. File upload parameters may not have a default." );
1020 }
1021 if ( $multi ) {
1022 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1023 }
1024 $value = $this->getMain()->getUpload( $encParamName );
1025 if ( !$value->exists() ) {
1026 // This will get the value without trying to normalize it
1027 // (because trying to normalize a large binary file
1028 // accidentally uploaded as a field fails spectacularly)
1029 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1030 if ( $value !== null ) {
1031 $this->dieUsage(
1032 "File upload param $encParamName is not a file upload; " .
1033 "be sure to use multipart/form-data for your POST and include " .
1034 "a filename in the Content-Disposition header.",
1035 "badupload_{$encParamName}"
1036 );
1037 }
1038 }
1039 } else {
1040 $value = $this->getMain()->getVal( $encParamName, $default );
1041
1042 if ( isset( $value ) && $type == 'namespace' ) {
1043 $type = MWNamespace::getValidNamespaces();
1044 }
1045 }
1046
1047 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
1048 $value = $this->parseMultiValue(
1049 $encParamName,
1050 $value,
1051 $multi,
1052 is_array( $type ) ? $type : null
1053 );
1054 }
1055
1056 // More validation only when choices were not given
1057 // choices were validated in parseMultiValue()
1058 if ( isset( $value ) ) {
1059 if ( !is_array( $type ) ) {
1060 switch ( $type ) {
1061 case 'NULL': // nothing to do
1062 break;
1063 case 'string':
1064 if ( $required && $value === '' ) {
1065 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1066 }
1067 break;
1068 case 'integer': // Force everything using intval() and optionally validate limits
1069 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
1070 $max = isset( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
1071 $enforceLimits = isset( $paramSettings[self::PARAM_RANGE_ENFORCE] )
1072 ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
1073
1074 if ( is_array( $value ) ) {
1075 $value = array_map( 'intval', $value );
1076 if ( !is_null( $min ) || !is_null( $max ) ) {
1077 foreach ( $value as &$v ) {
1078 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1079 }
1080 }
1081 } else {
1082 $value = intval( $value );
1083 if ( !is_null( $min ) || !is_null( $max ) ) {
1084 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1085 }
1086 }
1087 break;
1088 case 'limit':
1089 if ( !$parseLimit ) {
1090 // Don't do any validation whatsoever
1091 break;
1092 }
1093 if ( !isset( $paramSettings[self::PARAM_MAX] )
1094 || !isset( $paramSettings[self::PARAM_MAX2] )
1095 ) {
1096 ApiBase::dieDebug(
1097 __METHOD__,
1098 "MAX1 or MAX2 are not defined for the limit $encParamName"
1099 );
1100 }
1101 if ( $multi ) {
1102 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1103 }
1104 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
1105 if ( $value == 'max' ) {
1106 $value = $this->getMain()->canApiHighLimits()
1107 ? $paramSettings[self::PARAM_MAX2]
1108 : $paramSettings[self::PARAM_MAX];
1109 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
1110 } else {
1111 $value = intval( $value );
1112 $this->validateLimit(
1113 $paramName,
1114 $value,
1115 $min,
1116 $paramSettings[self::PARAM_MAX],
1117 $paramSettings[self::PARAM_MAX2]
1118 );
1119 }
1120 break;
1121 case 'boolean':
1122 if ( $multi ) {
1123 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1124 }
1125 break;
1126 case 'timestamp':
1127 if ( is_array( $value ) ) {
1128 foreach ( $value as $key => $val ) {
1129 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1130 }
1131 } else {
1132 $value = $this->validateTimestamp( $value, $encParamName );
1133 }
1134 break;
1135 case 'user':
1136 if ( is_array( $value ) ) {
1137 foreach ( $value as $key => $val ) {
1138 $value[$key] = $this->validateUser( $val, $encParamName );
1139 }
1140 } else {
1141 $value = $this->validateUser( $value, $encParamName );
1142 }
1143 break;
1144 case 'upload': // nothing to do
1145 break;
1146 default:
1147 ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
1148 }
1149 }
1150
1151 // Throw out duplicates if requested
1152 if ( !$dupes && is_array( $value ) ) {
1153 $value = array_unique( $value );
1154 }
1155
1156 // Set a warning if a deprecated parameter has been passed
1157 if ( $deprecated && $value !== false ) {
1158 $this->setWarning( "The $encParamName parameter has been deprecated." );
1159 }
1160 } elseif ( $required ) {
1161 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1162 }
1163
1164 return $value;
1165 }
1166
1167 /**
1168 * Return an array of values that were given in a 'a|b|c' notation,
1169 * after it optionally validates them against the list allowed values.
1170 *
1171 * @param string $valueName The name of the parameter (for error
1172 * reporting)
1173 * @param $value mixed The value being parsed
1174 * @param bool $allowMultiple Can $value contain more than one value
1175 * separated by '|'?
1176 * @param $allowedValues mixed An array of values to check against. If
1177 * null, all values are accepted.
1178 * @return mixed (allowMultiple ? an_array_of_values : a_single_value)
1179 */
1180 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1181 if ( trim( $value ) === '' && $allowMultiple ) {
1182 return array();
1183 }
1184
1185 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1186 // because it unstubs $wgUser
1187 $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 );
1188 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits()
1189 ? self::LIMIT_SML2
1190 : self::LIMIT_SML1;
1191
1192 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
1193 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1194 "the limit is $sizeLimit" );
1195 }
1196
1197 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1198 // Bug 33482 - Allow entries with | in them for non-multiple values
1199 if ( in_array( $value, $allowedValues, true ) ) {
1200 return $value;
1201 }
1202
1203 $possibleValues = is_array( $allowedValues )
1204 ? "of '" . implode( "', '", $allowedValues ) . "'"
1205 : '';
1206 $this->dieUsage(
1207 "Only one $possibleValues is allowed for parameter '$valueName'",
1208 "multival_$valueName"
1209 );
1210 }
1211
1212 if ( is_array( $allowedValues ) ) {
1213 // Check for unknown values
1214 $unknown = array_diff( $valuesList, $allowedValues );
1215 if ( count( $unknown ) ) {
1216 if ( $allowMultiple ) {
1217 $s = count( $unknown ) > 1 ? 's' : '';
1218 $vals = implode( ", ", $unknown );
1219 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1220 } else {
1221 $this->dieUsage(
1222 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1223 "unknown_$valueName"
1224 );
1225 }
1226 }
1227 // Now throw them out
1228 $valuesList = array_intersect( $valuesList, $allowedValues );
1229 }
1230
1231 return $allowMultiple ? $valuesList : $valuesList[0];
1232 }
1233
1234 /**
1235 * Validate the value against the minimum and user/bot maximum limits.
1236 * Prints usage info on failure.
1237 * @param string $paramName Parameter name
1238 * @param int $value Parameter value
1239 * @param int|null $min Minimum value
1240 * @param int|null $max Maximum value for users
1241 * @param int $botMax Maximum value for sysops/bots
1242 * @param $enforceLimits Boolean Whether to enforce (die) if value is outside limits
1243 */
1244 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1245 if ( !is_null( $min ) && $value < $min ) {
1246
1247 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1248 $this->warnOrDie( $msg, $enforceLimits );
1249 $value = $min;
1250 }
1251
1252 // Minimum is always validated, whereas maximum is checked only if not
1253 // running in internal call mode
1254 if ( $this->getMain()->isInternalMode() ) {
1255 return;
1256 }
1257
1258 // Optimization: do not check user's bot status unless really needed -- skips db query
1259 // assumes $botMax >= $max
1260 if ( !is_null( $max ) && $value > $max ) {
1261 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1262 if ( $value > $botMax ) {
1263 $msg = $this->encodeParamName( $paramName ) .
1264 " may not be over $botMax (set to $value) for bots or sysops";
1265 $this->warnOrDie( $msg, $enforceLimits );
1266 $value = $botMax;
1267 }
1268 } else {
1269 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1270 $this->warnOrDie( $msg, $enforceLimits );
1271 $value = $max;
1272 }
1273 }
1274 }
1275
1276 /**
1277 * Validate and normalize of parameters of type 'timestamp'
1278 * @param string $value Parameter value
1279 * @param string $encParamName Parameter name
1280 * @return string Validated and normalized parameter
1281 */
1282 function validateTimestamp( $value, $encParamName ) {
1283 $unixTimestamp = wfTimestamp( TS_UNIX, $value );
1284 if ( $unixTimestamp === false ) {
1285 $this->dieUsage(
1286 "Invalid value '$value' for timestamp parameter $encParamName",
1287 "badtimestamp_{$encParamName}"
1288 );
1289 }
1290
1291 return wfTimestamp( TS_MW, $unixTimestamp );
1292 }
1293
1294 /**
1295 * Validate and normalize of parameters of type 'user'
1296 * @param string $value Parameter value
1297 * @param string $encParamName Parameter name
1298 * @return string Validated and normalized parameter
1299 */
1300 private function validateUser( $value, $encParamName ) {
1301 $title = Title::makeTitleSafe( NS_USER, $value );
1302 if ( $title === null ) {
1303 $this->dieUsage(
1304 "Invalid value '$value' for user parameter $encParamName",
1305 "baduser_{$encParamName}"
1306 );
1307 }
1308
1309 return $title->getText();
1310 }
1311
1312 /**
1313 * Adds a warning to the output, else dies
1314 *
1315 * @param $msg String Message to show as a warning, or error message if dying
1316 * @param $enforceLimits Boolean Whether this is an enforce (die)
1317 */
1318 private function warnOrDie( $msg, $enforceLimits = false ) {
1319 if ( $enforceLimits ) {
1320 $this->dieUsage( $msg, 'integeroutofrange' );
1321 }
1322
1323 $this->setWarning( $msg );
1324 }
1325
1326 /**
1327 * Truncate an array to a certain length.
1328 * @param array $arr Array to truncate
1329 * @param int $limit Maximum length
1330 * @return bool True if the array was truncated, false otherwise
1331 */
1332 public static function truncateArray( &$arr, $limit ) {
1333 $modified = false;
1334 while ( count( $arr ) > $limit ) {
1335 array_pop( $arr );
1336 $modified = true;
1337 }
1338
1339 return $modified;
1340 }
1341
1342 /**
1343 * Throw a UsageException, which will (if uncaught) call the main module's
1344 * error handler and die with an error message.
1345 *
1346 * @param string $description One-line human-readable description of the
1347 * error condition, e.g., "The API requires a valid action parameter"
1348 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1349 * automated identification of the error, e.g., 'unknown_action'
1350 * @param int $httpRespCode HTTP response code
1351 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1352 * @throws UsageException
1353 */
1354 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1355 Profiler::instance()->close();
1356 throw new UsageException(
1357 $description,
1358 $this->encodeParamName( $errorCode ),
1359 $httpRespCode,
1360 $extradata
1361 );
1362 }
1363
1364 /**
1365 * Throw a UsageException based on the errors in the Status object.
1366 *
1367 * @since 1.22
1368 * @param Status $status Status object
1369 * @throws MWException
1370 */
1371 public function dieStatus( $status ) {
1372 if ( $status->isGood() ) {
1373 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1374 }
1375
1376 $errors = $status->getErrorsArray();
1377 if ( !$errors ) {
1378 // No errors? Assume the warnings should be treated as errors
1379 $errors = $status->getWarningsArray();
1380 }
1381 if ( !$errors ) {
1382 // Still no errors? Punt
1383 $errors = array( array( 'unknownerror-nocode' ) );
1384 }
1385
1386 // Cannot use dieUsageMsg() because extensions might return custom
1387 // error messages.
1388 if ( $errors[0] instanceof Message ) {
1389 $msg = $errors[0];
1390 $code = $msg->getKey();
1391 } else {
1392 $code = array_shift( $errors[0] );
1393 $msg = wfMessage( $code, $errors[0] );
1394 }
1395 if ( isset( ApiBase::$messageMap[$code] ) ) {
1396 // Translate message to code, for backwards compatability
1397 $code = ApiBase::$messageMap[$code]['code'];
1398 }
1399 $this->dieUsage( $msg->inLanguage( 'en' )->useDatabase( false )->plain(), $code );
1400 }
1401
1402 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1403 /**
1404 * Array that maps message keys to error messages. $1 and friends are replaced.
1405 */
1406 public static $messageMap = array(
1407 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1408 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1409 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1410
1411 // Messages from Title::getUserPermissionsErrors()
1412 'ns-specialprotected' => array(
1413 'code' => 'unsupportednamespace',
1414 'info' => "Pages in the Special namespace can't be edited"
1415 ),
1416 'protectedinterface' => array(
1417 'code' => 'protectednamespace-interface',
1418 'info' => "You're not allowed to edit interface messages"
1419 ),
1420 'namespaceprotected' => array(
1421 'code' => 'protectednamespace',
1422 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1423 ),
1424 'customcssprotected' => array(
1425 'code' => 'customcssprotected',
1426 'info' => "You're not allowed to edit custom CSS pages"
1427 ),
1428 'customjsprotected' => array(
1429 'code' => 'customjsprotected',
1430 'info' => "You're not allowed to edit custom JavaScript pages"
1431 ),
1432 'cascadeprotected' => array(
1433 'code' => 'cascadeprotected',
1434 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1435 ),
1436 'protectedpagetext' => array(
1437 'code' => 'protectedpage',
1438 'info' => "The \"\$1\" right is required to edit this page"
1439 ),
1440 'protect-cantedit' => array(
1441 'code' => 'cantedit',
1442 'info' => "You can't protect this page because you can't edit it"
1443 ),
1444 'badaccess-group0' => array(
1445 'code' => 'permissiondenied',
1446 'info' => "Permission denied"
1447 ), // Generic permission denied message
1448 'badaccess-groups' => array(
1449 'code' => 'permissiondenied',
1450 'info' => "Permission denied"
1451 ),
1452 'titleprotected' => array(
1453 'code' => 'protectedtitle',
1454 'info' => "This title has been protected from creation"
1455 ),
1456 'nocreate-loggedin' => array(
1457 'code' => 'cantcreate',
1458 'info' => "You don't have permission to create new pages"
1459 ),
1460 'nocreatetext' => array(
1461 'code' => 'cantcreate-anon',
1462 'info' => "Anonymous users can't create new pages"
1463 ),
1464 'movenologintext' => array(
1465 'code' => 'cantmove-anon',
1466 'info' => "Anonymous users can't move pages"
1467 ),
1468 'movenotallowed' => array(
1469 'code' => 'cantmove',
1470 'info' => "You don't have permission to move pages"
1471 ),
1472 'confirmedittext' => array(
1473 'code' => 'confirmemail',
1474 'info' => "You must confirm your email address before you can edit"
1475 ),
1476 'blockedtext' => array(
1477 'code' => 'blocked',
1478 'info' => "You have been blocked from editing"
1479 ),
1480 'autoblockedtext' => array(
1481 'code' => 'autoblocked',
1482 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1483 ),
1484
1485 // Miscellaneous interface messages
1486 'actionthrottledtext' => array(
1487 'code' => 'ratelimited',
1488 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1489 ),
1490 'alreadyrolled' => array(
1491 'code' => 'alreadyrolled',
1492 'info' => "The page you tried to rollback was already rolled back"
1493 ),
1494 'cantrollback' => array(
1495 'code' => 'onlyauthor',
1496 'info' => "The page you tried to rollback only has one author"
1497 ),
1498 'readonlytext' => array(
1499 'code' => 'readonly',
1500 'info' => "The wiki is currently in read-only mode"
1501 ),
1502 'sessionfailure' => array(
1503 'code' => 'badtoken',
1504 'info' => "Invalid token" ),
1505 'cannotdelete' => array(
1506 'code' => 'cantdelete',
1507 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1508 ),
1509 'notanarticle' => array(
1510 'code' => 'missingtitle',
1511 'info' => "The page you requested doesn't exist"
1512 ),
1513 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1514 ),
1515 'immobile_namespace' => array(
1516 'code' => 'immobilenamespace',
1517 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1518 ),
1519 'articleexists' => array(
1520 'code' => 'articleexists',
1521 'info' => "The destination article already exists and is not a redirect to the source article"
1522 ),
1523 'protectedpage' => array(
1524 'code' => 'protectedpage',
1525 'info' => "You don't have permission to perform this move"
1526 ),
1527 'hookaborted' => array(
1528 'code' => 'hookaborted',
1529 'info' => "The modification you tried to make was aborted by an extension hook"
1530 ),
1531 'cantmove-titleprotected' => array(
1532 'code' => 'protectedtitle',
1533 'info' => "The destination article has been protected from creation"
1534 ),
1535 'imagenocrossnamespace' => array(
1536 'code' => 'nonfilenamespace',
1537 'info' => "Can't move a file to a non-file namespace"
1538 ),
1539 'imagetypemismatch' => array(
1540 'code' => 'filetypemismatch',
1541 'info' => "The new file extension doesn't match its type"
1542 ),
1543 // 'badarticleerror' => shouldn't happen
1544 // 'badtitletext' => shouldn't happen
1545 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1546 'range_block_disabled' => array(
1547 'code' => 'rangedisabled',
1548 'info' => "Blocking IP ranges has been disabled"
1549 ),
1550 'nosuchusershort' => array(
1551 'code' => 'nosuchuser',
1552 'info' => "The user you specified doesn't exist"
1553 ),
1554 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1555 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1556 'ipb_already_blocked' => array(
1557 'code' => 'alreadyblocked',
1558 'info' => "The user you tried to block was already blocked"
1559 ),
1560 'ipb_blocked_as_range' => array(
1561 'code' => 'blockedasrange',
1562 '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."
1563 ),
1564 'ipb_cant_unblock' => array(
1565 'code' => 'cantunblock',
1566 'info' => "The block you specified was not found. It may have been unblocked already"
1567 ),
1568 'mailnologin' => array(
1569 'code' => 'cantsend',
1570 '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"
1571 ),
1572 'ipbblocked' => array(
1573 'code' => 'ipbblocked',
1574 'info' => 'You cannot block or unblock users while you are yourself blocked'
1575 ),
1576 'ipbnounblockself' => array(
1577 'code' => 'ipbnounblockself',
1578 'info' => 'You are not allowed to unblock yourself'
1579 ),
1580 'usermaildisabled' => array(
1581 'code' => 'usermaildisabled',
1582 'info' => "User email has been disabled"
1583 ),
1584 'blockedemailuser' => array(
1585 'code' => 'blockedfrommail',
1586 'info' => "You have been blocked from sending email"
1587 ),
1588 'notarget' => array(
1589 'code' => 'notarget',
1590 'info' => "You have not specified a valid target for this action"
1591 ),
1592 'noemail' => array(
1593 'code' => 'noemail',
1594 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1595 ),
1596 'rcpatroldisabled' => array(
1597 'code' => 'patroldisabled',
1598 'info' => "Patrolling is disabled on this wiki"
1599 ),
1600 'markedaspatrollederror-noautopatrol' => array(
1601 'code' => 'noautopatrol',
1602 'info' => "You don't have permission to patrol your own changes"
1603 ),
1604 'delete-toobig' => array(
1605 'code' => 'bigdelete',
1606 'info' => "You can't delete this page because it has more than \$1 revisions"
1607 ),
1608 'movenotallowedfile' => array(
1609 'code' => 'cantmovefile',
1610 'info' => "You don't have permission to move files"
1611 ),
1612 'userrights-no-interwiki' => array(
1613 'code' => 'nointerwikiuserrights',
1614 'info' => "You don't have permission to change user rights on other wikis"
1615 ),
1616 'userrights-nodatabase' => array(
1617 'code' => 'nosuchdatabase',
1618 'info' => "Database \"\$1\" does not exist or is not local"
1619 ),
1620 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1621 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1622 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1623 'import-rootpage-invalid' => array(
1624 'code' => 'import-rootpage-invalid',
1625 'info' => 'Root page is an invalid title'
1626 ),
1627 'import-rootpage-nosubpage' => array(
1628 'code' => 'import-rootpage-nosubpage',
1629 'info' => 'Namespace "$1" of the root page does not allow subpages'
1630 ),
1631
1632 // API-specific messages
1633 'readrequired' => array(
1634 'code' => 'readapidenied',
1635 'info' => "You need read permission to use this module"
1636 ),
1637 'writedisabled' => array(
1638 'code' => 'noapiwrite',
1639 '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"
1640 ),
1641 'writerequired' => array(
1642 'code' => 'writeapidenied',
1643 'info' => "You're not allowed to edit this wiki through the API"
1644 ),
1645 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1646 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1647 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1648 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1649 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1650 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1651 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1652 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1653 'create-titleexists' => array(
1654 'code' => 'create-titleexists',
1655 'info' => "Existing titles can't be protected with 'create'"
1656 ),
1657 'missingtitle-createonly' => array(
1658 'code' => 'missingtitle-createonly',
1659 'info' => "Missing titles can only be protected with 'create'"
1660 ),
1661 'cantblock' => array( 'code' => 'cantblock',
1662 'info' => "You don't have permission to block users"
1663 ),
1664 'canthide' => array(
1665 'code' => 'canthide',
1666 'info' => "You don't have permission to hide user names from the block log"
1667 ),
1668 'cantblock-email' => array(
1669 'code' => 'cantblock-email',
1670 'info' => "You don't have permission to block users from sending email through the wiki"
1671 ),
1672 'unblock-notarget' => array(
1673 'code' => 'notarget',
1674 'info' => "Either the id or the user parameter must be set"
1675 ),
1676 'unblock-idanduser' => array(
1677 'code' => 'idanduser',
1678 'info' => "The id and user parameters can't be used together"
1679 ),
1680 'cantunblock' => array(
1681 'code' => 'permissiondenied',
1682 'info' => "You don't have permission to unblock users"
1683 ),
1684 'cannotundelete' => array(
1685 'code' => 'cantundelete',
1686 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1687 ),
1688 'permdenied-undelete' => array(
1689 'code' => 'permissiondenied',
1690 'info' => "You don't have permission to restore deleted revisions"
1691 ),
1692 'createonly-exists' => array(
1693 'code' => 'articleexists',
1694 'info' => "The article you tried to create has been created already"
1695 ),
1696 'nocreate-missing' => array(
1697 'code' => 'missingtitle',
1698 'info' => "The article you tried to edit doesn't exist"
1699 ),
1700 'nosuchrcid' => array(
1701 'code' => 'nosuchrcid',
1702 'info' => "There is no change with rcid \"\$1\""
1703 ),
1704 'protect-invalidaction' => array(
1705 'code' => 'protect-invalidaction',
1706 'info' => "Invalid protection type \"\$1\""
1707 ),
1708 'protect-invalidlevel' => array(
1709 'code' => 'protect-invalidlevel',
1710 'info' => "Invalid protection level \"\$1\""
1711 ),
1712 'toofewexpiries' => array(
1713 'code' => 'toofewexpiries',
1714 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1715 ),
1716 'cantimport' => array(
1717 'code' => 'cantimport',
1718 'info' => "You don't have permission to import pages"
1719 ),
1720 'cantimport-upload' => array(
1721 'code' => 'cantimport-upload',
1722 'info' => "You don't have permission to import uploaded pages"
1723 ),
1724 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1725 'importuploaderrorsize' => array(
1726 'code' => 'filetoobig',
1727 'info' => 'The file you uploaded is bigger than the maximum upload size'
1728 ),
1729 'importuploaderrorpartial' => array(
1730 'code' => 'partialupload',
1731 'info' => 'The file was only partially uploaded'
1732 ),
1733 'importuploaderrortemp' => array(
1734 'code' => 'notempdir',
1735 'info' => 'The temporary upload directory is missing'
1736 ),
1737 'importcantopen' => array(
1738 'code' => 'cantopenfile',
1739 'info' => "Couldn't open the uploaded file"
1740 ),
1741 'import-noarticle' => array(
1742 'code' => 'badinterwiki',
1743 'info' => 'Invalid interwiki title specified'
1744 ),
1745 'importbadinterwiki' => array(
1746 'code' => 'badinterwiki',
1747 'info' => 'Invalid interwiki title specified'
1748 ),
1749 'import-unknownerror' => array(
1750 'code' => 'import-unknownerror',
1751 'info' => "Unknown error on import: \"\$1\""
1752 ),
1753 'cantoverwrite-sharedfile' => array(
1754 'code' => 'cantoverwrite-sharedfile',
1755 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1756 ),
1757 'sharedfile-exists' => array(
1758 'code' => 'fileexists-sharedrepo-perm',
1759 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1760 ),
1761 'mustbeposted' => array(
1762 'code' => 'mustbeposted',
1763 'info' => "The \$1 module requires a POST request"
1764 ),
1765 'show' => array(
1766 'code' => 'show',
1767 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1768 ),
1769 'specialpage-cantexecute' => array(
1770 'code' => 'specialpage-cantexecute',
1771 'info' => "You don't have permission to view the results of this special page"
1772 ),
1773 'invalidoldimage' => array(
1774 'code' => 'invalidoldimage',
1775 'info' => 'The oldimage parameter has invalid format'
1776 ),
1777 'nodeleteablefile' => array(
1778 'code' => 'nodeleteablefile',
1779 'info' => 'No such old version of the file'
1780 ),
1781 'fileexists-forbidden' => array(
1782 'code' => 'fileexists-forbidden',
1783 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1784 ),
1785 'fileexists-shared-forbidden' => array(
1786 'code' => 'fileexists-shared-forbidden',
1787 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1788 ),
1789 'filerevert-badversion' => array(
1790 'code' => 'filerevert-badversion',
1791 'info' => 'There is no previous local version of this file with the provided timestamp.'
1792 ),
1793
1794 // ApiEditPage messages
1795 'noimageredirect-anon' => array(
1796 'code' => 'noimageredirect-anon',
1797 'info' => "Anonymous users can't create image redirects"
1798 ),
1799 'noimageredirect-logged' => array(
1800 'code' => 'noimageredirect',
1801 'info' => "You don't have permission to create image redirects"
1802 ),
1803 'spamdetected' => array(
1804 'code' => 'spamdetected',
1805 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1806 ),
1807 'contenttoobig' => array(
1808 'code' => 'contenttoobig',
1809 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1810 ),
1811 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1812 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1813 'wasdeleted' => array(
1814 'code' => 'pagedeleted',
1815 'info' => "The page has been deleted since you fetched its timestamp"
1816 ),
1817 'blankpage' => array(
1818 'code' => 'emptypage',
1819 'info' => "Creating new, empty pages is not allowed"
1820 ),
1821 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1822 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1823 'missingtext' => array(
1824 'code' => 'notext',
1825 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1826 ),
1827 'emptynewsection' => array(
1828 'code' => 'emptynewsection',
1829 'info' => 'Creating empty new sections is not possible.'
1830 ),
1831 'revwrongpage' => array(
1832 'code' => 'revwrongpage',
1833 'info' => "r\$1 is not a revision of \"\$2\""
1834 ),
1835 'undo-failure' => array(
1836 'code' => 'undofailure',
1837 'info' => 'Undo failed due to conflicting intermediate edits'
1838 ),
1839
1840 // Messages from WikiPage::doEit()
1841 'edit-hook-aborted' => array(
1842 'code' => 'edit-hook-aborted',
1843 'info' => "Your edit was aborted by an ArticleSave hook"
1844 ),
1845 'edit-gone-missing' => array(
1846 'code' => 'edit-gone-missing',
1847 'info' => "The page you tried to edit doesn't seem to exist anymore"
1848 ),
1849 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1850 'edit-already-exists' => array(
1851 'code' => 'edit-already-exists',
1852 'info' => 'It seems the page you tried to create already exist'
1853 ),
1854
1855 // uploadMsgs
1856 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1857 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1858 'uploaddisabled' => array(
1859 'code' => 'uploaddisabled',
1860 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1861 ),
1862 'copyuploaddisabled' => array(
1863 'code' => 'copyuploaddisabled',
1864 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1865 ),
1866 'copyuploadbaddomain' => array(
1867 'code' => 'copyuploadbaddomain',
1868 'info' => 'Uploads by URL are not allowed from this domain.'
1869 ),
1870 'copyuploadbadurl' => array(
1871 'code' => 'copyuploadbadurl',
1872 'info' => 'Upload not allowed from this URL.'
1873 ),
1874
1875 'filename-tooshort' => array(
1876 'code' => 'filename-tooshort',
1877 'info' => 'The filename is too short'
1878 ),
1879 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1880 'illegal-filename' => array(
1881 'code' => 'illegal-filename',
1882 'info' => 'The filename is not allowed'
1883 ),
1884 'filetype-missing' => array(
1885 'code' => 'filetype-missing',
1886 'info' => 'The file is missing an extension'
1887 ),
1888
1889 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1890 );
1891 // @codingStandardsIgnoreEnd
1892
1893 /**
1894 * Helper function for readonly errors
1895 */
1896 public function dieReadOnly() {
1897 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1898 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1899 array( 'readonlyreason' => wfReadOnlyReason() ) );
1900 }
1901
1902 /**
1903 * Output the error message related to a certain array
1904 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1905 */
1906 public function dieUsageMsg( $error ) {
1907 # most of the time we send a 1 element, so we might as well send it as
1908 # a string and make this an array here.
1909 if ( is_string( $error ) ) {
1910 $error = array( $error );
1911 }
1912 $parsed = $this->parseMsg( $error );
1913 $this->dieUsage( $parsed['info'], $parsed['code'] );
1914 }
1915
1916 /**
1917 * Will only set a warning instead of failing if the global $wgDebugAPI
1918 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1919 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1920 * @since 1.21
1921 */
1922 public function dieUsageMsgOrDebug( $error ) {
1923 global $wgDebugAPI;
1924 if ( $wgDebugAPI !== true ) {
1925 $this->dieUsageMsg( $error );
1926 }
1927
1928 if ( is_string( $error ) ) {
1929 $error = array( $error );
1930 }
1931
1932 $parsed = $this->parseMsg( $error );
1933 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1934 }
1935
1936 /**
1937 * Die with the $prefix.'badcontinue' error. This call is common enough to
1938 * make it into the base method.
1939 * @param $condition boolean will only die if this value is true
1940 * @since 1.21
1941 */
1942 protected function dieContinueUsageIf( $condition ) {
1943 if ( $condition ) {
1944 $this->dieUsage(
1945 'Invalid continue param. You should pass the original value returned by the previous query',
1946 'badcontinue' );
1947 }
1948 }
1949
1950 /**
1951 * Return the error message related to a certain array
1952 * @param array $error Element of a getUserPermissionsErrors()-style array
1953 * @return array('code' => code, 'info' => info)
1954 */
1955 public function parseMsg( $error ) {
1956 $error = (array)$error; // It seems strings sometimes make their way in here
1957 $key = array_shift( $error );
1958
1959 // Check whether the error array was nested
1960 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1961 if ( is_array( $key ) ) {
1962 $error = $key;
1963 $key = array_shift( $error );
1964 }
1965
1966 if ( isset( self::$messageMap[$key] ) ) {
1967 return array(
1968 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
1969 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
1970 );
1971 }
1972
1973 // If the key isn't present, throw an "unknown error"
1974 return $this->parseMsg( array( 'unknownerror', $key ) );
1975 }
1976
1977 /**
1978 * Internal code errors should be reported with this method
1979 * @param string $method Method or function name
1980 * @param string $message Error message
1981 * @throws MWException
1982 */
1983 protected static function dieDebug( $method, $message ) {
1984 throw new MWException( "Internal error in $method: $message" );
1985 }
1986
1987 /**
1988 * Indicates if this module needs maxlag to be checked
1989 * @return bool
1990 */
1991 public function shouldCheckMaxlag() {
1992 return true;
1993 }
1994
1995 /**
1996 * Indicates whether this module requires read rights
1997 * @return bool
1998 */
1999 public function isReadMode() {
2000 return true;
2001 }
2002
2003 /**
2004 * Indicates whether this module requires write mode
2005 * @return bool
2006 */
2007 public function isWriteMode() {
2008 return false;
2009 }
2010
2011 /**
2012 * Indicates whether this module must be called with a POST request
2013 * @return bool
2014 */
2015 public function mustBePosted() {
2016 return false;
2017 }
2018
2019 /**
2020 * Returns whether this module requires a token to execute
2021 * It is used to show possible errors in action=paraminfo
2022 * see bug 25248
2023 * @return bool
2024 */
2025 public function needsToken() {
2026 return false;
2027 }
2028
2029 /**
2030 * Returns the token salt if there is one,
2031 * '' if the module doesn't require a salt,
2032 * else false if the module doesn't need a token
2033 * You have also to override needsToken()
2034 * Value is passed to User::getEditToken
2035 * @return bool|string|array
2036 */
2037 public function getTokenSalt() {
2038 return false;
2039 }
2040
2041 /**
2042 * Gets the user for whom to get the watchlist
2043 *
2044 * @param $params array
2045 * @return User
2046 */
2047 public function getWatchlistUser( $params ) {
2048 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
2049 $user = User::newFromName( $params['owner'], false );
2050 if ( !( $user && $user->getId() ) ) {
2051 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
2052 }
2053 $token = $user->getOption( 'watchlisttoken' );
2054 if ( $token == '' || $token != $params['token'] ) {
2055 $this->dieUsage(
2056 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
2057 'bad_wltoken'
2058 );
2059 }
2060 } else {
2061 if ( !$this->getUser()->isLoggedIn() ) {
2062 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
2063 }
2064 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
2065 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
2066 }
2067 $user = $this->getUser();
2068 }
2069
2070 return $user;
2071 }
2072
2073 /**
2074 * @return bool|string|array Returns a false if the module has no help URL,
2075 * else returns a (array of) string
2076 */
2077 public function getHelpUrls() {
2078 return false;
2079 }
2080
2081 /**
2082 * Returns a list of all possible errors returned by the module
2083 *
2084 * Don't call this function directly: use getFinalPossibleErrors() to allow
2085 * hooks to modify parameters as needed.
2086 *
2087 * @return array in the format of array( key, param1, param2, ... )
2088 * or array( 'code' => ..., 'info' => ... )
2089 */
2090 public function getPossibleErrors() {
2091 $ret = array();
2092
2093 $params = $this->getFinalParams();
2094 if ( $params ) {
2095 foreach ( $params as $paramName => $paramSettings ) {
2096 if ( isset( $paramSettings[ApiBase::PARAM_REQUIRED] )
2097 && $paramSettings[ApiBase::PARAM_REQUIRED]
2098 ) {
2099 $ret[] = array( 'missingparam', $paramName );
2100 }
2101 }
2102 if ( array_key_exists( 'continue', $params ) ) {
2103 $ret[] = array(
2104 'code' => 'badcontinue',
2105 'info' => 'Invalid continue param. You should pass the ' .
2106 'original value returned by the previous query'
2107 );
2108 }
2109 }
2110
2111 if ( $this->mustBePosted() ) {
2112 $ret[] = array( 'mustbeposted', $this->getModuleName() );
2113 }
2114
2115 if ( $this->isReadMode() ) {
2116 $ret[] = array( 'readrequired' );
2117 }
2118
2119 if ( $this->isWriteMode() ) {
2120 $ret[] = array( 'writerequired' );
2121 $ret[] = array( 'writedisabled' );
2122 }
2123
2124 if ( $this->needsToken() ) {
2125 if ( !isset( $params['token'][ApiBase::PARAM_REQUIRED] )
2126 || !$params['token'][ApiBase::PARAM_REQUIRED]
2127 ) {
2128 // Add token as possible missing parameter, if not already done
2129 $ret[] = array( 'missingparam', 'token' );
2130 }
2131 $ret[] = array( 'sessionfailure' );
2132 }
2133
2134 return $ret;
2135 }
2136
2137 /**
2138 * Get final list of possible errors, after hooks have had a chance to
2139 * tweak it as needed.
2140 *
2141 * @return array
2142 * @since 1.22
2143 */
2144 public function getFinalPossibleErrors() {
2145 $possibleErrors = $this->getPossibleErrors();
2146 wfRunHooks( 'APIGetPossibleErrors', array( $this, &$possibleErrors ) );
2147
2148 return $possibleErrors;
2149 }
2150
2151 /**
2152 * Parses a list of errors into a standardised format
2153 * @param array $errors List of errors. Items can be in the for
2154 * array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
2155 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
2156 */
2157 public function parseErrors( $errors ) {
2158 $ret = array();
2159
2160 foreach ( $errors as $row ) {
2161 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
2162 $ret[] = $row;
2163 } else {
2164 $ret[] = $this->parseMsg( $row );
2165 }
2166 }
2167
2168 return $ret;
2169 }
2170
2171 /**
2172 * Profiling: total module execution time
2173 */
2174 private $mTimeIn = 0, $mModuleTime = 0;
2175
2176 /**
2177 * Start module profiling
2178 */
2179 public function profileIn() {
2180 if ( $this->mTimeIn !== 0 ) {
2181 ApiBase::dieDebug( __METHOD__, 'Called twice without calling profileOut()' );
2182 }
2183 $this->mTimeIn = microtime( true );
2184 wfProfileIn( $this->getModuleProfileName() );
2185 }
2186
2187 /**
2188 * End module profiling
2189 */
2190 public function profileOut() {
2191 if ( $this->mTimeIn === 0 ) {
2192 ApiBase::dieDebug( __METHOD__, 'Called without calling profileIn() first' );
2193 }
2194 if ( $this->mDBTimeIn !== 0 ) {
2195 ApiBase::dieDebug(
2196 __METHOD__,
2197 'Must be called after database profiling is done with profileDBOut()'
2198 );
2199 }
2200
2201 $this->mModuleTime += microtime( true ) - $this->mTimeIn;
2202 $this->mTimeIn = 0;
2203 wfProfileOut( $this->getModuleProfileName() );
2204 }
2205
2206 /**
2207 * When modules crash, sometimes it is needed to do a profileOut() regardless
2208 * of the profiling state the module was in. This method does such cleanup.
2209 */
2210 public function safeProfileOut() {
2211 if ( $this->mTimeIn !== 0 ) {
2212 if ( $this->mDBTimeIn !== 0 ) {
2213 $this->profileDBOut();
2214 }
2215 $this->profileOut();
2216 }
2217 }
2218
2219 /**
2220 * Total time the module was executed
2221 * @return float
2222 */
2223 public function getProfileTime() {
2224 if ( $this->mTimeIn !== 0 ) {
2225 ApiBase::dieDebug( __METHOD__, 'Called without calling profileOut() first' );
2226 }
2227
2228 return $this->mModuleTime;
2229 }
2230
2231 /**
2232 * Profiling: database execution time
2233 */
2234 private $mDBTimeIn = 0, $mDBTime = 0;
2235
2236 /**
2237 * Start module profiling
2238 */
2239 public function profileDBIn() {
2240 if ( $this->mTimeIn === 0 ) {
2241 ApiBase::dieDebug(
2242 __METHOD__,
2243 'Must be called while profiling the entire module with profileIn()'
2244 );
2245 }
2246 if ( $this->mDBTimeIn !== 0 ) {
2247 ApiBase::dieDebug( __METHOD__, 'Called twice without calling profileDBOut()' );
2248 }
2249 $this->mDBTimeIn = microtime( true );
2250 wfProfileIn( $this->getModuleProfileName( true ) );
2251 }
2252
2253 /**
2254 * End database profiling
2255 */
2256 public function profileDBOut() {
2257 if ( $this->mTimeIn === 0 ) {
2258 ApiBase::dieDebug( __METHOD__, 'Must be called while profiling ' .
2259 'the entire module with profileIn()' );
2260 }
2261 if ( $this->mDBTimeIn === 0 ) {
2262 ApiBase::dieDebug( __METHOD__, 'Called without calling profileDBIn() first' );
2263 }
2264
2265 $time = microtime( true ) - $this->mDBTimeIn;
2266 $this->mDBTimeIn = 0;
2267
2268 $this->mDBTime += $time;
2269 $this->getMain()->mDBTime += $time;
2270 wfProfileOut( $this->getModuleProfileName( true ) );
2271 }
2272
2273 /**
2274 * Total time the module used the database
2275 * @return float
2276 */
2277 public function getProfileDBTime() {
2278 if ( $this->mDBTimeIn !== 0 ) {
2279 ApiBase::dieDebug( __METHOD__, 'Called without calling profileDBOut() first' );
2280 }
2281
2282 return $this->mDBTime;
2283 }
2284
2285 /**
2286 * Gets a default slave database connection object
2287 * @return DatabaseBase
2288 */
2289 protected function getDB() {
2290 if ( !isset( $this->mSlaveDB ) ) {
2291 $this->profileDBIn();
2292 $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
2293 $this->profileDBOut();
2294 }
2295
2296 return $this->mSlaveDB;
2297 }
2298
2299 /**
2300 * Debugging function that prints a value and an optional backtrace
2301 * @param $value mixed Value to print
2302 * @param string $name Description of the printed value
2303 * @param bool $backtrace If true, print a backtrace
2304 */
2305 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
2306 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
2307 var_export( $value );
2308 if ( $backtrace ) {
2309 print "\n" . wfBacktrace();
2310 }
2311 print "\n</pre>\n";
2312 }
2313 }