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