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