(bug 19195) Make user IDs more readily available with the API
[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 * @return string
39 */
40 public function getRootElement() {
41 return $this->rootElement;
42 }
43
44 /**
45 * @param $fname
46 */
47 private function run( $fname ) {
48 $parser = xml_parser_create_ns( 'UTF-8' );
49
50 // case folding violates XML standard, turn it off
51 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
52
53 xml_set_element_handler( $parser, array( $this, 'rootElementOpen' ), false );
54
55 if ( file_exists( $fname ) ) {
56 $file = fopen( $fname, "rb" );
57 if ( $file ) {
58 do {
59 $chunk = fread( $file, 32768 );
60 $ret = xml_parse( $parser, $chunk, feof( $file ) );
61 if( $ret == 0 ) {
62 // XML isn't well-formed!
63 fclose( $file );
64 xml_parser_free( $parser );
65 return;
66 }
67 } while( !feof( $file ) );
68
69 fclose( $file );
70 }
71 }
72
73 $this->wellFormed = true;
74
75 xml_parser_free( $parser );
76 }
77
78 /**
79 * @param $parser
80 * @param $name
81 * @param $attribs
82 */
83 private function rootElementOpen( $parser, $name, $attribs ) {
84 $this->rootElement = $name;
85
86 if( is_callable( $this->filterCallback ) ) {
87 xml_set_element_handler( $parser, array( $this, 'elementOpen' ), false );
88 $this->elementOpen( $parser, $name, $attribs );
89 } else {
90 // We only need the first open element
91 xml_set_element_handler( $parser, false, false );
92 }
93 }
94
95 /**
96 * @param $parser
97 * @param $name
98 * @param $attribs
99 */
100 private function elementOpen( $parser, $name, $attribs ) {
101 if( call_user_func( $this->filterCallback, $name, $attribs ) ) {
102 // Filter hit!
103 $this->filterMatch = true;
104 }
105 }
106 }