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