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