<?php
/**
* ACS - Ultimate Script for Import/Export from many formats (csv,html,xml,array,mysql db,pdf etc.)
* File: ACS.php
* Author: Pritesh Gupta
* Version: 1.2
* Date: 11-Jul-2013
* Copyright (c) 2013 Pritesh Gupta. All Rights Reserved.

/* ABOUT THIS FILE:
   -------------------------------------------------------------------------

   -------------------------------------------------------------------------
*/
error_reporting(0);

/* Uncomment the below lines to work with login management.*/
/*
session_start();
if(!isset($_SESSION['username']))
{
	header("Location:../../login.php");
}*/

require_once('DBModel.php');
class ACS 
{
	/********************* Debugging variables - use these variables to debug application ********************************/
	public $error;                     // Display any error occured in conversion   
	public $messages="";				  // Display all messages at various steps for processing conversion 
	public $inputDataArray=array();       // Display the input data as array generated by input format
	public $formattedDataArray=array();	  // Display the formatted data as array after processing the input data
	
	/********************* File related variables - use this for various file operations *********************************/
	public $fileOutputMode="browser";     // if fileOutputMode="browser", then it will ask for download else it will save
	public $checkFileName=true;           // If true then it checks for illegal character in file name
	public $checkFileNameCharacters=true; // If true then it checks for no. of character in file name, should be less than 255
	public $replaceOlderFile=false;       // If true then it will replace the older file if present at same location
	public $uploadedFileName="";          // Name of new uploaded file 
	public $fileUploadPath="../upload/";  // Path of the uploaded file
	public $maxSize=100000;               // Max size of file allowed for file upload
	public $fileSavePath="../saved/";     // Default path for saving generated file 

	public $pdfFontName="helvetica";      // font name for pdf
	public $pdfFontSize="8";              // font size for pdf
	public $pdfFontWeight="B";            // font weight for pdf
	public $pdfAuthorName="Author Name";  // Author name for pdf
	public $pdfSubject="PDF Subject Name";// Subject name for pdf	

	public $excelFormat="2007";           // Set format of excel generate (.xlsx or .xls)
	
	public $user_name="root";	           // Username for the database
	public $password="";              	   // Password for database
	public $host_name="localhost";         // hostname/server for database
	public $db_name="acs";                 // Database name
	public $dbTableName="";                // Database table name
	public $columns=array();               // Column names for the database table name
	
	private $db;						   // Internally used db object	
	public $isFirstRowHeader=false;
	public $delimiter=",";                 // Delimiter to be used in handling csv files, default is ','
	public $enclosure='"';                 // Enclosure to be used in handling csv files, default is '"' 
	
	public $isFile=false;                // Whether the supplied xml or html source is file or not
	public $useFirstRowAsTag=false;
	public $outputHTML="";               // Display html table generated  
	public $tableCssClass="tblCss";      // css class for the html table
	public $trCssClass="trCss";          // css class for the html table row (tr)   
	public $htmlTableStyle="";           // css style for the html table
	public $htmlTRStyle="";              // css style for the html table row (tr)
	public $htmlTDStyle="";				 // css style for the html table col (td)
	
	public $outputXML="";                // Display xml table generated  
	public $rootElement="root";          // Root Element for the xml
	public $encoding="utf-8";            // Encoding for the xml file
	public $rowTagName="";               // If this is set to some valid xml tag name then generated xml will contain this tagname after each subarray of two dimensional array
	
	public $logusername="demo";          // Set this to check the login username or else you can use database checking
	public $logpassword="demo";          // Set this to check the login password or else you can use database checking
	
/*	Version 1.1 New Variables            */
	public $append=false;                //If true, then will append in the existing file rather than creating a new one(you must set $existingFilePath variable to the location of the existing file)
	public $existingFilePath;           // Complete path of existing file including name to use in append operation
	 function __construct() {
		 $this->db=new DBModel();
		 $this->db->dbConnect($this->host_name,$this->user_name,$this->password,$this->db_name);
   }
   /**
	 * Main Convert function - It converts a given format ($from) to a specified format ($to).
	 *
	 * @param   string   $from              The name of the format, that needs to be converted 
	 * @param   string   $from              The name of the format, to which given format($from) needs to be converted. 
	 * @param   string   $inputSource       The name of the input file which needs to be converted.
	 * @param   string   $from              The name of the output file after conversion.
	 *
 	 */
	function convert($from,$to,$inputSource="",$outputFileName="")
	{
		if(!$this->checkValidImportOptions($from))
		{
			$this->error="Please select valid import options. See documentation for valid options";
			return false;
		}
		if(!$this->checkValidExportOptions($to))
		{
			$this->error="Please select valid export options. See documentation for valid options";
			return false;
		}		

		$this->inputDataArray=$this->getInputData($from,$inputSource,$outputFileName);
		$this->formattedDataArray=$this->formatInputData($to,$this->inputDataArray);

		if($this->processOutput($to,$this->formattedDataArray,$outputFileName))
		{
			$this->messages.=" Operation done successfully";
			return true;
		}
		else
		{
			$this->messages.=" Error in operation. Please see error: ". $this->error;
			return false;
		}		
	}
	
