2c7a82bea2eaff95ab1fb0246271f8ed78dc5a15
[lhc/web/wiklou.git] / includes / Xml.php
1 <?php
2
3 /**
4 * Module of static functions for generating XML
5 */
6
7 class Xml {
8 /**
9 * Format an XML element with given attributes and, optionally, text content.
10 * Element and attribute names are assumed to be ready for literal inclusion.
11 * Strings are assumed to not contain XML-illegal characters; special
12 * characters (<, >, &) are escaped but illegals are not touched.
13 *
14 * @param $element String:
15 * @param $attribs Array: Name=>value pairs. Values will be escaped.
16 * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
17 * @return string
18 */
19 public static function element( $element, $attribs = null, $contents = '') {
20 $out = '<' . $element;
21 if( !is_null( $attribs ) ) {
22 foreach( $attribs as $name => $val ) {
23 $out .= ' ' . $name . '="' . Sanitizer::encodeAttribute( $val ) . '"';
24 }
25 }
26 if( is_null( $contents ) ) {
27 $out .= '>';
28 } else {
29 if( $contents === '' ) {
30 $out .= ' />';
31 } else {
32 $out .= '>' . htmlspecialchars( $contents ) . "</$element>";
33 }
34 }
35 return $out;
36 }
37
38 /**
39 * Format an XML element as with self::element(), but run text through the
40 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
41 * is passed.
42 *
43 * @param $element String:
44 * @param $attribs Array: Name=>value pairs. Values will be escaped.
45 * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
46 * @return string
47 */
48 public static function elementClean( $element, $attribs = array(), $contents = '') {
49 if( $attribs ) {
50 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
51 }
52 if( $contents ) {
53 wfProfileIn( __METHOD__ . '-norm' );
54 $contents = UtfNormal::cleanUp( $contents );
55 wfProfileOut( __METHOD__ . '-norm' );
56 }
57 return self::element( $element, $attribs, $contents );
58 }
59
60 // Shortcuts
61 public static function openElement( $element, $attribs = null ) { return self::element( $element, $attribs, null ); }
62 public static function closeElement( $element ) { return "</$element>"; }
63
64 /**
65 * Same as <link>element</link>, but does not escape contents. Handy when the
66 * content you have is already valid xml.
67 */
68 public static function tags( $element, $attribs = null, $contents ) {
69 return self::element( $element, $attribs, null ) . $contents . "</$element>";
70 }
71
72 /**
73 * Create a namespace selector
74 *
75 * @param $selected Mixed: the namespace which should be selected, default ''
76 * @param $allnamespaces String: value of a special item denoting all namespaces. Null to not include (default)
77 * @param $includehidden Bool: include hidden namespaces?
78 * @return String: Html string containing the namespace selector
79 */
80 public static function namespaceSelector($selected = '', $allnamespaces = null, $includehidden=false) {
81 global $wgContLang;
82 if( $selected !== '' ) {
83 if( is_null( $selected ) ) {
84 // No namespace selected; let exact match work without hitting Main
85 $selected = '';
86 } else {
87 // Let input be numeric strings without breaking the empty match.
88 $selected = intval( $selected );
89 }
90 }
91 $s = "\n<select id='namespace' name='namespace' class='namespaceselector'>\n";
92 $arr = $wgContLang->getFormattedNamespaces();
93 if( !is_null($allnamespaces) ) {
94 $arr = array($allnamespaces => wfMsg('namespacesall')) + $arr;
95 }
96 foreach ($arr as $index => $name) {
97 if ($index < NS_MAIN) continue;
98
99 $name = $index !== 0 ? $name : wfMsg('blanknamespace');
100
101 if ($index === $selected) {
102 $s .= "\t" . self::element("option",
103 array("value" => $index, "selected" => "selected"),
104 $name) . "\n";
105 } else {
106 $s .= "\t" . self::element("option", array("value" => $index), $name) . "\n";
107 }
108 }
109 $s .= "</select>\n";
110 return $s;
111 }
112
113 public static function languageSelector( $selected, $customisedOnly = true ) {
114 global $wgContLanguageCode;
115 /**
116 * Make sure the site language is in the list; a custom language code
117 * might not have a defined name...
118 */
119 $languages = Language::getLanguageNames( $customisedOnly );
120 if( !array_key_exists( $wgContLanguageCode, $languages ) ) {
121 $languages[$wgContLanguageCode] = $wgContLanguageCode;
122 }
123 ksort( $languages );
124
125 /**
126 * If a bogus value is set, default to the content language.
127 * Otherwise, no default is selected and the user ends up
128 * with an Afrikaans interface since it's first in the list.
129 */
130 $selectedLang = isset( $languages[$selected] ) ? $selected : $wgContLanguageCode;
131 $options = "\n";
132 foreach( $languages as $code => $name ) {
133 $selected = ($code == $selectedLang);
134 $options .= Xml::option( "$code - $name", $code, $selected ) . "\n";
135 }
136
137 return array(
138 Xml::label( wfMsg('yourlanguage'), 'wpUserLanguage' ),
139 Xml::tags( 'select',
140 array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ),
141 $options
142 )
143 );
144
145 }
146
147 public static function span( $text, $class, $attribs=array() ) {
148 return self::element( 'span', array( 'class' => $class ) + $attribs, $text );
149 }
150
151 /**
152 * Convenience function to build an HTML text input field
153 * @return string HTML
154 */
155 public static function input( $name, $size=false, $value=false, $attribs=array() ) {
156 return self::element( 'input', array(
157 'name' => $name,
158 'size' => $size,
159 'value' => $value ) + $attribs );
160 }
161
162 /**
163 * Internal function for use in checkboxes and radio buttons and such.
164 * @return array
165 */
166 public static function attrib( $name, $present = true ) {
167 return $present ? array( $name => $name ) : array();
168 }
169
170 /**
171 * Convenience function to build an HTML checkbox
172 * @return string HTML
173 */
174 public static function check( $name, $checked=false, $attribs=array() ) {
175 return self::element( 'input', array_merge(
176 array(
177 'name' => $name,
178 'type' => 'checkbox',
179 'value' => 1 ),
180 self::attrib( 'checked', $checked ),
181 $attribs ) );
182 }
183
184 /**
185 * Convenience function to build an HTML radio button
186 * @return string HTML
187 */
188 public static function radio( $name, $value, $checked=false, $attribs=array() ) {
189 return self::element( 'input', array(
190 'name' => $name,
191 'type' => 'radio',
192 'value' => $value ) + self::attrib( 'checked', $checked ) + $attribs );
193 }
194
195 /**
196 * Convenience function to build an HTML form label
197 * @return string HTML
198 */
199 public static function label( $label, $id ) {
200 return self::element( 'label', array( 'for' => $id ), $label );
201 }
202
203 /**
204 * Convenience function to build an HTML text input field with a label
205 * @return string HTML
206 */
207 public static function inputLabel( $label, $name, $id, $size=false, $value=false, $attribs=array() ) {
208 return Xml::label( $label, $id ) .
209 '&nbsp;' .
210 self::input( $name, $size, $value, array( 'id' => $id ) + $attribs );
211 }
212
213 /**
214 * Convenience function to build an HTML checkbox with a label
215 * @return string HTML
216 */
217 public static function checkLabel( $label, $name, $id, $checked=false, $attribs=array() ) {
218 return self::check( $name, $checked, array( 'id' => $id ) + $attribs ) .
219 '&nbsp;' .
220 self::label( $label, $id );
221 }
222
223 /**
224 * Convenience function to build an HTML radio button with a label
225 * @return string HTML
226 */
227 public static function radioLabel( $label, $name, $value, $id, $checked=false, $attribs=array() ) {
228 return self::radio( $name, $value, $checked, array( 'id' => $id ) + $attribs ) .
229 '&nbsp;' .
230 self::label( $label, $id );
231 }
232
233 /**
234 * Convenience function to build an HTML submit button
235 * @param $value String: label text for the button
236 * @param $attribs Array: optional custom attributes
237 * @return string HTML
238 */
239 public static function submitButton( $value, $attribs=array() ) {
240 return self::element( 'input', array( 'type' => 'submit', 'value' => $value ) + $attribs );
241 }
242
243 /**
244 * Convenience function to build an HTML hidden form field.
245 * @todo Document $name parameter.
246 * @param $name FIXME
247 * @param $value String: label text for the button
248 * @param $attribs Array: optional custom attributes
249 * @return string HTML
250 */
251 public static function hidden( $name, $value, $attribs=array() ) {
252 return self::element( 'input', array(
253 'name' => $name,
254 'type' => 'hidden',
255 'value' => $value ) + $attribs );
256 }
257
258 /**
259 * Convenience function to build an HTML drop-down list item.
260 * @param $text String: text for this item
261 * @param $value String: form submission value; if empty, use text
262 * @param $selected boolean: if true, will be the default selected item
263 * @param $attribs array: optional additional HTML attributes
264 * @return string HTML
265 */
266 public static function option( $text, $value=null, $selected=false,
267 $attribs=array() ) {
268 if( !is_null( $value ) ) {
269 $attribs['value'] = $value;
270 }
271 if( $selected ) {
272 $attribs['selected'] = 'selected';
273 }
274 return self::element( 'option', $attribs, $text );
275 }
276
277 /**
278 * Returns an escaped string suitable for inclusion in a string literal
279 * for JavaScript source code.
280 * Illegal control characters are assumed not to be present.
281 *
282 * @param string $string
283 * @return string
284 */
285 public static function escapeJsString( $string ) {
286 // See ECMA 262 section 7.8.4 for string literal format
287 $pairs = array(
288 "\\" => "\\\\",
289 "\"" => "\\\"",
290 '\'' => '\\\'',
291 "\n" => "\\n",
292 "\r" => "\\r",
293
294 # To avoid closing the element or CDATA section
295 "<" => "\\x3c",
296 ">" => "\\x3e",
297
298 # To avoid any complaints about bad entity refs
299 "&" => "\\x26",
300 );
301 return strtr( $string, $pairs );
302 }
303
304 /**
305 * Encode a variable of unknown type to JavaScript.
306 * Doesn't support hashtables just yet.
307 */
308 public static function encodeJsVar( $value ) {
309 if ( is_bool( $value ) ) {
310 $s = $value ? 'true' : 'false';
311 } elseif ( is_null( $value ) ) {
312 $s = 'null';
313 } elseif ( is_int( $value ) ) {
314 $s = $value;
315 } elseif ( is_array( $value ) ) {
316 $s = '[';
317 foreach ( $value as $name => $elt ) {
318 if ( $s != '[' ) {
319 $s .= ', ';
320 }
321 $s .= self::encodeJsVar( $elt );
322 }
323 $s .= ']';
324 } else {
325 $s = '"' . self::escapeJsString( $value ) . '"';
326 }
327 return $s;
328 }
329
330
331 /**
332 * Check if a string is well-formed XML.
333 * Must include the surrounding tag.
334 *
335 * @param $text String: string to test.
336 * @return bool
337 *
338 * @todo Error position reporting return
339 */
340 public static function isWellFormed( $text ) {
341 $parser = xml_parser_create( "UTF-8" );
342
343 # case folding violates XML standard, turn it off
344 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
345
346 if( !xml_parse( $parser, $text, true ) ) {
347 //$err = xml_error_string( xml_get_error_code( $parser ) );
348 //$position = xml_get_current_byte_index( $parser );
349 //$fragment = $this->extractFragment( $html, $position );
350 //$this->mXmlError = "$err at byte $position:\n$fragment";
351 xml_parser_free( $parser );
352 return false;
353 }
354 xml_parser_free( $parser );
355 return true;
356 }
357
358 /**
359 * Check if a string is a well-formed XML fragment.
360 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
361 * and can use HTML named entities.
362 *
363 * @param $text String:
364 * @return bool
365 */
366 public static function isWellFormedXmlFragment( $text ) {
367 $html =
368 Sanitizer::hackDocType() .
369 '<html>' .
370 $text .
371 '</html>';
372 return Xml::isWellFormed( $html );
373 }
374
375 /**
376 * Replace " > and < with their respective HTML entities ( &quot;,
377 * &gt;, &lt;)
378 *
379 * @param $in String: text that might contain HTML tags.
380 * @return string Escaped string
381 */
382 public static function escapeTagsOnly( $in ) {
383 return str_replace(
384 array( '"', '>', '<' ),
385 array( '&quot;', '&gt;', '&lt;' ),
386 $in );
387 }
388 }
389 ?>