Merge "Fix sessionfailure i18n message during authentication"
[lhc/web/wiklou.git] / includes / api / ApiBase.php
1 <?php
2 /**
3 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use Wikimedia\Rdbms\IDatabase;
24
25 /**
26 * This abstract class implements many basic API functions, and is the base of
27 * all API classes.
28 * The class functions are divided into several areas of functionality:
29 *
30 * Module parameters: Derived classes can define getAllowedParams() to specify
31 * which parameters to expect, how to parse and validate them.
32 *
33 * Self-documentation: code to allow the API to document its own state
34 *
35 * @ingroup API
36 */
37 abstract class ApiBase extends ContextSource {
38
39 /**
40 * @name Constants for ::getAllowedParams() arrays
41 * These constants are keys in the arrays returned by ::getAllowedParams()
42 * and accepted by ::getParameterFromSettings() that define how the
43 * parameters coming in from the request are to be interpreted.
44 * @{
45 */
46
47 /** (null|boolean|integer|string) Default value of the parameter. */
48 const PARAM_DFLT = 0;
49
50 /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
51 const PARAM_ISMULTI = 1;
52
53 /**
54 * (string|string[]) Either an array of allowed value strings, or a string
55 * type as described below. If not specified, will be determined from the
56 * type of PARAM_DFLT.
57 *
58 * Supported string types are:
59 * - boolean: A boolean parameter, returned as false if the parameter is
60 * omitted and true if present (even with a falsey value, i.e. it works
61 * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
62 * Cannot be used with PARAM_ISMULTI.
63 * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
64 * PARAM_RANGE_ENFORCE.
65 * - limit: An integer or the string 'max'. Default lower limit is 0 (but
66 * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
67 * specified. Cannot be used with PARAM_ISMULTI.
68 * - namespace: An integer representing a MediaWiki namespace. Forces PARAM_ALL = true to
69 * support easily specifying all namespaces.
70 * - NULL: Any string.
71 * - password: Any non-empty string. Input value is private or sensitive.
72 * <input type="password"> would be an appropriate HTML form field.
73 * - string: Any non-empty string, not expected to be very long or contain newlines.
74 * <input type="text"> would be an appropriate HTML form field.
75 * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
76 * - tags: A string naming an existing, explicitly-defined tag. Should usually be
77 * used with PARAM_ISMULTI.
78 * - text: Any non-empty string, expected to be very long or contain newlines.
79 * <textarea> would be an appropriate HTML form field.
80 * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
81 * string 'now' representing the current timestamp. Will be returned in
82 * TS_MW format.
83 * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
84 * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
85 * Cannot be used with PARAM_ISMULTI.
86 */
87 const PARAM_TYPE = 2;
88
89 /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
90 const PARAM_MAX = 3;
91
92 /**
93 * (integer) Max value allowed for the parameter for users with the
94 * apihighlimits right, for PARAM_TYPE 'limit'.
95 */
96 const PARAM_MAX2 = 4;
97
98 /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
99 const PARAM_MIN = 5;
100
101 /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
102 const PARAM_ALLOW_DUPLICATES = 6;
103
104 /** (boolean) Is the parameter deprecated (will show a warning)? */
105 const PARAM_DEPRECATED = 7;
106
107 /**
108 * (boolean) Is the parameter required?
109 * @since 1.17
110 */
111 const PARAM_REQUIRED = 8;
112
113 /**
114 * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
115 * @since 1.17
116 */
117 const PARAM_RANGE_ENFORCE = 9;
118
119 /**
120 * (string|array|Message) Specify an alternative i18n documentation message
121 * for this parameter. Default is apihelp-{$path}-param-{$param}.
122 * @since 1.25
123 */
124 const PARAM_HELP_MSG = 10;
125
126 /**
127 * ((string|array|Message)[]) Specify additional i18n messages to append to
128 * the normal message for this parameter.
129 * @since 1.25
130 */
131 const PARAM_HELP_MSG_APPEND = 11;
132
133 /**
134 * (array) Specify additional information tags for the parameter. Value is
135 * an array of arrays, with the first member being the 'tag' for the info
136 * and the remaining members being the values. In the help, this is
137 * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
138 * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
139 * @since 1.25
140 */
141 const PARAM_HELP_MSG_INFO = 12;
142
143 /**
144 * (string[]) When PARAM_TYPE is an array, this may be an array mapping
145 * those values to page titles which will be linked in the help.
146 * @since 1.25
147 */
148 const PARAM_VALUE_LINKS = 13;
149
150 /**
151 * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
152 * mapping those values to $msg for ApiBase::makeMessage(). Any value not
153 * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
154 * Specify an empty array to use the default message key for all values.
155 * @since 1.25
156 */
157 const PARAM_HELP_MSG_PER_VALUE = 14;
158
159 /**
160 * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
161 * submodule paths. Default is to use all modules in
162 * $this->getModuleManager() in the group matching the parameter name.
163 * @since 1.26
164 */
165 const PARAM_SUBMODULE_MAP = 15;
166
167 /**
168 * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
169 * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
170 * @since 1.26
171 */
172 const PARAM_SUBMODULE_PARAM_PREFIX = 16;
173
174 /**
175 * (boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,
176 * this allows for an asterisk ('*') to be passed in place of a pipe-separated list of
177 * every possible value. If a string is set, it will be used in place of the asterisk.
178 * @since 1.29
179 */
180 const PARAM_ALL = 17;
181
182 /**
183 * (int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
184 * @since 1.29
185 */
186 const PARAM_EXTRA_NAMESPACES = 18;
187
188 /**
189 * (boolean) Is the parameter sensitive? Note 'password'-type fields are
190 * always sensitive regardless of the value of this field.
191 * @since 1.29
192 */
193 const PARAM_SENSITIVE = 19;
194
195 /**
196 * (array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
197 * Keys are the deprecated parameter values, values define the warning
198 * message to emit: either boolean true (to use a default message) or a
199 * $msg for ApiBase::makeMessage().
200 * @since 1.30
201 */
202 const PARAM_DEPRECATED_VALUES = 20;
203
204 /**
205 * (integer) Maximum number of values, for normal users. Must be used with PARAM_ISMULTI.
206 * @since 1.30
207 */
208 const PARAM_ISMULTI_LIMIT1 = 21;
209
210 /**
211 * (integer) Maximum number of values, for users with the apihighimits right.
212 * Must be used with PARAM_ISMULTI.
213 * @since 1.30
214 */
215 const PARAM_ISMULTI_LIMIT2 = 22;
216
217 /**
218 * (integer) Maximum length of a string in bytes (in UTF-8 encoding).
219 * @since 1.31
220 */
221 const PARAM_MAX_BYTES = 23;
222
223 /**
224 * (integer) Maximum length of a string in characters (unicode codepoints).
225 * @since 1.31
226 */
227 const PARAM_MAX_CHARS = 24;
228
229 /**@}*/
230
231 const ALL_DEFAULT_STRING = '*';
232
233 /** Fast query, standard limit. */
234 const LIMIT_BIG1 = 500;
235 /** Fast query, apihighlimits limit. */
236 const LIMIT_BIG2 = 5000;
237 /** Slow query, standard limit. */
238 const LIMIT_SML1 = 50;
239 /** Slow query, apihighlimits limit. */
240 const LIMIT_SML2 = 500;
241
242 /**
243 * getAllowedParams() flag: When set, the result could take longer to generate,
244 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
245 * @since 1.21
246 */
247 const GET_VALUES_FOR_HELP = 1;
248
249 /** @var array Maps extension paths to info arrays */
250 private static $extensionInfo = null;
251
252 /** @var ApiMain */
253 private $mMainModule;
254 /** @var string */
255 private $mModuleName, $mModulePrefix;
256 private $mSlaveDB = null;
257 private $mParamCache = [];
258 /** @var array|null|bool */
259 private $mModuleSource = false;
260
261 /**
262 * @param ApiMain $mainModule
263 * @param string $moduleName Name of this module
264 * @param string $modulePrefix Prefix to use for parameter names
265 */
266 public function __construct( ApiMain $mainModule, $moduleName, $modulePrefix = '' ) {
267 $this->mMainModule = $mainModule;
268 $this->mModuleName = $moduleName;
269 $this->mModulePrefix = $modulePrefix;
270
271 if ( !$this->isMain() ) {
272 $this->setContext( $mainModule->getContext() );
273 }
274 }
275
276 /************************************************************************//**
277 * @name Methods to implement
278 * @{
279 */
280
281 /**
282 * Evaluates the parameters, performs the requested query, and sets up
283 * the result. Concrete implementations of ApiBase must override this
284 * method to provide whatever functionality their module offers.
285 * Implementations must not produce any output on their own and are not
286 * expected to handle any errors.
287 *
288 * The execute() method will be invoked directly by ApiMain immediately
289 * before the result of the module is output. Aside from the
290 * constructor, implementations should assume that no other methods
291 * will be called externally on the module before the result is
292 * processed.
293 *
294 * The result data should be stored in the ApiResult object available
295 * through getResult().
296 */
297 abstract public function execute();
298
299 /**
300 * Get the module manager, or null if this module has no sub-modules
301 * @since 1.21
302 * @return ApiModuleManager
303 */
304 public function getModuleManager() {
305 return null;
306 }
307
308 /**
309 * If the module may only be used with a certain format module,
310 * it should override this method to return an instance of that formatter.
311 * A value of null means the default format will be used.
312 * @note Do not use this just because you don't want to support non-json
313 * formats. This should be used only when there is a fundamental
314 * requirement for a specific format.
315 * @return mixed Instance of a derived class of ApiFormatBase, or null
316 */
317 public function getCustomPrinter() {
318 return null;
319 }
320
321 /**
322 * Returns usage examples for this module.
323 *
324 * Return value has query strings as keys, with values being either strings
325 * (message key), arrays (message key + parameter), or Message objects.
326 *
327 * Do not call this base class implementation when overriding this method.
328 *
329 * @since 1.25
330 * @return array
331 */
332 protected function getExamplesMessages() {
333 // Fall back to old non-localised method
334 $ret = [];
335
336 $examples = $this->getExamples();
337 if ( $examples ) {
338 if ( !is_array( $examples ) ) {
339 $examples = [ $examples ];
340 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
341 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
342 !preg_match( '/^\s*api\.php\?/', $examples[0] )
343 ) {
344 // Fix up the ugly "even numbered elements are description, odd
345 // numbered elemts are the link" format (see doc for self::getExamples)
346 $tmp = [];
347 $examplesCount = count( $examples );
348 for ( $i = 0; $i < $examplesCount; $i += 2 ) {
349 $tmp[$examples[$i + 1]] = $examples[$i];
350 }
351 $examples = $tmp;
352 }
353
354 foreach ( $examples as $k => $v ) {
355 if ( is_numeric( $k ) ) {
356 $qs = $v;
357 $msg = '';
358 } else {
359 $qs = $k;
360 $msg = self::escapeWikiText( $v );
361 if ( is_array( $msg ) ) {
362 $msg = implode( ' ', $msg );
363 }
364 }
365
366 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
367 $ret[$qs] = $this->msg( 'api-help-fallback-example', [ $msg ] );
368 }
369 }
370
371 return $ret;
372 }
373
374 /**
375 * Return links to more detailed help pages about the module.
376 * @since 1.25, returning boolean false is deprecated
377 * @return string|array
378 */
379 public function getHelpUrls() {
380 return [];
381 }
382
383 /**
384 * Returns an array of allowed parameters (parameter name) => (default
385 * value) or (parameter name) => (array with PARAM_* constants as keys)
386 * Don't call this function directly: use getFinalParams() to allow
387 * hooks to modify parameters as needed.
388 *
389 * Some derived classes may choose to handle an integer $flags parameter
390 * in the overriding methods. Callers of this method can pass zero or
391 * more OR-ed flags like GET_VALUES_FOR_HELP.
392 *
393 * @return array
394 */
395 protected function getAllowedParams( /* $flags = 0 */ ) {
396 // int $flags is not declared because it causes "Strict standards"
397 // warning. Most derived classes do not implement it.
398 return [];
399 }
400
401 /**
402 * Indicates if this module needs maxlag to be checked
403 * @return bool
404 */
405 public function shouldCheckMaxlag() {
406 return true;
407 }
408
409 /**
410 * Indicates whether this module requires read rights
411 * @return bool
412 */
413 public function isReadMode() {
414 return true;
415 }
416
417 /**
418 * Indicates whether this module requires write mode
419 *
420 * This should return true for modules that may require synchronous database writes.
421 * Modules that do not need such writes should also not rely on master database access,
422 * since only read queries are needed and each master DB is a single point of failure.
423 * Additionally, requests that only need replica DBs can be efficiently routed to any
424 * datacenter via the Promise-Non-Write-API-Action header.
425 *
426 * @return bool
427 */
428 public function isWriteMode() {
429 return false;
430 }
431
432 /**
433 * Indicates whether this module must be called with a POST request
434 * @return bool
435 */
436 public function mustBePosted() {
437 return $this->needsToken() !== false;
438 }
439
440 /**
441 * Indicates whether this module is deprecated
442 * @since 1.25
443 * @return bool
444 */
445 public function isDeprecated() {
446 return false;
447 }
448
449 /**
450 * Indicates whether this module is "internal"
451 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
452 * @since 1.25
453 * @return bool
454 */
455 public function isInternal() {
456 return false;
457 }
458
459 /**
460 * Returns the token type this module requires in order to execute.
461 *
462 * Modules are strongly encouraged to use the core 'csrf' type unless they
463 * have specialized security needs. If the token type is not one of the
464 * core types, you must use the ApiQueryTokensRegisterTypes hook to
465 * register it.
466 *
467 * Returning a non-falsey value here will force the addition of an
468 * appropriate 'token' parameter in self::getFinalParams(). Also,
469 * self::mustBePosted() must return true when tokens are used.
470 *
471 * In previous versions of MediaWiki, true was a valid return value.
472 * Returning true will generate errors indicating that the API module needs
473 * updating.
474 *
475 * @return string|false
476 */
477 public function needsToken() {
478 return false;
479 }
480
481 /**
482 * Fetch the salt used in the Web UI corresponding to this module.
483 *
484 * Only override this if the Web UI uses a token with a non-constant salt.
485 *
486 * @since 1.24
487 * @param array $params All supplied parameters for the module
488 * @return string|array|null
489 */
490 protected function getWebUITokenSalt( array $params ) {
491 return null;
492 }
493
494 /**
495 * Returns data for HTTP conditional request mechanisms.
496 *
497 * @since 1.26
498 * @param string $condition Condition being queried:
499 * - last-modified: Return a timestamp representing the maximum of the
500 * last-modified dates for all resources involved in the request. See
501 * RFC 7232 § 2.2 for semantics.
502 * - etag: Return an entity-tag representing the state of all resources involved
503 * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
504 * @return string|bool|null As described above, or null if no value is available.
505 */
506 public function getConditionalRequestData( $condition ) {
507 return null;
508 }
509
510 /**@}*/
511
512 /************************************************************************//**
513 * @name Data access methods
514 * @{
515 */
516
517 /**
518 * Get the name of the module being executed by this instance
519 * @return string
520 */
521 public function getModuleName() {
522 return $this->mModuleName;
523 }
524
525 /**
526 * Get parameter prefix (usually two letters or an empty string).
527 * @return string
528 */
529 public function getModulePrefix() {
530 return $this->mModulePrefix;
531 }
532
533 /**
534 * Get the main module
535 * @return ApiMain
536 */
537 public function getMain() {
538 return $this->mMainModule;
539 }
540
541 /**
542 * Returns true if this module is the main module ($this === $this->mMainModule),
543 * false otherwise.
544 * @return bool
545 */
546 public function isMain() {
547 return $this === $this->mMainModule;
548 }
549
550 /**
551 * Get the parent of this module
552 * @since 1.25
553 * @return ApiBase|null
554 */
555 public function getParent() {
556 return $this->isMain() ? null : $this->getMain();
557 }
558
559 /**
560 * Returns true if the current request breaks the same-origin policy.
561 *
562 * For example, json with callbacks.
563 *
564 * https://en.wikipedia.org/wiki/Same-origin_policy
565 *
566 * @since 1.25
567 * @return bool
568 */
569 public function lacksSameOriginSecurity() {
570 // Main module has this method overridden
571 // Safety - avoid infinite loop:
572 if ( $this->isMain() ) {
573 self::dieDebug( __METHOD__, 'base method was called on main module.' );
574 }
575
576 return $this->getMain()->lacksSameOriginSecurity();
577 }
578
579 /**
580 * Get the path to this module
581 *
582 * @since 1.25
583 * @return string
584 */
585 public function getModulePath() {
586 if ( $this->isMain() ) {
587 return 'main';
588 } elseif ( $this->getParent()->isMain() ) {
589 return $this->getModuleName();
590 } else {
591 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
592 }
593 }
594
595 /**
596 * Get a module from its module path
597 *
598 * @since 1.25
599 * @param string $path
600 * @return ApiBase|null
601 * @throws ApiUsageException
602 */
603 public function getModuleFromPath( $path ) {
604 $module = $this->getMain();
605 if ( $path === 'main' ) {
606 return $module;
607 }
608
609 $parts = explode( '+', $path );
610 if ( count( $parts ) === 1 ) {
611 // In case the '+' was typed into URL, it resolves as a space
612 $parts = explode( ' ', $path );
613 }
614
615 $count = count( $parts );
616 for ( $i = 0; $i < $count; $i++ ) {
617 $parent = $module;
618 $manager = $parent->getModuleManager();
619 if ( $manager === null ) {
620 $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
621 $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
622 }
623 $module = $manager->getModule( $parts[$i] );
624
625 if ( $module === null ) {
626 $errorPath = $i ? implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
627 $this->dieWithError(
628 [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
629 'badmodule'
630 );
631 }
632 }
633
634 return $module;
635 }
636
637 /**
638 * Get the result object
639 * @return ApiResult
640 */
641 public function getResult() {
642 // Main module has getResult() method overridden
643 // Safety - avoid infinite loop:
644 if ( $this->isMain() ) {
645 self::dieDebug( __METHOD__, 'base method was called on main module. ' );
646 }
647
648 return $this->getMain()->getResult();
649 }
650
651 /**
652 * Get the error formatter
653 * @return ApiErrorFormatter
654 */
655 public function getErrorFormatter() {
656 // Main module has getErrorFormatter() method overridden
657 // Safety - avoid infinite loop:
658 if ( $this->isMain() ) {
659 self::dieDebug( __METHOD__, 'base method was called on main module. ' );
660 }
661
662 return $this->getMain()->getErrorFormatter();
663 }
664
665 /**
666 * Gets a default replica DB connection object
667 * @return IDatabase
668 */
669 protected function getDB() {
670 if ( !isset( $this->mSlaveDB ) ) {
671 $this->mSlaveDB = wfGetDB( DB_REPLICA, 'api' );
672 }
673
674 return $this->mSlaveDB;
675 }
676
677 /**
678 * Get the continuation manager
679 * @return ApiContinuationManager|null
680 */
681 public function getContinuationManager() {
682 // Main module has getContinuationManager() method overridden
683 // Safety - avoid infinite loop:
684 if ( $this->isMain() ) {
685 self::dieDebug( __METHOD__, 'base method was called on main module. ' );
686 }
687
688 return $this->getMain()->getContinuationManager();
689 }
690
691 /**
692 * Set the continuation manager
693 * @param ApiContinuationManager|null $manager
694 */
695 public function setContinuationManager( $manager ) {
696 // Main module has setContinuationManager() method overridden
697 // Safety - avoid infinite loop:
698 if ( $this->isMain() ) {
699 self::dieDebug( __METHOD__, 'base method was called on main module. ' );
700 }
701
702 $this->getMain()->setContinuationManager( $manager );
703 }
704
705 /**@}*/
706
707 /************************************************************************//**
708 * @name Parameter handling
709 * @{
710 */
711
712 /**
713 * Indicate if the module supports dynamically-determined parameters that
714 * cannot be included in self::getAllowedParams().
715 * @return string|array|Message|null Return null if the module does not
716 * support additional dynamic parameters, otherwise return a message
717 * describing them.
718 */
719 public function dynamicParameterDocumentation() {
720 return null;
721 }
722
723 /**
724 * This method mangles parameter name based on the prefix supplied to the constructor.
725 * Override this method to change parameter name during runtime
726 * @param string|string[] $paramName Parameter name
727 * @return string|string[] Prefixed parameter name
728 * @since 1.29 accepts an array of strings
729 */
730 public function encodeParamName( $paramName ) {
731 if ( is_array( $paramName ) ) {
732 return array_map( function ( $name ) {
733 return $this->mModulePrefix . $name;
734 }, $paramName );
735 } else {
736 return $this->mModulePrefix . $paramName;
737 }
738 }
739
740 /**
741 * Using getAllowedParams(), this function makes an array of the values
742 * provided by the user, with key being the name of the variable, and
743 * value - validated value from user or default. limits will not be
744 * parsed if $parseLimit is set to false; use this when the max
745 * limit is not definitive yet, e.g. when getting revisions.
746 * @param bool $parseLimit True by default
747 * @return array
748 */
749 public function extractRequestParams( $parseLimit = true ) {
750 // Cache parameters, for performance and to avoid T26564.
751 if ( !isset( $this->mParamCache[$parseLimit] ) ) {
752 $params = $this->getFinalParams();
753 $results = [];
754
755 if ( $params ) { // getFinalParams() can return false
756 foreach ( $params as $paramName => $paramSettings ) {
757 $results[$paramName] = $this->getParameterFromSettings(
758 $paramName, $paramSettings, $parseLimit );
759 }
760 }
761 $this->mParamCache[$parseLimit] = $results;
762 }
763
764 return $this->mParamCache[$parseLimit];
765 }
766
767 /**
768 * Get a value for the given parameter
769 * @param string $paramName Parameter name
770 * @param bool $parseLimit See extractRequestParams()
771 * @return mixed Parameter value
772 */
773 protected function getParameter( $paramName, $parseLimit = true ) {
774 $paramSettings = $this->getFinalParams()[$paramName];
775
776 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
777 }
778
779 /**
780 * Die if none or more than one of a certain set of parameters is set and not false.
781 *
782 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
783 * @param string $required,... Names of parameters of which exactly one must be set
784 */
785 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
786 $required = func_get_args();
787 array_shift( $required );
788
789 $intersection = array_intersect( array_keys( array_filter( $params,
790 [ $this, 'parameterNotEmpty' ] ) ), $required );
791
792 if ( count( $intersection ) > 1 ) {
793 $this->dieWithError( [
794 'apierror-invalidparammix',
795 Message::listParam( array_map(
796 function ( $p ) {
797 return '<var>' . $this->encodeParamName( $p ) . '</var>';
798 },
799 array_values( $intersection )
800 ) ),
801 count( $intersection ),
802 ] );
803 } elseif ( count( $intersection ) == 0 ) {
804 $this->dieWithError( [
805 'apierror-missingparam-one-of',
806 Message::listParam( array_map(
807 function ( $p ) {
808 return '<var>' . $this->encodeParamName( $p ) . '</var>';
809 },
810 array_values( $required )
811 ) ),
812 count( $required ),
813 ], 'missingparam' );
814 }
815 }
816
817 /**
818 * Die if more than one of a certain set of parameters is set and not false.
819 *
820 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
821 * @param string $required,... Names of parameters of which at most one must be set
822 */
823 public function requireMaxOneParameter( $params, $required /*...*/ ) {
824 $required = func_get_args();
825 array_shift( $required );
826
827 $intersection = array_intersect( array_keys( array_filter( $params,
828 [ $this, 'parameterNotEmpty' ] ) ), $required );
829
830 if ( count( $intersection ) > 1 ) {
831 $this->dieWithError( [
832 'apierror-invalidparammix',
833 Message::listParam( array_map(
834 function ( $p ) {
835 return '<var>' . $this->encodeParamName( $p ) . '</var>';
836 },
837 array_values( $intersection )
838 ) ),
839 count( $intersection ),
840 ] );
841 }
842 }
843
844 /**
845 * Die if none of a certain set of parameters is set and not false.
846 *
847 * @since 1.23
848 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
849 * @param string $required,... Names of parameters of which at least one must be set
850 */
851 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
852 $required = func_get_args();
853 array_shift( $required );
854
855 $intersection = array_intersect(
856 array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
857 $required
858 );
859
860 if ( count( $intersection ) == 0 ) {
861 $this->dieWithError( [
862 'apierror-missingparam-at-least-one-of',
863 Message::listParam( array_map(
864 function ( $p ) {
865 return '<var>' . $this->encodeParamName( $p ) . '</var>';
866 },
867 array_values( $required )
868 ) ),
869 count( $required ),
870 ], 'missingparam' );
871 }
872 }
873
874 /**
875 * Die if any of the specified parameters were found in the query part of
876 * the URL rather than the post body.
877 * @since 1.28
878 * @param string[] $params Parameters to check
879 * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
880 */
881 public function requirePostedParameters( $params, $prefix = 'prefix' ) {
882 // Skip if $wgDebugAPI is set or we're in internal mode
883 if ( $this->getConfig()->get( 'DebugAPI' ) || $this->getMain()->isInternalMode() ) {
884 return;
885 }
886
887 $queryValues = $this->getRequest()->getQueryValues();
888 $badParams = [];
889 foreach ( $params as $param ) {
890 if ( $prefix !== 'noprefix' ) {
891 $param = $this->encodeParamName( $param );
892 }
893 if ( array_key_exists( $param, $queryValues ) ) {
894 $badParams[] = $param;
895 }
896 }
897
898 if ( $badParams ) {
899 $this->dieWithError(
900 [ 'apierror-mustpostparams', join( ', ', $badParams ), count( $badParams ) ]
901 );
902 }
903 }
904
905 /**
906 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
907 *
908 * @param object $x Parameter to check is not null/false
909 * @return bool
910 */
911 private function parameterNotEmpty( $x ) {
912 return !is_null( $x ) && $x !== false;
913 }
914
915 /**
916 * Get a WikiPage object from a title or pageid param, if possible.
917 * Can die, if no param is set or if the title or page id is not valid.
918 *
919 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
920 * @param bool|string $load Whether load the object's state from the database:
921 * - false: don't load (if the pageid is given, it will still be loaded)
922 * - 'fromdb': load from a replica DB
923 * - 'fromdbmaster': load from the master database
924 * @return WikiPage
925 */
926 public function getTitleOrPageId( $params, $load = false ) {
927 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
928
929 $pageObj = null;
930 if ( isset( $params['title'] ) ) {
931 $titleObj = Title::newFromText( $params['title'] );
932 if ( !$titleObj || $titleObj->isExternal() ) {
933 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
934 }
935 if ( !$titleObj->canExist() ) {
936 $this->dieWithError( 'apierror-pagecannotexist' );
937 }
938 $pageObj = WikiPage::factory( $titleObj );
939 if ( $load !== false ) {
940 $pageObj->loadPageData( $load );
941 }
942 } elseif ( isset( $params['pageid'] ) ) {
943 if ( $load === false ) {
944 $load = 'fromdb';
945 }
946 $pageObj = WikiPage::newFromID( $params['pageid'], $load );
947 if ( !$pageObj ) {
948 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
949 }
950 }
951
952 return $pageObj;
953 }
954
955 /**
956 * Get a Title object from a title or pageid param, if possible.
957 * Can die, if no param is set or if the title or page id is not valid.
958 *
959 * @since 1.29
960 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
961 * @return Title
962 */
963 public function getTitleFromTitleOrPageId( $params ) {
964 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
965
966 $titleObj = null;
967 if ( isset( $params['title'] ) ) {
968 $titleObj = Title::newFromText( $params['title'] );
969 if ( !$titleObj || $titleObj->isExternal() ) {
970 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
971 }
972 return $titleObj;
973 } elseif ( isset( $params['pageid'] ) ) {
974 $titleObj = Title::newFromID( $params['pageid'] );
975 if ( !$titleObj ) {
976 $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
977 }
978 }
979
980 return $titleObj;
981 }
982
983 /**
984 * Return true if we're to watch the page, false if not, null if no change.
985 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
986 * @param Title $titleObj The page under consideration
987 * @param string $userOption The user option to consider when $watchlist=preferences.
988 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
989 * @return bool
990 */
991 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
992 $userWatching = $this->getUser()->isWatched( $titleObj, User::IGNORE_USER_RIGHTS );
993
994 switch ( $watchlist ) {
995 case 'watch':
996 return true;
997
998 case 'unwatch':
999 return false;
1000
1001 case 'preferences':
1002 # If the user is already watching, don't bother checking
1003 if ( $userWatching ) {
1004 return true;
1005 }
1006 # If no user option was passed, use watchdefault and watchcreations
1007 if ( is_null( $userOption ) ) {
1008 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
1009 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
1010 }
1011
1012 # Watch the article based on the user preference
1013 return $this->getUser()->getBoolOption( $userOption );
1014
1015 case 'nochange':
1016 return $userWatching;
1017
1018 default:
1019 return $userWatching;
1020 }
1021 }
1022
1023 /**
1024 * Using the settings determine the value for the given parameter
1025 *
1026 * @param string $paramName Parameter name
1027 * @param array|mixed $paramSettings Default value or an array of settings
1028 * using PARAM_* constants.
1029 * @param bool $parseLimit Whether to parse and validate 'limit' parameters
1030 * @return mixed Parameter value
1031 */
1032 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
1033 // Some classes may decide to change parameter names
1034 $encParamName = $this->encodeParamName( $paramName );
1035
1036 // Shorthand
1037 if ( !is_array( $paramSettings ) ) {
1038 $paramSettings = [
1039 self::PARAM_DFLT => $paramSettings,
1040 ];
1041 }
1042
1043 $default = isset( $paramSettings[self::PARAM_DFLT] )
1044 ? $paramSettings[self::PARAM_DFLT]
1045 : null;
1046 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
1047 ? $paramSettings[self::PARAM_ISMULTI]
1048 : false;
1049 $multiLimit1 = isset( $paramSettings[self::PARAM_ISMULTI_LIMIT1] )
1050 ? $paramSettings[self::PARAM_ISMULTI_LIMIT1]
1051 : null;
1052 $multiLimit2 = isset( $paramSettings[self::PARAM_ISMULTI_LIMIT2] )
1053 ? $paramSettings[self::PARAM_ISMULTI_LIMIT2]
1054 : null;
1055 $type = isset( $paramSettings[self::PARAM_TYPE] )
1056 ? $paramSettings[self::PARAM_TYPE]
1057 : null;
1058 $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] )
1059 ? $paramSettings[self::PARAM_ALLOW_DUPLICATES]
1060 : false;
1061 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] )
1062 ? $paramSettings[self::PARAM_DEPRECATED]
1063 : false;
1064 $deprecatedValues = isset( $paramSettings[self::PARAM_DEPRECATED_VALUES] )
1065 ? $paramSettings[self::PARAM_DEPRECATED_VALUES]
1066 : [];
1067 $required = isset( $paramSettings[self::PARAM_REQUIRED] )
1068 ? $paramSettings[self::PARAM_REQUIRED]
1069 : false;
1070 $allowAll = isset( $paramSettings[self::PARAM_ALL] )
1071 ? $paramSettings[self::PARAM_ALL]
1072 : false;
1073
1074 // When type is not given, and no choices, the type is the same as $default
1075 if ( !isset( $type ) ) {
1076 if ( isset( $default ) ) {
1077 $type = gettype( $default );
1078 } else {
1079 $type = 'NULL'; // allow everything
1080 }
1081 }
1082
1083 if ( $type == 'password' || !empty( $paramSettings[self::PARAM_SENSITIVE] ) ) {
1084 $this->getMain()->markParamsSensitive( $encParamName );
1085 }
1086
1087 if ( $type == 'boolean' ) {
1088 if ( isset( $default ) && $default !== false ) {
1089 // Having a default value of anything other than 'false' is not allowed
1090 self::dieDebug(
1091 __METHOD__,
1092 "Boolean param $encParamName's default is set to '$default'. " .
1093 'Boolean parameters must default to false.'
1094 );
1095 }
1096
1097 $value = $this->getMain()->getCheck( $encParamName );
1098 } elseif ( $type == 'upload' ) {
1099 if ( isset( $default ) ) {
1100 // Having a default value is not allowed
1101 self::dieDebug(
1102 __METHOD__,
1103 "File upload param $encParamName's default is set to " .
1104 "'$default'. File upload parameters may not have a default." );
1105 }
1106 if ( $multi ) {
1107 self::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1108 }
1109 $value = $this->getMain()->getUpload( $encParamName );
1110 if ( !$value->exists() ) {
1111 // This will get the value without trying to normalize it
1112 // (because trying to normalize a large binary file
1113 // accidentally uploaded as a field fails spectacularly)
1114 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1115 if ( $value !== null ) {
1116 $this->dieWithError(
1117 [ 'apierror-badupload', $encParamName ],
1118 "badupload_{$encParamName}"
1119 );
1120 }
1121 }
1122 } else {
1123 $value = $this->getMain()->getVal( $encParamName, $default );
1124
1125 if ( isset( $value ) && $type == 'namespace' ) {
1126 $type = MWNamespace::getValidNamespaces();
1127 if ( isset( $paramSettings[self::PARAM_EXTRA_NAMESPACES] ) &&
1128 is_array( $paramSettings[self::PARAM_EXTRA_NAMESPACES] )
1129 ) {
1130 $type = array_merge( $type, $paramSettings[self::PARAM_EXTRA_NAMESPACES] );
1131 }
1132 // By default, namespace parameters allow ALL_DEFAULT_STRING to be used to specify
1133 // all namespaces.
1134 $allowAll = true;
1135 }
1136 if ( isset( $value ) && $type == 'submodule' ) {
1137 if ( isset( $paramSettings[self::PARAM_SUBMODULE_MAP] ) ) {
1138 $type = array_keys( $paramSettings[self::PARAM_SUBMODULE_MAP] );
1139 } else {
1140 $type = $this->getModuleManager()->getNames( $paramName );
1141 }
1142 }
1143
1144 $request = $this->getMain()->getRequest();
1145 $rawValue = $request->getRawVal( $encParamName );
1146 if ( $rawValue === null ) {
1147 $rawValue = $default;
1148 }
1149
1150 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1151 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1152 if ( $multi ) {
1153 // This loses the potential $wgContLang->checkTitleEncoding() transformation
1154 // done by WebRequest for $_GET. Let's call that a feature.
1155 $value = join( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1156 } else {
1157 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1158 }
1159 }
1160
1161 // Check for NFC normalization, and warn
1162 if ( $rawValue !== $value ) {
1163 $this->handleParamNormalization( $paramName, $value, $rawValue );
1164 }
1165 }
1166
1167 $allSpecifier = ( is_string( $allowAll ) ? $allowAll : self::ALL_DEFAULT_STRING );
1168 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1169 self::dieDebug(
1170 __METHOD__,
1171 "For param $encParamName, PARAM_ALL collides with a possible value" );
1172 }
1173 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
1174 $value = $this->parseMultiValue(
1175 $encParamName,
1176 $value,
1177 $multi,
1178 is_array( $type ) ? $type : null,
1179 $allowAll ? $allSpecifier : null,
1180 $multiLimit1,
1181 $multiLimit2
1182 );
1183 }
1184
1185 if ( isset( $value ) ) {
1186 // More validation only when choices were not given
1187 // choices were validated in parseMultiValue()
1188 if ( !is_array( $type ) ) {
1189 switch ( $type ) {
1190 case 'NULL': // nothing to do
1191 break;
1192 case 'string':
1193 case 'text':
1194 case 'password':
1195 if ( $required && $value === '' ) {
1196 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1197 }
1198 break;
1199 case 'integer': // Force everything using intval() and optionally validate limits
1200 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
1201 $max = isset( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
1202 $enforceLimits = isset( $paramSettings[self::PARAM_RANGE_ENFORCE] )
1203 ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
1204
1205 if ( is_array( $value ) ) {
1206 $value = array_map( 'intval', $value );
1207 if ( !is_null( $min ) || !is_null( $max ) ) {
1208 foreach ( $value as &$v ) {
1209 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1210 }
1211 }
1212 } else {
1213 $value = intval( $value );
1214 if ( !is_null( $min ) || !is_null( $max ) ) {
1215 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1216 }
1217 }
1218 break;
1219 case 'limit':
1220 if ( !$parseLimit ) {
1221 // Don't do any validation whatsoever
1222 break;
1223 }
1224 if ( !isset( $paramSettings[self::PARAM_MAX] )
1225 || !isset( $paramSettings[self::PARAM_MAX2] )
1226 ) {
1227 self::dieDebug(
1228 __METHOD__,
1229 "MAX1 or MAX2 are not defined for the limit $encParamName"
1230 );
1231 }
1232 if ( $multi ) {
1233 self::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1234 }
1235 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
1236 if ( $value == 'max' ) {
1237 $value = $this->getMain()->canApiHighLimits()
1238 ? $paramSettings[self::PARAM_MAX2]
1239 : $paramSettings[self::PARAM_MAX];
1240 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1241 } else {
1242 $value = intval( $value );
1243 $this->validateLimit(
1244 $paramName,
1245 $value,
1246 $min,
1247 $paramSettings[self::PARAM_MAX],
1248 $paramSettings[self::PARAM_MAX2]
1249 );
1250 }
1251 break;
1252 case 'boolean':
1253 if ( $multi ) {
1254 self::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1255 }
1256 break;
1257 case 'timestamp':
1258 if ( is_array( $value ) ) {
1259 foreach ( $value as $key => $val ) {
1260 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1261 }
1262 } else {
1263 $value = $this->validateTimestamp( $value, $encParamName );
1264 }
1265 break;
1266 case 'user':
1267 if ( is_array( $value ) ) {
1268 foreach ( $value as $key => $val ) {
1269 $value[$key] = $this->validateUser( $val, $encParamName );
1270 }
1271 } else {
1272 $value = $this->validateUser( $value, $encParamName );
1273 }
1274 break;
1275 case 'upload': // nothing to do
1276 break;
1277 case 'tags':
1278 // If change tagging was requested, check that the tags are valid.
1279 if ( !is_array( $value ) && !$multi ) {
1280 $value = [ $value ];
1281 }
1282 $tagsStatus = ChangeTags::canAddTagsAccompanyingChange( $value );
1283 if ( !$tagsStatus->isGood() ) {
1284 $this->dieStatus( $tagsStatus );
1285 }
1286 break;
1287 default:
1288 self::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
1289 }
1290 }
1291
1292 // Throw out duplicates if requested
1293 if ( !$dupes && is_array( $value ) ) {
1294 $value = array_unique( $value );
1295 }
1296
1297 if ( in_array( $type, [ 'NULL', 'string', 'text', 'password' ], true ) ) {
1298 foreach ( (array)$value as $val ) {
1299 if ( isset( $paramSettings[self::PARAM_MAX_BYTES] )
1300 && strlen( $val ) > $paramSettings[self::PARAM_MAX_BYTES]
1301 ) {
1302 $this->dieWithError( [ 'apierror-maxbytes', $encParamName,
1303 $paramSettings[self::PARAM_MAX_BYTES] ] );
1304 }
1305 if ( isset( $paramSettings[self::PARAM_MAX_CHARS] )
1306 && mb_strlen( $val, 'UTF-8' ) > $paramSettings[self::PARAM_MAX_CHARS]
1307 ) {
1308 $this->dieWithError( [ 'apierror-maxchars', $encParamName,
1309 $paramSettings[self::PARAM_MAX_CHARS] ] );
1310 }
1311 }
1312 }
1313
1314 // Set a warning if a deprecated parameter has been passed
1315 if ( $deprecated && $value !== false ) {
1316 $feature = $encParamName;
1317 $m = $this;
1318 while ( !$m->isMain() ) {
1319 $p = $m->getParent();
1320 $name = $m->getModuleName();
1321 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1322 $feature = "{$param}={$name}&{$feature}";
1323 $m = $p;
1324 }
1325 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1326 }
1327
1328 // Set a warning if a deprecated parameter value has been passed
1329 $usedDeprecatedValues = $deprecatedValues && $value !== false
1330 ? array_intersect( array_keys( $deprecatedValues ), (array)$value )
1331 : [];
1332 if ( $usedDeprecatedValues ) {
1333 $feature = "$encParamName=";
1334 $m = $this;
1335 while ( !$m->isMain() ) {
1336 $p = $m->getParent();
1337 $name = $m->getModuleName();
1338 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1339 $feature = "{$param}={$name}&{$feature}";
1340 $m = $p;
1341 }
1342 foreach ( $usedDeprecatedValues as $v ) {
1343 $msg = $deprecatedValues[$v];
1344 if ( $msg === true ) {
1345 $msg = [ 'apiwarn-deprecation-parameter', "$encParamName=$v" ];
1346 }
1347 $this->addDeprecation( $msg, "$feature$v" );
1348 }
1349 }
1350 } elseif ( $required ) {
1351 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1352 }
1353
1354 return $value;
1355 }
1356
1357 /**
1358 * Handle when a parameter was Unicode-normalized
1359 * @since 1.28
1360 * @param string $paramName Unprefixed parameter name
1361 * @param string $value Input that will be used.
1362 * @param string $rawValue Input before normalization.
1363 */
1364 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1365 $encParamName = $this->encodeParamName( $paramName );
1366 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1367 }
1368
1369 /**
1370 * Split a multi-valued parameter string, like explode()
1371 * @since 1.28
1372 * @param string $value
1373 * @param int $limit
1374 * @return string[]
1375 */
1376 protected function explodeMultiValue( $value, $limit ) {
1377 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1378 $sep = "\x1f";
1379 $value = substr( $value, 1 );
1380 } else {
1381 $sep = '|';
1382 }
1383
1384 return explode( $sep, $value, $limit );
1385 }
1386
1387 /**
1388 * Return an array of values that were given in a 'a|b|c' notation,
1389 * after it optionally validates them against the list allowed values.
1390 *
1391 * @param string $valueName The name of the parameter (for error
1392 * reporting)
1393 * @param mixed $value The value being parsed
1394 * @param bool $allowMultiple Can $value contain more than one value
1395 * separated by '|'?
1396 * @param string[]|null $allowedValues An array of values to check against. If
1397 * null, all values are accepted.
1398 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1399 * if this behavior should not be allowed
1400 * @param int|null $limit1 Maximum number of values, for normal users.
1401 * @param int|null $limit2 Maximum number of values, for users with the apihighlimits right.
1402 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1403 */
1404 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1405 $allSpecifier = null, $limit1 = null, $limit2 = null
1406 ) {
1407 if ( ( $value === '' || $value === "\x1f" ) && $allowMultiple ) {
1408 return [];
1409 }
1410 $limit1 = $limit1 ?: self::LIMIT_SML1;
1411 $limit2 = $limit2 ?: self::LIMIT_SML2;
1412
1413 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1414 // because it unstubs $wgUser
1415 $valuesList = $this->explodeMultiValue( $value, $limit2 + 1 );
1416 $sizeLimit = count( $valuesList ) > $limit1 && $this->mMainModule->canApiHighLimits()
1417 ? $limit2
1418 : $limit1;
1419
1420 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1421 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1422 ) {
1423 return $allowedValues;
1424 }
1425
1426 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
1427 $this->addDeprecation(
1428 [ 'apiwarn-toomanyvalues', $valueName, $sizeLimit ],
1429 "too-many-$valueName-for-{$this->getModulePath()}"
1430 );
1431 }
1432
1433 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1434 // T35482 - Allow entries with | in them for non-multiple values
1435 if ( in_array( $value, $allowedValues, true ) ) {
1436 return $value;
1437 }
1438
1439 if ( is_array( $allowedValues ) ) {
1440 $values = array_map( function ( $v ) {
1441 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1442 }, $allowedValues );
1443 $this->dieWithError( [
1444 'apierror-multival-only-one-of',
1445 $valueName,
1446 Message::listParam( $values ),
1447 count( $values ),
1448 ], "multival_$valueName" );
1449 } else {
1450 $this->dieWithError( [
1451 'apierror-multival-only-one',
1452 $valueName,
1453 ], "multival_$valueName" );
1454 }
1455 }
1456
1457 if ( is_array( $allowedValues ) ) {
1458 // Check for unknown values
1459 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1460 if ( count( $unknown ) ) {
1461 if ( $allowMultiple ) {
1462 $this->addWarning( [
1463 'apiwarn-unrecognizedvalues',
1464 $valueName,
1465 Message::listParam( $unknown, 'comma' ),
1466 count( $unknown ),
1467 ] );
1468 } else {
1469 $this->dieWithError(
1470 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1471 "unknown_$valueName"
1472 );
1473 }
1474 }
1475 // Now throw them out
1476 $valuesList = array_intersect( $valuesList, $allowedValues );
1477 }
1478
1479 return $allowMultiple ? $valuesList : $valuesList[0];
1480 }
1481
1482 /**
1483 * Validate the value against the minimum and user/bot maximum limits.
1484 * Prints usage info on failure.
1485 * @param string $paramName Parameter name
1486 * @param int &$value Parameter value
1487 * @param int|null $min Minimum value
1488 * @param int|null $max Maximum value for users
1489 * @param int $botMax Maximum value for sysops/bots
1490 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1491 */
1492 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1493 $enforceLimits = false
1494 ) {
1495 if ( !is_null( $min ) && $value < $min ) {
1496 $msg = ApiMessage::create(
1497 [ 'apierror-integeroutofrange-belowminimum',
1498 $this->encodeParamName( $paramName ), $min, $value ],
1499 'integeroutofrange',
1500 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
1501 );
1502 $this->warnOrDie( $msg, $enforceLimits );
1503 $value = $min;
1504 }
1505
1506 // Minimum is always validated, whereas maximum is checked only if not
1507 // running in internal call mode
1508 if ( $this->getMain()->isInternalMode() ) {
1509 return;
1510 }
1511
1512 // Optimization: do not check user's bot status unless really needed -- skips db query
1513 // assumes $botMax >= $max
1514 if ( !is_null( $max ) && $value > $max ) {
1515 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1516 if ( $value > $botMax ) {
1517 $msg = ApiMessage::create(
1518 [ 'apierror-integeroutofrange-abovebotmax',
1519 $this->encodeParamName( $paramName ), $botMax, $value ],
1520 'integeroutofrange',
1521 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
1522 );
1523 $this->warnOrDie( $msg, $enforceLimits );
1524 $value = $botMax;
1525 }
1526 } else {
1527 $msg = ApiMessage::create(
1528 [ 'apierror-integeroutofrange-abovemax',
1529 $this->encodeParamName( $paramName ), $max, $value ],
1530 'integeroutofrange',
1531 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
1532 );
1533 $this->warnOrDie( $msg, $enforceLimits );
1534 $value = $max;
1535 }
1536 }
1537 }
1538
1539 /**
1540 * Validate and normalize of parameters of type 'timestamp'
1541 * @param string $value Parameter value
1542 * @param string $encParamName Parameter name
1543 * @return string Validated and normalized parameter
1544 */
1545 protected function validateTimestamp( $value, $encParamName ) {
1546 // Confusing synonyms for the current time accepted by wfTimestamp()
1547 // (wfTimestamp() also accepts various non-strings and the string of 14
1548 // ASCII NUL bytes, but those can't get here)
1549 if ( !$value ) {
1550 $this->addDeprecation(
1551 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1552 'unclear-"now"-timestamp'
1553 );
1554 return wfTimestamp( TS_MW );
1555 }
1556
1557 // Explicit synonym for the current time
1558 if ( $value === 'now' ) {
1559 return wfTimestamp( TS_MW );
1560 }
1561
1562 $unixTimestamp = wfTimestamp( TS_UNIX, $value );
1563 if ( $unixTimestamp === false ) {
1564 $this->dieWithError(
1565 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1566 "badtimestamp_{$encParamName}"
1567 );
1568 }
1569
1570 return wfTimestamp( TS_MW, $unixTimestamp );
1571 }
1572
1573 /**
1574 * Validate the supplied token.
1575 *
1576 * @since 1.24
1577 * @param string $token Supplied token
1578 * @param array $params All supplied parameters for the module
1579 * @return bool
1580 * @throws MWException
1581 */
1582 final public function validateToken( $token, array $params ) {
1583 $tokenType = $this->needsToken();
1584 $salts = ApiQueryTokens::getTokenTypeSalts();
1585 if ( !isset( $salts[$tokenType] ) ) {
1586 throw new MWException(
1587 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1588 'without registering it'
1589 );
1590 }
1591
1592 $tokenObj = ApiQueryTokens::getToken(
1593 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1594 );
1595 if ( $tokenObj->match( $token ) ) {
1596 return true;
1597 }
1598
1599 $webUiSalt = $this->getWebUITokenSalt( $params );
1600 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1601 $token,
1602 $webUiSalt,
1603 $this->getRequest()
1604 ) ) {
1605 return true;
1606 }
1607
1608 return false;
1609 }
1610
1611 /**
1612 * Validate and normalize of parameters of type 'user'
1613 * @param string $value Parameter value
1614 * @param string $encParamName Parameter name
1615 * @return string Validated and normalized parameter
1616 */
1617 private function validateUser( $value, $encParamName ) {
1618 $title = Title::makeTitleSafe( NS_USER, $value );
1619 if ( $title === null || $title->hasFragment() ) {
1620 $this->dieWithError(
1621 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1622 "baduser_{$encParamName}"
1623 );
1624 }
1625
1626 return $title->getText();
1627 }
1628
1629 /**@}*/
1630
1631 /************************************************************************//**
1632 * @name Utility methods
1633 * @{
1634 */
1635
1636 /**
1637 * Set a watch (or unwatch) based the based on a watchlist parameter.
1638 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1639 * @param Title $titleObj The article's title to change
1640 * @param string $userOption The user option to consider when $watch=preferences
1641 */
1642 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1643 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1644 if ( $value === null ) {
1645 return;
1646 }
1647
1648 WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1649 }
1650
1651 /**
1652 * Truncate an array to a certain length.
1653 * @param array &$arr Array to truncate
1654 * @param int $limit Maximum length
1655 * @return bool True if the array was truncated, false otherwise
1656 */
1657 public static function truncateArray( &$arr, $limit ) {
1658 $modified = false;
1659 while ( count( $arr ) > $limit ) {
1660 array_pop( $arr );
1661 $modified = true;
1662 }
1663
1664 return $modified;
1665 }
1666
1667 /**
1668 * Gets the user for whom to get the watchlist
1669 *
1670 * @param array $params
1671 * @return User
1672 */
1673 public function getWatchlistUser( $params ) {
1674 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1675 $user = User::newFromName( $params['owner'], false );
1676 if ( !( $user && $user->getId() ) ) {
1677 $this->dieWithError(
1678 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1679 );
1680 }
1681 $token = $user->getOption( 'watchlisttoken' );
1682 if ( $token == '' || !hash_equals( $token, $params['token'] ) ) {
1683 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1684 }
1685 } else {
1686 if ( !$this->getUser()->isLoggedIn() ) {
1687 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1688 }
1689 $this->checkUserRightsAny( 'viewmywatchlist' );
1690 $user = $this->getUser();
1691 }
1692
1693 return $user;
1694 }
1695
1696 /**
1697 * A subset of wfEscapeWikiText for BC texts
1698 *
1699 * @since 1.25
1700 * @param string|array $v
1701 * @return string|array
1702 */
1703 private static function escapeWikiText( $v ) {
1704 if ( is_array( $v ) ) {
1705 return array_map( 'self::escapeWikiText', $v );
1706 } else {
1707 return strtr( $v, [
1708 '__' => '_&#95;', '{' => '&#123;', '}' => '&#125;',
1709 '[[Category:' => '[[:Category:',
1710 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1711 ] );
1712 }
1713 }
1714
1715 /**
1716 * Create a Message from a string or array
1717 *
1718 * A string is used as a message key. An array has the message key as the
1719 * first value and message parameters as subsequent values.
1720 *
1721 * @since 1.25
1722 * @param string|array|Message $msg
1723 * @param IContextSource $context
1724 * @param array $params
1725 * @return Message|null
1726 */
1727 public static function makeMessage( $msg, IContextSource $context, array $params = null ) {
1728 if ( is_string( $msg ) ) {
1729 $msg = wfMessage( $msg );
1730 } elseif ( is_array( $msg ) ) {
1731 $msg = call_user_func_array( 'wfMessage', $msg );
1732 }
1733 if ( !$msg instanceof Message ) {
1734 return null;
1735 }
1736
1737 $msg->setContext( $context );
1738 if ( $params ) {
1739 $msg->params( $params );
1740 }
1741
1742 return $msg;
1743 }
1744
1745 /**
1746 * Turn an array of message keys or key+param arrays into a Status
1747 * @since 1.29
1748 * @param array $errors
1749 * @param User|null $user
1750 * @return Status
1751 */
1752 public function errorArrayToStatus( array $errors, User $user = null ) {
1753 if ( $user === null ) {
1754 $user = $this->getUser();
1755 }
1756
1757 $status = Status::newGood();
1758 foreach ( $errors as $error ) {
1759 if ( is_array( $error ) && $error[0] === 'blockedtext' && $user->getBlock() ) {
1760 $status->fatal( ApiMessage::create(
1761 'apierror-blocked',
1762 'blocked',
1763 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
1764 ) );
1765 } elseif ( is_array( $error ) && $error[0] === 'autoblockedtext' && $user->getBlock() ) {
1766 $status->fatal( ApiMessage::create(
1767 'apierror-autoblocked',
1768 'autoblocked',
1769 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
1770 ) );
1771 } elseif ( is_array( $error ) && $error[0] === 'systemblockedtext' && $user->getBlock() ) {
1772 $status->fatal( ApiMessage::create(
1773 'apierror-systemblocked',
1774 'blocked',
1775 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
1776 ) );
1777 } else {
1778 call_user_func_array( [ $status, 'fatal' ], (array)$error );
1779 }
1780 }
1781 return $status;
1782 }
1783
1784 /**@}*/
1785
1786 /************************************************************************//**
1787 * @name Warning and error reporting
1788 * @{
1789 */
1790
1791 /**
1792 * Add a warning for this module.
1793 *
1794 * Users should monitor this section to notice any changes in API. Multiple
1795 * calls to this function will result in multiple warning messages.
1796 *
1797 * If $msg is not an ApiMessage, the message code will be derived from the
1798 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1799 *
1800 * @since 1.29
1801 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1802 * @param string|null $code See ApiErrorFormatter::addWarning()
1803 * @param array|null $data See ApiErrorFormatter::addWarning()
1804 */
1805 public function addWarning( $msg, $code = null, $data = null ) {
1806 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1807 }
1808
1809 /**
1810 * Add a deprecation warning for this module.
1811 *
1812 * A combination of $this->addWarning() and $this->logFeatureUsage()
1813 *
1814 * @since 1.29
1815 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1816 * @param string|null $feature See ApiBase::logFeatureUsage()
1817 * @param array|null $data See ApiErrorFormatter::addWarning()
1818 */
1819 public function addDeprecation( $msg, $feature, $data = [] ) {
1820 $data = (array)$data;
1821 if ( $feature !== null ) {
1822 $data['feature'] = $feature;
1823 $this->logFeatureUsage( $feature );
1824 }
1825 $this->addWarning( $msg, 'deprecation', $data );
1826
1827 // No real need to deduplicate here, ApiErrorFormatter does that for
1828 // us (assuming the hook is deterministic).
1829 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1830 Hooks::run( 'ApiDeprecationHelp', [ &$msgs ] );
1831 if ( count( $msgs ) > 1 ) {
1832 $key = '$' . join( ' $', range( 1, count( $msgs ) ) );
1833 $msg = ( new RawMessage( $key ) )->params( $msgs );
1834 } else {
1835 $msg = reset( $msgs );
1836 }
1837 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1838 }
1839
1840 /**
1841 * Add an error for this module without aborting
1842 *
1843 * If $msg is not an ApiMessage, the message code will be derived from the
1844 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1845 *
1846 * @note If you want to abort processing, use self::dieWithError() instead.
1847 * @since 1.29
1848 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1849 * @param string|null $code See ApiErrorFormatter::addError()
1850 * @param array|null $data See ApiErrorFormatter::addError()
1851 */
1852 public function addError( $msg, $code = null, $data = null ) {
1853 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1854 }
1855
1856 /**
1857 * Add warnings and/or errors from a Status
1858 *
1859 * @note If you want to abort processing, use self::dieStatus() instead.
1860 * @since 1.29
1861 * @param StatusValue $status
1862 * @param string[] $types 'warning' and/or 'error'
1863 */
1864 public function addMessagesFromStatus( StatusValue $status, $types = [ 'warning', 'error' ] ) {
1865 $this->getErrorFormatter()->addMessagesFromStatus( $this->getModulePath(), $status, $types );
1866 }
1867
1868 /**
1869 * Abort execution with an error
1870 *
1871 * If $msg is not an ApiMessage, the message code will be derived from the
1872 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1873 *
1874 * @since 1.29
1875 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1876 * @param string|null $code See ApiErrorFormatter::addError()
1877 * @param array|null $data See ApiErrorFormatter::addError()
1878 * @param int|null $httpCode HTTP error code to use
1879 * @throws ApiUsageException always
1880 */
1881 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1882 throw ApiUsageException::newWithMessage( $this, $msg, $code, $data, $httpCode );
1883 }
1884
1885 /**
1886 * Abort execution with an error derived from an exception
1887 *
1888 * @since 1.29
1889 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
1890 * @param array $options See ApiErrorFormatter::getMessageFromException()
1891 * @throws ApiUsageException always
1892 */
1893 public function dieWithException( $exception, array $options = [] ) {
1894 $this->dieWithError(
1895 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
1896 );
1897 }
1898
1899 /**
1900 * Adds a warning to the output, else dies
1901 *
1902 * @param ApiMessage $msg Message to show as a warning, or error message if dying
1903 * @param bool $enforceLimits Whether this is an enforce (die)
1904 */
1905 private function warnOrDie( ApiMessage $msg, $enforceLimits = false ) {
1906 if ( $enforceLimits ) {
1907 $this->dieWithError( $msg );
1908 } else {
1909 $this->addWarning( $msg );
1910 }
1911 }
1912
1913 /**
1914 * Throw an ApiUsageException, which will (if uncaught) call the main module's
1915 * error handler and die with an error message including block info.
1916 *
1917 * @since 1.27
1918 * @param Block $block The block used to generate the ApiUsageException
1919 * @throws ApiUsageException always
1920 */
1921 public function dieBlocked( Block $block ) {
1922 // Die using the appropriate message depending on block type
1923 if ( $block->getType() == Block::TYPE_AUTO ) {
1924 $this->dieWithError(
1925 'apierror-autoblocked',
1926 'autoblocked',
1927 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ]
1928 );
1929 } else {
1930 $this->dieWithError(
1931 'apierror-blocked',
1932 'blocked',
1933 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ]
1934 );
1935 }
1936 }
1937
1938 /**
1939 * Throw an ApiUsageException based on the Status object.
1940 *
1941 * @since 1.22
1942 * @since 1.29 Accepts a StatusValue
1943 * @param StatusValue $status
1944 * @throws ApiUsageException always
1945 */
1946 public function dieStatus( StatusValue $status ) {
1947 if ( $status->isGood() ) {
1948 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1949 }
1950
1951 // ApiUsageException needs a fatal status, but this method has
1952 // historically accepted any non-good status. Convert it if necessary.
1953 $status->setOK( false );
1954 if ( !$status->getErrorsByType( 'error' ) ) {
1955 $newStatus = Status::newGood();
1956 foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
1957 call_user_func_array(
1958 [ $newStatus, 'fatal' ],
1959 array_merge( [ $err['message'] ], $err['params'] )
1960 );
1961 }
1962 if ( !$newStatus->getErrorsByType( 'error' ) ) {
1963 $newStatus->fatal( 'unknownerror-nocode' );
1964 }
1965 $status = $newStatus;
1966 }
1967
1968 throw new ApiUsageException( $this, $status );
1969 }
1970
1971 /**
1972 * Helper function for readonly errors
1973 *
1974 * @throws ApiUsageException always
1975 */
1976 public function dieReadOnly() {
1977 $this->dieWithError(
1978 'apierror-readonly',
1979 'readonly',
1980 [ 'readonlyreason' => wfReadOnlyReason() ]
1981 );
1982 }
1983
1984 /**
1985 * Helper function for permission-denied errors
1986 * @since 1.29
1987 * @param string|string[] $rights
1988 * @param User|null $user
1989 * @throws ApiUsageException if the user doesn't have any of the rights.
1990 * The error message is based on $rights[0].
1991 */
1992 public function checkUserRightsAny( $rights, $user = null ) {
1993 if ( !$user ) {
1994 $user = $this->getUser();
1995 }
1996 $rights = (array)$rights;
1997 if ( !call_user_func_array( [ $user, 'isAllowedAny' ], $rights ) ) {
1998 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
1999 }
2000 }
2001
2002 /**
2003 * Helper function for permission-denied errors
2004 * @since 1.29
2005 * @param Title $title
2006 * @param string|string[] $actions
2007 * @param User|null $user
2008 * @throws ApiUsageException if the user doesn't have all of the rights.
2009 */
2010 public function checkTitleUserPermissions( Title $title, $actions, $user = null ) {
2011 if ( !$user ) {
2012 $user = $this->getUser();
2013 }
2014
2015 $errors = [];
2016 foreach ( (array)$actions as $action ) {
2017 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
2018 }
2019 if ( $errors ) {
2020 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
2021 }
2022 }
2023
2024 /**
2025 * Will only set a warning instead of failing if the global $wgDebugAPI
2026 * is set to true. Otherwise behaves exactly as self::dieWithError().
2027 *
2028 * @since 1.29
2029 * @param string|array|Message $msg
2030 * @param string|null $code
2031 * @param array|null $data
2032 * @param int|null $httpCode
2033 * @throws ApiUsageException
2034 */
2035 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
2036 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2037 $this->dieWithError( $msg, $code, $data, $httpCode );
2038 } else {
2039 $this->addWarning( $msg, $code, $data );
2040 }
2041 }
2042
2043 /**
2044 * Die with the 'badcontinue' error.
2045 *
2046 * This call is common enough to make it into the base method.
2047 *
2048 * @param bool $condition Will only die if this value is true
2049 * @throws ApiUsageException
2050 * @since 1.21
2051 */
2052 protected function dieContinueUsageIf( $condition ) {
2053 if ( $condition ) {
2054 $this->dieWithError( 'apierror-badcontinue' );
2055 }
2056 }
2057
2058 /**
2059 * Internal code errors should be reported with this method
2060 * @param string $method Method or function name
2061 * @param string $message Error message
2062 * @throws MWException always
2063 */
2064 protected static function dieDebug( $method, $message ) {
2065 throw new MWException( "Internal error in $method: $message" );
2066 }
2067
2068 /**
2069 * Write logging information for API features to a debug log, for usage
2070 * analysis.
2071 * @note Consider using $this->addDeprecation() instead to both warn and log.
2072 * @param string $feature Feature being used.
2073 */
2074 public function logFeatureUsage( $feature ) {
2075 $request = $this->getRequest();
2076 $s = '"' . addslashes( $feature ) . '"' .
2077 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2078 ' "' . $request->getIP() . '"' .
2079 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2080 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2081 wfDebugLog( 'api-feature-usage', $s, 'private' );
2082 }
2083
2084 /**@}*/
2085
2086 /************************************************************************//**
2087 * @name Help message generation
2088 * @{
2089 */
2090
2091 /**
2092 * Return the summary message.
2093 *
2094 * This is a one-line description of the module, suitable for display in a
2095 * list of modules.
2096 *
2097 * @since 1.30
2098 * @return string|array|Message
2099 */
2100 protected function getSummaryMessage() {
2101 return "apihelp-{$this->getModulePath()}-summary";
2102 }
2103
2104 /**
2105 * Return the extended help text message.
2106 *
2107 * This is additional text to display at the top of the help section, below
2108 * the summary.
2109 *
2110 * @since 1.30
2111 * @return string|array|Message
2112 */
2113 protected function getExtendedDescription() {
2114 return [ [
2115 "apihelp-{$this->getModulePath()}-extended-description",
2116 'api-help-no-extended-description',
2117 ] ];
2118 }
2119
2120 /**
2121 * Get final module summary
2122 *
2123 * Ideally this will just be the getSummaryMessage(). However, for
2124 * backwards compatibility, if that message does not exist then the first
2125 * line of wikitext from the description message will be used instead.
2126 *
2127 * @since 1.30
2128 * @return Message
2129 */
2130 public function getFinalSummary() {
2131 $msg = self::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2132 $this->getModulePrefix(),
2133 $this->getModuleName(),
2134 $this->getModulePath(),
2135 ] );
2136 if ( !$msg->exists() ) {
2137 wfDeprecated( 'API help "description" messages', '1.30' );
2138 $msg = self::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2139 $this->getModulePrefix(),
2140 $this->getModuleName(),
2141 $this->getModulePath(),
2142 ] );
2143 $msg = self::makeMessage( 'rawmessage', $this->getContext(), [
2144 preg_replace( '/\n.*/s', '', $msg->text() )
2145 ] );
2146 }
2147 return $msg;
2148 }
2149
2150 /**
2151 * Get final module description, after hooks have had a chance to tweak it as
2152 * needed.
2153 *
2154 * @since 1.25, returns Message[] rather than string[]
2155 * @return Message[]
2156 */
2157 public function getFinalDescription() {
2158 $desc = $this->getDescription();
2159
2160 // Avoid PHP 7.1 warning of passing $this by reference
2161 $apiModule = $this;
2162 Hooks::run( 'APIGetDescription', [ &$apiModule, &$desc ] );
2163 $desc = self::escapeWikiText( $desc );
2164 if ( is_array( $desc ) ) {
2165 $desc = implode( "\n", $desc );
2166 } else {
2167 $desc = (string)$desc;
2168 }
2169
2170 $summary = self::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2171 $this->getModulePrefix(),
2172 $this->getModuleName(),
2173 $this->getModulePath(),
2174 ] );
2175 $extendedDescription = self::makeMessage(
2176 $this->getExtendedDescription(), $this->getContext(), [
2177 $this->getModulePrefix(),
2178 $this->getModuleName(),
2179 $this->getModulePath(),
2180 ]
2181 );
2182
2183 if ( $summary->exists() ) {
2184 $msgs = [ $summary, $extendedDescription ];
2185 } else {
2186 wfDeprecated( 'API help "description" messages', '1.30' );
2187 $description = self::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2188 $this->getModulePrefix(),
2189 $this->getModuleName(),
2190 $this->getModulePath(),
2191 ] );
2192 if ( !$description->exists() ) {
2193 $description = $this->msg( 'api-help-fallback-description', $desc );
2194 }
2195 $msgs = [ $description ];
2196 }
2197
2198 Hooks::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2199
2200 return $msgs;
2201 }
2202
2203 /**
2204 * Get final list of parameters, after hooks have had a chance to
2205 * tweak it as needed.
2206 *
2207 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2208 * @return array|bool False on no parameters
2209 * @since 1.21 $flags param added
2210 */
2211 public function getFinalParams( $flags = 0 ) {
2212 $params = $this->getAllowedParams( $flags );
2213 if ( !$params ) {
2214 $params = [];
2215 }
2216
2217 if ( $this->needsToken() ) {
2218 $params['token'] = [
2219 self::PARAM_TYPE => 'string',
2220 self::PARAM_REQUIRED => true,
2221 self::PARAM_SENSITIVE => true,
2222 self::PARAM_HELP_MSG => [
2223 'api-help-param-token',
2224 $this->needsToken(),
2225 ],
2226 ] + ( isset( $params['token'] ) ? $params['token'] : [] );
2227 }
2228
2229 // Avoid PHP 7.1 warning of passing $this by reference
2230 $apiModule = $this;
2231 Hooks::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2232
2233 return $params;
2234 }
2235
2236 /**
2237 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2238 * needed.
2239 *
2240 * @since 1.25, returns array of Message[] rather than array of string[]
2241 * @return array Keys are parameter names, values are arrays of Message objects
2242 */
2243 public function getFinalParamDescription() {
2244 $prefix = $this->getModulePrefix();
2245 $name = $this->getModuleName();
2246 $path = $this->getModulePath();
2247
2248 $desc = $this->getParamDescription();
2249
2250 // Avoid PHP 7.1 warning of passing $this by reference
2251 $apiModule = $this;
2252 Hooks::run( 'APIGetParamDescription', [ &$apiModule, &$desc ] );
2253
2254 if ( !$desc ) {
2255 $desc = [];
2256 }
2257 $desc = self::escapeWikiText( $desc );
2258
2259 $params = $this->getFinalParams( self::GET_VALUES_FOR_HELP );
2260 $msgs = [];
2261 foreach ( $params as $param => $settings ) {
2262 if ( !is_array( $settings ) ) {
2263 $settings = [];
2264 }
2265
2266 $d = isset( $desc[$param] ) ? $desc[$param] : '';
2267 if ( is_array( $d ) ) {
2268 // Special handling for prop parameters
2269 $d = array_map( function ( $line ) {
2270 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2271 $line = "\n;{$m[1]}:{$m[2]}";
2272 }
2273 return $line;
2274 }, $d );
2275 $d = implode( ' ', $d );
2276 }
2277
2278 if ( isset( $settings[self::PARAM_HELP_MSG] ) ) {
2279 $msg = $settings[self::PARAM_HELP_MSG];
2280 } else {
2281 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2282 if ( !$msg->exists() ) {
2283 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2284 }
2285 }
2286 $msg = self::makeMessage( $msg, $this->getContext(),
2287 [ $prefix, $param, $name, $path ] );
2288 if ( !$msg ) {
2289 self::dieDebug( __METHOD__,
2290 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2291 }
2292 $msgs[$param] = [ $msg ];
2293
2294 if ( isset( $settings[self::PARAM_TYPE] ) &&
2295 $settings[self::PARAM_TYPE] === 'submodule'
2296 ) {
2297 if ( isset( $settings[self::PARAM_SUBMODULE_MAP] ) ) {
2298 $map = $settings[self::PARAM_SUBMODULE_MAP];
2299 } else {
2300 $prefix = $this->isMain() ? '' : ( $this->getModulePath() . '+' );
2301 $map = [];
2302 foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
2303 $map[$submoduleName] = $prefix . $submoduleName;
2304 }
2305 }
2306 ksort( $map );
2307 $submodules = [];
2308 $deprecatedSubmodules = [];
2309 foreach ( $map as $v => $m ) {
2310 $arr = &$submodules;
2311 $isDeprecated = false;
2312 $summary = null;
2313 try {
2314 $submod = $this->getModuleFromPath( $m );
2315 if ( $submod ) {
2316 $summary = $submod->getFinalSummary();
2317 $isDeprecated = $submod->isDeprecated();
2318 if ( $isDeprecated ) {
2319 $arr = &$deprecatedSubmodules;
2320 }
2321 }
2322 } catch ( ApiUsageException $ex ) {
2323 // Ignore
2324 }
2325 if ( $summary ) {
2326 $key = $summary->getKey();
2327 $params = $summary->getParams();
2328 } else {
2329 $key = 'api-help-undocumented-module';
2330 $params = [ $m ];
2331 }
2332 $m = new ApiHelpParamValueMessage( "[[Special:ApiHelp/$m|$v]]", $key, $params, $isDeprecated );
2333 $arr[] = $m->setContext( $this->getContext() );
2334 }
2335 $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
2336 } elseif ( isset( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
2337 if ( !is_array( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
2338 self::dieDebug( __METHOD__,
2339 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2340 }
2341 if ( !is_array( $settings[self::PARAM_TYPE] ) ) {
2342 self::dieDebug( __METHOD__,
2343 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2344 'ApiBase::PARAM_TYPE is an array' );
2345 }
2346
2347 $valueMsgs = $settings[self::PARAM_HELP_MSG_PER_VALUE];
2348 $deprecatedValues = isset( $settings[self::PARAM_DEPRECATED_VALUES] )
2349 ? $settings[self::PARAM_DEPRECATED_VALUES]
2350 : [];
2351
2352 foreach ( $settings[self::PARAM_TYPE] as $value ) {
2353 if ( isset( $valueMsgs[$value] ) ) {
2354 $msg = $valueMsgs[$value];
2355 } else {
2356 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2357 }
2358 $m = self::makeMessage( $msg, $this->getContext(),
2359 [ $prefix, $param, $name, $path, $value ] );
2360 if ( $m ) {
2361 $m = new ApiHelpParamValueMessage(
2362 $value,
2363 [ $m->getKey(), 'api-help-param-no-description' ],
2364 $m->getParams(),
2365 isset( $deprecatedValues[$value] )
2366 );
2367 $msgs[$param][] = $m->setContext( $this->getContext() );
2368 } else {
2369 self::dieDebug( __METHOD__,
2370 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2371 }
2372 }
2373 }
2374
2375 if ( isset( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
2376 if ( !is_array( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
2377 self::dieDebug( __METHOD__,
2378 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2379 }
2380 foreach ( $settings[self::PARAM_HELP_MSG_APPEND] as $m ) {
2381 $m = self::makeMessage( $m, $this->getContext(),
2382 [ $prefix, $param, $name, $path ] );
2383 if ( $m ) {
2384 $msgs[$param][] = $m;
2385 } else {
2386 self::dieDebug( __METHOD__,
2387 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2388 }
2389 }
2390 }
2391 }
2392
2393 Hooks::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2394
2395 return $msgs;
2396 }
2397
2398 /**
2399 * Generates the list of flags for the help screen and for action=paraminfo
2400 *
2401 * Corresponding messages: api-help-flag-deprecated,
2402 * api-help-flag-internal, api-help-flag-readrights,
2403 * api-help-flag-writerights, api-help-flag-mustbeposted
2404 *
2405 * @return string[]
2406 */
2407 protected function getHelpFlags() {
2408 $flags = [];
2409
2410 if ( $this->isDeprecated() ) {
2411 $flags[] = 'deprecated';
2412 }
2413 if ( $this->isInternal() ) {
2414 $flags[] = 'internal';
2415 }
2416 if ( $this->isReadMode() ) {
2417 $flags[] = 'readrights';
2418 }
2419 if ( $this->isWriteMode() ) {
2420 $flags[] = 'writerights';
2421 }
2422 if ( $this->mustBePosted() ) {
2423 $flags[] = 'mustbeposted';
2424 }
2425
2426 return $flags;
2427 }
2428
2429 /**
2430 * Returns information about the source of this module, if known
2431 *
2432 * Returned array is an array with the following keys:
2433 * - path: Install path
2434 * - name: Extension name, or "MediaWiki" for core
2435 * - namemsg: (optional) i18n message key for a display name
2436 * - license-name: (optional) Name of license
2437 *
2438 * @return array|null
2439 */
2440 protected function getModuleSourceInfo() {
2441 global $IP;
2442
2443 if ( $this->mModuleSource !== false ) {
2444 return $this->mModuleSource;
2445 }
2446
2447 // First, try to find where the module comes from...
2448 $rClass = new ReflectionClass( $this );
2449 $path = $rClass->getFileName();
2450 if ( !$path ) {
2451 // No path known?
2452 $this->mModuleSource = null;
2453 return null;
2454 }
2455 $path = realpath( $path ) ?: $path;
2456
2457 // Build map of extension directories to extension info
2458 if ( self::$extensionInfo === null ) {
2459 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2460 self::$extensionInfo = [
2461 realpath( __DIR__ ) ?: __DIR__ => [
2462 'path' => $IP,
2463 'name' => 'MediaWiki',
2464 'license-name' => 'GPL-2.0+',
2465 ],
2466 realpath( "$IP/extensions" ) ?: "$IP/extensions" => null,
2467 realpath( $extDir ) ?: $extDir => null,
2468 ];
2469 $keep = [
2470 'path' => null,
2471 'name' => null,
2472 'namemsg' => null,
2473 'license-name' => null,
2474 ];
2475 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2476 foreach ( $group as $ext ) {
2477 if ( !isset( $ext['path'] ) || !isset( $ext['name'] ) ) {
2478 // This shouldn't happen, but does anyway.
2479 continue;
2480 }
2481
2482 $extpath = $ext['path'];
2483 if ( !is_dir( $extpath ) ) {
2484 $extpath = dirname( $extpath );
2485 }
2486 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2487 array_intersect_key( $ext, $keep );
2488 }
2489 }
2490 foreach ( ExtensionRegistry::getInstance()->getAllThings() as $ext ) {
2491 $extpath = $ext['path'];
2492 if ( !is_dir( $extpath ) ) {
2493 $extpath = dirname( $extpath );
2494 }
2495 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2496 array_intersect_key( $ext, $keep );
2497 }
2498 }
2499
2500 // Now traverse parent directories until we find a match or run out of
2501 // parents.
2502 do {
2503 if ( array_key_exists( $path, self::$extensionInfo ) ) {
2504 // Found it!
2505 $this->mModuleSource = self::$extensionInfo[$path];
2506 return $this->mModuleSource;
2507 }
2508
2509 $oldpath = $path;
2510 $path = dirname( $path );
2511 } while ( $path !== $oldpath );
2512
2513 // No idea what extension this might be.
2514 $this->mModuleSource = null;
2515 return null;
2516 }
2517
2518 /**
2519 * Called from ApiHelp before the pieces are joined together and returned.
2520 *
2521 * This exists mainly for ApiMain to add the Permissions and Credits
2522 * sections. Other modules probably don't need it.
2523 *
2524 * @param string[] &$help Array of help data
2525 * @param array $options Options passed to ApiHelp::getHelp
2526 * @param array &$tocData If a TOC is being generated, this array has keys
2527 * as anchors in the page and values as for Linker::generateTOC().
2528 */
2529 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2530 }
2531
2532 /**@}*/
2533
2534 /************************************************************************//**
2535 * @name Deprecated
2536 * @{
2537 */
2538
2539 /**
2540 * Returns the description string for this module
2541 *
2542 * Ignored if an i18n message exists for
2543 * "apihelp-{$this->getModulePath()}-description".
2544 *
2545 * @deprecated since 1.25
2546 * @return Message|string|array|false
2547 */
2548 protected function getDescription() {
2549 return false;
2550 }
2551
2552 /**
2553 * Returns an array of parameter descriptions.
2554 *
2555 * For each parameter, ignored if an i18n message exists for the parameter.
2556 * By default that message is
2557 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2558 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2559 * self::getFinalParams().
2560 *
2561 * @deprecated since 1.25
2562 * @return array|bool False on no parameter descriptions
2563 */
2564 protected function getParamDescription() {
2565 return [];
2566 }
2567
2568 /**
2569 * Returns usage examples for this module.
2570 *
2571 * Return value as an array is either:
2572 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2573 * values
2574 * - sequential numeric keys with even-numbered keys being display-text
2575 * and odd-numbered keys being partial urls
2576 * - partial URLs as keys with display-text (string or array-to-be-joined)
2577 * as values
2578 * Return value as a string is the same as an array with a numeric key and
2579 * that value, and boolean false means "no examples".
2580 *
2581 * @deprecated since 1.25, use getExamplesMessages() instead
2582 * @return bool|string|array
2583 */
2584 protected function getExamples() {
2585 return false;
2586 }
2587
2588 /**
2589 * @deprecated since 1.25, always returns empty string
2590 * @param IDatabase|bool $db
2591 * @return string
2592 */
2593 public function getModuleProfileName( $db = false ) {
2594 wfDeprecated( __METHOD__, '1.25' );
2595 return '';
2596 }
2597
2598 /**
2599 * @deprecated since 1.25
2600 */
2601 public function profileIn() {
2602 // No wfDeprecated() yet because extensions call this and might need to
2603 // keep doing so for BC.
2604 }
2605
2606 /**
2607 * @deprecated since 1.25
2608 */
2609 public function profileOut() {
2610 // No wfDeprecated() yet because extensions call this and might need to
2611 // keep doing so for BC.
2612 }
2613
2614 /**
2615 * @deprecated since 1.25
2616 */
2617 public function safeProfileOut() {
2618 wfDeprecated( __METHOD__, '1.25' );
2619 }
2620
2621 /**
2622 * @deprecated since 1.25, always returns 0
2623 * @return float
2624 */
2625 public function getProfileTime() {
2626 wfDeprecated( __METHOD__, '1.25' );
2627 return 0;
2628 }
2629
2630 /**
2631 * @deprecated since 1.25
2632 */
2633 public function profileDBIn() {
2634 wfDeprecated( __METHOD__, '1.25' );
2635 }
2636
2637 /**
2638 * @deprecated since 1.25
2639 */
2640 public function profileDBOut() {
2641 wfDeprecated( __METHOD__, '1.25' );
2642 }
2643
2644 /**
2645 * @deprecated since 1.25, always returns 0
2646 * @return float
2647 */
2648 public function getProfileDBTime() {
2649 wfDeprecated( __METHOD__, '1.25' );
2650 return 0;
2651 }
2652
2653 /**
2654 * Call wfTransactionalTimeLimit() if this request was POSTed
2655 * @since 1.26
2656 */
2657 protected function useTransactionalTimeLimit() {
2658 if ( $this->getRequest()->wasPosted() ) {
2659 wfTransactionalTimeLimit();
2660 }
2661 }
2662
2663 /**
2664 * @deprecated since 1.29, use ApiBase::addWarning() instead
2665 * @param string $warning Warning message
2666 */
2667 public function setWarning( $warning ) {
2668 wfDeprecated( __METHOD__, '1.29' );
2669 $msg = new ApiRawMessage( $warning, 'warning' );
2670 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg );
2671 }
2672
2673 /**
2674 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2675 * error handler and die with an error message.
2676 *
2677 * @deprecated since 1.29, use self::dieWithError() instead
2678 * @param string $description One-line human-readable description of the
2679 * error condition, e.g., "The API requires a valid action parameter"
2680 * @param string $errorCode Brief, arbitrary, stable string to allow easy
2681 * automated identification of the error, e.g., 'unknown_action'
2682 * @param int $httpRespCode HTTP response code
2683 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
2684 * @throws ApiUsageException always
2685 */
2686 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
2687 wfDeprecated( __METHOD__, '1.29' );
2688 $this->dieWithError(
2689 new RawMessage( '$1', [ $description ] ),
2690 $errorCode,
2691 $extradata,
2692 $httpRespCode
2693 );
2694 }
2695
2696 /**
2697 * Get error (as code, string) from a Status object.
2698 *
2699 * @since 1.23
2700 * @deprecated since 1.29, use ApiErrorFormatter::arrayFromStatus instead
2701 * @param Status $status
2702 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
2703 * @return array Array of code and error string
2704 * @throws MWException
2705 */
2706 public function getErrorFromStatus( $status, &$extraData = null ) {
2707 wfDeprecated( __METHOD__, '1.29' );
2708 if ( $status->isGood() ) {
2709 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2710 }
2711
2712 $errors = $status->getErrorsByType( 'error' );
2713 if ( !$errors ) {
2714 // No errors? Assume the warnings should be treated as errors
2715 $errors = $status->getErrorsByType( 'warning' );
2716 }
2717 if ( !$errors ) {
2718 // Still no errors? Punt
2719 $errors = [ [ 'message' => 'unknownerror-nocode', 'params' => [] ] ];
2720 }
2721
2722 if ( $errors[0]['message'] instanceof MessageSpecifier ) {
2723 $msg = $errors[0]['message'];
2724 } else {
2725 $msg = new Message( $errors[0]['message'], $errors[0]['params'] );
2726 }
2727 if ( !$msg instanceof IApiMessage ) {
2728 $key = $msg->getKey();
2729 $params = $msg->getParams();
2730 array_unshift( $params, isset( self::$messageMap[$key] ) ? self::$messageMap[$key] : $key );
2731 $msg = ApiMessage::create( $params );
2732 }
2733
2734 return [
2735 $msg->getApiCode(),
2736 ApiErrorFormatter::stripMarkup( $msg->inLanguage( 'en' )->useDatabase( false )->text() )
2737 ];
2738 }
2739
2740 /**
2741 * @deprecated since 1.29. Prior to 1.29, this was a public mapping from
2742 * arbitrary strings (often message keys used elsewhere in MediaWiki) to
2743 * API codes and message texts, and a few interfaces required poking
2744 * something in here. Now we're repurposing it to map those same strings
2745 * to i18n messages, and declaring that any interface that requires poking
2746 * at this is broken and needs replacing ASAP.
2747 */
2748 private static $messageMap = [
2749 'unknownerror' => 'apierror-unknownerror',
2750 'unknownerror-nocode' => 'apierror-unknownerror-nocode',
2751 'ns-specialprotected' => 'ns-specialprotected',
2752 'protectedinterface' => 'protectedinterface',
2753 'namespaceprotected' => 'namespaceprotected',
2754 'customcssprotected' => 'customcssprotected',
2755 'customjsprotected' => 'customjsprotected',
2756 'cascadeprotected' => 'cascadeprotected',
2757 'protectedpagetext' => 'protectedpagetext',
2758 'protect-cantedit' => 'protect-cantedit',
2759 'deleteprotected' => 'deleteprotected',
2760 'badaccess-group0' => 'badaccess-group0',
2761 'badaccess-groups' => 'badaccess-groups',
2762 'titleprotected' => 'titleprotected',
2763 'nocreate-loggedin' => 'nocreate-loggedin',
2764 'nocreatetext' => 'nocreatetext',
2765 'movenologintext' => 'movenologintext',
2766 'movenotallowed' => 'movenotallowed',
2767 'confirmedittext' => 'confirmedittext',
2768 'blockedtext' => 'apierror-blocked',
2769 'autoblockedtext' => 'apierror-autoblocked',
2770 'systemblockedtext' => 'apierror-systemblocked',
2771 'actionthrottledtext' => 'apierror-ratelimited',
2772 'alreadyrolled' => 'alreadyrolled',
2773 'cantrollback' => 'cantrollback',
2774 'readonlytext' => 'readonlytext',
2775 'sessionfailure' => 'sessionfailure',
2776 'cannotdelete' => 'cannotdelete',
2777 'notanarticle' => 'apierror-missingtitle',
2778 'selfmove' => 'selfmove',
2779 'immobile_namespace' => 'apierror-immobilenamespace',
2780 'articleexists' => 'articleexists',
2781 'hookaborted' => 'hookaborted',
2782 'cantmove-titleprotected' => 'cantmove-titleprotected',
2783 'imagenocrossnamespace' => 'imagenocrossnamespace',
2784 'imagetypemismatch' => 'imagetypemismatch',
2785 'ip_range_invalid' => 'ip_range_invalid',
2786 'range_block_disabled' => 'range_block_disabled',
2787 'nosuchusershort' => 'nosuchusershort',
2788 'badipaddress' => 'badipaddress',
2789 'ipb_expiry_invalid' => 'ipb_expiry_invalid',
2790 'ipb_already_blocked' => 'ipb_already_blocked',
2791 'ipb_blocked_as_range' => 'ipb_blocked_as_range',
2792 'ipb_cant_unblock' => 'ipb_cant_unblock',
2793 'mailnologin' => 'apierror-cantsend',
2794 'ipbblocked' => 'ipbblocked',
2795 'ipbnounblockself' => 'ipbnounblockself',
2796 'usermaildisabled' => 'usermaildisabled',
2797 'blockedemailuser' => 'apierror-blockedfrommail',
2798 'notarget' => 'apierror-notarget',
2799 'noemail' => 'noemail',
2800 'rcpatroldisabled' => 'rcpatroldisabled',
2801 'markedaspatrollederror-noautopatrol' => 'markedaspatrollederror-noautopatrol',
2802 'delete-toobig' => 'delete-toobig',
2803 'movenotallowedfile' => 'movenotallowedfile',
2804 'userrights-no-interwiki' => 'userrights-no-interwiki',
2805 'userrights-nodatabase' => 'userrights-nodatabase',
2806 'nouserspecified' => 'nouserspecified',
2807 'noname' => 'noname',
2808 'summaryrequired' => 'apierror-summaryrequired',
2809 'import-rootpage-invalid' => 'import-rootpage-invalid',
2810 'import-rootpage-nosubpage' => 'import-rootpage-nosubpage',
2811 'readrequired' => 'apierror-readapidenied',
2812 'writedisabled' => 'apierror-noapiwrite',
2813 'writerequired' => 'apierror-writeapidenied',
2814 'missingparam' => 'apierror-missingparam',
2815 'invalidtitle' => 'apierror-invalidtitle',
2816 'nosuchpageid' => 'apierror-nosuchpageid',
2817 'nosuchrevid' => 'apierror-nosuchrevid',
2818 'nosuchuser' => 'nosuchusershort',
2819 'invaliduser' => 'apierror-invaliduser',
2820 'invalidexpiry' => 'apierror-invalidexpiry',
2821 'pastexpiry' => 'apierror-pastexpiry',
2822 'create-titleexists' => 'apierror-create-titleexists',
2823 'missingtitle-createonly' => 'apierror-missingtitle-createonly',
2824 'cantblock' => 'apierror-cantblock',
2825 'canthide' => 'apierror-canthide',
2826 'cantblock-email' => 'apierror-cantblock-email',
2827 'cantunblock' => 'apierror-permissiondenied-generic',
2828 'cannotundelete' => 'cannotundelete',
2829 'permdenied-undelete' => 'apierror-permissiondenied-generic',
2830 'createonly-exists' => 'apierror-articleexists',
2831 'nocreate-missing' => 'apierror-missingtitle',
2832 'cantchangecontentmodel' => 'apierror-cantchangecontentmodel',
2833 'nosuchrcid' => 'apierror-nosuchrcid',
2834 'nosuchlogid' => 'apierror-nosuchlogid',
2835 'protect-invalidaction' => 'apierror-protect-invalidaction',
2836 'protect-invalidlevel' => 'apierror-protect-invalidlevel',
2837 'toofewexpiries' => 'apierror-toofewexpiries',
2838 'cantimport' => 'apierror-cantimport',
2839 'cantimport-upload' => 'apierror-cantimport-upload',
2840 'importnofile' => 'importnofile',
2841 'importuploaderrorsize' => 'importuploaderrorsize',
2842 'importuploaderrorpartial' => 'importuploaderrorpartial',
2843 'importuploaderrortemp' => 'importuploaderrortemp',
2844 'importcantopen' => 'importcantopen',
2845 'import-noarticle' => 'import-noarticle',
2846 'importbadinterwiki' => 'importbadinterwiki',
2847 'import-unknownerror' => 'apierror-import-unknownerror',
2848 'cantoverwrite-sharedfile' => 'apierror-cantoverwrite-sharedfile',
2849 'sharedfile-exists' => 'apierror-fileexists-sharedrepo-perm',
2850 'mustbeposted' => 'apierror-mustbeposted',
2851 'show' => 'apierror-show',
2852 'specialpage-cantexecute' => 'apierror-specialpage-cantexecute',
2853 'invalidoldimage' => 'apierror-invalidoldimage',
2854 'nodeleteablefile' => 'apierror-nodeleteablefile',
2855 'fileexists-forbidden' => 'fileexists-forbidden',
2856 'fileexists-shared-forbidden' => 'fileexists-shared-forbidden',
2857 'filerevert-badversion' => 'filerevert-badversion',
2858 'noimageredirect-anon' => 'apierror-noimageredirect-anon',
2859 'noimageredirect-logged' => 'apierror-noimageredirect',
2860 'spamdetected' => 'apierror-spamdetected',
2861 'contenttoobig' => 'apierror-contenttoobig',
2862 'noedit-anon' => 'apierror-noedit-anon',
2863 'noedit' => 'apierror-noedit',
2864 'wasdeleted' => 'apierror-pagedeleted',
2865 'blankpage' => 'apierror-emptypage',
2866 'editconflict' => 'editconflict',
2867 'hashcheckfailed' => 'apierror-badmd5',
2868 'missingtext' => 'apierror-notext',
2869 'emptynewsection' => 'apierror-emptynewsection',
2870 'revwrongpage' => 'apierror-revwrongpage',
2871 'undo-failure' => 'undo-failure',
2872 'content-not-allowed-here' => 'content-not-allowed-here',
2873 'edit-hook-aborted' => 'edit-hook-aborted',
2874 'edit-gone-missing' => 'edit-gone-missing',
2875 'edit-conflict' => 'edit-conflict',
2876 'edit-already-exists' => 'edit-already-exists',
2877 'invalid-file-key' => 'apierror-invalid-file-key',
2878 'nouploadmodule' => 'apierror-nouploadmodule',
2879 'uploaddisabled' => 'uploaddisabled',
2880 'copyuploaddisabled' => 'copyuploaddisabled',
2881 'copyuploadbaddomain' => 'apierror-copyuploadbaddomain',
2882 'copyuploadbadurl' => 'apierror-copyuploadbadurl',
2883 'filename-tooshort' => 'filename-tooshort',
2884 'filename-toolong' => 'filename-toolong',
2885 'illegal-filename' => 'illegal-filename',
2886 'filetype-missing' => 'filetype-missing',
2887 'mustbeloggedin' => 'apierror-mustbeloggedin',
2888 ];
2889
2890 /**
2891 * @deprecated do not use
2892 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2893 * @return ApiMessage
2894 */
2895 private function parseMsgInternal( $error ) {
2896 $msg = Message::newFromSpecifier( $error );
2897 if ( !$msg instanceof IApiMessage ) {
2898 $key = $msg->getKey();
2899 if ( isset( self::$messageMap[$key] ) ) {
2900 $params = $msg->getParams();
2901 array_unshift( $params, self::$messageMap[$key] );
2902 } else {
2903 $params = [ 'apierror-unknownerror', wfEscapeWikiText( $key ) ];
2904 }
2905 $msg = ApiMessage::create( $params );
2906 }
2907 return $msg;
2908 }
2909
2910 /**
2911 * Return the error message related to a certain array
2912 * @deprecated since 1.29
2913 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2914 * @return array [ 'code' => code, 'info' => info ]
2915 */
2916 public function parseMsg( $error ) {
2917 wfDeprecated( __METHOD__, '1.29' );
2918 // Check whether someone passed the whole array, instead of one element as
2919 // documented. This breaks if it's actually an array of fallback keys, but
2920 // that's long-standing misbehavior introduced in r87627 to incorrectly
2921 // fix T30797.
2922 if ( is_array( $error ) ) {
2923 $first = reset( $error );
2924 if ( is_array( $first ) ) {
2925 wfDebug( __METHOD__ . ' was passed an array of arrays. ' . wfGetAllCallers( 5 ) );
2926 $error = $first;
2927 }
2928 }
2929
2930 $msg = $this->parseMsgInternal( $error );
2931 return [
2932 'code' => $msg->getApiCode(),
2933 'info' => ApiErrorFormatter::stripMarkup(
2934 $msg->inLanguage( 'en' )->useDatabase( false )->text()
2935 ),
2936 'data' => $msg->getApiData()
2937 ];
2938 }
2939
2940 /**
2941 * Output the error message related to a certain array
2942 * @deprecated since 1.29, use ApiBase::dieWithError() instead
2943 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2944 * @throws ApiUsageException always
2945 */
2946 public function dieUsageMsg( $error ) {
2947 wfDeprecated( __METHOD__, '1.29' );
2948 $this->dieWithError( $this->parseMsgInternal( $error ) );
2949 }
2950
2951 /**
2952 * Will only set a warning instead of failing if the global $wgDebugAPI
2953 * is set to true. Otherwise behaves exactly as dieUsageMsg().
2954 * @deprecated since 1.29, use ApiBase::dieWithErrorOrDebug() instead
2955 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2956 * @throws ApiUsageException
2957 * @since 1.21
2958 */
2959 public function dieUsageMsgOrDebug( $error ) {
2960 wfDeprecated( __METHOD__, '1.29' );
2961 $this->dieWithErrorOrDebug( $this->parseMsgInternal( $error ) );
2962 }
2963
2964 /**
2965 * Return the description message.
2966 *
2967 * This is additional text to display on the help page after the summary.
2968 *
2969 * @deprecated since 1.30
2970 * @return string|array|Message
2971 */
2972 protected function getDescriptionMessage() {
2973 return [ [
2974 "apihelp-{$this->getModulePath()}-description",
2975 "apihelp-{$this->getModulePath()}-summary",
2976 ] ];
2977 }
2978
2979 /**@}*/
2980 }
2981
2982 /**
2983 * For really cool vim folding this needs to be at the end:
2984 * vim: foldmarker=@{,@} foldmethod=marker
2985 */