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