<?php


class Odt2xhtml {

	/**
	 * Extract 'content.xml' from odt file (zip archive).
	 */
	public function oo_unzip($file, $path = false) {
		if (!function_exists('zip_open')) {
			throw new Exception('NO ZIP FUNCTIONS DETECTED. Do you have the PECL ZIP extensions loaded?');
		}
		if (!is_file($file)) {
			throw new Exception('Can\'t find file: '.$file);
		}
		if ($zip = zip_open($file)) {
			$content = null;
			$img = array();
			while ($zip_entry = zip_read($zip)) {
				$filename = zip_entry_name($zip_entry);
				if (zip_entry_name($zip_entry) == 'content.xml' && zip_entry_open($zip, $zip_entry, "r")) {
					$content = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
					zip_entry_close($zip_entry);
				}
				if (substr($filename, 0, strlen('Pictures/')) == 'Pictures/' && false === strpos('Object', $filename) && zip_entry_open($zip, $zip_entry, "r")) {
					$img[$filename] = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
					zip_entry_close($zip_entry);
				}
			}
			if (isset($content)) {
				if (is_array($img) && !empty($img)) {
					if (!is_dir($path.'Pictures')) {
						mkdir($path.'Pictures');
					}
					foreach ($img as $key => $val) {
						file_put_contents($path.$key, $val);
					}
				}
				return $content;
			}
		}
	}

	/**
	 * Convert xml content using xsl template file.
	 */
	public function oo_convert($xml, $xsl_file = 'template.xsl') {
		$xls = new DOMDocument;
		$xls->load($xsl_file);
		$xslt = new XSLTProcessor;
		$xslt->importStylesheet($xls);
		
		$x = preg_replace('#<draw:image xlink:href="Pictures/([a-z .A-Z_0-9]*)" (.*?)/>#es', "ODT2XHTML::makeImage('\\1')", $xml);
		
		$xml = new DOMDocument;
		$xml->loadXML($x);
		return html_entity_decode($xslt->transformToXML($xml));
	}

	public function makeImage($img) {
		return '&lt;img src="Pictures/'.$img.'" border="0" /&gt;';
	}

}
