API: Overhaul ApiResult, make format=xml not throw, and add json formatversion
[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 * Self-documentation: code to allow the API to document its own state
36 *
37 * @ingroup API
38 */
39 abstract class ApiBase extends ContextSource {
40 // These constants allow modules to specify exactly how to treat incoming parameters.
41
42 // Default value of the parameter
43 const PARAM_DFLT = 0;
44 // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
45 const PARAM_ISMULTI = 1;
46 // Can be either a string type (e.g.: 'integer') or an array of allowed values
47 const PARAM_TYPE = 2;
48 // Max value allowed for a parameter. Only applies if TYPE='integer'
49 const PARAM_MAX = 3;
50 // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
51 const PARAM_MAX2 = 4;
52 // Lowest value allowed for a parameter. Only applies if TYPE='integer'
53 const PARAM_MIN = 5;
54 // Boolean, do we allow the same value to be set more than once when ISMULTI=true
55 const PARAM_ALLOW_DUPLICATES = 6;
56 // Boolean, is the parameter deprecated (will show a warning)
57 const PARAM_DEPRECATED = 7;
58 /// @since 1.17
59 const PARAM_REQUIRED = 8; // Boolean, is the parameter required?
60 /// @since 1.17
61 // Boolean, if MIN/MAX are set, enforce (die) these?
62 // Only applies if TYPE='integer' Use with extreme caution
63 const PARAM_RANGE_ENFORCE = 9;
64 /// @since 1.25
65 // Specify an alternative i18n message for this help parameter.
66 // Value is $msg for ApiBase::makeMessage()
67 const PARAM_HELP_MSG = 10;
68 /// @since 1.25
69 // Specify additional i18n messages to append to the normal message. Value
70 // is an array of $msg for ApiBase::makeMessage()
71 const PARAM_HELP_MSG_APPEND = 11;
72 /// @since 1.25
73 // Specify additional information tags for the parameter. Value is an array
74 // of arrays, with the first member being the 'tag' for the info and the
75 // remaining members being the values. In the help, this is formatted using
76 // apihelp-{$path}-paraminfo-{$tag}, which is passed $1 = count, $2 =
77 // comma-joined list of values, $3 = module prefix.
78 const PARAM_HELP_MSG_INFO = 12;
79 /// @since 1.25
80 // When PARAM_TYPE is an array, this may be an array mapping those values
81 // to page titles which will be linked in the help.
82 const PARAM_VALUE_LINKS = 13;
83 /// @since 1.25
84 // When PARAM_TYPE is an array, this is an array mapping those values to
85 // $msg for ApiBase::makeMessage(). Any value not having a mapping will use
86 // apihelp-{$path}-paramvalue-{$param}-{$value} is used.
87 const PARAM_HELP_MSG_PER_VALUE = 14;
88
89 const LIMIT_BIG1 = 500; // Fast query, std user limit
90 const LIMIT_BIG2 = 5000; // Fast query, bot/sysop limit
91 const LIMIT_SML1 = 50; // Slow query, std user limit
92 const LIMIT_SML2 = 500; // Slow query, bot/sysop limit
93
94 /**
95 * getAllowedParams() flag: When set, the result could take longer to generate,
96 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
97 * @since 1.21
98 */
99 const GET_VALUES_FOR_HELP = 1;
100
101 /** @var ApiMain */
102 private $mMainModule;
103 /** @var string */
104 private $mModuleName, $mModulePrefix;
105 private $mSlaveDB = null;
106 private $mParamCache = array();
107
108 /**
109 * @param ApiMain $mainModule
110 * @param string $moduleName Name of this module
111 * @param string $modulePrefix Prefix to use for parameter names
112 */
113 public function __construct( ApiMain $mainModule, $moduleName, $modulePrefix = '' ) {
114 $this->mMainModule = $mainModule;
115 $this->mModuleName = $moduleName;
116 $this->mModulePrefix = $modulePrefix;
117
118 if ( !$this->isMain() ) {
119 $this->setContext( $mainModule->getContext() );
120 }
121 }
122
123
124 /************************************************************************//**
125 * @name Methods to implement
126 * @{
127 */
128
129 /**
130 * Evaluates the parameters, performs the requested query, and sets up
131 * the result. Concrete implementations of ApiBase must override this
132 * method to provide whatever functionality their module offers.
133 * Implementations must not produce any output on their own and are not
134 * expected to handle any errors.
135 *
136 * The execute() method will be invoked directly by ApiMain immediately
137 * before the result of the module is output. Aside from the
138 * constructor, implementations should assume that no other methods
139 * will be called externally on the module before the result is
140 * processed.
141 *
142 * The result data should be stored in the ApiResult object available
143 * through getResult().
144 */
145 abstract public function execute();
146
147 /**
148 * Get the module manager, or null if this module has no sub-modules
149 * @since 1.21
150 * @return ApiModuleManager
151 */
152 public function getModuleManager() {
153 return null;
154 }
155
156 /**
157 * If the module may only be used with a certain format module,
158 * it should override this method to return an instance of that formatter.
159 * A value of null means the default format will be used.
160 * @note Do not use this just because you don't want to support non-json
161 * formats. This should be used only when there is a fundamental
162 * requirement for a specific format.
163 * @return mixed Instance of a derived class of ApiFormatBase, or null
164 */
165 public function getCustomPrinter() {
166 return null;
167 }
168
169 /**
170 * Returns usage examples for this module.
171 *
172 * Return value has query strings as keys, with values being either strings
173 * (message key), arrays (message key + parameter), or Message objects.
174 *
175 * Do not call this base class implementation when overriding this method.
176 *
177 * @since 1.25
178 * @return array
179 */
180 protected function getExamplesMessages() {
181 // Fall back to old non-localised method
182 $ret = array();
183
184 $examples = $this->getExamples();
185 if ( $examples ) {
186 if ( !is_array( $examples ) ) {
187 $examples = array( $examples );
188 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
189 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
190 !preg_match( '/^\s*api\.php\?/', $examples[0] )
191 ) {
192 // Fix up the ugly "even numbered elements are description, odd
193 // numbered elemts are the link" format (see doc for self::getExamples)
194 $tmp = array();
195 for ( $i = 0; $i < count( $examples ); $i += 2 ) {
196 $tmp[$examples[$i + 1]] = $examples[$i];
197 }
198 $examples = $tmp;
199 }
200
201 foreach ( $examples as $k => $v ) {
202 if ( is_numeric( $k ) ) {
203 $qs = $v;
204 $msg = '';
205 } else {
206 $qs = $k;
207 $msg = self::escapeWikiText( $v );
208 if ( is_array( $msg ) ) {
209 $msg = join( " ", $msg );
210 }
211 }
212
213 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
214 $ret[$qs] = $this->msg( 'api-help-fallback-example', array( $msg ) );
215 }
216 }
217
218 return $ret;
219 }
220
221 /**
222 * Return links to more detailed help pages about the module.
223 * @since 1.25, returning boolean false is deprecated
224 * @return string|array
225 */
226 public function getHelpUrls() {
227 return array();
228 }
229
230 /**
231 * Returns an array of allowed parameters (parameter name) => (default
232 * value) or (parameter name) => (array with PARAM_* constants as keys)
233 * Don't call this function directly: use getFinalParams() to allow
234 * hooks to modify parameters as needed.
235 *
236 * Some derived classes may choose to handle an integer $flags parameter
237 * in the overriding methods. Callers of this method can pass zero or
238 * more OR-ed flags like GET_VALUES_FOR_HELP.
239 *
240 * @return array
241 */
242 protected function getAllowedParams( /* $flags = 0 */ ) {
243 // int $flags is not declared because it causes "Strict standards"
244 // warning. Most derived classes do not implement it.
245 return array();
246 }
247
248 /**
249 * Indicates if this module needs maxlag to be checked
250 * @return bool
251 */
252 public function shouldCheckMaxlag() {
253 return true;
254 }
255
256 /**
257 * Indicates whether this module requires read rights
258 * @return bool
259 */
260 public function isReadMode() {
261 return true;
262 }
263
264 /**
265 * Indicates whether this module requires write mode
266 * @return bool
267 */
268 public function isWriteMode() {
269 return false;
270 }
271
272 /**
273 * Indicates whether this module must be called with a POST request
274 * @return bool
275 */
276 public function mustBePosted() {
277 return $this->needsToken() !== false;
278 }
279
280 /**
281 * Indicates whether this module is deprecated
282 * @since 1.25
283 * @return bool
284 */
285 public function isDeprecated() {
286 return false;
287 }
288
289 /**
290 * Indicates whether this module is "internal"
291 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
292 * @since 1.25
293 * @return bool
294 */
295 public function isInternal() {
296 return false;
297 }
298
299 /**
300 * Returns the token type this module requires in order to execute.
301 *
302 * Modules are strongly encouraged to use the core 'csrf' type unless they
303 * have specialized security needs. If the token type is not one of the
304 * core types, you must use the ApiQueryTokensRegisterTypes hook to
305 * register it.
306 *
307 * Returning a non-falsey value here will force the addition of an
308 * appropriate 'token' parameter in self::getFinalParams(). Also,
309 * self::mustBePosted() must return true when tokens are used.
310 *
311 * In previous versions of MediaWiki, true was a valid return value.
312 * Returning true will generate errors indicating that the API module needs
313 * updating.
314 *
315 * @return string|false
316 */
317 public function needsToken() {
318 return false;
319 }
320
321 /**
322 * Fetch the salt used in the Web UI corresponding to this module.
323 *
324 * Only override this if the Web UI uses a token with a non-constant salt.
325 *
326 * @since 1.24
327 * @param array $params All supplied parameters for the module
328 * @return string|array|null
329 */
330 protected function getWebUITokenSalt( array $params ) {
331 return null;
332 }
333
334 /**@}*/
335
336 /************************************************************************//**
337 * @name Data access methods
338 * @{
339 */
340
341 /**
342 * Get the name of the module being executed by this instance
343 * @return string
344 */
345 public function getModuleName() {
346 return $this->mModuleName;
347 }
348
349 /**
350 * Get parameter prefix (usually two letters or an empty string).
351 * @return string
352 */
353 public function getModulePrefix() {
354 return $this->mModulePrefix;
355 }
356
357 /**
358 * Get the main module
359 * @return ApiMain
360 */
361 public function getMain() {
362 return $this->mMainModule;
363 }
364
365 /**
366 * Returns true if this module is the main module ($this === $this->mMainModule),
367 * false otherwise.
368 * @return bool
369 */
370 public function isMain() {
371 return $this === $this->mMainModule;
372 }
373
374 /**
375 * Get the parent of this module
376 * @since 1.25
377 * @return ApiBase|null
378 */
379 public function getParent() {
380 return $this->isMain() ? null : $this->getMain();
381 }
382
383 /**
384 * Returns true if the current request breaks the same-origin policy.
385 *
386 * For example, json with callbacks.
387 *
388 * https://en.wikipedia.org/wiki/Same-origin_policy
389 *
390 * @since 1.25
391 * @return bool
392 */
393 public function lacksSameOriginSecurity() {
394 return $this->getMain()->getRequest()->getVal( 'callback' ) !== null;
395 }
396
397 /**
398 * Get the path to this module
399 *
400 * @since 1.25
401 * @return string
402 */
403 public function getModulePath() {
404 if ( $this->isMain() ) {
405 return 'main';
406 } elseif ( $this->getParent()->isMain() ) {
407 return $this->getModuleName();
408 } else {
409 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
410 }
411 }
412
413 /**
414 * Get a module from its module path
415 *
416 * @since 1.25
417 * @param string $path
418 * @return ApiBase|null
419 * @throws UsageException
420 */
421 public function getModuleFromPath( $path ) {
422 $module = $this->getMain();
423 if ( $path === 'main' ) {
424 return $module;
425 }
426
427 $parts = explode( '+', $path );
428 if ( count( $parts ) === 1 ) {
429 // In case the '+' was typed into URL, it resolves as a space
430 $parts = explode( ' ', $path );
431 }
432
433 $count = count( $parts );
434 for ( $i = 0; $i < $count; $i++ ) {
435 $parent = $module;
436 $manager = $parent->getModuleManager();
437 if ( $manager === null ) {
438 $errorPath = join( '+', array_slice( $parts, 0, $i ) );
439 $this->dieUsage( "The module \"$errorPath\" has no submodules", 'badmodule' );
440 }
441 $module = $manager->getModule( $parts[$i] );
442
443 if ( $module === null ) {
444 $errorPath = $i ? join( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
445 $this->dieUsage(
446 "The module \"$errorPath\" does not have a submodule \"{$parts[$i]}\"",
447 'badmodule'
448 );
449 }
450 }
451
452 return $module;
453 }
454
455 /**
456 * Get the result object
457 * @return ApiResult
458 */
459 public function getResult() {
460 // Main module has getResult() method overridden
461 // Safety - avoid infinite loop:
462 if ( $this->isMain() ) {
463 ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
464 }
465
466 return $this->getMain()->getResult();
467 }
468
469 /**
470 * Get the error formatter
471 * @return ApiErrorFormatter
472 */
473 public function getErrorFormatter() {
474 // Main module has getErrorFormatter() method overridden
475 // Safety - avoid infinite loop:
476 if ( $this->isMain() ) {
477 ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
478 }
479
480 return $this->getMain()->getErrorFormatter();
481 }
482
483 /**
484 * Gets a default slave database connection object
485 * @return DatabaseBase
486 */
487 protected function getDB() {
488 if ( !isset( $this->mSlaveDB ) ) {
489 $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
490 }
491
492 return $this->mSlaveDB;
493 }
494
495 /**
496 * Get the continuation manager
497 * @return ApiContinuationManager|null
498 */
499 public function getContinuationManager() {
500 // Main module has getContinuationManager() method overridden
501 // Safety - avoid infinite loop:
502 if ( $this->isMain() ) {
503 ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
504 }
505
506 return $this->getMain()->getContinuationManager();
507 }
508
509 /**
510 * Set the continuation manager
511 * @param ApiContinuationManager|null
512 */
513 public function setContinuationManager( $manager ) {
514 // Main module has setContinuationManager() method overridden
515 // Safety - avoid infinite loop:
516 if ( $this->isMain() ) {
517 ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
518 }
519
520 $this->getMain()->setContinuationManager( $manager );
521 }
522
523 /**@}*/
524
525 /************************************************************************//**
526 * @name Parameter handling
527 * @{
528 */
529
530 /**
531 * This method mangles parameter name based on the prefix supplied to the constructor.
532 * Override this method to change parameter name during runtime
533 * @param string $paramName Parameter name
534 * @return string Prefixed parameter name
535 */
536 public function encodeParamName( $paramName ) {
537 return $this->mModulePrefix . $paramName;
538 }
539
540 /**
541 * Using getAllowedParams(), this function makes an array of the values
542 * provided by the user, with key being the name of the variable, and
543 * value - validated value from user or default. limits will not be
544 * parsed if $parseLimit is set to false; use this when the max
545 * limit is not definitive yet, e.g. when getting revisions.
546 * @param bool $parseLimit True by default
547 * @return array
548 */
549 public function extractRequestParams( $parseLimit = true ) {
550 // Cache parameters, for performance and to avoid bug 24564.
551 if ( !isset( $this->mParamCache[$parseLimit] ) ) {
552 $params = $this->getFinalParams();
553 $results = array();
554
555 if ( $params ) { // getFinalParams() can return false
556 foreach ( $params as $paramName => $paramSettings ) {
557 $results[$paramName] = $this->getParameterFromSettings(
558 $paramName, $paramSettings, $parseLimit );
559 }
560 }
561 $this->mParamCache[$parseLimit] = $results;
562 }
563
564 return $this->mParamCache[$parseLimit];
565 }
566
567 /**
568 * Get a value for the given parameter
569 * @param string $paramName Parameter name
570 * @param bool $parseLimit See extractRequestParams()
571 * @return mixed Parameter value
572 */
573 protected function getParameter( $paramName, $parseLimit = true ) {
574 $params = $this->getFinalParams();
575 $paramSettings = $params[$paramName];
576
577 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
578 }
579
580 /**
581 * Die if none or more than one of a certain set of parameters is set and not false.
582 *
583 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
584 * @param string $required,... Names of parameters of which exactly one must be set
585 */
586 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
587 $required = func_get_args();
588 array_shift( $required );
589 $p = $this->getModulePrefix();
590
591 $intersection = array_intersect( array_keys( array_filter( $params,
592 array( $this, "parameterNotEmpty" ) ) ), $required );
593
594 if ( count( $intersection ) > 1 ) {
595 $this->dieUsage(
596 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
597 'invalidparammix' );
598 } elseif ( count( $intersection ) == 0 ) {
599 $this->dieUsage(
600 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
601 'missingparam'
602 );
603 }
604 }
605
606 /**
607 * Die if more than one of a certain set of parameters is set and not false.
608 *
609 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
610 * @param string $required,... Names of parameters of which at most one must be set
611 */
612 public function requireMaxOneParameter( $params, $required /*...*/ ) {
613 $required = func_get_args();
614 array_shift( $required );
615 $p = $this->getModulePrefix();
616
617 $intersection = array_intersect( array_keys( array_filter( $params,
618 array( $this, "parameterNotEmpty" ) ) ), $required );
619
620 if ( count( $intersection ) > 1 ) {
621 $this->dieUsage(
622 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
623 'invalidparammix'
624 );
625 }
626 }
627
628 /**
629 * Die if none of a certain set of parameters is set and not false.
630 *
631 * @since 1.23
632 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
633 * @param string $required,... Names of parameters of which at least one must be set
634 */
635 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
636 $required = func_get_args();
637 array_shift( $required );
638 $p = $this->getModulePrefix();
639
640 $intersection = array_intersect(
641 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
642 $required
643 );
644
645 if ( count( $intersection ) == 0 ) {
646 $this->dieUsage( "At least one of the parameters {$p}" .
647 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
648 }
649 }
650
651 /**
652 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
653 *
654 * @param object $x Parameter to check is not null/false
655 * @return bool
656 */
657 private function parameterNotEmpty( $x ) {
658 return !is_null( $x ) && $x !== false;
659 }
660
661 /**
662 * Get a WikiPage object from a title or pageid param, if possible.
663 * Can die, if no param is set or if the title or page id is not valid.
664 *
665 * @param array $params
666 * @param bool|string $load Whether load the object's state from the database:
667 * - false: don't load (if the pageid is given, it will still be loaded)
668 * - 'fromdb': load from a slave database
669 * - 'fromdbmaster': load from the master database
670 * @return WikiPage
671 */
672 public function getTitleOrPageId( $params, $load = false ) {
673 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
674
675 $pageObj = null;
676 if ( isset( $params['title'] ) ) {
677 $titleObj = Title::newFromText( $params['title'] );
678 if ( !$titleObj || $titleObj->isExternal() ) {
679 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
680 }
681 if ( !$titleObj->canExist() ) {
682 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
683 }
684 $pageObj = WikiPage::factory( $titleObj );
685 if ( $load !== false ) {
686 $pageObj->loadPageData( $load );
687 }
688 } elseif ( isset( $params['pageid'] ) ) {
689 if ( $load === false ) {
690 $load = 'fromdb';
691 }
692 $pageObj = WikiPage::newFromID( $params['pageid'], $load );
693 if ( !$pageObj ) {
694 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
695 }
696 }
697
698 return $pageObj;
699 }
700
701 /**
702 * Return true if we're to watch the page, false if not, null if no change.
703 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
704 * @param Title $titleObj The page under consideration
705 * @param string $userOption The user option to consider when $watchlist=preferences.
706 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
707 * @return bool
708 */
709 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
710
711 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem::IGNORE_USER_RIGHTS );
712
713 switch ( $watchlist ) {
714 case 'watch':
715 return true;
716
717 case 'unwatch':
718 return false;
719
720 case 'preferences':
721 # If the user is already watching, don't bother checking
722 if ( $userWatching ) {
723 return true;
724 }
725 # If no user option was passed, use watchdefault and watchcreations
726 if ( is_null( $userOption ) ) {
727 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
728 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
729 }
730
731 # Watch the article based on the user preference
732 return $this->getUser()->getBoolOption( $userOption );
733
734 case 'nochange':
735 return $userWatching;
736
737 default:
738 return $userWatching;
739 }
740 }
741
742 /**
743 * Using the settings determine the value for the given parameter
744 *
745 * @param string $paramName Parameter name
746 * @param array|mixed $paramSettings Default value or an array of settings
747 * using PARAM_* constants.
748 * @param bool $parseLimit Parse limit?
749 * @return mixed Parameter value
750 */
751 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
752 // Some classes may decide to change parameter names
753 $encParamName = $this->encodeParamName( $paramName );
754
755 if ( !is_array( $paramSettings ) ) {
756 $default = $paramSettings;
757 $multi = false;
758 $type = gettype( $paramSettings );
759 $dupes = false;
760 $deprecated = false;
761 $required = false;
762 } else {
763 $default = isset( $paramSettings[self::PARAM_DFLT] )
764 ? $paramSettings[self::PARAM_DFLT]
765 : null;
766 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
767 ? $paramSettings[self::PARAM_ISMULTI]
768 : false;
769 $type = isset( $paramSettings[self::PARAM_TYPE] )
770 ? $paramSettings[self::PARAM_TYPE]
771 : null;
772 $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] )
773 ? $paramSettings[self::PARAM_ALLOW_DUPLICATES]
774 : false;
775 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] )
776 ? $paramSettings[self::PARAM_DEPRECATED]
777 : false;
778 $required = isset( $paramSettings[self::PARAM_REQUIRED] )
779 ? $paramSettings[self::PARAM_REQUIRED]
780 : false;
781
782 // When type is not given, and no choices, the type is the same as $default
783 if ( !isset( $type ) ) {
784 if ( isset( $default ) ) {
785 $type = gettype( $default );
786 } else {
787 $type = 'NULL'; // allow everything
788 }
789 }
790 }
791
792 if ( $type == 'boolean' ) {
793 if ( isset( $default ) && $default !== false ) {
794 // Having a default value of anything other than 'false' is not allowed
795 ApiBase::dieDebug(
796 __METHOD__,
797 "Boolean param $encParamName's default is set to '$default'. " .
798 "Boolean parameters must default to false."
799 );
800 }
801
802 $value = $this->getMain()->getCheck( $encParamName );
803 } elseif ( $type == 'upload' ) {
804 if ( isset( $default ) ) {
805 // Having a default value is not allowed
806 ApiBase::dieDebug(
807 __METHOD__,
808 "File upload param $encParamName's default is set to " .
809 "'$default'. File upload parameters may not have a default." );
810 }
811 if ( $multi ) {
812 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
813 }
814 $value = $this->getMain()->getUpload( $encParamName );
815 if ( !$value->exists() ) {
816 // This will get the value without trying to normalize it
817 // (because trying to normalize a large binary file
818 // accidentally uploaded as a field fails spectacularly)
819 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
820 if ( $value !== null ) {
821 $this->dieUsage(
822 "File upload param $encParamName is not a file upload; " .
823 "be sure to use multipart/form-data for your POST and include " .
824 "a filename in the Content-Disposition header.",
825 "badupload_{$encParamName}"
826 );
827 }
828 }
829 } else {
830 $value = $this->getMain()->getVal( $encParamName, $default );
831
832 if ( isset( $value ) && $type == 'namespace' ) {
833 $type = MWNamespace::getValidNamespaces();
834 }
835 if ( isset( $value ) && $type == 'submodule' ) {
836 $type = $this->getModuleManager()->getNames( $paramName );
837 }
838 }
839
840 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
841 $value = $this->parseMultiValue(
842 $encParamName,
843 $value,
844 $multi,
845 is_array( $type ) ? $type : null
846 );
847 }
848
849 // More validation only when choices were not given
850 // choices were validated in parseMultiValue()
851 if ( isset( $value ) ) {
852 if ( !is_array( $type ) ) {
853 switch ( $type ) {
854 case 'NULL': // nothing to do
855 break;
856 case 'string':
857 if ( $required && $value === '' ) {
858 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
859 }
860 break;
861 case 'integer': // Force everything using intval() and optionally validate limits
862 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
863 $max = isset( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
864 $enforceLimits = isset( $paramSettings[self::PARAM_RANGE_ENFORCE] )
865 ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
866
867 if ( is_array( $value ) ) {
868 $value = array_map( 'intval', $value );
869 if ( !is_null( $min ) || !is_null( $max ) ) {
870 foreach ( $value as &$v ) {
871 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
872 }
873 }
874 } else {
875 $value = intval( $value );
876 if ( !is_null( $min ) || !is_null( $max ) ) {
877 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
878 }
879 }
880 break;
881 case 'limit':
882 if ( !$parseLimit ) {
883 // Don't do any validation whatsoever
884 break;
885 }
886 if ( !isset( $paramSettings[self::PARAM_MAX] )
887 || !isset( $paramSettings[self::PARAM_MAX2] )
888 ) {
889 ApiBase::dieDebug(
890 __METHOD__,
891 "MAX1 or MAX2 are not defined for the limit $encParamName"
892 );
893 }
894 if ( $multi ) {
895 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
896 }
897 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
898 if ( $value == 'max' ) {
899 $value = $this->getMain()->canApiHighLimits()
900 ? $paramSettings[self::PARAM_MAX2]
901 : $paramSettings[self::PARAM_MAX];
902 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
903 } else {
904 $value = intval( $value );
905 $this->validateLimit(
906 $paramName,
907 $value,
908 $min,
909 $paramSettings[self::PARAM_MAX],
910 $paramSettings[self::PARAM_MAX2]
911 );
912 }
913 break;
914 case 'boolean':
915 if ( $multi ) {
916 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
917 }
918 break;
919 case 'timestamp':
920 if ( is_array( $value ) ) {
921 foreach ( $value as $key => $val ) {
922 $value[$key] = $this->validateTimestamp( $val, $encParamName );
923 }
924 } else {
925 $value = $this->validateTimestamp( $value, $encParamName );
926 }
927 break;
928 case 'user':
929 if ( is_array( $value ) ) {
930 foreach ( $value as $key => $val ) {
931 $value[$key] = $this->validateUser( $val, $encParamName );
932 }
933 } else {
934 $value = $this->validateUser( $value, $encParamName );
935 }
936 break;
937 case 'upload': // nothing to do
938 break;
939 default:
940 ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
941 }
942 }
943
944 // Throw out duplicates if requested
945 if ( !$dupes && is_array( $value ) ) {
946 $value = array_unique( $value );
947 }
948
949 // Set a warning if a deprecated parameter has been passed
950 if ( $deprecated && $value !== false ) {
951 $this->setWarning( "The $encParamName parameter has been deprecated." );
952 }
953 } elseif ( $required ) {
954 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
955 }
956
957 return $value;
958 }
959
960 /**
961 * Return an array of values that were given in a 'a|b|c' notation,
962 * after it optionally validates them against the list allowed values.
963 *
964 * @param string $valueName The name of the parameter (for error
965 * reporting)
966 * @param mixed $value The value being parsed
967 * @param bool $allowMultiple Can $value contain more than one value
968 * separated by '|'?
969 * @param string[]|null $allowedValues An array of values to check against. If
970 * null, all values are accepted.
971 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
972 */
973 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
974 if ( trim( $value ) === '' && $allowMultiple ) {
975 return array();
976 }
977
978 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
979 // because it unstubs $wgUser
980 $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 );
981 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits()
982 ? self::LIMIT_SML2
983 : self::LIMIT_SML1;
984
985 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
986 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
987 "the limit is $sizeLimit" );
988 }
989
990 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
991 // Bug 33482 - Allow entries with | in them for non-multiple values
992 if ( in_array( $value, $allowedValues, true ) ) {
993 return $value;
994 }
995
996 $possibleValues = is_array( $allowedValues )
997 ? "of '" . implode( "', '", $allowedValues ) . "'"
998 : '';
999 $this->dieUsage(
1000 "Only one $possibleValues is allowed for parameter '$valueName'",
1001 "multival_$valueName"
1002 );
1003 }
1004
1005 if ( is_array( $allowedValues ) ) {
1006 // Check for unknown values
1007 $unknown = array_diff( $valuesList, $allowedValues );
1008 if ( count( $unknown ) ) {
1009 if ( $allowMultiple ) {
1010 $s = count( $unknown ) > 1 ? 's' : '';
1011 $vals = implode( ", ", $unknown );
1012 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1013 } else {
1014 $this->dieUsage(
1015 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1016 "unknown_$valueName"
1017 );
1018 }
1019 }
1020 // Now throw them out
1021 $valuesList = array_intersect( $valuesList, $allowedValues );
1022 }
1023
1024 return $allowMultiple ? $valuesList : $valuesList[0];
1025 }
1026
1027 /**
1028 * Validate the value against the minimum and user/bot maximum limits.
1029 * Prints usage info on failure.
1030 * @param string $paramName Parameter name
1031 * @param int $value Parameter value
1032 * @param int|null $min Minimum value
1033 * @param int|null $max Maximum value for users
1034 * @param int $botMax Maximum value for sysops/bots
1035 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1036 */
1037 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1038 if ( !is_null( $min ) && $value < $min ) {
1039
1040 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1041 $this->warnOrDie( $msg, $enforceLimits );
1042 $value = $min;
1043 }
1044
1045 // Minimum is always validated, whereas maximum is checked only if not
1046 // running in internal call mode
1047 if ( $this->getMain()->isInternalMode() ) {
1048 return;
1049 }
1050
1051 // Optimization: do not check user's bot status unless really needed -- skips db query
1052 // assumes $botMax >= $max
1053 if ( !is_null( $max ) && $value > $max ) {
1054 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1055 if ( $value > $botMax ) {
1056 $msg = $this->encodeParamName( $paramName ) .
1057 " may not be over $botMax (set to $value) for bots or sysops";
1058 $this->warnOrDie( $msg, $enforceLimits );
1059 $value = $botMax;
1060 }
1061 } else {
1062 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1063 $this->warnOrDie( $msg, $enforceLimits );
1064 $value = $max;
1065 }
1066 }
1067 }
1068
1069 /**
1070 * Validate and normalize of parameters of type 'timestamp'
1071 * @param string $value Parameter value
1072 * @param string $encParamName Parameter name
1073 * @return string Validated and normalized parameter
1074 */
1075 protected function validateTimestamp( $value, $encParamName ) {
1076 $unixTimestamp = wfTimestamp( TS_UNIX, $value );
1077 if ( $unixTimestamp === false ) {
1078 $this->dieUsage(
1079 "Invalid value '$value' for timestamp parameter $encParamName",
1080 "badtimestamp_{$encParamName}"
1081 );
1082 }
1083
1084 return wfTimestamp( TS_MW, $unixTimestamp );
1085 }
1086
1087 /**
1088 * Validate the supplied token.
1089 *
1090 * @since 1.24
1091 * @param string $token Supplied token
1092 * @param array $params All supplied parameters for the module
1093 * @return bool
1094 * @throws MWException
1095 */
1096 final public function validateToken( $token, array $params ) {
1097 $tokenType = $this->needsToken();
1098 $salts = ApiQueryTokens::getTokenTypeSalts();
1099 if ( !isset( $salts[$tokenType] ) ) {
1100 throw new MWException(
1101 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1102 'without registering it'
1103 );
1104 }
1105
1106 if ( $this->getUser()->matchEditToken(
1107 $token,
1108 $salts[$tokenType],
1109 $this->getRequest()
1110 ) ) {
1111 return true;
1112 }
1113
1114 $webUiSalt = $this->getWebUITokenSalt( $params );
1115 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1116 $token,
1117 $webUiSalt,
1118 $this->getRequest()
1119 ) ) {
1120 return true;
1121 }
1122
1123 return false;
1124 }
1125
1126 /**
1127 * Validate and normalize of parameters of type 'user'
1128 * @param string $value Parameter value
1129 * @param string $encParamName Parameter name
1130 * @return string Validated and normalized parameter
1131 */
1132 private function validateUser( $value, $encParamName ) {
1133 $title = Title::makeTitleSafe( NS_USER, $value );
1134 if ( $title === null ) {
1135 $this->dieUsage(
1136 "Invalid value '$value' for user parameter $encParamName",
1137 "baduser_{$encParamName}"
1138 );
1139 }
1140
1141 return $title->getText();
1142 }
1143
1144 /**@}*/
1145
1146 /************************************************************************//**
1147 * @name Utility methods
1148 * @{
1149 */
1150
1151 /**
1152 * Set a watch (or unwatch) based the based on a watchlist parameter.
1153 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1154 * @param Title $titleObj The article's title to change
1155 * @param string $userOption The user option to consider when $watch=preferences
1156 */
1157 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1158 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1159 if ( $value === null ) {
1160 return;
1161 }
1162
1163 WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1164 }
1165
1166 /**
1167 * Truncate an array to a certain length.
1168 * @param array $arr Array to truncate
1169 * @param int $limit Maximum length
1170 * @return bool True if the array was truncated, false otherwise
1171 */
1172 public static function truncateArray( &$arr, $limit ) {
1173 $modified = false;
1174 while ( count( $arr ) > $limit ) {
1175 array_pop( $arr );
1176 $modified = true;
1177 }
1178
1179 return $modified;
1180 }
1181
1182 /**
1183 * Gets the user for whom to get the watchlist
1184 *
1185 * @param array $params
1186 * @return User
1187 */
1188 public function getWatchlistUser( $params ) {
1189 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1190 $user = User::newFromName( $params['owner'], false );
1191 if ( !( $user && $user->getId() ) ) {
1192 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1193 }
1194 $token = $user->getOption( 'watchlisttoken' );
1195 if ( $token == '' || $token != $params['token'] ) {
1196 $this->dieUsage(
1197 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1198 'bad_wltoken'
1199 );
1200 }
1201 } else {
1202 if ( !$this->getUser()->isLoggedIn() ) {
1203 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1204 }
1205 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1206 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1207 }
1208 $user = $this->getUser();
1209 }
1210
1211 return $user;
1212 }
1213
1214 /**
1215 * A subset of wfEscapeWikiText for BC texts
1216 *
1217 * @since 1.25
1218 * @param string|array $v
1219 * @return string|array
1220 */
1221 private static function escapeWikiText( $v ) {
1222 if ( is_array( $v ) ) {
1223 return array_map( 'self::escapeWikiText', $v );
1224 } else {
1225 return strtr( $v, array(
1226 '__' => '_&#95;', '{' => '&#123;', '}' => '&#125;',
1227 '[[Category:' => '[[:Category:',
1228 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1229 ) );
1230 }
1231 }
1232
1233 /**
1234 * Create a Message from a string or array
1235 *
1236 * A string is used as a message key. An array has the message key as the
1237 * first value and message parameters as subsequent values.
1238 *
1239 * @since 1.25
1240 * @param string|array|Message $msg
1241 * @param IContextSource $context
1242 * @param array $params
1243 * @return Message|null
1244 */
1245 public static function makeMessage( $msg, IContextSource $context, array $params = null ) {
1246 if ( is_string( $msg ) ) {
1247 $msg = wfMessage( $msg );
1248 } elseif ( is_array( $msg ) ) {
1249 $msg = call_user_func_array( 'wfMessage', $msg );
1250 }
1251 if ( !$msg instanceof Message ) {
1252 return null;
1253 }
1254
1255 $msg->setContext( $context );
1256 if ( $params ) {
1257 $msg->params( $params );
1258 }
1259
1260 return $msg;
1261 }
1262
1263 /**@}*/
1264
1265 /************************************************************************//**
1266 * @name Warning and error reporting
1267 * @{
1268 */
1269
1270 /**
1271 * Set warning section for this module. Users should monitor this
1272 * section to notice any changes in API. Multiple calls to this
1273 * function will result in the warning messages being separated by
1274 * newlines
1275 * @param string $warning Warning message
1276 */
1277 public function setWarning( $warning ) {
1278 $msg = new ApiRawMessage( $warning, 'warning' );
1279 $this->getErrorFormatter()->addWarning( $this->getModuleName(), $msg );
1280 }
1281
1282 /**
1283 * Adds a warning to the output, else dies
1284 *
1285 * @param string $msg Message to show as a warning, or error message if dying
1286 * @param bool $enforceLimits Whether this is an enforce (die)
1287 */
1288 private function warnOrDie( $msg, $enforceLimits = false ) {
1289 if ( $enforceLimits ) {
1290 $this->dieUsage( $msg, 'integeroutofrange' );
1291 }
1292
1293 $this->setWarning( $msg );
1294 }
1295
1296 /**
1297 * Throw a UsageException, which will (if uncaught) call the main module's
1298 * error handler and die with an error message.
1299 *
1300 * @param string $description One-line human-readable description of the
1301 * error condition, e.g., "The API requires a valid action parameter"
1302 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1303 * automated identification of the error, e.g., 'unknown_action'
1304 * @param int $httpRespCode HTTP response code
1305 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1306 * @throws UsageException
1307 */
1308 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1309 throw new UsageException(
1310 $description,
1311 $this->encodeParamName( $errorCode ),
1312 $httpRespCode,
1313 $extradata
1314 );
1315 }
1316
1317 /**
1318 * Get error (as code, string) from a Status object.
1319 *
1320 * @since 1.23
1321 * @param Status $status
1322 * @return array Array of code and error string
1323 * @throws MWException
1324 */
1325 public function getErrorFromStatus( $status ) {
1326 if ( $status->isGood() ) {
1327 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1328 }
1329
1330 $errors = $status->getErrorsArray();
1331 if ( !$errors ) {
1332 // No errors? Assume the warnings should be treated as errors
1333 $errors = $status->getWarningsArray();
1334 }
1335 if ( !$errors ) {
1336 // Still no errors? Punt
1337 $errors = array( array( 'unknownerror-nocode' ) );
1338 }
1339
1340 // Cannot use dieUsageMsg() because extensions might return custom
1341 // error messages.
1342 if ( $errors[0] instanceof Message ) {
1343 $msg = $errors[0];
1344 $code = $msg->getKey();
1345 } else {
1346 $code = array_shift( $errors[0] );
1347 $msg = wfMessage( $code, $errors[0] );
1348 }
1349 if ( isset( ApiBase::$messageMap[$code] ) ) {
1350 // Translate message to code, for backwards compatibility
1351 $code = ApiBase::$messageMap[$code]['code'];
1352 }
1353
1354 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1355 }
1356
1357 /**
1358 * Throw a UsageException based on the errors in the Status object.
1359 *
1360 * @since 1.22
1361 * @param Status $status
1362 * @throws MWException
1363 */
1364 public function dieStatus( $status ) {
1365
1366 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1367 $this->dieUsage( $msg, $code );
1368 }
1369
1370 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1371 /**
1372 * Array that maps message keys to error messages. $1 and friends are replaced.
1373 */
1374 public static $messageMap = array(
1375 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1376 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1377 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1378
1379 // Messages from Title::getUserPermissionsErrors()
1380 'ns-specialprotected' => array(
1381 'code' => 'unsupportednamespace',
1382 'info' => "Pages in the Special namespace can't be edited"
1383 ),
1384 'protectedinterface' => array(
1385 'code' => 'protectednamespace-interface',
1386 'info' => "You're not allowed to edit interface messages"
1387 ),
1388 'namespaceprotected' => array(
1389 'code' => 'protectednamespace',
1390 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1391 ),
1392 'customcssprotected' => array(
1393 'code' => 'customcssprotected',
1394 'info' => "You're not allowed to edit custom CSS pages"
1395 ),
1396 'customjsprotected' => array(
1397 'code' => 'customjsprotected',
1398 'info' => "You're not allowed to edit custom JavaScript pages"
1399 ),
1400 'cascadeprotected' => array(
1401 'code' => 'cascadeprotected',
1402 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1403 ),
1404 'protectedpagetext' => array(
1405 'code' => 'protectedpage',
1406 'info' => "The \"\$1\" right is required to edit this page"
1407 ),
1408 'protect-cantedit' => array(
1409 'code' => 'cantedit',
1410 'info' => "You can't protect this page because you can't edit it"
1411 ),
1412 'deleteprotected' => array(
1413 'code' => 'cantedit',
1414 'info' => "You can't delete this page because it has been protected"
1415 ),
1416 'badaccess-group0' => array(
1417 'code' => 'permissiondenied',
1418 'info' => "Permission denied"
1419 ), // Generic permission denied message
1420 'badaccess-groups' => array(
1421 'code' => 'permissiondenied',
1422 'info' => "Permission denied"
1423 ),
1424 'titleprotected' => array(
1425 'code' => 'protectedtitle',
1426 'info' => "This title has been protected from creation"
1427 ),
1428 'nocreate-loggedin' => array(
1429 'code' => 'cantcreate',
1430 'info' => "You don't have permission to create new pages"
1431 ),
1432 'nocreatetext' => array(
1433 'code' => 'cantcreate-anon',
1434 'info' => "Anonymous users can't create new pages"
1435 ),
1436 'movenologintext' => array(
1437 'code' => 'cantmove-anon',
1438 'info' => "Anonymous users can't move pages"
1439 ),
1440 'movenotallowed' => array(
1441 'code' => 'cantmove',
1442 'info' => "You don't have permission to move pages"
1443 ),
1444 'confirmedittext' => array(
1445 'code' => 'confirmemail',
1446 'info' => "You must confirm your email address before you can edit"
1447 ),
1448 'blockedtext' => array(
1449 'code' => 'blocked',
1450 'info' => "You have been blocked from editing"
1451 ),
1452 'autoblockedtext' => array(
1453 'code' => 'autoblocked',
1454 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1455 ),
1456
1457 // Miscellaneous interface messages
1458 'actionthrottledtext' => array(
1459 'code' => 'ratelimited',
1460 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1461 ),
1462 'alreadyrolled' => array(
1463 'code' => 'alreadyrolled',
1464 'info' => "The page you tried to rollback was already rolled back"
1465 ),
1466 'cantrollback' => array(
1467 'code' => 'onlyauthor',
1468 'info' => "The page you tried to rollback only has one author"
1469 ),
1470 'readonlytext' => array(
1471 'code' => 'readonly',
1472 'info' => "The wiki is currently in read-only mode"
1473 ),
1474 'sessionfailure' => array(
1475 'code' => 'badtoken',
1476 'info' => "Invalid token" ),
1477 'cannotdelete' => array(
1478 'code' => 'cantdelete',
1479 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1480 ),
1481 'notanarticle' => array(
1482 'code' => 'missingtitle',
1483 'info' => "The page you requested doesn't exist"
1484 ),
1485 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1486 ),
1487 'immobile_namespace' => array(
1488 'code' => 'immobilenamespace',
1489 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1490 ),
1491 'articleexists' => array(
1492 'code' => 'articleexists',
1493 'info' => "The destination article already exists and is not a redirect to the source article"
1494 ),
1495 'protectedpage' => array(
1496 'code' => 'protectedpage',
1497 'info' => "You don't have permission to perform this move"
1498 ),
1499 'hookaborted' => array(
1500 'code' => 'hookaborted',
1501 'info' => "The modification you tried to make was aborted by an extension hook"
1502 ),
1503 'cantmove-titleprotected' => array(
1504 'code' => 'protectedtitle',
1505 'info' => "The destination article has been protected from creation"
1506 ),
1507 'imagenocrossnamespace' => array(
1508 'code' => 'nonfilenamespace',
1509 'info' => "Can't move a file to a non-file namespace"
1510 ),
1511 'imagetypemismatch' => array(
1512 'code' => 'filetypemismatch',
1513 'info' => "The new file extension doesn't match its type"
1514 ),
1515 // 'badarticleerror' => shouldn't happen
1516 // 'badtitletext' => shouldn't happen
1517 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1518 'range_block_disabled' => array(
1519 'code' => 'rangedisabled',
1520 'info' => "Blocking IP ranges has been disabled"
1521 ),
1522 'nosuchusershort' => array(
1523 'code' => 'nosuchuser',
1524 'info' => "The user you specified doesn't exist"
1525 ),
1526 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1527 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1528 'ipb_already_blocked' => array(
1529 'code' => 'alreadyblocked',
1530 'info' => "The user you tried to block was already blocked"
1531 ),
1532 'ipb_blocked_as_range' => array(
1533 'code' => 'blockedasrange',
1534 'info' => "IP address \"\$1\" was blocked as part of range \"\$2\". You can't unblock the IP individually, but you can unblock the range as a whole."
1535 ),
1536 'ipb_cant_unblock' => array(
1537 'code' => 'cantunblock',
1538 'info' => "The block you specified was not found. It may have been unblocked already"
1539 ),
1540 'mailnologin' => array(
1541 'code' => 'cantsend',
1542 'info' => "You are not logged in, you do not have a confirmed email address, or you are not allowed to send email to other users, so you cannot send email"
1543 ),
1544 'ipbblocked' => array(
1545 'code' => 'ipbblocked',
1546 'info' => 'You cannot block or unblock users while you are yourself blocked'
1547 ),
1548 'ipbnounblockself' => array(
1549 'code' => 'ipbnounblockself',
1550 'info' => 'You are not allowed to unblock yourself'
1551 ),
1552 'usermaildisabled' => array(
1553 'code' => 'usermaildisabled',
1554 'info' => "User email has been disabled"
1555 ),
1556 'blockedemailuser' => array(
1557 'code' => 'blockedfrommail',
1558 'info' => "You have been blocked from sending email"
1559 ),
1560 'notarget' => array(
1561 'code' => 'notarget',
1562 'info' => "You have not specified a valid target for this action"
1563 ),
1564 'noemail' => array(
1565 'code' => 'noemail',
1566 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1567 ),
1568 'rcpatroldisabled' => array(
1569 'code' => 'patroldisabled',
1570 'info' => "Patrolling is disabled on this wiki"
1571 ),
1572 'markedaspatrollederror-noautopatrol' => array(
1573 'code' => 'noautopatrol',
1574 'info' => "You don't have permission to patrol your own changes"
1575 ),
1576 'delete-toobig' => array(
1577 'code' => 'bigdelete',
1578 'info' => "You can't delete this page because it has more than \$1 revisions"
1579 ),
1580 'movenotallowedfile' => array(
1581 'code' => 'cantmovefile',
1582 'info' => "You don't have permission to move files"
1583 ),
1584 'userrights-no-interwiki' => array(
1585 'code' => 'nointerwikiuserrights',
1586 'info' => "You don't have permission to change user rights on other wikis"
1587 ),
1588 'userrights-nodatabase' => array(
1589 'code' => 'nosuchdatabase',
1590 'info' => "Database \"\$1\" does not exist or is not local"
1591 ),
1592 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1593 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1594 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1595 'import-rootpage-invalid' => array(
1596 'code' => 'import-rootpage-invalid',
1597 'info' => 'Root page is an invalid title'
1598 ),
1599 'import-rootpage-nosubpage' => array(
1600 'code' => 'import-rootpage-nosubpage',
1601 'info' => 'Namespace "$1" of the root page does not allow subpages'
1602 ),
1603
1604 // API-specific messages
1605 'readrequired' => array(
1606 'code' => 'readapidenied',
1607 'info' => "You need read permission to use this module"
1608 ),
1609 'writedisabled' => array(
1610 'code' => 'noapiwrite',
1611 '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"
1612 ),
1613 'writerequired' => array(
1614 'code' => 'writeapidenied',
1615 'info' => "You're not allowed to edit this wiki through the API"
1616 ),
1617 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1618 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1619 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1620 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1621 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1622 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1623 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1624 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1625 'create-titleexists' => array(
1626 'code' => 'create-titleexists',
1627 'info' => "Existing titles can't be protected with 'create'"
1628 ),
1629 'missingtitle-createonly' => array(
1630 'code' => 'missingtitle-createonly',
1631 'info' => "Missing titles can only be protected with 'create'"
1632 ),
1633 'cantblock' => array( 'code' => 'cantblock',
1634 'info' => "You don't have permission to block users"
1635 ),
1636 'canthide' => array(
1637 'code' => 'canthide',
1638 'info' => "You don't have permission to hide user names from the block log"
1639 ),
1640 'cantblock-email' => array(
1641 'code' => 'cantblock-email',
1642 'info' => "You don't have permission to block users from sending email through the wiki"
1643 ),
1644 'unblock-notarget' => array(
1645 'code' => 'notarget',
1646 'info' => "Either the id or the user parameter must be set"
1647 ),
1648 'unblock-idanduser' => array(
1649 'code' => 'idanduser',
1650 'info' => "The id and user parameters can't be used together"
1651 ),
1652 'cantunblock' => array(
1653 'code' => 'permissiondenied',
1654 'info' => "You don't have permission to unblock users"
1655 ),
1656 'cannotundelete' => array(
1657 'code' => 'cantundelete',
1658 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1659 ),
1660 'permdenied-undelete' => array(
1661 'code' => 'permissiondenied',
1662 'info' => "You don't have permission to restore deleted revisions"
1663 ),
1664 'createonly-exists' => array(
1665 'code' => 'articleexists',
1666 'info' => "The article you tried to create has been created already"
1667 ),
1668 'nocreate-missing' => array(
1669 'code' => 'missingtitle',
1670 'info' => "The article you tried to edit doesn't exist"
1671 ),
1672 'cantchangecontentmodel' => array(
1673 'code' => 'cantchangecontentmodel',
1674 'info' => "You don't have permission to change the content model of a page"
1675 ),
1676 'nosuchrcid' => array(
1677 'code' => 'nosuchrcid',
1678 'info' => "There is no change with rcid \"\$1\""
1679 ),
1680 'protect-invalidaction' => array(
1681 'code' => 'protect-invalidaction',
1682 'info' => "Invalid protection type \"\$1\""
1683 ),
1684 'protect-invalidlevel' => array(
1685 'code' => 'protect-invalidlevel',
1686 'info' => "Invalid protection level \"\$1\""
1687 ),
1688 'toofewexpiries' => array(
1689 'code' => 'toofewexpiries',
1690 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1691 ),
1692 'cantimport' => array(
1693 'code' => 'cantimport',
1694 'info' => "You don't have permission to import pages"
1695 ),
1696 'cantimport-upload' => array(
1697 'code' => 'cantimport-upload',
1698 'info' => "You don't have permission to import uploaded pages"
1699 ),
1700 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1701 'importuploaderrorsize' => array(
1702 'code' => 'filetoobig',
1703 'info' => 'The file you uploaded is bigger than the maximum upload size'
1704 ),
1705 'importuploaderrorpartial' => array(
1706 'code' => 'partialupload',
1707 'info' => 'The file was only partially uploaded'
1708 ),
1709 'importuploaderrortemp' => array(
1710 'code' => 'notempdir',
1711 'info' => 'The temporary upload directory is missing'
1712 ),
1713 'importcantopen' => array(
1714 'code' => 'cantopenfile',
1715 'info' => "Couldn't open the uploaded file"
1716 ),
1717 'import-noarticle' => array(
1718 'code' => 'badinterwiki',
1719 'info' => 'Invalid interwiki title specified'
1720 ),
1721 'importbadinterwiki' => array(
1722 'code' => 'badinterwiki',
1723 'info' => 'Invalid interwiki title specified'
1724 ),
1725 'import-unknownerror' => array(
1726 'code' => 'import-unknownerror',
1727 'info' => "Unknown error on import: \"\$1\""
1728 ),
1729 'cantoverwrite-sharedfile' => array(
1730 'code' => 'cantoverwrite-sharedfile',
1731 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1732 ),
1733 'sharedfile-exists' => array(
1734 'code' => 'fileexists-sharedrepo-perm',
1735 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1736 ),
1737 'mustbeposted' => array(
1738 'code' => 'mustbeposted',
1739 'info' => "The \$1 module requires a POST request"
1740 ),
1741 'show' => array(
1742 'code' => 'show',
1743 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1744 ),
1745 'specialpage-cantexecute' => array(
1746 'code' => 'specialpage-cantexecute',
1747 'info' => "You don't have permission to view the results of this special page"
1748 ),
1749 'invalidoldimage' => array(
1750 'code' => 'invalidoldimage',
1751 'info' => 'The oldimage parameter has invalid format'
1752 ),
1753 'nodeleteablefile' => array(
1754 'code' => 'nodeleteablefile',
1755 'info' => 'No such old version of the file'
1756 ),
1757 'fileexists-forbidden' => array(
1758 'code' => 'fileexists-forbidden',
1759 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1760 ),
1761 'fileexists-shared-forbidden' => array(
1762 'code' => 'fileexists-shared-forbidden',
1763 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1764 ),
1765 'filerevert-badversion' => array(
1766 'code' => 'filerevert-badversion',
1767 'info' => 'There is no previous local version of this file with the provided timestamp.'
1768 ),
1769
1770 // ApiEditPage messages
1771 'noimageredirect-anon' => array(
1772 'code' => 'noimageredirect-anon',
1773 'info' => "Anonymous users can't create image redirects"
1774 ),
1775 'noimageredirect-logged' => array(
1776 'code' => 'noimageredirect',
1777 'info' => "You don't have permission to create image redirects"
1778 ),
1779 'spamdetected' => array(
1780 'code' => 'spamdetected',
1781 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1782 ),
1783 'contenttoobig' => array(
1784 'code' => 'contenttoobig',
1785 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1786 ),
1787 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1788 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1789 'wasdeleted' => array(
1790 'code' => 'pagedeleted',
1791 'info' => "The page has been deleted since you fetched its timestamp"
1792 ),
1793 'blankpage' => array(
1794 'code' => 'emptypage',
1795 'info' => "Creating new, empty pages is not allowed"
1796 ),
1797 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1798 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1799 'missingtext' => array(
1800 'code' => 'notext',
1801 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1802 ),
1803 'emptynewsection' => array(
1804 'code' => 'emptynewsection',
1805 'info' => 'Creating empty new sections is not possible.'
1806 ),
1807 'revwrongpage' => array(
1808 'code' => 'revwrongpage',
1809 'info' => "r\$1 is not a revision of \"\$2\""
1810 ),
1811 'undo-failure' => array(
1812 'code' => 'undofailure',
1813 'info' => 'Undo failed due to conflicting intermediate edits'
1814 ),
1815 'content-not-allowed-here' => array(
1816 'code' => 'contentnotallowedhere',
1817 'info' => 'Content model "$1" is not allowed at title "$2"'
1818 ),
1819
1820 // Messages from WikiPage::doEit()
1821 'edit-hook-aborted' => array(
1822 'code' => 'edit-hook-aborted',
1823 'info' => "Your edit was aborted by an ArticleSave hook"
1824 ),
1825 'edit-gone-missing' => array(
1826 'code' => 'edit-gone-missing',
1827 'info' => "The page you tried to edit doesn't seem to exist anymore"
1828 ),
1829 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1830 'edit-already-exists' => array(
1831 'code' => 'edit-already-exists',
1832 'info' => 'It seems the page you tried to create already exist'
1833 ),
1834
1835 // uploadMsgs
1836 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1837 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1838 'uploaddisabled' => array(
1839 'code' => 'uploaddisabled',
1840 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1841 ),
1842 'copyuploaddisabled' => array(
1843 'code' => 'copyuploaddisabled',
1844 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1845 ),
1846 'copyuploadbaddomain' => array(
1847 'code' => 'copyuploadbaddomain',
1848 'info' => 'Uploads by URL are not allowed from this domain.'
1849 ),
1850 'copyuploadbadurl' => array(
1851 'code' => 'copyuploadbadurl',
1852 'info' => 'Upload not allowed from this URL.'
1853 ),
1854
1855 'filename-tooshort' => array(
1856 'code' => 'filename-tooshort',
1857 'info' => 'The filename is too short'
1858 ),
1859 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1860 'illegal-filename' => array(
1861 'code' => 'illegal-filename',
1862 'info' => 'The filename is not allowed'
1863 ),
1864 'filetype-missing' => array(
1865 'code' => 'filetype-missing',
1866 'info' => 'The file is missing an extension'
1867 ),
1868
1869 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1870 );
1871 // @codingStandardsIgnoreEnd
1872
1873 /**
1874 * Helper function for readonly errors
1875 */
1876 public function dieReadOnly() {
1877 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1878 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1879 array( 'readonlyreason' => wfReadOnlyReason() ) );
1880 }
1881
1882 /**
1883 * Output the error message related to a certain array
1884 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1885 */
1886 public function dieUsageMsg( $error ) {
1887 # most of the time we send a 1 element, so we might as well send it as
1888 # a string and make this an array here.
1889 if ( is_string( $error ) ) {
1890 $error = array( $error );
1891 }
1892 $parsed = $this->parseMsg( $error );
1893 $this->dieUsage( $parsed['info'], $parsed['code'] );
1894 }
1895
1896 /**
1897 * Will only set a warning instead of failing if the global $wgDebugAPI
1898 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1899 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1900 * @since 1.21
1901 */
1902 public function dieUsageMsgOrDebug( $error ) {
1903 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1904 $this->dieUsageMsg( $error );
1905 }
1906
1907 if ( is_string( $error ) ) {
1908 $error = array( $error );
1909 }
1910 $parsed = $this->parseMsg( $error );
1911 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1912 }
1913
1914 /**
1915 * Die with the $prefix.'badcontinue' error. This call is common enough to
1916 * make it into the base method.
1917 * @param bool $condition Will only die if this value is true
1918 * @since 1.21
1919 */
1920 protected function dieContinueUsageIf( $condition ) {
1921 if ( $condition ) {
1922 $this->dieUsage(
1923 'Invalid continue param. You should pass the original value returned by the previous query',
1924 'badcontinue' );
1925 }
1926 }
1927
1928 /**
1929 * Return the error message related to a certain array
1930 * @param array $error Element of a getUserPermissionsErrors()-style array
1931 * @return array('code' => code, 'info' => info)
1932 */
1933 public function parseMsg( $error ) {
1934 $error = (array)$error; // It seems strings sometimes make their way in here
1935 $key = array_shift( $error );
1936
1937 // Check whether the error array was nested
1938 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1939 if ( is_array( $key ) ) {
1940 $error = $key;
1941 $key = array_shift( $error );
1942 }
1943
1944 if ( isset( self::$messageMap[$key] ) ) {
1945 return array(
1946 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
1947 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
1948 );
1949 }
1950
1951 // If the key isn't present, throw an "unknown error"
1952 return $this->parseMsg( array( 'unknownerror', $key ) );
1953 }
1954
1955 /**
1956 * Internal code errors should be reported with this method
1957 * @param string $method Method or function name
1958 * @param string $message Error message
1959 * @throws MWException
1960 */
1961 protected static function dieDebug( $method, $message ) {
1962 throw new MWException( "Internal error in $method: $message" );
1963 }
1964
1965 /**
1966 * Write logging information for API features to a debug log, for usage
1967 * analysis.
1968 * @param string $feature Feature being used.
1969 */
1970 protected function logFeatureUsage( $feature ) {
1971 $request = $this->getRequest();
1972 $s = '"' . addslashes( $feature ) . '"' .
1973 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
1974 ' "' . $request->getIP() . '"' .
1975 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
1976 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
1977 wfDebugLog( 'api-feature-usage', $s, 'private' );
1978 }
1979
1980 /**@}*/
1981
1982 /************************************************************************//**
1983 * @name Help message generation
1984 * @{
1985 */
1986
1987 /**
1988 * Return the description message.
1989 *
1990 * @return string|array|Message
1991 */
1992 protected function getDescriptionMessage() {
1993 return "apihelp-{$this->getModulePath()}-description";
1994 }
1995
1996 /**
1997 * Get final module description, after hooks have had a chance to tweak it as
1998 * needed.
1999 *
2000 * @since 1.25, returns Message[] rather than string[]
2001 * @return Message[]
2002 */
2003 public function getFinalDescription() {
2004 $desc = $this->getDescription();
2005 Hooks::run( 'APIGetDescription', array( &$this, &$desc ) );
2006 $desc = self::escapeWikiText( $desc );
2007 if ( is_array( $desc ) ) {
2008 $desc = join( "\n", $desc );
2009 } else {
2010 $desc = (string)$desc;
2011 }
2012
2013 $msg = ApiBase::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
2014 $this->getModulePrefix(),
2015 $this->getModuleName(),
2016 $this->getModulePath(),
2017 ) );
2018 if ( !$msg->exists() ) {
2019 $msg = $this->msg( 'api-help-fallback-description', $desc );
2020 }
2021 $msgs = array( $msg );
2022
2023 Hooks::run( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
2024
2025 return $msgs;
2026 }
2027
2028 /**
2029 * Get final list of parameters, after hooks have had a chance to
2030 * tweak it as needed.
2031 *
2032 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2033 * @return array|bool False on no parameters
2034 * @since 1.21 $flags param added
2035 */
2036 public function getFinalParams( $flags = 0 ) {
2037 $params = $this->getAllowedParams( $flags );
2038 if ( !$params ) {
2039 $params = array();
2040 }
2041
2042 if ( $this->needsToken() ) {
2043 $params['token'] = array(
2044 ApiBase::PARAM_TYPE => 'string',
2045 ApiBase::PARAM_REQUIRED => true,
2046 ApiBase::PARAM_HELP_MSG => array(
2047 'api-help-param-token',
2048 $this->needsToken(),
2049 ),
2050 ) + ( isset( $params['token'] ) ? $params['token'] : array() );
2051 }
2052
2053 Hooks::run( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2054
2055 return $params;
2056 }
2057
2058 /**
2059 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2060 * needed.
2061 *
2062 * @since 1.25, returns array of Message[] rather than array of string[]
2063 * @return array Keys are parameter names, values are arrays of Message objects
2064 */
2065 public function getFinalParamDescription() {
2066 $prefix = $this->getModulePrefix();
2067 $name = $this->getModuleName();
2068 $path = $this->getModulePath();
2069
2070 $desc = $this->getParamDescription();
2071 Hooks::run( 'APIGetParamDescription', array( &$this, &$desc ) );
2072
2073 if ( !$desc ) {
2074 $desc = array();
2075 }
2076 $desc = self::escapeWikiText( $desc );
2077
2078 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
2079 $msgs = array();
2080 foreach ( $params as $param => $settings ) {
2081 if ( !is_array( $settings ) ) {
2082 $settings = array();
2083 }
2084
2085 $d = isset( $desc[$param] ) ? $desc[$param] : '';
2086 if ( is_array( $d ) ) {
2087 // Special handling for prop parameters
2088 $d = array_map( function ( $line ) {
2089 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2090 $line = "\n;{$m[1]}:{$m[2]}";
2091 }
2092 return $line;
2093 }, $d );
2094 $d = join( ' ', $d );
2095 }
2096
2097 if ( isset( $settings[ApiBase::PARAM_HELP_MSG] ) ) {
2098 $msg = $settings[ApiBase::PARAM_HELP_MSG];
2099 } else {
2100 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2101 if ( !$msg->exists() ) {
2102 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2103 }
2104 }
2105 $msg = ApiBase::makeMessage( $msg, $this->getContext(),
2106 array( $prefix, $param, $name, $path ) );
2107 if ( !$msg ) {
2108 $this->dieDebug( __METHOD__,
2109 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2110 }
2111 $msgs[$param] = array( $msg );
2112
2113 if ( isset( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
2114 if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
2115 $this->dieDebug( __METHOD__,
2116 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2117 }
2118 if ( !is_array( $settings[ApiBase::PARAM_TYPE] ) ) {
2119 $this->dieDebug( __METHOD__,
2120 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2121 'ApiBase::PARAM_TYPE is an array' );
2122 }
2123
2124 $valueMsgs = $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE];
2125 foreach ( $settings[ApiBase::PARAM_TYPE] as $value ) {
2126 if ( isset( $valueMsgs[$value] ) ) {
2127 $msg = $valueMsgs[$value];
2128 } else {
2129 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2130 }
2131 $m = ApiBase::makeMessage( $msg, $this->getContext(),
2132 array( $prefix, $param, $name, $path, $value ) );
2133 if ( $m ) {
2134 $m = new ApiHelpParamValueMessage(
2135 $value,
2136 array( $m->getKey(), 'api-help-param-no-description' ),
2137 $m->getParams()
2138 );
2139 $msgs[$param][] = $m->setContext( $this->getContext() );
2140 } else {
2141 $this->dieDebug( __METHOD__,
2142 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2143 }
2144 }
2145 }
2146
2147 if ( isset( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2148 if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2149 $this->dieDebug( __METHOD__,
2150 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2151 }
2152 foreach ( $settings[ApiBase::PARAM_HELP_MSG_APPEND] as $m ) {
2153 $m = ApiBase::makeMessage( $m, $this->getContext(),
2154 array( $prefix, $param, $name, $path ) );
2155 if ( $m ) {
2156 $msgs[$param][] = $m;
2157 } else {
2158 $this->dieDebug( __METHOD__,
2159 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2160 }
2161 }
2162 }
2163 }
2164
2165 Hooks::run( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2166
2167 return $msgs;
2168 }
2169
2170 /**
2171 * Generates the list of flags for the help screen and for action=paraminfo
2172 *
2173 * Corresponding messages: api-help-flag-deprecated,
2174 * api-help-flag-internal, api-help-flag-readrights,
2175 * api-help-flag-writerights, api-help-flag-mustbeposted
2176 *
2177 * @return string[]
2178 */
2179 protected function getHelpFlags() {
2180 $flags = array();
2181
2182 if ( $this->isDeprecated() ) {
2183 $flags[] = 'deprecated';
2184 }
2185 if ( $this->isInternal() ) {
2186 $flags[] = 'internal';
2187 }
2188 if ( $this->isReadMode() ) {
2189 $flags[] = 'readrights';
2190 }
2191 if ( $this->isWriteMode() ) {
2192 $flags[] = 'writerights';
2193 }
2194 if ( $this->mustBePosted() ) {
2195 $flags[] = 'mustbeposted';
2196 }
2197
2198 return $flags;
2199 }
2200
2201 /**
2202 * Called from ApiHelp before the pieces are joined together and returned.
2203 *
2204 * This exists mainly for ApiMain to add the Permissions and Credits
2205 * sections. Other modules probably don't need it.
2206 *
2207 * @param string[] &$help Array of help data
2208 * @param array $options Options passed to ApiHelp::getHelp
2209 */
2210 public function modifyHelp( array &$help, array $options ) {
2211 }
2212
2213 /**@}*/
2214
2215 /************************************************************************//**
2216 * @name Deprecated
2217 * @{
2218 */
2219
2220 /// @deprecated since 1.24
2221 const PROP_ROOT = 'ROOT';
2222 /// @deprecated since 1.24
2223 const PROP_LIST = 'LIST';
2224 /// @deprecated since 1.24
2225 const PROP_TYPE = 0;
2226 /// @deprecated since 1.24
2227 const PROP_NULLABLE = 1;
2228
2229 /**
2230 * Formerly returned a string that identifies the version of the extending
2231 * class. Typically included the class name, the svn revision, timestamp,
2232 * and last author. Usually done with SVN's Id keyword
2233 *
2234 * @deprecated since 1.21, version string is no longer supported
2235 * @return string
2236 */
2237 public function getVersion() {
2238 wfDeprecated( __METHOD__, '1.21' );
2239 return '';
2240 }
2241
2242 /**
2243 * Formerly used to fetch a list of possible properites in the result,
2244 * somehow organized with respect to the prop parameter that causes them to
2245 * be returned. The specific semantics of the return value was never
2246 * specified. Since this was never possible to be accurately updated, it
2247 * has been removed.
2248 *
2249 * @deprecated since 1.24
2250 * @return array|bool
2251 */
2252 protected function getResultProperties() {
2253 wfDeprecated( __METHOD__, '1.24' );
2254 return false;
2255 }
2256
2257 /**
2258 * @see self::getResultProperties()
2259 * @deprecated since 1.24
2260 * @return array|bool
2261 */
2262 public function getFinalResultProperties() {
2263 wfDeprecated( __METHOD__, '1.24' );
2264 return array();
2265 }
2266
2267 /**
2268 * @see self::getResultProperties()
2269 * @deprecated since 1.24
2270 */
2271 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2272 wfDeprecated( __METHOD__, '1.24' );
2273 }
2274
2275 /**
2276 * @see self::getPossibleErrors()
2277 * @deprecated since 1.24
2278 * @return array
2279 */
2280 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2281 wfDeprecated( __METHOD__, '1.24' );
2282 return array();
2283 }
2284
2285 /**
2286 * @see self::getPossibleErrors()
2287 * @deprecated since 1.24
2288 * @return array
2289 */
2290 public function getRequireMaxOneParameterErrorMessages( $params ) {
2291 wfDeprecated( __METHOD__, '1.24' );
2292 return array();
2293 }
2294
2295 /**
2296 * @see self::getPossibleErrors()
2297 * @deprecated since 1.24
2298 * @return array
2299 */
2300 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2301 wfDeprecated( __METHOD__, '1.24' );
2302 return array();
2303 }
2304
2305 /**
2306 * @see self::getPossibleErrors()
2307 * @deprecated since 1.24
2308 * @return array
2309 */
2310 public function getTitleOrPageIdErrorMessage() {
2311 wfDeprecated( __METHOD__, '1.24' );
2312 return array();
2313 }
2314
2315 /**
2316 * This formerly attempted to return a list of all possible errors returned
2317 * by the module. However, this was impossible to maintain in many cases
2318 * since errors could come from other areas of MediaWiki and in some cases
2319 * from arbitrary extension hooks. Since a partial list claiming to be
2320 * comprehensive is unlikely to be useful, it was removed.
2321 *
2322 * @deprecated since 1.24
2323 * @return array
2324 */
2325 public function getPossibleErrors() {
2326 wfDeprecated( __METHOD__, '1.24' );
2327 return array();
2328 }
2329
2330 /**
2331 * @see self::getPossibleErrors()
2332 * @deprecated since 1.24
2333 * @return array
2334 */
2335 public function getFinalPossibleErrors() {
2336 wfDeprecated( __METHOD__, '1.24' );
2337 return array();
2338 }
2339
2340 /**
2341 * @see self::getPossibleErrors()
2342 * @deprecated since 1.24
2343 * @return array
2344 */
2345 public function parseErrors( $errors ) {
2346 wfDeprecated( __METHOD__, '1.24' );
2347 return array();
2348 }
2349
2350 /**
2351 * Returns the description string for this module
2352 *
2353 * Ignored if an i18n message exists for
2354 * "apihelp-{$this->getModulePathString()}-description".
2355 *
2356 * @deprecated since 1.25
2357 * @return Message|string|array
2358 */
2359 protected function getDescription() {
2360 return false;
2361 }
2362
2363 /**
2364 * Returns an array of parameter descriptions.
2365 *
2366 * For each parameter, ignored if an i18n message exists for the parameter.
2367 * By default that message is
2368 * "apihelp-{$this->getModulePathString()}-param-{$param}", but it may be
2369 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2370 * self::getFinalParams().
2371 *
2372 * @deprecated since 1.25
2373 * @return array|bool False on no parameter descriptions
2374 */
2375 protected function getParamDescription() {
2376 return array();
2377 }
2378
2379 /**
2380 * Returns usage examples for this module.
2381 *
2382 * Return value as an array is either:
2383 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2384 * values
2385 * - sequential numeric keys with even-numbered keys being display-text
2386 * and odd-numbered keys being partial urls
2387 * - partial URLs as keys with display-text (string or array-to-be-joined)
2388 * as values
2389 * Return value as a string is the same as an array with a numeric key and
2390 * that value, and boolean false means "no examples".
2391 *
2392 * @deprecated since 1.25, use getExamplesMessages() instead
2393 * @return bool|string|array
2394 */
2395 protected function getExamples() {
2396 return false;
2397 }
2398
2399 /**
2400 * Generates help message for this module, or false if there is no description
2401 * @deprecated since 1.25
2402 * @return string|bool
2403 */
2404 public function makeHelpMsg() {
2405 wfDeprecated( __METHOD__, '1.25' );
2406 static $lnPrfx = "\n ";
2407
2408 $msg = $this->getFinalDescription();
2409
2410 if ( $msg !== false ) {
2411
2412 if ( !is_array( $msg ) ) {
2413 $msg = array(
2414 $msg
2415 );
2416 }
2417 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2418
2419 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2420
2421 if ( $this->isReadMode() ) {
2422 $msg .= "\nThis module requires read rights";
2423 }
2424 if ( $this->isWriteMode() ) {
2425 $msg .= "\nThis module requires write rights";
2426 }
2427 if ( $this->mustBePosted() ) {
2428 $msg .= "\nThis module only accepts POST requests";
2429 }
2430 if ( $this->isReadMode() || $this->isWriteMode() ||
2431 $this->mustBePosted()
2432 ) {
2433 $msg .= "\n";
2434 }
2435
2436 // Parameters
2437 $paramsMsg = $this->makeHelpMsgParameters();
2438 if ( $paramsMsg !== false ) {
2439 $msg .= "Parameters:\n$paramsMsg";
2440 }
2441
2442 $examples = $this->getExamples();
2443 if ( $examples ) {
2444 if ( !is_array( $examples ) ) {
2445 $examples = array(
2446 $examples
2447 );
2448 }
2449 $msg .= "Example" . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
2450 foreach ( $examples as $k => $v ) {
2451 if ( is_numeric( $k ) ) {
2452 $msg .= " $v\n";
2453 } else {
2454 if ( is_array( $v ) ) {
2455 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2456 } else {
2457 $msgExample = " $v";
2458 }
2459 $msgExample .= ":";
2460 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2461 }
2462 }
2463 }
2464 }
2465
2466 return $msg;
2467 }
2468
2469 /**
2470 * @deprecated since 1.25
2471 * @param string $item
2472 * @return string
2473 */
2474 private function indentExampleText( $item ) {
2475 return " " . $item;
2476 }
2477
2478 /**
2479 * @deprecated since 1.25
2480 * @param string $prefix Text to split output items
2481 * @param string $title What is being output
2482 * @param string|array $input
2483 * @return string
2484 */
2485 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2486 wfDeprecated( __METHOD__, '1.25' );
2487 if ( $input === false ) {
2488 return '';
2489 }
2490 if ( !is_array( $input ) ) {
2491 $input = array( $input );
2492 }
2493
2494 if ( count( $input ) > 0 ) {
2495 if ( $title ) {
2496 $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n ";
2497 } else {
2498 $msg = ' ';
2499 }
2500 $msg .= implode( $prefix, $input ) . "\n";
2501
2502 return $msg;
2503 }
2504
2505 return '';
2506 }
2507
2508 /**
2509 * Generates the parameter descriptions for this module, to be displayed in the
2510 * module's help.
2511 * @deprecated since 1.25
2512 * @return string|bool
2513 */
2514 public function makeHelpMsgParameters() {
2515 wfDeprecated( __METHOD__, '1.25' );
2516 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
2517 if ( $params ) {
2518
2519 $paramsDescription = $this->getFinalParamDescription();
2520 $msg = '';
2521 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2522 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2523 foreach ( $params as $paramName => $paramSettings ) {
2524 $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
2525 if ( is_array( $desc ) ) {
2526 $desc = implode( $paramPrefix, $desc );
2527 }
2528
2529 //handle shorthand
2530 if ( !is_array( $paramSettings ) ) {
2531 $paramSettings = array(
2532 self::PARAM_DFLT => $paramSettings,
2533 );
2534 }
2535
2536 //handle missing type
2537 if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) {
2538 $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] )
2539 ? $paramSettings[ApiBase::PARAM_DFLT]
2540 : null;
2541 if ( is_bool( $dflt ) ) {
2542 $paramSettings[ApiBase::PARAM_TYPE] = 'boolean';
2543 } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
2544 $paramSettings[ApiBase::PARAM_TYPE] = 'string';
2545 } elseif ( is_int( $dflt ) ) {
2546 $paramSettings[ApiBase::PARAM_TYPE] = 'integer';
2547 }
2548 }
2549
2550 if ( isset( $paramSettings[self::PARAM_DEPRECATED] )
2551 && $paramSettings[self::PARAM_DEPRECATED]
2552 ) {
2553 $desc = "DEPRECATED! $desc";
2554 }
2555
2556 if ( isset( $paramSettings[self::PARAM_REQUIRED] )
2557 && $paramSettings[self::PARAM_REQUIRED]
2558 ) {
2559 $desc .= $paramPrefix . "This parameter is required";
2560 }
2561
2562 $type = isset( $paramSettings[self::PARAM_TYPE] )
2563 ? $paramSettings[self::PARAM_TYPE]
2564 : null;
2565 if ( isset( $type ) ) {
2566 $hintPipeSeparated = true;
2567 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
2568 ? $paramSettings[self::PARAM_ISMULTI]
2569 : false;
2570 if ( $multi ) {
2571 $prompt = 'Values (separate with \'|\'): ';
2572 } else {
2573 $prompt = 'One value: ';
2574 }
2575
2576 if ( $type === 'submodule' ) {
2577 $type = $this->getModuleManager()->getNames( $paramName );
2578 sort( $type );
2579 }
2580 if ( is_array( $type ) ) {
2581 $choices = array();
2582 $nothingPrompt = '';
2583 foreach ( $type as $t ) {
2584 if ( $t === '' ) {
2585 $nothingPrompt = 'Can be empty, or ';
2586 } else {
2587 $choices[] = $t;
2588 }
2589 }
2590 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2591 $choicesstring = implode( ', ', $choices );
2592 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2593 $hintPipeSeparated = false;
2594 } else {
2595 switch ( $type ) {
2596 case 'namespace':
2597 // Special handling because namespaces are
2598 // type-limited, yet they are not given
2599 $desc .= $paramPrefix . $prompt;
2600 $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
2601 100, $descWordwrap );
2602 $hintPipeSeparated = false;
2603 break;
2604 case 'limit':
2605 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2606 if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
2607 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2608 }
2609 $desc .= ' allowed';
2610 break;
2611 case 'integer':
2612 $s = $multi ? 's' : '';
2613 $hasMin = isset( $paramSettings[self::PARAM_MIN] );
2614 $hasMax = isset( $paramSettings[self::PARAM_MAX] );
2615 if ( $hasMin || $hasMax ) {
2616 if ( !$hasMax ) {
2617 $intRangeStr = "The value$s must be no less than " .
2618 "{$paramSettings[self::PARAM_MIN]}";
2619 } elseif ( !$hasMin ) {
2620 $intRangeStr = "The value$s must be no more than " .
2621 "{$paramSettings[self::PARAM_MAX]}";
2622 } else {
2623 $intRangeStr = "The value$s must be between " .
2624 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2625 }
2626
2627 $desc .= $paramPrefix . $intRangeStr;
2628 }
2629 break;
2630 case 'upload':
2631 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2632 break;
2633 }
2634 }
2635
2636 if ( $multi ) {
2637 if ( $hintPipeSeparated ) {
2638 $desc .= $paramPrefix . "Separate values with '|'";
2639 }
2640
2641 $isArray = is_array( $type );
2642 if ( !$isArray
2643 || $isArray && count( $type ) > self::LIMIT_SML1
2644 ) {
2645 $desc .= $paramPrefix . "Maximum number of values " .
2646 self::LIMIT_SML1 . " (" . self::LIMIT_SML2 . " for bots)";
2647 }
2648 }
2649 }
2650
2651 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
2652 if ( !is_null( $default ) && $default !== false ) {
2653 $desc .= $paramPrefix . "Default: $default";
2654 }
2655
2656 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2657 }
2658
2659 return $msg;
2660 }
2661
2662 return false;
2663 }
2664
2665 /**
2666 * @deprecated since 1.25, always returns empty string
2667 * @param DatabaseBase|bool $db
2668 * @return string
2669 */
2670 public function getModuleProfileName( $db = false ) {
2671 wfDeprecated( __METHOD__, '1.25' );
2672 return '';
2673 }
2674
2675 /**
2676 * @deprecated since 1.25
2677 */
2678 public function profileIn() {
2679 // No wfDeprecated() yet because extensions call this and might need to
2680 // keep doing so for BC.
2681 }
2682
2683 /**
2684 * @deprecated since 1.25
2685 */
2686 public function profileOut() {
2687 // No wfDeprecated() yet because extensions call this and might need to
2688 // keep doing so for BC.
2689 }
2690
2691 /**
2692 * @deprecated since 1.25
2693 */
2694 public function safeProfileOut() {
2695 wfDeprecated( __METHOD__, '1.25' );
2696 }
2697
2698 /**
2699 * @deprecated since 1.25, always returns 0
2700 * @return float
2701 */
2702 public function getProfileTime() {
2703 wfDeprecated( __METHOD__, '1.25' );
2704 return 0;
2705 }
2706
2707 /**
2708 * @deprecated since 1.25
2709 */
2710 public function profileDBIn() {
2711 wfDeprecated( __METHOD__, '1.25' );
2712 }
2713
2714 /**
2715 * @deprecated since 1.25
2716 */
2717 public function profileDBOut() {
2718 wfDeprecated( __METHOD__, '1.25' );
2719 }
2720
2721 /**
2722 * @deprecated since 1.25, always returns 0
2723 * @return float
2724 */
2725 public function getProfileDBTime() {
2726 wfDeprecated( __METHOD__, '1.25' );
2727 return 0;
2728 }
2729
2730 /**
2731 * Get the result data array (read-only)
2732 * @deprecated since 1.25, use $this->getResult() methods instead
2733 * @return array
2734 */
2735 public function getResultData() {
2736 return $this->getResult()->getData();
2737 }
2738
2739 /**@}*/
2740 }
2741
2742 /**
2743 * For really cool vim folding this needs to be at the end:
2744 * vim: foldmarker=@{,@} foldmethod=marker
2745 */