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