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