api: Update QueryFilearchive to provide information to everyone
[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 // @phan-suppress-next-line PhanUndeclaredMethodInCallable
107 if ( is_callable( [ $dom, 'saveXML' ] ) ) {
108 // @phan-suppress-next-line PhanUndeclaredMethod
109 $xml = $dom->saveXML();
110 } else {
111 // @phan-suppress-next-line PhanUndeclaredMethod
112 $xml = $dom->__toString();
113 }
114 if ( isset( $prop['parsetree'] ) ) {
115 unset( $prop['parsetree'] );
116 $retval['parsetree'] = $xml;
117 } else {
118 // the old way
119 $result->addValue( null, 'parsetree', $xml );
120 $result->addValue( null, ApiResult::META_BC_SUBELEMENTS, [ 'parsetree' ] );
121 }
122 }
123
124 // if they didn't want any output except (probably) the parse tree,
125 // then don't bother actually fully expanding it
126 if ( $prop || $params['prop'] === null ) {
127 $parser->startExternalParse( $titleObj, $options, Parser::OT_PREPROCESS );
128 $frame = $parser->getPreprocessor()->newFrame();
129 $wikitext = $parser->preprocess( $params['text'], $titleObj, $options, $revid, $frame );
130 if ( $params['prop'] === null ) {
131 // the old way
132 ApiResult::setContentValue( $retval, 'wikitext', $wikitext );
133 } else {
134 $p_output = $parser->getOutput();
135 if ( isset( $prop['categories'] ) ) {
136 $categories = $p_output->getCategories();
137 if ( $categories ) {
138 $categories_result = [];
139 foreach ( $categories as $category => $sortkey ) {
140 $entry = [];
141 $entry['sortkey'] = $sortkey;
142 ApiResult::setContentValue( $entry, 'category', (string)$category );
143 $categories_result[] = $entry;
144 }
145 ApiResult::setIndexedTagName( $categories_result, 'category' );
146 $retval['categories'] = $categories_result;
147 }
148 }
149 if ( isset( $prop['properties'] ) ) {
150 $properties = $p_output->getProperties();
151 if ( $properties ) {
152 ApiResult::setArrayType( $properties, 'BCkvp', 'name' );
153 ApiResult::setIndexedTagName( $properties, 'property' );
154 $retval['properties'] = $properties;
155 }
156 }
157 if ( isset( $prop['volatile'] ) ) {
158 $retval['volatile'] = $frame->isVolatile();
159 }
160 if ( isset( $prop['ttl'] ) && $frame->getTTL() !== null ) {
161 $retval['ttl'] = $frame->getTTL();
162 }
163 if ( isset( $prop['wikitext'] ) ) {
164 $retval['wikitext'] = $wikitext;
165 }
166 if ( isset( $prop['modules'] ) ) {
167 $retval['modules'] = array_values( array_unique( $p_output->getModules() ) );
168 // Deprecated since 1.32 (T188689)
169 $retval['modulescripts'] = [];
170 $retval['modulestyles'] = array_values( array_unique( $p_output->getModuleStyles() ) );
171 }
172 if ( isset( $prop['jsconfigvars'] ) ) {
173 $retval['jsconfigvars'] =
174 ApiResult::addMetadataToResultVars( $p_output->getJsConfigVars() );
175 }
176 if ( isset( $prop['encodedjsconfigvars'] ) ) {
177 $retval['encodedjsconfigvars'] = FormatJson::encode(
178 $p_output->getJsConfigVars(), false, FormatJson::ALL_OK
179 );
180 $retval[ApiResult::META_SUBELEMENTS][] = 'encodedjsconfigvars';
181 }
182 if ( isset( $prop['modules'] ) &&
183 !isset( $prop['jsconfigvars'] ) && !isset( $prop['encodedjsconfigvars'] ) ) {
184 $this->addWarning( 'apiwarn-moduleswithoutvars' );
185 }
186 }
187 }
188 ApiResult::setSubelementsList( $retval, [ 'wikitext', 'parsetree' ] );
189 $result->addValue( null, $this->getModuleName(), $retval );
190 }
191
192 public function getAllowedParams() {
193 return [
194 'title' => null,
195 'text' => [
196 ApiBase::PARAM_TYPE => 'text',
197 ApiBase::PARAM_REQUIRED => true,
198 ],
199 'revid' => [
200 ApiBase::PARAM_TYPE => 'integer',
201 ],
202 'prop' => [
203 ApiBase::PARAM_TYPE => [
204 'wikitext',
205 'categories',
206 'properties',
207 'volatile',
208 'ttl',
209 'modules',
210 'jsconfigvars',
211 'encodedjsconfigvars',
212 'parsetree',
213 ],
214 ApiBase::PARAM_ISMULTI => true,
215 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
216 ],
217 'includecomments' => false,
218 'generatexml' => [
219 ApiBase::PARAM_TYPE => 'boolean',
220 ApiBase::PARAM_DEPRECATED => true,
221 ],
222 ];
223 }
224
225 protected function getExamplesMessages() {
226 return [
227 'action=expandtemplates&text={{Project:Sandbox}}'
228 => 'apihelp-expandtemplates-example-simple',
229 ];
230 }
231
232 public function getHelpUrls() {
233 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Parsing_wikitext#expandtemplates';
234 }
235 }