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