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