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