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