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