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