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