ApiMain.php 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033
  1. <?php
  2. /**
  3. * Created on Sep 4, 2006
  4. *
  5. * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License along
  18. * with this program; if not, write to the Free Software Foundation, Inc.,
  19. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  20. * http://www.gnu.org/copyleft/gpl.html
  21. *
  22. * @file
  23. * @defgroup API API
  24. */
  25. use MediaWiki\Logger\LoggerFactory;
  26. use MediaWiki\MediaWikiServices;
  27. use Wikimedia\Timestamp\TimestampException;
  28. use Wikimedia\Rdbms\DBQueryError;
  29. use Wikimedia\Rdbms\DBError;
  30. /**
  31. * This is the main API class, used for both external and internal processing.
  32. * When executed, it will create the requested formatter object,
  33. * instantiate and execute an object associated with the needed action,
  34. * and use formatter to print results.
  35. * In case of an exception, an error message will be printed using the same formatter.
  36. *
  37. * To use API from another application, run it using FauxRequest object, in which
  38. * case any internal exceptions will not be handled but passed up to the caller.
  39. * After successful execution, use getResult() for the resulting data.
  40. *
  41. * @ingroup API
  42. */
  43. class ApiMain extends ApiBase {
  44. /**
  45. * When no format parameter is given, this format will be used
  46. */
  47. const API_DEFAULT_FORMAT = 'jsonfm';
  48. /**
  49. * When no uselang parameter is given, this language will be used
  50. */
  51. const API_DEFAULT_USELANG = 'user';
  52. /**
  53. * List of available modules: action name => module class
  54. */
  55. private static $Modules = [
  56. 'login' => 'ApiLogin',
  57. 'clientlogin' => 'ApiClientLogin',
  58. 'logout' => 'ApiLogout',
  59. 'createaccount' => 'ApiAMCreateAccount',
  60. 'linkaccount' => 'ApiLinkAccount',
  61. 'unlinkaccount' => 'ApiRemoveAuthenticationData',
  62. 'changeauthenticationdata' => 'ApiChangeAuthenticationData',
  63. 'removeauthenticationdata' => 'ApiRemoveAuthenticationData',
  64. 'resetpassword' => 'ApiResetPassword',
  65. 'query' => 'ApiQuery',
  66. 'expandtemplates' => 'ApiExpandTemplates',
  67. 'parse' => 'ApiParse',
  68. 'stashedit' => 'ApiStashEdit',
  69. 'opensearch' => 'ApiOpenSearch',
  70. 'feedcontributions' => 'ApiFeedContributions',
  71. 'feedrecentchanges' => 'ApiFeedRecentChanges',
  72. 'feedwatchlist' => 'ApiFeedWatchlist',
  73. 'help' => 'ApiHelp',
  74. 'paraminfo' => 'ApiParamInfo',
  75. 'rsd' => 'ApiRsd',
  76. 'compare' => 'ApiComparePages',
  77. 'tokens' => 'ApiTokens',
  78. 'checktoken' => 'ApiCheckToken',
  79. 'cspreport' => 'ApiCSPReport',
  80. 'validatepassword' => 'ApiValidatePassword',
  81. // Write modules
  82. 'purge' => 'ApiPurge',
  83. 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
  84. 'rollback' => 'ApiRollback',
  85. 'delete' => 'ApiDelete',
  86. 'undelete' => 'ApiUndelete',
  87. 'protect' => 'ApiProtect',
  88. 'block' => 'ApiBlock',
  89. 'unblock' => 'ApiUnblock',
  90. 'move' => 'ApiMove',
  91. 'edit' => 'ApiEditPage',
  92. 'upload' => 'ApiUpload',
  93. 'filerevert' => 'ApiFileRevert',
  94. 'emailuser' => 'ApiEmailUser',
  95. 'watch' => 'ApiWatch',
  96. 'patrol' => 'ApiPatrol',
  97. 'import' => 'ApiImport',
  98. 'clearhasmsg' => 'ApiClearHasMsg',
  99. 'userrights' => 'ApiUserrights',
  100. 'options' => 'ApiOptions',
  101. 'imagerotate' => 'ApiImageRotate',
  102. 'revisiondelete' => 'ApiRevisionDelete',
  103. 'managetags' => 'ApiManageTags',
  104. 'tag' => 'ApiTag',
  105. 'mergehistory' => 'ApiMergeHistory',
  106. 'setpagelanguage' => 'ApiSetPageLanguage',
  107. ];
  108. /**
  109. * List of available formats: format name => format class
  110. */
  111. private static $Formats = [
  112. 'json' => 'ApiFormatJson',
  113. 'jsonfm' => 'ApiFormatJson',
  114. 'php' => 'ApiFormatPhp',
  115. 'phpfm' => 'ApiFormatPhp',
  116. 'xml' => 'ApiFormatXml',
  117. 'xmlfm' => 'ApiFormatXml',
  118. 'rawfm' => 'ApiFormatJson',
  119. 'none' => 'ApiFormatNone',
  120. ];
  121. // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
  122. /**
  123. * List of user roles that are specifically relevant to the API.
  124. * [ 'right' => [ 'msg' => 'Some message with a $1',
  125. * 'params' => [ $someVarToSubst ] ],
  126. * ];
  127. */
  128. private static $mRights = [
  129. 'writeapi' => [
  130. 'msg' => 'right-writeapi',
  131. 'params' => []
  132. ],
  133. 'apihighlimits' => [
  134. 'msg' => 'api-help-right-apihighlimits',
  135. 'params' => [ ApiBase::LIMIT_SML2, ApiBase::LIMIT_BIG2 ]
  136. ]
  137. ];
  138. // @codingStandardsIgnoreEnd
  139. /**
  140. * @var ApiFormatBase
  141. */
  142. private $mPrinter;
  143. private $mModuleMgr, $mResult, $mErrorFormatter = null;
  144. /** @var ApiContinuationManager|null */
  145. private $mContinuationManager;
  146. private $mAction;
  147. private $mEnableWrite;
  148. private $mInternalMode, $mSquidMaxage;
  149. /** @var ApiBase */
  150. private $mModule;
  151. private $mCacheMode = 'private';
  152. private $mCacheControl = [];
  153. private $mParamsUsed = [];
  154. private $mParamsSensitive = [];
  155. /** @var bool|null Cached return value from self::lacksSameOriginSecurity() */
  156. private $lacksSameOriginSecurity = null;
  157. /**
  158. * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
  159. *
  160. * @param IContextSource|WebRequest $context If this is an instance of
  161. * FauxRequest, errors are thrown and no printing occurs
  162. * @param bool $enableWrite Should be set to true if the api may modify data
  163. */
  164. public function __construct( $context = null, $enableWrite = false ) {
  165. if ( $context === null ) {
  166. $context = RequestContext::getMain();
  167. } elseif ( $context instanceof WebRequest ) {
  168. // BC for pre-1.19
  169. $request = $context;
  170. $context = RequestContext::getMain();
  171. }
  172. // We set a derivative context so we can change stuff later
  173. $this->setContext( new DerivativeContext( $context ) );
  174. if ( isset( $request ) ) {
  175. $this->getContext()->setRequest( $request );
  176. } else {
  177. $request = $this->getRequest();
  178. }
  179. $this->mInternalMode = ( $request instanceof FauxRequest );
  180. // Special handling for the main module: $parent === $this
  181. parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
  182. $config = $this->getConfig();
  183. if ( !$this->mInternalMode ) {
  184. // Log if a request with a non-whitelisted Origin header is seen
  185. // with session cookies.
  186. $originHeader = $request->getHeader( 'Origin' );
  187. if ( $originHeader === false ) {
  188. $origins = [];
  189. } else {
  190. $originHeader = trim( $originHeader );
  191. $origins = preg_split( '/\s+/', $originHeader );
  192. }
  193. $sessionCookies = array_intersect(
  194. array_keys( $_COOKIE ),
  195. MediaWiki\Session\SessionManager::singleton()->getVaryCookies()
  196. );
  197. if ( $origins && $sessionCookies && (
  198. count( $origins ) !== 1 || !self::matchOrigin(
  199. $origins[0],
  200. $config->get( 'CrossSiteAJAXdomains' ),
  201. $config->get( 'CrossSiteAJAXdomainExceptions' )
  202. )
  203. ) ) {
  204. LoggerFactory::getInstance( 'cors' )->warning(
  205. 'Non-whitelisted CORS request with session cookies', [
  206. 'origin' => $originHeader,
  207. 'cookies' => $sessionCookies,
  208. 'ip' => $request->getIP(),
  209. 'userAgent' => $this->getUserAgent(),
  210. 'wiki' => wfWikiID(),
  211. ]
  212. );
  213. }
  214. // If we're in a mode that breaks the same-origin policy, strip
  215. // user credentials for security.
  216. if ( $this->lacksSameOriginSecurity() ) {
  217. global $wgUser;
  218. wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
  219. $wgUser = new User();
  220. $this->getContext()->setUser( $wgUser );
  221. $request->response()->header( 'MediaWiki-Login-Suppressed: true' );
  222. }
  223. }
  224. $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
  225. // Setup uselang. This doesn't use $this->getParameter()
  226. // because we're not ready to handle errors yet.
  227. $uselang = $request->getVal( 'uselang', self::API_DEFAULT_USELANG );
  228. if ( $uselang === 'user' ) {
  229. // Assume the parent context is going to return the user language
  230. // for uselang=user (see T85635).
  231. } else {
  232. if ( $uselang === 'content' ) {
  233. global $wgContLang;
  234. $uselang = $wgContLang->getCode();
  235. }
  236. $code = RequestContext::sanitizeLangCode( $uselang );
  237. $this->getContext()->setLanguage( $code );
  238. if ( !$this->mInternalMode ) {
  239. global $wgLang;
  240. $wgLang = $this->getContext()->getLanguage();
  241. RequestContext::getMain()->setLanguage( $wgLang );
  242. }
  243. }
  244. // Set up the error formatter. This doesn't use $this->getParameter()
  245. // because we're not ready to handle errors yet.
  246. $errorFormat = $request->getVal( 'errorformat', 'bc' );
  247. $errorLangCode = $request->getVal( 'errorlang', 'uselang' );
  248. $errorsUseDB = $request->getCheck( 'errorsuselocal' );
  249. if ( in_array( $errorFormat, [ 'plaintext', 'wikitext', 'html', 'raw', 'none' ], true ) ) {
  250. if ( $errorLangCode === 'uselang' ) {
  251. $errorLang = $this->getLanguage();
  252. } elseif ( $errorLangCode === 'content' ) {
  253. global $wgContLang;
  254. $errorLang = $wgContLang;
  255. } else {
  256. $errorLangCode = RequestContext::sanitizeLangCode( $errorLangCode );
  257. $errorLang = Language::factory( $errorLangCode );
  258. }
  259. $this->mErrorFormatter = new ApiErrorFormatter(
  260. $this->mResult, $errorLang, $errorFormat, $errorsUseDB
  261. );
  262. } else {
  263. $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
  264. }
  265. $this->mResult->setErrorFormatter( $this->getErrorFormatter() );
  266. $this->mModuleMgr = new ApiModuleManager( $this );
  267. $this->mModuleMgr->addModules( self::$Modules, 'action' );
  268. $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
  269. $this->mModuleMgr->addModules( self::$Formats, 'format' );
  270. $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
  271. Hooks::run( 'ApiMain::moduleManager', [ $this->mModuleMgr ] );
  272. $this->mContinuationManager = null;
  273. $this->mEnableWrite = $enableWrite;
  274. $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
  275. $this->mCommit = false;
  276. }
  277. /**
  278. * Return true if the API was started by other PHP code using FauxRequest
  279. * @return bool
  280. */
  281. public function isInternalMode() {
  282. return $this->mInternalMode;
  283. }
  284. /**
  285. * Get the ApiResult object associated with current request
  286. *
  287. * @return ApiResult
  288. */
  289. public function getResult() {
  290. return $this->mResult;
  291. }
  292. /**
  293. * Get the security flag for the current request
  294. * @return bool
  295. */
  296. public function lacksSameOriginSecurity() {
  297. if ( $this->lacksSameOriginSecurity !== null ) {
  298. return $this->lacksSameOriginSecurity;
  299. }
  300. $request = $this->getRequest();
  301. // JSONP mode
  302. if ( $request->getVal( 'callback' ) !== null ) {
  303. $this->lacksSameOriginSecurity = true;
  304. return true;
  305. }
  306. // Anonymous CORS
  307. if ( $request->getVal( 'origin' ) === '*' ) {
  308. $this->lacksSameOriginSecurity = true;
  309. return true;
  310. }
  311. // Header to be used from XMLHTTPRequest when the request might
  312. // otherwise be used for XSS.
  313. if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
  314. $this->lacksSameOriginSecurity = true;
  315. return true;
  316. }
  317. // Allow extensions to override.
  318. $this->lacksSameOriginSecurity = !Hooks::run( 'RequestHasSameOriginSecurity', [ $request ] );
  319. return $this->lacksSameOriginSecurity;
  320. }
  321. /**
  322. * Get the ApiErrorFormatter object associated with current request
  323. * @return ApiErrorFormatter
  324. */
  325. public function getErrorFormatter() {
  326. return $this->mErrorFormatter;
  327. }
  328. /**
  329. * Get the continuation manager
  330. * @return ApiContinuationManager|null
  331. */
  332. public function getContinuationManager() {
  333. return $this->mContinuationManager;
  334. }
  335. /**
  336. * Set the continuation manager
  337. * @param ApiContinuationManager|null $manager
  338. */
  339. public function setContinuationManager( $manager ) {
  340. if ( $manager !== null ) {
  341. if ( !$manager instanceof ApiContinuationManager ) {
  342. throw new InvalidArgumentException( __METHOD__ . ': Was passed ' .
  343. is_object( $manager ) ? get_class( $manager ) : gettype( $manager )
  344. );
  345. }
  346. if ( $this->mContinuationManager !== null ) {
  347. throw new UnexpectedValueException(
  348. __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
  349. ' when a manager is already set from ' . $this->mContinuationManager->getSource()
  350. );
  351. }
  352. }
  353. $this->mContinuationManager = $manager;
  354. }
  355. /**
  356. * Get the API module object. Only works after executeAction()
  357. *
  358. * @return ApiBase
  359. */
  360. public function getModule() {
  361. return $this->mModule;
  362. }
  363. /**
  364. * Get the result formatter object. Only works after setupExecuteAction()
  365. *
  366. * @return ApiFormatBase
  367. */
  368. public function getPrinter() {
  369. return $this->mPrinter;
  370. }
  371. /**
  372. * Set how long the response should be cached.
  373. *
  374. * @param int $maxage
  375. */
  376. public function setCacheMaxAge( $maxage ) {
  377. $this->setCacheControl( [
  378. 'max-age' => $maxage,
  379. 's-maxage' => $maxage
  380. ] );
  381. }
  382. /**
  383. * Set the type of caching headers which will be sent.
  384. *
  385. * @param string $mode One of:
  386. * - 'public': Cache this object in public caches, if the maxage or smaxage
  387. * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
  388. * not provided by any of these means, the object will be private.
  389. * - 'private': Cache this object only in private client-side caches.
  390. * - 'anon-public-user-private': Make this object cacheable for logged-out
  391. * users, but private for logged-in users. IMPORTANT: If this is set, it must be
  392. * set consistently for a given URL, it cannot be set differently depending on
  393. * things like the contents of the database, or whether the user is logged in.
  394. *
  395. * If the wiki does not allow anonymous users to read it, the mode set here
  396. * will be ignored, and private caching headers will always be sent. In other words,
  397. * the "public" mode is equivalent to saying that the data sent is as public as a page
  398. * view.
  399. *
  400. * For user-dependent data, the private mode should generally be used. The
  401. * anon-public-user-private mode should only be used where there is a particularly
  402. * good performance reason for caching the anonymous response, but where the
  403. * response to logged-in users may differ, or may contain private data.
  404. *
  405. * If this function is never called, then the default will be the private mode.
  406. */
  407. public function setCacheMode( $mode ) {
  408. if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
  409. wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
  410. // Ignore for forwards-compatibility
  411. return;
  412. }
  413. if ( !User::isEveryoneAllowed( 'read' ) ) {
  414. // Private wiki, only private headers
  415. if ( $mode !== 'private' ) {
  416. wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
  417. return;
  418. }
  419. }
  420. if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
  421. // User language is used for i18n, so we don't want to publicly
  422. // cache. Anons are ok, because if they have non-default language
  423. // then there's an appropriate Vary header set by whatever set
  424. // their non-default language.
  425. wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
  426. "'anon-public-user-private' due to uselang=user\n" );
  427. $mode = 'anon-public-user-private';
  428. }
  429. wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
  430. $this->mCacheMode = $mode;
  431. }
  432. /**
  433. * Set directives (key/value pairs) for the Cache-Control header.
  434. * Boolean values will be formatted as such, by including or omitting
  435. * without an equals sign.
  436. *
  437. * Cache control values set here will only be used if the cache mode is not
  438. * private, see setCacheMode().
  439. *
  440. * @param array $directives
  441. */
  442. public function setCacheControl( $directives ) {
  443. $this->mCacheControl = $directives + $this->mCacheControl;
  444. }
  445. /**
  446. * Create an instance of an output formatter by its name
  447. *
  448. * @param string $format
  449. *
  450. * @return ApiFormatBase
  451. */
  452. public function createPrinterByName( $format ) {
  453. $printer = $this->mModuleMgr->getModule( $format, 'format' );
  454. if ( $printer === null ) {
  455. $this->dieWithError(
  456. [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
  457. );
  458. }
  459. return $printer;
  460. }
  461. /**
  462. * Execute api request. Any errors will be handled if the API was called by the remote client.
  463. */
  464. public function execute() {
  465. if ( $this->mInternalMode ) {
  466. $this->executeAction();
  467. } else {
  468. $this->executeActionWithErrorHandling();
  469. }
  470. }
  471. /**
  472. * Execute an action, and in case of an error, erase whatever partial results
  473. * have been accumulated, and replace it with an error message and a help screen.
  474. */
  475. protected function executeActionWithErrorHandling() {
  476. // Verify the CORS header before executing the action
  477. if ( !$this->handleCORS() ) {
  478. // handleCORS() has sent a 403, abort
  479. return;
  480. }
  481. // Exit here if the request method was OPTIONS
  482. // (assume there will be a followup GET or POST)
  483. if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
  484. return;
  485. }
  486. // In case an error occurs during data output,
  487. // clear the output buffer and print just the error information
  488. $obLevel = ob_get_level();
  489. ob_start();
  490. $t = microtime( true );
  491. $isError = false;
  492. try {
  493. $this->executeAction();
  494. $runTime = microtime( true ) - $t;
  495. $this->logRequest( $runTime );
  496. if ( $this->mModule->isWriteMode() && $this->getRequest()->wasPosted() ) {
  497. MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
  498. 'api.' . $this->mModule->getModuleName() . '.executeTiming', 1000 * $runTime
  499. );
  500. }
  501. } catch ( Exception $e ) {
  502. $this->handleException( $e );
  503. $this->logRequest( microtime( true ) - $t, $e );
  504. $isError = true;
  505. }
  506. // Commit DBs and send any related cookies and headers
  507. MediaWiki::preOutputCommit( $this->getContext() );
  508. // Send cache headers after any code which might generate an error, to
  509. // avoid sending public cache headers for errors.
  510. $this->sendCacheHeaders( $isError );
  511. // Executing the action might have already messed with the output
  512. // buffers.
  513. while ( ob_get_level() > $obLevel ) {
  514. ob_end_flush();
  515. }
  516. }
  517. /**
  518. * Handle an exception as an API response
  519. *
  520. * @since 1.23
  521. * @param Exception $e
  522. */
  523. protected function handleException( Exception $e ) {
  524. // T65145: Rollback any open database transactions
  525. if ( !( $e instanceof ApiUsageException || $e instanceof UsageException ) ) {
  526. // UsageExceptions are intentional, so don't rollback if that's the case
  527. MWExceptionHandler::rollbackMasterChangesAndLog( $e );
  528. }
  529. // Allow extra cleanup and logging
  530. Hooks::run( 'ApiMain::onException', [ $this, $e ] );
  531. // Handle any kind of exception by outputting properly formatted error message.
  532. // If this fails, an unhandled exception should be thrown so that global error
  533. // handler will process and log it.
  534. $errCodes = $this->substituteResultWithError( $e );
  535. // Error results should not be cached
  536. $this->setCacheMode( 'private' );
  537. $response = $this->getRequest()->response();
  538. $headerStr = 'MediaWiki-API-Error: ' . join( ', ', $errCodes );
  539. $response->header( $headerStr );
  540. // Reset and print just the error message
  541. ob_clean();
  542. // Printer may not be initialized if the extractRequestParams() fails for the main module
  543. $this->createErrorPrinter();
  544. $failed = false;
  545. try {
  546. $this->printResult( $e->getCode() );
  547. } catch ( ApiUsageException $ex ) {
  548. // The error printer itself is failing. Try suppressing its request
  549. // parameters and redo.
  550. $failed = true;
  551. $this->addWarning( 'apiwarn-errorprinterfailed' );
  552. foreach ( $ex->getStatusValue()->getErrors() as $error ) {
  553. try {
  554. $this->mPrinter->addWarning( $error );
  555. } catch ( Exception $ex2 ) {
  556. // WTF?
  557. $this->addWarning( $error );
  558. }
  559. }
  560. } catch ( UsageException $ex ) {
  561. // The error printer itself is failing. Try suppressing its request
  562. // parameters and redo.
  563. $failed = true;
  564. $this->addWarning(
  565. [ 'apiwarn-errorprinterfailed-ex', $ex->getMessage() ], 'errorprinterfailed'
  566. );
  567. }
  568. if ( $failed ) {
  569. $this->mPrinter = null;
  570. $this->createErrorPrinter();
  571. $this->mPrinter->forceDefaultParams();
  572. if ( $e->getCode() ) {
  573. $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
  574. }
  575. $this->printResult( $e->getCode() );
  576. }
  577. }
  578. /**
  579. * Handle an exception from the ApiBeforeMain hook.
  580. *
  581. * This tries to print the exception as an API response, to be more
  582. * friendly to clients. If it fails, it will rethrow the exception.
  583. *
  584. * @since 1.23
  585. * @param Exception $e
  586. * @throws Exception
  587. */
  588. public static function handleApiBeforeMainException( Exception $e ) {
  589. ob_start();
  590. try {
  591. $main = new self( RequestContext::getMain(), false );
  592. $main->handleException( $e );
  593. $main->logRequest( 0, $e );
  594. } catch ( Exception $e2 ) {
  595. // Nope, even that didn't work. Punt.
  596. throw $e;
  597. }
  598. // Reset cache headers
  599. $main->sendCacheHeaders( true );
  600. ob_end_flush();
  601. }
  602. /**
  603. * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
  604. *
  605. * If no origin parameter is present, nothing happens.
  606. * If an origin parameter is present but doesn't match the Origin header, a 403 status code
  607. * is set and false is returned.
  608. * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
  609. * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
  610. * headers are set.
  611. * https://www.w3.org/TR/cors/#resource-requests
  612. * https://www.w3.org/TR/cors/#resource-preflight-requests
  613. *
  614. * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
  615. */
  616. protected function handleCORS() {
  617. $originParam = $this->getParameter( 'origin' ); // defaults to null
  618. if ( $originParam === null ) {
  619. // No origin parameter, nothing to do
  620. return true;
  621. }
  622. $request = $this->getRequest();
  623. $response = $request->response();
  624. $matchedOrigin = false;
  625. $allowTiming = false;
  626. $varyOrigin = true;
  627. if ( $originParam === '*' ) {
  628. // Request for anonymous CORS
  629. // Technically we should check for the presence of an Origin header
  630. // and not process it as CORS if it's not set, but that would
  631. // require us to vary on Origin for all 'origin=*' requests which
  632. // we don't want to do.
  633. $matchedOrigin = true;
  634. $allowOrigin = '*';
  635. $allowCredentials = 'false';
  636. $varyOrigin = false; // No need to vary
  637. } else {
  638. // Non-anonymous CORS, check we allow the domain
  639. // Origin: header is a space-separated list of origins, check all of them
  640. $originHeader = $request->getHeader( 'Origin' );
  641. if ( $originHeader === false ) {
  642. $origins = [];
  643. } else {
  644. $originHeader = trim( $originHeader );
  645. $origins = preg_split( '/\s+/', $originHeader );
  646. }
  647. if ( !in_array( $originParam, $origins ) ) {
  648. // origin parameter set but incorrect
  649. // Send a 403 response
  650. $response->statusHeader( 403 );
  651. $response->header( 'Cache-Control: no-cache' );
  652. echo "'origin' parameter does not match Origin header\n";
  653. return false;
  654. }
  655. $config = $this->getConfig();
  656. $matchedOrigin = count( $origins ) === 1 && self::matchOrigin(
  657. $originParam,
  658. $config->get( 'CrossSiteAJAXdomains' ),
  659. $config->get( 'CrossSiteAJAXdomainExceptions' )
  660. );
  661. $allowOrigin = $originHeader;
  662. $allowCredentials = 'true';
  663. $allowTiming = $originHeader;
  664. }
  665. if ( $matchedOrigin ) {
  666. $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
  667. $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
  668. if ( $preflight ) {
  669. // This is a CORS preflight request
  670. if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
  671. // If method is not a case-sensitive match, do not set any additional headers and terminate.
  672. $response->header( 'MediaWiki-CORS-Rejection: Unsupported method requested in preflight' );
  673. return true;
  674. }
  675. // We allow the actual request to send the following headers
  676. $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
  677. if ( $requestedHeaders !== false ) {
  678. if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
  679. $response->header( 'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
  680. return true;
  681. }
  682. $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
  683. }
  684. // We only allow the actual request to be GET or POST
  685. $response->header( 'Access-Control-Allow-Methods: POST, GET' );
  686. } elseif ( $request->getMethod() !== 'POST' && $request->getMethod() !== 'GET' ) {
  687. // Unsupported non-preflight method, don't handle it as CORS
  688. $response->header(
  689. 'MediaWiki-CORS-Rejection: Unsupported method for simple request or actual request'
  690. );
  691. return true;
  692. }
  693. $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
  694. $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
  695. // https://www.w3.org/TR/resource-timing/#timing-allow-origin
  696. if ( $allowTiming !== false ) {
  697. $response->header( "Timing-Allow-Origin: $allowTiming" );
  698. }
  699. if ( !$preflight ) {
  700. $response->header(
  701. 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
  702. . 'MediaWiki-Login-Suppressed'
  703. );
  704. }
  705. } else {
  706. $response->header( 'MediaWiki-CORS-Rejection: Origin mismatch' );
  707. }
  708. if ( $varyOrigin ) {
  709. $this->getOutput()->addVaryHeader( 'Origin' );
  710. }
  711. return true;
  712. }
  713. /**
  714. * Attempt to match an Origin header against a set of rules and a set of exceptions
  715. * @param string $value Origin header
  716. * @param array $rules Set of wildcard rules
  717. * @param array $exceptions Set of wildcard rules
  718. * @return bool True if $value matches a rule in $rules and doesn't match
  719. * any rules in $exceptions, false otherwise
  720. */
  721. protected static function matchOrigin( $value, $rules, $exceptions ) {
  722. foreach ( $rules as $rule ) {
  723. if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
  724. // Rule matches, check exceptions
  725. foreach ( $exceptions as $exc ) {
  726. if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
  727. return false;
  728. }
  729. }
  730. return true;
  731. }
  732. }
  733. return false;
  734. }
  735. /**
  736. * Attempt to validate the value of Access-Control-Request-Headers against a list
  737. * of headers that we allow the follow up request to send.
  738. *
  739. * @param string $requestedHeaders Comma seperated list of HTTP headers
  740. * @return bool True if all requested headers are in the list of allowed headers
  741. */
  742. protected static function matchRequestedHeaders( $requestedHeaders ) {
  743. if ( trim( $requestedHeaders ) === '' ) {
  744. return true;
  745. }
  746. $requestedHeaders = explode( ',', $requestedHeaders );
  747. $allowedAuthorHeaders = array_flip( [
  748. /* simple headers (see spec) */
  749. 'accept',
  750. 'accept-language',
  751. 'content-language',
  752. 'content-type',
  753. /* non-authorable headers in XHR, which are however requested by some UAs */
  754. 'accept-encoding',
  755. 'dnt',
  756. 'origin',
  757. /* MediaWiki whitelist */
  758. 'api-user-agent',
  759. ] );
  760. foreach ( $requestedHeaders as $rHeader ) {
  761. $rHeader = strtolower( trim( $rHeader ) );
  762. if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
  763. wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
  764. return false;
  765. }
  766. }
  767. return true;
  768. }
  769. /**
  770. * Helper function to convert wildcard string into a regex
  771. * '*' => '.*?'
  772. * '?' => '.'
  773. *
  774. * @param string $wildcard String with wildcards
  775. * @return string Regular expression
  776. */
  777. protected static function wildcardToRegex( $wildcard ) {
  778. $wildcard = preg_quote( $wildcard, '/' );
  779. $wildcard = str_replace(
  780. [ '\*', '\?' ],
  781. [ '.*?', '.' ],
  782. $wildcard
  783. );
  784. return "/^https?:\/\/$wildcard$/";
  785. }
  786. /**
  787. * Send caching headers
  788. * @param bool $isError Whether an error response is being output
  789. * @since 1.26 added $isError parameter
  790. */
  791. protected function sendCacheHeaders( $isError ) {
  792. $response = $this->getRequest()->response();
  793. $out = $this->getOutput();
  794. $out->addVaryHeader( 'Treat-as-Untrusted' );
  795. $config = $this->getConfig();
  796. if ( $config->get( 'VaryOnXFP' ) ) {
  797. $out->addVaryHeader( 'X-Forwarded-Proto' );
  798. }
  799. if ( !$isError && $this->mModule &&
  800. ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
  801. ) {
  802. $etag = $this->mModule->getConditionalRequestData( 'etag' );
  803. if ( $etag !== null ) {
  804. $response->header( "ETag: $etag" );
  805. }
  806. $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
  807. if ( $lastMod !== null ) {
  808. $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
  809. }
  810. }
  811. // The logic should be:
  812. // $this->mCacheControl['max-age'] is set?
  813. // Use it, the module knows better than our guess.
  814. // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
  815. // Use 0 because we can guess caching is probably the wrong thing to do.
  816. // Use $this->getParameter( 'maxage' ), which already defaults to 0.
  817. $maxage = 0;
  818. if ( isset( $this->mCacheControl['max-age'] ) ) {
  819. $maxage = $this->mCacheControl['max-age'];
  820. } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
  821. $this->mCacheMode !== 'private'
  822. ) {
  823. $maxage = $this->getParameter( 'maxage' );
  824. }
  825. $privateCache = 'private, must-revalidate, max-age=' . $maxage;
  826. if ( $this->mCacheMode == 'private' ) {
  827. $response->header( "Cache-Control: $privateCache" );
  828. return;
  829. }
  830. $useKeyHeader = $config->get( 'UseKeyHeader' );
  831. if ( $this->mCacheMode == 'anon-public-user-private' ) {
  832. $out->addVaryHeader( 'Cookie' );
  833. $response->header( $out->getVaryHeader() );
  834. if ( $useKeyHeader ) {
  835. $response->header( $out->getKeyHeader() );
  836. if ( $out->haveCacheVaryCookies() ) {
  837. // Logged in, mark this request private
  838. $response->header( "Cache-Control: $privateCache" );
  839. return;
  840. }
  841. // Logged out, send normal public headers below
  842. } elseif ( MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent() ) {
  843. // Logged in or otherwise has session (e.g. anonymous users who have edited)
  844. // Mark request private
  845. $response->header( "Cache-Control: $privateCache" );
  846. return;
  847. } // else no Key and anonymous, send public headers below
  848. }
  849. // Send public headers
  850. $response->header( $out->getVaryHeader() );
  851. if ( $useKeyHeader ) {
  852. $response->header( $out->getKeyHeader() );
  853. }
  854. // If nobody called setCacheMaxAge(), use the (s)maxage parameters
  855. if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
  856. $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
  857. }
  858. if ( !isset( $this->mCacheControl['max-age'] ) ) {
  859. $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
  860. }
  861. if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
  862. // Public cache not requested
  863. // Sending a Vary header in this case is harmless, and protects us
  864. // against conditional calls of setCacheMaxAge().
  865. $response->header( "Cache-Control: $privateCache" );
  866. return;
  867. }
  868. $this->mCacheControl['public'] = true;
  869. // Send an Expires header
  870. $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
  871. $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
  872. $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
  873. // Construct the Cache-Control header
  874. $ccHeader = '';
  875. $separator = '';
  876. foreach ( $this->mCacheControl as $name => $value ) {
  877. if ( is_bool( $value ) ) {
  878. if ( $value ) {
  879. $ccHeader .= $separator . $name;
  880. $separator = ', ';
  881. }
  882. } else {
  883. $ccHeader .= $separator . "$name=$value";
  884. $separator = ', ';
  885. }
  886. }
  887. $response->header( "Cache-Control: $ccHeader" );
  888. }
  889. /**
  890. * Create the printer for error output
  891. */
  892. private function createErrorPrinter() {
  893. if ( !isset( $this->mPrinter ) ) {
  894. $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
  895. if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
  896. $value = self::API_DEFAULT_FORMAT;
  897. }
  898. $this->mPrinter = $this->createPrinterByName( $value );
  899. }
  900. // Printer may not be able to handle errors. This is particularly
  901. // likely if the module returns something for getCustomPrinter().
  902. if ( !$this->mPrinter->canPrintErrors() ) {
  903. $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
  904. }
  905. }
  906. /**
  907. * Create an error message for the given exception.
  908. *
  909. * If an ApiUsageException, errors/warnings will be extracted from the
  910. * embedded StatusValue.
  911. *
  912. * If a base UsageException, the getMessageArray() method will be used to
  913. * extract the code and English message for a single error (no warnings).
  914. *
  915. * Any other exception will be returned with a generic code and wrapper
  916. * text around the exception's (presumably English) message as a single
  917. * error (no warnings).
  918. *
  919. * @param Exception $e
  920. * @param string $type 'error' or 'warning'
  921. * @return ApiMessage[]
  922. * @since 1.27
  923. */
  924. protected function errorMessagesFromException( $e, $type = 'error' ) {
  925. $messages = [];
  926. if ( $e instanceof ApiUsageException ) {
  927. foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
  928. $messages[] = ApiMessage::create( $error );
  929. }
  930. } elseif ( $type !== 'error' ) {
  931. // None of the rest have any messages for non-error types
  932. } elseif ( $e instanceof UsageException ) {
  933. // User entered incorrect parameters - generate error response
  934. $data = MediaWiki\quietCall( [ $e, 'getMessageArray' ] );
  935. $code = $data['code'];
  936. $info = $data['info'];
  937. unset( $data['code'], $data['info'] );
  938. $messages[] = new ApiRawMessage( [ '$1', $info ], $code, $data );
  939. } else {
  940. // Something is seriously wrong
  941. $config = $this->getConfig();
  942. $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $e ) );
  943. $code = 'internal_api_error_' . $class;
  944. if ( ( $e instanceof DBQueryError ) && !$config->get( 'ShowSQLErrors' ) ) {
  945. $params = [ 'apierror-databaseerror', WebRequest::getRequestId() ];
  946. } else {
  947. $params = [
  948. 'apierror-exceptioncaught',
  949. WebRequest::getRequestId(),
  950. $e instanceof ILocalizedException
  951. ? $e->getMessageObject()
  952. : wfEscapeWikiText( $e->getMessage() )
  953. ];
  954. }
  955. $messages[] = ApiMessage::create( $params, $code );
  956. }
  957. return $messages;
  958. }
  959. /**
  960. * Replace the result data with the information about an exception.
  961. * @param Exception $e
  962. * @return string[] Error codes
  963. */
  964. protected function substituteResultWithError( $e ) {
  965. $result = $this->getResult();
  966. $formatter = $this->getErrorFormatter();
  967. $config = $this->getConfig();
  968. $errorCodes = [];
  969. // Remember existing warnings and errors across the reset
  970. $errors = $result->getResultData( [ 'errors' ] );
  971. $warnings = $result->getResultData( [ 'warnings' ] );
  972. $result->reset();
  973. if ( $warnings !== null ) {
  974. $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
  975. }
  976. if ( $errors !== null ) {
  977. $result->addValue( null, 'errors', $errors, ApiResult::NO_SIZE_CHECK );
  978. // Collect the copied error codes for the return value
  979. foreach ( $errors as $error ) {
  980. if ( isset( $error['code'] ) ) {
  981. $errorCodes[$error['code']] = true;
  982. }
  983. }
  984. }
  985. // Add errors from the exception
  986. $modulePath = $e instanceof ApiUsageException ? $e->getModulePath() : null;
  987. foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
  988. $errorCodes[$msg->getApiCode()] = true;
  989. $formatter->addError( $modulePath, $msg );
  990. }
  991. foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
  992. $formatter->addWarning( $modulePath, $msg );
  993. }
  994. // Add additional data. Path depends on whether we're in BC mode or not.
  995. // Data depends on the type of exception.
  996. if ( $formatter instanceof ApiErrorFormatter_BackCompat ) {
  997. $path = [ 'error' ];
  998. } else {
  999. $path = null;
  1000. }
  1001. if ( $e instanceof ApiUsageException || $e instanceof UsageException ) {
  1002. $link = wfExpandUrl( wfScript( 'api' ) );
  1003. $result->addContentValue(
  1004. $path,
  1005. 'docref',
  1006. trim(
  1007. $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
  1008. . ' '
  1009. . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
  1010. )
  1011. );
  1012. } else {
  1013. if ( $config->get( 'ShowExceptionDetails' ) &&
  1014. ( !$e instanceof DBError || $config->get( 'ShowDBErrorBacktrace' ) )
  1015. ) {
  1016. $result->addContentValue(
  1017. $path,
  1018. 'trace',
  1019. $this->msg( 'api-exception-trace',
  1020. get_class( $e ),
  1021. $e->getFile(),
  1022. $e->getLine(),
  1023. MWExceptionHandler::getRedactedTraceAsString( $e )
  1024. )->inLanguage( $formatter->getLanguage() )->text()
  1025. );
  1026. }
  1027. }
  1028. // Add the id and such
  1029. $this->addRequestedFields( [ 'servedby' ] );
  1030. return array_keys( $errorCodes );
  1031. }
  1032. /**
  1033. * Add requested fields to the result
  1034. * @param string[] $force Which fields to force even if not requested. Accepted values are:
  1035. * - servedby
  1036. */
  1037. protected function addRequestedFields( $force = [] ) {
  1038. $result = $this->getResult();
  1039. $requestid = $this->getParameter( 'requestid' );
  1040. if ( $requestid !== null ) {
  1041. $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
  1042. }
  1043. if ( $this->getConfig()->get( 'ShowHostnames' ) && (
  1044. in_array( 'servedby', $force, true ) || $this->getParameter( 'servedby' )
  1045. ) ) {
  1046. $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
  1047. }
  1048. if ( $this->getParameter( 'curtimestamp' ) ) {
  1049. $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601, time() ),
  1050. ApiResult::NO_SIZE_CHECK );
  1051. }
  1052. if ( $this->getParameter( 'responselanginfo' ) ) {
  1053. $result->addValue( null, 'uselang', $this->getLanguage()->getCode(),
  1054. ApiResult::NO_SIZE_CHECK );
  1055. $result->addValue( null, 'errorlang', $this->getErrorFormatter()->getLanguage()->getCode(),
  1056. ApiResult::NO_SIZE_CHECK );
  1057. }
  1058. }
  1059. /**
  1060. * Set up for the execution.
  1061. * @return array
  1062. */
  1063. protected function setupExecuteAction() {
  1064. $this->addRequestedFields();
  1065. $params = $this->extractRequestParams();
  1066. $this->mAction = $params['action'];
  1067. return $params;
  1068. }
  1069. /**
  1070. * Set up the module for response
  1071. * @return ApiBase The module that will handle this action
  1072. * @throws MWException
  1073. * @throws ApiUsageException
  1074. */
  1075. protected function setupModule() {
  1076. // Instantiate the module requested by the user
  1077. $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
  1078. if ( $module === null ) {
  1079. $this->dieWithError(
  1080. [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction ) ], 'unknown_action'
  1081. );
  1082. }
  1083. $moduleParams = $module->extractRequestParams();
  1084. // Check token, if necessary
  1085. if ( $module->needsToken() === true ) {
  1086. throw new MWException(
  1087. "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
  1088. 'See documentation for ApiBase::needsToken for details.'
  1089. );
  1090. }
  1091. if ( $module->needsToken() ) {
  1092. if ( !$module->mustBePosted() ) {
  1093. throw new MWException(
  1094. "Module '{$module->getModuleName()}' must require POST to use tokens."
  1095. );
  1096. }
  1097. if ( !isset( $moduleParams['token'] ) ) {
  1098. $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
  1099. }
  1100. $module->requirePostedParameters( [ 'token' ] );
  1101. if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
  1102. $module->dieWithError( 'apierror-badtoken' );
  1103. }
  1104. }
  1105. return $module;
  1106. }
  1107. /**
  1108. * @return array
  1109. */
  1110. private function getMaxLag() {
  1111. $dbLag = MediaWikiServices::getInstance()->getDBLoadBalancer()->getMaxLag();
  1112. $lagInfo = [
  1113. 'host' => $dbLag[0],
  1114. 'lag' => $dbLag[1],
  1115. 'type' => 'db'
  1116. ];
  1117. $jobQueueLagFactor = $this->getConfig()->get( 'JobQueueIncludeInMaxLagFactor' );
  1118. if ( $jobQueueLagFactor ) {
  1119. // Turn total number of jobs into seconds by using the configured value
  1120. $totalJobs = array_sum( JobQueueGroup::singleton()->getQueueSizes() );
  1121. $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
  1122. if ( $jobQueueLag > $lagInfo['lag'] ) {
  1123. $lagInfo = [
  1124. 'host' => wfHostname(), // XXX: Is there a better value that could be used?
  1125. 'lag' => $jobQueueLag,
  1126. 'type' => 'jobqueue',
  1127. 'jobs' => $totalJobs,
  1128. ];
  1129. }
  1130. }
  1131. return $lagInfo;
  1132. }
  1133. /**
  1134. * Check the max lag if necessary
  1135. * @param ApiBase $module Api module being used
  1136. * @param array $params Array an array containing the request parameters.
  1137. * @return bool True on success, false should exit immediately
  1138. */
  1139. protected function checkMaxLag( $module, $params ) {
  1140. if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
  1141. $maxLag = $params['maxlag'];
  1142. $lagInfo = $this->getMaxLag();
  1143. if ( $lagInfo['lag'] > $maxLag ) {
  1144. $response = $this->getRequest()->response();
  1145. $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
  1146. $response->header( 'X-Database-Lag: ' . intval( $lagInfo['lag'] ) );
  1147. if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
  1148. $this->dieWithError(
  1149. [ 'apierror-maxlag', $lagInfo['lag'], $lagInfo['host'] ],
  1150. 'maxlag',
  1151. $lagInfo
  1152. );
  1153. }
  1154. $this->dieWithError( [ 'apierror-maxlag-generic', $lagInfo['lag'] ], 'maxlag', $lagInfo );
  1155. }
  1156. }
  1157. return true;
  1158. }
  1159. /**
  1160. * Check selected RFC 7232 precondition headers
  1161. *
  1162. * RFC 7232 envisions a particular model where you send your request to "a
  1163. * resource", and for write requests that you can read "the resource" by
  1164. * changing the method to GET. When the API receives a GET request, it
  1165. * works out even though "the resource" from RFC 7232's perspective might
  1166. * be many resources from MediaWiki's perspective. But it totally fails for
  1167. * a POST, since what HTTP sees as "the resource" is probably just
  1168. * "/api.php" with all the interesting bits in the body.
  1169. *
  1170. * Therefore, we only support RFC 7232 precondition headers for GET (and
  1171. * HEAD). That means we don't need to bother with If-Match and
  1172. * If-Unmodified-Since since they only apply to modification requests.
  1173. *
  1174. * And since we don't support Range, If-Range is ignored too.
  1175. *
  1176. * @since 1.26
  1177. * @param ApiBase $module Api module being used
  1178. * @return bool True on success, false should exit immediately
  1179. */
  1180. protected function checkConditionalRequestHeaders( $module ) {
  1181. if ( $this->mInternalMode ) {
  1182. // No headers to check in internal mode
  1183. return true;
  1184. }
  1185. if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
  1186. // Don't check POSTs
  1187. return true;
  1188. }
  1189. $return304 = false;
  1190. $ifNoneMatch = array_diff(
  1191. $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
  1192. [ '' ]
  1193. );
  1194. if ( $ifNoneMatch ) {
  1195. if ( $ifNoneMatch === [ '*' ] ) {
  1196. // API responses always "exist"
  1197. $etag = '*';
  1198. } else {
  1199. $etag = $module->getConditionalRequestData( 'etag' );
  1200. }
  1201. }
  1202. if ( $ifNoneMatch && $etag !== null ) {
  1203. $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
  1204. $match = array_map( function ( $s ) {
  1205. return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
  1206. }, $ifNoneMatch );
  1207. $return304 = in_array( $test, $match, true );
  1208. } else {
  1209. $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
  1210. // Some old browsers sends sizes after the date, like this:
  1211. // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
  1212. // Ignore that.
  1213. $i = strpos( $value, ';' );
  1214. if ( $i !== false ) {
  1215. $value = trim( substr( $value, 0, $i ) );
  1216. }
  1217. if ( $value !== '' ) {
  1218. try {
  1219. $ts = new MWTimestamp( $value );
  1220. if (
  1221. // RFC 7231 IMF-fixdate
  1222. $ts->getTimestamp( TS_RFC2822 ) === $value ||
  1223. // RFC 850
  1224. $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
  1225. // asctime (with and without space-padded day)
  1226. $ts->format( 'D M j H:i:s Y' ) === $value ||
  1227. $ts->format( 'D M j H:i:s Y' ) === $value
  1228. ) {
  1229. $lastMod = $module->getConditionalRequestData( 'last-modified' );
  1230. if ( $lastMod !== null ) {
  1231. // Mix in some MediaWiki modification times
  1232. $modifiedTimes = [
  1233. 'page' => $lastMod,
  1234. 'user' => $this->getUser()->getTouched(),
  1235. 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
  1236. ];
  1237. if ( $this->getConfig()->get( 'UseSquid' ) ) {
  1238. // T46570: the core page itself may not change, but resources might
  1239. $modifiedTimes['sepoch'] = wfTimestamp(
  1240. TS_MW, time() - $this->getConfig()->get( 'SquidMaxage' )
  1241. );
  1242. }
  1243. Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
  1244. $lastMod = max( $modifiedTimes );
  1245. $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
  1246. }
  1247. }
  1248. } catch ( TimestampException $e ) {
  1249. // Invalid timestamp, ignore it
  1250. }
  1251. }
  1252. }
  1253. if ( $return304 ) {
  1254. $this->getRequest()->response()->statusHeader( 304 );
  1255. // Avoid outputting the compressed representation of a zero-length body
  1256. MediaWiki\suppressWarnings();
  1257. ini_set( 'zlib.output_compression', 0 );
  1258. MediaWiki\restoreWarnings();
  1259. wfClearOutputBuffers();
  1260. return false;
  1261. }
  1262. return true;
  1263. }
  1264. /**
  1265. * Check for sufficient permissions to execute
  1266. * @param ApiBase $module An Api module
  1267. */
  1268. protected function checkExecutePermissions( $module ) {
  1269. $user = $this->getUser();
  1270. if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
  1271. !$user->isAllowed( 'read' )
  1272. ) {
  1273. $this->dieWithError( 'apierror-readapidenied' );
  1274. }
  1275. if ( $module->isWriteMode() ) {
  1276. if ( !$this->mEnableWrite ) {
  1277. $this->dieWithError( 'apierror-noapiwrite' );
  1278. } elseif ( !$user->isAllowed( 'writeapi' ) ) {
  1279. $this->dieWithError( 'apierror-writeapidenied' );
  1280. } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
  1281. $this->dieWithError( 'apierror-promised-nonwrite-api' );
  1282. }
  1283. $this->checkReadOnly( $module );
  1284. }
  1285. // Allow extensions to stop execution for arbitrary reasons.
  1286. $message = false;
  1287. if ( !Hooks::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
  1288. $this->dieWithError( $message );
  1289. }
  1290. }
  1291. /**
  1292. * Check if the DB is read-only for this user
  1293. * @param ApiBase $module An Api module
  1294. */
  1295. protected function checkReadOnly( $module ) {
  1296. if ( wfReadOnly() ) {
  1297. $this->dieReadOnly();
  1298. }
  1299. if ( $module->isWriteMode()
  1300. && $this->getUser()->isBot()
  1301. && wfGetLB()->getServerCount() > 1
  1302. ) {
  1303. $this->checkBotReadOnly();
  1304. }
  1305. }
  1306. /**
  1307. * Check whether we are readonly for bots
  1308. */
  1309. private function checkBotReadOnly() {
  1310. // Figure out how many servers have passed the lag threshold
  1311. $numLagged = 0;
  1312. $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
  1313. $laggedServers = [];
  1314. $loadBalancer = wfGetLB();
  1315. foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
  1316. if ( $lag > $lagLimit ) {
  1317. ++$numLagged;
  1318. $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
  1319. }
  1320. }
  1321. // If a majority of replica DBs are too lagged then disallow writes
  1322. $replicaCount = wfGetLB()->getServerCount() - 1;
  1323. if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
  1324. $laggedServers = implode( ', ', $laggedServers );
  1325. wfDebugLog(
  1326. 'api-readonly',
  1327. "Api request failed as read only because the following DBs are lagged: $laggedServers"
  1328. );
  1329. $this->dieWithError(
  1330. 'readonly_lag',
  1331. 'readonly',
  1332. [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
  1333. );
  1334. }
  1335. }
  1336. /**
  1337. * Check asserts of the user's rights
  1338. * @param array $params
  1339. */
  1340. protected function checkAsserts( $params ) {
  1341. if ( isset( $params['assert'] ) ) {
  1342. $user = $this->getUser();
  1343. switch ( $params['assert'] ) {
  1344. case 'user':
  1345. if ( $user->isAnon() ) {
  1346. $this->dieWithError( 'apierror-assertuserfailed' );
  1347. }
  1348. break;
  1349. case 'bot':
  1350. if ( !$user->isAllowed( 'bot' ) ) {
  1351. $this->dieWithError( 'apierror-assertbotfailed' );
  1352. }
  1353. break;
  1354. }
  1355. }
  1356. if ( isset( $params['assertuser'] ) ) {
  1357. $assertUser = User::newFromName( $params['assertuser'], false );
  1358. if ( !$assertUser || !$this->getUser()->equals( $assertUser ) ) {
  1359. $this->dieWithError(
  1360. [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
  1361. );
  1362. }
  1363. }
  1364. }
  1365. /**
  1366. * Check POST for external response and setup result printer
  1367. * @param ApiBase $module An Api module
  1368. * @param array $params An array with the request parameters
  1369. */
  1370. protected function setupExternalResponse( $module, $params ) {
  1371. $request = $this->getRequest();
  1372. if ( !$request->wasPosted() && $module->mustBePosted() ) {
  1373. // Module requires POST. GET request might still be allowed
  1374. // if $wgDebugApi is true, otherwise fail.
  1375. $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction ] );
  1376. }
  1377. // See if custom printer is used
  1378. $this->mPrinter = $module->getCustomPrinter();
  1379. if ( is_null( $this->mPrinter ) ) {
  1380. // Create an appropriate printer
  1381. $this->mPrinter = $this->createPrinterByName( $params['format'] );
  1382. }
  1383. if ( $request->getProtocol() === 'http' && (
  1384. $request->getSession()->shouldForceHTTPS() ||
  1385. ( $this->getUser()->isLoggedIn() &&
  1386. $this->getUser()->requiresHTTPS() )
  1387. ) ) {
  1388. $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
  1389. }
  1390. }
  1391. /**
  1392. * Execute the actual module, without any error handling
  1393. */
  1394. protected function executeAction() {
  1395. $params = $this->setupExecuteAction();
  1396. $module = $this->setupModule();
  1397. $this->mModule = $module;
  1398. if ( !$this->mInternalMode ) {
  1399. $this->setRequestExpectations( $module );
  1400. }
  1401. $this->checkExecutePermissions( $module );
  1402. if ( !$this->checkMaxLag( $module, $params ) ) {
  1403. return;
  1404. }
  1405. if ( !$this->checkConditionalRequestHeaders( $module ) ) {
  1406. return;
  1407. }
  1408. if ( !$this->mInternalMode ) {
  1409. $this->setupExternalResponse( $module, $params );
  1410. }
  1411. $this->checkAsserts( $params );
  1412. // Execute
  1413. $module->execute();
  1414. Hooks::run( 'APIAfterExecute', [ &$module ] );
  1415. $this->reportUnusedParams();
  1416. if ( !$this->mInternalMode ) {
  1417. // append Debug information
  1418. MWDebug::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
  1419. // Print result data
  1420. $this->printResult();
  1421. }
  1422. }
  1423. /**
  1424. * Set database connection, query, and write expectations given this module request
  1425. * @param ApiBase $module
  1426. */
  1427. protected function setRequestExpectations( ApiBase $module ) {
  1428. $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
  1429. $trxProfiler = Profiler::instance()->getTransactionProfiler();
  1430. $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
  1431. if ( $this->getRequest()->hasSafeMethod() ) {
  1432. $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
  1433. } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
  1434. $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
  1435. $this->getRequest()->markAsSafeRequest();
  1436. } else {
  1437. $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
  1438. }
  1439. }
  1440. /**
  1441. * Log the preceding request
  1442. * @param float $time Time in seconds
  1443. * @param Exception $e Exception caught while processing the request
  1444. */
  1445. protected function logRequest( $time, $e = null ) {
  1446. $request = $this->getRequest();
  1447. $logCtx = [
  1448. 'ts' => time(),
  1449. 'ip' => $request->getIP(),
  1450. 'userAgent' => $this->getUserAgent(),
  1451. 'wiki' => wfWikiID(),
  1452. 'timeSpentBackend' => (int)round( $time * 1000 ),
  1453. 'hadError' => $e !== null,
  1454. 'errorCodes' => [],
  1455. 'params' => [],
  1456. ];
  1457. if ( $e ) {
  1458. foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
  1459. $logCtx['errorCodes'][] = $msg->getApiCode();
  1460. }
  1461. }
  1462. // Construct space separated message for 'api' log channel
  1463. $msg = "API {$request->getMethod()} " .
  1464. wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
  1465. " {$logCtx['ip']} " .
  1466. "T={$logCtx['timeSpentBackend']}ms";
  1467. $sensitive = array_flip( $this->getSensitiveParams() );
  1468. foreach ( $this->getParamsUsed() as $name ) {
  1469. $value = $request->getVal( $name );
  1470. if ( $value === null ) {
  1471. continue;
  1472. }
  1473. if ( isset( $sensitive[$name] ) ) {
  1474. $value = '[redacted]';
  1475. $encValue = '[redacted]';
  1476. } elseif ( strlen( $value ) > 256 ) {
  1477. $value = substr( $value, 0, 256 );
  1478. $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
  1479. } else {
  1480. $encValue = $this->encodeRequestLogValue( $value );
  1481. }
  1482. $logCtx['params'][$name] = $value;
  1483. $msg .= " {$name}={$encValue}";
  1484. }
  1485. wfDebugLog( 'api', $msg, 'private' );
  1486. // ApiAction channel is for structured data consumers
  1487. wfDebugLog( 'ApiAction', '', 'private', $logCtx );
  1488. }
  1489. /**
  1490. * Encode a value in a format suitable for a space-separated log line.
  1491. * @param string $s
  1492. * @return string
  1493. */
  1494. protected function encodeRequestLogValue( $s ) {
  1495. static $table;
  1496. if ( !$table ) {
  1497. $chars = ';@$!*(),/:';
  1498. $numChars = strlen( $chars );
  1499. for ( $i = 0; $i < $numChars; $i++ ) {
  1500. $table[rawurlencode( $chars[$i] )] = $chars[$i];
  1501. }
  1502. }
  1503. return strtr( rawurlencode( $s ), $table );
  1504. }
  1505. /**
  1506. * Get the request parameters used in the course of the preceding execute() request
  1507. * @return array
  1508. */
  1509. protected function getParamsUsed() {
  1510. return array_keys( $this->mParamsUsed );
  1511. }
  1512. /**
  1513. * Mark parameters as used
  1514. * @param string|string[] $params
  1515. */
  1516. public function markParamsUsed( $params ) {
  1517. $this->mParamsUsed += array_fill_keys( (array)$params, true );
  1518. }
  1519. /**
  1520. * Get the request parameters that should be considered sensitive
  1521. * @since 1.29
  1522. * @return array
  1523. */
  1524. protected function getSensitiveParams() {
  1525. return array_keys( $this->mParamsSensitive );
  1526. }
  1527. /**
  1528. * Mark parameters as sensitive
  1529. * @since 1.29
  1530. * @param string|string[] $params
  1531. */
  1532. public function markParamsSensitive( $params ) {
  1533. $this->mParamsSensitive += array_fill_keys( (array)$params, true );
  1534. }
  1535. /**
  1536. * Get a request value, and register the fact that it was used, for logging.
  1537. * @param string $name
  1538. * @param mixed $default
  1539. * @return mixed
  1540. */
  1541. public function getVal( $name, $default = null ) {
  1542. $this->mParamsUsed[$name] = true;
  1543. $ret = $this->getRequest()->getVal( $name );
  1544. if ( $ret === null ) {
  1545. if ( $this->getRequest()->getArray( $name ) !== null ) {
  1546. // See T12262 for why we don't just implode( '|', ... ) the
  1547. // array.
  1548. $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
  1549. }
  1550. $ret = $default;
  1551. }
  1552. return $ret;
  1553. }
  1554. /**
  1555. * Get a boolean request value, and register the fact that the parameter
  1556. * was used, for logging.
  1557. * @param string $name
  1558. * @return bool
  1559. */
  1560. public function getCheck( $name ) {
  1561. return $this->getVal( $name, null ) !== null;
  1562. }
  1563. /**
  1564. * Get a request upload, and register the fact that it was used, for logging.
  1565. *
  1566. * @since 1.21
  1567. * @param string $name Parameter name
  1568. * @return WebRequestUpload
  1569. */
  1570. public function getUpload( $name ) {
  1571. $this->mParamsUsed[$name] = true;
  1572. return $this->getRequest()->getUpload( $name );
  1573. }
  1574. /**
  1575. * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
  1576. * for example in case of spelling mistakes or a missing 'g' prefix for generators.
  1577. */
  1578. protected function reportUnusedParams() {
  1579. $paramsUsed = $this->getParamsUsed();
  1580. $allParams = $this->getRequest()->getValueNames();
  1581. if ( !$this->mInternalMode ) {
  1582. // Printer has not yet executed; don't warn that its parameters are unused
  1583. $printerParams = $this->mPrinter->encodeParamName(
  1584. array_keys( $this->mPrinter->getFinalParams() ?: [] )
  1585. );
  1586. $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
  1587. } else {
  1588. $unusedParams = array_diff( $allParams, $paramsUsed );
  1589. }
  1590. if ( count( $unusedParams ) ) {
  1591. $this->addWarning( [
  1592. 'apierror-unrecognizedparams',
  1593. Message::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
  1594. count( $unusedParams )
  1595. ] );
  1596. }
  1597. }
  1598. /**
  1599. * Print results using the current printer
  1600. *
  1601. * @param int $httpCode HTTP status code, or 0 to not change
  1602. */
  1603. protected function printResult( $httpCode = 0 ) {
  1604. if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
  1605. $this->addWarning( 'apiwarn-wgDebugAPI' );
  1606. }
  1607. $printer = $this->mPrinter;
  1608. $printer->initPrinter( false );
  1609. if ( $httpCode ) {
  1610. $printer->setHttpStatus( $httpCode );
  1611. }
  1612. $printer->execute();
  1613. $printer->closePrinter();
  1614. }
  1615. /**
  1616. * @return bool
  1617. */
  1618. public function isReadMode() {
  1619. return false;
  1620. }
  1621. /**
  1622. * See ApiBase for description.
  1623. *
  1624. * @return array
  1625. */
  1626. public function getAllowedParams() {
  1627. return [
  1628. 'action' => [
  1629. ApiBase::PARAM_DFLT => 'help',
  1630. ApiBase::PARAM_TYPE => 'submodule',
  1631. ],
  1632. 'format' => [
  1633. ApiBase::PARAM_DFLT => self::API_DEFAULT_FORMAT,
  1634. ApiBase::PARAM_TYPE => 'submodule',
  1635. ],
  1636. 'maxlag' => [
  1637. ApiBase::PARAM_TYPE => 'integer'
  1638. ],
  1639. 'smaxage' => [
  1640. ApiBase::PARAM_TYPE => 'integer',
  1641. ApiBase::PARAM_DFLT => 0
  1642. ],
  1643. 'maxage' => [
  1644. ApiBase::PARAM_TYPE => 'integer',
  1645. ApiBase::PARAM_DFLT => 0
  1646. ],
  1647. 'assert' => [
  1648. ApiBase::PARAM_TYPE => [ 'user', 'bot' ]
  1649. ],
  1650. 'assertuser' => [
  1651. ApiBase::PARAM_TYPE => 'user',
  1652. ],
  1653. 'requestid' => null,
  1654. 'servedby' => false,
  1655. 'curtimestamp' => false,
  1656. 'responselanginfo' => false,
  1657. 'origin' => null,
  1658. 'uselang' => [
  1659. ApiBase::PARAM_DFLT => self::API_DEFAULT_USELANG,
  1660. ],
  1661. 'errorformat' => [
  1662. ApiBase::PARAM_TYPE => [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
  1663. ApiBase::PARAM_DFLT => 'bc',
  1664. ],
  1665. 'errorlang' => [
  1666. ApiBase::PARAM_DFLT => 'uselang',
  1667. ],
  1668. 'errorsuselocal' => [
  1669. ApiBase::PARAM_DFLT => false,
  1670. ],
  1671. ];
  1672. }
  1673. /** @inheritDoc */
  1674. protected function getExamplesMessages() {
  1675. return [
  1676. 'action=help'
  1677. => 'apihelp-help-example-main',
  1678. 'action=help&recursivesubmodules=1'
  1679. => 'apihelp-help-example-recursive',
  1680. ];
  1681. }
  1682. public function modifyHelp( array &$help, array $options, array &$tocData ) {
  1683. // Wish PHP had an "array_insert_before". Instead, we have to manually
  1684. // reindex the array to get 'permissions' in the right place.
  1685. $oldHelp = $help;
  1686. $help = [];
  1687. foreach ( $oldHelp as $k => $v ) {
  1688. if ( $k === 'submodules' ) {
  1689. $help['permissions'] = '';
  1690. }
  1691. $help[$k] = $v;
  1692. }
  1693. $help['datatypes'] = '';
  1694. $help['credits'] = '';
  1695. // Fill 'permissions'
  1696. $help['permissions'] .= Html::openElement( 'div',
  1697. [ 'class' => 'apihelp-block apihelp-permissions' ] );
  1698. $m = $this->msg( 'api-help-permissions' );
  1699. if ( !$m->isDisabled() ) {
  1700. $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
  1701. $m->numParams( count( self::$mRights ) )->parse()
  1702. );
  1703. }
  1704. $help['permissions'] .= Html::openElement( 'dl' );
  1705. foreach ( self::$mRights as $right => $rightMsg ) {
  1706. $help['permissions'] .= Html::element( 'dt', null, $right );
  1707. $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
  1708. $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
  1709. $groups = array_map( function ( $group ) {
  1710. return $group == '*' ? 'all' : $group;
  1711. }, User::getGroupsWithPermission( $right ) );
  1712. $help['permissions'] .= Html::rawElement( 'dd', null,
  1713. $this->msg( 'api-help-permissions-granted-to' )
  1714. ->numParams( count( $groups ) )
  1715. ->params( Message::listParam( $groups ) )
  1716. ->parse()
  1717. );
  1718. }
  1719. $help['permissions'] .= Html::closeElement( 'dl' );
  1720. $help['permissions'] .= Html::closeElement( 'div' );
  1721. // Fill 'datatypes' and 'credits', if applicable
  1722. if ( empty( $options['nolead'] ) ) {
  1723. $level = $options['headerlevel'];
  1724. $tocnumber = &$options['tocnumber'];
  1725. $header = $this->msg( 'api-help-datatypes-header' )->parse();
  1726. $id = Sanitizer::escapeIdForAttribute( 'main/datatypes', Sanitizer::ID_PRIMARY );
  1727. $idFallback = Sanitizer::escapeIdForAttribute( 'main/datatypes', Sanitizer::ID_FALLBACK );
  1728. $headline = Linker::makeHeadline( min( 6, $level ),
  1729. ' class="apihelp-header">',
  1730. $id,
  1731. $header,
  1732. '',
  1733. $idFallback
  1734. );
  1735. // Ensure we have a sane anchor
  1736. if ( $id !== 'main/datatypes' && $idFallback !== 'main/datatypes' ) {
  1737. $headline = '<div id="main/datatypes"></div>' . $headline;
  1738. }
  1739. $help['datatypes'] .= $headline;
  1740. $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
  1741. if ( !isset( $tocData['main/datatypes'] ) ) {
  1742. $tocnumber[$level]++;
  1743. $tocData['main/datatypes'] = [
  1744. 'toclevel' => count( $tocnumber ),
  1745. 'level' => $level,
  1746. 'anchor' => 'main/datatypes',
  1747. 'line' => $header,
  1748. 'number' => implode( '.', $tocnumber ),
  1749. 'index' => false,
  1750. ];
  1751. }
  1752. $header = $this->msg( 'api-credits-header' )->parse();
  1753. $id = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_PRIMARY );
  1754. $idFallback = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_FALLBACK );
  1755. $headline = Linker::makeHeadline( min( 6, $level ),
  1756. ' class="apihelp-header">',
  1757. $id,
  1758. $header,
  1759. '',
  1760. $idFallback
  1761. );
  1762. // Ensure we have a sane anchor
  1763. if ( $id !== 'main/credits' && $idFallback !== 'main/credits' ) {
  1764. $headline = '<div id="main/credits"></div>' . $headline;
  1765. }
  1766. $help['credits'] .= $headline;
  1767. $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
  1768. if ( !isset( $tocData['main/credits'] ) ) {
  1769. $tocnumber[$level]++;
  1770. $tocData['main/credits'] = [
  1771. 'toclevel' => count( $tocnumber ),
  1772. 'level' => $level,
  1773. 'anchor' => 'main/credits',
  1774. 'line' => $header,
  1775. 'number' => implode( '.', $tocnumber ),
  1776. 'index' => false,
  1777. ];
  1778. }
  1779. }
  1780. }
  1781. private $mCanApiHighLimits = null;
  1782. /**
  1783. * Check whether the current user is allowed to use high limits
  1784. * @return bool
  1785. */
  1786. public function canApiHighLimits() {
  1787. if ( !isset( $this->mCanApiHighLimits ) ) {
  1788. $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
  1789. }
  1790. return $this->mCanApiHighLimits;
  1791. }
  1792. /**
  1793. * Overrides to return this instance's module manager.
  1794. * @return ApiModuleManager
  1795. */
  1796. public function getModuleManager() {
  1797. return $this->mModuleMgr;
  1798. }
  1799. /**
  1800. * Fetches the user agent used for this request
  1801. *
  1802. * The value will be the combination of the 'Api-User-Agent' header (if
  1803. * any) and the standard User-Agent header (if any).
  1804. *
  1805. * @return string
  1806. */
  1807. public function getUserAgent() {
  1808. return trim(
  1809. $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
  1810. $this->getRequest()->getHeader( 'User-agent' )
  1811. );
  1812. }
  1813. }
  1814. /**
  1815. * For really cool vim folding this needs to be at the end:
  1816. * vim: foldmarker=@{,@} foldmethod=marker
  1817. */