* (bug 9898) Allow viewing all namespaces in Special:Newpages
[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 *
129 * @param $language The language code of the selected language
130 * @param $customisedOnly If true only languages which have some content are listed
131 * @return array of label and select
132 */
133 public static function languageSelector( $selected, $customisedOnly = true ) {
134 global $wgContLanguageCode;
135 /**
136 * Make sure the site language is in the list; a custom language code
137 * might not have a defined name...
138 */
139 $languages = Language::getLanguageNames( $customisedOnly );
140 if( !array_key_exists( $wgContLanguageCode, $languages ) ) {
141 $languages[$wgContLanguageCode] = $wgContLanguageCode;
142 }
143 ksort( $languages );
144
145 /**
146 * If a bogus value is set, default to the content language.
147 * Otherwise, no default is selected and the user ends up
148 * with an Afrikaans interface since it's first in the list.
149 */
150 $selected = isset( $languages[$selected] ) ? $selected : $wgContLanguageCode;
151 $options = "\n";
152 foreach( $languages as $code => $name ) {
153 $options .= Xml::option( "$code - $name", $code, ($code == $selected) ) . "\n";
154 }
155
156 return array(
157 Xml::label( wfMsg('yourlanguage'), 'wpUserLanguage' ),
158 Xml::tags( 'select',
159 array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ),
160 $options
161 )
162 );
163
164 }
165
166 public static function span( $text, $class, $attribs=array() ) {
167 return self::element( 'span', array( 'class' => $class ) + $attribs, $text );
168 }
169
170 /**
171 * Convenience function to build an HTML text input field
172 * @return string HTML
173 */
174 public static function input( $name, $size=false, $value=false, $attribs=array() ) {
175 return self::element( 'input', array(
176 'name' => $name,
177 'size' => $size,
178 'value' => $value ) + $attribs );
179 }
180
181 /**
182 * Convenience function to build an HTML password input field
183 * @return string HTML
184 */
185 public static function password( $name, $size=false, $value=false, $attribs=array() ) {
186 return self::input( $name, $size, $value, array_merge($attribs, array('type' => 'password')));
187 }
188
189 /**
190 * Internal function for use in checkboxes and radio buttons and such.
191 * @return array
192 */
193 public static function attrib( $name, $present = true ) {
194 return $present ? array( $name => $name ) : array();
195 }
196
197 /**
198 * Convenience function to build an HTML checkbox
199 * @return string HTML
200 */
201 public static function check( $name, $checked=false, $attribs=array() ) {
202 return self::element( 'input', array_merge(
203 array(
204 'name' => $name,
205 'type' => 'checkbox',
206 'value' => 1 ),
207 self::attrib( 'checked', $checked ),
208 $attribs ) );
209 }
210
211 /**
212 * Convenience function to build an HTML radio button
213 * @return string HTML
214 */
215 public static function radio( $name, $value, $checked=false, $attribs=array() ) {
216 return self::element( 'input', array(
217 'name' => $name,
218 'type' => 'radio',
219 'value' => $value ) + self::attrib( 'checked', $checked ) + $attribs );
220 }
221
222 /**
223 * Convenience function to build an HTML form label
224 * @return string HTML
225 */
226 public static function label( $label, $id ) {
227 return self::element( 'label', array( 'for' => $id ), $label );
228 }
229
230 /**
231 * Convenience function to build an HTML text input field with a label
232 * @return string HTML
233 */
234 public static function inputLabel( $label, $name, $id, $size=false, $value=false, $attribs=array() ) {
235 return Xml::label( $label, $id ) .
236 '&nbsp;' .
237 self::input( $name, $size, $value, array( 'id' => $id ) + $attribs );
238 }
239
240 /**
241 * Convenience function to build an HTML checkbox with a label
242 * @return string HTML
243 */
244 public static function checkLabel( $label, $name, $id, $checked=false, $attribs=array() ) {
245 return self::check( $name, $checked, array( 'id' => $id ) + $attribs ) .
246 '&nbsp;' .
247 self::label( $label, $id );
248 }
249
250 /**
251 * Convenience function to build an HTML radio button with a label
252 * @return string HTML
253 */
254 public static function radioLabel( $label, $name, $value, $id, $checked=false, $attribs=array() ) {
255 return self::radio( $name, $value, $checked, array( 'id' => $id ) + $attribs ) .
256 '&nbsp;' .
257 self::label( $label, $id );
258 }
259
260 /**
261 * Convenience function to build an HTML submit button
262 * @param $value String: label text for the button
263 * @param $attribs Array: optional custom attributes
264 * @return string HTML
265 */
266 public static function submitButton( $value, $attribs=array() ) {
267 return self::element( 'input', array( 'type' => 'submit', 'value' => $value ) + $attribs );
268 }
269
270 /**
271 * Convenience function to build an HTML hidden form field.
272 * @todo Document $name parameter.
273 * @param $name FIXME
274 * @param $value String: label text for the button
275 * @param $attribs Array: optional custom attributes
276 * @return string HTML
277 */
278 public static function hidden( $name, $value, $attribs=array() ) {
279 return self::element( 'input', array(
280 'name' => $name,
281 'type' => 'hidden',
282 'value' => $value ) + $attribs );
283 }
284
285 /**
286 * Convenience function to build an HTML drop-down list item.
287 * @param $text String: text for this item
288 * @param $value String: form submission value; if empty, use text
289 * @param $selected boolean: if true, will be the default selected item
290 * @param $attribs array: optional additional HTML attributes
291 * @return string HTML
292 */
293 public static function option( $text, $value=null, $selected=false,
294 $attribs=array() ) {
295 if( !is_null( $value ) ) {
296 $attribs['value'] = $value;
297 }
298 if( $selected ) {
299 $attribs['selected'] = 'selected';
300 }
301 return self::element( 'option', $attribs, $text );
302 }
303
304 /**
305 * Returns an escaped string suitable for inclusion in a string literal
306 * for JavaScript source code.
307 * Illegal control characters are assumed not to be present.
308 *
309 * @param string $string
310 * @return string
311 */
312 public static function escapeJsString( $string ) {
313 // See ECMA 262 section 7.8.4 for string literal format
314 $pairs = array(
315 "\\" => "\\\\",
316 "\"" => "\\\"",
317 '\'' => '\\\'',
318 "\n" => "\\n",
319 "\r" => "\\r",
320
321 # To avoid closing the element or CDATA section
322 "<" => "\\x3c",
323 ">" => "\\x3e",
324
325 # To avoid any complaints about bad entity refs
326 "&" => "\\x26",
327 );
328 return strtr( $string, $pairs );
329 }
330
331 /**
332 * Encode a variable of unknown type to JavaScript.
333 * Doesn't support hashtables just yet.
334 */
335 public static function encodeJsVar( $value ) {
336 if ( is_bool( $value ) ) {
337 $s = $value ? 'true' : 'false';
338 } elseif ( is_null( $value ) ) {
339 $s = 'null';
340 } elseif ( is_int( $value ) ) {
341 $s = $value;
342 } elseif ( is_array( $value ) ) {
343 $s = '[';
344 foreach ( $value as $name => $elt ) {
345 if ( $s != '[' ) {
346 $s .= ', ';
347 }
348 $s .= self::encodeJsVar( $elt );
349 }
350 $s .= ']';
351 } else {
352 $s = '"' . self::escapeJsString( $value ) . '"';
353 }
354 return $s;
355 }
356
357
358 /**
359 * Check if a string is well-formed XML.
360 * Must include the surrounding tag.
361 *
362 * @param $text String: string to test.
363 * @return bool
364 *
365 * @todo Error position reporting return
366 */
367 public static function isWellFormed( $text ) {
368 $parser = xml_parser_create( "UTF-8" );
369
370 # case folding violates XML standard, turn it off
371 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
372
373 if( !xml_parse( $parser, $text, true ) ) {
374 //$err = xml_error_string( xml_get_error_code( $parser ) );
375 //$position = xml_get_current_byte_index( $parser );
376 //$fragment = $this->extractFragment( $html, $position );
377 //$this->mXmlError = "$err at byte $position:\n$fragment";
378 xml_parser_free( $parser );
379 return false;
380 }
381 xml_parser_free( $parser );
382 return true;
383 }
384
385 /**
386 * Check if a string is a well-formed XML fragment.
387 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
388 * and can use HTML named entities.
389 *
390 * @param $text String:
391 * @return bool
392 */
393 public static function isWellFormedXmlFragment( $text ) {
394 $html =
395 Sanitizer::hackDocType() .
396 '<html>' .
397 $text .
398 '</html>';
399 return Xml::isWellFormed( $html );
400 }
401
402 /**
403 * Replace " > and < with their respective HTML entities ( &quot;,
404 * &gt;, &lt;)
405 *
406 * @param $in String: text that might contain HTML tags.
407 * @return string Escaped string
408 */
409 public static function escapeTagsOnly( $in ) {
410 return str_replace(
411 array( '"', '>', '<' ),
412 array( '&quot;', '&gt;', '&lt;' ),
413 $in );
414 }
415 }
416 ?>