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