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