MediaWiki  master
ApiExpandTemplates.php
Go to the documentation of this file.
1 <?php
24 
32 class ApiExpandTemplates extends ApiBase {
33 
34  public function execute() {
35  // Cache may vary on the user because ParserOptions gets data from it
36  $this->getMain()->setCacheMode( 'anon-public-user-private' );
37 
38  // Get parameters
39  $params = $this->extractRequestParams();
40  $this->requireMaxOneParameter( $params, 'prop', 'generatexml' );
41 
42  $title = $params['title'];
43  if ( $title === null ) {
44  $titleProvided = false;
45  // A title is needed for parsing, so arbitrarily choose one
46  $title = 'API';
47  } else {
48  $titleProvided = true;
49  }
50 
51  if ( $params['prop'] === null ) {
52  $this->addDeprecation(
53  [ 'apiwarn-deprecation-missingparam', 'prop' ], 'action=expandtemplates&!prop'
54  );
55  $prop = [];
56  } else {
57  $prop = array_flip( $params['prop'] );
58  }
59 
60  $titleObj = Title::newFromText( $title );
61  if ( !$titleObj || $titleObj->isExternal() ) {
62  $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
63  }
64 
65  // Get title and revision ID for parser
66  $revid = $params['revid'];
67  if ( $revid !== null ) {
68  $rev = MediaWikiServices::getInstance()->getRevisionStore()->getRevisionById( $revid );
69  if ( !$rev ) {
70  $this->dieWithError( [ 'apierror-nosuchrevid', $revid ] );
71  }
72  $pTitleObj = $titleObj;
73  $titleObj = Title::newFromLinkTarget( $rev->getPageAsLinkTarget() );
74  if ( $titleProvided ) {
75  if ( !$titleObj->equals( $pTitleObj ) ) {
76  $this->addWarning( [ 'apierror-revwrongpage', $rev->getId(),
77  wfEscapeWikiText( $pTitleObj->getPrefixedText() ) ] );
78  }
79  }
80  }
81 
82  $result = $this->getResult();
83 
84  // Parse text
85  $options = ParserOptions::newFromContext( $this->getContext() );
86 
87  if ( $params['includecomments'] ) {
88  $options->setRemoveComments( false );
89  }
90 
91  $reset = null;
92  $suppressCache = false;
93  $this->getHookRunner()->onApiMakeParserOptions(
94  $options, $titleObj, $params, $this, $reset, $suppressCache );
95 
96  $retval = [];
97 
98  $parser = MediaWikiServices::getInstance()->getParser();
99  if ( isset( $prop['parsetree'] ) || $params['generatexml'] ) {
100  $parser->startExternalParse( $titleObj, $options, Parser::OT_PREPROCESS );
101  $dom = $parser->preprocessToDom( $params['text'] );
102  if ( is_callable( [ $dom, 'saveXML' ] ) ) {
103  // @phan-suppress-next-line PhanUndeclaredMethod
104  $xml = $dom->saveXML();
105  } else {
106  // @phan-suppress-next-line PhanUndeclaredMethod
107  $xml = $dom->__toString();
108  }
109  if ( isset( $prop['parsetree'] ) ) {
110  unset( $prop['parsetree'] );
111  $retval['parsetree'] = $xml;
112  } else {
113  // the old way
114  $result->addValue( null, 'parsetree', $xml );
115  $result->addValue( null, ApiResult::META_BC_SUBELEMENTS, [ 'parsetree' ] );
116  }
117  }
118 
119  // if they didn't want any output except (probably) the parse tree,
120  // then don't bother actually fully expanding it
121  if ( $prop || $params['prop'] === null ) {
122  $parser->startExternalParse( $titleObj, $options, Parser::OT_PREPROCESS );
123  $frame = $parser->getPreprocessor()->newFrame();
124  $wikitext = $parser->preprocess( $params['text'], $titleObj, $options, $revid, $frame );
125  if ( $params['prop'] === null ) {
126  // the old way
127  ApiResult::setContentValue( $retval, 'wikitext', $wikitext );
128  } else {
129  $p_output = $parser->getOutput();
130  if ( isset( $prop['categories'] ) ) {
131  $categories = $p_output->getCategories();
132  if ( $categories ) {
133  $categories_result = [];
134  foreach ( $categories as $category => $sortkey ) {
135  $entry = [];
136  $entry['sortkey'] = $sortkey;
137  ApiResult::setContentValue( $entry, 'category', (string)$category );
138  $categories_result[] = $entry;
139  }
140  ApiResult::setIndexedTagName( $categories_result, 'category' );
141  $retval['categories'] = $categories_result;
142  }
143  }
144  if ( isset( $prop['properties'] ) ) {
145  $properties = $p_output->getProperties();
146  if ( $properties ) {
147  ApiResult::setArrayType( $properties, 'BCkvp', 'name' );
148  ApiResult::setIndexedTagName( $properties, 'property' );
149  $retval['properties'] = $properties;
150  }
151  }
152  if ( isset( $prop['volatile'] ) ) {
153  $retval['volatile'] = $frame->isVolatile();
154  }
155  if ( isset( $prop['ttl'] ) && $frame->getTTL() !== null ) {
156  $retval['ttl'] = $frame->getTTL();
157  }
158  if ( isset( $prop['wikitext'] ) ) {
159  $retval['wikitext'] = $wikitext;
160  }
161  if ( isset( $prop['modules'] ) ) {
162  $retval['modules'] = array_values( array_unique( $p_output->getModules() ) );
163  // Deprecated since 1.32 (T188689)
164  $retval['modulescripts'] = [];
165  $retval['modulestyles'] = array_values( array_unique( $p_output->getModuleStyles() ) );
166  }
167  if ( isset( $prop['jsconfigvars'] ) ) {
168  $retval['jsconfigvars'] =
169  ApiResult::addMetadataToResultVars( $p_output->getJsConfigVars() );
170  }
171  if ( isset( $prop['encodedjsconfigvars'] ) ) {
172  $retval['encodedjsconfigvars'] = FormatJson::encode(
173  $p_output->getJsConfigVars(), false, FormatJson::ALL_OK
174  );
175  $retval[ApiResult::META_SUBELEMENTS][] = 'encodedjsconfigvars';
176  }
177  if ( isset( $prop['modules'] ) &&
178  !isset( $prop['jsconfigvars'] ) && !isset( $prop['encodedjsconfigvars'] ) ) {
179  $this->addWarning( 'apiwarn-moduleswithoutvars' );
180  }
181  }
182  }
183  ApiResult::setSubelementsList( $retval, [ 'wikitext', 'parsetree' ] );
184  $result->addValue( null, $this->getModuleName(), $retval );
185  }
186 
187  public function getAllowedParams() {
188  return [
189  'title' => null,
190  'text' => [
191  ApiBase::PARAM_TYPE => 'text',
192  ApiBase::PARAM_REQUIRED => true,
193  ],
194  'revid' => [
195  ApiBase::PARAM_TYPE => 'integer',
196  ],
197  'prop' => [
199  'wikitext',
200  'categories',
201  'properties',
202  'volatile',
203  'ttl',
204  'modules',
205  'jsconfigvars',
206  'encodedjsconfigvars',
207  'parsetree',
208  ],
209  ApiBase::PARAM_ISMULTI => true,
211  ],
212  'includecomments' => false,
213  'generatexml' => [
214  ApiBase::PARAM_TYPE => 'boolean',
216  ],
217  ];
218  }
219 
220  protected function getExamplesMessages() {
221  return [
222  'action=expandtemplates&text={{Project:Sandbox}}'
223  => 'apihelp-expandtemplates-example-simple',
224  ];
225  }
226 
227  public function getHelpUrls() {
228  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Parsing_wikitext#expandtemplates';
229  }
230 }
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:329
ContextSource\getContext
getContext()
Get the base IContextSource object.
Definition: ContextSource.php:42
ApiBase\addWarning
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition: ApiBase.php:1301
ApiBase\PARAM_REQUIRED
const PARAM_REQUIRED
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:77
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:154
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1382
ApiResult\META_BC_SUBELEMENTS
const META_BC_SUBELEMENTS
Key for the 'BC subelements' metadata item.
Definition: ApiResult.php:143
ApiBase\PARAM_TYPE
const PARAM_TYPE
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:71
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:565
FormatJson\ALL_OK
const ALL_OK
Skip escaping as many characters as reasonably possible.
Definition: FormatJson.php:55
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:52
ApiResult\setContentValue
static setContentValue(array &$arr, $name, $value, $flags=0)
Add an output value to the array by name and mark as META_CONTENT.
Definition: ApiResult.php:466
ApiBase\PARAM_DEPRECATED
const PARAM_DEPRECATED
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:76
FormatJson\encode
static encode( $value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:115
ApiResult\setArrayType
static setArrayType(array &$arr, $type, $kvpKeyName=null)
Set the array data type.
Definition: ApiResult.php:716
ApiExpandTemplates\getAllowedParams
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiExpandTemplates.php:187
ApiResult\addMetadataToResultVars
static addMetadataToResultVars( $vars, $forceHash=true)
Add the correct metadata to an array of vars we want to export through the API.
Definition: ApiResult.php:1138
ApiResult\META_SUBELEMENTS
const META_SUBELEMENTS
Key for the 'subelements' metadata item.
Definition: ApiResult.php:78
ApiExpandTemplates\getHelpUrls
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiExpandTemplates.php:227
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:717
$title
$title
Definition: testCompression.php:38
ApiResult\setIndexedTagName
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:604
ApiBase\requireMaxOneParameter
requireMaxOneParameter( $params,... $required)
Die if more than one of a certain set of parameters is set and not false.
Definition: ApiBase.php:889
ParserOptions\newFromContext
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource object.
Definition: ParserOptions.php:1113
ApiBase\addDeprecation
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
Definition: ApiBase.php:1315
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1487
Title\newFromLinkTarget
static newFromLinkTarget(LinkTarget $linkTarget, $forceClone='')
Returns a Title given a LinkTarget.
Definition: Title.php:281
Parser\OT_PREPROCESS
const OT_PREPROCESS
Definition: Parser.php:122
ApiExpandTemplates
API module that functions as a shortcut to the wikitext preprocessor.
Definition: ApiExpandTemplates.php:32
ApiExpandTemplates\execute
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition: ApiExpandTemplates.php:34
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:444
ApiBase\PARAM_ISMULTI
const PARAM_ISMULTI
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:70
ApiBase\getMain
getMain()
Get the main module.
Definition: ApiBase.php:460
ApiBase\PARAM_HELP_MSG_PER_VALUE
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, this is an array mapping those values to $msg...
Definition: ApiBase.php:140
ApiBase\getHookRunner
getHookRunner()
Get an ApiHookRunner for running core API hooks.
Definition: ApiBase.php:662
ApiResult\setSubelementsList
static setSubelementsList(array &$arr, $names)
Causes the elements with the specified names to be output as subelements rather than attributes.
Definition: ApiResult.php:553
ApiExpandTemplates\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiExpandTemplates.php:220