MediaWiki REL1_31
ApiExpandTemplates.php
Go to the documentation of this file.
1<?php
31
32 public function execute() {
33 // Cache may vary on the user because ParserOptions gets data from it
34 $this->getMain()->setCacheMode( 'anon-public-user-private' );
35
36 // Get parameters
38 $this->requireMaxOneParameter( $params, 'prop', 'generatexml' );
39
40 $title = $params['title'];
41 if ( $title === null ) {
42 $titleProvided = false;
43 // A title is needed for parsing, so arbitrarily choose one
44 $title = 'API';
45 } else {
46 $titleProvided = true;
47 }
48
49 if ( $params['prop'] === null ) {
50 $this->addDeprecation(
51 'apiwarn-deprecation-expandtemplates-prop', 'action=expandtemplates&!prop'
52 );
53 $prop = [];
54 } else {
55 $prop = array_flip( $params['prop'] );
56 }
57
58 $titleObj = Title::newFromText( $title );
59 if ( !$titleObj || $titleObj->isExternal() ) {
60 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
61 }
62
63 // Get title and revision ID for parser
64 $revid = $params['revid'];
65 if ( $revid !== null ) {
66 $rev = Revision::newFromId( $revid );
67 if ( !$rev ) {
68 $this->dieWithError( [ 'apierror-nosuchrevid', $revid ] );
69 }
70 $pTitleObj = $titleObj;
71 $titleObj = $rev->getTitle();
72 if ( $titleProvided ) {
73 if ( !$titleObj->equals( $pTitleObj ) ) {
74 $this->addWarning( [ 'apierror-revwrongpage', $rev->getId(),
75 wfEscapeWikiText( $pTitleObj->getPrefixedText() ) ] );
76 }
77 } else {
78 // Consider the title derived from the revid as having
79 // been provided.
80 $titleProvided = true;
81 }
82 }
83
84 $result = $this->getResult();
85
86 // Parse text
87 global $wgParser;
88 $options = ParserOptions::newFromContext( $this->getContext() );
89
90 if ( $params['includecomments'] ) {
91 $options->setRemoveComments( false );
92 }
93
94 $reset = null;
95 $suppressCache = false;
96 Hooks::run( 'ApiMakeParserOptions',
97 [ $options, $titleObj, $params, $this, &$reset, &$suppressCache ] );
98
99 $retval = [];
100
101 if ( isset( $prop['parsetree'] ) || $params['generatexml'] ) {
102 $wgParser->startExternalParse( $titleObj, $options, Parser::OT_PREPROCESS );
103 $dom = $wgParser->preprocessToDom( $params['text'] );
104 if ( is_callable( [ $dom, 'saveXML' ] ) ) {
105 $xml = $dom->saveXML();
106 } else {
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 $wgParser->startExternalParse( $titleObj, $options, Parser::OT_PREPROCESS );
123 $frame = $wgParser->getPreprocessor()->newFrame();
124 $wikitext = $wgParser->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 = $wgParser->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 $retval['modulescripts'] = array_values( array_unique( $p_output->getModuleScripts() ) );
164 $retval['modulestyles'] = array_values( array_unique( $p_output->getModuleStyles() ) );
165 }
166 if ( isset( $prop['jsconfigvars'] ) ) {
167 $retval['jsconfigvars'] =
168 ApiResult::addMetadataToResultVars( $p_output->getJsConfigVars() );
169 }
170 if ( isset( $prop['encodedjsconfigvars'] ) ) {
171 $retval['encodedjsconfigvars'] = FormatJson::encode(
172 $p_output->getJsConfigVars(), false, FormatJson::ALL_OK
173 );
174 $retval[ApiResult::META_SUBELEMENTS][] = 'encodedjsconfigvars';
175 }
176 if ( isset( $prop['modules'] ) &&
177 !isset( $prop['jsconfigvars'] ) && !isset( $prop['encodedjsconfigvars'] ) ) {
178 $this->addWarning( 'apiwarn-moduleswithoutvars' );
179 }
180 }
181 }
182 ApiResult::setSubelementsList( $retval, [ 'wikitext', 'parsetree' ] );
183 $result->addValue( null, $this->getModuleName(), $retval );
184 }
185
186 public function getAllowedParams() {
187 return [
188 'title' => null,
189 'text' => [
190 ApiBase::PARAM_TYPE => 'text',
192 ],
193 'revid' => [
194 ApiBase::PARAM_TYPE => 'integer',
195 ],
196 'prop' => [
198 'wikitext',
199 'categories',
200 'properties',
201 'volatile',
202 'ttl',
203 'modules',
204 'jsconfigvars',
205 'encodedjsconfigvars',
206 'parsetree',
207 ],
210 ],
211 'includecomments' => false,
212 'generatexml' => [
213 ApiBase::PARAM_TYPE => 'boolean',
215 ],
216 ];
217 }
218
219 protected function getExamplesMessages() {
220 return [
221 'action=expandtemplates&text={{Project:Sandbox}}'
222 => 'apihelp-expandtemplates-example-simple',
223 ];
224 }
225
226 public function getHelpUrls() {
227 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Parsing_wikitext#expandtemplates';
228 }
229}
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
$wgParser
Definition Setup.php:917
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:37
const PARAM_REQUIRED
(boolean) Is the parameter required?
Definition ApiBase.php:111
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
Definition ApiBase.php:105
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition ApiBase.php:1895
getMain()
Get the main module.
Definition ApiBase.php:537
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition ApiBase.php:87
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:749
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:157
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
Definition ApiBase.php:1833
getResult()
Get the result object.
Definition ApiBase.php:641
requireMaxOneParameter( $params, $required)
Die if more than one of a certain set of parameters is set and not false.
Definition ApiBase.php:823
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition ApiBase.php:1819
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:521
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition ApiBase.php:51
API module that functions as a shortcut to the wikitext preprocessor.
getExamplesMessages()
Returns usage examples for this module.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
getHelpUrls()
Return links to more detailed help pages about the module.
static setArrayType(array &$arr, $type, $kvpKeyName=null)
Set the array data type.
static addMetadataToResultVars( $vars, $forceHash=true)
Add the correct metadata to an array of vars we want to export through the API.
const META_SUBELEMENTS
Key for the 'subelements' metadata item.
Definition ApiResult.php:76
static setSubelementsList(array &$arr, $names)
Causes the elements with the specified names to be output as subelements rather than attributes.
const META_BC_SUBELEMENTS
Key for the 'BC subelements' metadata item.
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
static setContentValue(array &$arr, $name, $value, $flags=0)
Add an output value to the array by name and mark as META_CONTENT.
getContext()
Get the base IContextSource object.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account incomplete not yet checked for validity & $retval
Definition hooks.txt:266
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition hooks.txt:2001
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition hooks.txt:1777
$params