ApiBase.php 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648
  1. <?php
  2. /**
  3. * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. */
  22. use MediaWiki\Block\AbstractBlock;
  23. use MediaWiki\Block\DatabaseBlock;
  24. use MediaWiki\Linker\LinkTarget;
  25. use MediaWiki\MediaWikiServices;
  26. use MediaWiki\Permissions\PermissionManager;
  27. use Wikimedia\Rdbms\IDatabase;
  28. /**
  29. * This abstract class implements many basic API functions, and is the base of
  30. * all API classes.
  31. * The class functions are divided into several areas of functionality:
  32. *
  33. * Module parameters: Derived classes can define getAllowedParams() to specify
  34. * which parameters to expect, how to parse and validate them.
  35. *
  36. * Self-documentation: code to allow the API to document its own state
  37. *
  38. * @ingroup API
  39. */
  40. abstract class ApiBase extends ContextSource {
  41. use ApiBlockInfoTrait;
  42. /**
  43. * @name Constants for ::getAllowedParams() arrays
  44. * These constants are keys in the arrays returned by ::getAllowedParams()
  45. * and accepted by ::getParameterFromSettings() that define how the
  46. * parameters coming in from the request are to be interpreted.
  47. * @{
  48. */
  49. /** (null|boolean|integer|string) Default value of the parameter. */
  50. const PARAM_DFLT = 0;
  51. /** (boolean) Accept multiple pipe-separated values for this parameter (e.g. titles)? */
  52. const PARAM_ISMULTI = 1;
  53. /**
  54. * (string|string[]) Either an array of allowed value strings, or a string
  55. * type as described below. If not specified, will be determined from the
  56. * type of PARAM_DFLT.
  57. *
  58. * Supported string types are:
  59. * - boolean: A boolean parameter, returned as false if the parameter is
  60. * omitted and true if present (even with a falsey value, i.e. it works
  61. * like HTML checkboxes). PARAM_DFLT must be boolean false, if specified.
  62. * Cannot be used with PARAM_ISMULTI.
  63. * - integer: An integer value. See also PARAM_MIN, PARAM_MAX, and
  64. * PARAM_RANGE_ENFORCE.
  65. * - limit: An integer or the string 'max'. Default lower limit is 0 (but
  66. * see PARAM_MIN), and requires that PARAM_MAX and PARAM_MAX2 be
  67. * specified. Cannot be used with PARAM_ISMULTI.
  68. * - namespace: An integer representing a MediaWiki namespace. Forces PARAM_ALL = true to
  69. * support easily specifying all namespaces.
  70. * - NULL: Any string.
  71. * - password: Any non-empty string. Input value is private or sensitive.
  72. * <input type="password"> would be an appropriate HTML form field.
  73. * - string: Any non-empty string, not expected to be very long or contain newlines.
  74. * <input type="text"> would be an appropriate HTML form field.
  75. * - submodule: The name of a submodule of this module, see PARAM_SUBMODULE_MAP.
  76. * - tags: A string naming an existing, explicitly-defined tag. Should usually be
  77. * used with PARAM_ISMULTI.
  78. * - text: Any non-empty string, expected to be very long or contain newlines.
  79. * <textarea> would be an appropriate HTML form field.
  80. * - timestamp: A timestamp in any format recognized by MWTimestamp, or the
  81. * string 'now' representing the current timestamp. Will be returned in
  82. * TS_MW format.
  83. * - user: A MediaWiki username or IP. Will be returned normalized but not canonicalized.
  84. * - upload: An uploaded file. Will be returned as a WebRequestUpload object.
  85. * Cannot be used with PARAM_ISMULTI.
  86. */
  87. const PARAM_TYPE = 2;
  88. /** (integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
  89. const PARAM_MAX = 3;
  90. /**
  91. * (integer) Max value allowed for the parameter for users with the
  92. * apihighlimits right, for PARAM_TYPE 'limit'.
  93. */
  94. const PARAM_MAX2 = 4;
  95. /** (integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'. */
  96. const PARAM_MIN = 5;
  97. /** (boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true? */
  98. const PARAM_ALLOW_DUPLICATES = 6;
  99. /** (boolean) Is the parameter deprecated (will show a warning)? */
  100. const PARAM_DEPRECATED = 7;
  101. /**
  102. * (boolean) Is the parameter required?
  103. * @since 1.17
  104. */
  105. const PARAM_REQUIRED = 8;
  106. /**
  107. * (boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
  108. * @since 1.17
  109. */
  110. const PARAM_RANGE_ENFORCE = 9;
  111. /**
  112. * (string|array|Message) Specify an alternative i18n documentation message
  113. * for this parameter. Default is apihelp-{$path}-param-{$param}.
  114. * @since 1.25
  115. */
  116. const PARAM_HELP_MSG = 10;
  117. /**
  118. * ((string|array|Message)[]) Specify additional i18n messages to append to
  119. * the normal message for this parameter.
  120. * @since 1.25
  121. */
  122. const PARAM_HELP_MSG_APPEND = 11;
  123. /**
  124. * (array) Specify additional information tags for the parameter. Value is
  125. * an array of arrays, with the first member being the 'tag' for the info
  126. * and the remaining members being the values. In the help, this is
  127. * formatted using apihelp-{$path}-paraminfo-{$tag}, which is passed
  128. * $1 = count, $2 = comma-joined list of values, $3 = module prefix.
  129. * @since 1.25
  130. */
  131. const PARAM_HELP_MSG_INFO = 12;
  132. /**
  133. * (string[]) When PARAM_TYPE is an array, this may be an array mapping
  134. * those values to page titles which will be linked in the help.
  135. * @since 1.25
  136. */
  137. const PARAM_VALUE_LINKS = 13;
  138. /**
  139. * ((string|array|Message)[]) When PARAM_TYPE is an array, this is an array
  140. * mapping those values to $msg for ApiBase::makeMessage(). Any value not
  141. * having a mapping will use apihelp-{$path}-paramvalue-{$param}-{$value}.
  142. * Specify an empty array to use the default message key for all values.
  143. * @since 1.25
  144. */
  145. const PARAM_HELP_MSG_PER_VALUE = 14;
  146. /**
  147. * (string[]) When PARAM_TYPE is 'submodule', map parameter values to
  148. * submodule paths. Default is to use all modules in
  149. * $this->getModuleManager() in the group matching the parameter name.
  150. * @since 1.26
  151. */
  152. const PARAM_SUBMODULE_MAP = 15;
  153. /**
  154. * (string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix
  155. * added by ApiQueryGeneratorBase (and similar if anything else ever does that).
  156. * @since 1.26
  157. */
  158. const PARAM_SUBMODULE_PARAM_PREFIX = 16;
  159. /**
  160. * (boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,
  161. * this allows for an asterisk ('*') to be passed in place of a pipe-separated list of
  162. * every possible value. If a string is set, it will be used in place of the asterisk.
  163. * @since 1.29
  164. */
  165. const PARAM_ALL = 17;
  166. /**
  167. * (int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
  168. * @since 1.29
  169. */
  170. const PARAM_EXTRA_NAMESPACES = 18;
  171. /**
  172. * (boolean) Is the parameter sensitive? Note 'password'-type fields are
  173. * always sensitive regardless of the value of this field.
  174. * @since 1.29
  175. */
  176. const PARAM_SENSITIVE = 19;
  177. /**
  178. * (array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
  179. * Keys are the deprecated parameter values, values define the warning
  180. * message to emit: either boolean true (to use a default message) or a
  181. * $msg for ApiBase::makeMessage().
  182. * @since 1.30
  183. */
  184. const PARAM_DEPRECATED_VALUES = 20;
  185. /**
  186. * (integer) Maximum number of values, for normal users. Must be used with PARAM_ISMULTI.
  187. * @since 1.30
  188. */
  189. const PARAM_ISMULTI_LIMIT1 = 21;
  190. /**
  191. * (integer) Maximum number of values, for users with the apihighimits right.
  192. * Must be used with PARAM_ISMULTI.
  193. * @since 1.30
  194. */
  195. const PARAM_ISMULTI_LIMIT2 = 22;
  196. /**
  197. * (integer) Maximum length of a string in bytes (in UTF-8 encoding).
  198. * @since 1.31
  199. */
  200. const PARAM_MAX_BYTES = 23;
  201. /**
  202. * (integer) Maximum length of a string in characters (unicode codepoints).
  203. * @since 1.31
  204. */
  205. const PARAM_MAX_CHARS = 24;
  206. /**
  207. * (array) Indicate that this is a templated parameter, and specify replacements. Keys are the
  208. * placeholders in the parameter name and values are the names of (unprefixed) parameters from
  209. * which the replacement values are taken.
  210. *
  211. * For example, a parameter "foo-{ns}-{title}" could be defined with
  212. * PARAM_TEMPLATE_VARS => [ 'ns' => 'namespaces', 'title' => 'titles' ]. Then a query for
  213. * namespaces=0|1&titles=X|Y would support parameters foo-0-X, foo-0-Y, foo-1-X, and foo-1-Y.
  214. *
  215. * All placeholders must be present in the parameter's name. Each target parameter must have
  216. * PARAM_ISMULTI true. If a target is itself a templated parameter, its PARAM_TEMPLATE_VARS must
  217. * be a subset of the referring parameter's, mapping the same placeholders to the same targets.
  218. * A parameter cannot target itself.
  219. *
  220. * @since 1.32
  221. */
  222. const PARAM_TEMPLATE_VARS = 25;
  223. /** @} */
  224. const ALL_DEFAULT_STRING = '*';
  225. /** Fast query, standard limit. */
  226. const LIMIT_BIG1 = 500;
  227. /** Fast query, apihighlimits limit. */
  228. const LIMIT_BIG2 = 5000;
  229. /** Slow query, standard limit. */
  230. const LIMIT_SML1 = 50;
  231. /** Slow query, apihighlimits limit. */
  232. const LIMIT_SML2 = 500;
  233. /**
  234. * getAllowedParams() flag: When set, the result could take longer to generate,
  235. * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
  236. * @since 1.21
  237. */
  238. const GET_VALUES_FOR_HELP = 1;
  239. /** @var array Maps extension paths to info arrays */
  240. private static $extensionInfo = null;
  241. /** @var stdClass[][] Cache for self::filterIDs() */
  242. private static $filterIDsCache = [];
  243. /** $var array Map of web UI block messages to corresponding API messages and codes */
  244. private static $blockMsgMap = [
  245. 'blockedtext' => [ 'apierror-blocked', 'blocked' ],
  246. 'blockedtext-partial' => [ 'apierror-blocked-partial', 'blocked' ],
  247. 'autoblockedtext' => [ 'apierror-autoblocked', 'autoblocked' ],
  248. 'systemblockedtext' => [ 'apierror-systemblocked', 'blocked' ],
  249. 'blockedtext-composite' => [ 'apierror-blocked', 'blocked' ],
  250. ];
  251. /** @var ApiMain */
  252. private $mMainModule;
  253. /** @var string */
  254. private $mModuleName, $mModulePrefix;
  255. private $mReplicaDB = null;
  256. private $mParamCache = [];
  257. /** @var array|null|bool */
  258. private $mModuleSource = false;
  259. /**
  260. * @param ApiMain $mainModule
  261. * @param string $moduleName Name of this module
  262. * @param string $modulePrefix Prefix to use for parameter names
  263. */
  264. public function __construct( ApiMain $mainModule, $moduleName, $modulePrefix = '' ) {
  265. $this->mMainModule = $mainModule;
  266. $this->mModuleName = $moduleName;
  267. $this->mModulePrefix = $modulePrefix;
  268. if ( !$this->isMain() ) {
  269. $this->setContext( $mainModule->getContext() );
  270. }
  271. }
  272. /************************************************************************//**
  273. * @name Methods to implement
  274. * @{
  275. */
  276. /**
  277. * Evaluates the parameters, performs the requested query, and sets up
  278. * the result. Concrete implementations of ApiBase must override this
  279. * method to provide whatever functionality their module offers.
  280. * Implementations must not produce any output on their own and are not
  281. * expected to handle any errors.
  282. *
  283. * The execute() method will be invoked directly by ApiMain immediately
  284. * before the result of the module is output. Aside from the
  285. * constructor, implementations should assume that no other methods
  286. * will be called externally on the module before the result is
  287. * processed.
  288. *
  289. * The result data should be stored in the ApiResult object available
  290. * through getResult().
  291. */
  292. abstract public function execute();
  293. /**
  294. * Get the module manager, or null if this module has no sub-modules
  295. * @since 1.21
  296. * @return ApiModuleManager
  297. */
  298. public function getModuleManager() {
  299. return null;
  300. }
  301. /**
  302. * If the module may only be used with a certain format module,
  303. * it should override this method to return an instance of that formatter.
  304. * A value of null means the default format will be used.
  305. * @note Do not use this just because you don't want to support non-json
  306. * formats. This should be used only when there is a fundamental
  307. * requirement for a specific format.
  308. * @return mixed Instance of a derived class of ApiFormatBase, or null
  309. */
  310. public function getCustomPrinter() {
  311. return null;
  312. }
  313. /**
  314. * Returns usage examples for this module.
  315. *
  316. * Return value has query strings as keys, with values being either strings
  317. * (message key), arrays (message key + parameter), or Message objects.
  318. *
  319. * Do not call this base class implementation when overriding this method.
  320. *
  321. * @since 1.25
  322. * @return array
  323. */
  324. protected function getExamplesMessages() {
  325. return [];
  326. }
  327. /**
  328. * Return links to more detailed help pages about the module.
  329. * @since 1.25, returning boolean false is deprecated
  330. * @return string|array
  331. */
  332. public function getHelpUrls() {
  333. return [];
  334. }
  335. /**
  336. * Returns an array of allowed parameters (parameter name) => (default
  337. * value) or (parameter name) => (array with PARAM_* constants as keys)
  338. * Don't call this function directly: use getFinalParams() to allow
  339. * hooks to modify parameters as needed.
  340. *
  341. * Some derived classes may choose to handle an integer $flags parameter
  342. * in the overriding methods. Callers of this method can pass zero or
  343. * more OR-ed flags like GET_VALUES_FOR_HELP.
  344. *
  345. * @return array
  346. */
  347. protected function getAllowedParams( /* $flags = 0 */ ) {
  348. // int $flags is not declared because it causes "Strict standards"
  349. // warning. Most derived classes do not implement it.
  350. return [];
  351. }
  352. /**
  353. * Indicates if this module needs maxlag to be checked
  354. * @return bool
  355. */
  356. public function shouldCheckMaxlag() {
  357. return true;
  358. }
  359. /**
  360. * Indicates whether this module requires read rights
  361. * @return bool
  362. */
  363. public function isReadMode() {
  364. return true;
  365. }
  366. /**
  367. * Indicates whether this module requires write mode
  368. *
  369. * This should return true for modules that may require synchronous database writes.
  370. * Modules that do not need such writes should also not rely on master database access,
  371. * since only read queries are needed and each master DB is a single point of failure.
  372. * Additionally, requests that only need replica DBs can be efficiently routed to any
  373. * datacenter via the Promise-Non-Write-API-Action header.
  374. *
  375. * @return bool
  376. */
  377. public function isWriteMode() {
  378. return false;
  379. }
  380. /**
  381. * Indicates whether this module must be called with a POST request
  382. * @return bool
  383. */
  384. public function mustBePosted() {
  385. return $this->needsToken() !== false;
  386. }
  387. /**
  388. * Indicates whether this module is deprecated
  389. * @since 1.25
  390. * @return bool
  391. */
  392. public function isDeprecated() {
  393. return false;
  394. }
  395. /**
  396. * Indicates whether this module is "internal"
  397. * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
  398. * @since 1.25
  399. * @return bool
  400. */
  401. public function isInternal() {
  402. return false;
  403. }
  404. /**
  405. * Returns the token type this module requires in order to execute.
  406. *
  407. * Modules are strongly encouraged to use the core 'csrf' type unless they
  408. * have specialized security needs. If the token type is not one of the
  409. * core types, you must use the ApiQueryTokensRegisterTypes hook to
  410. * register it.
  411. *
  412. * Returning a non-falsey value here will force the addition of an
  413. * appropriate 'token' parameter in self::getFinalParams(). Also,
  414. * self::mustBePosted() must return true when tokens are used.
  415. *
  416. * In previous versions of MediaWiki, true was a valid return value.
  417. * Returning true will generate errors indicating that the API module needs
  418. * updating.
  419. *
  420. * @return string|false
  421. */
  422. public function needsToken() {
  423. return false;
  424. }
  425. /**
  426. * Fetch the salt used in the Web UI corresponding to this module.
  427. *
  428. * Only override this if the Web UI uses a token with a non-constant salt.
  429. *
  430. * @since 1.24
  431. * @param array $params All supplied parameters for the module
  432. * @return string|array|null
  433. */
  434. protected function getWebUITokenSalt( array $params ) {
  435. return null;
  436. }
  437. /**
  438. * Returns data for HTTP conditional request mechanisms.
  439. *
  440. * @since 1.26
  441. * @param string $condition Condition being queried:
  442. * - last-modified: Return a timestamp representing the maximum of the
  443. * last-modified dates for all resources involved in the request. See
  444. * RFC 7232 § 2.2 for semantics.
  445. * - etag: Return an entity-tag representing the state of all resources involved
  446. * in the request. Quotes must be included. See RFC 7232 § 2.3 for semantics.
  447. * @return string|bool|null As described above, or null if no value is available.
  448. */
  449. public function getConditionalRequestData( $condition ) {
  450. return null;
  451. }
  452. /** @} */
  453. /************************************************************************//**
  454. * @name Data access methods
  455. * @{
  456. */
  457. /**
  458. * Get the name of the module being executed by this instance
  459. * @return string
  460. */
  461. public function getModuleName() {
  462. return $this->mModuleName;
  463. }
  464. /**
  465. * Get parameter prefix (usually two letters or an empty string).
  466. * @return string
  467. */
  468. public function getModulePrefix() {
  469. return $this->mModulePrefix;
  470. }
  471. /**
  472. * Get the main module
  473. * @return ApiMain
  474. */
  475. public function getMain() {
  476. return $this->mMainModule;
  477. }
  478. /**
  479. * Returns true if this module is the main module ($this === $this->mMainModule),
  480. * false otherwise.
  481. * @return bool
  482. */
  483. public function isMain() {
  484. return $this === $this->mMainModule;
  485. }
  486. /**
  487. * Get the parent of this module
  488. * @since 1.25
  489. * @return ApiBase|null
  490. */
  491. public function getParent() {
  492. return $this->isMain() ? null : $this->getMain();
  493. }
  494. /**
  495. * Returns true if the current request breaks the same-origin policy.
  496. *
  497. * For example, json with callbacks.
  498. *
  499. * https://en.wikipedia.org/wiki/Same-origin_policy
  500. *
  501. * @since 1.25
  502. * @return bool
  503. */
  504. public function lacksSameOriginSecurity() {
  505. // Main module has this method overridden
  506. // Safety - avoid infinite loop:
  507. if ( $this->isMain() ) {
  508. self::dieDebug( __METHOD__, 'base method was called on main module.' );
  509. }
  510. return $this->getMain()->lacksSameOriginSecurity();
  511. }
  512. /**
  513. * Get the path to this module
  514. *
  515. * @since 1.25
  516. * @return string
  517. */
  518. public function getModulePath() {
  519. if ( $this->isMain() ) {
  520. return 'main';
  521. } elseif ( $this->getParent()->isMain() ) {
  522. return $this->getModuleName();
  523. } else {
  524. return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
  525. }
  526. }
  527. /**
  528. * Get a module from its module path
  529. *
  530. * @since 1.25
  531. * @param string $path
  532. * @return ApiBase|null
  533. * @throws ApiUsageException
  534. */
  535. public function getModuleFromPath( $path ) {
  536. $module = $this->getMain();
  537. if ( $path === 'main' ) {
  538. return $module;
  539. }
  540. $parts = explode( '+', $path );
  541. if ( count( $parts ) === 1 ) {
  542. // In case the '+' was typed into URL, it resolves as a space
  543. $parts = explode( ' ', $path );
  544. }
  545. $count = count( $parts );
  546. for ( $i = 0; $i < $count; $i++ ) {
  547. $parent = $module;
  548. $manager = $parent->getModuleManager();
  549. if ( $manager === null ) {
  550. $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
  551. $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
  552. }
  553. $module = $manager->getModule( $parts[$i] );
  554. if ( $module === null ) {
  555. $errorPath = $i ? implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
  556. $this->dieWithError(
  557. [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
  558. 'badmodule'
  559. );
  560. }
  561. }
  562. return $module;
  563. }
  564. /**
  565. * Get the result object
  566. * @return ApiResult
  567. */
  568. public function getResult() {
  569. // Main module has getResult() method overridden
  570. // Safety - avoid infinite loop:
  571. if ( $this->isMain() ) {
  572. self::dieDebug( __METHOD__, 'base method was called on main module. ' );
  573. }
  574. return $this->getMain()->getResult();
  575. }
  576. /**
  577. * Get the error formatter
  578. * @return ApiErrorFormatter
  579. */
  580. public function getErrorFormatter() {
  581. // Main module has getErrorFormatter() method overridden
  582. // Safety - avoid infinite loop:
  583. if ( $this->isMain() ) {
  584. self::dieDebug( __METHOD__, 'base method was called on main module. ' );
  585. }
  586. return $this->getMain()->getErrorFormatter();
  587. }
  588. /**
  589. * Gets a default replica DB connection object
  590. * @return IDatabase
  591. */
  592. protected function getDB() {
  593. if ( !isset( $this->mReplicaDB ) ) {
  594. $this->mReplicaDB = wfGetDB( DB_REPLICA, 'api' );
  595. }
  596. return $this->mReplicaDB;
  597. }
  598. /**
  599. * Get the continuation manager
  600. * @return ApiContinuationManager|null
  601. */
  602. public function getContinuationManager() {
  603. // Main module has getContinuationManager() method overridden
  604. // Safety - avoid infinite loop:
  605. if ( $this->isMain() ) {
  606. self::dieDebug( __METHOD__, 'base method was called on main module. ' );
  607. }
  608. return $this->getMain()->getContinuationManager();
  609. }
  610. /**
  611. * Set the continuation manager
  612. * @param ApiContinuationManager|null $manager
  613. */
  614. public function setContinuationManager( ApiContinuationManager $manager = null ) {
  615. // Main module has setContinuationManager() method overridden
  616. // Safety - avoid infinite loop:
  617. if ( $this->isMain() ) {
  618. self::dieDebug( __METHOD__, 'base method was called on main module. ' );
  619. }
  620. $this->getMain()->setContinuationManager( $manager );
  621. }
  622. /**
  623. * Obtain a PermissionManager instance that subclasses may use in their authorization checks.
  624. *
  625. * @since 1.34
  626. * @return PermissionManager
  627. */
  628. protected function getPermissionManager(): PermissionManager {
  629. return MediaWikiServices::getInstance()->getPermissionManager();
  630. }
  631. /** @} */
  632. /************************************************************************//**
  633. * @name Parameter handling
  634. * @{
  635. */
  636. /**
  637. * Indicate if the module supports dynamically-determined parameters that
  638. * cannot be included in self::getAllowedParams().
  639. * @return string|array|Message|null Return null if the module does not
  640. * support additional dynamic parameters, otherwise return a message
  641. * describing them.
  642. */
  643. public function dynamicParameterDocumentation() {
  644. return null;
  645. }
  646. /**
  647. * This method mangles parameter name based on the prefix supplied to the constructor.
  648. * Override this method to change parameter name during runtime
  649. * @param string|string[] $paramName Parameter name
  650. * @return string|string[] Prefixed parameter name
  651. * @since 1.29 accepts an array of strings
  652. */
  653. public function encodeParamName( $paramName ) {
  654. if ( is_array( $paramName ) ) {
  655. return array_map( function ( $name ) {
  656. return $this->mModulePrefix . $name;
  657. }, $paramName );
  658. } else {
  659. return $this->mModulePrefix . $paramName;
  660. }
  661. }
  662. /**
  663. * Using getAllowedParams(), this function makes an array of the values
  664. * provided by the user, with key being the name of the variable, and
  665. * value - validated value from user or default. limits will not be
  666. * parsed if $parseLimit is set to false; use this when the max
  667. * limit is not definitive yet, e.g. when getting revisions.
  668. * @param bool|array $options If a boolean, uses that as the value for 'parseLimit'
  669. * - parseLimit: (bool, default true) Whether to parse the 'max' value for limit types
  670. * - safeMode: (bool, default false) If true, avoid throwing for parameter validation errors.
  671. * Returned parameter values might be ApiUsageException instances.
  672. * @return array
  673. */
  674. public function extractRequestParams( $options = [] ) {
  675. if ( is_bool( $options ) ) {
  676. $options = [ 'parseLimit' => $options ];
  677. }
  678. $options += [
  679. 'parseLimit' => true,
  680. 'safeMode' => false,
  681. ];
  682. $parseLimit = (bool)$options['parseLimit'];
  683. // Cache parameters, for performance and to avoid T26564.
  684. if ( !isset( $this->mParamCache[$parseLimit] ) ) {
  685. $params = $this->getFinalParams() ?: [];
  686. $results = [];
  687. $warned = [];
  688. // Process all non-templates and save templates for secondary
  689. // processing.
  690. $toProcess = [];
  691. foreach ( $params as $paramName => $paramSettings ) {
  692. if ( isset( $paramSettings[self::PARAM_TEMPLATE_VARS] ) ) {
  693. $toProcess[] = [ $paramName, $paramSettings[self::PARAM_TEMPLATE_VARS], $paramSettings ];
  694. } else {
  695. try {
  696. $results[$paramName] = $this->getParameterFromSettings(
  697. $paramName, $paramSettings, $parseLimit
  698. );
  699. } catch ( ApiUsageException $ex ) {
  700. $results[$paramName] = $ex;
  701. }
  702. }
  703. }
  704. // Now process all the templates by successively replacing the
  705. // placeholders with all client-supplied values.
  706. // This bit duplicates JavaScript logic in
  707. // ApiSandbox.PageLayout.prototype.updateTemplatedParams().
  708. // If you update this, see if that needs updating too.
  709. while ( $toProcess ) {
  710. list( $name, $targets, $settings ) = array_shift( $toProcess );
  711. foreach ( $targets as $placeholder => $target ) {
  712. if ( !array_key_exists( $target, $results ) ) {
  713. // The target wasn't processed yet, try the next one.
  714. // If all hit this case, the parameter has no expansions.
  715. continue;
  716. }
  717. if ( !is_array( $results[$target] ) || !$results[$target] ) {
  718. // The target was processed but has no (valid) values.
  719. // That means it has no expansions.
  720. break;
  721. }
  722. // Expand this target in the name and all other targets,
  723. // then requeue if there are more targets left or put in
  724. // $results if all are done.
  725. unset( $targets[$placeholder] );
  726. $placeholder = '{' . $placeholder . '}';
  727. // @phan-suppress-next-line PhanTypeNoAccessiblePropertiesForeach
  728. foreach ( $results[$target] as $value ) {
  729. if ( !preg_match( '/^[^{}]*$/', $value ) ) {
  730. // Skip values that make invalid parameter names.
  731. $encTargetName = $this->encodeParamName( $target );
  732. if ( !isset( $warned[$encTargetName][$value] ) ) {
  733. $warned[$encTargetName][$value] = true;
  734. $this->addWarning( [
  735. 'apiwarn-ignoring-invalid-templated-value',
  736. wfEscapeWikiText( $encTargetName ),
  737. wfEscapeWikiText( $value ),
  738. ] );
  739. }
  740. continue;
  741. }
  742. $newName = str_replace( $placeholder, $value, $name );
  743. if ( !$targets ) {
  744. try {
  745. $results[$newName] = $this->getParameterFromSettings( $newName, $settings, $parseLimit );
  746. } catch ( ApiUsageException $ex ) {
  747. $results[$newName] = $ex;
  748. }
  749. } else {
  750. $newTargets = [];
  751. foreach ( $targets as $k => $v ) {
  752. $newTargets[$k] = str_replace( $placeholder, $value, $v );
  753. }
  754. $toProcess[] = [ $newName, $newTargets, $settings ];
  755. }
  756. }
  757. break;
  758. }
  759. }
  760. $this->mParamCache[$parseLimit] = $results;
  761. }
  762. $ret = $this->mParamCache[$parseLimit];
  763. if ( !$options['safeMode'] ) {
  764. foreach ( $ret as $v ) {
  765. if ( $v instanceof ApiUsageException ) {
  766. throw $v;
  767. }
  768. }
  769. }
  770. return $this->mParamCache[$parseLimit];
  771. }
  772. /**
  773. * Get a value for the given parameter
  774. * @param string $paramName Parameter name
  775. * @param bool $parseLimit See extractRequestParams()
  776. * @return mixed Parameter value
  777. */
  778. protected function getParameter( $paramName, $parseLimit = true ) {
  779. $ret = $this->extractRequestParams( [
  780. 'parseLimit' => $parseLimit,
  781. 'safeMode' => true,
  782. ] )[$paramName];
  783. if ( $ret instanceof ApiUsageException ) {
  784. throw $ret;
  785. }
  786. return $ret;
  787. }
  788. /**
  789. * Die if none or more than one of a certain set of parameters is set and not false.
  790. *
  791. * @param array $params User provided set of parameters, as from $this->extractRequestParams()
  792. * @param string $required,... Names of parameters of which exactly one must be set
  793. */
  794. public function requireOnlyOneParameter( $params, $required /*...*/ ) {
  795. $required = func_get_args();
  796. array_shift( $required );
  797. $intersection = array_intersect( array_keys( array_filter( $params,
  798. [ $this, 'parameterNotEmpty' ] ) ), $required );
  799. if ( count( $intersection ) > 1 ) {
  800. $this->dieWithError( [
  801. 'apierror-invalidparammix',
  802. Message::listParam( array_map(
  803. function ( $p ) {
  804. return '<var>' . $this->encodeParamName( $p ) . '</var>';
  805. },
  806. array_values( $intersection )
  807. ) ),
  808. count( $intersection ),
  809. ] );
  810. } elseif ( count( $intersection ) == 0 ) {
  811. $this->dieWithError( [
  812. 'apierror-missingparam-one-of',
  813. Message::listParam( array_map(
  814. function ( $p ) {
  815. return '<var>' . $this->encodeParamName( $p ) . '</var>';
  816. },
  817. array_values( $required )
  818. ) ),
  819. count( $required ),
  820. ], 'missingparam' );
  821. }
  822. }
  823. /**
  824. * Die if more than one of a certain set of parameters is set and not false.
  825. *
  826. * @param array $params User provided set of parameters, as from $this->extractRequestParams()
  827. * @param string $required,... Names of parameters of which at most one must be set
  828. */
  829. public function requireMaxOneParameter( $params, $required /*...*/ ) {
  830. $required = func_get_args();
  831. array_shift( $required );
  832. $intersection = array_intersect( array_keys( array_filter( $params,
  833. [ $this, 'parameterNotEmpty' ] ) ), $required );
  834. if ( count( $intersection ) > 1 ) {
  835. $this->dieWithError( [
  836. 'apierror-invalidparammix',
  837. Message::listParam( array_map(
  838. function ( $p ) {
  839. return '<var>' . $this->encodeParamName( $p ) . '</var>';
  840. },
  841. array_values( $intersection )
  842. ) ),
  843. count( $intersection ),
  844. ] );
  845. }
  846. }
  847. /**
  848. * Die if none of a certain set of parameters is set and not false.
  849. *
  850. * @since 1.23
  851. * @param array $params User provided set of parameters, as from $this->extractRequestParams()
  852. * @param string $required,... Names of parameters of which at least one must be set
  853. */
  854. public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
  855. $required = func_get_args();
  856. array_shift( $required );
  857. $intersection = array_intersect(
  858. array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
  859. $required
  860. );
  861. if ( count( $intersection ) == 0 ) {
  862. $this->dieWithError( [
  863. 'apierror-missingparam-at-least-one-of',
  864. Message::listParam( array_map(
  865. function ( $p ) {
  866. return '<var>' . $this->encodeParamName( $p ) . '</var>';
  867. },
  868. array_values( $required )
  869. ) ),
  870. count( $required ),
  871. ], 'missingparam' );
  872. }
  873. }
  874. /**
  875. * Die if any of the specified parameters were found in the query part of
  876. * the URL rather than the post body.
  877. * @since 1.28
  878. * @param string[] $params Parameters to check
  879. * @param string $prefix Set to 'noprefix' to skip calling $this->encodeParamName()
  880. */
  881. public function requirePostedParameters( $params, $prefix = 'prefix' ) {
  882. // Skip if $wgDebugAPI is set or we're in internal mode
  883. if ( $this->getConfig()->get( 'DebugAPI' ) || $this->getMain()->isInternalMode() ) {
  884. return;
  885. }
  886. $queryValues = $this->getRequest()->getQueryValuesOnly();
  887. $badParams = [];
  888. foreach ( $params as $param ) {
  889. if ( $prefix !== 'noprefix' ) {
  890. $param = $this->encodeParamName( $param );
  891. }
  892. if ( array_key_exists( $param, $queryValues ) ) {
  893. $badParams[] = $param;
  894. }
  895. }
  896. if ( $badParams ) {
  897. $this->dieWithError(
  898. [ 'apierror-mustpostparams', implode( ', ', $badParams ), count( $badParams ) ]
  899. );
  900. }
  901. }
  902. /**
  903. * Callback function used in requireOnlyOneParameter to check whether required parameters are set
  904. *
  905. * @param object $x Parameter to check is not null/false
  906. * @return bool
  907. */
  908. private function parameterNotEmpty( $x ) {
  909. return !is_null( $x ) && $x !== false;
  910. }
  911. /**
  912. * Get a WikiPage object from a title or pageid param, if possible.
  913. * Can die, if no param is set or if the title or page id is not valid.
  914. *
  915. * @param array $params User provided set of parameters, as from $this->extractRequestParams()
  916. * @param bool|string $load Whether load the object's state from the database:
  917. * - false: don't load (if the pageid is given, it will still be loaded)
  918. * - 'fromdb': load from a replica DB
  919. * - 'fromdbmaster': load from the master database
  920. * @return WikiPage
  921. */
  922. public function getTitleOrPageId( $params, $load = false ) {
  923. $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
  924. $pageObj = null;
  925. if ( isset( $params['title'] ) ) {
  926. $titleObj = Title::newFromText( $params['title'] );
  927. if ( !$titleObj || $titleObj->isExternal() ) {
  928. $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
  929. }
  930. if ( !$titleObj->canExist() ) {
  931. $this->dieWithError( 'apierror-pagecannotexist' );
  932. }
  933. $pageObj = WikiPage::factory( $titleObj );
  934. if ( $load !== false ) {
  935. $pageObj->loadPageData( $load );
  936. }
  937. } elseif ( isset( $params['pageid'] ) ) {
  938. if ( $load === false ) {
  939. $load = 'fromdb';
  940. }
  941. $pageObj = WikiPage::newFromID( $params['pageid'], $load );
  942. if ( !$pageObj ) {
  943. $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
  944. }
  945. }
  946. return $pageObj;
  947. }
  948. /**
  949. * Get a Title object from a title or pageid param, if possible.
  950. * Can die, if no param is set or if the title or page id is not valid.
  951. *
  952. * @since 1.29
  953. * @param array $params User provided set of parameters, as from $this->extractRequestParams()
  954. * @return Title
  955. */
  956. public function getTitleFromTitleOrPageId( $params ) {
  957. $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
  958. $titleObj = null;
  959. if ( isset( $params['title'] ) ) {
  960. $titleObj = Title::newFromText( $params['title'] );
  961. if ( !$titleObj || $titleObj->isExternal() ) {
  962. $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
  963. }
  964. return $titleObj;
  965. } elseif ( isset( $params['pageid'] ) ) {
  966. $titleObj = Title::newFromID( $params['pageid'] );
  967. if ( !$titleObj ) {
  968. $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
  969. }
  970. }
  971. return $titleObj;
  972. }
  973. /**
  974. * Return true if we're to watch the page, false if not, null if no change.
  975. * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
  976. * @param Title $titleObj The page under consideration
  977. * @param string|null $userOption The user option to consider when $watchlist=preferences.
  978. * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
  979. * @return bool
  980. */
  981. protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
  982. $userWatching = $this->getUser()->isWatched( $titleObj, User::IGNORE_USER_RIGHTS );
  983. switch ( $watchlist ) {
  984. case 'watch':
  985. return true;
  986. case 'unwatch':
  987. return false;
  988. case 'preferences':
  989. # If the user is already watching, don't bother checking
  990. if ( $userWatching ) {
  991. return true;
  992. }
  993. # If no user option was passed, use watchdefault and watchcreations
  994. if ( is_null( $userOption ) ) {
  995. return $this->getUser()->getBoolOption( 'watchdefault' ) ||
  996. $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
  997. }
  998. # Watch the article based on the user preference
  999. return $this->getUser()->getBoolOption( $userOption );
  1000. case 'nochange':
  1001. return $userWatching;
  1002. default:
  1003. return $userWatching;
  1004. }
  1005. }
  1006. /**
  1007. * Using the settings determine the value for the given parameter
  1008. *
  1009. * @param string $paramName Parameter name
  1010. * @param array|mixed $paramSettings Default value or an array of settings
  1011. * using PARAM_* constants.
  1012. * @param bool $parseLimit Whether to parse and validate 'limit' parameters
  1013. * @return mixed Parameter value
  1014. */
  1015. protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
  1016. // Some classes may decide to change parameter names
  1017. $encParamName = $this->encodeParamName( $paramName );
  1018. // Shorthand
  1019. if ( !is_array( $paramSettings ) ) {
  1020. $paramSettings = [
  1021. self::PARAM_DFLT => $paramSettings,
  1022. ];
  1023. }
  1024. $default = $paramSettings[self::PARAM_DFLT] ?? null;
  1025. $multi = $paramSettings[self::PARAM_ISMULTI] ?? false;
  1026. $multiLimit1 = $paramSettings[self::PARAM_ISMULTI_LIMIT1] ?? null;
  1027. $multiLimit2 = $paramSettings[self::PARAM_ISMULTI_LIMIT2] ?? null;
  1028. $type = $paramSettings[self::PARAM_TYPE] ?? null;
  1029. $dupes = $paramSettings[self::PARAM_ALLOW_DUPLICATES] ?? false;
  1030. $deprecated = $paramSettings[self::PARAM_DEPRECATED] ?? false;
  1031. $deprecatedValues = $paramSettings[self::PARAM_DEPRECATED_VALUES] ?? [];
  1032. $required = $paramSettings[self::PARAM_REQUIRED] ?? false;
  1033. $allowAll = $paramSettings[self::PARAM_ALL] ?? false;
  1034. // When type is not given, and no choices, the type is the same as $default
  1035. if ( !isset( $type ) ) {
  1036. if ( isset( $default ) ) {
  1037. $type = gettype( $default );
  1038. } else {
  1039. $type = 'NULL'; // allow everything
  1040. }
  1041. }
  1042. if ( $type == 'password' || !empty( $paramSettings[self::PARAM_SENSITIVE] ) ) {
  1043. $this->getMain()->markParamsSensitive( $encParamName );
  1044. }
  1045. if ( $type == 'boolean' ) {
  1046. if ( isset( $default ) && $default !== false ) {
  1047. // Having a default value of anything other than 'false' is not allowed
  1048. self::dieDebug(
  1049. __METHOD__,
  1050. "Boolean param $encParamName's default is set to '$default'. " .
  1051. 'Boolean parameters must default to false.'
  1052. );
  1053. }
  1054. $value = $this->getMain()->getCheck( $encParamName );
  1055. $provided = $value;
  1056. } elseif ( $type == 'upload' ) {
  1057. if ( isset( $default ) ) {
  1058. // Having a default value is not allowed
  1059. self::dieDebug(
  1060. __METHOD__,
  1061. "File upload param $encParamName's default is set to " .
  1062. "'$default'. File upload parameters may not have a default." );
  1063. }
  1064. if ( $multi ) {
  1065. self::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
  1066. }
  1067. $value = $this->getMain()->getUpload( $encParamName );
  1068. $provided = $value->exists();
  1069. if ( !$value->exists() ) {
  1070. // This will get the value without trying to normalize it
  1071. // (because trying to normalize a large binary file
  1072. // accidentally uploaded as a field fails spectacularly)
  1073. $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
  1074. if ( $value !== null ) {
  1075. $this->dieWithError(
  1076. [ 'apierror-badupload', $encParamName ],
  1077. "badupload_{$encParamName}"
  1078. );
  1079. }
  1080. }
  1081. } else {
  1082. $value = $this->getMain()->getVal( $encParamName, $default );
  1083. $provided = $this->getMain()->getCheck( $encParamName );
  1084. if ( isset( $value ) && $type == 'namespace' ) {
  1085. $type = MediaWikiServices::getInstance()->getNamespaceInfo()->
  1086. getValidNamespaces();
  1087. if ( isset( $paramSettings[self::PARAM_EXTRA_NAMESPACES] ) &&
  1088. is_array( $paramSettings[self::PARAM_EXTRA_NAMESPACES] )
  1089. ) {
  1090. $type = array_merge( $type, $paramSettings[self::PARAM_EXTRA_NAMESPACES] );
  1091. }
  1092. // Namespace parameters allow ALL_DEFAULT_STRING to be used to
  1093. // specify all namespaces irrespective of PARAM_ALL.
  1094. $allowAll = true;
  1095. }
  1096. if ( isset( $value ) && $type == 'submodule' ) {
  1097. if ( isset( $paramSettings[self::PARAM_SUBMODULE_MAP] ) ) {
  1098. $type = array_keys( $paramSettings[self::PARAM_SUBMODULE_MAP] );
  1099. } else {
  1100. $type = $this->getModuleManager()->getNames( $paramName );
  1101. }
  1102. }
  1103. $request = $this->getMain()->getRequest();
  1104. $rawValue = $request->getRawVal( $encParamName );
  1105. if ( $rawValue === null ) {
  1106. $rawValue = $default;
  1107. }
  1108. // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
  1109. if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
  1110. if ( $multi ) {
  1111. // This loses the potential checkTitleEncoding() transformation done by
  1112. // WebRequest for $_GET. Let's call that a feature.
  1113. $value = implode( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
  1114. } else {
  1115. $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
  1116. }
  1117. }
  1118. // Check for NFC normalization, and warn
  1119. if ( $rawValue !== $value ) {
  1120. $this->handleParamNormalization( $paramName, $value, $rawValue );
  1121. }
  1122. }
  1123. $allSpecifier = ( is_string( $allowAll ) ? $allowAll : self::ALL_DEFAULT_STRING );
  1124. if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
  1125. self::dieDebug(
  1126. __METHOD__,
  1127. "For param $encParamName, PARAM_ALL collides with a possible value" );
  1128. }
  1129. if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
  1130. $value = $this->parseMultiValue(
  1131. $encParamName,
  1132. $value,
  1133. $multi,
  1134. is_array( $type ) ? $type : null,
  1135. $allowAll ? $allSpecifier : null,
  1136. $multiLimit1,
  1137. $multiLimit2
  1138. );
  1139. }
  1140. if ( isset( $value ) ) {
  1141. // More validation only when choices were not given
  1142. // choices were validated in parseMultiValue()
  1143. if ( !is_array( $type ) ) {
  1144. switch ( $type ) {
  1145. case 'NULL': // nothing to do
  1146. break;
  1147. case 'string':
  1148. case 'text':
  1149. case 'password':
  1150. if ( $required && $value === '' ) {
  1151. $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
  1152. }
  1153. break;
  1154. case 'integer': // Force everything using intval() and optionally validate limits
  1155. $min = $paramSettings[self::PARAM_MIN] ?? null;
  1156. $max = $paramSettings[self::PARAM_MAX] ?? null;
  1157. $enforceLimits = $paramSettings[self::PARAM_RANGE_ENFORCE] ?? false;
  1158. if ( is_array( $value ) ) {
  1159. $value = array_map( 'intval', $value );
  1160. if ( !is_null( $min ) || !is_null( $max ) ) {
  1161. foreach ( $value as &$v ) {
  1162. $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
  1163. }
  1164. }
  1165. } else {
  1166. $value = (int)$value;
  1167. if ( !is_null( $min ) || !is_null( $max ) ) {
  1168. $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
  1169. }
  1170. }
  1171. break;
  1172. case 'limit':
  1173. // Must be a number or 'max'
  1174. if ( $value !== 'max' ) {
  1175. $value = (int)$value;
  1176. }
  1177. if ( $multi ) {
  1178. self::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
  1179. }
  1180. if ( !$parseLimit ) {
  1181. // Don't do min/max validation and don't parse 'max'
  1182. break;
  1183. }
  1184. if ( !isset( $paramSettings[self::PARAM_MAX] )
  1185. || !isset( $paramSettings[self::PARAM_MAX2] )
  1186. ) {
  1187. self::dieDebug(
  1188. __METHOD__,
  1189. "MAX1 or MAX2 are not defined for the limit $encParamName"
  1190. );
  1191. }
  1192. if ( $value === 'max' ) {
  1193. $value = $this->getMain()->canApiHighLimits()
  1194. ? $paramSettings[self::PARAM_MAX2]
  1195. : $paramSettings[self::PARAM_MAX];
  1196. $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
  1197. } else {
  1198. $this->validateLimit(
  1199. $paramName,
  1200. $value,
  1201. $paramSettings[self::PARAM_MIN] ?? 0,
  1202. $paramSettings[self::PARAM_MAX],
  1203. $paramSettings[self::PARAM_MAX2]
  1204. );
  1205. }
  1206. break;
  1207. case 'boolean':
  1208. if ( $multi ) {
  1209. self::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
  1210. }
  1211. break;
  1212. case 'timestamp':
  1213. if ( is_array( $value ) ) {
  1214. foreach ( $value as $key => $val ) {
  1215. $value[$key] = $this->validateTimestamp( $val, $encParamName );
  1216. }
  1217. } else {
  1218. $value = $this->validateTimestamp( $value, $encParamName );
  1219. }
  1220. break;
  1221. case 'user':
  1222. if ( is_array( $value ) ) {
  1223. foreach ( $value as $key => $val ) {
  1224. $value[$key] = $this->validateUser( $val, $encParamName );
  1225. }
  1226. } else {
  1227. $value = $this->validateUser( $value, $encParamName );
  1228. }
  1229. break;
  1230. case 'upload': // nothing to do
  1231. break;
  1232. case 'tags':
  1233. // If change tagging was requested, check that the tags are valid.
  1234. if ( !is_array( $value ) && !$multi ) {
  1235. $value = [ $value ];
  1236. }
  1237. $tagsStatus = ChangeTags::canAddTagsAccompanyingChange( $value );
  1238. if ( !$tagsStatus->isGood() ) {
  1239. $this->dieStatus( $tagsStatus );
  1240. }
  1241. break;
  1242. default:
  1243. self::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
  1244. }
  1245. }
  1246. // Throw out duplicates if requested
  1247. if ( !$dupes && is_array( $value ) ) {
  1248. $value = array_unique( $value );
  1249. }
  1250. if ( in_array( $type, [ 'NULL', 'string', 'text', 'password' ], true ) ) {
  1251. foreach ( (array)$value as $val ) {
  1252. if ( isset( $paramSettings[self::PARAM_MAX_BYTES] )
  1253. && strlen( $val ) > $paramSettings[self::PARAM_MAX_BYTES]
  1254. ) {
  1255. $this->dieWithError( [ 'apierror-maxbytes', $encParamName,
  1256. $paramSettings[self::PARAM_MAX_BYTES] ] );
  1257. }
  1258. if ( isset( $paramSettings[self::PARAM_MAX_CHARS] )
  1259. && mb_strlen( $val, 'UTF-8' ) > $paramSettings[self::PARAM_MAX_CHARS]
  1260. ) {
  1261. $this->dieWithError( [ 'apierror-maxchars', $encParamName,
  1262. $paramSettings[self::PARAM_MAX_CHARS] ] );
  1263. }
  1264. }
  1265. }
  1266. // Set a warning if a deprecated parameter has been passed
  1267. if ( $deprecated && $provided ) {
  1268. $feature = $encParamName;
  1269. $m = $this;
  1270. while ( !$m->isMain() ) {
  1271. $p = $m->getParent();
  1272. $name = $m->getModuleName();
  1273. $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
  1274. $feature = "{$param}={$name}&{$feature}";
  1275. $m = $p;
  1276. }
  1277. $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
  1278. }
  1279. // Set a warning if a deprecated parameter value has been passed
  1280. $usedDeprecatedValues = $deprecatedValues && $provided
  1281. ? array_intersect( array_keys( $deprecatedValues ), (array)$value )
  1282. : [];
  1283. if ( $usedDeprecatedValues ) {
  1284. $feature = "$encParamName=";
  1285. $m = $this;
  1286. while ( !$m->isMain() ) {
  1287. $p = $m->getParent();
  1288. $name = $m->getModuleName();
  1289. $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
  1290. $feature = "{$param}={$name}&{$feature}";
  1291. $m = $p;
  1292. }
  1293. foreach ( $usedDeprecatedValues as $v ) {
  1294. $msg = $deprecatedValues[$v];
  1295. if ( $msg === true ) {
  1296. $msg = [ 'apiwarn-deprecation-parameter', "$encParamName=$v" ];
  1297. }
  1298. $this->addDeprecation( $msg, "$feature$v" );
  1299. }
  1300. }
  1301. } elseif ( $required ) {
  1302. $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
  1303. }
  1304. return $value;
  1305. }
  1306. /**
  1307. * Handle when a parameter was Unicode-normalized
  1308. * @since 1.28
  1309. * @param string $paramName Unprefixed parameter name
  1310. * @param string $value Input that will be used.
  1311. * @param string $rawValue Input before normalization.
  1312. */
  1313. protected function handleParamNormalization( $paramName, $value, $rawValue ) {
  1314. $encParamName = $this->encodeParamName( $paramName );
  1315. $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
  1316. }
  1317. /**
  1318. * Split a multi-valued parameter string, like explode()
  1319. * @since 1.28
  1320. * @param string $value
  1321. * @param int $limit
  1322. * @return string[]
  1323. */
  1324. protected function explodeMultiValue( $value, $limit ) {
  1325. if ( substr( $value, 0, 1 ) === "\x1f" ) {
  1326. $sep = "\x1f";
  1327. $value = substr( $value, 1 );
  1328. } else {
  1329. $sep = '|';
  1330. }
  1331. return explode( $sep, $value, $limit );
  1332. }
  1333. /**
  1334. * Return an array of values that were given in a 'a|b|c' notation,
  1335. * after it optionally validates them against the list allowed values.
  1336. *
  1337. * @param string $valueName The name of the parameter (for error
  1338. * reporting)
  1339. * @param mixed $value The value being parsed
  1340. * @param bool $allowMultiple Can $value contain more than one value
  1341. * separated by '|'?
  1342. * @param string[]|null $allowedValues An array of values to check against. If
  1343. * null, all values are accepted.
  1344. * @param string|null $allSpecifier String to use to specify all allowed values, or null
  1345. * if this behavior should not be allowed
  1346. * @param int|null $limit1 Maximum number of values, for normal users.
  1347. * @param int|null $limit2 Maximum number of values, for users with the apihighlimits right.
  1348. * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
  1349. */
  1350. protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
  1351. $allSpecifier = null, $limit1 = null, $limit2 = null
  1352. ) {
  1353. if ( ( $value === '' || $value === "\x1f" ) && $allowMultiple ) {
  1354. return [];
  1355. }
  1356. $limit1 = $limit1 ?: self::LIMIT_SML1;
  1357. $limit2 = $limit2 ?: self::LIMIT_SML2;
  1358. // This is a bit awkward, but we want to avoid calling canApiHighLimits()
  1359. // because it unstubs $wgUser
  1360. $valuesList = $this->explodeMultiValue( $value, $limit2 + 1 );
  1361. $sizeLimit = count( $valuesList ) > $limit1 && $this->mMainModule->canApiHighLimits()
  1362. ? $limit2
  1363. : $limit1;
  1364. if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
  1365. count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
  1366. ) {
  1367. return $allowedValues;
  1368. }
  1369. if ( count( $valuesList ) > $sizeLimit ) {
  1370. $this->dieWithError(
  1371. [ 'apierror-toomanyvalues', $valueName, $sizeLimit ],
  1372. "too-many-$valueName"
  1373. );
  1374. }
  1375. if ( !$allowMultiple && count( $valuesList ) != 1 ) {
  1376. // T35482 - Allow entries with | in them for non-multiple values
  1377. if ( in_array( $value, $allowedValues, true ) ) {
  1378. return $value;
  1379. }
  1380. $values = array_map( function ( $v ) {
  1381. return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
  1382. }, $allowedValues );
  1383. $this->dieWithError( [
  1384. 'apierror-multival-only-one-of',
  1385. $valueName,
  1386. Message::listParam( $values ),
  1387. count( $values ),
  1388. ], "multival_$valueName" );
  1389. }
  1390. if ( is_array( $allowedValues ) ) {
  1391. // Check for unknown values
  1392. $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
  1393. if ( count( $unknown ) ) {
  1394. if ( $allowMultiple ) {
  1395. $this->addWarning( [
  1396. 'apiwarn-unrecognizedvalues',
  1397. $valueName,
  1398. Message::listParam( $unknown, 'comma' ),
  1399. count( $unknown ),
  1400. ] );
  1401. } else {
  1402. $this->dieWithError(
  1403. [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
  1404. "unknown_$valueName"
  1405. );
  1406. }
  1407. }
  1408. // Now throw them out
  1409. $valuesList = array_intersect( $valuesList, $allowedValues );
  1410. }
  1411. return $allowMultiple ? $valuesList : $valuesList[0];
  1412. }
  1413. /**
  1414. * Validate the value against the minimum and user/bot maximum limits.
  1415. * Prints usage info on failure.
  1416. * @param string $paramName Parameter name
  1417. * @param int &$value Parameter value
  1418. * @param int|null $min Minimum value
  1419. * @param int|null $max Maximum value for users
  1420. * @param int|null $botMax Maximum value for sysops/bots
  1421. * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
  1422. */
  1423. protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
  1424. $enforceLimits = false
  1425. ) {
  1426. if ( !is_null( $min ) && $value < $min ) {
  1427. $msg = ApiMessage::create(
  1428. [ 'apierror-integeroutofrange-belowminimum',
  1429. $this->encodeParamName( $paramName ), $min, $value ],
  1430. 'integeroutofrange',
  1431. [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
  1432. );
  1433. // @phan-suppress-next-line PhanTypeMismatchArgument
  1434. $this->warnOrDie( $msg, $enforceLimits );
  1435. $value = $min;
  1436. }
  1437. // Minimum is always validated, whereas maximum is checked only if not
  1438. // running in internal call mode
  1439. if ( $this->getMain()->isInternalMode() ) {
  1440. return;
  1441. }
  1442. // Optimization: do not check user's bot status unless really needed -- skips db query
  1443. // assumes $botMax >= $max
  1444. if ( !is_null( $max ) && $value > $max ) {
  1445. if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
  1446. if ( $value > $botMax ) {
  1447. $msg = ApiMessage::create(
  1448. [ 'apierror-integeroutofrange-abovebotmax',
  1449. $this->encodeParamName( $paramName ), $botMax, $value ],
  1450. 'integeroutofrange',
  1451. [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
  1452. );
  1453. // @phan-suppress-next-line PhanTypeMismatchArgument
  1454. $this->warnOrDie( $msg, $enforceLimits );
  1455. $value = $botMax;
  1456. }
  1457. } else {
  1458. $msg = ApiMessage::create(
  1459. [ 'apierror-integeroutofrange-abovemax',
  1460. $this->encodeParamName( $paramName ), $max, $value ],
  1461. 'integeroutofrange',
  1462. [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
  1463. );
  1464. // @phan-suppress-next-line PhanTypeMismatchArgument
  1465. $this->warnOrDie( $msg, $enforceLimits );
  1466. $value = $max;
  1467. }
  1468. }
  1469. }
  1470. /**
  1471. * Validate and normalize parameters of type 'timestamp'
  1472. * @param string $value Parameter value
  1473. * @param string $encParamName Parameter name
  1474. * @return string Validated and normalized parameter
  1475. */
  1476. protected function validateTimestamp( $value, $encParamName ) {
  1477. // Confusing synonyms for the current time accepted by wfTimestamp()
  1478. // (wfTimestamp() also accepts various non-strings and the string of 14
  1479. // ASCII NUL bytes, but those can't get here)
  1480. if ( !$value ) {
  1481. $this->addDeprecation(
  1482. [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
  1483. 'unclear-"now"-timestamp'
  1484. );
  1485. return wfTimestamp( TS_MW );
  1486. }
  1487. // Explicit synonym for the current time
  1488. if ( $value === 'now' ) {
  1489. return wfTimestamp( TS_MW );
  1490. }
  1491. $timestamp = wfTimestamp( TS_MW, $value );
  1492. if ( $timestamp === false ) {
  1493. $this->dieWithError(
  1494. [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
  1495. "badtimestamp_{$encParamName}"
  1496. );
  1497. }
  1498. return $timestamp;
  1499. }
  1500. /**
  1501. * Validate the supplied token.
  1502. *
  1503. * @since 1.24
  1504. * @param string $token Supplied token
  1505. * @param array $params All supplied parameters for the module
  1506. * @return bool
  1507. * @throws MWException
  1508. */
  1509. final public function validateToken( $token, array $params ) {
  1510. $tokenType = $this->needsToken();
  1511. $salts = ApiQueryTokens::getTokenTypeSalts();
  1512. if ( !isset( $salts[$tokenType] ) ) {
  1513. throw new MWException(
  1514. "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
  1515. 'without registering it'
  1516. );
  1517. }
  1518. $tokenObj = ApiQueryTokens::getToken(
  1519. $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
  1520. );
  1521. if ( $tokenObj->match( $token ) ) {
  1522. return true;
  1523. }
  1524. $webUiSalt = $this->getWebUITokenSalt( $params );
  1525. if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
  1526. $token,
  1527. $webUiSalt,
  1528. $this->getRequest()
  1529. ) ) {
  1530. return true;
  1531. }
  1532. return false;
  1533. }
  1534. /**
  1535. * Validate and normalize parameters of type 'user'
  1536. * @param string $value Parameter value
  1537. * @param string $encParamName Parameter name
  1538. * @return string Validated and normalized parameter
  1539. */
  1540. private function validateUser( $value, $encParamName ) {
  1541. if ( ExternalUserNames::isExternal( $value ) && User::newFromName( $value, false ) ) {
  1542. return $value;
  1543. }
  1544. $name = User::getCanonicalName( $value, 'valid' );
  1545. if ( $name !== false ) {
  1546. return $name;
  1547. }
  1548. if (
  1549. // We allow ranges as well, for blocks.
  1550. IP::isIPAddress( $value ) ||
  1551. // See comment for User::isIP. We don't just call that function
  1552. // here because it also returns true for things like
  1553. // 300.300.300.300 that are neither valid usernames nor valid IP
  1554. // addresses.
  1555. preg_match(
  1556. '/^' . RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.xxx$/',
  1557. $value
  1558. )
  1559. ) {
  1560. return IP::sanitizeIP( $value );
  1561. }
  1562. $this->dieWithError(
  1563. [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
  1564. "baduser_{$encParamName}"
  1565. );
  1566. }
  1567. /** @} */
  1568. /************************************************************************//**
  1569. * @name Utility methods
  1570. * @{
  1571. */
  1572. /**
  1573. * Set a watch (or unwatch) based the based on a watchlist parameter.
  1574. * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
  1575. * @param Title $titleObj The article's title to change
  1576. * @param string|null $userOption The user option to consider when $watch=preferences
  1577. */
  1578. protected function setWatch( $watch, $titleObj, $userOption = null ) {
  1579. $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
  1580. if ( $value === null ) {
  1581. return;
  1582. }
  1583. WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
  1584. }
  1585. /**
  1586. * Gets the user for whom to get the watchlist
  1587. *
  1588. * @param array $params
  1589. * @return User
  1590. */
  1591. public function getWatchlistUser( $params ) {
  1592. if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
  1593. $user = User::newFromName( $params['owner'], false );
  1594. if ( !( $user && $user->getId() ) ) {
  1595. $this->dieWithError(
  1596. [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
  1597. );
  1598. }
  1599. $token = $user->getOption( 'watchlisttoken' );
  1600. if ( $token == '' || !hash_equals( $token, $params['token'] ) ) {
  1601. $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
  1602. }
  1603. } else {
  1604. if ( !$this->getUser()->isLoggedIn() ) {
  1605. $this->dieWithError( 'watchlistanontext', 'notloggedin' );
  1606. }
  1607. $this->checkUserRightsAny( 'viewmywatchlist' );
  1608. $user = $this->getUser();
  1609. }
  1610. return $user;
  1611. }
  1612. /**
  1613. * Create a Message from a string or array
  1614. *
  1615. * A string is used as a message key. An array has the message key as the
  1616. * first value and message parameters as subsequent values.
  1617. *
  1618. * @since 1.25
  1619. * @param string|array|Message $msg
  1620. * @param IContextSource $context
  1621. * @param array|null $params
  1622. * @return Message|null
  1623. */
  1624. public static function makeMessage( $msg, IContextSource $context, array $params = null ) {
  1625. if ( is_string( $msg ) ) {
  1626. $msg = wfMessage( $msg );
  1627. } elseif ( is_array( $msg ) ) {
  1628. $msg = wfMessage( ...$msg );
  1629. }
  1630. if ( !$msg instanceof Message ) {
  1631. return null;
  1632. }
  1633. $msg->setContext( $context );
  1634. if ( $params ) {
  1635. $msg->params( $params );
  1636. }
  1637. return $msg;
  1638. }
  1639. /**
  1640. * Turn an array of message keys or key+param arrays into a Status
  1641. * @since 1.29
  1642. * @param array $errors
  1643. * @param User|null $user
  1644. * @return Status
  1645. */
  1646. public function errorArrayToStatus( array $errors, User $user = null ) {
  1647. if ( $user === null ) {
  1648. $user = $this->getUser();
  1649. }
  1650. $status = Status::newGood();
  1651. foreach ( $errors as $error ) {
  1652. if ( !is_array( $error ) ) {
  1653. $error = [ $error ];
  1654. }
  1655. if ( is_string( $error[0] ) && isset( self::$blockMsgMap[$error[0]] ) && $user->getBlock() ) {
  1656. list( $msg, $code ) = self::$blockMsgMap[$error[0]];
  1657. $status->fatal( ApiMessage::create( $msg, $code,
  1658. [ 'blockinfo' => $this->getBlockDetails( $user->getBlock() ) ]
  1659. ) );
  1660. } else {
  1661. $status->fatal( ...$error );
  1662. }
  1663. }
  1664. return $status;
  1665. }
  1666. /**
  1667. * Add block info to block messages in a Status
  1668. * @since 1.33
  1669. * @param StatusValue $status
  1670. * @param User|null $user
  1671. */
  1672. public function addBlockInfoToStatus( StatusValue $status, User $user = null ) {
  1673. if ( $user === null ) {
  1674. $user = $this->getUser();
  1675. }
  1676. foreach ( self::$blockMsgMap as $msg => list( $apiMsg, $code ) ) {
  1677. if ( $status->hasMessage( $msg ) && $user->getBlock() ) {
  1678. $status->replaceMessage( $msg, ApiMessage::create( $apiMsg, $code,
  1679. [ 'blockinfo' => $this->getBlockDetails( $user->getBlock() ) ]
  1680. ) );
  1681. }
  1682. }
  1683. }
  1684. /**
  1685. * Call wfTransactionalTimeLimit() if this request was POSTed
  1686. * @since 1.26
  1687. */
  1688. protected function useTransactionalTimeLimit() {
  1689. if ( $this->getRequest()->wasPosted() ) {
  1690. wfTransactionalTimeLimit();
  1691. }
  1692. }
  1693. /**
  1694. * Filter out-of-range values from a list of positive integer IDs
  1695. * @since 1.33
  1696. * @param array $fields Array of pairs of table and field to check
  1697. * @param (string|int)[] $ids IDs to filter. Strings in the array are
  1698. * expected to be stringified ints.
  1699. * @return (string|int)[] Filtered IDs.
  1700. */
  1701. protected function filterIDs( $fields, array $ids ) {
  1702. $min = INF;
  1703. $max = 0;
  1704. foreach ( $fields as list( $table, $field ) ) {
  1705. if ( isset( self::$filterIDsCache[$table][$field] ) ) {
  1706. $row = self::$filterIDsCache[$table][$field];
  1707. } else {
  1708. $row = $this->getDB()->selectRow(
  1709. $table,
  1710. [
  1711. 'min_id' => "MIN($field)",
  1712. 'max_id' => "MAX($field)",
  1713. ],
  1714. '',
  1715. __METHOD__
  1716. );
  1717. self::$filterIDsCache[$table][$field] = $row;
  1718. }
  1719. $min = min( $min, $row->min_id );
  1720. $max = max( $max, $row->max_id );
  1721. }
  1722. return array_filter( $ids, function ( $id ) use ( $min, $max ) {
  1723. return ( is_int( $id ) && $id >= 0 || ctype_digit( $id ) )
  1724. && $id >= $min && $id <= $max;
  1725. } );
  1726. }
  1727. /** @} */
  1728. /************************************************************************//**
  1729. * @name Warning and error reporting
  1730. * @{
  1731. */
  1732. /**
  1733. * Add a warning for this module.
  1734. *
  1735. * Users should monitor this section to notice any changes in API. Multiple
  1736. * calls to this function will result in multiple warning messages.
  1737. *
  1738. * If $msg is not an ApiMessage, the message code will be derived from the
  1739. * message key by stripping any "apiwarn-" or "apierror-" prefix.
  1740. *
  1741. * @since 1.29
  1742. * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
  1743. * @param string|null $code See ApiErrorFormatter::addWarning()
  1744. * @param array|null $data See ApiErrorFormatter::addWarning()
  1745. */
  1746. public function addWarning( $msg, $code = null, $data = null ) {
  1747. $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
  1748. }
  1749. /**
  1750. * Add a deprecation warning for this module.
  1751. *
  1752. * A combination of $this->addWarning() and $this->logFeatureUsage()
  1753. *
  1754. * @since 1.29
  1755. * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
  1756. * @param string|null $feature See ApiBase::logFeatureUsage()
  1757. * @param array|null $data See ApiErrorFormatter::addWarning()
  1758. */
  1759. public function addDeprecation( $msg, $feature, $data = [] ) {
  1760. $data = (array)$data;
  1761. if ( $feature !== null ) {
  1762. $data['feature'] = $feature;
  1763. $this->logFeatureUsage( $feature );
  1764. }
  1765. $this->addWarning( $msg, 'deprecation', $data );
  1766. // No real need to deduplicate here, ApiErrorFormatter does that for
  1767. // us (assuming the hook is deterministic).
  1768. $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
  1769. Hooks::run( 'ApiDeprecationHelp', [ &$msgs ] );
  1770. if ( count( $msgs ) > 1 ) {
  1771. $key = '$' . implode( ' $', range( 1, count( $msgs ) ) );
  1772. $msg = ( new RawMessage( $key ) )->params( $msgs );
  1773. } else {
  1774. $msg = reset( $msgs );
  1775. }
  1776. $this->getMain()->addWarning( $msg, 'deprecation-help' );
  1777. }
  1778. /**
  1779. * Add an error for this module without aborting
  1780. *
  1781. * If $msg is not an ApiMessage, the message code will be derived from the
  1782. * message key by stripping any "apiwarn-" or "apierror-" prefix.
  1783. *
  1784. * @note If you want to abort processing, use self::dieWithError() instead.
  1785. * @since 1.29
  1786. * @param string|array|Message $msg See ApiErrorFormatter::addError()
  1787. * @param string|null $code See ApiErrorFormatter::addError()
  1788. * @param array|null $data See ApiErrorFormatter::addError()
  1789. */
  1790. public function addError( $msg, $code = null, $data = null ) {
  1791. $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
  1792. }
  1793. /**
  1794. * Add warnings and/or errors from a Status
  1795. *
  1796. * @note If you want to abort processing, use self::dieStatus() instead.
  1797. * @since 1.29
  1798. * @param StatusValue $status
  1799. * @param string[] $types 'warning' and/or 'error'
  1800. * @param string[] $filter Message keys to filter out (since 1.33)
  1801. */
  1802. public function addMessagesFromStatus(
  1803. StatusValue $status, $types = [ 'warning', 'error' ], array $filter = []
  1804. ) {
  1805. $this->getErrorFormatter()->addMessagesFromStatus(
  1806. $this->getModulePath(), $status, $types, $filter
  1807. );
  1808. }
  1809. /**
  1810. * Abort execution with an error
  1811. *
  1812. * If $msg is not an ApiMessage, the message code will be derived from the
  1813. * message key by stripping any "apiwarn-" or "apierror-" prefix.
  1814. *
  1815. * @since 1.29
  1816. * @param string|array|Message $msg See ApiErrorFormatter::addError()
  1817. * @param string|null $code See ApiErrorFormatter::addError()
  1818. * @param array|null $data See ApiErrorFormatter::addError()
  1819. * @param int|null $httpCode HTTP error code to use
  1820. * @throws ApiUsageException always
  1821. */
  1822. public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
  1823. throw ApiUsageException::newWithMessage( $this, $msg, $code, $data, $httpCode );
  1824. }
  1825. /**
  1826. * Abort execution with an error derived from an exception
  1827. *
  1828. * @since 1.29
  1829. * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
  1830. * @param array $options See ApiErrorFormatter::getMessageFromException()
  1831. * @throws ApiUsageException always
  1832. */
  1833. public function dieWithException( $exception, array $options = [] ) {
  1834. $this->dieWithError(
  1835. // @phan-suppress-next-line PhanTypeMismatchArgument
  1836. $this->getErrorFormatter()->getMessageFromException( $exception, $options )
  1837. );
  1838. }
  1839. /**
  1840. * Adds a warning to the output, else dies
  1841. *
  1842. * @param ApiMessage $msg Message to show as a warning, or error message if dying
  1843. * @param bool $enforceLimits Whether this is an enforce (die)
  1844. */
  1845. private function warnOrDie( ApiMessage $msg, $enforceLimits = false ) {
  1846. if ( $enforceLimits ) {
  1847. $this->dieWithError( $msg );
  1848. } else {
  1849. $this->addWarning( $msg );
  1850. }
  1851. }
  1852. /**
  1853. * Throw an ApiUsageException, which will (if uncaught) call the main module's
  1854. * error handler and die with an error message including block info.
  1855. *
  1856. * @since 1.27
  1857. * @param AbstractBlock $block The block used to generate the ApiUsageException
  1858. * @throws ApiUsageException always
  1859. */
  1860. public function dieBlocked( AbstractBlock $block ) {
  1861. // Die using the appropriate message depending on block type
  1862. if ( $block->getType() == DatabaseBlock::TYPE_AUTO ) {
  1863. $this->dieWithError(
  1864. 'apierror-autoblocked',
  1865. 'autoblocked',
  1866. [ 'blockinfo' => $this->getBlockDetails( $block ) ]
  1867. );
  1868. } elseif ( !$block->isSitewide() ) {
  1869. $this->dieWithError(
  1870. 'apierror-blocked-partial',
  1871. 'blocked',
  1872. [ 'blockinfo' => $this->getBlockDetails( $block ) ]
  1873. );
  1874. } else {
  1875. $this->dieWithError(
  1876. 'apierror-blocked',
  1877. 'blocked',
  1878. [ 'blockinfo' => $this->getBlockDetails( $block ) ]
  1879. );
  1880. }
  1881. }
  1882. /**
  1883. * Throw an ApiUsageException based on the Status object.
  1884. *
  1885. * @since 1.22
  1886. * @since 1.29 Accepts a StatusValue
  1887. * @param StatusValue $status
  1888. * @throws ApiUsageException always
  1889. */
  1890. public function dieStatus( StatusValue $status ) {
  1891. if ( $status->isGood() ) {
  1892. throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
  1893. }
  1894. // ApiUsageException needs a fatal status, but this method has
  1895. // historically accepted any non-good status. Convert it if necessary.
  1896. $status->setOK( false );
  1897. if ( !$status->getErrorsByType( 'error' ) ) {
  1898. $newStatus = Status::newGood();
  1899. foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
  1900. $newStatus->fatal( $err['message'], ...$err['params'] );
  1901. }
  1902. if ( !$newStatus->getErrorsByType( 'error' ) ) {
  1903. $newStatus->fatal( 'unknownerror-nocode' );
  1904. }
  1905. $status = $newStatus;
  1906. }
  1907. $this->addBlockInfoToStatus( $status );
  1908. throw new ApiUsageException( $this, $status );
  1909. }
  1910. /**
  1911. * Helper function for readonly errors
  1912. *
  1913. * @throws ApiUsageException always
  1914. */
  1915. public function dieReadOnly() {
  1916. $this->dieWithError(
  1917. 'apierror-readonly',
  1918. 'readonly',
  1919. [ 'readonlyreason' => wfReadOnlyReason() ]
  1920. );
  1921. }
  1922. /**
  1923. * Helper function for permission-denied errors
  1924. * @since 1.29
  1925. * @param string|string[] $rights
  1926. * @param User|null $user
  1927. * @throws ApiUsageException if the user doesn't have any of the rights.
  1928. * The error message is based on $rights[0].
  1929. */
  1930. public function checkUserRightsAny( $rights, $user = null ) {
  1931. if ( !$user ) {
  1932. $user = $this->getUser();
  1933. }
  1934. $rights = (array)$rights;
  1935. if ( !$this->getPermissionManager()
  1936. ->userHasAnyRight( $user, ...$rights )
  1937. ) {
  1938. $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
  1939. }
  1940. }
  1941. /**
  1942. * Helper function for permission-denied errors
  1943. *
  1944. * @param LinkTarget $linkTarget
  1945. * @param string|string[] $actions
  1946. * @param array $options Additional options
  1947. * - user: (User) User to use rather than $this->getUser()
  1948. * - autoblock: (bool, default false) Whether to spread autoblocks
  1949. * For compatibility, passing a User object is treated as the value for the 'user' option.
  1950. * @throws ApiUsageException if the user doesn't have all of the rights.
  1951. *
  1952. * @since 1.29
  1953. * @since 1.33 Changed the third parameter from $user to $options.
  1954. */
  1955. public function checkTitleUserPermissions( LinkTarget $linkTarget, $actions, $options = [] ) {
  1956. if ( !is_array( $options ) ) {
  1957. wfDeprecated( '$user as the third parameter to ' . __METHOD__, '1.33' );
  1958. $options = [ 'user' => $options ];
  1959. }
  1960. $user = $options['user'] ?? $this->getUser();
  1961. $errors = [];
  1962. foreach ( (array)$actions as $action ) {
  1963. $errors = array_merge(
  1964. $errors,
  1965. $this->getPermissionManager()->getPermissionErrors( $action, $user, $linkTarget )
  1966. );
  1967. }
  1968. if ( $errors ) {
  1969. if ( !empty( $options['autoblock'] ) ) {
  1970. $user->spreadAnyEditBlock();
  1971. }
  1972. $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
  1973. }
  1974. }
  1975. /**
  1976. * Will only set a warning instead of failing if the global $wgDebugAPI
  1977. * is set to true. Otherwise behaves exactly as self::dieWithError().
  1978. *
  1979. * @since 1.29
  1980. * @param string|array|Message $msg
  1981. * @param string|null $code
  1982. * @param array|null $data
  1983. * @param int|null $httpCode
  1984. * @throws ApiUsageException
  1985. */
  1986. public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
  1987. if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
  1988. $this->dieWithError( $msg, $code, $data, $httpCode );
  1989. } else {
  1990. $this->addWarning( $msg, $code, $data );
  1991. }
  1992. }
  1993. /**
  1994. * Die with the 'badcontinue' error.
  1995. *
  1996. * This call is common enough to make it into the base method.
  1997. *
  1998. * @param bool $condition Will only die if this value is true
  1999. * @throws ApiUsageException
  2000. * @since 1.21
  2001. */
  2002. protected function dieContinueUsageIf( $condition ) {
  2003. if ( $condition ) {
  2004. $this->dieWithError( 'apierror-badcontinue' );
  2005. }
  2006. }
  2007. /**
  2008. * Internal code errors should be reported with this method
  2009. * @param string $method Method or function name
  2010. * @param string $message Error message
  2011. * @throws MWException always
  2012. */
  2013. protected static function dieDebug( $method, $message ) {
  2014. throw new MWException( "Internal error in $method: $message" );
  2015. }
  2016. /**
  2017. * Write logging information for API features to a debug log, for usage
  2018. * analysis.
  2019. * @note Consider using $this->addDeprecation() instead to both warn and log.
  2020. * @param string $feature Feature being used.
  2021. */
  2022. public function logFeatureUsage( $feature ) {
  2023. static $loggedFeatures = [];
  2024. // Only log each feature once per request. We can get multiple calls from calls to
  2025. // extractRequestParams() with different values for 'parseLimit', for example.
  2026. if ( isset( $loggedFeatures[$feature] ) ) {
  2027. return;
  2028. }
  2029. $loggedFeatures[$feature] = true;
  2030. $request = $this->getRequest();
  2031. $ctx = [
  2032. 'feature' => $feature,
  2033. // Spaces to underscores in 'username' for historical reasons.
  2034. 'username' => str_replace( ' ', '_', $this->getUser()->getName() ),
  2035. 'ip' => $request->getIP(),
  2036. 'referer' => (string)$request->getHeader( 'Referer' ),
  2037. 'agent' => $this->getMain()->getUserAgent(),
  2038. ];
  2039. // Text string is deprecated. Remove (or replace with just $feature) in MW 1.34.
  2040. $s = '"' . addslashes( $ctx['feature'] ) . '"' .
  2041. ' "' . wfUrlencode( $ctx['username'] ) . '"' .
  2042. ' "' . $ctx['ip'] . '"' .
  2043. ' "' . addslashes( $ctx['referer'] ) . '"' .
  2044. ' "' . addslashes( $ctx['agent'] ) . '"';
  2045. wfDebugLog( 'api-feature-usage', $s, 'private', $ctx );
  2046. }
  2047. /** @} */
  2048. /************************************************************************//**
  2049. * @name Help message generation
  2050. * @{
  2051. */
  2052. /**
  2053. * Return the summary message.
  2054. *
  2055. * This is a one-line description of the module, suitable for display in a
  2056. * list of modules.
  2057. *
  2058. * @since 1.30
  2059. * @return string|array|Message
  2060. */
  2061. protected function getSummaryMessage() {
  2062. return "apihelp-{$this->getModulePath()}-summary";
  2063. }
  2064. /**
  2065. * Return the extended help text message.
  2066. *
  2067. * This is additional text to display at the top of the help section, below
  2068. * the summary.
  2069. *
  2070. * @since 1.30
  2071. * @return string|array|Message
  2072. */
  2073. protected function getExtendedDescription() {
  2074. return [ [
  2075. "apihelp-{$this->getModulePath()}-extended-description",
  2076. 'api-help-no-extended-description',
  2077. ] ];
  2078. }
  2079. /**
  2080. * Get final module summary
  2081. *
  2082. * @since 1.30
  2083. * @return Message
  2084. */
  2085. public function getFinalSummary() {
  2086. $msg = self::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
  2087. $this->getModulePrefix(),
  2088. $this->getModuleName(),
  2089. $this->getModulePath(),
  2090. ] );
  2091. return $msg;
  2092. }
  2093. /**
  2094. * Get final module description, after hooks have had a chance to tweak it as
  2095. * needed.
  2096. *
  2097. * @since 1.25, returns Message[] rather than string[]
  2098. * @return Message[]
  2099. */
  2100. public function getFinalDescription() {
  2101. $summary = self::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
  2102. $this->getModulePrefix(),
  2103. $this->getModuleName(),
  2104. $this->getModulePath(),
  2105. ] );
  2106. $extendedDescription = self::makeMessage(
  2107. $this->getExtendedDescription(), $this->getContext(), [
  2108. $this->getModulePrefix(),
  2109. $this->getModuleName(),
  2110. $this->getModulePath(),
  2111. ]
  2112. );
  2113. $msgs = [ $summary, $extendedDescription ];
  2114. Hooks::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
  2115. return $msgs;
  2116. }
  2117. /**
  2118. * Get final list of parameters, after hooks have had a chance to
  2119. * tweak it as needed.
  2120. *
  2121. * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
  2122. * @return array|bool False on no parameters
  2123. * @since 1.21 $flags param added
  2124. */
  2125. public function getFinalParams( $flags = 0 ) {
  2126. $params = $this->getAllowedParams( $flags );
  2127. if ( !$params ) {
  2128. $params = [];
  2129. }
  2130. if ( $this->needsToken() ) {
  2131. $params['token'] = [
  2132. self::PARAM_TYPE => 'string',
  2133. self::PARAM_REQUIRED => true,
  2134. self::PARAM_SENSITIVE => true,
  2135. self::PARAM_HELP_MSG => [
  2136. 'api-help-param-token',
  2137. $this->needsToken(),
  2138. ],
  2139. ] + ( $params['token'] ?? [] );
  2140. }
  2141. // Avoid PHP 7.1 warning of passing $this by reference
  2142. $apiModule = $this;
  2143. Hooks::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
  2144. return $params;
  2145. }
  2146. /**
  2147. * Get final parameter descriptions, after hooks have had a chance to tweak it as
  2148. * needed.
  2149. *
  2150. * @since 1.25, returns array of Message[] rather than array of string[]
  2151. * @return array Keys are parameter names, values are arrays of Message objects
  2152. */
  2153. public function getFinalParamDescription() {
  2154. $prefix = $this->getModulePrefix();
  2155. $name = $this->getModuleName();
  2156. $path = $this->getModulePath();
  2157. $params = $this->getFinalParams( self::GET_VALUES_FOR_HELP );
  2158. $msgs = [];
  2159. foreach ( $params as $param => $settings ) {
  2160. if ( !is_array( $settings ) ) {
  2161. $settings = [];
  2162. }
  2163. if ( isset( $settings[self::PARAM_HELP_MSG] ) ) {
  2164. $msg = $settings[self::PARAM_HELP_MSG];
  2165. } else {
  2166. $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
  2167. }
  2168. $msg = self::makeMessage( $msg, $this->getContext(),
  2169. [ $prefix, $param, $name, $path ] );
  2170. if ( !$msg ) {
  2171. self::dieDebug( __METHOD__,
  2172. 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
  2173. }
  2174. $msgs[$param] = [ $msg ];
  2175. if ( isset( $settings[self::PARAM_TYPE] ) &&
  2176. $settings[self::PARAM_TYPE] === 'submodule'
  2177. ) {
  2178. if ( isset( $settings[self::PARAM_SUBMODULE_MAP] ) ) {
  2179. $map = $settings[self::PARAM_SUBMODULE_MAP];
  2180. } else {
  2181. $prefix = $this->isMain() ? '' : ( $this->getModulePath() . '+' );
  2182. $map = [];
  2183. foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
  2184. $map[$submoduleName] = $prefix . $submoduleName;
  2185. }
  2186. }
  2187. ksort( $map );
  2188. $submodules = [];
  2189. $deprecatedSubmodules = [];
  2190. foreach ( $map as $v => $m ) {
  2191. $arr = &$submodules;
  2192. $isDeprecated = false;
  2193. $summary = null;
  2194. try {
  2195. $submod = $this->getModuleFromPath( $m );
  2196. if ( $submod ) {
  2197. $summary = $submod->getFinalSummary();
  2198. $isDeprecated = $submod->isDeprecated();
  2199. if ( $isDeprecated ) {
  2200. $arr = &$deprecatedSubmodules;
  2201. }
  2202. }
  2203. } catch ( ApiUsageException $ex ) {
  2204. // Ignore
  2205. }
  2206. if ( $summary ) {
  2207. $key = $summary->getKey();
  2208. $params = $summary->getParams();
  2209. } else {
  2210. $key = 'api-help-undocumented-module';
  2211. $params = [ $m ];
  2212. }
  2213. $m = new ApiHelpParamValueMessage( "[[Special:ApiHelp/$m|$v]]", $key, $params, $isDeprecated );
  2214. $arr[] = $m->setContext( $this->getContext() );
  2215. }
  2216. $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
  2217. } elseif ( isset( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
  2218. if ( !is_array( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
  2219. self::dieDebug( __METHOD__,
  2220. 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
  2221. }
  2222. if ( !is_array( $settings[self::PARAM_TYPE] ) ) {
  2223. self::dieDebug( __METHOD__,
  2224. 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
  2225. 'ApiBase::PARAM_TYPE is an array' );
  2226. }
  2227. $valueMsgs = $settings[self::PARAM_HELP_MSG_PER_VALUE];
  2228. $deprecatedValues = $settings[self::PARAM_DEPRECATED_VALUES] ?? [];
  2229. foreach ( $settings[self::PARAM_TYPE] as $value ) {
  2230. if ( isset( $valueMsgs[$value] ) ) {
  2231. $msg = $valueMsgs[$value];
  2232. } else {
  2233. $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
  2234. }
  2235. $m = self::makeMessage( $msg, $this->getContext(),
  2236. [ $prefix, $param, $name, $path, $value ] );
  2237. if ( $m ) {
  2238. $m = new ApiHelpParamValueMessage(
  2239. $value,
  2240. // @phan-suppress-next-line PhanTypeMismatchArgument
  2241. [ $m->getKey(), 'api-help-param-no-description' ],
  2242. $m->getParams(),
  2243. isset( $deprecatedValues[$value] )
  2244. );
  2245. $msgs[$param][] = $m->setContext( $this->getContext() );
  2246. } else {
  2247. self::dieDebug( __METHOD__,
  2248. "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
  2249. }
  2250. }
  2251. }
  2252. if ( isset( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
  2253. if ( !is_array( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
  2254. self::dieDebug( __METHOD__,
  2255. 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
  2256. }
  2257. foreach ( $settings[self::PARAM_HELP_MSG_APPEND] as $m ) {
  2258. $m = self::makeMessage( $m, $this->getContext(),
  2259. [ $prefix, $param, $name, $path ] );
  2260. if ( $m ) {
  2261. $msgs[$param][] = $m;
  2262. } else {
  2263. self::dieDebug( __METHOD__,
  2264. 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
  2265. }
  2266. }
  2267. }
  2268. }
  2269. Hooks::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
  2270. return $msgs;
  2271. }
  2272. /**
  2273. * Generates the list of flags for the help screen and for action=paraminfo
  2274. *
  2275. * Corresponding messages: api-help-flag-deprecated,
  2276. * api-help-flag-internal, api-help-flag-readrights,
  2277. * api-help-flag-writerights, api-help-flag-mustbeposted
  2278. *
  2279. * @return string[]
  2280. */
  2281. protected function getHelpFlags() {
  2282. $flags = [];
  2283. if ( $this->isDeprecated() ) {
  2284. $flags[] = 'deprecated';
  2285. }
  2286. if ( $this->isInternal() ) {
  2287. $flags[] = 'internal';
  2288. }
  2289. if ( $this->isReadMode() ) {
  2290. $flags[] = 'readrights';
  2291. }
  2292. if ( $this->isWriteMode() ) {
  2293. $flags[] = 'writerights';
  2294. }
  2295. if ( $this->mustBePosted() ) {
  2296. $flags[] = 'mustbeposted';
  2297. }
  2298. return $flags;
  2299. }
  2300. /**
  2301. * Returns information about the source of this module, if known
  2302. *
  2303. * Returned array is an array with the following keys:
  2304. * - path: Install path
  2305. * - name: Extension name, or "MediaWiki" for core
  2306. * - namemsg: (optional) i18n message key for a display name
  2307. * - license-name: (optional) Name of license
  2308. *
  2309. * @return array|null
  2310. */
  2311. protected function getModuleSourceInfo() {
  2312. global $IP;
  2313. if ( $this->mModuleSource !== false ) {
  2314. return $this->mModuleSource;
  2315. }
  2316. // First, try to find where the module comes from...
  2317. $rClass = new ReflectionClass( $this );
  2318. $path = $rClass->getFileName();
  2319. if ( !$path ) {
  2320. // No path known?
  2321. $this->mModuleSource = null;
  2322. return null;
  2323. }
  2324. $path = realpath( $path ) ?: $path;
  2325. // Build map of extension directories to extension info
  2326. if ( self::$extensionInfo === null ) {
  2327. $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
  2328. self::$extensionInfo = [
  2329. realpath( __DIR__ ) ?: __DIR__ => [
  2330. 'path' => $IP,
  2331. 'name' => 'MediaWiki',
  2332. 'license-name' => 'GPL-2.0-or-later',
  2333. ],
  2334. realpath( "$IP/extensions" ) ?: "$IP/extensions" => null,
  2335. realpath( $extDir ) ?: $extDir => null,
  2336. ];
  2337. $keep = [
  2338. 'path' => null,
  2339. 'name' => null,
  2340. 'namemsg' => null,
  2341. 'license-name' => null,
  2342. ];
  2343. foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
  2344. foreach ( $group as $ext ) {
  2345. if ( !isset( $ext['path'] ) || !isset( $ext['name'] ) ) {
  2346. // This shouldn't happen, but does anyway.
  2347. continue;
  2348. }
  2349. $extpath = $ext['path'];
  2350. if ( !is_dir( $extpath ) ) {
  2351. $extpath = dirname( $extpath );
  2352. }
  2353. self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
  2354. array_intersect_key( $ext, $keep );
  2355. }
  2356. }
  2357. foreach ( ExtensionRegistry::getInstance()->getAllThings() as $ext ) {
  2358. $extpath = $ext['path'];
  2359. if ( !is_dir( $extpath ) ) {
  2360. $extpath = dirname( $extpath );
  2361. }
  2362. self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
  2363. array_intersect_key( $ext, $keep );
  2364. }
  2365. }
  2366. // Now traverse parent directories until we find a match or run out of
  2367. // parents.
  2368. do {
  2369. if ( array_key_exists( $path, self::$extensionInfo ) ) {
  2370. // Found it!
  2371. $this->mModuleSource = self::$extensionInfo[$path];
  2372. return $this->mModuleSource;
  2373. }
  2374. $oldpath = $path;
  2375. $path = dirname( $path );
  2376. } while ( $path !== $oldpath );
  2377. // No idea what extension this might be.
  2378. $this->mModuleSource = null;
  2379. return null;
  2380. }
  2381. /**
  2382. * Called from ApiHelp before the pieces are joined together and returned.
  2383. *
  2384. * This exists mainly for ApiMain to add the Permissions and Credits
  2385. * sections. Other modules probably don't need it.
  2386. *
  2387. * @param string[] &$help Array of help data
  2388. * @param array $options Options passed to ApiHelp::getHelp
  2389. * @param array &$tocData If a TOC is being generated, this array has keys
  2390. * as anchors in the page and values as for Linker::generateTOC().
  2391. */
  2392. public function modifyHelp( array &$help, array $options, array &$tocData ) {
  2393. }
  2394. /** @} */
  2395. }
  2396. /**
  2397. * For really cool vim folding this needs to be at the end:
  2398. * vim: foldmarker=@{,@} foldmethod=marker
  2399. */