<?php
/**
* (c) 2000, 2001, 2002, 2003 Remistech Sdn Bhd. All Rights Reserved.
*  Developed by John Lim
*  Licensed to Natsoft (M) Sdn Bhd to distribute and support. Refer to LICENSE document.
*/

include_once(PHPLENS_DIR.'/smarty/Smarty.class.php');

/*======================================================================*\
    Function: smarty_func_print_global -- jlim
    Purpose:  print a global
\*======================================================================*/
function phplens_func_print_global()
{
	extract(func_get_arg(0));
	print $GLOBALS[$name];
}

class CPHPLens_EditGrid  {
var $lens;

	function CPHPLens_EditGrid(&$lens) {
		$this->lens = &$lens;
	}
	
	function Assign($var)
	{
		$this->lens->_editGridVars = &$var;
	}
	
	function Fetch($file)
	{
	}
	
	function Close()
	{
	}
}

/*======================================================================*\
    Default Template Class
\*======================================================================*/
class PHPLensTemplate {
var $templateObj;
//var $lens;

	function PHPLensTemplate(&$lens)
	{
	global $PHP_SELF;
	
		$dirname = $lens->templateBaseDir;
		$this->templateObj = &new Smarty();
		$o = &$this->templateObj;
		$o->compile_check = ($lens->dynEdit != 0);
		$o->register_function('print_global','phplens_func_print_global');
		$o->assign('PHP_SELF',$PHP_SELF);
		$o->assign('_ISEDIT_','');
		if (is_array($lens->templateAssign))
		    $o->assign($lens->templateAssign);
		if ($dirname) {
			$o->compile_dir = $dirname.'/templates_c';
			$o->config_dir = $dirname.'/configs';
			$o->cache_dir = $dirname.'/cache';
			$o->template_dir = $dirname.'/templates';
		}
	}
	
	function Assign($var) // accepts array
	{
		$this->templateObj->assign($var);
	}
	
	function Fetch($file)
	{	
		return $this->templateObj->fetch($file);
	}
	
	function Close()
	{
		
		$this->templateObj->clear_all_assign();
		$this->templateObj = false;
	}
}

/*==================================================================================*\
// Export file as CSV, save to $lens->imageTmpDir (and deleted by phplens-img.php).
//
// Fetch() is called by the Layout renderer, Detail renderer, and Grid Row renderer.
//
// Fetch('L') - layout - called when time to save export file and redirect
// Fetch('D') - detail - not used - ignore
// Fetch('G') - grid - called once for every row
\*==================================================================================*/
class PHPLensExportText { 
	var $vars;
	var $quote = '"';           // character to quote data
	var $sep = ',';             // separator used
	var $escquote = '"';        // escape character for quote character
	var $replaceNewLine = " ";  // if newline detected, replace with....
	//------ private
	var $fp = false;
	var $lens;
	var $file = false;
	var $error = false;
		
	function PHPLensExportText(&$lens)
	{
		$vars = array();
		$lens->templateDetail = 'D';
		$lens->templateGrid = 'G';
		$lens->templateLayout = 'L';
		$lens->columns = 1;
		$this->lens = $lens;
	}
	
	function Assign($var)
	{
		if (is_array($var)) {
			foreach($var as $k => $v) {
				if (strlen($k) <= 2 or 
					(($k[0] != '_' or $k[strlen($k)-1] != '_') && 
					(substr($k,strlen($k)-2) != '_T')))
					$this->vars[$k] = $v;
			}
		}
	}
	
	function OpenFile()
	{
		$lens = $this->lens;
		$file = false;
		$fp = false;
		if (!empty($lens->imageTmpDir)) {
		 	$file = tempnam($lens->imageTmpDir, 'lenexp_'.$lens->id);
		 	$fp = fopen($file,'w');
		} else {
			print "<p>imageTmpDir not defined</p>";
			$this->error = true;
		}
		return array($fp,$file);
	}

	function Close()
	{
	}
	
	function ExportFile($filepath,$mime,$default_suffix)
	{
	global $PHPLENS_PATH, $PHP_SELF;
		
	 	$lens = $this->lens;
		
		// setup file name
		$name = @$lens->_export['NAME'][1];
		if (empty($name)) $name = 'exp-$ID-$DATE'.$default_suffix;
		$name = preg_replace('/\$DATE/i',date('Y-m-d'),$name);
		$name = preg_replace('/\$ID/i',$lens->id,$name);
		
		// setup url
		if (defined('PHPLENS_IMG_CODE')) $imagePage = PHPLENS_IMG_CODE;
		else $imagePage = $PHPLENS_PATH.'/'.$lens->imagePage;
		$imagePage .= "?f=".urlencode($filepath).
			'&t='.urlencode($mime).  //or text/tab-separated-values
			'&n='.urlencode($name);
		
		if (headers_sent()) {
			print "
<table border=1 bgcolor=white><tr><td>
<h1>Programmer note:</h1><h3>Please put ob_start() at the beginning of your code for <i>$PHP_SELF</i> to enable output buffering and allow redirects to the export file to work</h3
</td></tr></table>";
			$bad = 1;
		} else
			$bad = 0;
		//die();
		if ($bad or $this->error or $lens->debug>0) {
			print "<p>Export file can be downloaded here: <a href='$imagePage'>$imagePage</a></p>";
		} else
			header("Location: $imagePage");
		
		print $lens->lang->exportReturn;
	}
	
