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