Fixing confusing function description
[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 public final 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 'nosuchrcid' => array(
1643 'code' => 'nosuchrcid',
1644 'info' => "There is no change with rcid \"\$1\""
1645 ),
1646 'protect-invalidaction' => array(
1647 'code' => 'protect-invalidaction',
1648 'info' => "Invalid protection type \"\$1\""
1649 ),
1650 'protect-invalidlevel' => array(
1651 'code' => 'protect-invalidlevel',
1652 'info' => "Invalid protection level \"\$1\""
1653 ),
1654 'toofewexpiries' => array(
1655 'code' => 'toofewexpiries',
1656 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1657 ),
1658 'cantimport' => array(
1659 'code' => 'cantimport',
1660 'info' => "You don't have permission to import pages"
1661 ),
1662 'cantimport-upload' => array(
1663 'code' => 'cantimport-upload',
1664 'info' => "You don't have permission to import uploaded pages"
1665 ),
1666 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1667 'importuploaderrorsize' => array(
1668 'code' => 'filetoobig',
1669 'info' => 'The file you uploaded is bigger than the maximum upload size'
1670 ),
1671 'importuploaderrorpartial' => array(
1672 'code' => 'partialupload',
1673 'info' => 'The file was only partially uploaded'
1674 ),
1675 'importuploaderrortemp' => array(
1676 'code' => 'notempdir',
1677 'info' => 'The temporary upload directory is missing'
1678 ),
1679 'importcantopen' => array(
1680 'code' => 'cantopenfile',
1681 'info' => "Couldn't open the uploaded file"
1682 ),
1683 'import-noarticle' => array(
1684 'code' => 'badinterwiki',
1685 'info' => 'Invalid interwiki title specified'
1686 ),
1687 'importbadinterwiki' => array(
1688 'code' => 'badinterwiki',
1689 'info' => 'Invalid interwiki title specified'
1690 ),
1691 'import-unknownerror' => array(
1692 'code' => 'import-unknownerror',
1693 'info' => "Unknown error on import: \"\$1\""
1694 ),
1695 'cantoverwrite-sharedfile' => array(
1696 'code' => 'cantoverwrite-sharedfile',
1697 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1698 ),
1699 'sharedfile-exists' => array(
1700 'code' => 'fileexists-sharedrepo-perm',
1701 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1702 ),
1703 'mustbeposted' => array(
1704 'code' => 'mustbeposted',
1705 'info' => "The \$1 module requires a POST request"
1706 ),
1707 'show' => array(
1708 'code' => 'show',
1709 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1710 ),
1711 'specialpage-cantexecute' => array(
1712 'code' => 'specialpage-cantexecute',
1713 'info' => "You don't have permission to view the results of this special page"
1714 ),
1715 'invalidoldimage' => array(
1716 'code' => 'invalidoldimage',
1717 'info' => 'The oldimage parameter has invalid format'
1718 ),
1719 'nodeleteablefile' => array(
1720 'code' => 'nodeleteablefile',
1721 'info' => 'No such old version of the file'
1722 ),
1723 'fileexists-forbidden' => array(
1724 'code' => 'fileexists-forbidden',
1725 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1726 ),
1727 'fileexists-shared-forbidden' => array(
1728 'code' => 'fileexists-shared-forbidden',
1729 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1730 ),
1731 'filerevert-badversion' => array(
1732 'code' => 'filerevert-badversion',
1733 'info' => 'There is no previous local version of this file with the provided timestamp.'
1734 ),
1735
1736 // ApiEditPage messages
1737 'noimageredirect-anon' => array(
1738 'code' => 'noimageredirect-anon',
1739 'info' => "Anonymous users can't create image redirects"
1740 ),
1741 'noimageredirect-logged' => array(
1742 'code' => 'noimageredirect',
1743 'info' => "You don't have permission to create image redirects"
1744 ),
1745 'spamdetected' => array(
1746 'code' => 'spamdetected',
1747 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1748 ),
1749 'contenttoobig' => array(
1750 'code' => 'contenttoobig',
1751 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1752 ),
1753 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1754 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1755 'wasdeleted' => array(
1756 'code' => 'pagedeleted',
1757 'info' => "The page has been deleted since you fetched its timestamp"
1758 ),
1759 'blankpage' => array(
1760 'code' => 'emptypage',
1761 'info' => "Creating new, empty pages is not allowed"
1762 ),
1763 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1764 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1765 'missingtext' => array(
1766 'code' => 'notext',
1767 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1768 ),
1769 'emptynewsection' => array(
1770 'code' => 'emptynewsection',
1771 'info' => 'Creating empty new sections is not possible.'
1772 ),
1773 'revwrongpage' => array(
1774 'code' => 'revwrongpage',
1775 'info' => "r\$1 is not a revision of \"\$2\""
1776 ),
1777 'undo-failure' => array(
1778 'code' => 'undofailure',
1779 'info' => 'Undo failed due to conflicting intermediate edits'
1780 ),
1781 'content-not-allowed-here' => array(
1782 'code' => 'contentnotallowedhere',
1783 'info' => 'Content model "$1" is not allowed at title "$2"'
1784 ),
1785
1786 // Messages from WikiPage::doEit()
1787 'edit-hook-aborted' => array(
1788 'code' => 'edit-hook-aborted',
1789 'info' => "Your edit was aborted by an ArticleSave hook"
1790 ),
1791 'edit-gone-missing' => array(
1792 'code' => 'edit-gone-missing',
1793 'info' => "The page you tried to edit doesn't seem to exist anymore"
1794 ),
1795 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1796 'edit-already-exists' => array(
1797 'code' => 'edit-already-exists',
1798 'info' => 'It seems the page you tried to create already exist'
1799 ),
1800
1801 // uploadMsgs
1802 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1803 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1804 'uploaddisabled' => array(
1805 'code' => 'uploaddisabled',
1806 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1807 ),
1808 'copyuploaddisabled' => array(
1809 'code' => 'copyuploaddisabled',
1810 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1811 ),
1812 'copyuploadbaddomain' => array(
1813 'code' => 'copyuploadbaddomain',
1814 'info' => 'Uploads by URL are not allowed from this domain.'
1815 ),
1816 'copyuploadbadurl' => array(
1817 'code' => 'copyuploadbadurl',
1818 'info' => 'Upload not allowed from this URL.'
1819 ),
1820
1821 'filename-tooshort' => array(
1822 'code' => 'filename-tooshort',
1823 'info' => 'The filename is too short'
1824 ),
1825 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1826 'illegal-filename' => array(
1827 'code' => 'illegal-filename',
1828 'info' => 'The filename is not allowed'
1829 ),
1830 'filetype-missing' => array(
1831 'code' => 'filetype-missing',
1832 'info' => 'The file is missing an extension'
1833 ),
1834
1835 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1836 );
1837 // @codingStandardsIgnoreEnd
1838
1839 /**
1840 * Helper function for readonly errors
1841 */
1842 public function dieReadOnly() {
1843 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1844 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1845 array( 'readonlyreason' => wfReadOnlyReason() ) );
1846 }
1847
1848 /**
1849 * Output the error message related to a certain array
1850 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1851 */
1852 public function dieUsageMsg( $error ) {
1853 # most of the time we send a 1 element, so we might as well send it as
1854 # a string and make this an array here.
1855 if ( is_string( $error ) ) {
1856 $error = array( $error );
1857 }
1858 $parsed = $this->parseMsg( $error );
1859 $this->dieUsage( $parsed['info'], $parsed['code'] );
1860 }
1861
1862 /**
1863 * Will only set a warning instead of failing if the global $wgDebugAPI
1864 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1865 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1866 * @since 1.21
1867 */
1868 public function dieUsageMsgOrDebug( $error ) {
1869 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1870 $this->dieUsageMsg( $error );
1871 }
1872
1873 if ( is_string( $error ) ) {
1874 $error = array( $error );
1875 }
1876 $parsed = $this->parseMsg( $error );
1877 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1878 }
1879
1880 /**
1881 * Die with the $prefix.'badcontinue' error. This call is common enough to
1882 * make it into the base method.
1883 * @param bool $condition Will only die if this value is true
1884 * @since 1.21
1885 */
1886 protected function dieContinueUsageIf( $condition ) {
1887 if ( $condition ) {
1888 $this->dieUsage(
1889 'Invalid continue param. You should pass the original value returned by the previous query',
1890 'badcontinue' );
1891 }
1892 }
1893
1894 /**
1895 * Return the error message related to a certain array
1896 * @param array $error Element of a getUserPermissionsErrors()-style array
1897 * @return array('code' => code, 'info' => info)
1898 */
1899 public function parseMsg( $error ) {
1900 $error = (array)$error; // It seems strings sometimes make their way in here
1901 $key = array_shift( $error );
1902
1903 // Check whether the error array was nested
1904 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1905 if ( is_array( $key ) ) {
1906 $error = $key;
1907 $key = array_shift( $error );
1908 }
1909
1910 if ( isset( self::$messageMap[$key] ) ) {
1911 return array(
1912 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
1913 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
1914 );
1915 }
1916
1917 // If the key isn't present, throw an "unknown error"
1918 return $this->parseMsg( array( 'unknownerror', $key ) );
1919 }
1920
1921 /**
1922 * Internal code errors should be reported with this method
1923 * @param string $method Method or function name
1924 * @param string $message Error message
1925 * @throws MWException
1926 */
1927 protected static function dieDebug( $method, $message ) {
1928 throw new MWException( "Internal error in $method: $message" );
1929 }
1930
1931 /**@}*/
1932
1933 /************************************************************************//**
1934 * @name Help message generation
1935 * @{
1936 */
1937
1938 /**
1939 * Return the description message.
1940 *
1941 * @return string|array|Message
1942 */
1943 protected function getDescriptionMessage() {
1944 return "apihelp-{$this->getModulePath()}-description";
1945 }
1946
1947 /**
1948 * Get final module description, after hooks have had a chance to tweak it as
1949 * needed.
1950 *
1951 * @since 1.25, returns Message[] rather than string[]
1952 * @return Message[]
1953 */
1954 public function getFinalDescription() {
1955 $desc = $this->getDescription();
1956 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
1957 $desc = self::escapeWikiText( $desc );
1958 if ( is_array( $desc ) ) {
1959 $desc = join( "\n", $desc );
1960 } else {
1961 $desc = (string)$desc;
1962 }
1963
1964 $msg = ApiBase::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
1965 $this->getModulePrefix(),
1966 $this->getModuleName(),
1967 $this->getModulePath(),
1968 ) );
1969 if ( !$msg->exists() ) {
1970 $msg = $this->msg( 'api-help-fallback-description', $desc );
1971 }
1972 $msgs = array( $msg );
1973
1974 wfRunHooks( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
1975
1976 return $msgs;
1977 }
1978
1979 /**
1980 * Get final list of parameters, after hooks have had a chance to
1981 * tweak it as needed.
1982 *
1983 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
1984 * @return array|bool False on no parameters
1985 * @since 1.21 $flags param added
1986 */
1987 public function getFinalParams( $flags = 0 ) {
1988 $params = $this->getAllowedParams( $flags );
1989 if ( !$params ) {
1990 $params = array();
1991 }
1992
1993 if ( $this->needsToken() ) {
1994 $params['token'] = array(
1995 ApiBase::PARAM_TYPE => 'string',
1996 ApiBase::PARAM_REQUIRED => true,
1997 ApiBase::PARAM_HELP_MSG => array(
1998 'api-help-param-token',
1999 $this->needsToken(),
2000 ),
2001 ) + ( isset( $params['token'] ) ? $params['token'] : array() );
2002 }
2003
2004 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2005
2006 return $params;
2007 }
2008
2009 /**
2010 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2011 * needed.
2012 *
2013 * @since 1.25, returns array of Message[] rather than array of string[]
2014 * @return array Keys are parameter names, values are arrays of Message objects
2015 */
2016 public function getFinalParamDescription() {
2017 $desc = $this->getParamDescription();
2018 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
2019
2020 if ( !$desc ) {
2021 $desc = array();
2022 }
2023 $desc = self::escapeWikiText( $desc );
2024
2025 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
2026 $msgs = array();
2027 foreach ( $params as $param => $settings ) {
2028 if ( !is_array( $settings ) ) {
2029 $settings = array();
2030 }
2031
2032 $d = isset( $desc[$param] ) ? $desc[$param] : '';
2033 if ( is_array( $d ) ) {
2034 // Special handling for prop parameters
2035 $d = array_map( function ( $line ) {
2036 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2037 $line = "\n;{$m[1]}:{$m[2]}";
2038 }
2039 return $line;
2040 }, $d );
2041 $d = join( ' ', $d );
2042 }
2043
2044 if ( isset( $settings[ApiBase::PARAM_HELP_MSG] ) ) {
2045 $msg = $settings[ApiBase::PARAM_HELP_MSG];
2046 } else {
2047 $msg = $this->msg( "apihelp-{$this->getModulePath()}-param-{$param}" );
2048 if ( !$msg->exists() ) {
2049 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2050 }
2051 }
2052 $msg = ApiBase::makeMessage( $msg, $this->getContext(), array(
2053 $this->getModulePrefix(),
2054 $param,
2055 $this->getModuleName(),
2056 $this->getModulePath(),
2057 ) );
2058 if ( !$msg ) {
2059 $this->dieDebug( __METHOD__,
2060 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2061 }
2062 $msgs[$param] = array( $msg );
2063
2064 if ( isset( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2065 if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2066 $this->dieDebug( __METHOD__,
2067 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2068 }
2069 foreach ( $settings[ApiBase::PARAM_HELP_MSG_APPEND] as $m ) {
2070 $m = ApiBase::makeMessage( $m, $this->getContext(), array(
2071 $this->getModulePrefix(),
2072 $param,
2073 $this->getModuleName(),
2074 $this->getModulePath(),
2075 ) );
2076 if ( $m ) {
2077 $msgs[$param][] = $m;
2078 } else {
2079 $this->dieDebug( __METHOD__,
2080 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2081 }
2082 }
2083 }
2084 }
2085
2086 wfRunHooks( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2087
2088 return $msgs;
2089 }
2090
2091 /**
2092 * Generates the list of flags for the help screen and for action=paraminfo
2093 *
2094 * Corresponding messages: api-help-flag-deprecated,
2095 * api-help-flag-internal, api-help-flag-readrights,
2096 * api-help-flag-writerights, api-help-flag-mustbeposted
2097 *
2098 * @return string[]
2099 */
2100 protected function getHelpFlags() {
2101 $flags = array();
2102
2103 if ( $this->isDeprecated() ) {
2104 $flags[] = 'deprecated';
2105 }
2106 if ( $this->isInternal() ) {
2107 $flags[] = 'internal';
2108 }
2109 if ( $this->isReadMode() ) {
2110 $flags[] = 'readrights';
2111 }
2112 if ( $this->isWriteMode() ) {
2113 $flags[] = 'writerights';
2114 }
2115 if ( $this->mustBePosted() ) {
2116 $flags[] = 'mustbeposted';
2117 }
2118
2119 return $flags;
2120 }
2121
2122 /**
2123 * Called from ApiHelp before the pieces are joined together and returned.
2124 *
2125 * This exists mainly for ApiMain to add the Permissions and Credits
2126 * sections. Other modules probably don't need it.
2127 *
2128 * @param string[] &$help Array of help data
2129 * @param array $options Options passed to ApiHelp::getHelp
2130 */
2131 public function modifyHelp( array &$help, array $options ) {
2132 }
2133
2134 /**@}*/
2135
2136 /************************************************************************//**
2137 * @name Profiling
2138 * @{
2139 */
2140
2141 /**
2142 * Profiling: total module execution time
2143 */
2144 private $mTimeIn = 0, $mModuleTime = 0;
2145
2146 /**
2147 * Get the name of the module as shown in the profiler log
2148 *
2149 * @param DatabaseBase|bool $db
2150 *
2151 * @return string
2152 */
2153 public function getModuleProfileName( $db = false ) {
2154 if ( $db ) {
2155 return 'API:' . $this->mModuleName . '-DB';
2156 }
2157
2158 return 'API:' . $this->mModuleName;
2159 }
2160
2161 /**
2162 * Start module profiling
2163 */
2164 public function profileIn() {
2165 if ( $this->mTimeIn !== 0 ) {
2166 ApiBase::dieDebug( __METHOD__, 'Called twice without calling profileOut()' );
2167 }
2168 $this->mTimeIn = microtime( true );
2169 wfProfileIn( $this->getModuleProfileName() );
2170 }
2171
2172 /**
2173 * End module profiling
2174 */
2175 public function profileOut() {
2176 if ( $this->mTimeIn === 0 ) {
2177 ApiBase::dieDebug( __METHOD__, 'Called without calling profileIn() first' );
2178 }
2179 if ( $this->mDBTimeIn !== 0 ) {
2180 ApiBase::dieDebug(
2181 __METHOD__,
2182 'Must be called after database profiling is done with profileDBOut()'
2183 );
2184 }
2185
2186 $this->mModuleTime += microtime( true ) - $this->mTimeIn;
2187 $this->mTimeIn = 0;
2188 wfProfileOut( $this->getModuleProfileName() );
2189 }
2190
2191 /**
2192 * When modules crash, sometimes it is needed to do a profileOut() regardless
2193 * of the profiling state the module was in. This method does such cleanup.
2194 */
2195 public function safeProfileOut() {
2196 if ( $this->mTimeIn !== 0 ) {
2197 if ( $this->mDBTimeIn !== 0 ) {
2198 $this->profileDBOut();
2199 }
2200 $this->profileOut();
2201 }
2202 }
2203
2204 /**
2205 * Total time the module was executed
2206 * @return float
2207 */
2208 public function getProfileTime() {
2209 if ( $this->mTimeIn !== 0 ) {
2210 ApiBase::dieDebug( __METHOD__, 'Called without calling profileOut() first' );
2211 }
2212
2213 return $this->mModuleTime;
2214 }
2215
2216 /**
2217 * Profiling: database execution time
2218 */
2219 private $mDBTimeIn = 0, $mDBTime = 0;
2220
2221 /**
2222 * Start module profiling
2223 */
2224 public function profileDBIn() {
2225 if ( $this->mTimeIn === 0 ) {
2226 ApiBase::dieDebug(
2227 __METHOD__,
2228 'Must be called while profiling the entire module with profileIn()'
2229 );
2230 }
2231 if ( $this->mDBTimeIn !== 0 ) {
2232 ApiBase::dieDebug( __METHOD__, 'Called twice without calling profileDBOut()' );
2233 }
2234 $this->mDBTimeIn = microtime( true );
2235 wfProfileIn( $this->getModuleProfileName( true ) );
2236 }
2237
2238 /**
2239 * End database profiling
2240 */
2241 public function profileDBOut() {
2242 if ( $this->mTimeIn === 0 ) {
2243 ApiBase::dieDebug( __METHOD__, 'Must be called while profiling ' .
2244 'the entire module with profileIn()' );
2245 }
2246 if ( $this->mDBTimeIn === 0 ) {
2247 ApiBase::dieDebug( __METHOD__, 'Called without calling profileDBIn() first' );
2248 }
2249
2250 $time = microtime( true ) - $this->mDBTimeIn;
2251 $this->mDBTimeIn = 0;
2252
2253 $this->mDBTime += $time;
2254 $this->getMain()->mDBTime += $time;
2255 wfProfileOut( $this->getModuleProfileName( true ) );
2256 }
2257
2258 /**
2259 * Total time the module used the database
2260 * @return float
2261 */
2262 public function getProfileDBTime() {
2263 if ( $this->mDBTimeIn !== 0 ) {
2264 ApiBase::dieDebug( __METHOD__, 'Called without calling profileDBOut() first' );
2265 }
2266
2267 return $this->mDBTime;
2268 }
2269
2270 /**
2271 * Write logging information for API features to a debug log, for usage
2272 * analysis.
2273 * @param string $feature Feature being used.
2274 */
2275 protected function logFeatureUsage( $feature ) {
2276 $request = $this->getRequest();
2277 $s = '"' . addslashes( $feature ) . '"' .
2278 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2279 ' "' . $request->getIP() . '"' .
2280 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2281 ' "' . addslashes( $request->getHeader( 'User-agent' ) ) . '"';
2282 wfDebugLog( 'api-feature-usage', $s, 'private' );
2283 }
2284
2285 /**@}*/
2286
2287 /************************************************************************//**
2288 * @name Deprecated
2289 * @{
2290 */
2291
2292 /// @deprecated since 1.24
2293 const PROP_ROOT = 'ROOT';
2294 /// @deprecated since 1.24
2295 const PROP_LIST = 'LIST';
2296 /// @deprecated since 1.24
2297 const PROP_TYPE = 0;
2298 /// @deprecated since 1.24
2299 const PROP_NULLABLE = 1;
2300
2301 /**
2302 * Formerly returned a string that identifies the version of the extending
2303 * class. Typically included the class name, the svn revision, timestamp,
2304 * and last author. Usually done with SVN's Id keyword
2305 *
2306 * @deprecated since 1.21, version string is no longer supported
2307 * @return string
2308 */
2309 public function getVersion() {
2310 wfDeprecated( __METHOD__, '1.21' );
2311 return '';
2312 }
2313
2314 /**
2315 * Formerly used to fetch a list of possible properites in the result,
2316 * somehow organized with respect to the prop parameter that causes them to
2317 * be returned. The specific semantics of the return value was never
2318 * specified. Since this was never possible to be accurately updated, it
2319 * has been removed.
2320 *
2321 * @deprecated since 1.24
2322 * @return array|bool
2323 */
2324 protected function getResultProperties() {
2325 wfDeprecated( __METHOD__, '1.24' );
2326 return false;
2327 }
2328
2329 /**
2330 * @see self::getResultProperties()
2331 * @deprecated since 1.24
2332 * @return array|bool
2333 */
2334 public function getFinalResultProperties() {
2335 wfDeprecated( __METHOD__, '1.24' );
2336 return array();
2337 }
2338
2339 /**
2340 * @see self::getResultProperties()
2341 * @deprecated since 1.24
2342 */
2343 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2344 wfDeprecated( __METHOD__, '1.24' );
2345 }
2346
2347 /**
2348 * @see self::getPossibleErrors()
2349 * @deprecated since 1.24
2350 * @return array
2351 */
2352 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2353 wfDeprecated( __METHOD__, '1.24' );
2354 return array();
2355 }
2356
2357 /**
2358 * @see self::getPossibleErrors()
2359 * @deprecated since 1.24
2360 * @return array
2361 */
2362 public function getRequireMaxOneParameterErrorMessages( $params ) {
2363 wfDeprecated( __METHOD__, '1.24' );
2364 return array();
2365 }
2366
2367 /**
2368 * @see self::getPossibleErrors()
2369 * @deprecated since 1.24
2370 * @return array
2371 */
2372 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2373 wfDeprecated( __METHOD__, '1.24' );
2374 return array();
2375 }
2376
2377 /**
2378 * @see self::getPossibleErrors()
2379 * @deprecated since 1.24
2380 * @return array
2381 */
2382 public function getTitleOrPageIdErrorMessage() {
2383 wfDeprecated( __METHOD__, '1.24' );
2384 return array();
2385 }
2386
2387 /**
2388 * This formerly attempted to return a list of all possible errors returned
2389 * by the module. However, this was impossible to maintain in many cases
2390 * since errors could come from other areas of MediaWiki and in some cases
2391 * from arbitrary extension hooks. Since a partial list claiming to be
2392 * comprehensive is unlikely to be useful, it was removed.
2393 *
2394 * @deprecated since 1.24
2395 * @return array
2396 */
2397 public function getPossibleErrors() {
2398 wfDeprecated( __METHOD__, '1.24' );
2399 return array();
2400 }
2401
2402 /**
2403 * @see self::getPossibleErrors()
2404 * @deprecated since 1.24
2405 * @return array
2406 */
2407 public function getFinalPossibleErrors() {
2408 wfDeprecated( __METHOD__, '1.24' );
2409 return array();
2410 }
2411
2412 /**
2413 * @see self::getPossibleErrors()
2414 * @deprecated since 1.24
2415 * @return array
2416 */
2417 public function parseErrors( $errors ) {
2418 wfDeprecated( __METHOD__, '1.24' );
2419 return array();
2420 }
2421
2422 /**
2423 * Returns the description string for this module
2424 *
2425 * Ignored if an i18n message exists for
2426 * "apihelp-{$this->getModulePathString()}-description".
2427 *
2428 * @deprecated since 1.25
2429 * @return Message|string|array
2430 */
2431 protected function getDescription() {
2432 return false;
2433 }
2434
2435 /**
2436 * Returns an array of parameter descriptions.
2437 *
2438 * For each parameter, ignored if an i18n message exists for the parameter.
2439 * By default that message is
2440 * "apihelp-{$this->getModulePathString()}-param-{$param}", but it may be
2441 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2442 * self::getFinalParams().
2443 *
2444 * @deprecated since 1.25
2445 * @return array|bool False on no parameter descriptions
2446 */
2447 protected function getParamDescription() {
2448 return array();
2449 }
2450
2451 /**
2452 * Returns usage examples for this module.
2453 *
2454 * Return value as an array is either:
2455 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2456 * values
2457 * - sequential numeric keys with even-numbered keys being display-text
2458 * and odd-numbered keys being partial urls
2459 * - partial URLs as keys with display-text (string or array-to-be-joined)
2460 * as values
2461 * Return value as a string is the same as an array with a numeric key and
2462 * that value, and boolean false means "no examples".
2463 *
2464 * @deprecated since 1.25, use getExamplesMessages() instead
2465 * @return bool|string|array
2466 */
2467 protected function getExamples() {
2468 return false;
2469 }
2470
2471 /**
2472 * Generates help message for this module, or false if there is no description
2473 * @deprecated since 1.25
2474 * @return string|bool
2475 */
2476 public function makeHelpMsg() {
2477 wfDeprecated( __METHOD__, '1.25' );
2478 static $lnPrfx = "\n ";
2479
2480 $msg = $this->getFinalDescription();
2481
2482 if ( $msg !== false ) {
2483
2484 if ( !is_array( $msg ) ) {
2485 $msg = array(
2486 $msg
2487 );
2488 }
2489 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2490
2491 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2492
2493 if ( $this->isReadMode() ) {
2494 $msg .= "\nThis module requires read rights";
2495 }
2496 if ( $this->isWriteMode() ) {
2497 $msg .= "\nThis module requires write rights";
2498 }
2499 if ( $this->mustBePosted() ) {
2500 $msg .= "\nThis module only accepts POST requests";
2501 }
2502 if ( $this->isReadMode() || $this->isWriteMode() ||
2503 $this->mustBePosted()
2504 ) {
2505 $msg .= "\n";
2506 }
2507
2508 // Parameters
2509 $paramsMsg = $this->makeHelpMsgParameters();
2510 if ( $paramsMsg !== false ) {
2511 $msg .= "Parameters:\n$paramsMsg";
2512 }
2513
2514 $examples = $this->getExamples();
2515 if ( $examples ) {
2516 if ( !is_array( $examples ) ) {
2517 $examples = array(
2518 $examples
2519 );
2520 }
2521 $msg .= "Example" . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
2522 foreach ( $examples as $k => $v ) {
2523 if ( is_numeric( $k ) ) {
2524 $msg .= " $v\n";
2525 } else {
2526 if ( is_array( $v ) ) {
2527 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2528 } else {
2529 $msgExample = " $v";
2530 }
2531 $msgExample .= ":";
2532 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2533 }
2534 }
2535 }
2536 }
2537
2538 return $msg;
2539 }
2540
2541 /**
2542 * @deprecated since 1.25
2543 * @param string $item
2544 * @return string
2545 */
2546 private function indentExampleText( $item ) {
2547 return " " . $item;
2548 }
2549
2550 /**
2551 * @deprecated since 1.25
2552 * @param string $prefix Text to split output items
2553 * @param string $title What is being output
2554 * @param string|array $input
2555 * @return string
2556 */
2557 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2558 wfDeprecated( __METHOD__, '1.25' );
2559 if ( $input === false ) {
2560 return '';
2561 }
2562 if ( !is_array( $input ) ) {
2563 $input = array( $input );
2564 }
2565
2566 if ( count( $input ) > 0 ) {
2567 if ( $title ) {
2568 $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n ";
2569 } else {
2570 $msg = ' ';
2571 }
2572 $msg .= implode( $prefix, $input ) . "\n";
2573
2574 return $msg;
2575 }
2576
2577 return '';
2578 }
2579
2580 /**
2581 * Generates the parameter descriptions for this module, to be displayed in the
2582 * module's help.
2583 * @deprecated since 1.25
2584 * @return string|bool
2585 */
2586 public function makeHelpMsgParameters() {
2587 wfDeprecated( __METHOD__, '1.25' );
2588 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
2589 if ( $params ) {
2590
2591 $paramsDescription = $this->getFinalParamDescription();
2592 $msg = '';
2593 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2594 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2595 foreach ( $params as $paramName => $paramSettings ) {
2596 $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
2597 if ( is_array( $desc ) ) {
2598 $desc = implode( $paramPrefix, $desc );
2599 }
2600
2601 //handle shorthand
2602 if ( !is_array( $paramSettings ) ) {
2603 $paramSettings = array(
2604 self::PARAM_DFLT => $paramSettings,
2605 );
2606 }
2607
2608 //handle missing type
2609 if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) {
2610 $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] )
2611 ? $paramSettings[ApiBase::PARAM_DFLT]
2612 : null;
2613 if ( is_bool( $dflt ) ) {
2614 $paramSettings[ApiBase::PARAM_TYPE] = 'boolean';
2615 } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
2616 $paramSettings[ApiBase::PARAM_TYPE] = 'string';
2617 } elseif ( is_int( $dflt ) ) {
2618 $paramSettings[ApiBase::PARAM_TYPE] = 'integer';
2619 }
2620 }
2621
2622 if ( isset( $paramSettings[self::PARAM_DEPRECATED] )
2623 && $paramSettings[self::PARAM_DEPRECATED]
2624 ) {
2625 $desc = "DEPRECATED! $desc";
2626 }
2627
2628 if ( isset( $paramSettings[self::PARAM_REQUIRED] )
2629 && $paramSettings[self::PARAM_REQUIRED]
2630 ) {
2631 $desc .= $paramPrefix . "This parameter is required";
2632 }
2633
2634 $type = isset( $paramSettings[self::PARAM_TYPE] )
2635 ? $paramSettings[self::PARAM_TYPE]
2636 : null;
2637 if ( isset( $type ) ) {
2638 $hintPipeSeparated = true;
2639 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
2640 ? $paramSettings[self::PARAM_ISMULTI]
2641 : false;
2642 if ( $multi ) {
2643 $prompt = 'Values (separate with \'|\'): ';
2644 } else {
2645 $prompt = 'One value: ';
2646 }
2647
2648 if ( $type === 'submodule' ) {
2649 $type = $this->getModuleManager()->getNames( $paramName );
2650 sort( $type );
2651 }
2652 if ( is_array( $type ) ) {
2653 $choices = array();
2654 $nothingPrompt = '';
2655 foreach ( $type as $t ) {
2656 if ( $t === '' ) {
2657 $nothingPrompt = 'Can be empty, or ';
2658 } else {
2659 $choices[] = $t;
2660 }
2661 }
2662 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2663 $choicesstring = implode( ', ', $choices );
2664 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2665 $hintPipeSeparated = false;
2666 } else {
2667 switch ( $type ) {
2668 case 'namespace':
2669 // Special handling because namespaces are
2670 // type-limited, yet they are not given
2671 $desc .= $paramPrefix . $prompt;
2672 $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
2673 100, $descWordwrap );
2674 $hintPipeSeparated = false;
2675 break;
2676 case 'limit':
2677 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2678 if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
2679 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2680 }
2681 $desc .= ' allowed';
2682 break;
2683 case 'integer':
2684 $s = $multi ? 's' : '';
2685 $hasMin = isset( $paramSettings[self::PARAM_MIN] );
2686 $hasMax = isset( $paramSettings[self::PARAM_MAX] );
2687 if ( $hasMin || $hasMax ) {
2688 if ( !$hasMax ) {
2689 $intRangeStr = "The value$s must be no less than " .
2690 "{$paramSettings[self::PARAM_MIN]}";
2691 } elseif ( !$hasMin ) {
2692 $intRangeStr = "The value$s must be no more than " .
2693 "{$paramSettings[self::PARAM_MAX]}";
2694 } else {
2695 $intRangeStr = "The value$s must be between " .
2696 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2697 }
2698
2699 $desc .= $paramPrefix . $intRangeStr;
2700 }
2701 break;
2702 case 'upload':
2703 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2704 break;
2705 }
2706 }
2707
2708 if ( $multi ) {
2709 if ( $hintPipeSeparated ) {
2710 $desc .= $paramPrefix . "Separate values with '|'";
2711 }
2712
2713 $isArray = is_array( $type );
2714 if ( !$isArray
2715 || $isArray && count( $type ) > self::LIMIT_SML1
2716 ) {
2717 $desc .= $paramPrefix . "Maximum number of values " .
2718 self::LIMIT_SML1 . " (" . self::LIMIT_SML2 . " for bots)";
2719 }
2720 }
2721 }
2722
2723 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
2724 if ( !is_null( $default ) && $default !== false ) {
2725 $desc .= $paramPrefix . "Default: $default";
2726 }
2727
2728 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2729 }
2730
2731 return $msg;
2732 }
2733
2734 return false;
2735 }
2736
2737 /**@}*/
2738 }
2739
2740 /**
2741 * For really cool vim folding this needs to be at the end:
2742 * vim: foldmarker=@{,@} foldmethod=marker
2743 */