MDL-27120 backup: fixed docblock and code cleanup
[moodle.git] / backup / util / xml / parser / progressive_parser.class.php
CommitLineData
be866f9d
EL
1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * @package moodlecore
20 * @subpackage backup-xml
21 * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25/**
26 * Class implementing one SAX progressive push parser.
27 *
28 * SAX parser able to process XML content from files/variables. It supports
29 * attributes and case folding and works only with UTF-8 content. It's one
30 * progressive push parser because, intead of loading big crunchs of information
31 * in memory, it "publishes" (pushes) small information in a "propietary array format" througt
32 * the corresponding @progressive_parser_procesor, that will be the responsibe for
33 * returning information into handy formats to higher levels.
34 *
35 * Note that, while this progressive parser is able to process any XML file, it is
36 * 100% progressive so it publishes the information in the original order it's parsed (that's
37 * the expected behaviour) so information belonging to the same path can be returned in
38 * different chunks if there are inner levels/paths in the middle. Be warned!
39 *
40 * The "propietary array format" that the parser publishes to the @progressive_parser_procesor
41 * is this:
42 * array (
43 * 'path' => path where the tags belong to,
44 * 'level'=> level (1-based) of the tags
45 * 'tags => array (
46 * 'name' => name of the tag,
47 * 'attrs'=> array( name of the attr => value of the attr),
48 * 'cdata => cdata of the tag
49 * )
50 * )
51 *
52 * TODO: Finish phpdocs
53 */
54class progressive_parser {
55
56 protected $xml_parser; // PHP's low level XML SAX parser
57 protected $file; // full path to file being progressively parsed | => mutually exclusive
58 protected $contents; // contents being progressively parsed |
59 protected $procesor; // progressive_parser_procesor to be used to publish processed information
60
61 protected $level; // level of the current tag
62 protected $path; // path of the current tag
63 protected $accum; // accumulated char data of the current tag
64 protected $attrs; // attributes of the current tag
65
66 protected $topush; // array containing current level information being parsed to be "pushed"
67 protected $prevlevel; // level of the previous tag processed - to detect pushing places
68 protected $currtag; // name/value/attributes of the tag being processed
69
70 public function __construct($case_folding = false) {
71 $this->xml_parser = xml_parser_create('UTF-8');
72 xml_parser_set_option($this->xml_parser, XML_OPTION_CASE_FOLDING, $case_folding);
73 xml_set_object($this->xml_parser, $this);
74 xml_set_element_handler($this->xml_parser, array($this, 'start_tag'), array($this, 'end_tag'));
75 xml_set_character_data_handler($this->xml_parser, array($this, 'char_data'));
76
77 $this->file = null;
78 $this->contents = null;
79 $this->procesor = null;
80 $this->level = 0;
81 $this->path = '';
82 $this->accum = '';
83 $this->attrs = array();
84 $this->topush = array();
85 $this->prevlevel = 0;
86 $this->currtag = array();
87 }
88
89 /*
90 * Sets the XML file to be processed by the parser
91 */
92 public function set_file($file) {
93 if (!file_exists($file) || (!is_readable($file))) {
94 throw new progressive_parser_exception('invalid_file_to_parse');
95 }
96 $this->file = $file;
97 $this->contents = null;
98 }
99
100 /*
101 * Sets the XML contents to be processed by the parser
102 */
103 public function set_contents($contents) {
104 if (empty($contents)) {
105 throw new progressive_parser_exception('invalid_contents_to_parse');
106 }
107 $this->contents = $contents;
108 $this->file = null;
109 }
110
111 /*
112 * Define the @progressive_parser_processor in charge of processing the parsed chunks
113 */
114 public function set_processor($processor) {
115 if (!$processor instanceof progressive_parser_processor) {
116 throw new progressive_parser_exception('invalid_parser_processor');
117 }
118 $this->processor = $processor;
119 }
120
121 /*
122 * Process the XML, delegating found chunks to the @progressive_parser_processor
123 */
124 public function process() {
125 if (empty($this->processor)) {
126 throw new progressive_parser_exception('undefined_parser_processor');
127 }
128 if (empty($this->file) && empty($this->contents)) {
129 throw new progressive_parser_exception('undefined_xml_to_parse');
130 }
131 if (is_null($this->xml_parser)) {
132 throw new progressive_parser_exception('progressive_parser_already_used');
133 }
134 if ($this->file) {
135 $fh = fopen($this->file, 'r');
136 while ($buffer = fread($fh, 8192)) {
137 $this->parse($buffer, feof($fh));
138 }
139 fclose($fh);
140 } else {
141 $this->parse($this->contents, true);
142 }
143 xml_parser_free($this->xml_parser);
144 $this->xml_parser = null;
145 }
146
e521039d
EL
147 /**
148 * Provides one cross-platform dirname function for
149 * handling parser paths, see MDL-24381
150 */
151 public static function dirname($path) {
f2bfe26a 152 return str_replace('\\', '/', dirname($path));
e521039d
EL
153 }
154
be866f9d
EL
155// Protected API starts here
156
157 protected function parse($data, $eof) {
158 if (!xml_parse($this->xml_parser, $data, $eof)) {
159 throw new progressive_parser_exception(
160 'xml_parsing_error', null,
161 sprintf('XML error: %s at line %d, column %d',
162 xml_error_string(xml_get_error_code($this->xml_parser)),
163 xml_get_current_line_number($this->xml_parser),
164 xml_get_current_column_number($this->xml_parser)));
165 }
166 }
167
168 protected function publish($data) {
169 $this->processor->receive_chunk($data);
170 }
171
4c7f6ac6
EL
172 /**
173 * Inform to the processor that we have started parsing one path
174 */
175 protected function inform_start($path) {
176 $this->processor->before_path($path);
177 }
178
179 /**
180 * Inform to the processor that we have finished parsing one path
181 */
182 protected function inform_end($path) {
183 $this->processor->after_path($path);
184 }
185
be866f9d
EL
186 protected function postprocess_cdata($data) {
187 return $this->processor->process_cdata($data);
188 }
189
190 protected function start_tag($parser, $tag, $attributes) {
191
192 // Normal update of parser internals
193 $this->level++;
194 $this->path .= '/' . $tag;
195 $this->accum = '';
196 $this->attrs = !empty($attributes) ? $attributes : array();
197
4c7f6ac6
EL
198 // Inform processor we are about to start one tag
199 $this->inform_start($this->path);
200
be866f9d
EL
201 // Entering a new inner level, publish all the information available
202 if ($this->level > $this->prevlevel) {
203 if (!empty($this->currtag) && (!empty($this->currtag['attrs']) || !empty($this->currtag['cdata']))) {
5539e698
EL
204 // We always add the last not-empty repetition. Empty ones are ignored.
205 if (isset($this->topush['tags'][$this->currtag['name']]) && trim($this->currtag['cdata']) === '') {
206 // Do nothing, the tag already exists and the repetition is empty
207 } else {
208 $this->topush['tags'][$this->currtag['name']] = $this->currtag;
209 }
be866f9d
EL
210 }
211 if (!empty($this->topush['tags'])) {
212 $this->publish($this->topush);
213 }
214 $this->currtag = array();
215 $this->topush = array();
216 }
217
218 // If not set, build to push common header
219 if (empty($this->topush)) {
e521039d 220 $this->topush['path'] = progressive_parser::dirname($this->path);
be866f9d
EL
221 $this->topush['level'] = $this->level;
222 $this->topush['tags'] = array();
223 }
224
225 // Handling a new tag, create it
226 $this->currtag['name'] = $tag;
227 // And add attributes if present
228 if ($this->attrs) {
229 $this->currtag['attrs'] = $this->attrs;
230 }
231
232 // For the records
233 $this->prevlevel = $this->level;
234 }
235
236 protected function end_tag($parser, $tag) {
237
238 // Ending rencently started tag, add value to current tag
239 if ($this->level == $this->prevlevel) {
240 $this->currtag['cdata'] = $this->postprocess_cdata($this->accum);
5539e698
EL
241 // We always add the last not-empty repetition. Empty ones are ignored.
242 if (isset($this->topush['tags'][$this->currtag['name']]) && trim($this->currtag['cdata']) === '') {
243 // Do nothing, the tag already exists and the repetition is empty
244 } else {
245 $this->topush['tags'][$this->currtag['name']] = $this->currtag;
246 }
be866f9d
EL
247 $this->currtag = array();
248 }
249
250 // Leaving one level, publish all the information available
251 if ($this->level < $this->prevlevel) {
252 if (!empty($this->topush['tags'])) {
253 $this->publish($this->topush);
254 }
255 $this->currtag = array();
256 $this->topush = array();
257 }
258
259 // For the records
260 $this->prevlevel = $this->level;
261
4c7f6ac6
EL
262 // Inform processor we have finished one tag
263 $this->inform_end($this->path);
264
be866f9d
EL
265 // Normal update of parser internals
266 $this->level--;
e521039d 267 $this->path = progressive_parser::dirname($this->path);
be866f9d
EL
268 }
269
270 protected function char_data($parser, $data) {
271 $this->accum .= $data;
272 }
273}
274
275/*
276 * Exception class used by all the @progressive_parser stuff
277 */
278class progressive_parser_exception extends moodle_exception {
279
280 public function __construct($errorcode, $a=NULL, $debuginfo=null) {
281 parent::__construct($errorcode, 'error', '', $a, null, $debuginfo);
282 }
283}