Add tests for WikiMap and WikiReference
[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 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1060 $this->warnOrDie( $msg, $enforceLimits );
1061 $value = $min;
1062 }
1063
1064 // Minimum is always validated, whereas maximum is checked only if not
1065 // running in internal call mode
1066 if ( $this->getMain()->isInternalMode() ) {
1067 return;
1068 }
1069
1070 // Optimization: do not check user's bot status unless really needed -- skips db query
1071 // assumes $botMax >= $max
1072 if ( !is_null( $max ) && $value > $max ) {
1073 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1074 if ( $value > $botMax ) {
1075 $msg = $this->encodeParamName( $paramName ) .
1076 " may not be over $botMax (set to $value) for bots or sysops";
1077 $this->warnOrDie( $msg, $enforceLimits );
1078 $value = $botMax;
1079 }
1080 } else {
1081 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1082 $this->warnOrDie( $msg, $enforceLimits );
1083 $value = $max;
1084 }
1085 }
1086 }
1087
1088 /**
1089 * Validate and normalize of parameters of type 'timestamp'
1090 * @param string $value Parameter value
1091 * @param string $encParamName Parameter name
1092 * @return string Validated and normalized parameter
1093 */
1094 protected function validateTimestamp( $value, $encParamName ) {
1095 // Confusing synonyms for the current time accepted by wfTimestamp()
1096 // (wfTimestamp() also accepts various non-strings and the string of 14
1097 // ASCII NUL bytes, but those can't get here)
1098 if ( !$value ) {
1099 $this->logFeatureUsage( 'unclear-"now"-timestamp' );
1100 $this->setWarning(
1101 "Passing '$value' for timestamp parameter $encParamName has been deprecated." .
1102 ' If for some reason you need to explicitly specify the current time without' .
1103 ' calculating it client-side, use "now".'
1104 );
1105 return wfTimestamp( TS_MW );
1106 }
1107
1108 // Explicit synonym for the current time
1109 if ( $value === 'now' ) {
1110 return wfTimestamp( TS_MW );
1111 }
1112
1113 $unixTimestamp = wfTimestamp( TS_UNIX, $value );
1114 if ( $unixTimestamp === false ) {
1115 $this->dieUsage(
1116 "Invalid value '$value' for timestamp parameter $encParamName",
1117 "badtimestamp_{$encParamName}"
1118 );
1119 }
1120
1121 return wfTimestamp( TS_MW, $unixTimestamp );
1122 }
1123
1124 /**
1125 * Validate the supplied token.
1126 *
1127 * @since 1.24
1128 * @param string $token Supplied token
1129 * @param array $params All supplied parameters for the module
1130 * @return bool
1131 * @throws MWException
1132 */
1133 final public function validateToken( $token, array $params ) {
1134 $tokenType = $this->needsToken();
1135 $salts = ApiQueryTokens::getTokenTypeSalts();
1136 if ( !isset( $salts[$tokenType] ) ) {
1137 throw new MWException(
1138 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1139 'without registering it'
1140 );
1141 }
1142
1143 if ( $this->getUser()->matchEditToken(
1144 $token,
1145 $salts[$tokenType],
1146 $this->getRequest()
1147 ) ) {
1148 return true;
1149 }
1150
1151 $webUiSalt = $this->getWebUITokenSalt( $params );
1152 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1153 $token,
1154 $webUiSalt,
1155 $this->getRequest()
1156 ) ) {
1157 return true;
1158 }
1159
1160 return false;
1161 }
1162
1163 /**
1164 * Validate and normalize of parameters of type 'user'
1165 * @param string $value Parameter value
1166 * @param string $encParamName Parameter name
1167 * @return string Validated and normalized parameter
1168 */
1169 private function validateUser( $value, $encParamName ) {
1170 $title = Title::makeTitleSafe( NS_USER, $value );
1171 if ( $title === null ) {
1172 $this->dieUsage(
1173 "Invalid value '$value' for user parameter $encParamName",
1174 "baduser_{$encParamName}"
1175 );
1176 }
1177
1178 return $title->getText();
1179 }
1180
1181 /**@}*/
1182
1183 /************************************************************************//**
1184 * @name Utility methods
1185 * @{
1186 */
1187
1188 /**
1189 * Set a watch (or unwatch) based the based on a watchlist parameter.
1190 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1191 * @param Title $titleObj The article's title to change
1192 * @param string $userOption The user option to consider when $watch=preferences
1193 */
1194 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1195 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1196 if ( $value === null ) {
1197 return;
1198 }
1199
1200 WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1201 }
1202
1203 /**
1204 * Truncate an array to a certain length.
1205 * @param array $arr Array to truncate
1206 * @param int $limit Maximum length
1207 * @return bool True if the array was truncated, false otherwise
1208 */
1209 public static function truncateArray( &$arr, $limit ) {
1210 $modified = false;
1211 while ( count( $arr ) > $limit ) {
1212 array_pop( $arr );
1213 $modified = true;
1214 }
1215
1216 return $modified;
1217 }
1218
1219 /**
1220 * Gets the user for whom to get the watchlist
1221 *
1222 * @param array $params
1223 * @return User
1224 */
1225 public function getWatchlistUser( $params ) {
1226 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1227 $user = User::newFromName( $params['owner'], false );
1228 if ( !( $user && $user->getId() ) ) {
1229 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1230 }
1231 $token = $user->getOption( 'watchlisttoken' );
1232 if ( $token == '' || !hash_equals( $token, $params['token'] ) ) {
1233 $this->dieUsage(
1234 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1235 'bad_wltoken'
1236 );
1237 }
1238 } else {
1239 if ( !$this->getUser()->isLoggedIn() ) {
1240 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1241 }
1242 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1243 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1244 }
1245 $user = $this->getUser();
1246 }
1247
1248 return $user;
1249 }
1250
1251 /**
1252 * A subset of wfEscapeWikiText for BC texts
1253 *
1254 * @since 1.25
1255 * @param string|array $v
1256 * @return string|array
1257 */
1258 private static function escapeWikiText( $v ) {
1259 if ( is_array( $v ) ) {
1260 return array_map( 'self::escapeWikiText', $v );
1261 } else {
1262 return strtr( $v, array(
1263 '__' => '_&#95;', '{' => '&#123;', '}' => '&#125;',
1264 '[[Category:' => '[[:Category:',
1265 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1266 ) );
1267 }
1268 }
1269
1270 /**
1271 * Create a Message from a string or array
1272 *
1273 * A string is used as a message key. An array has the message key as the
1274 * first value and message parameters as subsequent values.
1275 *
1276 * @since 1.25
1277 * @param string|array|Message $msg
1278 * @param IContextSource $context
1279 * @param array $params
1280 * @return Message|null
1281 */
1282 public static function makeMessage( $msg, IContextSource $context, array $params = null ) {
1283 if ( is_string( $msg ) ) {
1284 $msg = wfMessage( $msg );
1285 } elseif ( is_array( $msg ) ) {
1286 $msg = call_user_func_array( 'wfMessage', $msg );
1287 }
1288 if ( !$msg instanceof Message ) {
1289 return null;
1290 }
1291
1292 $msg->setContext( $context );
1293 if ( $params ) {
1294 $msg->params( $params );
1295 }
1296
1297 return $msg;
1298 }
1299
1300 /**@}*/
1301
1302 /************************************************************************//**
1303 * @name Warning and error reporting
1304 * @{
1305 */
1306
1307 /**
1308 * Set warning section for this module. Users should monitor this
1309 * section to notice any changes in API. Multiple calls to this
1310 * function will result in the warning messages being separated by
1311 * newlines
1312 * @param string $warning Warning message
1313 */
1314 public function setWarning( $warning ) {
1315 $msg = new ApiRawMessage( $warning, 'warning' );
1316 $this->getErrorFormatter()->addWarning( $this->getModuleName(), $msg );
1317 }
1318
1319 /**
1320 * Adds a warning to the output, else dies
1321 *
1322 * @param string $msg Message to show as a warning, or error message if dying
1323 * @param bool $enforceLimits Whether this is an enforce (die)
1324 */
1325 private function warnOrDie( $msg, $enforceLimits = false ) {
1326 if ( $enforceLimits ) {
1327 $this->dieUsage( $msg, 'integeroutofrange' );
1328 }
1329
1330 $this->setWarning( $msg );
1331 }
1332
1333 /**
1334 * Throw a UsageException, which will (if uncaught) call the main module's
1335 * error handler and die with an error message.
1336 *
1337 * @param string $description One-line human-readable description of the
1338 * error condition, e.g., "The API requires a valid action parameter"
1339 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1340 * automated identification of the error, e.g., 'unknown_action'
1341 * @param int $httpRespCode HTTP response code
1342 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1343 * @throws UsageException
1344 */
1345 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1346 throw new UsageException(
1347 $description,
1348 $this->encodeParamName( $errorCode ),
1349 $httpRespCode,
1350 $extradata
1351 );
1352 }
1353
1354 /**
1355 * Get error (as code, string) from a Status object.
1356 *
1357 * @since 1.23
1358 * @param Status $status
1359 * @return array Array of code and error string
1360 * @throws MWException
1361 */
1362 public function getErrorFromStatus( $status ) {
1363 if ( $status->isGood() ) {
1364 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1365 }
1366
1367 $errors = $status->getErrorsArray();
1368 if ( !$errors ) {
1369 // No errors? Assume the warnings should be treated as errors
1370 $errors = $status->getWarningsArray();
1371 }
1372 if ( !$errors ) {
1373 // Still no errors? Punt
1374 $errors = array( array( 'unknownerror-nocode' ) );
1375 }
1376
1377 // Cannot use dieUsageMsg() because extensions might return custom
1378 // error messages.
1379 if ( $errors[0] instanceof Message ) {
1380 $msg = $errors[0];
1381 $code = $msg->getKey();
1382 } else {
1383 $code = array_shift( $errors[0] );
1384 $msg = wfMessage( $code, $errors[0] );
1385 }
1386 if ( isset( ApiBase::$messageMap[$code] ) ) {
1387 // Translate message to code, for backwards compatibility
1388 $code = ApiBase::$messageMap[$code]['code'];
1389 }
1390
1391 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1392 }
1393
1394 /**
1395 * Throw a UsageException based on the errors in the Status object.
1396 *
1397 * @since 1.22
1398 * @param Status $status
1399 * @throws MWException
1400 */
1401 public function dieStatus( $status ) {
1402
1403 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1404 $this->dieUsage( $msg, $code );
1405 }
1406
1407 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1408 /**
1409 * Array that maps message keys to error messages. $1 and friends are replaced.
1410 */
1411 public static $messageMap = array(
1412 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1413 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1414 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1415
1416 // Messages from Title::getUserPermissionsErrors()
1417 'ns-specialprotected' => array(
1418 'code' => 'unsupportednamespace',
1419 'info' => "Pages in the Special namespace can't be edited"
1420 ),
1421 'protectedinterface' => array(
1422 'code' => 'protectednamespace-interface',
1423 'info' => "You're not allowed to edit interface messages"
1424 ),
1425 'namespaceprotected' => array(
1426 'code' => 'protectednamespace',
1427 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1428 ),
1429 'customcssprotected' => array(
1430 'code' => 'customcssprotected',
1431 'info' => "You're not allowed to edit custom CSS pages"
1432 ),
1433 'customjsprotected' => array(
1434 'code' => 'customjsprotected',
1435 'info' => "You're not allowed to edit custom JavaScript pages"
1436 ),
1437 'cascadeprotected' => array(
1438 'code' => 'cascadeprotected',
1439 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1440 ),
1441 'protectedpagetext' => array(
1442 'code' => 'protectedpage',
1443 'info' => "The \"\$1\" right is required to edit this page"
1444 ),
1445 'protect-cantedit' => array(
1446 'code' => 'cantedit',
1447 'info' => "You can't protect this page because you can't edit it"
1448 ),
1449 'deleteprotected' => array(
1450 'code' => 'cantedit',
1451 'info' => "You can't delete this page because it has been protected"
1452 ),
1453 'badaccess-group0' => array(
1454 'code' => 'permissiondenied',
1455 'info' => "Permission denied"
1456 ), // Generic permission denied message
1457 'badaccess-groups' => array(
1458 'code' => 'permissiondenied',
1459 'info' => "Permission denied"
1460 ),
1461 'titleprotected' => array(
1462 'code' => 'protectedtitle',
1463 'info' => "This title has been protected from creation"
1464 ),
1465 'nocreate-loggedin' => array(
1466 'code' => 'cantcreate',
1467 'info' => "You don't have permission to create new pages"
1468 ),
1469 'nocreatetext' => array(
1470 'code' => 'cantcreate-anon',
1471 'info' => "Anonymous users can't create new pages"
1472 ),
1473 'movenologintext' => array(
1474 'code' => 'cantmove-anon',
1475 'info' => "Anonymous users can't move pages"
1476 ),
1477 'movenotallowed' => array(
1478 'code' => 'cantmove',
1479 'info' => "You don't have permission to move pages"
1480 ),
1481 'confirmedittext' => array(
1482 'code' => 'confirmemail',
1483 'info' => "You must confirm your email address before you can edit"
1484 ),
1485 'blockedtext' => array(
1486 'code' => 'blocked',
1487 'info' => "You have been blocked from editing"
1488 ),
1489 'autoblockedtext' => array(
1490 'code' => 'autoblocked',
1491 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1492 ),
1493
1494 // Miscellaneous interface messages
1495 'actionthrottledtext' => array(
1496 'code' => 'ratelimited',
1497 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1498 ),
1499 'alreadyrolled' => array(
1500 'code' => 'alreadyrolled',
1501 'info' => "The page you tried to rollback was already rolled back"
1502 ),
1503 'cantrollback' => array(
1504 'code' => 'onlyauthor',
1505 'info' => "The page you tried to rollback only has one author"
1506 ),
1507 'readonlytext' => array(
1508 'code' => 'readonly',
1509 'info' => "The wiki is currently in read-only mode"
1510 ),
1511 'sessionfailure' => array(
1512 'code' => 'badtoken',
1513 'info' => "Invalid token" ),
1514 'cannotdelete' => array(
1515 'code' => 'cantdelete',
1516 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1517 ),
1518 'notanarticle' => array(
1519 'code' => 'missingtitle',
1520 'info' => "The page you requested doesn't exist"
1521 ),
1522 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1523 ),
1524 'immobile_namespace' => array(
1525 'code' => 'immobilenamespace',
1526 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1527 ),
1528 'articleexists' => array(
1529 'code' => 'articleexists',
1530 'info' => "The destination article already exists and is not a redirect to the source article"
1531 ),
1532 'protectedpage' => array(
1533 'code' => 'protectedpage',
1534 'info' => "You don't have permission to perform this move"
1535 ),
1536 'hookaborted' => array(
1537 'code' => 'hookaborted',
1538 'info' => "The modification you tried to make was aborted by an extension hook"
1539 ),
1540 'cantmove-titleprotected' => array(
1541 'code' => 'protectedtitle',
1542 'info' => "The destination article has been protected from creation"
1543 ),
1544 'imagenocrossnamespace' => array(
1545 'code' => 'nonfilenamespace',
1546 'info' => "Can't move a file to a non-file namespace"
1547 ),
1548 'imagetypemismatch' => array(
1549 'code' => 'filetypemismatch',
1550 'info' => "The new file extension doesn't match its type"
1551 ),
1552 // 'badarticleerror' => shouldn't happen
1553 // 'badtitletext' => shouldn't happen
1554 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1555 'range_block_disabled' => array(
1556 'code' => 'rangedisabled',
1557 'info' => "Blocking IP ranges has been disabled"
1558 ),
1559 'nosuchusershort' => array(
1560 'code' => 'nosuchuser',
1561 'info' => "The user you specified doesn't exist"
1562 ),
1563 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1564 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1565 'ipb_already_blocked' => array(
1566 'code' => 'alreadyblocked',
1567 'info' => "The user you tried to block was already blocked"
1568 ),
1569 'ipb_blocked_as_range' => array(
1570 'code' => 'blockedasrange',
1571 '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."
1572 ),
1573 'ipb_cant_unblock' => array(
1574 'code' => 'cantunblock',
1575 'info' => "The block you specified was not found. It may have been unblocked already"
1576 ),
1577 'mailnologin' => array(
1578 'code' => 'cantsend',
1579 '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"
1580 ),
1581 'ipbblocked' => array(
1582 'code' => 'ipbblocked',
1583 'info' => 'You cannot block or unblock users while you are yourself blocked'
1584 ),
1585 'ipbnounblockself' => array(
1586 'code' => 'ipbnounblockself',
1587 'info' => 'You are not allowed to unblock yourself'
1588 ),
1589 'usermaildisabled' => array(
1590 'code' => 'usermaildisabled',
1591 'info' => "User email has been disabled"
1592 ),
1593 'blockedemailuser' => array(
1594 'code' => 'blockedfrommail',
1595 'info' => "You have been blocked from sending email"
1596 ),
1597 'notarget' => array(
1598 'code' => 'notarget',
1599 'info' => "You have not specified a valid target for this action"
1600 ),
1601 'noemail' => array(
1602 'code' => 'noemail',
1603 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1604 ),
1605 'rcpatroldisabled' => array(
1606 'code' => 'patroldisabled',
1607 'info' => "Patrolling is disabled on this wiki"
1608 ),
1609 'markedaspatrollederror-noautopatrol' => array(
1610 'code' => 'noautopatrol',
1611 'info' => "You don't have permission to patrol your own changes"
1612 ),
1613 'delete-toobig' => array(
1614 'code' => 'bigdelete',
1615 'info' => "You can't delete this page because it has more than \$1 revisions"
1616 ),
1617 'movenotallowedfile' => array(
1618 'code' => 'cantmovefile',
1619 'info' => "You don't have permission to move files"
1620 ),
1621 'userrights-no-interwiki' => array(
1622 'code' => 'nointerwikiuserrights',
1623 'info' => "You don't have permission to change user rights on other wikis"
1624 ),
1625 'userrights-nodatabase' => array(
1626 'code' => 'nosuchdatabase',
1627 'info' => "Database \"\$1\" does not exist or is not local"
1628 ),
1629 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1630 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1631 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1632 'import-rootpage-invalid' => array(
1633 'code' => 'import-rootpage-invalid',
1634 'info' => 'Root page is an invalid title'
1635 ),
1636 'import-rootpage-nosubpage' => array(
1637 'code' => 'import-rootpage-nosubpage',
1638 'info' => 'Namespace "$1" of the root page does not allow subpages'
1639 ),
1640
1641 // API-specific messages
1642 'readrequired' => array(
1643 'code' => 'readapidenied',
1644 'info' => "You need read permission to use this module"
1645 ),
1646 'writedisabled' => array(
1647 'code' => 'noapiwrite',
1648 '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"
1649 ),
1650 'writerequired' => array(
1651 'code' => 'writeapidenied',
1652 'info' => "You're not allowed to edit this wiki through the API"
1653 ),
1654 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1655 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1656 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1657 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1658 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1659 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1660 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1661 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1662 'create-titleexists' => array(
1663 'code' => 'create-titleexists',
1664 'info' => "Existing titles can't be protected with 'create'"
1665 ),
1666 'missingtitle-createonly' => array(
1667 'code' => 'missingtitle-createonly',
1668 'info' => "Missing titles can only be protected with 'create'"
1669 ),
1670 'cantblock' => array( 'code' => 'cantblock',
1671 'info' => "You don't have permission to block users"
1672 ),
1673 'canthide' => array(
1674 'code' => 'canthide',
1675 'info' => "You don't have permission to hide user names from the block log"
1676 ),
1677 'cantblock-email' => array(
1678 'code' => 'cantblock-email',
1679 'info' => "You don't have permission to block users from sending email through the wiki"
1680 ),
1681 'unblock-notarget' => array(
1682 'code' => 'notarget',
1683 'info' => "Either the id or the user parameter must be set"
1684 ),
1685 'unblock-idanduser' => array(
1686 'code' => 'idanduser',
1687 'info' => "The id and user parameters can't be used together"
1688 ),
1689 'cantunblock' => array(
1690 'code' => 'permissiondenied',
1691 'info' => "You don't have permission to unblock users"
1692 ),
1693 'cannotundelete' => array(
1694 'code' => 'cantundelete',
1695 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1696 ),
1697 'permdenied-undelete' => array(
1698 'code' => 'permissiondenied',
1699 'info' => "You don't have permission to restore deleted revisions"
1700 ),
1701 'createonly-exists' => array(
1702 'code' => 'articleexists',
1703 'info' => "The article you tried to create has been created already"
1704 ),
1705 'nocreate-missing' => array(
1706 'code' => 'missingtitle',
1707 'info' => "The article you tried to edit doesn't exist"
1708 ),
1709 'cantchangecontentmodel' => array(
1710 'code' => 'cantchangecontentmodel',
1711 'info' => "You don't have permission to change the content model of a page"
1712 ),
1713 'nosuchrcid' => array(
1714 'code' => 'nosuchrcid',
1715 'info' => "There is no change with rcid \"\$1\""
1716 ),
1717 'nosuchlogid' => array(
1718 'code' => 'nosuchlogid',
1719 'info' => "There is no log entry with ID \"\$1\""
1720 ),
1721 'protect-invalidaction' => array(
1722 'code' => 'protect-invalidaction',
1723 'info' => "Invalid protection type \"\$1\""
1724 ),
1725 'protect-invalidlevel' => array(
1726 'code' => 'protect-invalidlevel',
1727 'info' => "Invalid protection level \"\$1\""
1728 ),
1729 'toofewexpiries' => array(
1730 'code' => 'toofewexpiries',
1731 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1732 ),
1733 'cantimport' => array(
1734 'code' => 'cantimport',
1735 'info' => "You don't have permission to import pages"
1736 ),
1737 'cantimport-upload' => array(
1738 'code' => 'cantimport-upload',
1739 'info' => "You don't have permission to import uploaded pages"
1740 ),
1741 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1742 'importuploaderrorsize' => array(
1743 'code' => 'filetoobig',
1744 'info' => 'The file you uploaded is bigger than the maximum upload size'
1745 ),
1746 'importuploaderrorpartial' => array(
1747 'code' => 'partialupload',
1748 'info' => 'The file was only partially uploaded'
1749 ),
1750 'importuploaderrortemp' => array(
1751 'code' => 'notempdir',
1752 'info' => 'The temporary upload directory is missing'
1753 ),
1754 'importcantopen' => array(
1755 'code' => 'cantopenfile',
1756 'info' => "Couldn't open the uploaded file"
1757 ),
1758 'import-noarticle' => array(
1759 'code' => 'badinterwiki',
1760 'info' => 'Invalid interwiki title specified'
1761 ),
1762 'importbadinterwiki' => array(
1763 'code' => 'badinterwiki',
1764 'info' => 'Invalid interwiki title specified'
1765 ),
1766 'import-unknownerror' => array(
1767 'code' => 'import-unknownerror',
1768 'info' => "Unknown error on import: \"\$1\""
1769 ),
1770 'cantoverwrite-sharedfile' => array(
1771 'code' => 'cantoverwrite-sharedfile',
1772 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1773 ),
1774 'sharedfile-exists' => array(
1775 'code' => 'fileexists-sharedrepo-perm',
1776 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1777 ),
1778 'mustbeposted' => array(
1779 'code' => 'mustbeposted',
1780 'info' => "The \$1 module requires a POST request"
1781 ),
1782 'show' => array(
1783 'code' => 'show',
1784 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1785 ),
1786 'specialpage-cantexecute' => array(
1787 'code' => 'specialpage-cantexecute',
1788 'info' => "You don't have permission to view the results of this special page"
1789 ),
1790 'invalidoldimage' => array(
1791 'code' => 'invalidoldimage',
1792 'info' => 'The oldimage parameter has invalid format'
1793 ),
1794 'nodeleteablefile' => array(
1795 'code' => 'nodeleteablefile',
1796 'info' => 'No such old version of the file'
1797 ),
1798 'fileexists-forbidden' => array(
1799 'code' => 'fileexists-forbidden',
1800 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1801 ),
1802 'fileexists-shared-forbidden' => array(
1803 'code' => 'fileexists-shared-forbidden',
1804 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1805 ),
1806 'filerevert-badversion' => array(
1807 'code' => 'filerevert-badversion',
1808 'info' => 'There is no previous local version of this file with the provided timestamp.'
1809 ),
1810
1811 // ApiEditPage messages
1812 'noimageredirect-anon' => array(
1813 'code' => 'noimageredirect-anon',
1814 'info' => "Anonymous users can't create image redirects"
1815 ),
1816 'noimageredirect-logged' => array(
1817 'code' => 'noimageredirect',
1818 'info' => "You don't have permission to create image redirects"
1819 ),
1820 'spamdetected' => array(
1821 'code' => 'spamdetected',
1822 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1823 ),
1824 'contenttoobig' => array(
1825 'code' => 'contenttoobig',
1826 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1827 ),
1828 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1829 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1830 'wasdeleted' => array(
1831 'code' => 'pagedeleted',
1832 'info' => "The page has been deleted since you fetched its timestamp"
1833 ),
1834 'blankpage' => array(
1835 'code' => 'emptypage',
1836 'info' => "Creating new, empty pages is not allowed"
1837 ),
1838 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1839 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1840 'missingtext' => array(
1841 'code' => 'notext',
1842 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1843 ),
1844 'emptynewsection' => array(
1845 'code' => 'emptynewsection',
1846 'info' => 'Creating empty new sections is not possible.'
1847 ),
1848 'revwrongpage' => array(
1849 'code' => 'revwrongpage',
1850 'info' => "r\$1 is not a revision of \"\$2\""
1851 ),
1852 'undo-failure' => array(
1853 'code' => 'undofailure',
1854 'info' => 'Undo failed due to conflicting intermediate edits'
1855 ),
1856 'content-not-allowed-here' => array(
1857 'code' => 'contentnotallowedhere',
1858 'info' => 'Content model "$1" is not allowed at title "$2"'
1859 ),
1860
1861 // Messages from WikiPage::doEit()
1862 'edit-hook-aborted' => array(
1863 'code' => 'edit-hook-aborted',
1864 'info' => "Your edit was aborted by an ArticleSave hook"
1865 ),
1866 'edit-gone-missing' => array(
1867 'code' => 'edit-gone-missing',
1868 'info' => "The page you tried to edit doesn't seem to exist anymore"
1869 ),
1870 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1871 'edit-already-exists' => array(
1872 'code' => 'edit-already-exists',
1873 'info' => 'It seems the page you tried to create already exist'
1874 ),
1875
1876 // uploadMsgs
1877 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1878 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1879 'uploaddisabled' => array(
1880 'code' => 'uploaddisabled',
1881 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1882 ),
1883 'copyuploaddisabled' => array(
1884 'code' => 'copyuploaddisabled',
1885 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1886 ),
1887 'copyuploadbaddomain' => array(
1888 'code' => 'copyuploadbaddomain',
1889 'info' => 'Uploads by URL are not allowed from this domain.'
1890 ),
1891 'copyuploadbadurl' => array(
1892 'code' => 'copyuploadbadurl',
1893 'info' => 'Upload not allowed from this URL.'
1894 ),
1895
1896 'filename-tooshort' => array(
1897 'code' => 'filename-tooshort',
1898 'info' => 'The filename is too short'
1899 ),
1900 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1901 'illegal-filename' => array(
1902 'code' => 'illegal-filename',
1903 'info' => 'The filename is not allowed'
1904 ),
1905 'filetype-missing' => array(
1906 'code' => 'filetype-missing',
1907 'info' => 'The file is missing an extension'
1908 ),
1909
1910 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1911 );
1912 // @codingStandardsIgnoreEnd
1913
1914 /**
1915 * Helper function for readonly errors
1916 */
1917 public function dieReadOnly() {
1918 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1919 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1920 array( 'readonlyreason' => wfReadOnlyReason() ) );
1921 }
1922
1923 /**
1924 * Output the error message related to a certain array
1925 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1926 */
1927 public function dieUsageMsg( $error ) {
1928 # most of the time we send a 1 element, so we might as well send it as
1929 # a string and make this an array here.
1930 if ( is_string( $error ) ) {
1931 $error = array( $error );
1932 }
1933 $parsed = $this->parseMsg( $error );
1934 $this->dieUsage( $parsed['info'], $parsed['code'] );
1935 }
1936
1937 /**
1938 * Will only set a warning instead of failing if the global $wgDebugAPI
1939 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1940 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1941 * @since 1.21
1942 */
1943 public function dieUsageMsgOrDebug( $error ) {
1944 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1945 $this->dieUsageMsg( $error );
1946 }
1947
1948 if ( is_string( $error ) ) {
1949 $error = array( $error );
1950 }
1951 $parsed = $this->parseMsg( $error );
1952 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1953 }
1954
1955 /**
1956 * Die with the $prefix.'badcontinue' error. This call is common enough to
1957 * make it into the base method.
1958 * @param bool $condition Will only die if this value is true
1959 * @since 1.21
1960 */
1961 protected function dieContinueUsageIf( $condition ) {
1962 if ( $condition ) {
1963 $this->dieUsage(
1964 'Invalid continue param. You should pass the original value returned by the previous query',
1965 'badcontinue' );
1966 }
1967 }
1968
1969 /**
1970 * Return the error message related to a certain array
1971 * @param array $error Element of a getUserPermissionsErrors()-style array
1972 * @return array('code' => code, 'info' => info)
1973 */
1974 public function parseMsg( $error ) {
1975 $error = (array)$error; // It seems strings sometimes make their way in here
1976 $key = array_shift( $error );
1977
1978 // Check whether the error array was nested
1979 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1980 if ( is_array( $key ) ) {
1981 $error = $key;
1982 $key = array_shift( $error );
1983 }
1984
1985 if ( isset( self::$messageMap[$key] ) ) {
1986 return array(
1987 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
1988 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
1989 );
1990 }
1991
1992 // If the key isn't present, throw an "unknown error"
1993 return $this->parseMsg( array( 'unknownerror', $key ) );
1994 }
1995
1996 /**
1997 * Internal code errors should be reported with this method
1998 * @param string $method Method or function name
1999 * @param string $message Error message
2000 * @throws MWException
2001 */
2002 protected static function dieDebug( $method, $message ) {
2003 throw new MWException( "Internal error in $method: $message" );
2004 }
2005
2006 /**
2007 * Write logging information for API features to a debug log, for usage
2008 * analysis.
2009 * @param string $feature Feature being used.
2010 */
2011 protected function logFeatureUsage( $feature ) {
2012 $request = $this->getRequest();
2013 $s = '"' . addslashes( $feature ) . '"' .
2014 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2015 ' "' . $request->getIP() . '"' .
2016 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2017 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2018 wfDebugLog( 'api-feature-usage', $s, 'private' );
2019 }
2020
2021 /**@}*/
2022
2023 /************************************************************************//**
2024 * @name Help message generation
2025 * @{
2026 */
2027
2028 /**
2029 * Return the description message.
2030 *
2031 * @return string|array|Message
2032 */
2033 protected function getDescriptionMessage() {
2034 return "apihelp-{$this->getModulePath()}-description";
2035 }
2036
2037 /**
2038 * Get final module description, after hooks have had a chance to tweak it as
2039 * needed.
2040 *
2041 * @since 1.25, returns Message[] rather than string[]
2042 * @return Message[]
2043 */
2044 public function getFinalDescription() {
2045 $desc = $this->getDescription();
2046 Hooks::run( 'APIGetDescription', array( &$this, &$desc ) );
2047 $desc = self::escapeWikiText( $desc );
2048 if ( is_array( $desc ) ) {
2049 $desc = join( "\n", $desc );
2050 } else {
2051 $desc = (string)$desc;
2052 }
2053
2054 $msg = ApiBase::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
2055 $this->getModulePrefix(),
2056 $this->getModuleName(),
2057 $this->getModulePath(),
2058 ) );
2059 if ( !$msg->exists() ) {
2060 $msg = $this->msg( 'api-help-fallback-description', $desc );
2061 }
2062 $msgs = array( $msg );
2063
2064 Hooks::run( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
2065
2066 return $msgs;
2067 }
2068
2069 /**
2070 * Get final list of parameters, after hooks have had a chance to
2071 * tweak it as needed.
2072 *
2073 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2074 * @return array|bool False on no parameters
2075 * @since 1.21 $flags param added
2076 */
2077 public function getFinalParams( $flags = 0 ) {
2078 $params = $this->getAllowedParams( $flags );
2079 if ( !$params ) {
2080 $params = array();
2081 }
2082
2083 if ( $this->needsToken() ) {
2084 $params['token'] = array(
2085 ApiBase::PARAM_TYPE => 'string',
2086 ApiBase::PARAM_REQUIRED => true,
2087 ApiBase::PARAM_HELP_MSG => array(
2088 'api-help-param-token',
2089 $this->needsToken(),
2090 ),
2091 ) + ( isset( $params['token'] ) ? $params['token'] : array() );
2092 }
2093
2094 Hooks::run( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2095
2096 return $params;
2097 }
2098
2099 /**
2100 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2101 * needed.
2102 *
2103 * @since 1.25, returns array of Message[] rather than array of string[]
2104 * @return array Keys are parameter names, values are arrays of Message objects
2105 */
2106 public function getFinalParamDescription() {
2107 $prefix = $this->getModulePrefix();
2108 $name = $this->getModuleName();
2109 $path = $this->getModulePath();
2110
2111 $desc = $this->getParamDescription();
2112 Hooks::run( 'APIGetParamDescription', array( &$this, &$desc ) );
2113
2114 if ( !$desc ) {
2115 $desc = array();
2116 }
2117 $desc = self::escapeWikiText( $desc );
2118
2119 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
2120 $msgs = array();
2121 foreach ( $params as $param => $settings ) {
2122 if ( !is_array( $settings ) ) {
2123 $settings = array();
2124 }
2125
2126 $d = isset( $desc[$param] ) ? $desc[$param] : '';
2127 if ( is_array( $d ) ) {
2128 // Special handling for prop parameters
2129 $d = array_map( function ( $line ) {
2130 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2131 $line = "\n;{$m[1]}:{$m[2]}";
2132 }
2133 return $line;
2134 }, $d );
2135 $d = join( ' ', $d );
2136 }
2137
2138 if ( isset( $settings[ApiBase::PARAM_HELP_MSG] ) ) {
2139 $msg = $settings[ApiBase::PARAM_HELP_MSG];
2140 } else {
2141 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2142 if ( !$msg->exists() ) {
2143 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2144 }
2145 }
2146 $msg = ApiBase::makeMessage( $msg, $this->getContext(),
2147 array( $prefix, $param, $name, $path ) );
2148 if ( !$msg ) {
2149 $this->dieDebug( __METHOD__,
2150 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2151 }
2152 $msgs[$param] = array( $msg );
2153
2154 if ( isset( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
2155 if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
2156 $this->dieDebug( __METHOD__,
2157 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2158 }
2159 if ( !is_array( $settings[ApiBase::PARAM_TYPE] ) ) {
2160 $this->dieDebug( __METHOD__,
2161 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2162 'ApiBase::PARAM_TYPE is an array' );
2163 }
2164
2165 $valueMsgs = $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE];
2166 foreach ( $settings[ApiBase::PARAM_TYPE] as $value ) {
2167 if ( isset( $valueMsgs[$value] ) ) {
2168 $msg = $valueMsgs[$value];
2169 } else {
2170 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2171 }
2172 $m = ApiBase::makeMessage( $msg, $this->getContext(),
2173 array( $prefix, $param, $name, $path, $value ) );
2174 if ( $m ) {
2175 $m = new ApiHelpParamValueMessage(
2176 $value,
2177 array( $m->getKey(), 'api-help-param-no-description' ),
2178 $m->getParams()
2179 );
2180 $msgs[$param][] = $m->setContext( $this->getContext() );
2181 } else {
2182 $this->dieDebug( __METHOD__,
2183 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2184 }
2185 }
2186 }
2187
2188 if ( isset( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2189 if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2190 $this->dieDebug( __METHOD__,
2191 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2192 }
2193 foreach ( $settings[ApiBase::PARAM_HELP_MSG_APPEND] as $m ) {
2194 $m = ApiBase::makeMessage( $m, $this->getContext(),
2195 array( $prefix, $param, $name, $path ) );
2196 if ( $m ) {
2197 $msgs[$param][] = $m;
2198 } else {
2199 $this->dieDebug( __METHOD__,
2200 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2201 }
2202 }
2203 }
2204 }
2205
2206 Hooks::run( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2207
2208 return $msgs;
2209 }
2210
2211 /**
2212 * Generates the list of flags for the help screen and for action=paraminfo
2213 *
2214 * Corresponding messages: api-help-flag-deprecated,
2215 * api-help-flag-internal, api-help-flag-readrights,
2216 * api-help-flag-writerights, api-help-flag-mustbeposted
2217 *
2218 * @return string[]
2219 */
2220 protected function getHelpFlags() {
2221 $flags = array();
2222
2223 if ( $this->isDeprecated() ) {
2224 $flags[] = 'deprecated';
2225 }
2226 if ( $this->isInternal() ) {
2227 $flags[] = 'internal';
2228 }
2229 if ( $this->isReadMode() ) {
2230 $flags[] = 'readrights';
2231 }
2232 if ( $this->isWriteMode() ) {
2233 $flags[] = 'writerights';
2234 }
2235 if ( $this->mustBePosted() ) {
2236 $flags[] = 'mustbeposted';
2237 }
2238
2239 return $flags;
2240 }
2241
2242 /**
2243 * Returns information about the source of this module, if known
2244 *
2245 * Returned array is an array with the following keys:
2246 * - path: Install path
2247 * - name: Extension name, or "MediaWiki" for core
2248 * - namemsg: (optional) i18n message key for a display name
2249 * - license-name: (optional) Name of license
2250 *
2251 * @return array|null
2252 */
2253 protected function getModuleSourceInfo() {
2254 global $IP;
2255
2256 if ( $this->mModuleSource !== false ) {
2257 return $this->mModuleSource;
2258 }
2259
2260 // First, try to find where the module comes from...
2261 $rClass = new ReflectionClass( $this );
2262 $path = $rClass->getFileName();
2263 if ( !$path ) {
2264 // No path known?
2265 $this->mModuleSource = null;
2266 return null;
2267 }
2268 $path = realpath( $path ) ?: $path;
2269
2270 // Build map of extension directories to extension info
2271 if ( self::$extensionInfo === null ) {
2272 self::$extensionInfo = array(
2273 realpath( __DIR__ ) ?: __DIR__ => array(
2274 'path' => $IP,
2275 'name' => 'MediaWiki',
2276 'license-name' => 'GPL-2.0+',
2277 ),
2278 realpath( "$IP/extensions" ) ?: "$IP/extensions" => null,
2279 );
2280 $keep = array(
2281 'path' => null,
2282 'name' => null,
2283 'namemsg' => null,
2284 'license-name' => null,
2285 );
2286 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2287 foreach ( $group as $ext ) {
2288 if ( !isset( $ext['path'] ) || !isset( $ext['name'] ) ) {
2289 // This shouldn't happen, but does anyway.
2290 continue;
2291 }
2292
2293 $extpath = $ext['path'];
2294 if ( !is_dir( $extpath ) ) {
2295 $extpath = dirname( $extpath );
2296 }
2297 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2298 array_intersect_key( $ext, $keep );
2299 }
2300 }
2301 foreach ( ExtensionRegistry::getInstance()->getAllThings() as $ext ) {
2302 $extpath = $ext['path'];
2303 if ( !is_dir( $extpath ) ) {
2304 $extpath = dirname( $extpath );
2305 }
2306 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2307 array_intersect_key( $ext, $keep );
2308 }
2309 }
2310
2311 // Now traverse parent directories until we find a match or run out of
2312 // parents.
2313 do {
2314 if ( array_key_exists( $path, self::$extensionInfo ) ) {
2315 // Found it!
2316 $this->mModuleSource = self::$extensionInfo[$path];
2317 return $this->mModuleSource;
2318 }
2319
2320 $oldpath = $path;
2321 $path = dirname( $path );
2322 } while ( $path !== $oldpath );
2323
2324 // No idea what extension this might be.
2325 $this->mModuleSource = null;
2326 return null;
2327 }
2328
2329 /**
2330 * Called from ApiHelp before the pieces are joined together and returned.
2331 *
2332 * This exists mainly for ApiMain to add the Permissions and Credits
2333 * sections. Other modules probably don't need it.
2334 *
2335 * @param string[] &$help Array of help data
2336 * @param array $options Options passed to ApiHelp::getHelp
2337 * @param array &$tocData If a TOC is being generated, this array has keys
2338 * as anchors in the page and values as for Linker::generateTOC().
2339 */
2340 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2341 }
2342
2343 /**@}*/
2344
2345 /************************************************************************//**
2346 * @name Deprecated
2347 * @{
2348 */
2349
2350 /// @deprecated since 1.24
2351 const PROP_ROOT = 'ROOT';
2352 /// @deprecated since 1.24
2353 const PROP_LIST = 'LIST';
2354 /// @deprecated since 1.24
2355 const PROP_TYPE = 0;
2356 /// @deprecated since 1.24
2357 const PROP_NULLABLE = 1;
2358
2359 /**
2360 * Formerly returned a string that identifies the version of the extending
2361 * class. Typically included the class name, the svn revision, timestamp,
2362 * and last author. Usually done with SVN's Id keyword
2363 *
2364 * @deprecated since 1.21, version string is no longer supported
2365 * @return string
2366 */
2367 public function getVersion() {
2368 wfDeprecated( __METHOD__, '1.21' );
2369 return '';
2370 }
2371
2372 /**
2373 * Formerly used to fetch a list of possible properites in the result,
2374 * somehow organized with respect to the prop parameter that causes them to
2375 * be returned. The specific semantics of the return value was never
2376 * specified. Since this was never possible to be accurately updated, it
2377 * has been removed.
2378 *
2379 * @deprecated since 1.24
2380 * @return array|bool
2381 */
2382 protected function getResultProperties() {
2383 wfDeprecated( __METHOD__, '1.24' );
2384 return false;
2385 }
2386
2387 /**
2388 * @see self::getResultProperties()
2389 * @deprecated since 1.24
2390 * @return array|bool
2391 */
2392 public function getFinalResultProperties() {
2393 wfDeprecated( __METHOD__, '1.24' );
2394 return array();
2395 }
2396
2397 /**
2398 * @see self::getResultProperties()
2399 * @deprecated since 1.24
2400 */
2401 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2402 wfDeprecated( __METHOD__, '1.24' );
2403 }
2404
2405 /**
2406 * @see self::getPossibleErrors()
2407 * @deprecated since 1.24
2408 * @return array
2409 */
2410 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2411 wfDeprecated( __METHOD__, '1.24' );
2412 return array();
2413 }
2414
2415 /**
2416 * @see self::getPossibleErrors()
2417 * @deprecated since 1.24
2418 * @return array
2419 */
2420 public function getRequireMaxOneParameterErrorMessages( $params ) {
2421 wfDeprecated( __METHOD__, '1.24' );
2422 return array();
2423 }
2424
2425 /**
2426 * @see self::getPossibleErrors()
2427 * @deprecated since 1.24
2428 * @return array
2429 */
2430 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2431 wfDeprecated( __METHOD__, '1.24' );
2432 return array();
2433 }
2434
2435 /**
2436 * @see self::getPossibleErrors()
2437 * @deprecated since 1.24
2438 * @return array
2439 */
2440 public function getTitleOrPageIdErrorMessage() {
2441 wfDeprecated( __METHOD__, '1.24' );
2442 return array();
2443 }
2444
2445 /**
2446 * This formerly attempted to return a list of all possible errors returned
2447 * by the module. However, this was impossible to maintain in many cases
2448 * since errors could come from other areas of MediaWiki and in some cases
2449 * from arbitrary extension hooks. Since a partial list claiming to be
2450 * comprehensive is unlikely to be useful, it was removed.
2451 *
2452 * @deprecated since 1.24
2453 * @return array
2454 */
2455 public function getPossibleErrors() {
2456 wfDeprecated( __METHOD__, '1.24' );
2457 return array();
2458 }
2459
2460 /**
2461 * @see self::getPossibleErrors()
2462 * @deprecated since 1.24
2463 * @return array
2464 */
2465 public function getFinalPossibleErrors() {
2466 wfDeprecated( __METHOD__, '1.24' );
2467 return array();
2468 }
2469
2470 /**
2471 * @see self::getPossibleErrors()
2472 * @deprecated since 1.24
2473 * @return array
2474 */
2475 public function parseErrors( $errors ) {
2476 wfDeprecated( __METHOD__, '1.24' );
2477 return array();
2478 }
2479
2480 /**
2481 * Returns the description string for this module
2482 *
2483 * Ignored if an i18n message exists for
2484 * "apihelp-{$this->getModulePath()}-description".
2485 *
2486 * @deprecated since 1.25
2487 * @return Message|string|array
2488 */
2489 protected function getDescription() {
2490 return false;
2491 }
2492
2493 /**
2494 * Returns an array of parameter descriptions.
2495 *
2496 * For each parameter, ignored if an i18n message exists for the parameter.
2497 * By default that message is
2498 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2499 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2500 * self::getFinalParams().
2501 *
2502 * @deprecated since 1.25
2503 * @return array|bool False on no parameter descriptions
2504 */
2505 protected function getParamDescription() {
2506 return array();
2507 }
2508
2509 /**
2510 * Returns usage examples for this module.
2511 *
2512 * Return value as an array is either:
2513 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2514 * values
2515 * - sequential numeric keys with even-numbered keys being display-text
2516 * and odd-numbered keys being partial urls
2517 * - partial URLs as keys with display-text (string or array-to-be-joined)
2518 * as values
2519 * Return value as a string is the same as an array with a numeric key and
2520 * that value, and boolean false means "no examples".
2521 *
2522 * @deprecated since 1.25, use getExamplesMessages() instead
2523 * @return bool|string|array
2524 */
2525 protected function getExamples() {
2526 return false;
2527 }
2528
2529 /**
2530 * Generates help message for this module, or false if there is no description
2531 * @deprecated since 1.25
2532 * @return string|bool
2533 */
2534 public function makeHelpMsg() {
2535 wfDeprecated( __METHOD__, '1.25' );
2536 static $lnPrfx = "\n ";
2537
2538 $msg = $this->getFinalDescription();
2539
2540 if ( $msg !== false ) {
2541
2542 if ( !is_array( $msg ) ) {
2543 $msg = array(
2544 $msg
2545 );
2546 }
2547 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2548
2549 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2550
2551 if ( $this->isReadMode() ) {
2552 $msg .= "\nThis module requires read rights";
2553 }
2554 if ( $this->isWriteMode() ) {
2555 $msg .= "\nThis module requires write rights";
2556 }
2557 if ( $this->mustBePosted() ) {
2558 $msg .= "\nThis module only accepts POST requests";
2559 }
2560 if ( $this->isReadMode() || $this->isWriteMode() ||
2561 $this->mustBePosted()
2562 ) {
2563 $msg .= "\n";
2564 }
2565
2566 // Parameters
2567 $paramsMsg = $this->makeHelpMsgParameters();
2568 if ( $paramsMsg !== false ) {
2569 $msg .= "Parameters:\n$paramsMsg";
2570 }
2571
2572 $examples = $this->getExamples();
2573 if ( $examples ) {
2574 if ( !is_array( $examples ) ) {
2575 $examples = array(
2576 $examples
2577 );
2578 }
2579 $msg .= "Example" . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
2580 foreach ( $examples as $k => $v ) {
2581 if ( is_numeric( $k ) ) {
2582 $msg .= " $v\n";
2583 } else {
2584 if ( is_array( $v ) ) {
2585 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2586 } else {
2587 $msgExample = " $v";
2588 }
2589 $msgExample .= ":";
2590 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2591 }
2592 }
2593 }
2594 }
2595
2596 return $msg;
2597 }
2598
2599 /**
2600 * @deprecated since 1.25
2601 * @param string $item
2602 * @return string
2603 */
2604 private function indentExampleText( $item ) {
2605 return " " . $item;
2606 }
2607
2608 /**
2609 * @deprecated since 1.25
2610 * @param string $prefix Text to split output items
2611 * @param string $title What is being output
2612 * @param string|array $input
2613 * @return string
2614 */
2615 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2616 wfDeprecated( __METHOD__, '1.25' );
2617 if ( $input === false ) {
2618 return '';
2619 }
2620 if ( !is_array( $input ) ) {
2621 $input = array( $input );
2622 }
2623
2624 if ( count( $input ) > 0 ) {
2625 if ( $title ) {
2626 $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n ";
2627 } else {
2628 $msg = ' ';
2629 }
2630 $msg .= implode( $prefix, $input ) . "\n";
2631
2632 return $msg;
2633 }
2634
2635 return '';
2636 }
2637
2638 /**
2639 * Generates the parameter descriptions for this module, to be displayed in the
2640 * module's help.
2641 * @deprecated since 1.25
2642 * @return string|bool
2643 */
2644 public function makeHelpMsgParameters() {
2645 wfDeprecated( __METHOD__, '1.25' );
2646 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
2647 if ( $params ) {
2648 $paramsDescription = $this->getFinalParamDescription();
2649 $msg = '';
2650 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2651 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2652 foreach ( $params as $paramName => $paramSettings ) {
2653 $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
2654 if ( is_array( $desc ) ) {
2655 $desc = implode( $paramPrefix, $desc );
2656 }
2657
2658 //handle shorthand
2659 if ( !is_array( $paramSettings ) ) {
2660 $paramSettings = array(
2661 self::PARAM_DFLT => $paramSettings,
2662 );
2663 }
2664
2665 //handle missing type
2666 if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) {
2667 $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] )
2668 ? $paramSettings[ApiBase::PARAM_DFLT]
2669 : null;
2670 if ( is_bool( $dflt ) ) {
2671 $paramSettings[ApiBase::PARAM_TYPE] = 'boolean';
2672 } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
2673 $paramSettings[ApiBase::PARAM_TYPE] = 'string';
2674 } elseif ( is_int( $dflt ) ) {
2675 $paramSettings[ApiBase::PARAM_TYPE] = 'integer';
2676 }
2677 }
2678
2679 if ( isset( $paramSettings[self::PARAM_DEPRECATED] )
2680 && $paramSettings[self::PARAM_DEPRECATED]
2681 ) {
2682 $desc = "DEPRECATED! $desc";
2683 }
2684
2685 if ( isset( $paramSettings[self::PARAM_REQUIRED] )
2686 && $paramSettings[self::PARAM_REQUIRED]
2687 ) {
2688 $desc .= $paramPrefix . "This parameter is required";
2689 }
2690
2691 $type = isset( $paramSettings[self::PARAM_TYPE] )
2692 ? $paramSettings[self::PARAM_TYPE]
2693 : null;
2694 if ( isset( $type ) ) {
2695 $hintPipeSeparated = true;
2696 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
2697 ? $paramSettings[self::PARAM_ISMULTI]
2698 : false;
2699 if ( $multi ) {
2700 $prompt = 'Values (separate with \'|\'): ';
2701 } else {
2702 $prompt = 'One value: ';
2703 }
2704
2705 if ( $type === 'submodule' ) {
2706 if ( isset( $paramSettings[self::PARAM_SUBMODULE_MAP] ) ) {
2707 $type = array_keys( $paramSettings[self::PARAM_SUBMODULE_MAP] );
2708 } else {
2709 $type = $this->getModuleManager()->getNames( $paramName );
2710 }
2711 sort( $type );
2712 }
2713 if ( is_array( $type ) ) {
2714 $choices = array();
2715 $nothingPrompt = '';
2716 foreach ( $type as $t ) {
2717 if ( $t === '' ) {
2718 $nothingPrompt = 'Can be empty, or ';
2719 } else {
2720 $choices[] = $t;
2721 }
2722 }
2723 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2724 $choicesstring = implode( ', ', $choices );
2725 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2726 $hintPipeSeparated = false;
2727 } else {
2728 switch ( $type ) {
2729 case 'namespace':
2730 // Special handling because namespaces are
2731 // type-limited, yet they are not given
2732 $desc .= $paramPrefix . $prompt;
2733 $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
2734 100, $descWordwrap );
2735 $hintPipeSeparated = false;
2736 break;
2737 case 'limit':
2738 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2739 if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
2740 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2741 }
2742 $desc .= ' allowed';
2743 break;
2744 case 'integer':
2745 $s = $multi ? 's' : '';
2746 $hasMin = isset( $paramSettings[self::PARAM_MIN] );
2747 $hasMax = isset( $paramSettings[self::PARAM_MAX] );
2748 if ( $hasMin || $hasMax ) {
2749 if ( !$hasMax ) {
2750 $intRangeStr = "The value$s must be no less than " .
2751 "{$paramSettings[self::PARAM_MIN]}";
2752 } elseif ( !$hasMin ) {
2753 $intRangeStr = "The value$s must be no more than " .
2754 "{$paramSettings[self::PARAM_MAX]}";
2755 } else {
2756 $intRangeStr = "The value$s must be between " .
2757 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2758 }
2759
2760 $desc .= $paramPrefix . $intRangeStr;
2761 }
2762 break;
2763 case 'upload':
2764 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2765 break;
2766 }
2767 }
2768
2769 if ( $multi ) {
2770 if ( $hintPipeSeparated ) {
2771 $desc .= $paramPrefix . "Separate values with '|'";
2772 }
2773
2774 $isArray = is_array( $type );
2775 if ( !$isArray
2776 || $isArray && count( $type ) > self::LIMIT_SML1
2777 ) {
2778 $desc .= $paramPrefix . "Maximum number of values " .
2779 self::LIMIT_SML1 . " (" . self::LIMIT_SML2 . " for bots)";
2780 }
2781 }
2782 }
2783
2784 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
2785 if ( !is_null( $default ) && $default !== false ) {
2786 $desc .= $paramPrefix . "Default: $default";
2787 }
2788
2789 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2790 }
2791
2792 return $msg;
2793 }
2794
2795 return false;
2796 }
2797
2798 /**
2799 * @deprecated since 1.25, always returns empty string
2800 * @param DatabaseBase|bool $db
2801 * @return string
2802 */
2803 public function getModuleProfileName( $db = false ) {
2804 wfDeprecated( __METHOD__, '1.25' );
2805 return '';
2806 }
2807
2808 /**
2809 * @deprecated since 1.25
2810 */
2811 public function profileIn() {
2812 // No wfDeprecated() yet because extensions call this and might need to
2813 // keep doing so for BC.
2814 }
2815
2816 /**
2817 * @deprecated since 1.25
2818 */
2819 public function profileOut() {
2820 // No wfDeprecated() yet because extensions call this and might need to
2821 // keep doing so for BC.
2822 }
2823
2824 /**
2825 * @deprecated since 1.25
2826 */
2827 public function safeProfileOut() {
2828 wfDeprecated( __METHOD__, '1.25' );
2829 }
2830
2831 /**
2832 * @deprecated since 1.25, always returns 0
2833 * @return float
2834 */
2835 public function getProfileTime() {
2836 wfDeprecated( __METHOD__, '1.25' );
2837 return 0;
2838 }
2839
2840 /**
2841 * @deprecated since 1.25
2842 */
2843 public function profileDBIn() {
2844 wfDeprecated( __METHOD__, '1.25' );
2845 }
2846
2847 /**
2848 * @deprecated since 1.25
2849 */
2850 public function profileDBOut() {
2851 wfDeprecated( __METHOD__, '1.25' );
2852 }
2853
2854 /**
2855 * @deprecated since 1.25, always returns 0
2856 * @return float
2857 */
2858 public function getProfileDBTime() {
2859 wfDeprecated( __METHOD__, '1.25' );
2860 return 0;
2861 }
2862
2863 /**
2864 * Get the result data array (read-only)
2865 * @deprecated since 1.25, use $this->getResult() methods instead
2866 * @return array
2867 */
2868 public function getResultData() {
2869 wfDeprecated( __METHOD__, '1.25' );
2870 return $this->getResult()->getData();
2871 }
2872
2873 /**
2874 * Call wfTransactionalTimeLimit() if this request was POSTed
2875 * @since 1.26
2876 */
2877 protected function useTransactionalTimeLimit() {
2878 if ( $this->getRequest()->wasPosted() ) {
2879 wfTransactionalTimeLimit();
2880 }
2881 }
2882
2883 /**@}*/
2884 }
2885
2886 /**
2887 * For really cool vim folding this needs to be at the end:
2888 * vim: foldmarker=@{,@} foldmethod=marker
2889 */