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