Don't look for pipes in the root node.
[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 * Will be set to true if the optional element filter returned
12 * a match at some point.
13 */
14 public $filterMatch = false;
15
16 /**
17 * Name of the document's root element, including any namespace
18 * as an expanded URL.
19 */
20 public $rootElement = '';
21
22 /**
23 * @param $file string filename
24 * @param $filterCallback callable (optional)
25 * Function to call to do additional custom validity checks from the
26 * SAX element handler event. This gives you access to the element
27 * namespace, name, and attributes, but not to text contents.
28 * Filter should return 'true' to toggle on $this->filterMatch
29 */
30 function __construct( $file, $filterCallback=null ) {
31 $this->filterCallback = $filterCallback;
32 $this->run( $file );
33 }
34
35 /**
36 * Get the root element. Simple accessor to $rootElement
37 */
38 public function getRootElement() {
39 return $this->rootElement;
40 }
41
42 private function run( $fname ) {
43 $parser = xml_parser_create_ns( 'UTF-8' );
44
45 // case folding violates XML standard, turn it off
46 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
47
48 xml_set_element_handler( $parser, array( $this, 'rootElementOpen' ), false );
49
50 $file = fopen( $fname, "rb" );
51 do {
52 $chunk = fread( $file, 32768 );
53 $ret = xml_parse( $parser, $chunk, feof( $file ) );
54 if( $ret == 0 ) {
55 // XML isn't well-formed!
56 fclose( $file );
57 xml_parser_free( $parser );
58 return;
59 }
60 } while( !feof( $file ) );
61
62 $this->wellFormed = true;
63
64 fclose( $file );
65 xml_parser_free( $parser );
66 }
67
68 private function rootElementOpen( $parser, $name, $attribs ) {
69 $this->rootElement = $name;
70
71 if( is_callable( $this->filterCallback ) ) {
72 xml_set_element_handler( $parser, array( $this, 'elementOpen' ), false );
73 $this->elementOpen( $parser, $name, $attribs );
74 } else {
75 // We only need the first open element
76 xml_set_element_handler( $parser, false, false );
77 }
78 }
79
80 private function elementOpen( $parser, $name, $attribs ) {
81 if( call_user_func( $this->filterCallback, $name, $attribs ) ) {
82 // Filter hit!
83 $this->filterMatch = true;
84 }
85 }
86 }