Debian Codegraph @

includes/api/ApiFormatXml.php

raw symbols SCIP
1 <?php
2 /**
3 * Copyright © 2006 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 namespace MediaWiki\Api;
24
25 use MediaWiki\MainConfigNames;
26 use MediaWiki\Title\Title;
27 use MediaWiki\Xml\Xml;
28 use Wikimedia\ParamValidator\ParamValidator;
29
30 /**
31 * API XML output formatter
32 * @ingroup API
33 */
34 class ApiFormatXml extends ApiFormatBase {
35
36 /** @var string */
37 private $mRootElemName = 'api';
38 /** @var string */
39 public static $namespace = 'http://www.mediawiki.org/xml/api/';
40 /** @var bool */
41 private $mIncludeNamespace = false;
42 /** @var string|null */
43 private $mXslt = null;
44
45 public function getMimeType() {
46 return 'text/xml';
47 }
48
49 public function setRootElement( $rootElemName ) {
50 $this->mRootElemName = $rootElemName;
51 }
52
53 public function execute() {
54 $params = $this->extractRequestParams();
55 $this->mIncludeNamespace = $params['includexmlnamespace'];
56 $this->mXslt = $params['xslt'];
57
58 $this->printText( '<?xml version="1.0"?>' );
59 if ( $this->mXslt !== null ) {
60 $this->addXslt();
61 }
62
63 $result = $this->getResult();
64 if ( $this->mIncludeNamespace && $result->getResultData( 'xmlns' ) === null ) {
65 // If the result data already contains an 'xmlns' namespace added
66 // for custom XML output types, it will override the one for the
67 // generic API results.
68 // This allows API output of other XML types like Atom, RSS, RSD.
69 $result->addValue( null, 'xmlns', self::$namespace, ApiResult::NO_SIZE_CHECK );
70 }
71 $data = $result->getResultData( null, [
72 'Custom' => static function ( &$data, &$metadata ) {
73 if ( isset( $metadata[ApiResult::META_TYPE] ) ) {
74 // We want to use non-BC for BCassoc to force outputting of _idx.
75 switch ( $metadata[ApiResult::META_TYPE] ) {
76 case 'BCassoc':
77 $metadata[ApiResult::META_TYPE] = 'assoc';
78 break;
79 }
80 }
81 },
82 'BC' => [ 'nobool', 'no*', 'nosub' ],
83 'Types' => [ 'ArmorKVP' => '_name' ],
84 ] );
85
86 $this->printText(
87 static::recXmlPrint( $this->mRootElemName,
88 $data,
89 $this->getIsHtml() ? -2 : null
90 )
91 );
92 }
93
94 /**
95 * This method takes an array and converts it to XML.
96 *
97 * @param string|null $name Tag name
98 * @param mixed $value Tag value (attributes/content/subelements)
99 * @param int|null $indent Indentation
100 * @param array $attributes Additional attributes
101 * @return string
102 */
103 public static function recXmlPrint( $name, $value, $indent, $attributes = [] ) {
104 $retval = '';
105 if ( $indent !== null ) {
106 if ( $name !== null ) {
107 $indent += 2;
108 }
109 $indstr = "\n" . str_repeat( ' ', $indent );
110 } else {
111 $indstr = '';
112 }
113
114 if ( is_object( $value ) ) {
115 $value = (array)$value;
116 }
117 if ( is_array( $value ) ) {
118 $contentKey = $value[ApiResult::META_CONTENT] ?? '*';
119 $subelementKeys = $value[ApiResult::META_SUBELEMENTS] ?? [];
120 if ( isset( $value[ApiResult::META_BC_SUBELEMENTS] ) ) {
121 $subelementKeys = array_merge(
122 $subelementKeys, $value[ApiResult::META_BC_SUBELEMENTS]
123 );
124 }
125 $preserveKeys = $value[ApiResult::META_PRESERVE_KEYS] ?? [];
126 $indexedTagName = isset( $value[ApiResult::META_INDEXED_TAG_NAME] )
127 ? self::mangleName( $value[ApiResult::META_INDEXED_TAG_NAME], $preserveKeys )
128 : '_v';
129 $bcBools = $value[ApiResult::META_BC_BOOLS] ?? [];
130 $indexSubelements = isset( $value[ApiResult::META_TYPE] )
131 && $value[ApiResult::META_TYPE] !== 'array';
132
133 $content = null;
134 $subelements = [];
135 $indexedSubelements = [];
136 foreach ( $value as $k => $v ) {
137 if ( ApiResult::isMetadataKey( $k ) && !in_array( $k, $preserveKeys, true ) ) {
138 continue;
139 }
140
141 $oldv = $v;
142 if ( is_bool( $v ) && !in_array( $k, $bcBools, true ) ) {
143 $v = $v ? 'true' : 'false';
144 }
145
146 if ( $name !== null && $k === $contentKey ) {
147 $content = $v;
148 } elseif ( is_int( $k ) ) {
149 $indexedSubelements[$k] = $v;
150 } elseif ( is_array( $v ) || is_object( $v ) ) {
151 $subelements[self::mangleName( $k, $preserveKeys )] = $v;
152 } elseif ( in_array( $k, $subelementKeys, true ) || $name === null ) {
153 $subelements[self::mangleName( $k, $preserveKeys )] = [
154 'content' => $v,
155 ApiResult::META_CONTENT => 'content',
156 ApiResult::META_TYPE => 'assoc',
157 ];
158 } elseif ( is_bool( $oldv ) ) {
159 if ( $oldv ) {
160 $attributes[self::mangleName( $k, $preserveKeys )] = '';
161 }
162 } elseif ( $v !== null ) {
163 $attributes[self::mangleName( $k, $preserveKeys )] = $v;
164 }
165 }
166
167 if ( $content !== null ) {
168 if ( $subelements || $indexedSubelements ) {
169 $subelements[self::mangleName( $contentKey, $preserveKeys )] = [
170 'content' => $content,
171 ApiResult::META_CONTENT => 'content',
172 ApiResult::META_TYPE => 'assoc',
173 ];
174 $content = null;
175 } elseif ( is_scalar( $content ) ) {
176 // Add xml:space="preserve" to the element so XML parsers
177 // will leave whitespace in the content alone
178 $attributes += [ 'xml:space' => 'preserve' ];
179 }
180 }
181
182 if ( $content !== null ) {
183 if ( is_scalar( $content ) ) {
184 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable name is check for null in other code
185 $retval .= $indstr . Xml::element( $name, $attributes, $content );
186 } else {
187 if ( $name !== null ) {
188 $retval .= $indstr . Xml::element( $name, $attributes, null );
189 }
190 $retval .= static::recXmlPrint( null, $content, $indent );
191 if ( $name !== null ) {
192 $retval .= $indstr . Xml::closeElement( $name );
193 }
194 }
195 } elseif ( !$indexedSubelements && !$subelements ) {
196 if ( $name !== null ) {
197 $retval .= $indstr . Xml::element( $name, $attributes );
198 }
199 } else {
200 if ( $name !== null ) {
201 $retval .= $indstr . Xml::element( $name, $attributes, null );
202 }
203 foreach ( $subelements as $k => $v ) {
204 $retval .= static::recXmlPrint( $k, $v, $indent );
205 }
206 foreach ( $indexedSubelements as $k => $v ) {
207 $retval .= static::recXmlPrint( $indexedTagName, $v, $indent,
208 $indexSubelements ? [ '_idx' => $k ] : []
209 );
210 }
211 if ( $name !== null ) {
212 $retval .= $indstr . Xml::closeElement( $name );
213 }
214 }
215 } else {
216 // to make sure null value doesn't produce unclosed element,
217 // which is what Xml::element( $name, null, null ) returns
218 if ( $value === null ) {
219 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable name is check for null in other code
220 $retval .= $indstr . Xml::element( $name, $attributes );
221 } else {
222 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable name is check for null in other code
223 $retval .= $indstr . Xml::element( $name, $attributes, $value );
224 }
225 }
226
227 return $retval;
228 }
229
230 /**
231 * Mangle XML-invalid names to be valid in XML
232 * @param string $name
233 * @param array $preserveKeys Names to not mangle
234 * @return string Mangled name
235 */
236 private static function mangleName( $name, $preserveKeys = [] ) {
237 static $nsc = null, $nc = null;
238
239 if ( in_array( $name, $preserveKeys, true ) ) {
240 return $name;
241 }
242
243 if ( $name === '' ) {
244 return '_';
245 }
246
247 if ( $nsc === null ) {
248 // Note we omit ':' from $nsc and $nc because it's reserved for XML
249 // namespacing, and we omit '_' from $nsc (but not $nc) because we
250 // reserve it.
251 $nsc = 'A-Za-z\x{C0}-\x{D6}\x{D8}-\x{F6}\x{F8}-\x{2FF}\x{370}-\x{37D}\x{37F}-\x{1FFF}' .
252 '\x{200C}-\x{200D}\x{2070}-\x{218F}\x{2C00}-\x{2FEF}\x{3001}-\x{D7FF}' .
253 '\x{F900}-\x{FDCF}\x{FDF0}-\x{FFFD}\x{10000}-\x{EFFFF}';
254 $nc = $nsc . '_\-.0-9\x{B7}\x{300}-\x{36F}\x{203F}-\x{2040}';
255 }
256
257 if ( preg_match( "/^[$nsc][$nc]*$/uS", $name ) ) {
258 return $name;
259 }
260
261 return '_' . preg_replace_callback(
262 "/[^$nc]/uS",
263 static function ( $m ) {
264 return sprintf( '.%X.', \UtfNormal\Utils::utf8ToCodepoint( $m[0] ) );
265 },
266 str_replace( '.', '.2E.', $name )
267 );
268 }
269
270 protected function addXslt() {
271 if ( !$this->getConfig()->get( MainConfigNames::EnableUnsafeXsltOption ) ) {
272 $this->addWarning( 'apiwarn-xslt-disabled' );
273 return;
274 }
275 $nt = Title::newFromText( $this->mXslt );
276 if ( $nt === null || !$nt->exists() ) {
277 $this->addWarning( 'apiwarn-invalidxmlstylesheet' );
278
279 return;
280 }
281 if ( $nt->getNamespace() !== NS_MEDIAWIKI ) {
282 $this->addWarning( 'apiwarn-invalidxmlstylesheetns' );
283
284 return;
285 }
286 if ( !str_ends_with( $nt->getText(), '.xsl' ) ) {
287 $this->addWarning( 'apiwarn-invalidxmlstylesheetext' );
288
289 return;
290 }
291 $this->printText( '<?xml-stylesheet href="' .
292 htmlspecialchars( $nt->getLocalURL( 'action=raw' ) ) . '" type="text/xsl" ?>' );
293 }
294
295 public function getAllowedParams() {
296 return parent::getAllowedParams() + [
297 'xslt' => [
298 ApiBase::PARAM_HELP_MSG => 'apihelp-xml-param-xslt',
299 ],
300 'includexmlnamespace' => [
301 ParamValidator::PARAM_DEFAULT => false,
302 ApiBase::PARAM_HELP_MSG => 'apihelp-xml-param-includexmlnamespace',
303 ],
304 ];
305 }
306 }
307
308 /** @deprecated class alias since 1.43 */
309 class_alias( ApiFormatXml::class, 'ApiFormatXml' );