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