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