Merge "Improve test coverage for ApiBase.php"
[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( ApiContinuationManager $manager = null ) {
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', implode( ', ', $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 // Namespace parameters allow ALL_DEFAULT_STRING to be used to
1133 // specify all namespaces irrespective of PARAM_ALL.
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 = implode( "\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 $values = array_map( function ( $v ) {
1440 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1441 }, $allowedValues );
1442 $this->dieWithError( [
1443 'apierror-multival-only-one-of',
1444 $valueName,
1445 Message::listParam( $values ),
1446 count( $values ),
1447 ], "multival_$valueName" );
1448 }
1449
1450 if ( is_array( $allowedValues ) ) {
1451 // Check for unknown values
1452 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1453 if ( count( $unknown ) ) {
1454 if ( $allowMultiple ) {
1455 $this->addWarning( [
1456 'apiwarn-unrecognizedvalues',
1457 $valueName,
1458 Message::listParam( $unknown, 'comma' ),
1459 count( $unknown ),
1460 ] );
1461 } else {
1462 $this->dieWithError(
1463 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1464 "unknown_$valueName"
1465 );
1466 }
1467 }
1468 // Now throw them out
1469 $valuesList = array_intersect( $valuesList, $allowedValues );
1470 }
1471
1472 return $allowMultiple ? $valuesList : $valuesList[0];
1473 }
1474
1475 /**
1476 * Validate the value against the minimum and user/bot maximum limits.
1477 * Prints usage info on failure.
1478 * @param string $paramName Parameter name
1479 * @param int &$value Parameter value
1480 * @param int|null $min Minimum value
1481 * @param int|null $max Maximum value for users
1482 * @param int $botMax Maximum value for sysops/bots
1483 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1484 */
1485 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1486 $enforceLimits = false
1487 ) {
1488 if ( !is_null( $min ) && $value < $min ) {
1489 $msg = ApiMessage::create(
1490 [ 'apierror-integeroutofrange-belowminimum',
1491 $this->encodeParamName( $paramName ), $min, $value ],
1492 'integeroutofrange',
1493 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
1494 );
1495 $this->warnOrDie( $msg, $enforceLimits );
1496 $value = $min;
1497 }
1498
1499 // Minimum is always validated, whereas maximum is checked only if not
1500 // running in internal call mode
1501 if ( $this->getMain()->isInternalMode() ) {
1502 return;
1503 }
1504
1505 // Optimization: do not check user's bot status unless really needed -- skips db query
1506 // assumes $botMax >= $max
1507 if ( !is_null( $max ) && $value > $max ) {
1508 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1509 if ( $value > $botMax ) {
1510 $msg = ApiMessage::create(
1511 [ 'apierror-integeroutofrange-abovebotmax',
1512 $this->encodeParamName( $paramName ), $botMax, $value ],
1513 'integeroutofrange',
1514 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
1515 );
1516 $this->warnOrDie( $msg, $enforceLimits );
1517 $value = $botMax;
1518 }
1519 } else {
1520 $msg = ApiMessage::create(
1521 [ 'apierror-integeroutofrange-abovemax',
1522 $this->encodeParamName( $paramName ), $max, $value ],
1523 'integeroutofrange',
1524 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
1525 );
1526 $this->warnOrDie( $msg, $enforceLimits );
1527 $value = $max;
1528 }
1529 }
1530 }
1531
1532 /**
1533 * Validate and normalize parameters of type 'timestamp'
1534 * @param string $value Parameter value
1535 * @param string $encParamName Parameter name
1536 * @return string Validated and normalized parameter
1537 */
1538 protected function validateTimestamp( $value, $encParamName ) {
1539 // Confusing synonyms for the current time accepted by wfTimestamp()
1540 // (wfTimestamp() also accepts various non-strings and the string of 14
1541 // ASCII NUL bytes, but those can't get here)
1542 if ( !$value ) {
1543 $this->addDeprecation(
1544 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1545 'unclear-"now"-timestamp'
1546 );
1547 return wfTimestamp( TS_MW );
1548 }
1549
1550 // Explicit synonym for the current time
1551 if ( $value === 'now' ) {
1552 return wfTimestamp( TS_MW );
1553 }
1554
1555 $timestamp = wfTimestamp( TS_MW, $value );
1556 if ( $timestamp === false ) {
1557 $this->dieWithError(
1558 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1559 "badtimestamp_{$encParamName}"
1560 );
1561 }
1562
1563 return $timestamp;
1564 }
1565
1566 /**
1567 * Validate the supplied token.
1568 *
1569 * @since 1.24
1570 * @param string $token Supplied token
1571 * @param array $params All supplied parameters for the module
1572 * @return bool
1573 * @throws MWException
1574 */
1575 final public function validateToken( $token, array $params ) {
1576 $tokenType = $this->needsToken();
1577 $salts = ApiQueryTokens::getTokenTypeSalts();
1578 if ( !isset( $salts[$tokenType] ) ) {
1579 throw new MWException(
1580 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1581 'without registering it'
1582 );
1583 }
1584
1585 $tokenObj = ApiQueryTokens::getToken(
1586 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1587 );
1588 if ( $tokenObj->match( $token ) ) {
1589 return true;
1590 }
1591
1592 $webUiSalt = $this->getWebUITokenSalt( $params );
1593 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1594 $token,
1595 $webUiSalt,
1596 $this->getRequest()
1597 ) ) {
1598 return true;
1599 }
1600
1601 return false;
1602 }
1603
1604 /**
1605 * Validate and normalize parameters of type 'user'
1606 * @param string $value Parameter value
1607 * @param string $encParamName Parameter name
1608 * @return string Validated and normalized parameter
1609 */
1610 private function validateUser( $value, $encParamName ) {
1611 if ( ExternalUserNames::isExternal( $value ) && User::newFromName( $value, false ) ) {
1612 return $value;
1613 }
1614
1615 $titleObj = Title::makeTitleSafe( NS_USER, $value );
1616
1617 if ( $titleObj ) {
1618 $value = $titleObj->getText();
1619 }
1620
1621 if (
1622 !User::isValidUserName( $value ) &&
1623 // We allow ranges as well, for blocks.
1624 !IP::isIPAddress( $value ) &&
1625 // See comment for User::isIP. We don't just call that function
1626 // here because it also returns true for things like
1627 // 300.300.300.300 that are neither valid usernames nor valid IP
1628 // addresses.
1629 !preg_match(
1630 '/^' . RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.xxx$/',
1631 $value
1632 )
1633 ) {
1634 $this->dieWithError(
1635 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1636 "baduser_{$encParamName}"
1637 );
1638 }
1639
1640 return $value;
1641 }
1642
1643 /**@}*/
1644
1645 /************************************************************************//**
1646 * @name Utility methods
1647 * @{
1648 */
1649
1650 /**
1651 * Set a watch (or unwatch) based the based on a watchlist parameter.
1652 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1653 * @param Title $titleObj The article's title to change
1654 * @param string $userOption The user option to consider when $watch=preferences
1655 */
1656 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1657 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1658 if ( $value === null ) {
1659 return;
1660 }
1661
1662 WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1663 }
1664
1665 /**
1666 * Truncate an array to a certain length.
1667 * @param array &$arr Array to truncate
1668 * @param int $limit Maximum length
1669 * @return bool True if the array was truncated, false otherwise
1670 */
1671 public static function truncateArray( &$arr, $limit ) {
1672 $modified = false;
1673 while ( count( $arr ) > $limit ) {
1674 array_pop( $arr );
1675 $modified = true;
1676 }
1677
1678 return $modified;
1679 }
1680
1681 /**
1682 * Gets the user for whom to get the watchlist
1683 *
1684 * @param array $params
1685 * @return User
1686 */
1687 public function getWatchlistUser( $params ) {
1688 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1689 $user = User::newFromName( $params['owner'], false );
1690 if ( !( $user && $user->getId() ) ) {
1691 $this->dieWithError(
1692 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1693 );
1694 }
1695 $token = $user->getOption( 'watchlisttoken' );
1696 if ( $token == '' || !hash_equals( $token, $params['token'] ) ) {
1697 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1698 }
1699 } else {
1700 if ( !$this->getUser()->isLoggedIn() ) {
1701 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1702 }
1703 $this->checkUserRightsAny( 'viewmywatchlist' );
1704 $user = $this->getUser();
1705 }
1706
1707 return $user;
1708 }
1709
1710 /**
1711 * A subset of wfEscapeWikiText for BC texts
1712 *
1713 * @since 1.25
1714 * @param string|array $v
1715 * @return string|array
1716 */
1717 private static function escapeWikiText( $v ) {
1718 if ( is_array( $v ) ) {
1719 return array_map( 'self::escapeWikiText', $v );
1720 } else {
1721 return strtr( $v, [
1722 '__' => '_&#95;', '{' => '&#123;', '}' => '&#125;',
1723 '[[Category:' => '[[:Category:',
1724 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1725 ] );
1726 }
1727 }
1728
1729 /**
1730 * Create a Message from a string or array
1731 *
1732 * A string is used as a message key. An array has the message key as the
1733 * first value and message parameters as subsequent values.
1734 *
1735 * @since 1.25
1736 * @param string|array|Message $msg
1737 * @param IContextSource $context
1738 * @param array $params
1739 * @return Message|null
1740 */
1741 public static function makeMessage( $msg, IContextSource $context, array $params = null ) {
1742 if ( is_string( $msg ) ) {
1743 $msg = wfMessage( $msg );
1744 } elseif ( is_array( $msg ) ) {
1745 $msg = call_user_func_array( 'wfMessage', $msg );
1746 }
1747 if ( !$msg instanceof Message ) {
1748 return null;
1749 }
1750
1751 $msg->setContext( $context );
1752 if ( $params ) {
1753 $msg->params( $params );
1754 }
1755
1756 return $msg;
1757 }
1758
1759 /**
1760 * Turn an array of message keys or key+param arrays into a Status
1761 * @since 1.29
1762 * @param array $errors
1763 * @param User|null $user
1764 * @return Status
1765 */
1766 public function errorArrayToStatus( array $errors, User $user = null ) {
1767 if ( $user === null ) {
1768 $user = $this->getUser();
1769 }
1770
1771 $status = Status::newGood();
1772 foreach ( $errors as $error ) {
1773 if ( is_array( $error ) && $error[0] === 'blockedtext' && $user->getBlock() ) {
1774 $status->fatal( ApiMessage::create(
1775 'apierror-blocked',
1776 'blocked',
1777 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
1778 ) );
1779 } elseif ( is_array( $error ) && $error[0] === 'autoblockedtext' && $user->getBlock() ) {
1780 $status->fatal( ApiMessage::create(
1781 'apierror-autoblocked',
1782 'autoblocked',
1783 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
1784 ) );
1785 } elseif ( is_array( $error ) && $error[0] === 'systemblockedtext' && $user->getBlock() ) {
1786 $status->fatal( ApiMessage::create(
1787 'apierror-systemblocked',
1788 'blocked',
1789 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
1790 ) );
1791 } else {
1792 call_user_func_array( [ $status, 'fatal' ], (array)$error );
1793 }
1794 }
1795 return $status;
1796 }
1797
1798 /**@}*/
1799
1800 /************************************************************************//**
1801 * @name Warning and error reporting
1802 * @{
1803 */
1804
1805 /**
1806 * Add a warning for this module.
1807 *
1808 * Users should monitor this section to notice any changes in API. Multiple
1809 * calls to this function will result in multiple warning messages.
1810 *
1811 * If $msg is not an ApiMessage, the message code will be derived from the
1812 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1813 *
1814 * @since 1.29
1815 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1816 * @param string|null $code See ApiErrorFormatter::addWarning()
1817 * @param array|null $data See ApiErrorFormatter::addWarning()
1818 */
1819 public function addWarning( $msg, $code = null, $data = null ) {
1820 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1821 }
1822
1823 /**
1824 * Add a deprecation warning for this module.
1825 *
1826 * A combination of $this->addWarning() and $this->logFeatureUsage()
1827 *
1828 * @since 1.29
1829 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1830 * @param string|null $feature See ApiBase::logFeatureUsage()
1831 * @param array|null $data See ApiErrorFormatter::addWarning()
1832 */
1833 public function addDeprecation( $msg, $feature, $data = [] ) {
1834 $data = (array)$data;
1835 if ( $feature !== null ) {
1836 $data['feature'] = $feature;
1837 $this->logFeatureUsage( $feature );
1838 }
1839 $this->addWarning( $msg, 'deprecation', $data );
1840
1841 // No real need to deduplicate here, ApiErrorFormatter does that for
1842 // us (assuming the hook is deterministic).
1843 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1844 Hooks::run( 'ApiDeprecationHelp', [ &$msgs ] );
1845 if ( count( $msgs ) > 1 ) {
1846 $key = '$' . implode( ' $', range( 1, count( $msgs ) ) );
1847 $msg = ( new RawMessage( $key ) )->params( $msgs );
1848 } else {
1849 $msg = reset( $msgs );
1850 }
1851 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1852 }
1853
1854 /**
1855 * Add an error for this module without aborting
1856 *
1857 * If $msg is not an ApiMessage, the message code will be derived from the
1858 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1859 *
1860 * @note If you want to abort processing, use self::dieWithError() instead.
1861 * @since 1.29
1862 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1863 * @param string|null $code See ApiErrorFormatter::addError()
1864 * @param array|null $data See ApiErrorFormatter::addError()
1865 */
1866 public function addError( $msg, $code = null, $data = null ) {
1867 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1868 }
1869
1870 /**
1871 * Add warnings and/or errors from a Status
1872 *
1873 * @note If you want to abort processing, use self::dieStatus() instead.
1874 * @since 1.29
1875 * @param StatusValue $status
1876 * @param string[] $types 'warning' and/or 'error'
1877 */
1878 public function addMessagesFromStatus( StatusValue $status, $types = [ 'warning', 'error' ] ) {
1879 $this->getErrorFormatter()->addMessagesFromStatus( $this->getModulePath(), $status, $types );
1880 }
1881
1882 /**
1883 * Abort execution with an error
1884 *
1885 * If $msg is not an ApiMessage, the message code will be derived from the
1886 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1887 *
1888 * @since 1.29
1889 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1890 * @param string|null $code See ApiErrorFormatter::addError()
1891 * @param array|null $data See ApiErrorFormatter::addError()
1892 * @param int|null $httpCode HTTP error code to use
1893 * @throws ApiUsageException always
1894 */
1895 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1896 throw ApiUsageException::newWithMessage( $this, $msg, $code, $data, $httpCode );
1897 }
1898
1899 /**
1900 * Abort execution with an error derived from an exception
1901 *
1902 * @since 1.29
1903 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
1904 * @param array $options See ApiErrorFormatter::getMessageFromException()
1905 * @throws ApiUsageException always
1906 */
1907 public function dieWithException( $exception, array $options = [] ) {
1908 $this->dieWithError(
1909 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
1910 );
1911 }
1912
1913 /**
1914 * Adds a warning to the output, else dies
1915 *
1916 * @param ApiMessage $msg Message to show as a warning, or error message if dying
1917 * @param bool $enforceLimits Whether this is an enforce (die)
1918 */
1919 private function warnOrDie( ApiMessage $msg, $enforceLimits = false ) {
1920 if ( $enforceLimits ) {
1921 $this->dieWithError( $msg );
1922 } else {
1923 $this->addWarning( $msg );
1924 }
1925 }
1926
1927 /**
1928 * Throw an ApiUsageException, which will (if uncaught) call the main module's
1929 * error handler and die with an error message including block info.
1930 *
1931 * @since 1.27
1932 * @param Block $block The block used to generate the ApiUsageException
1933 * @throws ApiUsageException always
1934 */
1935 public function dieBlocked( Block $block ) {
1936 // Die using the appropriate message depending on block type
1937 if ( $block->getType() == Block::TYPE_AUTO ) {
1938 $this->dieWithError(
1939 'apierror-autoblocked',
1940 'autoblocked',
1941 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ]
1942 );
1943 } else {
1944 $this->dieWithError(
1945 'apierror-blocked',
1946 'blocked',
1947 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ]
1948 );
1949 }
1950 }
1951
1952 /**
1953 * Throw an ApiUsageException based on the Status object.
1954 *
1955 * @since 1.22
1956 * @since 1.29 Accepts a StatusValue
1957 * @param StatusValue $status
1958 * @throws ApiUsageException always
1959 */
1960 public function dieStatus( StatusValue $status ) {
1961 if ( $status->isGood() ) {
1962 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1963 }
1964
1965 // ApiUsageException needs a fatal status, but this method has
1966 // historically accepted any non-good status. Convert it if necessary.
1967 $status->setOK( false );
1968 if ( !$status->getErrorsByType( 'error' ) ) {
1969 $newStatus = Status::newGood();
1970 foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
1971 call_user_func_array(
1972 [ $newStatus, 'fatal' ],
1973 array_merge( [ $err['message'] ], $err['params'] )
1974 );
1975 }
1976 if ( !$newStatus->getErrorsByType( 'error' ) ) {
1977 $newStatus->fatal( 'unknownerror-nocode' );
1978 }
1979 $status = $newStatus;
1980 }
1981
1982 throw new ApiUsageException( $this, $status );
1983 }
1984
1985 /**
1986 * Helper function for readonly errors
1987 *
1988 * @throws ApiUsageException always
1989 */
1990 public function dieReadOnly() {
1991 $this->dieWithError(
1992 'apierror-readonly',
1993 'readonly',
1994 [ 'readonlyreason' => wfReadOnlyReason() ]
1995 );
1996 }
1997
1998 /**
1999 * Helper function for permission-denied errors
2000 * @since 1.29
2001 * @param string|string[] $rights
2002 * @param User|null $user
2003 * @throws ApiUsageException if the user doesn't have any of the rights.
2004 * The error message is based on $rights[0].
2005 */
2006 public function checkUserRightsAny( $rights, $user = null ) {
2007 if ( !$user ) {
2008 $user = $this->getUser();
2009 }
2010 $rights = (array)$rights;
2011 if ( !call_user_func_array( [ $user, 'isAllowedAny' ], $rights ) ) {
2012 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
2013 }
2014 }
2015
2016 /**
2017 * Helper function for permission-denied errors
2018 * @since 1.29
2019 * @param Title $title
2020 * @param string|string[] $actions
2021 * @param User|null $user
2022 * @throws ApiUsageException if the user doesn't have all of the rights.
2023 */
2024 public function checkTitleUserPermissions( Title $title, $actions, $user = null ) {
2025 if ( !$user ) {
2026 $user = $this->getUser();
2027 }
2028
2029 $errors = [];
2030 foreach ( (array)$actions as $action ) {
2031 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
2032 }
2033 if ( $errors ) {
2034 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
2035 }
2036 }
2037
2038 /**
2039 * Will only set a warning instead of failing if the global $wgDebugAPI
2040 * is set to true. Otherwise behaves exactly as self::dieWithError().
2041 *
2042 * @since 1.29
2043 * @param string|array|Message $msg
2044 * @param string|null $code
2045 * @param array|null $data
2046 * @param int|null $httpCode
2047 * @throws ApiUsageException
2048 */
2049 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
2050 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2051 $this->dieWithError( $msg, $code, $data, $httpCode );
2052 } else {
2053 $this->addWarning( $msg, $code, $data );
2054 }
2055 }
2056
2057 /**
2058 * Die with the 'badcontinue' error.
2059 *
2060 * This call is common enough to make it into the base method.
2061 *
2062 * @param bool $condition Will only die if this value is true
2063 * @throws ApiUsageException
2064 * @since 1.21
2065 */
2066 protected function dieContinueUsageIf( $condition ) {
2067 if ( $condition ) {
2068 $this->dieWithError( 'apierror-badcontinue' );
2069 }
2070 }
2071
2072 /**
2073 * Internal code errors should be reported with this method
2074 * @param string $method Method or function name
2075 * @param string $message Error message
2076 * @throws MWException always
2077 */
2078 protected static function dieDebug( $method, $message ) {
2079 throw new MWException( "Internal error in $method: $message" );
2080 }
2081
2082 /**
2083 * Write logging information for API features to a debug log, for usage
2084 * analysis.
2085 * @note Consider using $this->addDeprecation() instead to both warn and log.
2086 * @param string $feature Feature being used.
2087 */
2088 public function logFeatureUsage( $feature ) {
2089 $request = $this->getRequest();
2090 $s = '"' . addslashes( $feature ) . '"' .
2091 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2092 ' "' . $request->getIP() . '"' .
2093 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2094 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2095 wfDebugLog( 'api-feature-usage', $s, 'private' );
2096 }
2097
2098 /**@}*/
2099
2100 /************************************************************************//**
2101 * @name Help message generation
2102 * @{
2103 */
2104
2105 /**
2106 * Return the summary message.
2107 *
2108 * This is a one-line description of the module, suitable for display in a
2109 * list of modules.
2110 *
2111 * @since 1.30
2112 * @return string|array|Message
2113 */
2114 protected function getSummaryMessage() {
2115 return "apihelp-{$this->getModulePath()}-summary";
2116 }
2117
2118 /**
2119 * Return the extended help text message.
2120 *
2121 * This is additional text to display at the top of the help section, below
2122 * the summary.
2123 *
2124 * @since 1.30
2125 * @return string|array|Message
2126 */
2127 protected function getExtendedDescription() {
2128 return [ [
2129 "apihelp-{$this->getModulePath()}-extended-description",
2130 'api-help-no-extended-description',
2131 ] ];
2132 }
2133
2134 /**
2135 * Get final module summary
2136 *
2137 * Ideally this will just be the getSummaryMessage(). However, for
2138 * backwards compatibility, if that message does not exist then the first
2139 * line of wikitext from the description message will be used instead.
2140 *
2141 * @since 1.30
2142 * @return Message
2143 */
2144 public function getFinalSummary() {
2145 $msg = self::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2146 $this->getModulePrefix(),
2147 $this->getModuleName(),
2148 $this->getModulePath(),
2149 ] );
2150 if ( !$msg->exists() ) {
2151 wfDeprecated( 'API help "description" messages', '1.30' );
2152 $msg = self::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2153 $this->getModulePrefix(),
2154 $this->getModuleName(),
2155 $this->getModulePath(),
2156 ] );
2157 $msg = self::makeMessage( 'rawmessage', $this->getContext(), [
2158 preg_replace( '/\n.*/s', '', $msg->text() )
2159 ] );
2160 }
2161 return $msg;
2162 }
2163
2164 /**
2165 * Get final module description, after hooks have had a chance to tweak it as
2166 * needed.
2167 *
2168 * @since 1.25, returns Message[] rather than string[]
2169 * @return Message[]
2170 */
2171 public function getFinalDescription() {
2172 $desc = $this->getDescription();
2173
2174 // Avoid PHP 7.1 warning of passing $this by reference
2175 $apiModule = $this;
2176 Hooks::run( 'APIGetDescription', [ &$apiModule, &$desc ] );
2177 $desc = self::escapeWikiText( $desc );
2178 if ( is_array( $desc ) ) {
2179 $desc = implode( "\n", $desc );
2180 } else {
2181 $desc = (string)$desc;
2182 }
2183
2184 $summary = self::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2185 $this->getModulePrefix(),
2186 $this->getModuleName(),
2187 $this->getModulePath(),
2188 ] );
2189 $extendedDescription = self::makeMessage(
2190 $this->getExtendedDescription(), $this->getContext(), [
2191 $this->getModulePrefix(),
2192 $this->getModuleName(),
2193 $this->getModulePath(),
2194 ]
2195 );
2196
2197 if ( $summary->exists() ) {
2198 $msgs = [ $summary, $extendedDescription ];
2199 } else {
2200 wfDeprecated( 'API help "description" messages', '1.30' );
2201 $description = self::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2202 $this->getModulePrefix(),
2203 $this->getModuleName(),
2204 $this->getModulePath(),
2205 ] );
2206 if ( !$description->exists() ) {
2207 $description = $this->msg( 'api-help-fallback-description', $desc );
2208 }
2209 $msgs = [ $description ];
2210 }
2211
2212 Hooks::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2213
2214 return $msgs;
2215 }
2216
2217 /**
2218 * Get final list of parameters, after hooks have had a chance to
2219 * tweak it as needed.
2220 *
2221 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2222 * @return array|bool False on no parameters
2223 * @since 1.21 $flags param added
2224 */
2225 public function getFinalParams( $flags = 0 ) {
2226 $params = $this->getAllowedParams( $flags );
2227 if ( !$params ) {
2228 $params = [];
2229 }
2230
2231 if ( $this->needsToken() ) {
2232 $params['token'] = [
2233 self::PARAM_TYPE => 'string',
2234 self::PARAM_REQUIRED => true,
2235 self::PARAM_SENSITIVE => true,
2236 self::PARAM_HELP_MSG => [
2237 'api-help-param-token',
2238 $this->needsToken(),
2239 ],
2240 ] + ( isset( $params['token'] ) ? $params['token'] : [] );
2241 }
2242
2243 // Avoid PHP 7.1 warning of passing $this by reference
2244 $apiModule = $this;
2245 Hooks::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2246
2247 return $params;
2248 }
2249
2250 /**
2251 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2252 * needed.
2253 *
2254 * @since 1.25, returns array of Message[] rather than array of string[]
2255 * @return array Keys are parameter names, values are arrays of Message objects
2256 */
2257 public function getFinalParamDescription() {
2258 $prefix = $this->getModulePrefix();
2259 $name = $this->getModuleName();
2260 $path = $this->getModulePath();
2261
2262 $desc = $this->getParamDescription();
2263
2264 // Avoid PHP 7.1 warning of passing $this by reference
2265 $apiModule = $this;
2266 Hooks::run( 'APIGetParamDescription', [ &$apiModule, &$desc ] );
2267
2268 if ( !$desc ) {
2269 $desc = [];
2270 }
2271 $desc = self::escapeWikiText( $desc );
2272
2273 $params = $this->getFinalParams( self::GET_VALUES_FOR_HELP );
2274 $msgs = [];
2275 foreach ( $params as $param => $settings ) {
2276 if ( !is_array( $settings ) ) {
2277 $settings = [];
2278 }
2279
2280 $d = isset( $desc[$param] ) ? $desc[$param] : '';
2281 if ( is_array( $d ) ) {
2282 // Special handling for prop parameters
2283 $d = array_map( function ( $line ) {
2284 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2285 $line = "\n;{$m[1]}:{$m[2]}";
2286 }
2287 return $line;
2288 }, $d );
2289 $d = implode( ' ', $d );
2290 }
2291
2292 if ( isset( $settings[self::PARAM_HELP_MSG] ) ) {
2293 $msg = $settings[self::PARAM_HELP_MSG];
2294 } else {
2295 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2296 if ( !$msg->exists() ) {
2297 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2298 }
2299 }
2300 $msg = self::makeMessage( $msg, $this->getContext(),
2301 [ $prefix, $param, $name, $path ] );
2302 if ( !$msg ) {
2303 self::dieDebug( __METHOD__,
2304 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2305 }
2306 $msgs[$param] = [ $msg ];
2307
2308 if ( isset( $settings[self::PARAM_TYPE] ) &&
2309 $settings[self::PARAM_TYPE] === 'submodule'
2310 ) {
2311 if ( isset( $settings[self::PARAM_SUBMODULE_MAP] ) ) {
2312 $map = $settings[self::PARAM_SUBMODULE_MAP];
2313 } else {
2314 $prefix = $this->isMain() ? '' : ( $this->getModulePath() . '+' );
2315 $map = [];
2316 foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
2317 $map[$submoduleName] = $prefix . $submoduleName;
2318 }
2319 }
2320 ksort( $map );
2321 $submodules = [];
2322 $deprecatedSubmodules = [];
2323 foreach ( $map as $v => $m ) {
2324 $arr = &$submodules;
2325 $isDeprecated = false;
2326 $summary = null;
2327 try {
2328 $submod = $this->getModuleFromPath( $m );
2329 if ( $submod ) {
2330 $summary = $submod->getFinalSummary();
2331 $isDeprecated = $submod->isDeprecated();
2332 if ( $isDeprecated ) {
2333 $arr = &$deprecatedSubmodules;
2334 }
2335 }
2336 } catch ( ApiUsageException $ex ) {
2337 // Ignore
2338 }
2339 if ( $summary ) {
2340 $key = $summary->getKey();
2341 $params = $summary->getParams();
2342 } else {
2343 $key = 'api-help-undocumented-module';
2344 $params = [ $m ];
2345 }
2346 $m = new ApiHelpParamValueMessage( "[[Special:ApiHelp/$m|$v]]", $key, $params, $isDeprecated );
2347 $arr[] = $m->setContext( $this->getContext() );
2348 }
2349 $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
2350 } elseif ( isset( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
2351 if ( !is_array( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
2352 self::dieDebug( __METHOD__,
2353 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2354 }
2355 if ( !is_array( $settings[self::PARAM_TYPE] ) ) {
2356 self::dieDebug( __METHOD__,
2357 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2358 'ApiBase::PARAM_TYPE is an array' );
2359 }
2360
2361 $valueMsgs = $settings[self::PARAM_HELP_MSG_PER_VALUE];
2362 $deprecatedValues = isset( $settings[self::PARAM_DEPRECATED_VALUES] )
2363 ? $settings[self::PARAM_DEPRECATED_VALUES]
2364 : [];
2365
2366 foreach ( $settings[self::PARAM_TYPE] as $value ) {
2367 if ( isset( $valueMsgs[$value] ) ) {
2368 $msg = $valueMsgs[$value];
2369 } else {
2370 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2371 }
2372 $m = self::makeMessage( $msg, $this->getContext(),
2373 [ $prefix, $param, $name, $path, $value ] );
2374 if ( $m ) {
2375 $m = new ApiHelpParamValueMessage(
2376 $value,
2377 [ $m->getKey(), 'api-help-param-no-description' ],
2378 $m->getParams(),
2379 isset( $deprecatedValues[$value] )
2380 );
2381 $msgs[$param][] = $m->setContext( $this->getContext() );
2382 } else {
2383 self::dieDebug( __METHOD__,
2384 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2385 }
2386 }
2387 }
2388
2389 if ( isset( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
2390 if ( !is_array( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
2391 self::dieDebug( __METHOD__,
2392 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2393 }
2394 foreach ( $settings[self::PARAM_HELP_MSG_APPEND] as $m ) {
2395 $m = self::makeMessage( $m, $this->getContext(),
2396 [ $prefix, $param, $name, $path ] );
2397 if ( $m ) {
2398 $msgs[$param][] = $m;
2399 } else {
2400 self::dieDebug( __METHOD__,
2401 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2402 }
2403 }
2404 }
2405 }
2406
2407 Hooks::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2408
2409 return $msgs;
2410 }
2411
2412 /**
2413 * Generates the list of flags for the help screen and for action=paraminfo
2414 *
2415 * Corresponding messages: api-help-flag-deprecated,
2416 * api-help-flag-internal, api-help-flag-readrights,
2417 * api-help-flag-writerights, api-help-flag-mustbeposted
2418 *
2419 * @return string[]
2420 */
2421 protected function getHelpFlags() {
2422 $flags = [];
2423
2424 if ( $this->isDeprecated() ) {
2425 $flags[] = 'deprecated';
2426 }
2427 if ( $this->isInternal() ) {
2428 $flags[] = 'internal';
2429 }
2430 if ( $this->isReadMode() ) {
2431 $flags[] = 'readrights';
2432 }
2433 if ( $this->isWriteMode() ) {
2434 $flags[] = 'writerights';
2435 }
2436 if ( $this->mustBePosted() ) {
2437 $flags[] = 'mustbeposted';
2438 }
2439
2440 return $flags;
2441 }
2442
2443 /**
2444 * Returns information about the source of this module, if known
2445 *
2446 * Returned array is an array with the following keys:
2447 * - path: Install path
2448 * - name: Extension name, or "MediaWiki" for core
2449 * - namemsg: (optional) i18n message key for a display name
2450 * - license-name: (optional) Name of license
2451 *
2452 * @return array|null
2453 */
2454 protected function getModuleSourceInfo() {
2455 global $IP;
2456
2457 if ( $this->mModuleSource !== false ) {
2458 return $this->mModuleSource;
2459 }
2460
2461 // First, try to find where the module comes from...
2462 $rClass = new ReflectionClass( $this );
2463 $path = $rClass->getFileName();
2464 if ( !$path ) {
2465 // No path known?
2466 $this->mModuleSource = null;
2467 return null;
2468 }
2469 $path = realpath( $path ) ?: $path;
2470
2471 // Build map of extension directories to extension info
2472 if ( self::$extensionInfo === null ) {
2473 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2474 self::$extensionInfo = [
2475 realpath( __DIR__ ) ?: __DIR__ => [
2476 'path' => $IP,
2477 'name' => 'MediaWiki',
2478 'license-name' => 'GPL-2.0-or-later',
2479 ],
2480 realpath( "$IP/extensions" ) ?: "$IP/extensions" => null,
2481 realpath( $extDir ) ?: $extDir => null,
2482 ];
2483 $keep = [
2484 'path' => null,
2485 'name' => null,
2486 'namemsg' => null,
2487 'license-name' => null,
2488 ];
2489 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2490 foreach ( $group as $ext ) {
2491 if ( !isset( $ext['path'] ) || !isset( $ext['name'] ) ) {
2492 // This shouldn't happen, but does anyway.
2493 continue;
2494 }
2495
2496 $extpath = $ext['path'];
2497 if ( !is_dir( $extpath ) ) {
2498 $extpath = dirname( $extpath );
2499 }
2500 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2501 array_intersect_key( $ext, $keep );
2502 }
2503 }
2504 foreach ( ExtensionRegistry::getInstance()->getAllThings() as $ext ) {
2505 $extpath = $ext['path'];
2506 if ( !is_dir( $extpath ) ) {
2507 $extpath = dirname( $extpath );
2508 }
2509 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2510 array_intersect_key( $ext, $keep );
2511 }
2512 }
2513
2514 // Now traverse parent directories until we find a match or run out of
2515 // parents.
2516 do {
2517 if ( array_key_exists( $path, self::$extensionInfo ) ) {
2518 // Found it!
2519 $this->mModuleSource = self::$extensionInfo[$path];
2520 return $this->mModuleSource;
2521 }
2522
2523 $oldpath = $path;
2524 $path = dirname( $path );
2525 } while ( $path !== $oldpath );
2526
2527 // No idea what extension this might be.
2528 $this->mModuleSource = null;
2529 return null;
2530 }
2531
2532 /**
2533 * Called from ApiHelp before the pieces are joined together and returned.
2534 *
2535 * This exists mainly for ApiMain to add the Permissions and Credits
2536 * sections. Other modules probably don't need it.
2537 *
2538 * @param string[] &$help Array of help data
2539 * @param array $options Options passed to ApiHelp::getHelp
2540 * @param array &$tocData If a TOC is being generated, this array has keys
2541 * as anchors in the page and values as for Linker::generateTOC().
2542 */
2543 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2544 }
2545
2546 /**@}*/
2547
2548 /************************************************************************//**
2549 * @name Deprecated
2550 * @{
2551 */
2552
2553 /**
2554 * Returns the description string for this module
2555 *
2556 * Ignored if an i18n message exists for
2557 * "apihelp-{$this->getModulePath()}-description".
2558 *
2559 * @deprecated since 1.25
2560 * @return Message|string|array|false
2561 */
2562 protected function getDescription() {
2563 return false;
2564 }
2565
2566 /**
2567 * Returns an array of parameter descriptions.
2568 *
2569 * For each parameter, ignored if an i18n message exists for the parameter.
2570 * By default that message is
2571 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2572 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2573 * self::getFinalParams().
2574 *
2575 * @deprecated since 1.25
2576 * @return array|bool False on no parameter descriptions
2577 */
2578 protected function getParamDescription() {
2579 return [];
2580 }
2581
2582 /**
2583 * Returns usage examples for this module.
2584 *
2585 * Return value as an array is either:
2586 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2587 * values
2588 * - sequential numeric keys with even-numbered keys being display-text
2589 * and odd-numbered keys being partial urls
2590 * - partial URLs as keys with display-text (string or array-to-be-joined)
2591 * as values
2592 * Return value as a string is the same as an array with a numeric key and
2593 * that value, and boolean false means "no examples".
2594 *
2595 * @deprecated since 1.25, use getExamplesMessages() instead
2596 * @return bool|string|array
2597 */
2598 protected function getExamples() {
2599 return false;
2600 }
2601
2602 /**
2603 * @deprecated since 1.25
2604 */
2605 public function profileIn() {
2606 // No wfDeprecated() yet because extensions call this and might need to
2607 // keep doing so for BC.
2608 }
2609
2610 /**
2611 * @deprecated since 1.25
2612 */
2613 public function profileOut() {
2614 // No wfDeprecated() yet because extensions call this and might need to
2615 // keep doing so for BC.
2616 }
2617
2618 /**
2619 * @deprecated since 1.25
2620 */
2621 public function safeProfileOut() {
2622 wfDeprecated( __METHOD__, '1.25' );
2623 }
2624
2625 /**
2626 * @deprecated since 1.25
2627 */
2628 public function profileDBIn() {
2629 wfDeprecated( __METHOD__, '1.25' );
2630 }
2631
2632 /**
2633 * @deprecated since 1.25
2634 */
2635 public function profileDBOut() {
2636 wfDeprecated( __METHOD__, '1.25' );
2637 }
2638
2639 /**
2640 * Call wfTransactionalTimeLimit() if this request was POSTed
2641 * @since 1.26
2642 */
2643 protected function useTransactionalTimeLimit() {
2644 if ( $this->getRequest()->wasPosted() ) {
2645 wfTransactionalTimeLimit();
2646 }
2647 }
2648
2649 /**
2650 * @deprecated since 1.29, use ApiBase::addWarning() instead
2651 * @param string $warning Warning message
2652 */
2653 public function setWarning( $warning ) {
2654 wfDeprecated( __METHOD__, '1.29' );
2655 $msg = new ApiRawMessage( $warning, 'warning' );
2656 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg );
2657 }
2658
2659 /**
2660 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2661 * error handler and die with an error message.
2662 *
2663 * @deprecated since 1.29, use self::dieWithError() instead
2664 * @param string $description One-line human-readable description of the
2665 * error condition, e.g., "The API requires a valid action parameter"
2666 * @param string $errorCode Brief, arbitrary, stable string to allow easy
2667 * automated identification of the error, e.g., 'unknown_action'
2668 * @param int $httpRespCode HTTP response code
2669 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
2670 * @throws ApiUsageException always
2671 */
2672 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
2673 wfDeprecated( __METHOD__, '1.29' );
2674 $this->dieWithError(
2675 new RawMessage( '$1', [ $description ] ),
2676 $errorCode,
2677 $extradata,
2678 $httpRespCode
2679 );
2680 }
2681
2682 /**
2683 * Get error (as code, string) from a Status object.
2684 *
2685 * @since 1.23
2686 * @deprecated since 1.29, use ApiErrorFormatter::arrayFromStatus instead
2687 * @param Status $status
2688 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
2689 * @return array Array of code and error string
2690 * @throws MWException
2691 */
2692 public function getErrorFromStatus( $status, &$extraData = null ) {
2693 wfDeprecated( __METHOD__, '1.29' );
2694 if ( $status->isGood() ) {
2695 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2696 }
2697
2698 $errors = $status->getErrorsByType( 'error' );
2699 if ( !$errors ) {
2700 // No errors? Assume the warnings should be treated as errors
2701 $errors = $status->getErrorsByType( 'warning' );
2702 }
2703 if ( !$errors ) {
2704 // Still no errors? Punt
2705 $errors = [ [ 'message' => 'unknownerror-nocode', 'params' => [] ] ];
2706 }
2707
2708 if ( $errors[0]['message'] instanceof MessageSpecifier ) {
2709 $msg = $errors[0]['message'];
2710 } else {
2711 $msg = new Message( $errors[0]['message'], $errors[0]['params'] );
2712 }
2713 if ( !$msg instanceof IApiMessage ) {
2714 $key = $msg->getKey();
2715 $params = $msg->getParams();
2716 array_unshift( $params, isset( self::$messageMap[$key] ) ? self::$messageMap[$key] : $key );
2717 $msg = ApiMessage::create( $params );
2718 }
2719
2720 return [
2721 $msg->getApiCode(),
2722 ApiErrorFormatter::stripMarkup( $msg->inLanguage( 'en' )->useDatabase( false )->text() )
2723 ];
2724 }
2725
2726 /**
2727 * @deprecated since 1.29. Prior to 1.29, this was a public mapping from
2728 * arbitrary strings (often message keys used elsewhere in MediaWiki) to
2729 * API codes and message texts, and a few interfaces required poking
2730 * something in here. Now we're repurposing it to map those same strings
2731 * to i18n messages, and declaring that any interface that requires poking
2732 * at this is broken and needs replacing ASAP.
2733 */
2734 private static $messageMap = [
2735 'unknownerror' => 'apierror-unknownerror',
2736 'unknownerror-nocode' => 'apierror-unknownerror-nocode',
2737 'ns-specialprotected' => 'ns-specialprotected',
2738 'protectedinterface' => 'protectedinterface',
2739 'namespaceprotected' => 'namespaceprotected',
2740 'customcssprotected' => 'customcssprotected',
2741 'customjsprotected' => 'customjsprotected',
2742 'cascadeprotected' => 'cascadeprotected',
2743 'protectedpagetext' => 'protectedpagetext',
2744 'protect-cantedit' => 'protect-cantedit',
2745 'deleteprotected' => 'deleteprotected',
2746 'badaccess-group0' => 'badaccess-group0',
2747 'badaccess-groups' => 'badaccess-groups',
2748 'titleprotected' => 'titleprotected',
2749 'nocreate-loggedin' => 'nocreate-loggedin',
2750 'nocreatetext' => 'nocreatetext',
2751 'movenologintext' => 'movenologintext',
2752 'movenotallowed' => 'movenotallowed',
2753 'confirmedittext' => 'confirmedittext',
2754 'blockedtext' => 'apierror-blocked',
2755 'autoblockedtext' => 'apierror-autoblocked',
2756 'systemblockedtext' => 'apierror-systemblocked',
2757 'actionthrottledtext' => 'apierror-ratelimited',
2758 'alreadyrolled' => 'alreadyrolled',
2759 'cantrollback' => 'cantrollback',
2760 'readonlytext' => 'readonlytext',
2761 'sessionfailure' => 'sessionfailure',
2762 'cannotdelete' => 'cannotdelete',
2763 'notanarticle' => 'apierror-missingtitle',
2764 'selfmove' => 'selfmove',
2765 'immobile_namespace' => 'apierror-immobilenamespace',
2766 'articleexists' => 'articleexists',
2767 'hookaborted' => 'hookaborted',
2768 'cantmove-titleprotected' => 'cantmove-titleprotected',
2769 'imagenocrossnamespace' => 'imagenocrossnamespace',
2770 'imagetypemismatch' => 'imagetypemismatch',
2771 'ip_range_invalid' => 'ip_range_invalid',
2772 'range_block_disabled' => 'range_block_disabled',
2773 'nosuchusershort' => 'nosuchusershort',
2774 'badipaddress' => 'badipaddress',
2775 'ipb_expiry_invalid' => 'ipb_expiry_invalid',
2776 'ipb_already_blocked' => 'ipb_already_blocked',
2777 'ipb_blocked_as_range' => 'ipb_blocked_as_range',
2778 'ipb_cant_unblock' => 'ipb_cant_unblock',
2779 'mailnologin' => 'apierror-cantsend',
2780 'ipbblocked' => 'ipbblocked',
2781 'ipbnounblockself' => 'ipbnounblockself',
2782 'usermaildisabled' => 'usermaildisabled',
2783 'blockedemailuser' => 'apierror-blockedfrommail',
2784 'notarget' => 'apierror-notarget',
2785 'noemail' => 'noemail',
2786 'rcpatroldisabled' => 'rcpatroldisabled',
2787 'markedaspatrollederror-noautopatrol' => 'markedaspatrollederror-noautopatrol',
2788 'delete-toobig' => 'delete-toobig',
2789 'movenotallowedfile' => 'movenotallowedfile',
2790 'userrights-no-interwiki' => 'userrights-no-interwiki',
2791 'userrights-nodatabase' => 'userrights-nodatabase',
2792 'nouserspecified' => 'nouserspecified',
2793 'noname' => 'noname',
2794 'summaryrequired' => 'apierror-summaryrequired',
2795 'import-rootpage-invalid' => 'import-rootpage-invalid',
2796 'import-rootpage-nosubpage' => 'import-rootpage-nosubpage',
2797 'readrequired' => 'apierror-readapidenied',
2798 'writedisabled' => 'apierror-noapiwrite',
2799 'writerequired' => 'apierror-writeapidenied',
2800 'missingparam' => 'apierror-missingparam',
2801 'invalidtitle' => 'apierror-invalidtitle',
2802 'nosuchpageid' => 'apierror-nosuchpageid',
2803 'nosuchrevid' => 'apierror-nosuchrevid',
2804 'nosuchuser' => 'nosuchusershort',
2805 'invaliduser' => 'apierror-invaliduser',
2806 'invalidexpiry' => 'apierror-invalidexpiry',
2807 'pastexpiry' => 'apierror-pastexpiry',
2808 'create-titleexists' => 'apierror-create-titleexists',
2809 'missingtitle-createonly' => 'apierror-missingtitle-createonly',
2810 'cantblock' => 'apierror-cantblock',
2811 'canthide' => 'apierror-canthide',
2812 'cantblock-email' => 'apierror-cantblock-email',
2813 'cantunblock' => 'apierror-permissiondenied-generic',
2814 'cannotundelete' => 'cannotundelete',
2815 'permdenied-undelete' => 'apierror-permissiondenied-generic',
2816 'createonly-exists' => 'apierror-articleexists',
2817 'nocreate-missing' => 'apierror-missingtitle',
2818 'cantchangecontentmodel' => 'apierror-cantchangecontentmodel',
2819 'nosuchrcid' => 'apierror-nosuchrcid',
2820 'nosuchlogid' => 'apierror-nosuchlogid',
2821 'protect-invalidaction' => 'apierror-protect-invalidaction',
2822 'protect-invalidlevel' => 'apierror-protect-invalidlevel',
2823 'toofewexpiries' => 'apierror-toofewexpiries',
2824 'cantimport' => 'apierror-cantimport',
2825 'cantimport-upload' => 'apierror-cantimport-upload',
2826 'importnofile' => 'importnofile',
2827 'importuploaderrorsize' => 'importuploaderrorsize',
2828 'importuploaderrorpartial' => 'importuploaderrorpartial',
2829 'importuploaderrortemp' => 'importuploaderrortemp',
2830 'importcantopen' => 'importcantopen',
2831 'import-noarticle' => 'import-noarticle',
2832 'importbadinterwiki' => 'importbadinterwiki',
2833 'import-unknownerror' => 'apierror-import-unknownerror',
2834 'cantoverwrite-sharedfile' => 'apierror-cantoverwrite-sharedfile',
2835 'sharedfile-exists' => 'apierror-fileexists-sharedrepo-perm',
2836 'mustbeposted' => 'apierror-mustbeposted',
2837 'show' => 'apierror-show',
2838 'specialpage-cantexecute' => 'apierror-specialpage-cantexecute',
2839 'invalidoldimage' => 'apierror-invalidoldimage',
2840 'nodeleteablefile' => 'apierror-nodeleteablefile',
2841 'fileexists-forbidden' => 'fileexists-forbidden',
2842 'fileexists-shared-forbidden' => 'fileexists-shared-forbidden',
2843 'filerevert-badversion' => 'filerevert-badversion',
2844 'noimageredirect-anon' => 'apierror-noimageredirect-anon',
2845 'noimageredirect-logged' => 'apierror-noimageredirect',
2846 'spamdetected' => 'apierror-spamdetected',
2847 'contenttoobig' => 'apierror-contenttoobig',
2848 'noedit-anon' => 'apierror-noedit-anon',
2849 'noedit' => 'apierror-noedit',
2850 'wasdeleted' => 'apierror-pagedeleted',
2851 'blankpage' => 'apierror-emptypage',
2852 'editconflict' => 'editconflict',
2853 'hashcheckfailed' => 'apierror-badmd5',
2854 'missingtext' => 'apierror-notext',
2855 'emptynewsection' => 'apierror-emptynewsection',
2856 'revwrongpage' => 'apierror-revwrongpage',
2857 'undo-failure' => 'undo-failure',
2858 'content-not-allowed-here' => 'content-not-allowed-here',
2859 'edit-hook-aborted' => 'edit-hook-aborted',
2860 'edit-gone-missing' => 'edit-gone-missing',
2861 'edit-conflict' => 'edit-conflict',
2862 'edit-already-exists' => 'edit-already-exists',
2863 'invalid-file-key' => 'apierror-invalid-file-key',
2864 'nouploadmodule' => 'apierror-nouploadmodule',
2865 'uploaddisabled' => 'uploaddisabled',
2866 'copyuploaddisabled' => 'copyuploaddisabled',
2867 'copyuploadbaddomain' => 'apierror-copyuploadbaddomain',
2868 'copyuploadbadurl' => 'apierror-copyuploadbadurl',
2869 'filename-tooshort' => 'filename-tooshort',
2870 'filename-toolong' => 'filename-toolong',
2871 'illegal-filename' => 'illegal-filename',
2872 'filetype-missing' => 'filetype-missing',
2873 'mustbeloggedin' => 'apierror-mustbeloggedin',
2874 ];
2875
2876 /**
2877 * @deprecated do not use
2878 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2879 * @return ApiMessage
2880 */
2881 private function parseMsgInternal( $error ) {
2882 $msg = Message::newFromSpecifier( $error );
2883 if ( !$msg instanceof IApiMessage ) {
2884 $key = $msg->getKey();
2885 if ( isset( self::$messageMap[$key] ) ) {
2886 $params = $msg->getParams();
2887 array_unshift( $params, self::$messageMap[$key] );
2888 } else {
2889 $params = [ 'apierror-unknownerror', wfEscapeWikiText( $key ) ];
2890 }
2891 $msg = ApiMessage::create( $params );
2892 }
2893 return $msg;
2894 }
2895
2896 /**
2897 * Return the error message related to a certain array
2898 * @deprecated since 1.29
2899 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2900 * @return array [ 'code' => code, 'info' => info ]
2901 */
2902 public function parseMsg( $error ) {
2903 wfDeprecated( __METHOD__, '1.29' );
2904 // Check whether someone passed the whole array, instead of one element as
2905 // documented. This breaks if it's actually an array of fallback keys, but
2906 // that's long-standing misbehavior introduced in r87627 to incorrectly
2907 // fix T30797.
2908 if ( is_array( $error ) ) {
2909 $first = reset( $error );
2910 if ( is_array( $first ) ) {
2911 wfDebug( __METHOD__ . ' was passed an array of arrays. ' . wfGetAllCallers( 5 ) );
2912 $error = $first;
2913 }
2914 }
2915
2916 $msg = $this->parseMsgInternal( $error );
2917 return [
2918 'code' => $msg->getApiCode(),
2919 'info' => ApiErrorFormatter::stripMarkup(
2920 $msg->inLanguage( 'en' )->useDatabase( false )->text()
2921 ),
2922 'data' => $msg->getApiData()
2923 ];
2924 }
2925
2926 /**
2927 * Output the error message related to a certain array
2928 * @deprecated since 1.29, use ApiBase::dieWithError() instead
2929 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2930 * @throws ApiUsageException always
2931 */
2932 public function dieUsageMsg( $error ) {
2933 wfDeprecated( __METHOD__, '1.29' );
2934 $this->dieWithError( $this->parseMsgInternal( $error ) );
2935 }
2936
2937 /**
2938 * Will only set a warning instead of failing if the global $wgDebugAPI
2939 * is set to true. Otherwise behaves exactly as dieUsageMsg().
2940 * @deprecated since 1.29, use ApiBase::dieWithErrorOrDebug() instead
2941 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2942 * @throws ApiUsageException
2943 * @since 1.21
2944 */
2945 public function dieUsageMsgOrDebug( $error ) {
2946 wfDeprecated( __METHOD__, '1.29' );
2947 $this->dieWithErrorOrDebug( $this->parseMsgInternal( $error ) );
2948 }
2949
2950 /**
2951 * Return the description message.
2952 *
2953 * This is additional text to display on the help page after the summary.
2954 *
2955 * @deprecated since 1.30
2956 * @return string|array|Message
2957 */
2958 protected function getDescriptionMessage() {
2959 return [ [
2960 "apihelp-{$this->getModulePath()}-description",
2961 "apihelp-{$this->getModulePath()}-summary",
2962 ] ];
2963 }
2964
2965 /**@}*/
2966 }
2967
2968 /**
2969 * For really cool vim folding this needs to be at the end:
2970 * vim: foldmarker=@{,@} foldmethod=marker
2971 */