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