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