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