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