<?php

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

class External_Ppt_Plugin extends Plugin
{
	var $binary_path = '';
	var $binary = '';

	function External_Ppt_Plugin()
	{
		if (substr(strtolower(PHP_OS), 0, 3) != 'win') {
			$this->binary = 'ppthtml';
		} else {
			$this->binary = 'ppthtml.exe';
		}
		$this->DetectPath();
	}

	function DetectPath()
	{
		$this->binary_path = Which($this->binary);
	}

	function Check()
	{
		$required_functions = array (
			'passthru',
			'unlink',
			'tempnam',
		);

		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;
			}
		}

		if ($this->binary_path == '') {
			$this->error = sprintf(GetLang('RequiredBinaryMissing'), $this->binary);
			return false;
		}

		return true;
	}

	function Parse($page, $url)
	{
		$this->DetectPath();

		// we need to save the file to disk first
		$tmpfname = tempnam(TEMP_DIRECTORY, "PPT");
		if ($tmpfname === false) {
			return '';
		}
		$save_ok = file_put_contents($tmpfname, $page);

		// Read the actual content
		ob_start();
		$command = $this->binary_path.' '.escapeshellarg($tmpfname);
		passthru($command);
		$output = ob_get_contents();
		ob_end_clean();

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

		return preg_replace('%\n[\n]+%s', '\n', strip_tags($output));
	}
}

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;
		}
	}
}

?>
