1<?php
2// $Header: /cvsroot/html2ps/treebuilder.class.php,v 1.17 2007/05/06 18:49:29 Konstantin Exp $
3
4if (!defined('XML_ELEMENT_NODE')) { define('XML_ELEMENT_NODE',1); };
5if (!defined('XML_TEXT_NODE')) { define('XML_TEXT_NODE',2); };
6if (!defined('XML_DOCUMENT_NODE')) { define('XML_DOCUMENT_NODE',3); };
7
8class TreeBuilder {
9  function build($xmlstring) {
10    // Detect if we're using PHP 4 (DOM XML extension)
11    // or PHP 5 (DOM extension)
12    // First uses a set of domxml_* functions,
13    // Second - object-oriented interface
14    // Third - pure PHP XML parser
15    if (function_exists('domxml_open_mem')) {
16      require_once(HTML2PS_DIR.'dom.php4.inc.php');
17      return PHP4DOMTree::from_DOMDocument(domxml_open_mem($xmlstring));
18    };
19
20    if (class_exists('DOMDocument')) {
21      require_once(HTML2PS_DIR.'dom.php5.inc.php');
22      return DOMTree::from_DOMDocument(DOMDocument::loadXML($xmlstring));
23    };
24
25    require_once(HTML2PS_DIR.'dom.activelink.inc.php');
26    if (file_exists(HTML2PS_DIR.'classes/include.php')) {
27      require_once(HTML2PS_DIR.'classes/include.php');
28      import('org.active-link.xml.XML');
29      import('org.active-link.xml.XMLDocument');
30
31      // preprocess character references
32      // literal references (actually, parser SHOULD do it itself; nevertheless, Activelink just ignores these entities)
33      $xmlstring = preg_replace("/&amp;/","&",$xmlstring);
34      $xmlstring = preg_replace("/&quot;/","\"",$xmlstring);
35      $xmlstring = preg_replace("/&lt;/","<",$xmlstring);
36      $xmlstring = preg_replace("/&gt;/",">",$xmlstring);
37
38      // in decimal form
39      while (preg_match("@&#(\d+);@",$xmlstring, $matches)) {
40        $xmlstring = preg_replace("@&#".$matches[1].";@",code_to_utf8($matches[1]),$xmlstring);
41      };
42      // in hexadecimal form
43      while (preg_match("@&#x(\d+);@i",$xmlstring, $matches)) {
44        $xmlstring = preg_replace("@&#x".$matches[1].";@i",code_to_utf8(hexdec($matches[1])),$xmlstring);
45      };
46
47      $tree = ActiveLinkDOMTree::from_XML(new XML($xmlstring));
48
49      return $tree;
50    }
51    die("None of DOM/XML, DOM or ActiveLink DOM extension found. Check your PHP configuration.");
52  }
53};
54?>