case change for aesthetic purposes
[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 $out .= self::expandAttributes( $attribs );
23 }
24 if( is_null( $contents ) ) {
25 $out .= '>';
26 } else {
27 if( $contents === '' ) {
28 $out .= ' />';
29 } else {
30 $out .= '>' . htmlspecialchars( $contents ) . "</$element>";
31 }
32 }
33 return $out;
34 }
35
36 /**
37 * Given an array of ('attributename' => 'value'), it generates the code
38 * to set the XML attributes : attributename="value".
39 * The values are passed to Sanitizer::encodeAttribute.
40 * Return null if no attributes given.
41 * @param $attribs Array of attributes for an XML element
42 */
43 private static function expandAttributes( $attribs ) {
44 if( is_null( $attribs ) ) {
45 return null;
46 } else {
47 $out = '';
48 foreach( $attribs as $name => $val ) {
49 $out .= ' ' . $name . '="' . Sanitizer::encodeAttribute( $val ) . '"';
50 }
51 return $out;
52 }
53 }
54
55 /**
56 * Format an XML element as with self::element(), but run text through the
57 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
58 * is passed.
59 *
60 * @param $element String:
61 * @param $attribs Array: Name=>value pairs. Values will be escaped.
62 * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
63 * @return string
64 */
65 public static function elementClean( $element, $attribs = array(), $contents = '') {
66 if( $attribs ) {
67 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
68 }
69 if( $contents ) {
70 wfProfileIn( __METHOD__ . '-norm' );
71 $contents = UtfNormal::cleanUp( $contents );
72 wfProfileOut( __METHOD__ . '-norm' );
73 }
74 return self::element( $element, $attribs, $contents );
75 }
76
77 /** This open an XML element */
78 public static function openElement( $element, $attribs = null ) {
79 return '<' . $element . self::expandAttributes( $attribs ) . '>';
80 }
81
82 // Shortcut
83 public static function closeElement( $element ) { return "</$element>"; }
84
85 /**
86 * Same as <link>element</link>, but does not escape contents. Handy when the
87 * content you have is already valid xml.
88 */
89 public static function tags( $element, $attribs = null, $contents ) {
90 return self::openElement( $element, $attribs ) . $contents . "</$element>";
91 }
92
93 /**
94 * Create a namespace selector
95 *
96 * @param $selected Mixed: the namespace which should be selected, default ''
97 * @param $allnamespaces String: value of a special item denoting all namespaces. Null to not include (default)
98 * @param $includehidden Bool: include hidden namespaces?
99 * @return String: Html string containing the namespace selector
100 */
101 public static function namespaceSelector($selected = '', $allnamespaces = null, $includehidden=false) {
102 global $wgContLang;
103 if( is_null( $selected ) )
104 $selected = '';
105 $s = "\n<select id='namespace' name='namespace' class='namespaceselector'>\n";
106 $arr = $wgContLang->getFormattedNamespaces();
107 if( !is_null($allnamespaces) ) {
108 $arr = array($allnamespaces => wfMsg('namespacesall')) + $arr;
109 }
110 foreach ($arr as $index => $name) {
111 if ($index < NS_MAIN) continue;
112
113 $name = $index !== 0 ? $name : wfMsg('blanknamespace');
114
115 if ($index === $selected) {
116 $s .= "\t" . self::element("option",
117 array("value" => $index, "selected" => "selected"),
118 $name) . "\n";
119 } else {
120 $s .= "\t" . self::element("option", array("value" => $index), $name) . "\n";
121 }
122 }
123 $s .= "</select>\n";
124 return $s;
125 }
126
127 /**
128 * Create a date selector
129 *
130 * @param $selected Mixed: the month which should be selected, default ''
131 * @param $allmonths String: value of a special item denoting all month. Null to not include (default)
132 * @param string $id Element identifier
133 * @return String: Html string containing the month selector
134 */
135 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
136 global $wgLang;
137 $options = array();
138 if( is_null( $selected ) )
139 $selected = '';
140 if( !is_null( $allmonths ) )
141 $options[] = self::option( wfMsg( 'monthsall' ), $allmonths, $selected === $allmonths );
142 for( $i = 1; $i < 13; $i++ )
143 $options[] = self::option( $wgLang->getMonthName( $i ), $i, $selected === $i );
144 return self::openElement( 'select', array( 'id' => $id, 'name' => 'month' ) )
145 . implode( "\n", $options )
146 . self::closeElement( 'select' );
147 }
148
149 /**
150 *
151 * @param $language The language code of the selected language
152 * @param $customisedOnly If true only languages which have some content are listed
153 * @return array of label and select
154 */
155 public static function languageSelector( $selected, $customisedOnly = true ) {
156 global $wgContLanguageCode;
157 /**
158 * Make sure the site language is in the list; a custom language code
159 * might not have a defined name...
160 */
161 $languages = Language::getLanguageNames( $customisedOnly );
162 if( !array_key_exists( $wgContLanguageCode, $languages ) ) {
163 $languages[$wgContLanguageCode] = $wgContLanguageCode;
164 }
165 ksort( $languages );
166
167 /**
168 * If a bogus value is set, default to the content language.
169 * Otherwise, no default is selected and the user ends up
170 * with an Afrikaans interface since it's first in the list.
171 */
172 $selected = isset( $languages[$selected] ) ? $selected : $wgContLanguageCode;
173 $options = "\n";
174 foreach( $languages as $code => $name ) {
175 $options .= Xml::option( "$code - $name", $code, ($code == $selected) ) . "\n";
176 }
177
178 return array(
179 Xml::label( wfMsg('yourlanguage'), 'wpUserLanguage' ),
180 Xml::tags( 'select',
181 array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ),
182 $options
183 )
184 );
185
186 }
187
188 public static function span( $text, $class, $attribs=array() ) {
189 return self::element( 'span', array( 'class' => $class ) + $attribs, $text );
190 }
191
192 /**
193 * Convenience function to build an HTML text input field
194 * @return string HTML
195 */
196 public static function input( $name, $size=false, $value=false, $attribs=array() ) {
197 return self::element( 'input', array(
198 'name' => $name,
199 'size' => $size,
200 'value' => $value ) + $attribs );
201 }
202
203 /**
204 * Convenience function to build an HTML password input field
205 * @return string HTML
206 */
207 public static function password( $name, $size=false, $value=false, $attribs=array() ) {
208 return self::input( $name, $size, $value, array_merge($attribs, array('type' => 'password')));
209 }
210
211 /**
212 * Internal function for use in checkboxes and radio buttons and such.
213 * @return array
214 */
215 public static function attrib( $name, $present = true ) {
216 return $present ? array( $name => $name ) : array();
217 }
218
219 /**
220 * Convenience function to build an HTML checkbox
221 * @return string HTML
222 */
223 public static function check( $name, $checked=false, $attribs=array() ) {
224 return self::element( 'input', array_merge(
225 array(
226 'name' => $name,
227 'type' => 'checkbox',
228 'value' => 1 ),
229 self::attrib( 'checked', $checked ),
230 $attribs ) );
231 }
232
233 /**
234 * Convenience function to build an HTML radio button
235 * @return string HTML
236 */
237 public static function radio( $name, $value, $checked=false, $attribs=array() ) {
238 return self::element( 'input', array(
239 'name' => $name,
240 'type' => 'radio',
241 'value' => $value ) + self::attrib( 'checked', $checked ) + $attribs );
242 }
243
244 /**
245 * Convenience function to build an HTML form label
246 * @return string HTML
247 */
248 public static function label( $label, $id ) {
249 return self::element( 'label', array( 'for' => $id ), $label );
250 }
251
252 /**
253 * Convenience function to build an HTML text input field with a label
254 * @return string HTML
255 */
256 public static function inputLabel( $label, $name, $id, $size=false, $value=false, $attribs=array() ) {
257 return Xml::label( $label, $id ) .
258 '&nbsp;' .
259 self::input( $name, $size, $value, array( 'id' => $id ) + $attribs );
260 }
261
262 /**
263 * Convenience function to build an HTML checkbox with a label
264 * @return string HTML
265 */
266 public static function checkLabel( $label, $name, $id, $checked=false, $attribs=array() ) {
267 return self::check( $name, $checked, array( 'id' => $id ) + $attribs ) .
268 '&nbsp;' .
269 self::label( $label, $id );
270 }
271
272 /**
273 * Convenience function to build an HTML radio button with a label
274 * @return string HTML
275 */
276 public static function radioLabel( $label, $name, $value, $id, $checked=false, $attribs=array() ) {
277 return self::radio( $name, $value, $checked, array( 'id' => $id ) + $attribs ) .
278 '&nbsp;' .
279 self::label( $label, $id );
280 }
281
282 /**
283 * Convenience function to build an HTML submit button
284 * @param $value String: label text for the button
285 * @param $attribs Array: optional custom attributes
286 * @return string HTML
287 */
288 public static function submitButton( $value, $attribs=array() ) {
289 return self::element( 'input', array( 'type' => 'submit', 'value' => $value ) + $attribs );
290 }
291
292 /**
293 * Convenience function to build an HTML hidden form field.
294 * @todo Document $name parameter.
295 * @param $name FIXME
296 * @param $value String: label text for the button
297 * @param $attribs Array: optional custom attributes
298 * @return string HTML
299 */
300 public static function hidden( $name, $value, $attribs=array() ) {
301 return self::element( 'input', array(
302 'name' => $name,
303 'type' => 'hidden',
304 'value' => $value ) + $attribs );
305 }
306
307 /**
308 * Convenience function to build an HTML drop-down list item.
309 * @param $text String: text for this item
310 * @param $value String: form submission value; if empty, use text
311 * @param $selected boolean: if true, will be the default selected item
312 * @param $attribs array: optional additional HTML attributes
313 * @return string HTML
314 */
315 public static function option( $text, $value=null, $selected=false,
316 $attribs=array() ) {
317 if( !is_null( $value ) ) {
318 $attribs['value'] = $value;
319 }
320 if( $selected ) {
321 $attribs['selected'] = 'selected';
322 }
323 return self::element( 'option', $attribs, $text );
324 }
325
326 /**
327 * Returns an escaped string suitable for inclusion in a string literal
328 * for JavaScript source code.
329 * Illegal control characters are assumed not to be present.
330 *
331 * @param string $string
332 * @return string
333 */
334 public static function escapeJsString( $string ) {
335 // See ECMA 262 section 7.8.4 for string literal format
336 $pairs = array(
337 "\\" => "\\\\",
338 "\"" => "\\\"",
339 '\'' => '\\\'',
340 "\n" => "\\n",
341 "\r" => "\\r",
342
343 # To avoid closing the element or CDATA section
344 "<" => "\\x3c",
345 ">" => "\\x3e",
346
347 # To avoid any complaints about bad entity refs
348 "&" => "\\x26",
349
350 # Work around https://bugzilla.mozilla.org/show_bug.cgi?id=274152
351 # Encode certain Unicode formatting chars so affected
352 # versions of Gecko don't misinterpret our strings;
353 # this is a common problem with Farsi text.
354 "\xe2\x80\x8c" => "\\u200c", // ZERO WIDTH NON-JOINER
355 "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
356 );
357 return strtr( $string, $pairs );
358 }
359
360 /**
361 * Encode a variable of unknown type to JavaScript.
362 * Arrays are converted to JS arrays, objects are converted to JS associative
363 * arrays (objects). So cast your PHP associative arrays to objects before
364 * passing them to here.
365 */
366 public static function encodeJsVar( $value ) {
367 if ( is_bool( $value ) ) {
368 $s = $value ? 'true' : 'false';
369 } elseif ( is_null( $value ) ) {
370 $s = 'null';
371 } elseif ( is_int( $value ) ) {
372 $s = $value;
373 } elseif ( is_array( $value ) ) {
374 $s = '[';
375 foreach ( $value as $elt ) {
376 if ( $s != '[' ) {
377 $s .= ', ';
378 }
379 $s .= self::encodeJsVar( $elt );
380 }
381 $s .= ']';
382 } elseif ( is_object( $value ) ) {
383 $s = '{';
384 foreach ( (array)$value as $name => $elt ) {
385 if ( $s != '{' ) {
386 $s .= ', ';
387 }
388 $s .= '"' . self::escapeJsString( $name ) . '": ' .
389 self::encodeJsVar( $elt );
390 }
391 $s .= '}';
392 } else {
393 $s = '"' . self::escapeJsString( $value ) . '"';
394 }
395 return $s;
396 }
397
398
399 /**
400 * Check if a string is well-formed XML.
401 * Must include the surrounding tag.
402 *
403 * @param $text String: string to test.
404 * @return bool
405 *
406 * @todo Error position reporting return
407 */
408 public static function isWellFormed( $text ) {
409 $parser = xml_parser_create( "UTF-8" );
410
411 # case folding violates XML standard, turn it off
412 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
413
414 if( !xml_parse( $parser, $text, true ) ) {
415 //$err = xml_error_string( xml_get_error_code( $parser ) );
416 //$position = xml_get_current_byte_index( $parser );
417 //$fragment = $this->extractFragment( $html, $position );
418 //$this->mXmlError = "$err at byte $position:\n$fragment";
419 xml_parser_free( $parser );
420 return false;
421 }
422 xml_parser_free( $parser );
423 return true;
424 }
425
426 /**
427 * Check if a string is a well-formed XML fragment.
428 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
429 * and can use HTML named entities.
430 *
431 * @param $text String:
432 * @return bool
433 */
434 public static function isWellFormedXmlFragment( $text ) {
435 $html =
436 Sanitizer::hackDocType() .
437 '<html>' .
438 $text .
439 '</html>';
440 return Xml::isWellFormed( $html );
441 }
442
443 /**
444 * Replace " > and < with their respective HTML entities ( &quot;,
445 * &gt;, &lt;)
446 *
447 * @param $in String: text that might contain HTML tags.
448 * @return string Escaped string
449 */
450 public static function escapeTagsOnly( $in ) {
451 return str_replace(
452 array( '"', '>', '<' ),
453 array( '&quot;', '&gt;', '&lt;' ),
454 $in );
455 }
456 }
457