Migrate index.xhtml and comparison.xhtml to use centralized entities for current...
[xhtml-compiler.git] / XHTMLCompiler / FilterManager.php
blobabb6ef7b44b68842dda89cdef826a480bb4c8c78
1 <?php
3 /**
4 * Manages various filters in a document, and performs text processing
5 */
6 class XHTMLCompiler_FilterManager
9 protected $preTextFilters = array();
10 protected $postTextFilters = array();
11 protected $DOMFilters = array();
12 protected $xcAttr = array();
14 protected $errors = array();
15 protected $deps = array();
17 /**
18 * Adds a pre-processing text filter to the queue.
19 * @note Filters added here are run before the document is
20 * parsed into a DOM. Suggested use is for transforming
21 * non-XML style specialized markup.
22 * @param $filter XHTMLCompiler_TextFilter
24 public function addPreTextFilter($filter) {
25 $filter = $this->loadFilter($filter, 'TextFilter');
26 $n = $filter->getName();
27 if (isset($this->preTextFilters[$n])) {
28 throw new Exception('Cannot overload pre text filter ' .
29 $filter->getName());
31 return $this->preTextFilters[$n] = $filter;
34 /**
35 * Adds a post-processing text filter to the queue.
36 * @note Filters added here are run after the document has been
37 * parsed into a DOM and then serialized back. Suggested use
38 * is for fixing cosmetic issues with the source.
39 * @warning Anything done on this step will not have its
40 * well-formedness corrected, so be careful.
41 * @param $filter XHTMLCompiler_TextFilter
43 public function addPostTextFilter($filter) {
44 $filter = $this->loadFilter($filter, 'TextFilter');
45 $n = $filter->getName();
46 if (isset($this->postTextFilters[$n])) {
47 throw new Exception('Cannot overload post text filter ' .
48 $filter->getName());
50 return $this->postTextFilters[$n] = $filter;
53 /**
54 * Adds a DOM-processing filter to the queue
55 * @param $filter XHTMLCompiler_DOMFilter
57 public function addDOMFilter($filter) {
58 $filter = $this->loadFilter($filter, 'DOMFilter');
59 $n = $filter->getName();
60 if (isset($this->DOMFilters[$n])) {
61 throw new Exception('Cannot overload DOM filter ' .
62 $filter->getName());
64 $attributes = $filter->getXCAttributesDefined();
65 foreach ($attributes as $attribute) {
66 if (isset($this->xcAttr[$attribute])) {
67 throw new Exception('Duplicate attribute definition for '.
68 'xc:' . $attribute);
70 $this->xcAttr[$attribute] = true;
72 return $this->DOMFilters[$n] = $filter;
75 /**
76 * If filter is string, load the filter based on a few guesses
77 * @param $filter String or object filter
79 protected function loadFilter($filter, $subclass) {
80 if (is_string($filter)) {
81 $class = "XHTMLCompiler_{$subclass}_$filter";
82 if (class_exists($class)) {
83 $filter = new $class;
84 } elseif (class_exists($filter)) {
85 $filter = new $filter;
86 } else {
87 require "$subclass/$filter.php";
88 $filter = new $class;
91 return $filter;
94 /** Returns the dependency array accumulated from the filter run */
95 public function getDeps() {return $this->deps;}
97 /** Adds a file to the dependency list */
98 public function addDependency($filename) {
99 $this->deps[$filename] = filemtime($filename);
103 * Accepts a page's text and processes it.
104 * @param $text String text to be processed
105 * @param $page XHTMLCompiler_Page representing currently processed page
107 public function process($text, $page) {
109 // do pre-text processing
110 foreach ($this->preTextFilters as $filter) {
111 $text = $filter->process($text, $page, $this);
114 // setup XML catalog to improve speed
115 $catalog = str_replace(array(' ', '\\'), array('%20', '/'),
116 dirname(__FILE__)) . '/../catalog/catalog.xml';
117 if ($catalog[1] == ':') $catalog = substr($catalog, 2); // remove drive
118 putenv('XML_CATALOG_FILES=' . $catalog);
120 // configure DOMDocument
121 $dom = new DOMDocument();
122 $dom->preserveWhiteSpace = false;
123 $dom->formatOutput = true;
124 $dom->resolveExternals = true;
126 // todo: somehow, collect information on which entity files
127 // are being added to the document, and add to xc-deps.
128 $dom->substituteEntities = true; // allows for custom entities too!
130 $dom->loadXML($text);
132 set_error_handler(array($this, 'muteErrorHandler'));
133 $dom->validate();
134 restore_error_handler();
136 $dom->encoding = 'UTF-8'; // override document encoding
138 // XInclude
139 // todo:
140 // * factor into a DOMFilter
141 // * add xincludes to the dependency list
142 $xpath = new DOMXPath($dom);
143 $xpath->registerNamespace('xi', $ns = 'http://www.w3.org/2001/XInclude');
144 $nodes = $xpath->query('//xi:include');
145 foreach ($nodes as $node) {
146 if (! $node instanceof DOMElement) continue;
147 if (! $filename = $node->getAttribute('href')) continue;
148 // doesn't handle second-level includes
149 $this->addDependency($filename);
151 // perform includes (we might need to loop to handle nested includes)
152 $dom->xinclude();
154 // run DOM filters
155 foreach ($this->DOMFilters as $filter) {
156 $filter->setup($dom);
157 $filter->process($dom, $page, $this);
160 // translate back to text
161 $text = $dom->saveXML();
163 // remove all non-default namespace declarations
164 $text = preg_replace('/ xmlns:.+?=".+?"/', '', $text);
165 foreach ($this->postTextFilters as $filter) {
166 $text = $filter->process($text, $page, $this);
169 // okay, now finally do validation, and let the errors get
170 // spit out if there are some
171 // collect parse errors
172 set_error_handler(array($this, 'validationErrorHandler'));
173 $dom->loadXML($text);
174 $status = $dom->validate();
175 restore_error_handler();
177 if (!$status || !empty($this->errors)) {
178 $body = $dom->getElementsByTagName('body')->item(0);
179 if (!$body) {
180 $dom->appendChild($html = $dom->createElement('html'));
181 $html->appendChild($body = $dom->createElement('body'));
183 $warning = $dom->createElement('div');
184 $warning->setAttribute('class', 'warning');
185 $warning->appendChild($dom->createElement('h2', 'Warning: Errors'));
186 $warning->appendChild($dom->createElement('p', 'This document has validation errors:'));
187 $list = $dom->createElement('ul');
188 foreach ($this->errors as $error) {
189 // strip-tags removes HTML tags to make the plaintext output
190 // more friendly, IS NOT for security reasons
191 $list->appendChild($dom->createElement('li', strip_tags($error)));
193 $warning->appendChild($list);
194 $body->insertBefore($warning, $body->childNodes->item(0));
195 $text = $dom->saveXML();
198 // scrub out XML declaration for Internet Explorer
199 $text = str_replace('<?xml version="1.0" encoding="UTF-8"?>'."\n", '', $text);
201 // scrub out custom DTD additions
202 $text = preg_replace('/(<!DOCTYPE[^>]*?) ?\[[^\]]+\]/', '\1', $text);
204 return $text;
208 * Temporary error handler to use when validating a document
210 public function validationErrorHandler($n, $text) {
211 $this->errors[] = $text;
215 * Handler that mutes all errors
217 public function muteErrorHandler($n, $t) {}