   /**
	 * Insert the data from two dimensional associative array to database using insert batch operation. Returns true 
	 * if operation performed successfully
	 * 
	 * @param   array     $data             	Associative array with key as column name and value as table values.
	 *
	 */	
	public function arrayToDB($data)
	{
		if(!is_array($data))
		{
			$this->error="Please provide valid input. ";
			return false;
		}
		$this->db->dbInsertBatch($this->dbTableName,$data);
		if($this->db->rows_affected>0)
		{
			$this->messages.=" Database insert operation done successfully";
			return true;
		}
		else 
		{
			$this->error=$this->db->error_info;
			return false;	
		}
		return false;
	}
	
   /**
	 * Generates the xml as output from the array provided. Returns true if operation performed successfully else return false
	 * 
	 * @param   array     $xmlArray             	Associative array with key as column name and value as table values.
	 * @param   string    $outputFileName           Output xml file name
	 *
	 */
	public function arrayToXML($xmlArray,$outputFileName="file.xml")
	{
		if(!is_array($xmlArray))
		{
			$this->error="Please provide valid input. ";
			return false;
		}
		$xmlObject = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"$this->encoding\" ?><$this->rootElement></$this->rootElement>");
		$this->generateXML($xmlArray,$xmlObject,$this->rootElement);
		if($this->fileOutputMode=="browser")
			$this->outputXML=$xmlObject->asXML();
		else
		{
			if($this->fileSavePath&&!is_dir($this->fileSavePath))
				mkdir($this->fileSavePath);	
			$xmlObject->asXML($this->fileSavePath.$outputFileName);
		}
		return true;
	}
	
   /**
	 * Generates the html table as output from the array provided.
	 * 
	 * @param   array     $htmlArray             	Associative array with key as column name and value as table values.
	 * @param   array     $outputFileName           Output file name
	 * @param   bool      $isCalledFromPDF          This function is used internally in arrayToPDF() also, to check whether it is called directly 			                                                    or using the pdf function 
	 
	 *
	 */	
	function arrayToHTML($htmlArray,$outputFileName="file.html",$isCalledFromPDF=false)
	{
		if(!is_array($htmlArray))
		{
			$this->error="Please provide valid input. ";
			return false;
		}
		$table_output='<table class="'.$this->tableCssClass.'" style="'.$this->htmlTableStyle.'">';
		$table_head="";
		if($this->useFirstRowAsTag==true)
			$table_head="<thead>";
		$table_body='<tbody>';
		$loop_count=0;
		
		foreach($htmlArray as $k=>$v)
		{
			if($this->useFirstRowAsTag==true&&$loop_count==0)
				$table_head.='<tr class="'.$this->trCssClass.'" style="'.$this->htmlTRStyle.'" id="row_'.$loop_count.'">';
			else
				$table_body.='<tr class="'.$this->trCssClass.'" style="'.$this->htmlTRStyle.'" id="row_'.$loop_count.'">';	
										
			foreach($v as $col=>$row)
			{	
				if($this->useFirstRowAsTag==true&&$loop_count==0)
					$table_head.='<th style="'.$this->htmlTDStyle.'">'.$row.'</th>';	
				else				
					$table_body.='<td style="'.$this->htmlTDStyle.'">'.$row.'</td>';	
			}
			$table_body.='</tr>';
			if($this->useFirstRowAsTag==true&&$loop_count==0)
				$table_body.='</tr></thead>';
				
			$loop_count++;
		}		
		
		$table_body.='</tbody>';
		$table_output=$table_output.$table_head.$table_body.'</table>';
		$this->outputHTML=$table_output;
		if($this->fileOutputMode=="save"&&!$isCalledFromPDF)
		{
			if($this->fileSavePath&&!is_dir($this->fileSavePath))
				mkdir($this->fileSavePath);	
			$fp = fopen($this->fileSavePath.$outputFileName, "w+"); 
			fwrite($fp, $this->outputHTML); 
			fclose($fp);  
		}
		
		return true;
	}

   /**
	 * Generates the pdf as output from the array provided. Returns true if operation performed successfully else return false
	 * 
	 * @param   array     $pdfArray             	Associative array with key as column name and value as table values.
	 * @param   string    $outputFileName           Output pdf file name
	 *
	 */	
	
	function arrayToPDF($pdfArray,$outputFileName="file.pdf")
	{
		if(!is_array($pdfArray))
		{
			$this->error="Please provide valid input. ";
			return false;
		}
		
		require_once(dirname(__FILE__) ."/library/tcpdf/tcpdf.php"); 
		$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
		$pdf->SetCreator(PDF_CREATOR);
		$pdf->SetFont($this->pdfFontName, $this->pdfFontWeight, $this->pdfFontSize, '', 'false');
		$pdf->SetAuthor($this->pdfAuthorName);
		$pdf->SetSubject($this->pdfSubject);
		$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
		$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
		$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
		if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
			require_once(dirname(__FILE__).'/lang/eng.php');
			$pdf->setLanguageArray($l);
		}
		$pdf->AddPage();
		$this->arrayToHTML($pdfArray,"file.html",true);
		$pdf->writeHTML($this->outputHTML, true, false, true, false, '');    
		if($this->fileOutputMode=="browser")
			$pdf->Output($outputFileName, 'I');
		else
		{
			if($this->fileSavePath&&!is_dir($this->fileSavePath))
				mkdir($this->fileSavePath);		
			$pdf->Output($this->fileSavePath.$outputFileName, 'F');
		}
		return true;	
	}
	
   /**
	 * Generates the excel file as output from the array provided. 
	 * 
	 * @param   array     $excelArray             	Associative array with key as column name and value as table values.
	 * @param   string    $outputFileName           Output excel file name
	 *
	 */	
	
	function arrayToExcel($excelArray,$outputFileName="file.xlsx")
	{
		if(!is_array($excelArray))
		{
			$this->error="Please provide valid input. ";
			return false;
		}
		if($this->append&&!isset($this->existingFilePath))
		{
			$this->error="Please provide existing file path, you want to append data ";
			return false;			
		}
		if(empty($outputFileName))
		{
			if($this->excelFormat=="2007")
				$outputFileName="file.xlsx";
			else
				$outputFileName="file.xls";
		}
		require_once(dirname(__FILE__) ."/library/PHPExcel/PHPExcel.php");
		
		if($this->append)
		{
			require_once (dirname(__FILE__) ."/library/PHPExcel/PHPExcel/IOFactory.php");
			if (!file_exists($this->existingFilePath)) 
			{
				$this->error="Could not open " . $this->existingFilePath . " for reading! File does not exist.";
				return false;	
			 }
			$objPHPExcel = PHPExcel_IOFactory::load($this->existingFilePath);
			
		}
		else
		{
			$objPHPExcel = new PHPExcel();
		}
		$objPHPExcel->setActiveSheetIndex(0);
		
		$cells=array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
		$colCount=1;
		
		if($this->append)
			$colCount=$objPHPExcel->getActiveSheet()->getHighestRow()+1;
			
		foreach($excelArray as $rows)
		{
			$cellLoop=0;
			foreach($rows as $row)
			{
				$objPHPExcel->getActiveSheet()->setCellValue($cells[$cellLoop].$colCount, $row);	
				$cellLoop++;
			}
			$colCount++;	
		}
		if($this->excelFormat=="2007")
		{
			$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');			
		}
		else
		{
			$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');			
		}
		if($this->append)
		{
			$objWriter->save($this->existingFilePath);
		}
		else
		{
			if($this->fileOutputMode=="browser")
			{
				if($this->excelFormat=="2007")
					header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
				else			
					header('Content-type: application/vnd.ms-excel');
	
				header('Content-Disposition: attachment; filename="'.$outputFileName.'"');
				$objWriter->save('php://output');
				die();
			}
			else
			{
				if($this->fileSavePath&&!is_dir($this->fileSavePath))
					mkdir($this->fileSavePath);
				$objWriter->save($this->fileSavePath.$outputFileName);
			}
		}
		
		return true;		
	}
	
   /**
	 * Generates the csv file as output from the array provided. 
	 * Returns true if operation performed successfully else return false.
	 * 
	 * @param   array     $csvArray             	Associative array with key as column name and value as table values.
	 * @param   string    $outputFileName           Output csv file name
	 *
	 */	
	 function arrayToCSV($csvArray,$fileName="file.csv")
	{
		if(!is_array($csvArray))
		{
			$this->error="Please provide valid input. ";
			return false;
		}		
		if(!$fileName)
		{
			$this->error="Please provide the csv file name";
			return false;
		}
		if($this->append&&!isset($this->existingFilePath))
		{
			$this->error="Please provide existing file path, you want to append data ";
			return false;			
		}
		$list = $csvArray;	
		if($this->fileSavePath&&!is_dir($this->fileSavePath))
			mkdir($this->fileSavePath);
		
		if($this->append)	
			$fp = fopen($this->existingFilePath, 'a+');
		else	
			$fp = fopen($this->fileSavePath.$fileName, 'w');
		
		foreach ($list as $fields) {
			fputcsv($fp, $fields,$this->delimiter,$this->enclosure);
		}
		
		if($this->fileOutputMode=='browser')
		{
			header("Content-type: application/csv");
			header("Content-Disposition: attachment; filename=".$fileName);
			header("Pragma: no-cache");		
			readfile($this->fileSavePath.$fileName);
			die();//to prevent page output
		}
		
		fclose($fp);
		return true;
	}
	
   /**
	 * Read an excel file and return content as array
	 * @param   string  $fileName            excel file name
	 *
	 * return   array                        return array 
	 */
	
	function excelToArray($fileName)
	{
		if(!$fileName)
		{
			$this->error="Please provide the excel file name";
			return false;
		}
		require_once(dirname(__FILE__)."/library/PHPExcel/PHPExcel/IOFactory.php");
		$objPHPExcel = PHPExcel_IOFactory::load($fileName);
		return $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
	}
	
   /**
	 * Read an xml file/xml and return content as array
	 * @param   string  $xmlSource            xml as string or xml file name
	 *
	 * return   array                        return array 
	 */
	
	function xmlToArray($xmlSource) {
			if($this->isFile)
				$xml = file_get_contents($xmlSource);
			else
				$xml=$xmlSource;
				
 			$xmlObject = new SimpleXMLElement($xml);
			return @json_decode(@json_encode($xmlObject),1);

	}

   /**
	 * Read a CSV File and return content as an array.
	 * @param   string $fileName       				 Path of file with file name (default is 'file.csv')
	 *
	 * return   array                                return content array
	 */
	 function csvToArray($fileName) { 
		 if(!$fileName)
		{
			$this->error="Please provide the csv file name";
			return false;
		}
		$csvArray=array();
        if (($handle = fopen($fileName, "r")) !== FALSE) { 
            $arrayIndex1 = 0; 
            while (($lineArray = fgetcsv($handle, 0, $this->delimiter)) !== FALSE) { 
                for ($arrayIndex2=0; $arrayIndex2<count($lineArray); $arrayIndex2++) { 
                    $csvArray[$arrayIndex1][$arrayIndex2] = $lineArray[$arrayIndex2]; 
                } 
                $arrayIndex1++; 
            } 
            fclose($handle); 
        } 
        return $csvArray; 
    } 
	
   /**
	 * Read an html file/html and return content as array
	 * @param   string  $html               	 html as string or xml file name
	 *
	 * return   array                        	 return array 
	 */
	
	function htmlToArray($htmlContent)
	{
		$dom = new DOMDocument();
		if($this->isFile)
			$htmlContent = file_get_contents($htmlContent);  			
		
		$html = $dom->loadHTML($htmlContent);  
		$dom->preserveWhiteSpace = false;   
		$tables = $dom->getElementsByTagName('table');   
		$rows = $tables->item(0)->getElementsByTagName('tr');   
		$cols = $rows->item(0)->getElementsByTagName('th');   
		$row_headers = NULL;
		foreach ($cols as $node) {
			$row_headers[] = $node->nodeValue;
		}   
		$data = array();
		$rows = $tables->item(0)->getElementsByTagName('tr');   
		foreach ($rows as $row)   
		{   
			$cols = $row->getElementsByTagName('td');   
			$row = array();
			$loop=0;
			foreach ($cols as $node) {
				if($row_headers==NULL)
					$row[] = $node->nodeValue;
				else
					$row[$row_headers[$loop]] = $node->nodeValue;
				$loop++;
			}   
			$data[] = $row;
		} 
		
		return $data;
	}
	
   /**
	 * Retrives all the tables from database
	 *
	 * return   array             table names in array
	 */	
	
	function getDBTables()
	{		
		$tables=$this->db->dbGetTableName();
		$dbtables=array();
		foreach($tables as $table)
		{
			$dbtables[]=$table ["Tables_in_".$this->db_name];
		}
		return $dbtables;
	}
	
   /**
	 * Retrives the column names from a given table
	 * @param   string  $table    The name of the table to get columns.
	 *
	 * return   array             column name in array
	 */
	
	function getDBTableColumns($dbTableName)
	{
		return $this->db->dbGetColumnName($dbTableName);
	}
	
	function fileUpload($fileObject,$fileUploadPath="",$maxSize=100000,$allowedFileTypes=array())
	{
		if($this->checkValidFileUpload($fileObject,$fileUploadPath,$maxSize,$allowedFileTypes))
		{			
			if(!is_dir($fileUploadPath)&&$fileUploadPath)
			{			
				mkdir($fileUploadPath);         
			} 
			if(!$this->uploadedFileName)
				$this->uploadedFileName=$fileUploadPath. $fileObject["name"];
			if(move_uploaded_file($fileObject["tmp_name"],$this->uploadedFileName))
			{
				$this->messages="File uploaded successfully.";
				return true;
			}
			else
			{
				$this->error="Some error occured in file upload. Please check error. Error code: ".$fileObject['error'] ;
				return false;
			}
		}
		
		return false;		
	}
