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