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