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