Merge "Unsuppress another phan issue (part 7)"
[lhc/web/wiklou.git] / includes / api / ApiExpandTemplates.php
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
23 use MediaWiki\MediaWikiServices;
24
25 /**
26 * API module that functions as a shortcut to the wikitext preprocessor. Expands
27 * any templates in a provided string, and returns the result of this expansion
28 * to the caller.
29 *
30 * @ingroup API
31 */
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 } else {
80 // Consider the title derived from the revid as having
81 // been provided.
82 $titleProvided = true;
83 }
84 }
85
86 $result = $this->getResult();
87
88 // Parse text
89 $options = ParserOptions::newFromContext( $this->getContext() );
90
91 if ( $params['includecomments'] ) {
92 $options->setRemoveComments( false );
93 }
94
95 $reset = null;
96 $suppressCache = false;
97 Hooks::run( 'ApiMakeParserOptions',
98 [ $options, $titleObj, $params, $this, &$reset, &$suppressCache ] );
99
100 $retval = [];
101
102 $parser = MediaWikiServices::getInstance()->getParser();
103 if ( isset( $prop['parsetree'] ) || $params['generatexml'] ) {
104 $parser->startExternalParse( $titleObj, $options, Parser::OT_PREPROCESS );
105 $dom = $parser->preprocessToDom( $params['text'] );
106 if ( is_callable( [ $dom, 'saveXML' ] ) ) {
107 // @phan-suppress-next-line PhanUndeclaredMethod
108 $xml = $dom->saveXML();
109 } else {
110 // @phan-suppress-next-line PhanUndeclaredMethod
111 $xml = $dom->__toString();
112 }
113 if ( isset( $prop['parsetree'] ) ) {
114 unset( $prop['parsetree'] );
115 $retval['parsetree'] = $xml;
116 } else {
117 // the old way
118 $result->addValue( null, 'parsetree', $xml );
119 $result->addValue( null, ApiResult::META_BC_SUBELEMENTS, [ 'parsetree' ] );
120 }
121 }
122
123 // if they didn't want any output except (probably) the parse tree,
124 // then don't bother actually fully expanding it
125 if ( $prop || $params['prop'] === null ) {
126 $parser->startExternalParse( $titleObj, $options, Parser::OT_PREPROCESS );
127 $frame = $parser->getPreprocessor()->newFrame();
128 $wikitext = $parser->preprocess( $params['text'], $titleObj, $options, $revid, $frame );
129 if ( $params['prop'] === null ) {
130 // the old way
131 ApiResult::setContentValue( $retval, 'wikitext', $wikitext );
132 } else {
133 $p_output = $parser->getOutput();
134 if ( isset( $prop['categories'] ) ) {
135 $categories = $p_output->getCategories();
136 if ( $categories ) {
137 $categories_result = [];
138 foreach ( $categories as $category => $sortkey ) {
139 $entry = [];
140 $entry['sortkey'] = $sortkey;
141 ApiResult::setContentValue( $entry, 'category', (string)$category );
142 $categories_result[] = $entry;
143 }
144 ApiResult::setIndexedTagName( $categories_result, 'category' );
145 $retval['categories'] = $categories_result;
146 }
147 }
148 if ( isset( $prop['properties'] ) ) {
149 $properties = $p_output->getProperties();
150 if ( $properties ) {
151 ApiResult::setArrayType( $properties, 'BCkvp', 'name' );
152 ApiResult::setIndexedTagName( $properties, 'property' );
153 $retval['properties'] = $properties;
154 }
155 }
156 if ( isset( $prop['volatile'] ) ) {
157 $retval['volatile'] = $frame->isVolatile();
158 }
159 if ( isset( $prop['ttl'] ) && $frame->getTTL() !== null ) {
160 $retval['ttl'] = $frame->getTTL();
161 }
162 if ( isset( $prop['wikitext'] ) ) {
163 $retval['wikitext'] = $wikitext;
164 }
165 if ( isset( $prop['modules'] ) ) {
166 $retval['modules'] = array_values( array_unique( $p_output->getModules() ) );
167 // Deprecated since 1.32 (T188689)
168 $retval['modulescripts'] = [];
169 $retval['modulestyles'] = array_values( array_unique( $p_output->getModuleStyles() ) );
170 }
171 if ( isset( $prop['jsconfigvars'] ) ) {
172 $retval['jsconfigvars'] =
173 ApiResult::addMetadataToResultVars( $p_output->getJsConfigVars() );
174 }
175 if ( isset( $prop['encodedjsconfigvars'] ) ) {
176 $retval['encodedjsconfigvars'] = FormatJson::encode(
177 $p_output->getJsConfigVars(), false, FormatJson::ALL_OK
178 );
179 $retval[ApiResult::META_SUBELEMENTS][] = 'encodedjsconfigvars';
180 }
181 if ( isset( $prop['modules'] ) &&
182 !isset( $prop['jsconfigvars'] ) && !isset( $prop['encodedjsconfigvars'] ) ) {
183 $this->addWarning( 'apiwarn-moduleswithoutvars' );
184 }
185 }
186 }
187 ApiResult::setSubelementsList( $retval, [ 'wikitext', 'parsetree' ] );
188 $result->addValue( null, $this->getModuleName(), $retval );
189 }
190
191 public function getAllowedParams() {
192 return [
193 'title' => null,
194 'text' => [
195 ApiBase::PARAM_TYPE => 'text',
196 ApiBase::PARAM_REQUIRED => true,
197 ],
198 'revid' => [
199 ApiBase::PARAM_TYPE => 'integer',
200 ],
201 'prop' => [
202 ApiBase::PARAM_TYPE => [
203 'wikitext',
204 'categories',
205 'properties',
206 'volatile',
207 'ttl',
208 'modules',
209 'jsconfigvars',
210 'encodedjsconfigvars',
211 'parsetree',
212 ],
213 ApiBase::PARAM_ISMULTI => true,
214 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
215 ],
216 'includecomments' => false,
217 'generatexml' => [
218 ApiBase::PARAM_TYPE => 'boolean',
219 ApiBase::PARAM_DEPRECATED => true,
220 ],
221 ];
222 }
223
224 protected function getExamplesMessages() {
225 return [
226 'action=expandtemplates&text={{Project:Sandbox}}'
227 => 'apihelp-expandtemplates-example-simple',
228 ];
229 }
230
231 public function getHelpUrls() {
232 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Parsing_wikitext#expandtemplates';
233 }
234 }