MediaWiki  1.34.0
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  Hooks::run( 'ApiMakeParserOptions',
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  // @phan-suppress-next-line PhanUndeclaredMethodInCallable
103  if ( is_callable( [ $dom, 'saveXML' ] ) ) {
104  // @phan-suppress-next-line PhanUndeclaredMethod
105  $xml = $dom->saveXML();
106  } else {
107  // @phan-suppress-next-line PhanUndeclaredMethod
108  $xml = $dom->__toString();
109  }
110  if ( isset( $prop['parsetree'] ) ) {
111  unset( $prop['parsetree'] );
112  $retval['parsetree'] = $xml;
113  } else {
114  // the old way
115  $result->addValue( null, 'parsetree', $xml );
116  $result->addValue( null, ApiResult::META_BC_SUBELEMENTS, [ 'parsetree' ] );
117  }
118  }
119 
120  // if they didn't want any output except (probably) the parse tree,
121  // then don't bother actually fully expanding it
122  if ( $prop || $params['prop'] === null ) {
123  $parser->startExternalParse( $titleObj, $options, Parser::OT_PREPROCESS );
124  $frame = $parser->getPreprocessor()->newFrame();
125  $wikitext = $parser->preprocess( $params['text'], $titleObj, $options, $revid, $frame );
126  if ( $params['prop'] === null ) {
127  // the old way
128  ApiResult::setContentValue( $retval, 'wikitext', $wikitext );
129  } else {
130  $p_output = $parser->getOutput();
131  if ( isset( $prop['categories'] ) ) {
132  $categories = $p_output->getCategories();
133  if ( $categories ) {
134  $categories_result = [];
135  foreach ( $categories as $category => $sortkey ) {
136  $entry = [];
137  $entry['sortkey'] = $sortkey;
138  ApiResult::setContentValue( $entry, 'category', (string)$category );
139  $categories_result[] = $entry;
140  }
141  ApiResult::setIndexedTagName( $categories_result, 'category' );
142  $retval['categories'] = $categories_result;
143  }
144  }
145  if ( isset( $prop['properties'] ) ) {
146  $properties = $p_output->getProperties();
147  if ( $properties ) {
148  ApiResult::setArrayType( $properties, 'BCkvp', 'name' );
149  ApiResult::setIndexedTagName( $properties, 'property' );
150  $retval['properties'] = $properties;
151  }
152  }
153  if ( isset( $prop['volatile'] ) ) {
154  $retval['volatile'] = $frame->isVolatile();
155  }
156  if ( isset( $prop['ttl'] ) && $frame->getTTL() !== null ) {
157  $retval['ttl'] = $frame->getTTL();
158  }
159  if ( isset( $prop['wikitext'] ) ) {
160  $retval['wikitext'] = $wikitext;
161  }
162  if ( isset( $prop['modules'] ) ) {
163  $retval['modules'] = array_values( array_unique( $p_output->getModules() ) );
164  // Deprecated since 1.32 (T188689)
165  $retval['modulescripts'] = [];
166  $retval['modulestyles'] = array_values( array_unique( $p_output->getModuleStyles() ) );
167  }
168  if ( isset( $prop['jsconfigvars'] ) ) {
169  $retval['jsconfigvars'] =
170  ApiResult::addMetadataToResultVars( $p_output->getJsConfigVars() );
171  }
172  if ( isset( $prop['encodedjsconfigvars'] ) ) {
173  $retval['encodedjsconfigvars'] = FormatJson::encode(
174  $p_output->getJsConfigVars(), false, FormatJson::ALL_OK
175  );
176  $retval[ApiResult::META_SUBELEMENTS][] = 'encodedjsconfigvars';
177  }
178  if ( isset( $prop['modules'] ) &&
179  !isset( $prop['jsconfigvars'] ) && !isset( $prop['encodedjsconfigvars'] ) ) {
180  $this->addWarning( 'apiwarn-moduleswithoutvars' );
181  }
182  }
183  }
184  ApiResult::setSubelementsList( $retval, [ 'wikitext', 'parsetree' ] );
185  $result->addValue( null, $this->getModuleName(), $retval );
186  }
187 
188  public function getAllowedParams() {
189  return [
190  'title' => null,
191  'text' => [
192  ApiBase::PARAM_TYPE => 'text',
193  ApiBase::PARAM_REQUIRED => true,
194  ],
195  'revid' => [
196  ApiBase::PARAM_TYPE => 'integer',
197  ],
198  'prop' => [
200  'wikitext',
201  'categories',
202  'properties',
203  'volatile',
204  'ttl',
205  'modules',
206  'jsconfigvars',
207  'encodedjsconfigvars',
208  'parsetree',
209  ],
210  ApiBase::PARAM_ISMULTI => true,
212  ],
213  'includecomments' => false,
214  'generatexml' => [
215  ApiBase::PARAM_TYPE => 'boolean',
217  ],
218  ];
219  }
220 
221  protected function getExamplesMessages() {
222  return [
223  'action=expandtemplates&text={{Project:Sandbox}}'
224  => 'apihelp-expandtemplates-example-simple',
225  ];
226  }
227 
228  public function getHelpUrls() {
229  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Parsing_wikitext#expandtemplates';
230  }
231 }
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:316
ContextSource\getContext
getContext()
Get the base IContextSource object.
Definition: ContextSource.php:40
ApiBase\addWarning
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition: ApiBase.php:1933
ApiBase\PARAM_REQUIRED
const PARAM_REQUIRED
(boolean) Is the parameter required?
Definition: ApiBase.php:118
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:117
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:2014
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
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition: ApiBase.php:94
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:640
OT_PREPROCESS
const OT_PREPROCESS
Definition: Defines.php:166
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:42
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:478
ApiBase\PARAM_DEPRECATED
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
Definition: ApiBase.php:112
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:728
ApiExpandTemplates\getAllowedParams
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiExpandTemplates.php:188
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:1150
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:228
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:761
$title
$title
Definition: testCompression.php:34
ApiResult\setIndexedTagName
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:616
ParserOptions\newFromContext
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource object.
Definition: ParserOptions.php:1052
ApiBase\addDeprecation
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
Definition: ApiBase.php:1947
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1551
ApiBase\requireMaxOneParameter
requireMaxOneParameter( $params, $required)
Die if more than one of a certain set of parameters is set and not false.
Definition: ApiBase.php:931
Title\newFromLinkTarget
static newFromLinkTarget(LinkTarget $linkTarget, $forceClone='')
Returns a Title given a LinkTarget.
Definition: Title.php:268
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:520
ApiBase\PARAM_ISMULTI
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:58
ApiBase\getMain
getMain()
Get the main module.
Definition: ApiBase.php:536
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:164
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
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:565
ApiExpandTemplates\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiExpandTemplates.php:221