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