<?php

	require_once(dirname(__FILE__).'/_plugin.php');

	class Docx_Plugin extends Plugin
	{
		function Parse($data, $url)
		{
			// zip_open only reads from a file so we need to save the file to disk first
			$tmpfname = tempnam(TEMP_DIRECTORY, "DOCX");
			if ($tmpfname === false) {
				return '';
			}
			$save_ok = file_put_contents($tmpfname, $data);

			if (!$save_ok) {
				return false;
			}

			// Read the actual document information from the docx zip archive
			$zh = zip_open($tmpfname);
			if (!is_resource($zh)) {
				return false;
			}
			$output = '';
			while ($entry = zip_read($zh)) {
				zip_entry_open($zh, $entry);
				$filename = zip_entry_name($entry);
				if ($filename === 'word/document.xml') {
					while ($chunk = zip_entry_read($entry)) {
						$output .= $chunk;
					}
				}
				zip_entry_close($entry);
				if ($output !== '') {
					break;
				}
			}
			zip_close($zh);

			// Remove our temporary file after we are done with it
			unlink($tmpfname);

			$output = utf8_decode($output);
			$output = preg_match_all('%<w:t>(.*?)</w:t>%s', $output, $matches);

			$clean_output = implode(' ', $matches[1]);

			$this->title = basename(urldecode($url));

			// Grab any information you are interested in and keep it to return
			return $clean_output;
		}

		function Check()
		{
			$required_functions = array (
				'zip_open',
			);

			static $disabled_functions = null;

			if ($disabled_functions === null) {
				$disabled_functions = explode(',', str_replace(' ', '', ini_get('disabled_functions')));
			}

			foreach ($required_functions as $f) {
				if (!function_exists($f)) {
					$this->error = sprintf(GetLang('RequiredFunctionMissing'), $f);
					return false;
				}

				if (in_array($f, $disabled_functions)) {
					$this->error = sprintf(GetLang('RequiredFunctionDisabled'), $f);
					return false;
				}
			}

			return true;
		}
	}

	if (!function_exists('file_put_contents')) {
		function file_put_contents($filename, $data)
		{
			$fp = fopen($filename, "w+b");
			if (!$fp) {
				return false;
			}
			$bytes_written = fwrite($fp, $data, strlen($data));
			fclose($fp);
			if ($bytes_written === false) {
				return false;
			} else {
				return $bytes_written;
			}
		}
	}


?>
