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