Merge "Improve the shell cgroup feature"
[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
44 // These constants allow modules to specify exactly how to treat incoming parameters.
45
46 const PARAM_DFLT = 0; // Default value of the parameter
47 const PARAM_ISMULTI = 1; // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
48 const PARAM_TYPE = 2; // Can be either a string type (e.g.: 'integer') or an array of allowed values
49 const PARAM_MAX = 3; // Max value allowed for a parameter. Only applies if TYPE='integer'
50 const PARAM_MAX2 = 4; // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
51 const PARAM_MIN = 5; // Lowest value allowed for a parameter. Only applies if TYPE='integer'
52 const PARAM_ALLOW_DUPLICATES = 6; // Boolean, do we allow the same value to be set more than once when ISMULTI=true
53 const PARAM_DEPRECATED = 7; // Boolean, is the parameter deprecated (will show a warning)
54 /// @since 1.17
55 const PARAM_REQUIRED = 8; // Boolean, is the parameter required?
56 /// @since 1.17
57 const PARAM_RANGE_ENFORCE = 9; // Boolean, if MIN/MAX are set, enforce (die) these? Only applies if TYPE='integer' Use with extreme caution
58
59 const PROP_ROOT = 'ROOT'; // Name of property group that is on the root element of the result, i.e. not part of a list
60 const PROP_LIST = 'LIST'; // Boolean, is the result multiple items? Defaults to true for query modules, to false for other modules
61 const PROP_TYPE = 0; // Type of the property, uses same format as PARAM_TYPE
62 const PROP_NULLABLE = 1; // Boolean, can the property be not included in the result? Defaults to false
63
64 const LIMIT_BIG1 = 500; // Fast query, std user limit
65 const LIMIT_BIG2 = 5000; // Fast query, bot/sysop limit
66 const LIMIT_SML1 = 50; // Slow query, std user limit
67 const LIMIT_SML2 = 500; // Slow query, bot/sysop limit
68
69 private $mMainModule, $mModuleName, $mModulePrefix;
70 private $mParamCache = array();
71
72 /**
73 * Constructor
74 * @param $mainModule ApiMain object
75 * @param $moduleName string Name of this module
76 * @param $modulePrefix string Prefix to use for parameter names
77 */
78 public function __construct( $mainModule, $moduleName, $modulePrefix = '' ) {
79 $this->mMainModule = $mainModule;
80 $this->mModuleName = $moduleName;
81 $this->mModulePrefix = $modulePrefix;
82
83 if ( !$this->isMain() ) {
84 $this->setContext( $mainModule->getContext() );
85 }
86 }
87
88 /*****************************************************************************
89 * ABSTRACT METHODS *
90 *****************************************************************************/
91
92 /**
93 * Evaluates the parameters, performs the requested query, and sets up
94 * the result. Concrete implementations of ApiBase must override this
95 * method to provide whatever functionality their module offers.
96 * Implementations must not produce any output on their own and are not
97 * expected to handle any errors.
98 *
99 * The execute() method will be invoked directly by ApiMain immediately
100 * before the result of the module is output. Aside from the
101 * constructor, implementations should assume that no other methods
102 * will be called externally on the module before the result is
103 * processed.
104 *
105 * The result data should be stored in the ApiResult object available
106 * through getResult().
107 */
108 abstract public function execute();
109
110 /**
111 * Returns a string that identifies the version of the extending class.
112 * Typically includes the class name, the svn revision, timestamp, and
113 * last author. Usually done with SVN's Id keyword
114 * @return string
115 * @deprecated since 1.21, version string is no longer supported
116 */
117 public function getVersion() {
118 wfDeprecated( __METHOD__, '1.21' );
119 return '';
120 }
121
122 /**
123 * Get the name of the module being executed by this instance
124 * @return string
125 */
126 public function getModuleName() {
127 return $this->mModuleName;
128 }
129
130
131 /**
132 * Get the module manager, or null if this module has no sub-modules
133 * @since 1.21
134 * @return ApiModuleManager
135 */
136 public function getModuleManager() {
137 return null;
138 }
139
140 /**
141 * Get parameter prefix (usually two letters or an empty string).
142 * @return string
143 */
144 public function getModulePrefix() {
145 return $this->mModulePrefix;
146 }
147
148 /**
149 * Get the name of the module as shown in the profiler log
150 *
151 * @param $db DatabaseBase|bool
152 *
153 * @return string
154 */
155 public function getModuleProfileName( $db = false ) {
156 if ( $db ) {
157 return 'API:' . $this->mModuleName . '-DB';
158 } else {
159 return 'API:' . $this->mModuleName;
160 }
161 }
162
163 /**
164 * Get the main module
165 * @return ApiMain object
166 */
167 public function getMain() {
168 return $this->mMainModule;
169 }
170
171 /**
172 * Returns true if this module is the main module ($this === $this->mMainModule),
173 * false otherwise.
174 * @return bool
175 */
176 public function isMain() {
177 return $this === $this->mMainModule;
178 }
179
180 /**
181 * Get the result object
182 * @return ApiResult
183 */
184 public function getResult() {
185 // Main module has getResult() method overriden
186 // Safety - avoid infinite loop:
187 if ( $this->isMain() ) {
188 ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
189 }
190 return $this->getMain()->getResult();
191 }
192
193 /**
194 * Get the result data array (read-only)
195 * @return array
196 */
197 public function getResultData() {
198 return $this->getResult()->getData();
199 }
200
201 /**
202 * Create a new RequestContext object to use e.g. for calls to other parts
203 * the software.
204 * The object will have the WebRequest and the User object set to the ones
205 * used in this instance.
206 *
207 * @deprecated since 1.19 use getContext to get the current context
208 * @return DerivativeContext
209 */
210 public function createContext() {
211 wfDeprecated( __METHOD__, '1.19' );
212 return new DerivativeContext( $this->getContext() );
213 }
214
215 /**
216 * Set warning section for this module. Users should monitor this
217 * section to notice any changes in API. Multiple calls to this
218 * function will result in the warning messages being separated by
219 * newlines
220 * @param $warning string Warning message
221 */
222 public function setWarning( $warning ) {
223 $result = $this->getResult();
224 $data = $result->getData();
225 if ( isset( $data['warnings'][$this->getModuleName()] ) ) {
226 // Don't add duplicate warnings
227 $warn_regex = preg_quote( $warning, '/' );
228 if ( preg_match( "/{$warn_regex}(\\n|$)/", $data['warnings'][$this->getModuleName()]['*'] ) ) {
229 return;
230 }
231 $oldwarning = $data['warnings'][$this->getModuleName()]['*'];
232 // If there is a warning already, append it to the existing one
233 $warning = "$oldwarning\n$warning";
234 $result->unsetValue( 'warnings', $this->getModuleName() );
235 }
236 $msg = array();
237 ApiResult::setContent( $msg, $warning );
238 $result->disableSizeCheck();
239 $result->addValue( 'warnings', $this->getModuleName(), $msg );
240 $result->enableSizeCheck();
241 }
242
243 /**
244 * If the module may only be used with a certain format module,
245 * it should override this method to return an instance of that formatter.
246 * A value of null means the default format will be used.
247 * @return mixed instance of a derived class of ApiFormatBase, or null
248 */
249 public function getCustomPrinter() {
250 return null;
251 }
252
253 /**
254 * Generates help message for this module, or false if there is no description
255 * @return mixed string or false
256 */
257 public function makeHelpMsg() {
258 static $lnPrfx = "\n ";
259
260 $msg = $this->getFinalDescription();
261
262 if ( $msg !== false ) {
263
264 if ( !is_array( $msg ) ) {
265 $msg = array(
266 $msg
267 );
268 }
269 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
270
271 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
272
273 if ( $this->isReadMode() ) {
274 $msg .= "\nThis module requires read rights";
275 }
276 if ( $this->isWriteMode() ) {
277 $msg .= "\nThis module requires write rights";
278 }
279 if ( $this->mustBePosted() ) {
280 $msg .= "\nThis module only accepts POST requests";
281 }
282 if ( $this->isReadMode() || $this->isWriteMode() ||
283 $this->mustBePosted() ) {
284 $msg .= "\n";
285 }
286
287 // Parameters
288 $paramsMsg = $this->makeHelpMsgParameters();
289 if ( $paramsMsg !== false ) {
290 $msg .= "Parameters:\n$paramsMsg";
291 }
292
293 $examples = $this->getExamples();
294 if ( $examples !== false && $examples !== '' ) {
295 if ( !is_array( $examples ) ) {
296 $examples = array(
297 $examples
298 );
299 }
300 $msg .= "Example" . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
301 foreach( $examples as $k => $v ) {
302
303 if ( is_numeric( $k ) ) {
304 $msg .= " $v\n";
305 } else {
306 if ( is_array( $v ) ) {
307 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
308 } else {
309 $msgExample = " $v";
310 }
311 $msgExample .= ":";
312 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
313 }
314 }
315 }
316 }
317
318 return $msg;
319 }
320
321 /**
322 * @param $item string
323 * @return string
324 */
325 private function indentExampleText( $item ) {
326 return " " . $item;
327 }
328
329 /**
330 * @param $prefix string Text to split output items
331 * @param $title string What is being output
332 * @param $input string|array
333 * @return string
334 */
335 protected function makeHelpArrayToString( $prefix, $title, $input ) {
336 if ( $input === false ) {
337 return '';
338 }
339 if ( !is_array( $input ) ) {
340 $input = array( $input );
341 }
342
343 if ( count( $input ) > 0 ) {
344 if ( $title ) {
345 $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n ";
346 } else {
347 $msg = ' ';
348 }
349 $msg .= implode( $prefix, $input ) . "\n";
350 return $msg;
351 }
352 return '';
353 }
354
355 /**
356 * Generates the parameter descriptions for this module, to be displayed in the
357 * module's help.
358 * @return string or false
359 */
360 public function makeHelpMsgParameters() {
361 $params = $this->getFinalParams();
362 if ( $params ) {
363
364 $paramsDescription = $this->getFinalParamDescription();
365 $msg = '';
366 $paramPrefix = "\n" . str_repeat( ' ', 24 );
367 $descWordwrap = "\n" . str_repeat( ' ', 28 );
368 foreach ( $params as $paramName => $paramSettings ) {
369 $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
370 if ( is_array( $desc ) ) {
371 $desc = implode( $paramPrefix, $desc );
372 }
373
374 //handle shorthand
375 if ( !is_array( $paramSettings ) ) {
376 $paramSettings = array(
377 self::PARAM_DFLT => $paramSettings,
378 );
379 }
380
381 //handle missing type
382 if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) {
383 $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] ) ? $paramSettings[ApiBase::PARAM_DFLT] : null;
384 if ( is_bool( $dflt ) ) {
385 $paramSettings[ApiBase::PARAM_TYPE] = 'boolean';
386 } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
387 $paramSettings[ApiBase::PARAM_TYPE] = 'string';
388 } elseif ( is_int( $dflt ) ) {
389 $paramSettings[ApiBase::PARAM_TYPE] = 'integer';
390 }
391 }
392
393 if ( isset( $paramSettings[self::PARAM_DEPRECATED] ) && $paramSettings[self::PARAM_DEPRECATED] ) {
394 $desc = "DEPRECATED! $desc";
395 }
396
397 if ( isset( $paramSettings[self::PARAM_REQUIRED] ) && $paramSettings[self::PARAM_REQUIRED] ) {
398 $desc .= $paramPrefix . "This parameter is required";
399 }
400
401 $type = isset( $paramSettings[self::PARAM_TYPE] ) ? $paramSettings[self::PARAM_TYPE] : null;
402 if ( isset( $type ) ) {
403 $hintPipeSeparated = true;
404 $multi = isset( $paramSettings[self::PARAM_ISMULTI] ) ? $paramSettings[self::PARAM_ISMULTI] : false;
405 if ( $multi ) {
406 $prompt = 'Values (separate with \'|\'): ';
407 } else {
408 $prompt = 'One value: ';
409 }
410
411 if ( is_array( $type ) ) {
412 $choices = array();
413 $nothingPrompt = '';
414 foreach ( $type as $t ) {
415 if ( $t === '' ) {
416 $nothingPrompt = 'Can be empty, or ';
417 } else {
418 $choices[] = $t;
419 }
420 }
421 $desc .= $paramPrefix . $nothingPrompt . $prompt;
422 $choicesstring = implode( ', ', $choices );
423 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
424 $hintPipeSeparated = false;
425 } else {
426 switch ( $type ) {
427 case 'namespace':
428 // Special handling because namespaces are type-limited, yet they are not given
429 $desc .= $paramPrefix . $prompt;
430 $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
431 100, $descWordwrap );
432 $hintPipeSeparated = false;
433 break;
434 case 'limit':
435 $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]}";
436 if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
437 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
438 }
439 $desc .= ' allowed';
440 break;
441 case 'integer':
442 $s = $multi ? 's' : '';
443 $hasMin = isset( $paramSettings[self::PARAM_MIN] );
444 $hasMax = isset( $paramSettings[self::PARAM_MAX] );
445 if ( $hasMin || $hasMax ) {
446 if ( !$hasMax ) {
447 $intRangeStr = "The value$s must be no less than {$paramSettings[self::PARAM_MIN]}";
448 } elseif ( !$hasMin ) {
449 $intRangeStr = "The value$s must be no more than {$paramSettings[self::PARAM_MAX]}";
450 } else {
451 $intRangeStr = "The value$s must be between {$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
452 }
453
454 $desc .= $paramPrefix . $intRangeStr;
455 }
456 break;
457 }
458 }
459
460 if ( $multi ) {
461 if ( $hintPipeSeparated ) {
462 $desc .= $paramPrefix . "Separate values with '|'";
463 }
464
465 $isArray = is_array( $type );
466 if ( !$isArray
467 || $isArray && count( $type ) > self::LIMIT_SML1 ) {
468 $desc .= $paramPrefix . "Maximum number of values " .
469 self::LIMIT_SML1 . " (" . self::LIMIT_SML2 . " for bots)";
470 }
471 }
472 }
473
474 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
475 if ( !is_null( $default ) && $default !== false ) {
476 $desc .= $paramPrefix . "Default: $default";
477 }
478
479 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
480 }
481 return $msg;
482
483 } else {
484 return false;
485 }
486 }
487
488 /**
489 * Returns the description string for this module
490 * @return mixed string or array of strings
491 */
492 protected function getDescription() {
493 return false;
494 }
495
496 /**
497 * Returns usage examples for this module. Return false if no examples are available.
498 * @return bool|string|array
499 */
500 protected function getExamples() {
501 return false;
502 }
503
504 /**
505 * Returns an array of allowed parameters (parameter name) => (default
506 * value) or (parameter name) => (array with PARAM_* constants as keys)
507 * Don't call this function directly: use getFinalParams() to allow
508 * hooks to modify parameters as needed.
509 * @return array|bool
510 */
511 protected function getAllowedParams() {
512 return false;
513 }
514
515 /**
516 * Returns an array of parameter descriptions.
517 * Don't call this functon directly: use getFinalParamDescription() to
518 * allow hooks to modify descriptions as needed.
519 * @return array|bool False on no parameter descriptions
520 */
521 protected function getParamDescription() {
522 return false;
523 }
524
525 /**
526 * Get final list of parameters, after hooks have had a chance to
527 * tweak it as needed.
528 *
529 * @return array|Bool False on no parameters
530 */
531 public function getFinalParams() {
532 $params = $this->getAllowedParams();
533 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params ) );
534 return $params;
535 }
536
537 /**
538 * Get final parameter descriptions, after hooks have had a chance to tweak it as
539 * needed.
540 *
541 * @return array|bool False on no parameter descriptions
542 */
543 public function getFinalParamDescription() {
544 $desc = $this->getParamDescription();
545 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
546 return $desc;
547 }
548
549 /**
550 * Returns possible properties in the result, grouped by the value of the prop parameter
551 * that shows them.
552 *
553 * Properties that are shown always are in a group with empty string as a key.
554 * Properties that can be shown by several values of prop are included multiple times.
555 * If some properties are part of a list and some are on the root object (see ApiQueryQueryPage),
556 * those on the root object are under the key PROP_ROOT.
557 * The array can also contain a boolean under the key PROP_LIST,
558 * indicating whether the result is a list.
559 *
560 * Don't call this functon directly: use getFinalResultProperties() to
561 * allow hooks to modify descriptions as needed.
562 *
563 * @return array|bool False on no properties
564 */
565 protected function getResultProperties() {
566 return false;
567 }
568
569 /**
570 * Get final possible result properties, after hooks have had a chance to tweak it as
571 * needed.
572 *
573 * @return array
574 */
575 public function getFinalResultProperties() {
576 $properties = $this->getResultProperties();
577 wfRunHooks( 'APIGetResultProperties', array( $this, &$properties ) );
578 return $properties;
579 }
580
581 /**
582 * Add token properties to the array used by getResultProperties,
583 * based on a token functions mapping.
584 */
585 protected static function addTokenProperties( &$props, $tokenFunctions ) {
586 foreach ( array_keys( $tokenFunctions ) as $token ) {
587 $props[''][$token . 'token'] = array(
588 ApiBase::PROP_TYPE => 'string',
589 ApiBase::PROP_NULLABLE => true
590 );
591 }
592 }
593
594 /**
595 * Get final module description, after hooks have had a chance to tweak it as
596 * needed.
597 *
598 * @return array|bool False on no parameters
599 */
600 public function getFinalDescription() {
601 $desc = $this->getDescription();
602 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
603 return $desc;
604 }
605
606 /**
607 * This method mangles parameter name based on the prefix supplied to the constructor.
608 * Override this method to change parameter name during runtime
609 * @param $paramName string Parameter name
610 * @return string Prefixed parameter name
611 */
612 public function encodeParamName( $paramName ) {
613 return $this->mModulePrefix . $paramName;
614 }
615
616 /**
617 * Using getAllowedParams(), this function makes an array of the values
618 * provided by the user, with key being the name of the variable, and
619 * value - validated value from user or default. limits will not be
620 * parsed if $parseLimit is set to false; use this when the max
621 * limit is not definitive yet, e.g. when getting revisions.
622 * @param $parseLimit Boolean: true by default
623 * @return array
624 */
625 public function extractRequestParams( $parseLimit = true ) {
626 // Cache parameters, for performance and to avoid bug 24564.
627 if ( !isset( $this->mParamCache[$parseLimit] ) ) {
628 $params = $this->getFinalParams();
629 $results = array();
630
631 if ( $params ) { // getFinalParams() can return false
632 foreach ( $params as $paramName => $paramSettings ) {
633 $results[$paramName] = $this->getParameterFromSettings(
634 $paramName, $paramSettings, $parseLimit );
635 }
636 }
637 $this->mParamCache[$parseLimit] = $results;
638 }
639 return $this->mParamCache[$parseLimit];
640 }
641
642 /**
643 * Get a value for the given parameter
644 * @param $paramName string Parameter name
645 * @param $parseLimit bool see extractRequestParams()
646 * @return mixed Parameter value
647 */
648 protected function getParameter( $paramName, $parseLimit = true ) {
649 $params = $this->getFinalParams();
650 $paramSettings = $params[$paramName];
651 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
652 }
653
654 /**
655 * Die if none or more than one of a certain set of parameters is set and not false.
656 * @param $params array of parameter names
657 */
658 public function requireOnlyOneParameter( $params ) {
659 $required = func_get_args();
660 array_shift( $required );
661 $p = $this->getModulePrefix();
662
663 $intersection = array_intersect( array_keys( array_filter( $params,
664 array( $this, "parameterNotEmpty" ) ) ), $required );
665
666 if ( count( $intersection ) > 1 ) {
667 $this->dieUsage( "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together', "{$p}invalidparammix" );
668 } elseif ( count( $intersection ) == 0 ) {
669 $this->dieUsage( "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
670 }
671 }
672
673 /**
674 * Generates the possible errors requireOnlyOneParameter() can die with
675 *
676 * @param $params array
677 * @return array
678 */
679 public function getRequireOnlyOneParameterErrorMessages( $params ) {
680 $p = $this->getModulePrefix();
681 $params = implode( ", {$p}", $params );
682
683 return array(
684 array( 'code' => "{$p}missingparam", 'info' => "One of the parameters {$p}{$params} is required" ),
685 array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
686 );
687 }
688
689 /**
690 * Die if more than one of a certain set of parameters is set and not false.
691 *
692 * @param $params array
693 */
694 public function requireMaxOneParameter( $params ) {
695 $required = func_get_args();
696 array_shift( $required );
697 $p = $this->getModulePrefix();
698
699 $intersection = array_intersect( array_keys( array_filter( $params,
700 array( $this, "parameterNotEmpty" ) ) ), $required );
701
702 if ( count( $intersection ) > 1 ) {
703 $this->dieUsage( "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together', "{$p}invalidparammix" );
704 }
705 }
706
707 /**
708 * Generates the possible error requireMaxOneParameter() can die with
709 *
710 * @param $params array
711 * @return array
712 */
713 public function getRequireMaxOneParameterErrorMessages( $params ) {
714 $p = $this->getModulePrefix();
715 $params = implode( ", {$p}", $params );
716
717 return array(
718 array( 'code' => "{$p}invalidparammix", 'info' => "The parameters {$p}{$params} can not be used together" )
719 );
720 }
721
722 /**
723 * @param $params array
724 * @param $load bool|string Whether load the object's state from the database:
725 * - false: don't load (if the pageid is given, it will still be loaded)
726 * - 'fromdb': load from a slave database
727 * - 'fromdbmaster': load from the master database
728 * @return WikiPage
729 */
730 public function getTitleOrPageId( $params, $load = false ) {
731 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
732
733 $pageObj = null;
734 if ( isset( $params['title'] ) ) {
735 $titleObj = Title::newFromText( $params['title'] );
736 if ( !$titleObj ) {
737 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
738 }
739 if ( !$titleObj->canExist() ) {
740 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
741 }
742 $pageObj = WikiPage::factory( $titleObj );
743 if ( $load !== false ) {
744 $pageObj->loadPageData( $load );
745 }
746 } elseif ( isset( $params['pageid'] ) ) {
747 if ( $load === false ) {
748 $load = 'fromdb';
749 }
750 $pageObj = WikiPage::newFromID( $params['pageid'], $load );
751 if ( !$pageObj ) {
752 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
753 }
754 }
755
756 return $pageObj;
757 }
758
759 /**
760 * @return array
761 */
762 public function getTitleOrPageIdErrorMessage() {
763 return array_merge(
764 $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ),
765 array(
766 array( 'invalidtitle', 'title' ),
767 array( 'nosuchpageid', 'pageid' ),
768 )
769 );
770 }
771
772 /**
773 * Callback function used in requireOnlyOneParameter to check whether reequired parameters are set
774 *
775 * @param $x object Parameter to check is not null/false
776 * @return bool
777 */
778 private function parameterNotEmpty( $x ) {
779 return !is_null( $x ) && $x !== false;
780 }
781
782 /**
783 * @deprecated since 1.17 use MWNamespace::getValidNamespaces()
784 *
785 * @return array
786 */
787 public static function getValidNamespaces() {
788 wfDeprecated( __METHOD__, '1.17' );
789 return MWNamespace::getValidNamespaces();
790 }
791
792 /**
793 * Return true if we're to watch the page, false if not, null if no change.
794 * @param $watchlist String Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
795 * @param $titleObj Title the page under consideration
796 * @param $userOption String The user option to consider when $watchlist=preferences.
797 * If not set will magically default to either watchdefault or watchcreations
798 * @return bool
799 */
800 protected function getWatchlistValue ( $watchlist, $titleObj, $userOption = null ) {
801
802 $userWatching = $this->getUser()->isWatched( $titleObj );
803
804 switch ( $watchlist ) {
805 case 'watch':
806 return true;
807
808 case 'unwatch':
809 return false;
810
811 case 'preferences':
812 # If the user is already watching, don't bother checking
813 if ( $userWatching ) {
814 return true;
815 }
816 # If no user option was passed, use watchdefault or watchcreation
817 if ( is_null( $userOption ) ) {
818 $userOption = $titleObj->exists()
819 ? 'watchdefault' : 'watchcreations';
820 }
821 # Watch the article based on the user preference
822 return (bool)$this->getUser()->getOption( $userOption );
823
824 case 'nochange':
825 return $userWatching;
826
827 default:
828 return $userWatching;
829 }
830 }
831
832 /**
833 * Set a watch (or unwatch) based the based on a watchlist parameter.
834 * @param $watch String Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
835 * @param $titleObj Title the article's title to change
836 * @param $userOption String The user option to consider when $watch=preferences
837 */
838 protected function setWatch( $watch, $titleObj, $userOption = null ) {
839 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
840 if ( $value === null ) {
841 return;
842 }
843
844 $user = $this->getUser();
845 if ( $value ) {
846 WatchAction::doWatch( $titleObj, $user );
847 } else {
848 WatchAction::doUnwatch( $titleObj, $user );
849 }
850 }
851
852 /**
853 * Using the settings determine the value for the given parameter
854 *
855 * @param $paramName String: parameter name
856 * @param $paramSettings array|mixed default value or an array of settings
857 * using PARAM_* constants.
858 * @param $parseLimit Boolean: parse limit?
859 * @return mixed Parameter value
860 */
861 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
862 // Some classes may decide to change parameter names
863 $encParamName = $this->encodeParamName( $paramName );
864
865 if ( !is_array( $paramSettings ) ) {
866 $default = $paramSettings;
867 $multi = false;
868 $type = gettype( $paramSettings );
869 $dupes = false;
870 $deprecated = false;
871 $required = false;
872 } else {
873 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
874 $multi = isset( $paramSettings[self::PARAM_ISMULTI] ) ? $paramSettings[self::PARAM_ISMULTI] : false;
875 $type = isset( $paramSettings[self::PARAM_TYPE] ) ? $paramSettings[self::PARAM_TYPE] : null;
876 $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] ) ? $paramSettings[self::PARAM_ALLOW_DUPLICATES] : false;
877 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] ) ? $paramSettings[self::PARAM_DEPRECATED] : false;
878 $required = isset( $paramSettings[self::PARAM_REQUIRED] ) ? $paramSettings[self::PARAM_REQUIRED] : false;
879
880 // When type is not given, and no choices, the type is the same as $default
881 if ( !isset( $type ) ) {
882 if ( isset( $default ) ) {
883 $type = gettype( $default );
884 } else {
885 $type = 'NULL'; // allow everything
886 }
887 }
888 }
889
890 if ( $type == 'boolean' ) {
891 if ( isset( $default ) && $default !== false ) {
892 // Having a default value of anything other than 'false' is not allowed
893 ApiBase::dieDebug( __METHOD__, "Boolean param $encParamName's default is set to '$default'. Boolean parameters must default to false." );
894 }
895
896 $value = $this->getMain()->getCheck( $encParamName );
897 } else {
898 $value = $this->getMain()->getVal( $encParamName, $default );
899
900 if ( isset( $value ) && $type == 'namespace' ) {
901 $type = MWNamespace::getValidNamespaces();
902 }
903 }
904
905 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
906 $value = $this->parseMultiValue( $encParamName, $value, $multi, is_array( $type ) ? $type : null );
907 }
908
909 // More validation only when choices were not given
910 // choices were validated in parseMultiValue()
911 if ( isset( $value ) ) {
912 if ( !is_array( $type ) ) {
913 switch ( $type ) {
914 case 'NULL': // nothing to do
915 break;
916 case 'string':
917 if ( $required && $value === '' ) {
918 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
919 }
920
921 break;
922 case 'integer': // Force everything using intval() and optionally validate limits
923 $min = isset ( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
924 $max = isset ( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
925 $enforceLimits = isset ( $paramSettings[self::PARAM_RANGE_ENFORCE] )
926 ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
927
928 if ( is_array( $value ) ) {
929 $value = array_map( 'intval', $value );
930 if ( !is_null( $min ) || !is_null( $max ) ) {
931 foreach ( $value as &$v ) {
932 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
933 }
934 }
935 } else {
936 $value = intval( $value );
937 if ( !is_null( $min ) || !is_null( $max ) ) {
938 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
939 }
940 }
941 break;
942 case 'limit':
943 if ( !$parseLimit ) {
944 // Don't do any validation whatsoever
945 break;
946 }
947 if ( !isset( $paramSettings[self::PARAM_MAX] ) || !isset( $paramSettings[self::PARAM_MAX2] ) ) {
948 ApiBase::dieDebug( __METHOD__, "MAX1 or MAX2 are not defined for the limit $encParamName" );
949 }
950 if ( $multi ) {
951 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
952 }
953 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
954 if ( $value == 'max' ) {
955 $value = $this->getMain()->canApiHighLimits() ? $paramSettings[self::PARAM_MAX2] : $paramSettings[self::PARAM_MAX];
956 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
957 } else {
958 $value = intval( $value );
959 $this->validateLimit( $paramName, $value, $min, $paramSettings[self::PARAM_MAX], $paramSettings[self::PARAM_MAX2] );
960 }
961 break;
962 case 'boolean':
963 if ( $multi ) {
964 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
965 }
966 break;
967 case 'timestamp':
968 if ( is_array( $value ) ) {
969 foreach ( $value as $key => $val ) {
970 $value[$key] = $this->validateTimestamp( $val, $encParamName );
971 }
972 } else {
973 $value = $this->validateTimestamp( $value, $encParamName );
974 }
975 break;
976 case 'user':
977 if ( !is_array( $value ) ) {
978 $value = array( $value );
979 }
980
981 foreach ( $value as $key => $val ) {
982 $title = Title::makeTitleSafe( NS_USER, $val );
983 if ( is_null( $title ) ) {
984 $this->dieUsage( "Invalid value for user parameter $encParamName", "baduser_{$encParamName}" );
985 }
986 $value[$key] = $title->getText();
987 }
988
989 if ( !$multi ) {
990 $value = $value[0];
991 }
992 break;
993 default:
994 ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
995 }
996 }
997
998 // Throw out duplicates if requested
999 if ( is_array( $value ) && !$dupes ) {
1000 $value = array_unique( $value );
1001 }
1002
1003 // Set a warning if a deprecated parameter has been passed
1004 if ( $deprecated && $value !== false ) {
1005 $this->setWarning( "The $encParamName parameter has been deprecated." );
1006 }
1007 } elseif ( $required ) {
1008 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1009 }
1010
1011 return $value;
1012 }
1013
1014 /**
1015 * Return an array of values that were given in a 'a|b|c' notation,
1016 * after it optionally validates them against the list allowed values.
1017 *
1018 * @param $valueName string The name of the parameter (for error
1019 * reporting)
1020 * @param $value mixed The value being parsed
1021 * @param $allowMultiple bool Can $value contain more than one value
1022 * separated by '|'?
1023 * @param $allowedValues mixed An array of values to check against. If
1024 * null, all values are accepted.
1025 * @return mixed (allowMultiple ? an_array_of_values : a_single_value)
1026 */
1027 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1028 if ( trim( $value ) === '' && $allowMultiple ) {
1029 return array();
1030 }
1031
1032 // This is a bit awkward, but we want to avoid calling canApiHighLimits() because it unstubs $wgUser
1033 $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 );
1034 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits() ?
1035 self::LIMIT_SML2 : self::LIMIT_SML1;
1036
1037 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
1038 $this->setWarning( "Too many values supplied for parameter '$valueName': the limit is $sizeLimit" );
1039 }
1040
1041 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1042 // Bug 33482 - Allow entries with | in them for non-multiple values
1043 if ( in_array( $value, $allowedValues ) ) {
1044 return $value;
1045 }
1046
1047 $possibleValues = is_array( $allowedValues ) ? "of '" . implode( "', '", $allowedValues ) . "'" : '';
1048 $this->dieUsage( "Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName" );
1049 }
1050
1051 if ( is_array( $allowedValues ) ) {
1052 // Check for unknown values
1053 $unknown = array_diff( $valuesList, $allowedValues );
1054 if ( count( $unknown ) ) {
1055 if ( $allowMultiple ) {
1056 $s = count( $unknown ) > 1 ? 's' : '';
1057 $vals = implode( ", ", $unknown );
1058 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1059 } else {
1060 $this->dieUsage( "Unrecognized value for parameter '$valueName': {$valuesList[0]}", "unknown_$valueName" );
1061 }
1062 }
1063 // Now throw them out
1064 $valuesList = array_intersect( $valuesList, $allowedValues );
1065 }
1066
1067 return $allowMultiple ? $valuesList : $valuesList[0];
1068 }
1069
1070 /**
1071 * Validate the value against the minimum and user/bot maximum limits.
1072 * Prints usage info on failure.
1073 * @param $paramName string Parameter name
1074 * @param $value int Parameter value
1075 * @param $min int|null Minimum value
1076 * @param $max int|null Maximum value for users
1077 * @param $botMax int Maximum value for sysops/bots
1078 * @param $enforceLimits Boolean Whether to enforce (die) if value is outside limits
1079 */
1080 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1081 if ( !is_null( $min ) && $value < $min ) {
1082
1083 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1084 $this->warnOrDie( $msg, $enforceLimits );
1085 $value = $min;
1086 }
1087
1088 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
1089 if ( $this->getMain()->isInternalMode() ) {
1090 return;
1091 }
1092
1093 // Optimization: do not check user's bot status unless really needed -- skips db query
1094 // assumes $botMax >= $max
1095 if ( !is_null( $max ) && $value > $max ) {
1096 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1097 if ( $value > $botMax ) {
1098 $msg = $this->encodeParamName( $paramName ) . " may not be over $botMax (set to $value) for bots or sysops";
1099 $this->warnOrDie( $msg, $enforceLimits );
1100 $value = $botMax;
1101 }
1102 } else {
1103 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1104 $this->warnOrDie( $msg, $enforceLimits );
1105 $value = $max;
1106 }
1107 }
1108 }
1109
1110 /**
1111 * @param $value string
1112 * @param $paramName string
1113 * @return string
1114 */
1115 function validateTimestamp( $value, $paramName ) {
1116 $unixTimestamp = wfTimestamp( TS_UNIX, $value );
1117 if ( $unixTimestamp === false ) {
1118 $this->dieUsage( "Invalid value '$value' for timestamp parameter $paramName", "badtimestamp_{$paramName}" );
1119 }
1120 return wfTimestamp( TS_MW, $unixTimestamp );
1121 }
1122
1123 /**
1124 * Adds a warning to the output, else dies
1125 *
1126 * @param $msg String Message to show as a warning, or error message if dying
1127 * @param $enforceLimits Boolean Whether this is an enforce (die)
1128 */
1129 private function warnOrDie( $msg, $enforceLimits = false ) {
1130 if ( $enforceLimits ) {
1131 $this->dieUsage( $msg, 'integeroutofrange' );
1132 } else {
1133 $this->setWarning( $msg );
1134 }
1135 }
1136
1137 /**
1138 * Truncate an array to a certain length.
1139 * @param $arr array Array to truncate
1140 * @param $limit int Maximum length
1141 * @return bool True if the array was truncated, false otherwise
1142 */
1143 public static function truncateArray( &$arr, $limit ) {
1144 $modified = false;
1145 while ( count( $arr ) > $limit ) {
1146 array_pop( $arr );
1147 $modified = true;
1148 }
1149 return $modified;
1150 }
1151
1152 /**
1153 * Throw a UsageException, which will (if uncaught) call the main module's
1154 * error handler and die with an error message.
1155 *
1156 * @param $description string One-line human-readable description of the
1157 * error condition, e.g., "The API requires a valid action parameter"
1158 * @param $errorCode string Brief, arbitrary, stable string to allow easy
1159 * automated identification of the error, e.g., 'unknown_action'
1160 * @param $httpRespCode int HTTP response code
1161 * @param $extradata array Data to add to the "<error>" element; array in ApiResult format
1162 * @throws UsageException
1163 */
1164 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1165 Profiler::instance()->close();
1166 throw new UsageException( $description, $this->encodeParamName( $errorCode ), $httpRespCode, $extradata );
1167 }
1168
1169 /**
1170 * Array that maps message keys to error messages. $1 and friends are replaced.
1171 */
1172 public static $messageMap = array(
1173 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1174 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1175 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1176
1177 // Messages from Title::getUserPermissionsErrors()
1178 'ns-specialprotected' => array( 'code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited" ),
1179 'protectedinterface' => array( 'code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages" ),
1180 'namespaceprotected' => array( 'code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the \"\$1\" namespace" ),
1181 'customcssprotected' => array( 'code' => 'customcssprotected', 'info' => "You're not allowed to edit custom CSS pages" ),
1182 'customjsprotected' => array( 'code' => 'customjsprotected', 'info' => "You're not allowed to edit custom JavaScript pages" ),
1183 'cascadeprotected' => array( 'code' => 'cascadeprotected', 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page" ),
1184 'protectedpagetext' => array( 'code' => 'protectedpage', 'info' => "The \"\$1\" right is required to edit this page" ),
1185 'protect-cantedit' => array( 'code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it" ),
1186 'badaccess-group0' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ), // Generic permission denied message
1187 'badaccess-groups' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ),
1188 'titleprotected' => array( 'code' => 'protectedtitle', 'info' => "This title has been protected from creation" ),
1189 'nocreate-loggedin' => array( 'code' => 'cantcreate', 'info' => "You don't have permission to create new pages" ),
1190 'nocreatetext' => array( 'code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages" ),
1191 'movenologintext' => array( 'code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages" ),
1192 'movenotallowed' => array( 'code' => 'cantmove', 'info' => "You don't have permission to move pages" ),
1193 'confirmedittext' => array( 'code' => 'confirmemail', 'info' => "You must confirm your e-mail address before you can edit" ),
1194 'blockedtext' => array( 'code' => 'blocked', 'info' => "You have been blocked from editing" ),
1195 'autoblockedtext' => array( 'code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user" ),
1196
1197 // Miscellaneous interface messages
1198 'actionthrottledtext' => array( 'code' => 'ratelimited', 'info' => "You've exceeded your rate limit. Please wait some time and try again" ),
1199 'alreadyrolled' => array( 'code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back" ),
1200 'cantrollback' => array( 'code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author" ),
1201 'readonlytext' => array( 'code' => 'readonly', 'info' => "The wiki is currently in read-only mode" ),
1202 'sessionfailure' => array( 'code' => 'badtoken', 'info' => "Invalid token" ),
1203 'cannotdelete' => array( 'code' => 'cantdelete', 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else" ),
1204 'notanarticle' => array( 'code' => 'missingtitle', 'info' => "The page you requested doesn't exist" ),
1205 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself" ),
1206 'immobile_namespace' => array( 'code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving" ),
1207 'articleexists' => array( 'code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article" ),
1208 'protectedpage' => array( 'code' => 'protectedpage', 'info' => "You don't have permission to perform this move" ),
1209 'hookaborted' => array( 'code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook" ),
1210 'cantmove-titleprotected' => array( 'code' => 'protectedtitle', 'info' => "The destination article has been protected from creation" ),
1211 'imagenocrossnamespace' => array( 'code' => 'nonfilenamespace', 'info' => "Can't move a file to a non-file namespace" ),
1212 'imagetypemismatch' => array( 'code' => 'filetypemismatch', 'info' => "The new file extension doesn't match its type" ),
1213 // 'badarticleerror' => shouldn't happen
1214 // 'badtitletext' => shouldn't happen
1215 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1216 'range_block_disabled' => array( 'code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled" ),
1217 'nosuchusershort' => array( 'code' => 'nosuchuser', 'info' => "The user you specified doesn't exist" ),
1218 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1219 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1220 'ipb_already_blocked' => array( 'code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked" ),
1221 'ipb_blocked_as_range' => array( 'code' => 'blockedasrange', 'info' => "IP address \"\$1\" was blocked as part of range \"\$2\". You can't unblock the IP invidually, but you can unblock the range as a whole." ),
1222 'ipb_cant_unblock' => array( 'code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already" ),
1223 'mailnologin' => array( 'code' => 'cantsend', 'info' => "You are not logged in, you do not have a confirmed e-mail address, or you are not allowed to send e-mail to other users, so you cannot send e-mail" ),
1224 'ipbblocked' => array( 'code' => 'ipbblocked', 'info' => 'You cannot block or unblock users while you are yourself blocked' ),
1225 'ipbnounblockself' => array( 'code' => 'ipbnounblockself', 'info' => 'You are not allowed to unblock yourself' ),
1226 'usermaildisabled' => array( 'code' => 'usermaildisabled', 'info' => "User email has been disabled" ),
1227 'blockedemailuser' => array( 'code' => 'blockedfrommail', 'info' => "You have been blocked from sending e-mail" ),
1228 'notarget' => array( 'code' => 'notarget', 'info' => "You have not specified a valid target for this action" ),
1229 'noemail' => array( 'code' => 'noemail', 'info' => "The user has not specified a valid e-mail address, or has chosen not to receive e-mail from other users" ),
1230 'rcpatroldisabled' => array( 'code' => 'patroldisabled', 'info' => "Patrolling is disabled on this wiki" ),
1231 'markedaspatrollederror-noautopatrol' => array( 'code' => 'noautopatrol', 'info' => "You don't have permission to patrol your own changes" ),
1232 'delete-toobig' => array( 'code' => 'bigdelete', 'info' => "You can't delete this page because it has more than \$1 revisions" ),
1233 'movenotallowedfile' => array( 'code' => 'cantmovefile', 'info' => "You don't have permission to move files" ),
1234 'userrights-no-interwiki' => array( 'code' => 'nointerwikiuserrights', 'info' => "You don't have permission to change user rights on other wikis" ),
1235 'userrights-nodatabase' => array( 'code' => 'nosuchdatabase', 'info' => "Database \"\$1\" does not exist or is not local" ),
1236 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1237 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1238 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1239 'import-rootpage-invalid' => array( 'code' => 'import-rootpage-invalid', 'info' => 'Root page is an invalid title' ),
1240 'import-rootpage-nosubpage' => array( 'code' => 'import-rootpage-nosubpage', 'info' => 'Namespace "$1" of the root page does not allow subpages' ),
1241
1242 // API-specific messages
1243 'readrequired' => array( 'code' => 'readapidenied', 'info' => "You need read permission to use this module" ),
1244 'writedisabled' => array( 'code' => 'noapiwrite', '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" ),
1245 'writerequired' => array( 'code' => 'writeapidenied', 'info' => "You're not allowed to edit this wiki through the API" ),
1246 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1247 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1248 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1249 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1250 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1251 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1252 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1253 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1254 'create-titleexists' => array( 'code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'" ),
1255 'missingtitle-createonly' => array( 'code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'" ),
1256 'cantblock' => array( 'code' => 'cantblock', 'info' => "You don't have permission to block users" ),
1257 'canthide' => array( 'code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log" ),
1258 'cantblock-email' => array( 'code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending e-mail through the wiki" ),
1259 'unblock-notarget' => array( 'code' => 'notarget', 'info' => "Either the id or the user parameter must be set" ),
1260 'unblock-idanduser' => array( 'code' => 'idanduser', 'info' => "The id and user parameters can't be used together" ),
1261 'cantunblock' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to unblock users" ),
1262 'cannotundelete' => array( 'code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already" ),
1263 'permdenied-undelete' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions" ),
1264 'createonly-exists' => array( 'code' => 'articleexists', 'info' => "The article you tried to create has been created already" ),
1265 'nocreate-missing' => array( 'code' => 'missingtitle', 'info' => "The article you tried to edit doesn't exist" ),
1266 'nosuchrcid' => array( 'code' => 'nosuchrcid', 'info' => "There is no change with rcid \"\$1\"" ),
1267 'protect-invalidaction' => array( 'code' => 'protect-invalidaction', 'info' => "Invalid protection type \"\$1\"" ),
1268 'protect-invalidlevel' => array( 'code' => 'protect-invalidlevel', 'info' => "Invalid protection level \"\$1\"" ),
1269 'toofewexpiries' => array( 'code' => 'toofewexpiries', 'info' => "\$1 expiry timestamps were provided where \$2 were needed" ),
1270 'cantimport' => array( 'code' => 'cantimport', 'info' => "You don't have permission to import pages" ),
1271 'cantimport-upload' => array( 'code' => 'cantimport-upload', 'info' => "You don't have permission to import uploaded pages" ),
1272 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1273 'importuploaderrorsize' => array( 'code' => 'filetoobig', 'info' => 'The file you uploaded is bigger than the maximum upload size' ),
1274 'importuploaderrorpartial' => array( 'code' => 'partialupload', 'info' => 'The file was only partially uploaded' ),
1275 'importuploaderrortemp' => array( 'code' => 'notempdir', 'info' => 'The temporary upload directory is missing' ),
1276 'importcantopen' => array( 'code' => 'cantopenfile', 'info' => "Couldn't open the uploaded file" ),
1277 'import-noarticle' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
1278 'importbadinterwiki' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
1279 'import-unknownerror' => array( 'code' => 'import-unknownerror', 'info' => "Unknown error on import: \"\$1\"" ),
1280 'cantoverwrite-sharedfile' => array( 'code' => 'cantoverwrite-sharedfile', 'info' => 'The target file exists on a shared repository and you do not have permission to override it' ),
1281 'sharedfile-exists' => array( 'code' => 'fileexists-sharedrepo-perm', 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.' ),
1282 'mustbeposted' => array( 'code' => 'mustbeposted', 'info' => "The \$1 module requires a POST request" ),
1283 'show' => array( 'code' => 'show', 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied' ),
1284 'specialpage-cantexecute' => array( 'code' => 'specialpage-cantexecute', 'info' => "You don't have permission to view the results of this special page" ),
1285 'invalidoldimage' => array( 'code' => 'invalidoldimage', 'info' => 'The oldimage parameter has invalid format' ),
1286 'nodeleteablefile' => array( 'code' => 'nodeleteablefile', 'info' => 'No such old version of the file' ),
1287 'fileexists-forbidden' => array( 'code' => 'fileexists-forbidden', 'info' => 'A file with name "$1" already exists, and cannot be overwritten.' ),
1288 'fileexists-shared-forbidden' => array( 'code' => 'fileexists-shared-forbidden', 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.' ),
1289 'filerevert-badversion' => array( 'code' => 'filerevert-badversion', 'info' => 'There is no previous local version of this file with the provided timestamp.' ),
1290
1291 // ApiEditPage messages
1292 'noimageredirect-anon' => array( 'code' => 'noimageredirect-anon', 'info' => "Anonymous users can't create image redirects" ),
1293 'noimageredirect-logged' => array( 'code' => 'noimageredirect', 'info' => "You don't have permission to create image redirects" ),
1294 'spamdetected' => array( 'code' => 'spamdetected', 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\"" ),
1295 'contenttoobig' => array( 'code' => 'contenttoobig', 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes" ),
1296 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1297 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1298 'wasdeleted' => array( 'code' => 'pagedeleted', 'info' => "The page has been deleted since you fetched its timestamp" ),
1299 'blankpage' => array( 'code' => 'emptypage', 'info' => "Creating new, empty pages is not allowed" ),
1300 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1301 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1302 'missingtext' => array( 'code' => 'notext', 'info' => "One of the text, appendtext, prependtext and undo parameters must be set" ),
1303 'emptynewsection' => array( 'code' => 'emptynewsection', 'info' => 'Creating empty new sections is not possible.' ),
1304 'revwrongpage' => array( 'code' => 'revwrongpage', 'info' => "r\$1 is not a revision of \"\$2\"" ),
1305 'undo-failure' => array( 'code' => 'undofailure', 'info' => 'Undo failed due to conflicting intermediate edits' ),
1306
1307 // Messages from WikiPage::doEit()
1308 'edit-hook-aborted' => array( 'code' => 'edit-hook-aborted', 'info' => "Your edit was aborted by an ArticleSave hook" ),
1309 'edit-gone-missing' => array( 'code' => 'edit-gone-missing', 'info' => "The page you tried to edit doesn't seem to exist anymore" ),
1310 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1311 'edit-already-exists' => array( 'code' => 'edit-already-exists', 'info' => "It seems the page you tried to create already exist" ),
1312
1313 // uploadMsgs
1314 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1315 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1316 'uploaddisabled' => array( 'code' => 'uploaddisabled', 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true' ),
1317 'copyuploaddisabled' => array( 'code' => 'copyuploaddisabled', 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.' ),
1318 'copyuploadbaddomain' => array( 'code' => 'copyuploadbaddomain', 'info' => 'Uploads by URL are not allowed from this domain.' ),
1319
1320 'filename-tooshort' => array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
1321 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1322 'illegal-filename' => array( 'code' => 'illegal-filename', 'info' => 'The filename is not allowed' ),
1323 'filetype-missing' => array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
1324
1325 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1326 );
1327
1328 /**
1329 * Helper function for readonly errors
1330 */
1331 public function dieReadOnly() {
1332 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1333 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1334 array( 'readonlyreason' => wfReadOnlyReason() ) );
1335 }
1336
1337 /**
1338 * Output the error message related to a certain array
1339 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1340 */
1341 public function dieUsageMsg( $error ) {
1342 # most of the time we send a 1 element, so we might as well send it as
1343 # a string and make this an array here.
1344 if( is_string( $error ) ) {
1345 $error = array( $error );
1346 }
1347 $parsed = $this->parseMsg( $error );
1348 $this->dieUsage( $parsed['info'], $parsed['code'] );
1349 }
1350
1351 /**
1352 * Will only set a warning instead of failing if the global $wgDebugAPI
1353 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1354 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1355 * @since 1.21
1356 */
1357 public function dieUsageMsgOrDebug( $error ) {
1358 global $wgDebugAPI;
1359 if( $wgDebugAPI !== true ) {
1360 $this->dieUsageMsg( $error );
1361 } else {
1362 if( is_string( $error ) ) {
1363 $error = array( $error );
1364 }
1365 $parsed = $this->parseMsg( $error );
1366 $this->setWarning( '$wgDebugAPI: ' . $parsed['code']
1367 . ' - ' . $parsed['info'] );
1368 }
1369 }
1370
1371 /**
1372 * Return the error message related to a certain array
1373 * @param $error array Element of a getUserPermissionsErrors()-style array
1374 * @return array('code' => code, 'info' => info)
1375 */
1376 public function parseMsg( $error ) {
1377 $error = (array)$error; // It seems strings sometimes make their way in here
1378 $key = array_shift( $error );
1379
1380 // Check whether the error array was nested
1381 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1382 if( is_array( $key ) ) {
1383 $error = $key;
1384 $key = array_shift( $error );
1385 }
1386
1387 if ( isset( self::$messageMap[$key] ) ) {
1388 return array(
1389 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
1390 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
1391 );
1392 }
1393
1394 // If the key isn't present, throw an "unknown error"
1395 return $this->parseMsg( array( 'unknownerror', $key ) );
1396 }
1397
1398 /**
1399 * Internal code errors should be reported with this method
1400 * @param $method string Method or function name
1401 * @param $message string Error message
1402 */
1403 protected static function dieDebug( $method, $message ) {
1404 wfDebugDieBacktrace( "Internal error in $method: $message" );
1405 }
1406
1407 /**
1408 * Indicates if this module needs maxlag to be checked
1409 * @return bool
1410 */
1411 public function shouldCheckMaxlag() {
1412 return true;
1413 }
1414
1415 /**
1416 * Indicates whether this module requires read rights
1417 * @return bool
1418 */
1419 public function isReadMode() {
1420 return true;
1421 }
1422 /**
1423 * Indicates whether this module requires write mode
1424 * @return bool
1425 */
1426 public function isWriteMode() {
1427 return false;
1428 }
1429
1430 /**
1431 * Indicates whether this module must be called with a POST request
1432 * @return bool
1433 */
1434 public function mustBePosted() {
1435 return false;
1436 }
1437
1438 /**
1439 * Returns whether this module requires a token to execute
1440 * It is used to show possible errors in action=paraminfo
1441 * see bug 25248
1442 * @return bool
1443 */
1444 public function needsToken() {
1445 return false;
1446 }
1447
1448 /**
1449 * Returns the token salt if there is one,
1450 * '' if the module doesn't require a salt,
1451 * else false if the module doesn't need a token
1452 * You have also to override needsToken()
1453 * Value is passed to User::getEditToken
1454 * @return bool|string|array
1455 */
1456 public function getTokenSalt() {
1457 return false;
1458 }
1459
1460 /**
1461 * Gets the user for whom to get the watchlist
1462 *
1463 * @param $params array
1464 * @return User
1465 */
1466 public function getWatchlistUser( $params ) {
1467 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1468 $user = User::newFromName( $params['owner'], false );
1469 if ( !($user && $user->getId()) ) {
1470 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1471 }
1472 $token = $user->getOption( 'watchlisttoken' );
1473 if ( $token == '' || $token != $params['token'] ) {
1474 $this->dieUsage( 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences', 'bad_wltoken' );
1475 }
1476 } else {
1477 if ( !$this->getUser()->isLoggedIn() ) {
1478 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1479 }
1480 $user = $this->getUser();
1481 }
1482 return $user;
1483 }
1484
1485 /**
1486 * @return bool|string|array Returns a false if the module has no help url, else returns a (array of) string
1487 */
1488 public function getHelpUrls() {
1489 return false;
1490 }
1491
1492 /**
1493 * Returns a list of all possible errors returned by the module
1494 * @return array in the format of array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1495 */
1496 public function getPossibleErrors() {
1497 $ret = array();
1498
1499 $params = $this->getFinalParams();
1500 if ( $params ) {
1501 foreach ( $params as $paramName => $paramSettings ) {
1502 if ( isset( $paramSettings[ApiBase::PARAM_REQUIRED] ) ) {
1503 $ret[] = array( 'missingparam', $paramName );
1504 }
1505 }
1506 }
1507
1508 if ( $this->mustBePosted() ) {
1509 $ret[] = array( 'mustbeposted', $this->getModuleName() );
1510 }
1511
1512 if ( $this->isReadMode() ) {
1513 $ret[] = array( 'readrequired' );
1514 }
1515
1516 if ( $this->isWriteMode() ) {
1517 $ret[] = array( 'writerequired' );
1518 $ret[] = array( 'writedisabled' );
1519 }
1520
1521 if ( $this->needsToken() ) {
1522 $ret[] = array( 'missingparam', 'token' );
1523 $ret[] = array( 'sessionfailure' );
1524 }
1525
1526 return $ret;
1527 }
1528
1529 /**
1530 * Parses a list of errors into a standardised format
1531 * @param $errors array List of errors. Items can be in the for array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1532 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
1533 */
1534 public function parseErrors( $errors ) {
1535 $ret = array();
1536
1537 foreach ( $errors as $row ) {
1538 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
1539 $ret[] = $row;
1540 } else {
1541 $ret[] = $this->parseMsg( $row );
1542 }
1543 }
1544 return $ret;
1545 }
1546
1547 /**
1548 * Profiling: total module execution time
1549 */
1550 private $mTimeIn = 0, $mModuleTime = 0;
1551
1552 /**
1553 * Start module profiling
1554 */
1555 public function profileIn() {
1556 if ( $this->mTimeIn !== 0 ) {
1557 ApiBase::dieDebug( __METHOD__, 'called twice without calling profileOut()' );
1558 }
1559 $this->mTimeIn = microtime( true );
1560 wfProfileIn( $this->getModuleProfileName() );
1561 }
1562
1563 /**
1564 * End module profiling
1565 */
1566 public function profileOut() {
1567 if ( $this->mTimeIn === 0 ) {
1568 ApiBase::dieDebug( __METHOD__, 'called without calling profileIn() first' );
1569 }
1570 if ( $this->mDBTimeIn !== 0 ) {
1571 ApiBase::dieDebug( __METHOD__, 'must be called after database profiling is done with profileDBOut()' );
1572 }
1573
1574 $this->mModuleTime += microtime( true ) - $this->mTimeIn;
1575 $this->mTimeIn = 0;
1576 wfProfileOut( $this->getModuleProfileName() );
1577 }
1578
1579 /**
1580 * When modules crash, sometimes it is needed to do a profileOut() regardless
1581 * of the profiling state the module was in. This method does such cleanup.
1582 */
1583 public function safeProfileOut() {
1584 if ( $this->mTimeIn !== 0 ) {
1585 if ( $this->mDBTimeIn !== 0 ) {
1586 $this->profileDBOut();
1587 }
1588 $this->profileOut();
1589 }
1590 }
1591
1592 /**
1593 * Total time the module was executed
1594 * @return float
1595 */
1596 public function getProfileTime() {
1597 if ( $this->mTimeIn !== 0 ) {
1598 ApiBase::dieDebug( __METHOD__, 'called without calling profileOut() first' );
1599 }
1600 return $this->mModuleTime;
1601 }
1602
1603 /**
1604 * Profiling: database execution time
1605 */
1606 private $mDBTimeIn = 0, $mDBTime = 0;
1607
1608 /**
1609 * Start module profiling
1610 */
1611 public function profileDBIn() {
1612 if ( $this->mTimeIn === 0 ) {
1613 ApiBase::dieDebug( __METHOD__, 'must be called while profiling the entire module with profileIn()' );
1614 }
1615 if ( $this->mDBTimeIn !== 0 ) {
1616 ApiBase::dieDebug( __METHOD__, 'called twice without calling profileDBOut()' );
1617 }
1618 $this->mDBTimeIn = microtime( true );
1619 wfProfileIn( $this->getModuleProfileName( true ) );
1620 }
1621
1622 /**
1623 * End database profiling
1624 */
1625 public function profileDBOut() {
1626 if ( $this->mTimeIn === 0 ) {
1627 ApiBase::dieDebug( __METHOD__, 'must be called while profiling the entire module with profileIn()' );
1628 }
1629 if ( $this->mDBTimeIn === 0 ) {
1630 ApiBase::dieDebug( __METHOD__, 'called without calling profileDBIn() first' );
1631 }
1632
1633 $time = microtime( true ) - $this->mDBTimeIn;
1634 $this->mDBTimeIn = 0;
1635
1636 $this->mDBTime += $time;
1637 $this->getMain()->mDBTime += $time;
1638 wfProfileOut( $this->getModuleProfileName( true ) );
1639 }
1640
1641 /**
1642 * Total time the module used the database
1643 * @return float
1644 */
1645 public function getProfileDBTime() {
1646 if ( $this->mDBTimeIn !== 0 ) {
1647 ApiBase::dieDebug( __METHOD__, 'called without calling profileDBOut() first' );
1648 }
1649 return $this->mDBTime;
1650 }
1651
1652 /**
1653 * @return DatabaseBase
1654 */
1655 protected function getDB() {
1656 return wfGetDB( DB_SLAVE, 'api' );
1657 }
1658
1659 /**
1660 * Debugging function that prints a value and an optional backtrace
1661 * @param $value mixed Value to print
1662 * @param $name string Description of the printed value
1663 * @param $backtrace bool If true, print a backtrace
1664 */
1665 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
1666 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
1667 var_export( $value );
1668 if ( $backtrace ) {
1669 print "\n" . wfBacktrace();
1670 }
1671 print "\n</pre>\n";
1672 }
1673 }