ApiExpandTemplates.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. <?php
  2. /**
  3. * Copyright © 2007 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. * API module that functions as a shortcut to the wikitext preprocessor. Expands
  25. * any templates in a provided string, and returns the result of this expansion
  26. * to the caller.
  27. *
  28. * @ingroup API
  29. */
  30. class ApiExpandTemplates extends ApiBase {
  31. public function execute() {
  32. // Cache may vary on the user because ParserOptions gets data from it
  33. $this->getMain()->setCacheMode( 'anon-public-user-private' );
  34. // Get parameters
  35. $params = $this->extractRequestParams();
  36. $this->requireMaxOneParameter( $params, 'prop', 'generatexml' );
  37. $title = $params['title'];
  38. if ( $title === null ) {
  39. $titleProvided = false;
  40. // A title is needed for parsing, so arbitrarily choose one
  41. $title = 'API';
  42. } else {
  43. $titleProvided = true;
  44. }
  45. if ( $params['prop'] === null ) {
  46. $this->addDeprecation(
  47. [ 'apiwarn-deprecation-missingparam', 'prop' ], 'action=expandtemplates&!prop'
  48. );
  49. $prop = [];
  50. } else {
  51. $prop = array_flip( $params['prop'] );
  52. }
  53. $titleObj = Title::newFromText( $title );
  54. if ( !$titleObj || $titleObj->isExternal() ) {
  55. $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
  56. }
  57. // Get title and revision ID for parser
  58. $revid = $params['revid'];
  59. if ( $revid !== null ) {
  60. $rev = MediaWikiServices::getInstance()->getRevisionStore()->getRevisionById( $revid );
  61. if ( !$rev ) {
  62. $this->dieWithError( [ 'apierror-nosuchrevid', $revid ] );
  63. }
  64. $pTitleObj = $titleObj;
  65. $titleObj = Title::newFromLinkTarget( $rev->getPageAsLinkTarget() );
  66. if ( $titleProvided ) {
  67. if ( !$titleObj->equals( $pTitleObj ) ) {
  68. $this->addWarning( [ 'apierror-revwrongpage', $rev->getId(),
  69. wfEscapeWikiText( $pTitleObj->getPrefixedText() ) ] );
  70. }
  71. }
  72. }
  73. $result = $this->getResult();
  74. // Parse text
  75. $options = ParserOptions::newFromContext( $this->getContext() );
  76. if ( $params['includecomments'] ) {
  77. $options->setRemoveComments( false );
  78. }
  79. $reset = null;
  80. $suppressCache = false;
  81. Hooks::run( 'ApiMakeParserOptions',
  82. [ $options, $titleObj, $params, $this, &$reset, &$suppressCache ] );
  83. $retval = [];
  84. $parser = MediaWikiServices::getInstance()->getParser();
  85. if ( isset( $prop['parsetree'] ) || $params['generatexml'] ) {
  86. $parser->startExternalParse( $titleObj, $options, Parser::OT_PREPROCESS );
  87. $dom = $parser->preprocessToDom( $params['text'] );
  88. // @phan-suppress-next-line PhanUndeclaredMethodInCallable
  89. if ( is_callable( [ $dom, 'saveXML' ] ) ) {
  90. // @phan-suppress-next-line PhanUndeclaredMethod
  91. $xml = $dom->saveXML();
  92. } else {
  93. // @phan-suppress-next-line PhanUndeclaredMethod
  94. $xml = $dom->__toString();
  95. }
  96. if ( isset( $prop['parsetree'] ) ) {
  97. unset( $prop['parsetree'] );
  98. $retval['parsetree'] = $xml;
  99. } else {
  100. // the old way
  101. $result->addValue( null, 'parsetree', $xml );
  102. $result->addValue( null, ApiResult::META_BC_SUBELEMENTS, [ 'parsetree' ] );
  103. }
  104. }
  105. // if they didn't want any output except (probably) the parse tree,
  106. // then don't bother actually fully expanding it
  107. if ( $prop || $params['prop'] === null ) {
  108. $parser->startExternalParse( $titleObj, $options, Parser::OT_PREPROCESS );
  109. $frame = $parser->getPreprocessor()->newFrame();
  110. $wikitext = $parser->preprocess( $params['text'], $titleObj, $options, $revid, $frame );
  111. if ( $params['prop'] === null ) {
  112. // the old way
  113. ApiResult::setContentValue( $retval, 'wikitext', $wikitext );
  114. } else {
  115. $p_output = $parser->getOutput();
  116. if ( isset( $prop['categories'] ) ) {
  117. $categories = $p_output->getCategories();
  118. if ( $categories ) {
  119. $categories_result = [];
  120. foreach ( $categories as $category => $sortkey ) {
  121. $entry = [];
  122. $entry['sortkey'] = $sortkey;
  123. ApiResult::setContentValue( $entry, 'category', (string)$category );
  124. $categories_result[] = $entry;
  125. }
  126. ApiResult::setIndexedTagName( $categories_result, 'category' );
  127. $retval['categories'] = $categories_result;
  128. }
  129. }
  130. if ( isset( $prop['properties'] ) ) {
  131. $properties = $p_output->getProperties();
  132. if ( $properties ) {
  133. ApiResult::setArrayType( $properties, 'BCkvp', 'name' );
  134. ApiResult::setIndexedTagName( $properties, 'property' );
  135. $retval['properties'] = $properties;
  136. }
  137. }
  138. if ( isset( $prop['volatile'] ) ) {
  139. $retval['volatile'] = $frame->isVolatile();
  140. }
  141. if ( isset( $prop['ttl'] ) && $frame->getTTL() !== null ) {
  142. $retval['ttl'] = $frame->getTTL();
  143. }
  144. if ( isset( $prop['wikitext'] ) ) {
  145. $retval['wikitext'] = $wikitext;
  146. }
  147. if ( isset( $prop['modules'] ) ) {
  148. $retval['modules'] = array_values( array_unique( $p_output->getModules() ) );
  149. // Deprecated since 1.32 (T188689)
  150. $retval['modulescripts'] = [];
  151. $retval['modulestyles'] = array_values( array_unique( $p_output->getModuleStyles() ) );
  152. }
  153. if ( isset( $prop['jsconfigvars'] ) ) {
  154. $retval['jsconfigvars'] =
  155. ApiResult::addMetadataToResultVars( $p_output->getJsConfigVars() );
  156. }
  157. if ( isset( $prop['encodedjsconfigvars'] ) ) {
  158. $retval['encodedjsconfigvars'] = FormatJson::encode(
  159. $p_output->getJsConfigVars(), false, FormatJson::ALL_OK
  160. );
  161. $retval[ApiResult::META_SUBELEMENTS][] = 'encodedjsconfigvars';
  162. }
  163. if ( isset( $prop['modules'] ) &&
  164. !isset( $prop['jsconfigvars'] ) && !isset( $prop['encodedjsconfigvars'] ) ) {
  165. $this->addWarning( 'apiwarn-moduleswithoutvars' );
  166. }
  167. }
  168. }
  169. ApiResult::setSubelementsList( $retval, [ 'wikitext', 'parsetree' ] );
  170. $result->addValue( null, $this->getModuleName(), $retval );
  171. }
  172. public function getAllowedParams() {
  173. return [
  174. 'title' => null,
  175. 'text' => [
  176. ApiBase::PARAM_TYPE => 'text',
  177. ApiBase::PARAM_REQUIRED => true,
  178. ],
  179. 'revid' => [
  180. ApiBase::PARAM_TYPE => 'integer',
  181. ],
  182. 'prop' => [
  183. ApiBase::PARAM_TYPE => [
  184. 'wikitext',
  185. 'categories',
  186. 'properties',
  187. 'volatile',
  188. 'ttl',
  189. 'modules',
  190. 'jsconfigvars',
  191. 'encodedjsconfigvars',
  192. 'parsetree',
  193. ],
  194. ApiBase::PARAM_ISMULTI => true,
  195. ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
  196. ],
  197. 'includecomments' => false,
  198. 'generatexml' => [
  199. ApiBase::PARAM_TYPE => 'boolean',
  200. ApiBase::PARAM_DEPRECATED => true,
  201. ],
  202. ];
  203. }
  204. protected function getExamplesMessages() {
  205. return [
  206. 'action=expandtemplates&text={{Project:Sandbox}}'
  207. => 'apihelp-expandtemplates-example-simple',
  208. ];
  209. }
  210. public function getHelpUrls() {
  211. return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Parsing_wikitext#expandtemplates';
  212. }
  213. }