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