/*----------------------------------------------------------- Internal Functions --------------------------------------*/	

	private function getInputData($from,$inputSource="",$outputFileName="")
	{
		$data=array();
		switch($from)
		{
			case "db":    $data=$this->db->dbSelect($this->dbTableName,$this->columns); break;
			case "excel": $data=$this->excelToArray($inputSource); break;
			case "html":  $data=$this->htmlToArray($inputSource); break;
			case "xml":   $data=$this->xmlToArray($inputSource); break;
			case "csv":   $data=$this->csvToArray($inputSource); break;
			case "sql":   $data=$this->db->dbExecuteQuery($inputSource); break;
			default:      $this->error="Please enter valid format"; break;
			
		}		
		$this->messages.=" Data exported successfully";
		return $data;
	}
	
	private function formatInputData($type,$content)
	{
		$rows=0;
		$startRow=0;
		$data=array();
		
		if($this->isFirstRowHeader)
			$startRow=1;
		
		$content=$this->array_values_recursive($content);		
		$content=$this->getTwoDimensionalArray($content);
		
		if(count($this->columns)==0)
		{
			$this->columns=$this->getColumns($content,$type);
		}

		for($rows=$startRow;$rows<count($content);$rows++)
		{
			for($csvColLoop=0;$csvColLoop<count($this->columns);$csvColLoop++)
			{
				$array[$this->columns[$csvColLoop]]=$content[$rows][$csvColLoop];
			}
			if($this->rowTagName&&$to='xml')
				$data[][$this->rowTagName]=$array;
			else	
				$data[]=$array;
		}
		return $data;
	}
	
	function array_values_recursive( $array ) {
		$array = array_values( $array );
		for ( $loop = 0; $loop < count( $array ); $loop++ ) {
			$element = $array[$loop];
			if ( is_array( $element ) ) {
				$array[$loop] = $this->array_values_recursive( $element );
			}
		}
		return $array;
	}  
	
	function getColumnName($table)
	{
		return $this->db->dbGetColumnName($table);
	}
	
	private function checkValidFileUpload($fileObject,$fileUploadPath,$maxSize,$allowedFileTypes)
	{
		if(count($allowedFileTypes)>0)
		{
			$fileExtensionLowerCase = strtolower($this->getFileExtension($fileObject['name']));
			$fileExtensionUpperCase = strtoupper($this->getFileExtension($fileObject['name']));
			if(!in_array($fileExtensionLowerCase,$allowedFileTypes)&&!in_array($fileExtensionUpperCase,$allowedFileTypes))
			{
				$this->error="Invalid file type";
				return false;
			}
		}
		
		if($fileObject["size"]==0)
		 {
			$this->error="File size is 0 bytes. Please upload a valid file";
			return false;
		 }
		
		if($fileObject["size"]>$maxSize)
		 {
			$this->error="File size is greater than max. file size allowed";
			return false;
		 }
		 
		 if($fileObject["size"]>$this->getBytes(ini_get('upload_max_filesize')))
		 {
			$this->error="File size is greater than max. file size allowed in INI File";
			return false;
		 }
		 
		if ($fileObject["error"] > 0)
		{
		  $this->error="There is some error occured. Please check error. Error code: ".$fileObject["error"];
		  return false;
		}
		
		if (file_exists($fileUploadPath. $fileObject["name"])&&!$this->replaceOlderFile)
		{
		  $this->error=$fileObject["name"] . " already exists. ";
		  return false;
		}
		
		if(!preg_match("`^[-0-9A-Z_\. ]+$`i",$fileObject["name"])&&$this->checkFileName)
		{
			$this->error=$fileObject["name"]." contains illegal character in name.";
			return false;
		}
		
		if(!mb_strlen($fileObject["name"],"UTF-8") > 225&&$this->checkFileNameCharacters)
		{
			$this->error=$fileObject["name"]." must be less than 225 characters";
			return false;
		}				
		
		return true;
	}
	private function getFileExtension($fileName)
	{
		return pathinfo($fileName, PATHINFO_EXTENSION);
	}
	
	private function getBytes ($sizeStr)
	{
		switch (substr ($sizeStr, -1))
		{
			case 'M': case 'm': return (int)$sizeStr * 1048576;
			case 'K': case 'k': return (int)$sizeStr * 1024;
			case 'G': case 'g': return (int)$sizeStr * 1073741824;
			default: return $sizeStr;
		}
	}
	private function generateXML($xmlArray, &$xmlObject,$rootElement="root") {
		foreach($xmlArray as $key => $value) {
			if(is_array($value)) {
				if(!is_numeric($key)){
					$subnode = $xmlObject->addChild("$key");
					$this->generateXML($value, $subnode,$rootElement);
				}
				else{
					$this->generateXML($value, $xmlObject,$rootElement);
				}
			}
			else {
				 if ( is_numeric( $key ) ) {
            	    	$key = $rootElement;
            		}
				$xmlObject->addChild("$key","$value");
			}
		}
	}
	private function checkValidExportOptions($to)
	{
		switch($to)
		{
			case "db": return true;
			case "html": return true;
			case "xml": return true;
			case "array": return true;			
			case "excel": return true;
			case "csv": return true;	
			case "pdf": return true;															
		}
		return false;
		
	}
	
	private function checkValidImportOptions($from)
	{
		switch($from)
		{
			case "db": return true;
			case "html": return true;
			case "xml": return true;
			case "array": return true;
			case "excel": return true;																
			case "csv": return true;
			case "sql": return true;																			
		}
		return false;
		
	}
	
	private function processOutput($to,$data,$outputFileName="")
	{
		switch($to)
		{
			case "db":    return $this->arrayToDB($data);
			case "xml":   return  $this->arrayToXML($data,$outputFileName);
			case "html":  return $this->arrayToHTML($data,$outputFileName);
			case "pdf":   return $this->arrayToPDF($data,$outputFileName);
			case "excel": return $this->arrayToExcel($data,$outputFileName);
			case "csv":   return $this->arrayToCSV($data,$outputFileName);
		}
		return false;
	}
	private function getColumns($content,$type)
	{
		foreach($content[0] as $columns)
			{
				if(is_array($columns))
				{
					return $this->getColumns($content[0]);
				}
				
				if($type=="xml")
					$cols[]=str_replace(" ","-",trim($columns));
				else	
					$cols[]=$columns;
			}
			return $cols;
	}
	
	private function isMulti($array) 
	{
    	return (count($array) != count($array, COUNT_RECURSIVE));
	} 
	
	private function getTwoDimensionalArray($content)
	{
		if($this->isMulti($content[0]))
		{
			$content=$content[0];
			return $this->getTwoDimensionalArray($content);
		}
		else
		{
			return $content;
		}
	}
	
}//end of class
?>