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