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