(bug 13718) Return the proper continue parameter for cmsort=timestamp
[lhc/web/wiklou.git] / includes / XmlTypeCheck.php
1 <?php
2
3 class XmlTypeCheck {
4 /**
5 * Will be set to true or false to indicate whether the file is
6 * well-formed XML. Note that this doesn't check schema validity.
7 */
8 public $wellFormed = false;
9
10 /**
11 * Name of the document's root element, including any namespace
12 * as an expanded URL.
13 */
14 public $rootElement = '';
15
16 private $softNamespaces;
17 private $namespaces = array();
18
19 /**
20 * @param $file string filename
21 * @param $softNamespaces bool
22 * If set to true, use of undeclared XML namespaces will be ignored.
23 * This matches the behavior of rsvg, but more compliant consumers
24 * such as Firefox will reject such files.
25 * Leave off for the default, stricter checks.
26 */
27 function __construct( $file, $softNamespaces=false ) {
28 $this->softNamespaces = $softNamespaces;
29 $this->run( $file );
30 }
31
32 private function run( $fname ) {
33 if( $this->softNamespaces ) {
34 $parser = xml_parser_create( 'UTF-8' );
35 } else {
36 $parser = xml_parser_create_ns( 'UTF-8' );
37 }
38
39 // case folding violates XML standard, turn it off
40 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
41
42 xml_set_element_handler( $parser, array( $this, 'elementOpen' ), false );
43
44 $file = fopen( $fname, "rb" );
45 do {
46 $chunk = fread( $file, 32768 );
47 $ret = xml_parse( $parser, $chunk, feof( $file ) );
48 if( $ret == 0 ) {
49 // XML isn't well-formed!
50 fclose( $file );
51 xml_parser_free( $parser );
52 return;
53 }
54 } while( !feof( $file ) );
55
56 $this->wellFormed = true;
57
58 fclose( $file );
59 xml_parser_free( $parser );
60 }
61
62 private function elementOpen( $parser, $name, $attribs ) {
63 if( $this->softNamespaces ) {
64 // Check namespaces manually, so expat doesn't throw
65 // errors on use of undeclared namespaces.
66 foreach( $attribs as $attrib => $val ) {
67 if( $attrib == 'xmlns' ) {
68 $this->namespaces[''] = $val;
69 } elseif( substr( $attrib, 0, strlen( 'xmlns:' ) ) == 'xmlns:' ) {
70 $this->namespaces[substr( $attrib, strlen( 'xmlns:' ) )] = $val;
71 }
72 }
73
74 if( strpos( $name, ':' ) === false ) {
75 $ns = '';
76 $subname = $name;
77 } else {
78 list( $ns, $subname ) = explode( ':', $name, 2 );
79 }
80
81 if( isset( $this->namespaces[$ns] ) ) {
82 $name = $this->namespaces[$ns] . ':' . $subname;
83 } else {
84 // Technically this is invalid for XML with Namespaces.
85 // But..... we'll just let it slide in soft mode.
86 }
87 }
88
89 // We only need the first open element
90 $this->rootElement = $name;
91 xml_set_element_handler( $parser, false, false );
92 }
93 }