Merge "LinkBatch::addObj can also work with TitleValue objs"
[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 if ( $this->getUser()->matchEditToken(
1264 $token,
1265 $salts[$tokenType],
1266 $this->getRequest()
1267 ) ) {
1268 return true;
1269 }
1270
1271 $webUiSalt = $this->getWebUITokenSalt( $params );
1272 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1273 $token,
1274 $webUiSalt,
1275 $this->getRequest()
1276 ) ) {
1277 return true;
1278 }
1279
1280 return false;
1281 }
1282
1283 /**
1284 * Validate and normalize of parameters of type 'user'
1285 * @param string $value Parameter value
1286 * @param string $encParamName Parameter name
1287 * @return string Validated and normalized parameter
1288 */
1289 private function validateUser( $value, $encParamName ) {
1290 $title = Title::makeTitleSafe( NS_USER, $value );
1291 if ( $title === null ) {
1292 $this->dieUsage(
1293 "Invalid value '$value' for user parameter $encParamName",
1294 "baduser_{$encParamName}"
1295 );
1296 }
1297
1298 return $title->getText();
1299 }
1300
1301 /**@}*/
1302
1303 /************************************************************************//**
1304 * @name Utility methods
1305 * @{
1306 */
1307
1308 /**
1309 * Set a watch (or unwatch) based the based on a watchlist parameter.
1310 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1311 * @param Title $titleObj The article's title to change
1312 * @param string $userOption The user option to consider when $watch=preferences
1313 */
1314 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1315 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1316 if ( $value === null ) {
1317 return;
1318 }
1319
1320 WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1321 }
1322
1323 /**
1324 * Truncate an array to a certain length.
1325 * @param array $arr Array to truncate
1326 * @param int $limit Maximum length
1327 * @return bool True if the array was truncated, false otherwise
1328 */
1329 public static function truncateArray( &$arr, $limit ) {
1330 $modified = false;
1331 while ( count( $arr ) > $limit ) {
1332 array_pop( $arr );
1333 $modified = true;
1334 }
1335
1336 return $modified;
1337 }
1338
1339 /**
1340 * Gets the user for whom to get the watchlist
1341 *
1342 * @param array $params
1343 * @return User
1344 */
1345 public function getWatchlistUser( $params ) {
1346 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1347 $user = User::newFromName( $params['owner'], false );
1348 if ( !( $user && $user->getId() ) ) {
1349 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1350 }
1351 $token = $user->getOption( 'watchlisttoken' );
1352 if ( $token == '' || !hash_equals( $token, $params['token'] ) ) {
1353 $this->dieUsage(
1354 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1355 'bad_wltoken'
1356 );
1357 }
1358 } else {
1359 if ( !$this->getUser()->isLoggedIn() ) {
1360 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1361 }
1362 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1363 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1364 }
1365 $user = $this->getUser();
1366 }
1367
1368 return $user;
1369 }
1370
1371 /**
1372 * A subset of wfEscapeWikiText for BC texts
1373 *
1374 * @since 1.25
1375 * @param string|array $v
1376 * @return string|array
1377 */
1378 private static function escapeWikiText( $v ) {
1379 if ( is_array( $v ) ) {
1380 return array_map( 'self::escapeWikiText', $v );
1381 } else {
1382 return strtr( $v, array(
1383 '__' => '_&#95;', '{' => '&#123;', '}' => '&#125;',
1384 '[[Category:' => '[[:Category:',
1385 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1386 ) );
1387 }
1388 }
1389
1390 /**
1391 * Create a Message from a string or array
1392 *
1393 * A string is used as a message key. An array has the message key as the
1394 * first value and message parameters as subsequent values.
1395 *
1396 * @since 1.25
1397 * @param string|array|Message $msg
1398 * @param IContextSource $context
1399 * @param array $params
1400 * @return Message|null
1401 */
1402 public static function makeMessage( $msg, IContextSource $context, array $params = null ) {
1403 if ( is_string( $msg ) ) {
1404 $msg = wfMessage( $msg );
1405 } elseif ( is_array( $msg ) ) {
1406 $msg = call_user_func_array( 'wfMessage', $msg );
1407 }
1408 if ( !$msg instanceof Message ) {
1409 return null;
1410 }
1411
1412 $msg->setContext( $context );
1413 if ( $params ) {
1414 $msg->params( $params );
1415 }
1416
1417 return $msg;
1418 }
1419
1420 /**@}*/
1421
1422 /************************************************************************//**
1423 * @name Warning and error reporting
1424 * @{
1425 */
1426
1427 /**
1428 * Set warning section for this module. Users should monitor this
1429 * section to notice any changes in API. Multiple calls to this
1430 * function will result in the warning messages being separated by
1431 * newlines
1432 * @param string $warning Warning message
1433 */
1434 public function setWarning( $warning ) {
1435 $msg = new ApiRawMessage( $warning, 'warning' );
1436 $this->getErrorFormatter()->addWarning( $this->getModuleName(), $msg );
1437 }
1438
1439 /**
1440 * Adds a warning to the output, else dies
1441 *
1442 * @param string $msg Message to show as a warning, or error message if dying
1443 * @param bool $enforceLimits Whether this is an enforce (die)
1444 */
1445 private function warnOrDie( $msg, $enforceLimits = false ) {
1446 if ( $enforceLimits ) {
1447 $this->dieUsage( $msg, 'integeroutofrange' );
1448 }
1449
1450 $this->setWarning( $msg );
1451 }
1452
1453 /**
1454 * Throw a UsageException, which will (if uncaught) call the main module's
1455 * error handler and die with an error message.
1456 *
1457 * @param string $description One-line human-readable description of the
1458 * error condition, e.g., "The API requires a valid action parameter"
1459 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1460 * automated identification of the error, e.g., 'unknown_action'
1461 * @param int $httpRespCode HTTP response code
1462 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
1463 * @throws UsageException always
1464 */
1465 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1466 throw new UsageException(
1467 $description,
1468 $this->encodeParamName( $errorCode ),
1469 $httpRespCode,
1470 $extradata
1471 );
1472 }
1473
1474 /**
1475 * Throw a UsageException, which will (if uncaught) call the main module's
1476 * error handler and die with an error message including block info.
1477 *
1478 * @since 1.27
1479 * @param Block $block The block used to generate the UsageException
1480 * @throws UsageException always
1481 */
1482 public function dieBlocked( Block $block ) {
1483 // Die using the appropriate message depending on block type
1484 if ( $block->getType() == Block::TYPE_AUTO ) {
1485 $this->dieUsage(
1486 'Your IP address has been blocked automatically, because it was used by a blocked user',
1487 'autoblocked',
1488 0,
1489 array( 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) )
1490 );
1491 } else {
1492 $this->dieUsage(
1493 'You have been blocked from editing',
1494 'blocked',
1495 0,
1496 array( 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) )
1497 );
1498 }
1499 }
1500
1501 /**
1502 * Get error (as code, string) from a Status object.
1503 *
1504 * @since 1.23
1505 * @param Status $status
1506 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
1507 * @return array Array of code and error string
1508 * @throws MWException
1509 */
1510 public function getErrorFromStatus( $status, &$extraData = null ) {
1511 if ( $status->isGood() ) {
1512 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1513 }
1514
1515 $errors = $status->getErrorsArray();
1516 if ( !$errors ) {
1517 // No errors? Assume the warnings should be treated as errors
1518 $errors = $status->getWarningsArray();
1519 }
1520 if ( !$errors ) {
1521 // Still no errors? Punt
1522 $errors = array( array( 'unknownerror-nocode' ) );
1523 }
1524
1525 // Cannot use dieUsageMsg() because extensions might return custom
1526 // error messages.
1527 if ( $errors[0] instanceof Message ) {
1528 $msg = $errors[0];
1529 if ( $msg instanceof IApiMessage ) {
1530 $extraData = $msg->getApiData();
1531 $code = $msg->getApiCode();
1532 } else {
1533 $code = $msg->getKey();
1534 }
1535 } else {
1536 $code = array_shift( $errors[0] );
1537 $msg = wfMessage( $code, $errors[0] );
1538 }
1539 if ( isset( ApiBase::$messageMap[$code] ) ) {
1540 // Translate message to code, for backwards compatibility
1541 $code = ApiBase::$messageMap[$code]['code'];
1542 }
1543
1544 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1545 }
1546
1547 /**
1548 * Throw a UsageException based on the errors in the Status object.
1549 *
1550 * @since 1.22
1551 * @param Status $status
1552 * @throws UsageException always
1553 */
1554 public function dieStatus( $status ) {
1555 $extraData = null;
1556 list( $code, $msg ) = $this->getErrorFromStatus( $status, $extraData );
1557 $this->dieUsage( $msg, $code, 0, $extraData );
1558 }
1559
1560 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1561 /**
1562 * Array that maps message keys to error messages. $1 and friends are replaced.
1563 */
1564 public static $messageMap = array(
1565 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1566 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1567 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1568
1569 // Messages from Title::getUserPermissionsErrors()
1570 'ns-specialprotected' => array(
1571 'code' => 'unsupportednamespace',
1572 'info' => "Pages in the Special namespace can't be edited"
1573 ),
1574 'protectedinterface' => array(
1575 'code' => 'protectednamespace-interface',
1576 'info' => "You're not allowed to edit interface messages"
1577 ),
1578 'namespaceprotected' => array(
1579 'code' => 'protectednamespace',
1580 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1581 ),
1582 'customcssprotected' => array(
1583 'code' => 'customcssprotected',
1584 'info' => "You're not allowed to edit custom CSS pages"
1585 ),
1586 'customjsprotected' => array(
1587 'code' => 'customjsprotected',
1588 'info' => "You're not allowed to edit custom JavaScript pages"
1589 ),
1590 'cascadeprotected' => array(
1591 'code' => 'cascadeprotected',
1592 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1593 ),
1594 'protectedpagetext' => array(
1595 'code' => 'protectedpage',
1596 'info' => "The \"\$1\" right is required to edit this page"
1597 ),
1598 'protect-cantedit' => array(
1599 'code' => 'cantedit',
1600 'info' => "You can't protect this page because you can't edit it"
1601 ),
1602 'deleteprotected' => array(
1603 'code' => 'cantedit',
1604 'info' => "You can't delete this page because it has been protected"
1605 ),
1606 'badaccess-group0' => array(
1607 'code' => 'permissiondenied',
1608 'info' => "Permission denied"
1609 ), // Generic permission denied message
1610 'badaccess-groups' => array(
1611 'code' => 'permissiondenied',
1612 'info' => "Permission denied"
1613 ),
1614 'titleprotected' => array(
1615 'code' => 'protectedtitle',
1616 'info' => "This title has been protected from creation"
1617 ),
1618 'nocreate-loggedin' => array(
1619 'code' => 'cantcreate',
1620 'info' => "You don't have permission to create new pages"
1621 ),
1622 'nocreatetext' => array(
1623 'code' => 'cantcreate-anon',
1624 'info' => "Anonymous users can't create new pages"
1625 ),
1626 'movenologintext' => array(
1627 'code' => 'cantmove-anon',
1628 'info' => "Anonymous users can't move pages"
1629 ),
1630 'movenotallowed' => array(
1631 'code' => 'cantmove',
1632 'info' => "You don't have permission to move pages"
1633 ),
1634 'confirmedittext' => array(
1635 'code' => 'confirmemail',
1636 'info' => "You must confirm your email address before you can edit"
1637 ),
1638 'blockedtext' => array(
1639 'code' => 'blocked',
1640 'info' => "You have been blocked from editing"
1641 ),
1642 'autoblockedtext' => array(
1643 'code' => 'autoblocked',
1644 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1645 ),
1646
1647 // Miscellaneous interface messages
1648 'actionthrottledtext' => array(
1649 'code' => 'ratelimited',
1650 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1651 ),
1652 'alreadyrolled' => array(
1653 'code' => 'alreadyrolled',
1654 'info' => "The page you tried to rollback was already rolled back"
1655 ),
1656 'cantrollback' => array(
1657 'code' => 'onlyauthor',
1658 'info' => "The page you tried to rollback only has one author"
1659 ),
1660 'readonlytext' => array(
1661 'code' => 'readonly',
1662 'info' => "The wiki is currently in read-only mode"
1663 ),
1664 'sessionfailure' => array(
1665 'code' => 'badtoken',
1666 'info' => "Invalid token" ),
1667 'cannotdelete' => array(
1668 'code' => 'cantdelete',
1669 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1670 ),
1671 'notanarticle' => array(
1672 'code' => 'missingtitle',
1673 'info' => "The page you requested doesn't exist"
1674 ),
1675 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1676 ),
1677 'immobile_namespace' => array(
1678 'code' => 'immobilenamespace',
1679 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1680 ),
1681 'articleexists' => array(
1682 'code' => 'articleexists',
1683 'info' => "The destination article already exists and is not a redirect to the source article"
1684 ),
1685 'protectedpage' => array(
1686 'code' => 'protectedpage',
1687 'info' => "You don't have permission to perform this move"
1688 ),
1689 'hookaborted' => array(
1690 'code' => 'hookaborted',
1691 'info' => "The modification you tried to make was aborted by an extension hook"
1692 ),
1693 'cantmove-titleprotected' => array(
1694 'code' => 'protectedtitle',
1695 'info' => "The destination article has been protected from creation"
1696 ),
1697 'imagenocrossnamespace' => array(
1698 'code' => 'nonfilenamespace',
1699 'info' => "Can't move a file to a non-file namespace"
1700 ),
1701 'imagetypemismatch' => array(
1702 'code' => 'filetypemismatch',
1703 'info' => "The new file extension doesn't match its type"
1704 ),
1705 // 'badarticleerror' => shouldn't happen
1706 // 'badtitletext' => shouldn't happen
1707 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1708 'range_block_disabled' => array(
1709 'code' => 'rangedisabled',
1710 'info' => "Blocking IP ranges has been disabled"
1711 ),
1712 'nosuchusershort' => array(
1713 'code' => 'nosuchuser',
1714 'info' => "The user you specified doesn't exist"
1715 ),
1716 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1717 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1718 'ipb_already_blocked' => array(
1719 'code' => 'alreadyblocked',
1720 'info' => "The user you tried to block was already blocked"
1721 ),
1722 'ipb_blocked_as_range' => array(
1723 'code' => 'blockedasrange',
1724 '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."
1725 ),
1726 'ipb_cant_unblock' => array(
1727 'code' => 'cantunblock',
1728 'info' => "The block you specified was not found. It may have been unblocked already"
1729 ),
1730 'mailnologin' => array(
1731 'code' => 'cantsend',
1732 '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"
1733 ),
1734 'ipbblocked' => array(
1735 'code' => 'ipbblocked',
1736 'info' => 'You cannot block or unblock users while you are yourself blocked'
1737 ),
1738 'ipbnounblockself' => array(
1739 'code' => 'ipbnounblockself',
1740 'info' => 'You are not allowed to unblock yourself'
1741 ),
1742 'usermaildisabled' => array(
1743 'code' => 'usermaildisabled',
1744 'info' => "User email has been disabled"
1745 ),
1746 'blockedemailuser' => array(
1747 'code' => 'blockedfrommail',
1748 'info' => "You have been blocked from sending email"
1749 ),
1750 'notarget' => array(
1751 'code' => 'notarget',
1752 'info' => "You have not specified a valid target for this action"
1753 ),
1754 'noemail' => array(
1755 'code' => 'noemail',
1756 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1757 ),
1758 'rcpatroldisabled' => array(
1759 'code' => 'patroldisabled',
1760 'info' => "Patrolling is disabled on this wiki"
1761 ),
1762 'markedaspatrollederror-noautopatrol' => array(
1763 'code' => 'noautopatrol',
1764 'info' => "You don't have permission to patrol your own changes"
1765 ),
1766 'delete-toobig' => array(
1767 'code' => 'bigdelete',
1768 'info' => "You can't delete this page because it has more than \$1 revisions"
1769 ),
1770 'movenotallowedfile' => array(
1771 'code' => 'cantmovefile',
1772 'info' => "You don't have permission to move files"
1773 ),
1774 'userrights-no-interwiki' => array(
1775 'code' => 'nointerwikiuserrights',
1776 'info' => "You don't have permission to change user rights on other wikis"
1777 ),
1778 'userrights-nodatabase' => array(
1779 'code' => 'nosuchdatabase',
1780 'info' => "Database \"\$1\" does not exist or is not local"
1781 ),
1782 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1783 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1784 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1785 'import-rootpage-invalid' => array(
1786 'code' => 'import-rootpage-invalid',
1787 'info' => 'Root page is an invalid title'
1788 ),
1789 'import-rootpage-nosubpage' => array(
1790 'code' => 'import-rootpage-nosubpage',
1791 'info' => 'Namespace "$1" of the root page does not allow subpages'
1792 ),
1793
1794 // API-specific messages
1795 'readrequired' => array(
1796 'code' => 'readapidenied',
1797 'info' => "You need read permission to use this module"
1798 ),
1799 'writedisabled' => array(
1800 'code' => 'noapiwrite',
1801 '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"
1802 ),
1803 'writerequired' => array(
1804 'code' => 'writeapidenied',
1805 'info' => "You're not allowed to edit this wiki through the API"
1806 ),
1807 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1808 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1809 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1810 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1811 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1812 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1813 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1814 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1815 'create-titleexists' => array(
1816 'code' => 'create-titleexists',
1817 'info' => "Existing titles can't be protected with 'create'"
1818 ),
1819 'missingtitle-createonly' => array(
1820 'code' => 'missingtitle-createonly',
1821 'info' => "Missing titles can only be protected with 'create'"
1822 ),
1823 'cantblock' => array( 'code' => 'cantblock',
1824 'info' => "You don't have permission to block users"
1825 ),
1826 'canthide' => array(
1827 'code' => 'canthide',
1828 'info' => "You don't have permission to hide user names from the block log"
1829 ),
1830 'cantblock-email' => array(
1831 'code' => 'cantblock-email',
1832 'info' => "You don't have permission to block users from sending email through the wiki"
1833 ),
1834 'unblock-notarget' => array(
1835 'code' => 'notarget',
1836 'info' => "Either the id or the user parameter must be set"
1837 ),
1838 'unblock-idanduser' => array(
1839 'code' => 'idanduser',
1840 'info' => "The id and user parameters can't be used together"
1841 ),
1842 'cantunblock' => array(
1843 'code' => 'permissiondenied',
1844 'info' => "You don't have permission to unblock users"
1845 ),
1846 'cannotundelete' => array(
1847 'code' => 'cantundelete',
1848 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1849 ),
1850 'permdenied-undelete' => array(
1851 'code' => 'permissiondenied',
1852 'info' => "You don't have permission to restore deleted revisions"
1853 ),
1854 'createonly-exists' => array(
1855 'code' => 'articleexists',
1856 'info' => "The article you tried to create has been created already"
1857 ),
1858 'nocreate-missing' => array(
1859 'code' => 'missingtitle',
1860 'info' => "The article you tried to edit doesn't exist"
1861 ),
1862 'cantchangecontentmodel' => array(
1863 'code' => 'cantchangecontentmodel',
1864 'info' => "You don't have permission to change the content model of a page"
1865 ),
1866 'nosuchrcid' => array(
1867 'code' => 'nosuchrcid',
1868 'info' => "There is no change with rcid \"\$1\""
1869 ),
1870 'nosuchlogid' => array(
1871 'code' => 'nosuchlogid',
1872 'info' => "There is no log entry with ID \"\$1\""
1873 ),
1874 'protect-invalidaction' => array(
1875 'code' => 'protect-invalidaction',
1876 'info' => "Invalid protection type \"\$1\""
1877 ),
1878 'protect-invalidlevel' => array(
1879 'code' => 'protect-invalidlevel',
1880 'info' => "Invalid protection level \"\$1\""
1881 ),
1882 'toofewexpiries' => array(
1883 'code' => 'toofewexpiries',
1884 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1885 ),
1886 'cantimport' => array(
1887 'code' => 'cantimport',
1888 'info' => "You don't have permission to import pages"
1889 ),
1890 'cantimport-upload' => array(
1891 'code' => 'cantimport-upload',
1892 'info' => "You don't have permission to import uploaded pages"
1893 ),
1894 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1895 'importuploaderrorsize' => array(
1896 'code' => 'filetoobig',
1897 'info' => 'The file you uploaded is bigger than the maximum upload size'
1898 ),
1899 'importuploaderrorpartial' => array(
1900 'code' => 'partialupload',
1901 'info' => 'The file was only partially uploaded'
1902 ),
1903 'importuploaderrortemp' => array(
1904 'code' => 'notempdir',
1905 'info' => 'The temporary upload directory is missing'
1906 ),
1907 'importcantopen' => array(
1908 'code' => 'cantopenfile',
1909 'info' => "Couldn't open the uploaded file"
1910 ),
1911 'import-noarticle' => array(
1912 'code' => 'badinterwiki',
1913 'info' => 'Invalid interwiki title specified'
1914 ),
1915 'importbadinterwiki' => array(
1916 'code' => 'badinterwiki',
1917 'info' => 'Invalid interwiki title specified'
1918 ),
1919 'import-unknownerror' => array(
1920 'code' => 'import-unknownerror',
1921 'info' => "Unknown error on import: \"\$1\""
1922 ),
1923 'cantoverwrite-sharedfile' => array(
1924 'code' => 'cantoverwrite-sharedfile',
1925 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1926 ),
1927 'sharedfile-exists' => array(
1928 'code' => 'fileexists-sharedrepo-perm',
1929 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1930 ),
1931 'mustbeposted' => array(
1932 'code' => 'mustbeposted',
1933 'info' => "The \$1 module requires a POST request"
1934 ),
1935 'show' => array(
1936 'code' => 'show',
1937 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1938 ),
1939 'specialpage-cantexecute' => array(
1940 'code' => 'specialpage-cantexecute',
1941 'info' => "You don't have permission to view the results of this special page"
1942 ),
1943 'invalidoldimage' => array(
1944 'code' => 'invalidoldimage',
1945 'info' => 'The oldimage parameter has invalid format'
1946 ),
1947 'nodeleteablefile' => array(
1948 'code' => 'nodeleteablefile',
1949 'info' => 'No such old version of the file'
1950 ),
1951 'fileexists-forbidden' => array(
1952 'code' => 'fileexists-forbidden',
1953 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1954 ),
1955 'fileexists-shared-forbidden' => array(
1956 'code' => 'fileexists-shared-forbidden',
1957 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1958 ),
1959 'filerevert-badversion' => array(
1960 'code' => 'filerevert-badversion',
1961 'info' => 'There is no previous local version of this file with the provided timestamp.'
1962 ),
1963
1964 // ApiEditPage messages
1965 'noimageredirect-anon' => array(
1966 'code' => 'noimageredirect-anon',
1967 'info' => "Anonymous users can't create image redirects"
1968 ),
1969 'noimageredirect-logged' => array(
1970 'code' => 'noimageredirect',
1971 'info' => "You don't have permission to create image redirects"
1972 ),
1973 'spamdetected' => array(
1974 'code' => 'spamdetected',
1975 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1976 ),
1977 'contenttoobig' => array(
1978 'code' => 'contenttoobig',
1979 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1980 ),
1981 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1982 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1983 'wasdeleted' => array(
1984 'code' => 'pagedeleted',
1985 'info' => "The page has been deleted since you fetched its timestamp"
1986 ),
1987 'blankpage' => array(
1988 'code' => 'emptypage',
1989 'info' => "Creating new, empty pages is not allowed"
1990 ),
1991 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1992 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1993 'missingtext' => array(
1994 'code' => 'notext',
1995 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1996 ),
1997 'emptynewsection' => array(
1998 'code' => 'emptynewsection',
1999 'info' => 'Creating empty new sections is not possible.'
2000 ),
2001 'revwrongpage' => array(
2002 'code' => 'revwrongpage',
2003 'info' => "r\$1 is not a revision of \"\$2\""
2004 ),
2005 'undo-failure' => array(
2006 'code' => 'undofailure',
2007 'info' => 'Undo failed due to conflicting intermediate edits'
2008 ),
2009 'content-not-allowed-here' => array(
2010 'code' => 'contentnotallowedhere',
2011 'info' => 'Content model "$1" is not allowed at title "$2"'
2012 ),
2013
2014 // Messages from WikiPage::doEit()
2015 'edit-hook-aborted' => array(
2016 'code' => 'edit-hook-aborted',
2017 'info' => "Your edit was aborted by an ArticleSave hook"
2018 ),
2019 'edit-gone-missing' => array(
2020 'code' => 'edit-gone-missing',
2021 'info' => "The page you tried to edit doesn't seem to exist anymore"
2022 ),
2023 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
2024 'edit-already-exists' => array(
2025 'code' => 'edit-already-exists',
2026 'info' => 'It seems the page you tried to create already exist'
2027 ),
2028
2029 // uploadMsgs
2030 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
2031 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
2032 'uploaddisabled' => array(
2033 'code' => 'uploaddisabled',
2034 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
2035 ),
2036 'copyuploaddisabled' => array(
2037 'code' => 'copyuploaddisabled',
2038 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
2039 ),
2040 'copyuploadbaddomain' => array(
2041 'code' => 'copyuploadbaddomain',
2042 'info' => 'Uploads by URL are not allowed from this domain.'
2043 ),
2044 'copyuploadbadurl' => array(
2045 'code' => 'copyuploadbadurl',
2046 'info' => 'Upload not allowed from this URL.'
2047 ),
2048
2049 'filename-tooshort' => array(
2050 'code' => 'filename-tooshort',
2051 'info' => 'The filename is too short'
2052 ),
2053 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
2054 'illegal-filename' => array(
2055 'code' => 'illegal-filename',
2056 'info' => 'The filename is not allowed'
2057 ),
2058 'filetype-missing' => array(
2059 'code' => 'filetype-missing',
2060 'info' => 'The file is missing an extension'
2061 ),
2062
2063 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
2064 );
2065 // @codingStandardsIgnoreEnd
2066
2067 /**
2068 * Helper function for readonly errors
2069 *
2070 * @throws UsageException always
2071 */
2072 public function dieReadOnly() {
2073 $parsed = $this->parseMsg( array( 'readonlytext' ) );
2074 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
2075 array( 'readonlyreason' => wfReadOnlyReason() ) );
2076 }
2077
2078 /**
2079 * Output the error message related to a certain array
2080 * @param array|string $error Element of a getUserPermissionsErrors()-style array
2081 * @throws UsageException always
2082 */
2083 public function dieUsageMsg( $error ) {
2084 # most of the time we send a 1 element, so we might as well send it as
2085 # a string and make this an array here.
2086 if ( is_string( $error ) ) {
2087 $error = array( $error );
2088 }
2089 $parsed = $this->parseMsg( $error );
2090 $extraData = isset( $parsed['data'] ) ? $parsed['data'] : null;
2091 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $extraData );
2092 }
2093
2094 /**
2095 * Will only set a warning instead of failing if the global $wgDebugAPI
2096 * is set to true. Otherwise behaves exactly as dieUsageMsg().
2097 * @param array|string $error Element of a getUserPermissionsErrors()-style array
2098 * @throws UsageException
2099 * @since 1.21
2100 */
2101 public function dieUsageMsgOrDebug( $error ) {
2102 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2103 $this->dieUsageMsg( $error );
2104 }
2105
2106 if ( is_string( $error ) ) {
2107 $error = array( $error );
2108 }
2109 $parsed = $this->parseMsg( $error );
2110 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
2111 }
2112
2113 /**
2114 * Die with the $prefix.'badcontinue' error. This call is common enough to
2115 * make it into the base method.
2116 * @param bool $condition Will only die if this value is true
2117 * @throws UsageException
2118 * @since 1.21
2119 */
2120 protected function dieContinueUsageIf( $condition ) {
2121 if ( $condition ) {
2122 $this->dieUsage(
2123 'Invalid continue param. You should pass the original value returned by the previous query',
2124 'badcontinue' );
2125 }
2126 }
2127
2128 /**
2129 * Return the error message related to a certain array
2130 * @param array $error Element of a getUserPermissionsErrors()-style array
2131 * @return array('code' => code, 'info' => info)
2132 */
2133 public function parseMsg( $error ) {
2134 $error = (array)$error; // It seems strings sometimes make their way in here
2135 $key = array_shift( $error );
2136
2137 // Check whether the error array was nested
2138 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
2139 if ( is_array( $key ) ) {
2140 $error = $key;
2141 $key = array_shift( $error );
2142 }
2143
2144 if ( $key instanceof IApiMessage ) {
2145 return array(
2146 'code' => $key->getApiCode(),
2147 'info' => $key->inLanguage( 'en' )->useDatabase( false )->text(),
2148 'data' => $key->getApiData()
2149 );
2150 }
2151
2152 if ( isset( self::$messageMap[$key] ) ) {
2153 return array(
2154 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
2155 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
2156 );
2157 }
2158
2159 // If the key isn't present, throw an "unknown error"
2160 return $this->parseMsg( array( 'unknownerror', $key ) );
2161 }
2162
2163 /**
2164 * Internal code errors should be reported with this method
2165 * @param string $method Method or function name
2166 * @param string $message Error message
2167 * @throws MWException always
2168 */
2169 protected static function dieDebug( $method, $message ) {
2170 throw new MWException( "Internal error in $method: $message" );
2171 }
2172
2173 /**
2174 * Write logging information for API features to a debug log, for usage
2175 * analysis.
2176 * @param string $feature Feature being used.
2177 */
2178 protected function logFeatureUsage( $feature ) {
2179 $request = $this->getRequest();
2180 $s = '"' . addslashes( $feature ) . '"' .
2181 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2182 ' "' . $request->getIP() . '"' .
2183 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2184 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2185 wfDebugLog( 'api-feature-usage', $s, 'private' );
2186 }
2187
2188 /**@}*/
2189
2190 /************************************************************************//**
2191 * @name Help message generation
2192 * @{
2193 */
2194
2195 /**
2196 * Return the description message.
2197 *
2198 * @return string|array|Message
2199 */
2200 protected function getDescriptionMessage() {
2201 return "apihelp-{$this->getModulePath()}-description";
2202 }
2203
2204 /**
2205 * Get final module description, after hooks have had a chance to tweak it as
2206 * needed.
2207 *
2208 * @since 1.25, returns Message[] rather than string[]
2209 * @return Message[]
2210 */
2211 public function getFinalDescription() {
2212 $desc = $this->getDescription();
2213 Hooks::run( 'APIGetDescription', array( &$this, &$desc ) );
2214 $desc = self::escapeWikiText( $desc );
2215 if ( is_array( $desc ) ) {
2216 $desc = join( "\n", $desc );
2217 } else {
2218 $desc = (string)$desc;
2219 }
2220
2221 $msg = ApiBase::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
2222 $this->getModulePrefix(),
2223 $this->getModuleName(),
2224 $this->getModulePath(),
2225 ) );
2226 if ( !$msg->exists() ) {
2227 $msg = $this->msg( 'api-help-fallback-description', $desc );
2228 }
2229 $msgs = array( $msg );
2230
2231 Hooks::run( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
2232
2233 return $msgs;
2234 }
2235
2236 /**
2237 * Get final list of parameters, after hooks have had a chance to
2238 * tweak it as needed.
2239 *
2240 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2241 * @return array|bool False on no parameters
2242 * @since 1.21 $flags param added
2243 */
2244 public function getFinalParams( $flags = 0 ) {
2245 $params = $this->getAllowedParams( $flags );
2246 if ( !$params ) {
2247 $params = array();
2248 }
2249
2250 if ( $this->needsToken() ) {
2251 $params['token'] = array(
2252 ApiBase::PARAM_TYPE => 'string',
2253 ApiBase::PARAM_REQUIRED => true,
2254 ApiBase::PARAM_HELP_MSG => array(
2255 'api-help-param-token',
2256 $this->needsToken(),
2257 ),
2258 ) + ( isset( $params['token'] ) ? $params['token'] : array() );
2259 }
2260
2261 Hooks::run( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2262
2263 return $params;
2264 }
2265
2266 /**
2267 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2268 * needed.
2269 *
2270 * @since 1.25, returns array of Message[] rather than array of string[]
2271 * @return array Keys are parameter names, values are arrays of Message objects
2272 */
2273 public function getFinalParamDescription() {
2274 $prefix = $this->getModulePrefix();
2275 $name = $this->getModuleName();
2276 $path = $this->getModulePath();
2277
2278 $desc = $this->getParamDescription();
2279 Hooks::run( 'APIGetParamDescription', array( &$this, &$desc ) );
2280
2281 if ( !$desc ) {
2282 $desc = array();
2283 }
2284 $desc = self::escapeWikiText( $desc );
2285
2286 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
2287 $msgs = array();
2288 foreach ( $params as $param => $settings ) {
2289 if ( !is_array( $settings ) ) {
2290 $settings = array();
2291 }
2292
2293 $d = isset( $desc[$param] ) ? $desc[$param] : '';
2294 if ( is_array( $d ) ) {
2295 // Special handling for prop parameters
2296 $d = array_map( function ( $line ) {
2297 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2298 $line = "\n;{$m[1]}:{$m[2]}";
2299 }
2300 return $line;
2301 }, $d );
2302 $d = join( ' ', $d );
2303 }
2304
2305 if ( isset( $settings[ApiBase::PARAM_HELP_MSG] ) ) {
2306 $msg = $settings[ApiBase::PARAM_HELP_MSG];
2307 } else {
2308 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2309 if ( !$msg->exists() ) {
2310 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2311 }
2312 }
2313 $msg = ApiBase::makeMessage( $msg, $this->getContext(),
2314 array( $prefix, $param, $name, $path ) );
2315 if ( !$msg ) {
2316 $this->dieDebug( __METHOD__,
2317 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2318 }
2319 $msgs[$param] = array( $msg );
2320
2321 if ( isset( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
2322 if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
2323 $this->dieDebug( __METHOD__,
2324 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2325 }
2326 if ( !is_array( $settings[ApiBase::PARAM_TYPE] ) ) {
2327 $this->dieDebug( __METHOD__,
2328 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2329 'ApiBase::PARAM_TYPE is an array' );
2330 }
2331
2332 $valueMsgs = $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE];
2333 foreach ( $settings[ApiBase::PARAM_TYPE] as $value ) {
2334 if ( isset( $valueMsgs[$value] ) ) {
2335 $msg = $valueMsgs[$value];
2336 } else {
2337 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2338 }
2339 $m = ApiBase::makeMessage( $msg, $this->getContext(),
2340 array( $prefix, $param, $name, $path, $value ) );
2341 if ( $m ) {
2342 $m = new ApiHelpParamValueMessage(
2343 $value,
2344 array( $m->getKey(), 'api-help-param-no-description' ),
2345 $m->getParams()
2346 );
2347 $msgs[$param][] = $m->setContext( $this->getContext() );
2348 } else {
2349 $this->dieDebug( __METHOD__,
2350 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2351 }
2352 }
2353 }
2354
2355 if ( isset( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2356 if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2357 $this->dieDebug( __METHOD__,
2358 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2359 }
2360 foreach ( $settings[ApiBase::PARAM_HELP_MSG_APPEND] as $m ) {
2361 $m = ApiBase::makeMessage( $m, $this->getContext(),
2362 array( $prefix, $param, $name, $path ) );
2363 if ( $m ) {
2364 $msgs[$param][] = $m;
2365 } else {
2366 $this->dieDebug( __METHOD__,
2367 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2368 }
2369 }
2370 }
2371 }
2372
2373 Hooks::run( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2374
2375 return $msgs;
2376 }
2377
2378 /**
2379 * Generates the list of flags for the help screen and for action=paraminfo
2380 *
2381 * Corresponding messages: api-help-flag-deprecated,
2382 * api-help-flag-internal, api-help-flag-readrights,
2383 * api-help-flag-writerights, api-help-flag-mustbeposted
2384 *
2385 * @return string[]
2386 */
2387 protected function getHelpFlags() {
2388 $flags = array();
2389
2390 if ( $this->isDeprecated() ) {
2391 $flags[] = 'deprecated';
2392 }
2393 if ( $this->isInternal() ) {
2394 $flags[] = 'internal';
2395 }
2396 if ( $this->isReadMode() ) {
2397 $flags[] = 'readrights';
2398 }
2399 if ( $this->isWriteMode() ) {
2400 $flags[] = 'writerights';
2401 }
2402 if ( $this->mustBePosted() ) {
2403 $flags[] = 'mustbeposted';
2404 }
2405
2406 return $flags;
2407 }
2408
2409 /**
2410 * Returns information about the source of this module, if known
2411 *
2412 * Returned array is an array with the following keys:
2413 * - path: Install path
2414 * - name: Extension name, or "MediaWiki" for core
2415 * - namemsg: (optional) i18n message key for a display name
2416 * - license-name: (optional) Name of license
2417 *
2418 * @return array|null
2419 */
2420 protected function getModuleSourceInfo() {
2421 global $IP;
2422
2423 if ( $this->mModuleSource !== false ) {
2424 return $this->mModuleSource;
2425 }
2426
2427 // First, try to find where the module comes from...
2428 $rClass = new ReflectionClass( $this );
2429 $path = $rClass->getFileName();
2430 if ( !$path ) {
2431 // No path known?
2432 $this->mModuleSource = null;
2433 return null;
2434 }
2435 $path = realpath( $path ) ?: $path;
2436
2437 // Build map of extension directories to extension info
2438 if ( self::$extensionInfo === null ) {
2439 self::$extensionInfo = array(
2440 realpath( __DIR__ ) ?: __DIR__ => array(
2441 'path' => $IP,
2442 'name' => 'MediaWiki',
2443 'license-name' => 'GPL-2.0+',
2444 ),
2445 realpath( "$IP/extensions" ) ?: "$IP/extensions" => null,
2446 );
2447 $keep = array(
2448 'path' => null,
2449 'name' => null,
2450 'namemsg' => null,
2451 'license-name' => null,
2452 );
2453 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2454 foreach ( $group as $ext ) {
2455 if ( !isset( $ext['path'] ) || !isset( $ext['name'] ) ) {
2456 // This shouldn't happen, but does anyway.
2457 continue;
2458 }
2459
2460 $extpath = $ext['path'];
2461 if ( !is_dir( $extpath ) ) {
2462 $extpath = dirname( $extpath );
2463 }
2464 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2465 array_intersect_key( $ext, $keep );
2466 }
2467 }
2468 foreach ( ExtensionRegistry::getInstance()->getAllThings() as $ext ) {
2469 $extpath = $ext['path'];
2470 if ( !is_dir( $extpath ) ) {
2471 $extpath = dirname( $extpath );
2472 }
2473 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2474 array_intersect_key( $ext, $keep );
2475 }
2476 }
2477
2478 // Now traverse parent directories until we find a match or run out of
2479 // parents.
2480 do {
2481 if ( array_key_exists( $path, self::$extensionInfo ) ) {
2482 // Found it!
2483 $this->mModuleSource = self::$extensionInfo[$path];
2484 return $this->mModuleSource;
2485 }
2486
2487 $oldpath = $path;
2488 $path = dirname( $path );
2489 } while ( $path !== $oldpath );
2490
2491 // No idea what extension this might be.
2492 $this->mModuleSource = null;
2493 return null;
2494 }
2495
2496 /**
2497 * Called from ApiHelp before the pieces are joined together and returned.
2498 *
2499 * This exists mainly for ApiMain to add the Permissions and Credits
2500 * sections. Other modules probably don't need it.
2501 *
2502 * @param string[] &$help Array of help data
2503 * @param array $options Options passed to ApiHelp::getHelp
2504 * @param array &$tocData If a TOC is being generated, this array has keys
2505 * as anchors in the page and values as for Linker::generateTOC().
2506 */
2507 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2508 }
2509
2510 /**@}*/
2511
2512 /************************************************************************//**
2513 * @name Deprecated
2514 * @{
2515 */
2516
2517 /// @deprecated since 1.24
2518 const PROP_ROOT = 'ROOT';
2519 /// @deprecated since 1.24
2520 const PROP_LIST = 'LIST';
2521 /// @deprecated since 1.24
2522 const PROP_TYPE = 0;
2523 /// @deprecated since 1.24
2524 const PROP_NULLABLE = 1;
2525
2526 /**
2527 * Formerly returned a string that identifies the version of the extending
2528 * class. Typically included the class name, the svn revision, timestamp,
2529 * and last author. Usually done with SVN's Id keyword
2530 *
2531 * @deprecated since 1.21, version string is no longer supported
2532 * @return string
2533 */
2534 public function getVersion() {
2535 wfDeprecated( __METHOD__, '1.21' );
2536 return '';
2537 }
2538
2539 /**
2540 * Formerly used to fetch a list of possible properites in the result,
2541 * somehow organized with respect to the prop parameter that causes them to
2542 * be returned. The specific semantics of the return value was never
2543 * specified. Since this was never possible to be accurately updated, it
2544 * has been removed.
2545 *
2546 * @deprecated since 1.24
2547 * @return array|bool
2548 */
2549 protected function getResultProperties() {
2550 wfDeprecated( __METHOD__, '1.24' );
2551 return false;
2552 }
2553
2554 /**
2555 * @see self::getResultProperties()
2556 * @deprecated since 1.24
2557 * @return array|bool
2558 */
2559 public function getFinalResultProperties() {
2560 wfDeprecated( __METHOD__, '1.24' );
2561 return array();
2562 }
2563
2564 /**
2565 * @see self::getResultProperties()
2566 * @deprecated since 1.24
2567 */
2568 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2569 wfDeprecated( __METHOD__, '1.24' );
2570 }
2571
2572 /**
2573 * @see self::getPossibleErrors()
2574 * @deprecated since 1.24
2575 * @return array
2576 */
2577 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2578 wfDeprecated( __METHOD__, '1.24' );
2579 return array();
2580 }
2581
2582 /**
2583 * @see self::getPossibleErrors()
2584 * @deprecated since 1.24
2585 * @return array
2586 */
2587 public function getRequireMaxOneParameterErrorMessages( $params ) {
2588 wfDeprecated( __METHOD__, '1.24' );
2589 return array();
2590 }
2591
2592 /**
2593 * @see self::getPossibleErrors()
2594 * @deprecated since 1.24
2595 * @return array
2596 */
2597 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2598 wfDeprecated( __METHOD__, '1.24' );
2599 return array();
2600 }
2601
2602 /**
2603 * @see self::getPossibleErrors()
2604 * @deprecated since 1.24
2605 * @return array
2606 */
2607 public function getTitleOrPageIdErrorMessage() {
2608 wfDeprecated( __METHOD__, '1.24' );
2609 return array();
2610 }
2611
2612 /**
2613 * This formerly attempted to return a list of all possible errors returned
2614 * by the module. However, this was impossible to maintain in many cases
2615 * since errors could come from other areas of MediaWiki and in some cases
2616 * from arbitrary extension hooks. Since a partial list claiming to be
2617 * comprehensive is unlikely to be useful, it was removed.
2618 *
2619 * @deprecated since 1.24
2620 * @return array
2621 */
2622 public function getPossibleErrors() {
2623 wfDeprecated( __METHOD__, '1.24' );
2624 return array();
2625 }
2626
2627 /**
2628 * @see self::getPossibleErrors()
2629 * @deprecated since 1.24
2630 * @return array
2631 */
2632 public function getFinalPossibleErrors() {
2633 wfDeprecated( __METHOD__, '1.24' );
2634 return array();
2635 }
2636
2637 /**
2638 * @see self::getPossibleErrors()
2639 * @deprecated since 1.24
2640 * @return array
2641 */
2642 public function parseErrors( $errors ) {
2643 wfDeprecated( __METHOD__, '1.24' );
2644 return array();
2645 }
2646
2647 /**
2648 * Returns the description string for this module
2649 *
2650 * Ignored if an i18n message exists for
2651 * "apihelp-{$this->getModulePath()}-description".
2652 *
2653 * @deprecated since 1.25
2654 * @return Message|string|array
2655 */
2656 protected function getDescription() {
2657 return false;
2658 }
2659
2660 /**
2661 * Returns an array of parameter descriptions.
2662 *
2663 * For each parameter, ignored if an i18n message exists for the parameter.
2664 * By default that message is
2665 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2666 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2667 * self::getFinalParams().
2668 *
2669 * @deprecated since 1.25
2670 * @return array|bool False on no parameter descriptions
2671 */
2672 protected function getParamDescription() {
2673 return array();
2674 }
2675
2676 /**
2677 * Returns usage examples for this module.
2678 *
2679 * Return value as an array is either:
2680 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2681 * values
2682 * - sequential numeric keys with even-numbered keys being display-text
2683 * and odd-numbered keys being partial urls
2684 * - partial URLs as keys with display-text (string or array-to-be-joined)
2685 * as values
2686 * Return value as a string is the same as an array with a numeric key and
2687 * that value, and boolean false means "no examples".
2688 *
2689 * @deprecated since 1.25, use getExamplesMessages() instead
2690 * @return bool|string|array
2691 */
2692 protected function getExamples() {
2693 return false;
2694 }
2695
2696 /**
2697 * Generates help message for this module, or false if there is no description
2698 * @deprecated since 1.25
2699 * @return string|bool
2700 */
2701 public function makeHelpMsg() {
2702 wfDeprecated( __METHOD__, '1.25' );
2703 static $lnPrfx = "\n ";
2704
2705 $msg = $this->getFinalDescription();
2706
2707 if ( $msg !== false ) {
2708
2709 if ( !is_array( $msg ) ) {
2710 $msg = array(
2711 $msg
2712 );
2713 }
2714 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2715
2716 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2717
2718 if ( $this->isReadMode() ) {
2719 $msg .= "\nThis module requires read rights";
2720 }
2721 if ( $this->isWriteMode() ) {
2722 $msg .= "\nThis module requires write rights";
2723 }
2724 if ( $this->mustBePosted() ) {
2725 $msg .= "\nThis module only accepts POST requests";
2726 }
2727 if ( $this->isReadMode() || $this->isWriteMode() ||
2728 $this->mustBePosted()
2729 ) {
2730 $msg .= "\n";
2731 }
2732
2733 // Parameters
2734 $paramsMsg = $this->makeHelpMsgParameters();
2735 if ( $paramsMsg !== false ) {
2736 $msg .= "Parameters:\n$paramsMsg";
2737 }
2738
2739 $examples = $this->getExamples();
2740 if ( $examples ) {
2741 if ( !is_array( $examples ) ) {
2742 $examples = array(
2743 $examples
2744 );
2745 }
2746 $msg .= "Example" . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
2747 foreach ( $examples as $k => $v ) {
2748 if ( is_numeric( $k ) ) {
2749 $msg .= " $v\n";
2750 } else {
2751 if ( is_array( $v ) ) {
2752 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2753 } else {
2754 $msgExample = " $v";
2755 }
2756 $msgExample .= ":";
2757 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2758 }
2759 }
2760 }
2761 }
2762
2763 return $msg;
2764 }
2765
2766 /**
2767 * @deprecated since 1.25
2768 * @param string $item
2769 * @return string
2770 */
2771 private function indentExampleText( $item ) {
2772 return " " . $item;
2773 }
2774
2775 /**
2776 * @deprecated since 1.25
2777 * @param string $prefix Text to split output items
2778 * @param string $title What is being output
2779 * @param string|array $input
2780 * @return string
2781 */
2782 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2783 wfDeprecated( __METHOD__, '1.25' );
2784 if ( $input === false ) {
2785 return '';
2786 }
2787 if ( !is_array( $input ) ) {
2788 $input = array( $input );
2789 }
2790
2791 if ( count( $input ) > 0 ) {
2792 if ( $title ) {
2793 $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n ";
2794 } else {
2795 $msg = ' ';
2796 }
2797 $msg .= implode( $prefix, $input ) . "\n";
2798
2799 return $msg;
2800 }
2801
2802 return '';
2803 }
2804
2805 /**
2806 * Generates the parameter descriptions for this module, to be displayed in the
2807 * module's help.
2808 * @deprecated since 1.25
2809 * @return string|bool
2810 */
2811 public function makeHelpMsgParameters() {
2812 wfDeprecated( __METHOD__, '1.25' );
2813 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
2814 if ( $params ) {
2815 $paramsDescription = $this->getFinalParamDescription();
2816 $msg = '';
2817 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2818 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2819 foreach ( $params as $paramName => $paramSettings ) {
2820 $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
2821 if ( is_array( $desc ) ) {
2822 $desc = implode( $paramPrefix, $desc );
2823 }
2824
2825 // handle shorthand
2826 if ( !is_array( $paramSettings ) ) {
2827 $paramSettings = array(
2828 self::PARAM_DFLT => $paramSettings,
2829 );
2830 }
2831
2832 // handle missing type
2833 if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) {
2834 $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] )
2835 ? $paramSettings[ApiBase::PARAM_DFLT]
2836 : null;
2837 if ( is_bool( $dflt ) ) {
2838 $paramSettings[ApiBase::PARAM_TYPE] = 'boolean';
2839 } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
2840 $paramSettings[ApiBase::PARAM_TYPE] = 'string';
2841 } elseif ( is_int( $dflt ) ) {
2842 $paramSettings[ApiBase::PARAM_TYPE] = 'integer';
2843 }
2844 }
2845
2846 if ( isset( $paramSettings[self::PARAM_DEPRECATED] )
2847 && $paramSettings[self::PARAM_DEPRECATED]
2848 ) {
2849 $desc = "DEPRECATED! $desc";
2850 }
2851
2852 if ( isset( $paramSettings[self::PARAM_REQUIRED] )
2853 && $paramSettings[self::PARAM_REQUIRED]
2854 ) {
2855 $desc .= $paramPrefix . "This parameter is required";
2856 }
2857
2858 $type = isset( $paramSettings[self::PARAM_TYPE] )
2859 ? $paramSettings[self::PARAM_TYPE]
2860 : null;
2861 if ( isset( $type ) ) {
2862 $hintPipeSeparated = true;
2863 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
2864 ? $paramSettings[self::PARAM_ISMULTI]
2865 : false;
2866 if ( $multi ) {
2867 $prompt = 'Values (separate with \'|\'): ';
2868 } else {
2869 $prompt = 'One value: ';
2870 }
2871
2872 if ( $type === 'submodule' ) {
2873 if ( isset( $paramSettings[self::PARAM_SUBMODULE_MAP] ) ) {
2874 $type = array_keys( $paramSettings[self::PARAM_SUBMODULE_MAP] );
2875 } else {
2876 $type = $this->getModuleManager()->getNames( $paramName );
2877 }
2878 sort( $type );
2879 }
2880 if ( is_array( $type ) ) {
2881 $choices = array();
2882 $nothingPrompt = '';
2883 foreach ( $type as $t ) {
2884 if ( $t === '' ) {
2885 $nothingPrompt = 'Can be empty, or ';
2886 } else {
2887 $choices[] = $t;
2888 }
2889 }
2890 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2891 $choicesstring = implode( ', ', $choices );
2892 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2893 $hintPipeSeparated = false;
2894 } else {
2895 switch ( $type ) {
2896 case 'namespace':
2897 // Special handling because namespaces are
2898 // type-limited, yet they are not given
2899 $desc .= $paramPrefix . $prompt;
2900 $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
2901 100, $descWordwrap );
2902 $hintPipeSeparated = false;
2903 break;
2904 case 'limit':
2905 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2906 if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
2907 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2908 }
2909 $desc .= ' allowed';
2910 break;
2911 case 'integer':
2912 $s = $multi ? 's' : '';
2913 $hasMin = isset( $paramSettings[self::PARAM_MIN] );
2914 $hasMax = isset( $paramSettings[self::PARAM_MAX] );
2915 if ( $hasMin || $hasMax ) {
2916 if ( !$hasMax ) {
2917 $intRangeStr = "The value$s must be no less than " .
2918 "{$paramSettings[self::PARAM_MIN]}";
2919 } elseif ( !$hasMin ) {
2920 $intRangeStr = "The value$s must be no more than " .
2921 "{$paramSettings[self::PARAM_MAX]}";
2922 } else {
2923 $intRangeStr = "The value$s must be between " .
2924 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2925 }
2926
2927 $desc .= $paramPrefix . $intRangeStr;
2928 }
2929 break;
2930 case 'upload':
2931 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2932 break;
2933 }
2934 }
2935
2936 if ( $multi ) {
2937 if ( $hintPipeSeparated ) {
2938 $desc .= $paramPrefix . "Separate values with '|'";
2939 }
2940
2941 $isArray = is_array( $type );
2942 if ( !$isArray
2943 || $isArray && count( $type ) > self::LIMIT_SML1
2944 ) {
2945 $desc .= $paramPrefix . "Maximum number of values " .
2946 self::LIMIT_SML1 . " (" . self::LIMIT_SML2 . " for bots)";
2947 }
2948 }
2949 }
2950
2951 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
2952 if ( !is_null( $default ) && $default !== false ) {
2953 $desc .= $paramPrefix . "Default: $default";
2954 }
2955
2956 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2957 }
2958
2959 return $msg;
2960 }
2961
2962 return false;
2963 }
2964
2965 /**
2966 * @deprecated since 1.25, always returns empty string
2967 * @param IDatabase|bool $db
2968 * @return string
2969 */
2970 public function getModuleProfileName( $db = false ) {
2971 wfDeprecated( __METHOD__, '1.25' );
2972 return '';
2973 }
2974
2975 /**
2976 * @deprecated since 1.25
2977 */
2978 public function profileIn() {
2979 // No wfDeprecated() yet because extensions call this and might need to
2980 // keep doing so for BC.
2981 }
2982
2983 /**
2984 * @deprecated since 1.25
2985 */
2986 public function profileOut() {
2987 // No wfDeprecated() yet because extensions call this and might need to
2988 // keep doing so for BC.
2989 }
2990
2991 /**
2992 * @deprecated since 1.25
2993 */
2994 public function safeProfileOut() {
2995 wfDeprecated( __METHOD__, '1.25' );
2996 }
2997
2998 /**
2999 * @deprecated since 1.25, always returns 0
3000 * @return float
3001 */
3002 public function getProfileTime() {
3003 wfDeprecated( __METHOD__, '1.25' );
3004 return 0;
3005 }
3006
3007 /**
3008 * @deprecated since 1.25
3009 */
3010 public function profileDBIn() {
3011 wfDeprecated( __METHOD__, '1.25' );
3012 }
3013
3014 /**
3015 * @deprecated since 1.25
3016 */
3017 public function profileDBOut() {
3018 wfDeprecated( __METHOD__, '1.25' );
3019 }
3020
3021 /**
3022 * @deprecated since 1.25, always returns 0
3023 * @return float
3024 */
3025 public function getProfileDBTime() {
3026 wfDeprecated( __METHOD__, '1.25' );
3027 return 0;
3028 }
3029
3030 /**
3031 * Get the result data array (read-only)
3032 * @deprecated since 1.25, use $this->getResult() methods instead
3033 * @return array
3034 */
3035 public function getResultData() {
3036 wfDeprecated( __METHOD__, '1.25' );
3037 return $this->getResult()->getData();
3038 }
3039
3040 /**
3041 * Call wfTransactionalTimeLimit() if this request was POSTed
3042 * @since 1.26
3043 */
3044 protected function useTransactionalTimeLimit() {
3045 if ( $this->getRequest()->wasPosted() ) {
3046 wfTransactionalTimeLimit();
3047 }
3048 }
3049
3050 /**@}*/
3051 }
3052
3053 /**
3054 * For really cool vim folding this needs to be at the end:
3055 * vim: foldmarker=@{,@} foldmethod=marker
3056 */