ApiFormatBase.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. <?php
  2. /**
  3. * Copyright © 2006 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\MediaWikiServices;
  23. /**
  24. * This is the abstract base class for API formatters.
  25. *
  26. * @ingroup API
  27. */
  28. abstract class ApiFormatBase extends ApiBase {
  29. private $mIsHtml, $mFormat;
  30. private $mBuffer, $mDisabled = false;
  31. private $mIsWrappedHtml = false;
  32. private $mHttpStatus = false;
  33. protected $mForceDefaultParams = false;
  34. /**
  35. * If $format ends with 'fm', pretty-print the output in HTML.
  36. * @param ApiMain $main
  37. * @param string $format Format name
  38. */
  39. public function __construct( ApiMain $main, $format ) {
  40. parent::__construct( $main, $format );
  41. $this->mIsHtml = ( substr( $format, -2, 2 ) === 'fm' ); // ends with 'fm'
  42. if ( $this->mIsHtml ) {
  43. $this->mFormat = substr( $format, 0, -2 ); // remove ending 'fm'
  44. $this->mIsWrappedHtml = $this->getMain()->getCheck( 'wrappedhtml' );
  45. } else {
  46. $this->mFormat = $format;
  47. }
  48. $this->mFormat = strtoupper( $this->mFormat );
  49. }
  50. /**
  51. * Overriding class returns the MIME type that should be sent to the client.
  52. *
  53. * When getIsHtml() returns true, the return value here is used for syntax
  54. * highlighting but the client sees text/html.
  55. *
  56. * @return string
  57. */
  58. abstract public function getMimeType();
  59. /**
  60. * Return a filename for this module's output.
  61. * @note If $this->getIsWrappedHtml() || $this->getIsHtml(), you'll very
  62. * likely want to fall back to this class's version.
  63. * @since 1.27
  64. * @return string Generally this should be "api-result.$ext"
  65. */
  66. public function getFilename() {
  67. if ( $this->getIsWrappedHtml() ) {
  68. return 'api-result-wrapped.json';
  69. } elseif ( $this->getIsHtml() ) {
  70. return 'api-result.html';
  71. } else {
  72. $exts = MediaWikiServices::getInstance()->getMimeAnalyzer()
  73. ->getExtensionsForType( $this->getMimeType() );
  74. $ext = $exts ? strtok( $exts, ' ' ) : strtolower( $this->mFormat );
  75. return "api-result.$ext";
  76. }
  77. }
  78. /**
  79. * Get the internal format name
  80. * @return string
  81. */
  82. public function getFormat() {
  83. return $this->mFormat;
  84. }
  85. /**
  86. * Returns true when the HTML pretty-printer should be used.
  87. * The default implementation assumes that formats ending with 'fm'
  88. * should be formatted in HTML.
  89. * @return bool
  90. */
  91. public function getIsHtml() {
  92. return $this->mIsHtml;
  93. }
  94. /**
  95. * Returns true when the special wrapped mode is enabled.
  96. * @since 1.27
  97. * @return bool
  98. */
  99. protected function getIsWrappedHtml() {
  100. return $this->mIsWrappedHtml;
  101. }
  102. /**
  103. * Disable the formatter.
  104. *
  105. * This causes calls to initPrinter() and closePrinter() to be ignored.
  106. */
  107. public function disable() {
  108. $this->mDisabled = true;
  109. }
  110. /**
  111. * Whether the printer is disabled
  112. * @return bool
  113. */
  114. public function isDisabled() {
  115. return $this->mDisabled;
  116. }
  117. /**
  118. * Whether this formatter can handle printing API errors.
  119. *
  120. * If this returns false, then on API errors the default printer will be
  121. * instantiated.
  122. * @since 1.23
  123. * @return bool
  124. */
  125. public function canPrintErrors() {
  126. return true;
  127. }
  128. /**
  129. * Ignore request parameters, force a default.
  130. *
  131. * Used as a fallback if errors are being thrown.
  132. * @since 1.26
  133. */
  134. public function forceDefaultParams() {
  135. $this->mForceDefaultParams = true;
  136. }
  137. /**
  138. * Overridden to honor $this->forceDefaultParams(), if applicable
  139. * @inheritDoc
  140. * @since 1.26
  141. */
  142. protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
  143. if ( !$this->mForceDefaultParams ) {
  144. return parent::getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
  145. }
  146. if ( !is_array( $paramSettings ) ) {
  147. return $paramSettings;
  148. }
  149. return $paramSettings[self::PARAM_DFLT] ?? null;
  150. }
  151. /**
  152. * Set the HTTP status code to be used for the response
  153. * @since 1.29
  154. * @param int $code
  155. */
  156. public function setHttpStatus( $code ) {
  157. if ( $this->mDisabled ) {
  158. return;
  159. }
  160. if ( $this->getIsHtml() ) {
  161. $this->mHttpStatus = $code;
  162. } else {
  163. $this->getMain()->getRequest()->response()->statusHeader( $code );
  164. }
  165. }
  166. /**
  167. * Initialize the printer function and prepare the output headers.
  168. * @param bool $unused Always false since 1.25
  169. */
  170. public function initPrinter( $unused = false ) {
  171. if ( $this->mDisabled ) {
  172. return;
  173. }
  174. $mime = $this->getIsWrappedHtml()
  175. ? 'text/mediawiki-api-prettyprint-wrapped'
  176. : ( $this->getIsHtml() ? 'text/html' : $this->getMimeType() );
  177. // Some printers (ex. Feed) do their own header settings,
  178. // in which case $mime will be set to null
  179. if ( $mime === null ) {
  180. return; // skip any initialization
  181. }
  182. $this->getMain()->getRequest()->response()->header( "Content-Type: $mime; charset=utf-8" );
  183. // Set X-Frame-Options API results (T41180)
  184. $apiFrameOptions = $this->getConfig()->get( 'ApiFrameOptions' );
  185. if ( $apiFrameOptions ) {
  186. $this->getMain()->getRequest()->response()->header( "X-Frame-Options: $apiFrameOptions" );
  187. }
  188. // Set a Content-Disposition header so something downloading an API
  189. // response uses a halfway-sensible filename (T128209).
  190. $header = 'Content-Disposition: inline';
  191. $filename = $this->getFilename();
  192. $compatFilename = mb_convert_encoding( $filename, 'ISO-8859-1' );
  193. if ( preg_match( '/^[0-9a-zA-Z!#$%&\'*+\-.^_`|~]+$/', $compatFilename ) ) {
  194. $header .= '; filename=' . $compatFilename;
  195. } else {
  196. $header .= '; filename="'
  197. . preg_replace( '/([\0-\x1f"\x5c\x7f])/', '\\\\$1', $compatFilename ) . '"';
  198. }
  199. if ( $compatFilename !== $filename ) {
  200. $value = "UTF-8''" . rawurlencode( $filename );
  201. // rawurlencode() encodes more characters than RFC 5987 specifies. Unescape the ones it allows.
  202. $value = strtr( $value, [
  203. '%21' => '!', '%23' => '#', '%24' => '$', '%26' => '&', '%2B' => '+', '%5E' => '^',
  204. '%60' => '`', '%7C' => '|',
  205. ] );
  206. $header .= '; filename*=' . $value;
  207. }
  208. $this->getMain()->getRequest()->response()->header( $header );
  209. }
  210. /**
  211. * Finish printing and output buffered data.
  212. */
  213. public function closePrinter() {
  214. if ( $this->mDisabled ) {
  215. return;
  216. }
  217. $mime = $this->getMimeType();
  218. if ( $this->getIsHtml() && $mime !== null ) {
  219. $format = $this->getFormat();
  220. $lcformat = strtolower( $format );
  221. $result = $this->getBuffer();
  222. $context = new DerivativeContext( $this->getMain() );
  223. $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
  224. $context->setSkin( $skinFactory->makeSkin( 'apioutput' ) );
  225. $context->setTitle( SpecialPage::getTitleFor( 'ApiHelp' ) );
  226. $out = new OutputPage( $context );
  227. $context->setOutput( $out );
  228. $out->setRobotPolicy( 'noindex,nofollow' );
  229. $out->addModuleStyles( 'mediawiki.apipretty' );
  230. $out->setPageTitle( $context->msg( 'api-format-title' ) );
  231. if ( !$this->getIsWrappedHtml() ) {
  232. // When the format without suffix 'fm' is defined, there is a non-html version
  233. if ( $this->getMain()->getModuleManager()->isDefined( $lcformat, 'format' ) ) {
  234. if ( !$this->getRequest()->wasPosted() ) {
  235. $nonHtmlUrl = strtok( $this->getRequest()->getFullRequestURL(), '?' )
  236. . '?' . $this->getRequest()->appendQueryValue( 'format', $lcformat );
  237. $msg = $context->msg( 'api-format-prettyprint-header-hyperlinked' )
  238. ->params( $format, $lcformat, $nonHtmlUrl );
  239. } else {
  240. $msg = $context->msg( 'api-format-prettyprint-header' )->params( $format, $lcformat );
  241. }
  242. } else {
  243. $msg = $context->msg( 'api-format-prettyprint-header-only-html' )->params( $format );
  244. }
  245. $header = $msg->parseAsBlock();
  246. $out->addHTML(
  247. Html::rawElement( 'div', [ 'class' => 'api-pretty-header' ],
  248. ApiHelp::fixHelpLinks( $header )
  249. )
  250. );
  251. if ( $this->mHttpStatus && $this->mHttpStatus !== 200 ) {
  252. $out->addHTML(
  253. Html::rawElement( 'div', [ 'class' => 'api-pretty-header api-pretty-status' ],
  254. $this->msg(
  255. 'api-format-prettyprint-status',
  256. $this->mHttpStatus,
  257. HttpStatus::getMessage( $this->mHttpStatus )
  258. )->parse()
  259. )
  260. );
  261. }
  262. }
  263. if ( Hooks::run( 'ApiFormatHighlight', [ $context, $result, $mime, $format ] ) ) {
  264. $out->addHTML(
  265. Html::element( 'pre', [ 'class' => 'api-pretty-content' ], $result )
  266. );
  267. }
  268. if ( $this->getIsWrappedHtml() ) {
  269. // This is a special output mode mainly intended for ApiSandbox use
  270. $time = $this->getMain()->getRequest()->getElapsedTime();
  271. $json = FormatJson::encode(
  272. [
  273. 'status' => (int)( $this->mHttpStatus ?: 200 ),
  274. 'statustext' => HttpStatus::getMessage( $this->mHttpStatus ?: 200 ),
  275. 'html' => $out->getHTML(),
  276. 'modules' => array_values( array_unique( array_merge(
  277. $out->getModules(),
  278. $out->getModuleStyles()
  279. ) ) ),
  280. 'continue' => $this->getResult()->getResultData( 'continue' ),
  281. 'time' => round( $time * 1000 ),
  282. ],
  283. false, FormatJson::ALL_OK
  284. );
  285. // T68776: OutputHandler::mangleFlashPolicy() avoids a nasty bug in
  286. // Flash, but what it does isn't friendly for the API, so we need to
  287. // work around it.
  288. if ( preg_match( '/\<\s*cross-domain-policy\s*\>/i', $json ) ) {
  289. $json = preg_replace(
  290. '/\<(\s*cross-domain-policy\s*)\>/i', '\\u003C$1\\u003E', $json
  291. );
  292. }
  293. echo $json;
  294. } else {
  295. // API handles its own clickjacking protection.
  296. // Note, that $wgBreakFrames will still override $wgApiFrameOptions for format mode.
  297. $out->allowClickjacking();
  298. $out->output();
  299. }
  300. } else {
  301. // For non-HTML output, clear all errors that might have been
  302. // displayed if display_errors=On
  303. ob_clean();
  304. echo $this->getBuffer();
  305. }
  306. }
  307. /**
  308. * Append text to the output buffer.
  309. * @param string $text
  310. */
  311. public function printText( $text ) {
  312. $this->mBuffer .= $text;
  313. }
  314. /**
  315. * Get the contents of the buffer.
  316. * @return string
  317. */
  318. public function getBuffer() {
  319. return $this->mBuffer;
  320. }
  321. public function getAllowedParams() {
  322. $ret = [];
  323. if ( $this->getIsHtml() ) {
  324. $ret['wrappedhtml'] = [
  325. ApiBase::PARAM_DFLT => false,
  326. ApiBase::PARAM_HELP_MSG => 'apihelp-format-param-wrappedhtml',
  327. ];
  328. }
  329. return $ret;
  330. }
  331. protected function getExamplesMessages() {
  332. return [
  333. 'action=query&meta=siteinfo&siprop=namespaces&format=' . $this->getModuleName()
  334. => [ 'apihelp-format-example-generic', $this->getFormat() ]
  335. ];
  336. }
  337. public function getHelpUrls() {
  338. return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Data_formats';
  339. }
  340. }
  341. /**
  342. * For really cool vim folding this needs to be at the end:
  343. * vim: foldmarker=@{,@} foldmethod=marker
  344. */