	// The list of fields is controlled by detailLens.
	// For the last object, we call 
	function Fetch($file)
	{
	static $visFields,$filepath;
		if ($file == 'L') { // export file complete at this stage, now perform redirect
		
			$this->ExportFile($filepath,'text/x-csv','.csv');
						
		 } else if ($file == 'D') { 
		 
		 	// template for Details, ignore
			
		 } else { // this part of the code is called once per line
		 
			$quote = $this->quote;
			$escquote = $this->escquote;
			$sep = $this->sep;
			$escquotequote = $escquote.$quote;
			$replaceNewLine = $this->replaceNewLine;
		
			// file created here, and deleted by phplens-img.php
			if (!$this->fp) 
				list($this->fp,$filepath) = $this->OpenFile();
		
			if (!isset($visFields)) {
				$visFields = $this->lens->GetExportNames();
				$s = '';
				$titles = $this->lens->GetExportTitles();
				
				if (0) {
					print_pre($visFields);
					print_pre($titles);			
					print_pre($this->vars);
					die();
				}
				foreach($visFields as $name) {
					if (isset($titles[$name])) $v = $titles[$name];
					else $v = $name;
					if ($escquote) $v = str_replace($quote,$escquotequote,$v);
					$v = str_replace("\n",$replaceNewLine,$v);

					//$v = strip_tags($v);
					if (strpos($v,'<') !== false && strpos($v,'>') !== false) $v = strip_tags($v);
					$s .= "$quote $v$quote$sep";
				}
		
				$outs = substr($s,0,strlen($s)-1);
				if ($this->fp !== false) fwrite($this->fp,($outs)."\n");
			}
		
			$s = '';
			
			/*
				$this->vars: The data for a row, indexed by column name in upper case
				$visFields: The list of fields to export in upper case
			*/
			$bad = false;
			foreach($visFields as $k) {
				if (!isset($this->vars[$k])) {
					$bad = true;
					break;
				}
				$v = $this->vars[$k]; // select one field from list
				if (is_numeric($v)) $s .= "$v$sep";
				else {
					if ($escquote) $v = str_replace($quote,$escquotequote,$v);
					$v = str_replace("\n",$replaceNewLine,$v);
					$v = str_replace('&nbsp;',' ',$v);
					$v = str_replace('&amp;','&',$v);
					$s .= "$quote$v$quote$sep";
				}
			}
			
			$outs = substr($s,0,strlen($s)-1);
			if (!$bad && $this->fp !== false) {
				$rez = fwrite($this->fp,strip_tags($outs)."\n");
				if ($rez == -1) {
					$this->error = true;
					print "<p>Error in writing to file $file</p>";
				}
			}
			return $outs;
		}
	}
}


/*==================================================================================*\
 Export in Excel 5.0 format, save to $lens->imageTmpDir (deleted by phplens-img.php).
\*==================================================================================*/
   
global $LENS_EXCEL;
$LENS_EXCEL = false;

class PHPLensExportExcel extends PHPLensExportText { 
	
	function PHPLensExportExcel(&$lens)
	{
	global $LENS_EXCEL;
		include_once(PHPLENS_DIR.'/phplens-excel.inc.php');

		if (empty($LENS_EXCEL)) $LENS_EXCEL = new PhpSimpleXlsGen(); 
		$this->PHPLensExportText($lens);
	}
		
	function Fetch($file)
	{
	global $LENS_EXCEL;
	static $visFields;
	
		// time to save and redirect
		if ($file == 'L') {
			$lens = $this->lens;
			if (!empty($lens->imageTmpDir)) {
			 	$file = tempnam($lens->imageTmpDir, 'lenexp_'.$lens->id);
			} else {
				print "<p>imageTmpDir not defined</p>";
				$this->error = true;
			}
			$LENS_EXCEL->End(); 
		  	$fp = fopen( $file, "wb" ); 
       		if ($fp) {
				$rez = fwrite( $fp, $LENS_EXCEL->xls_data); 
       			fclose( $fp); 
				if ($rez == -1)  {
					$this->error = true;
					print "<p>Error in writing Excel temporary file $file</p>";
				} else 
					$this->ExportFile($file,'application/x-msexcel','.xls');
			} else {
				$this->error = true;
				print "<p>Error in saving file $file</p>";
			}
			
		} else {
		
		 // display header titles
			if (!isset($visFields)) {
				$visFields = $this->lens->GetExportNames();
				$LENS_EXCEL->totalcol = sizeof($visFields);
				$titles = $this->lens->GetExportTitles();
				foreach($titles as $k) $LENS_EXCEL->InsertText($k);
			}
			
		// display 1 row of data
			foreach($visFields as $k) {
				$v = strip_tags($this->vars[$k]); // select one field from list
				$v = str_replace('&nbsp;','',trim($v));
				// match +/-number.number
				if (strlen($v) && preg_match('/^[\-\+]?[0-9]*(\.[0-9]*)?$/',trim($v))) $LENS_EXCEL->InsertNumber((double)$v);
				else {
					if (strlen($v) && $v[0] == '"' && $v[strlen($v)-1] == '"')
						$v = substr($v,1,strlen($v)-2);
					$LENS_EXCEL->InsertText($v);
				}
			}
			return '';
		} // else
	}  // Fetch()
} // end class

?>