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