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