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