<?php
/*
/**
* CHRONOFORMS version 2.0 stable
* Copyright (c) 2006 Chrono_Man, ChronoEngine.com. All rights reserved.
* Author: Chrono_Man (ChronoEngine.com)
* See readme.html.
* Visit http://www.ChronoEngine.com for regular update and information.
**/

/* ensure that this file is not called from another file */
defined('_JEXEC') or die('Restricted access'); 

//global $mosConfig_lang, $mosConfig_absolute_path, $chronocontact_params;
// Loading of the database class and the HTML class
require_once( JApplicationHelper::getPath( 'admin_html' ) ); 
require_once( JApplicationHelper::getPath( 'class' ) );

$id 	= JRequest::getVar( 'id', '', 'get', 'int', 0 );
//$task 	= JRequest::getVar( 'task', '', 'post', 'string', '' );
$cid 	= JRequest::getVar( 'cid', '', 'post', 'array', array(0) );
if (!is_array( $cid )) {
	$cid = array(0);
}
$cid_del 	= JRequest::getVar( 'cid_del', '', 'post', 'array', array(0) );
if (!is_array( $cid_del )) {
	$cid_del = array(0);
}

// case differentiation
switch ($task) {
case "ajaxfields":
ajaxfields();
break;
	case "publish":
		publishChronoContact( $cid, 1, $option );
		break;
	case "unpublish":
		publishChronoContact( $cid, 0, $option );
		break;
	case "add":
		editChronoContact( 0, $option );
		break;
	case "edit":
		editChronoContact( $cid[0], $option );
		break;
	case "applychanges":
		saveChronoContact( $option );
		editChronoContact( $_POST['id'], $option );
		break;
	case "remove":
		removeChronoContact( $cid, $option );
		break;
	case "save":
		saveChronoContact( $option );
		break;
	case "copy":
		copyChronoContact( $cid[0], $option );
		break;
	case "cancel":
		cancelChronoContact( $option );
		break;
	case "addmenuitem":
		addmenuitem( $option );
		break;
	////////
	case "cancelview":
	case "show":
		showdataChronoContact( $cid[0], $option );
		break;
	case "viewdata":
		viewdataChronoContact( $cid[0], $option );
		break;
	case "createtable":
		maketableChronoContact( $cid[0], $option );
		break;
	case "deletetable":
		deletetableChronoContact( $cid[0], $option);
		break;
	case "finalizetable":
		finalizetableChronoContact( $option );
		break;
	case "deleterecord":
		deleterecordChronoContact( $cid, $option );
		break;
	////// backup
	case "backup":
		backupChronoContact( $cid[0], $option );
		break;
	case "restore1":
		restore1ChronoContact( $cid[0], $option );
		break;
	case "restore2":
		restore2ChronoContact( $cid[0], $option );
		break;
	case "backexcel":
		BackupExcel( $id, $option );
		break;
	case "backcsv":
		BackupCSV( $id, $option );
		break;
	////// config
	case 'config':
		showConfig( $option );
		break;
	case 'saveconfig':
		saveSettings( $option );
		break;
	case 'cancelconfig':
		cancelSettings( $option );
		break;
	case 'save_conf':
		save_conf( $option );
		break;
	case 'menu_creator':
		menu_creator( $option );
		break;
	case 'menu_save':
		menu_save( $option );
		break;
	///////////////
	default: 
		global $mainframe;
		$database =& JFactory::getDBO();
		$switch = 1;
		if(strpos("x".$task,"plugin_")){
			$directory = JPATH_SITE.'/components/com_chronocontact/plugins/';
			$results = array();
			$handler = opendir($directory);
			while ($file = readdir($handler)) {
				if ( $file != '.' && $file != '..' && substr($file, -4) == '.php' && substr($file, 0, 3) == 'cf_')
					$results[] = str_replace(".php","", $file);
			}
			closedir($handler);
			foreach($results as $result){
				if($task == 'plugin_'.$result){
					require_once(JPATH_SITE."/components/com_chronocontact/plugins/".$result.".php");
					${$result} = new $result();
					$switch = 0;
					
					$database->setQuery( "SELECT id FROM #__chrono_contact_plugins WHERE form_id='".$cid[0]."' AND name='".$result."'" );
					$id = $database->loadResult();
					$row =& JTable::getInstance('chronocontactplugins', 'Table');
					$row->load( $id );
					${$result}->show_conf($row, $id, $cid[0], $option);
					break;
				}
			}
		}
		//echo 'xxx'.$cf_joomla_registration->result_TITLE;
		if($switch == 1){
			showChronoContact( $option );
		}
		break;
}

function save_conf( $option ){

	require_once(JPATH_SITE."/components/com_chronocontact/plugins/".$_POST['name'].".php");
	${$_POST['name']} = new $_POST['name']();
	${$_POST['name']}->save_conf($option);
}
function ajaxfields(){
	global $mainframe;
	$database =& JFactory::getDBO();
	$tablename = $_POST['table'];
	$tables = array( $tablename );
	$result = $database->getTableFields( $tables );
	$table_fields = array_keys($result[$tablename]);
	echo "*#*"."yes"."#999-#";
	?>
	<select name="params[field_name]">
		<?php
		foreach($table_fields as $table_field){
		?>
			<option value="<?php echo $table_field; ?>"><?php echo $table_field; ?></option>
		<?php
		}
		?>
	</select>
	<?php
	echo "*#*";
}
// Publishing of the entries
function publishChronoContact( $cid, $publish, $option ) {
	global $mainframe;
	$database =& JFactory::getDBO();
	if (count( $cid ) < 1) {
		$action = $publish ? 'publish' : 'unpublish';
		echo "<script> alert('Select a item to ".$action."'); window.history.go(-1);</script>\n";
		exit;
	}
    $cids = implode( ',', $cid );
	//$database->setQuery( "UPDATE #__joomla_book SET published=($publish) WHERE id IN ($cids)");
	$database->setQuery( "UPDATE #__chrono_contact SET published=".$publish." WHERE id IN ($cids)");
	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit();
	}
 	if (count( $cid ) == 1) {
		$row =& JTable::getInstance('chronocontact', 'Table'); 
		$row->checkin( $cid[0] );
	}
	$mainframe->redirect( "index2.php?option=$option" );
}
// create a new entry (id = 0)
// or change entry with id = n
function editChronoContact( $id, $option ) {
	$database =& JFactory::getDBO();
	$row =& JTable::getInstance('chronocontact', 'Table'); 
	$row->load($id);
	HTML_ChronoContact::editChronoContact( $row, $option );
}
// deletion of entries
function removeChronoContact( $cid, $option ) {
	global $mainframe;
	$database =& JFactory::getDBO();
	if (!is_array( $cid ) || count( $cid ) < 1) {
		echo "<script> alert('Please select an entry to delete'); window.history.go(-1);</script>\n";
		exit;
	}
	$cids = implode( ',', $cid );
	$database->setQuery( "DELETE FROM #__chrono_contact WHERE id IN ($cids)" );
	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
	}
	$mainframe->redirect( "index2.php?option=$option" );
}
function copyChronoContact( $id , $option ) {
	global $mainframe;
	$database =& JFactory::getDBO();
	$row =& JTable::getInstance('chronocontact', 'Table'); 
	$row->load($id);
	$row->id = '';
	if (!$row->store()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	$mainframe->redirect( "index2.php?option=".$option );
}
// save entry
function saveChronoContact( $option ) {
	global $mainframe;
	$database =& JFactory::getDBO();
	$row =& JTable::getInstance('chronocontact', 'Table');
	$post = JRequest::get( 'post' , JREQUEST_ALLOWRAW );
	//$post = JRequest::getVar( 'description', '', 'post','string', _J_ALLOWRAW );
	if (!$row->bind( $post )) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	
	$params = JRequest::getVar( 'params', '', 'post', 'array', array(0) );
	if (is_array( $params )) {
		$txt = array();
		foreach ( $params as $k=>$v) {
			$txt[] = "$k=$v";
		}
		//$plugins = mosgetparam($_POST, 'plugins', array(0));
		$plugins 	= JRequest::getVar( 'plugins', '', 'post', 'array', array(0) );
		if($plugins){
			$txt[] = "plugins=".implode(",",$plugins);
		}
		$mplugins_order = JRequest::getVar( 'mplugins_order', '', 'post', 'array', array(0) );
		if($mplugins_order){
			$txt[] = "mplugins_order=".implode(",",$mplugins_order);
		}
		$row->paramsall = implode( "\n", $txt );
	}
	$row->titlesall = $_POST['titles'];
	if (!$row->store()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	$mainframe->redirect( "index2.php?option=".$option );
}
// abort the current action
function cancelChronoContact( $option ) {
	global $mainframe;
	$database =& JFactory::getDBO();
	$row =& JTable::getInstance('chronocontact', 'Table');
	$row->bind( $_POST );
	$row->checkin();
	$mainframe->redirect( "index2.php?option=$option" );
}
// list entries
function showChronoContact($option) {
	global $database,$mosConfig_absolute_path, $mainframe, $mosConfig_list_limit;
	$limit = JRequest::getVar('limit', $mainframe->getCfg('list_limit')); 
	$limitstart = JRequest::getVar('limitstart', 0);
	// count entries
	$database =& JFactory::getDBO();
	$database->setQuery( "SELECT count(*) FROM #__chrono_contact" );
	$total = $database->loadResult();
	echo $database->getErrorMsg();
	jimport('joomla.html.pagination'); 		
	$pageNav = new JPagination($total, $limitstart, $limit); 
	# main database query
	$database->setQuery( "SELECT * FROM #__chrono_contact ORDER BY id LIMIT $pageNav->limitstart,$pageNav->limit" );
	$rows = $database->loadObjectList();
	if ($database->getErrorNum()) {
		echo $database->stderr();
		return false;
	}
	HTML_ChronoContact::showChronoContact( $rows, $pageNav, $option );
}

function showConfig( $option='com_chronocontact') {
		global $database, $mainframe, $mosConfig_list_limit;

	$query = "SELECT a.id
				FROM #__components AS a
				WHERE a.name = 'Chrono Forms'";
	$database->setQuery( $query );
	$id = $database->loadResult();

	// load the row from the db table
	$row = new mosComponent( $database );
	$row->load( $id );

	// get params definitions
	$params = new mosParameters( $row->params, $mainframe->getPath( 'com_xml', $row->option ), 'component' );
	
	HTML_ChronoContact::settings( $option, $params, $id );
}

function saveSettings( $option ) {
	global $database;

	$params = mosGetParam( $_POST, 'params', '' );
	if (is_array( $params )) {
		$txt = array();
		foreach ($params as $k=>$v) {
			$txt[] = "$k=$v";
		}
		if( is_callable(array('mosParameters', 'textareaHandling'))) {
			$_POST['params'] = mosParameters::textareaHandling( $txt );
		}
		else {
			
			$total = count( $txt );
			for( $i=0; $i < $total; $i++ ) {
				if ( strstr( $txt[$i], "\n" ) ) {
					$txt[$i] = str_replace( "\n", '<br />', $txt[$i] );
				}
			}
			$_POST['params'] = implode( "\n", $txt );
	
		}
	}

	$id = mosGetParam( $_POST, 'id' );
	$row = new mosComponent( $database );
	$row->load( $id );
	if (!$row->bind( $_POST )) {
		echo "<script type=\"text/javascript\"> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

	if (!$row->check()) {
		echo "<script type=\"text/javascript\"> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	if (!$row->store()) {
		echo "<script type=\"text/javascript\"> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

	$msg = 'Settings successfully Saved';
	$mainframe->redirect( 'index2.php?option='. $option, $msg );
}
function cancelSettings( $option='com_chronocontact'){
	global $mainframe;
	$mainframe->redirect( 'index2.php?option='.$option );
}



///////////////////////////////
function showdataChronoContact($id, $option) {
	global $mainframe;	
	$database =& JFactory::getDBO();
	if(!$id){
		if(is_array(JRequest::getVar('formid', '', 'post', 'array', array(0)))){
			$id_arr = JRequest::getVar('formid', '', 'post', 'array', array(0));
			$id = $id_arr[0];
		}else{
			$id = JRequest::getVar('formid', '', 'post', 'int', 0);
		}
	}
	if(!$id){
		$id = JRequest::getVar('formid', '', 'get', 'int', 0);
	}
	$result = $database->getTableList();
	if (!in_array($mainframe->getCfg('dbprefix')."chronoforms_".$id, $result)) {
	//echo $mosConfig_dbprefix."_chronoforms_".$id;
		echo "<form action=\"index2.php\" method=\"post\" name=\"adminForm\">Table Doesn't Exist for this form, Please create a table first to store your form data
		<input type=\"hidden\" name=\"task\" value=\"\" /><input type=\"hidden\" name=\"option\" value=\"$option\" />
		</form>";
	} else {
		$limit = JRequest::getVar('limit', $mainframe->getCfg('list_limit')); 
		$limitstart = JRequest::getVar('limitstart', 0);
		// count entries
		$database->setQuery( "SELECT count(*) FROM #__chronoforms_".$id );
		$total = $database->loadResult();
		echo $database->getErrorMsg();
		jimport('joomla.html.pagination'); 		
		$pageNav = new JPagination($total, $limitstart, $limit);
		# main database query
		$database->setQuery( "SELECT * FROM #__chronoforms_".$id." ORDER BY cf_id LIMIT $pageNav->limitstart,$pageNav->limit" );
		$rows = $database->loadObjectList();
		if ($database->getErrorNum()) {
			echo $database->stderr();
			return false;
		}
		$formid = $id;
		HTML_ChronoContact::showdataChronoContact( $rows, $pageNav, $option, $formid );
	}
}
function viewdataChronoContact( $ids, $option ) {
	global $mainframe;	
	$database =& JFactory::getDBO();
	$fids = explode("_",$ids);
	$database->setQuery( "SELECT * FROM #__chronoforms_".$fids[1]." WHERE cf_id=".$fids[0] );
	$rows = $database->loadObjectList();
	$row = $rows[0];
	$tablename = $mainframe->getCfg('dbprefix')."chronoforms_".$fids[1];
	HTML_ChronoContact::viewdataChronoContact( $row, $option, $tablename, $fids[1] );
}
function maketableChronoContact( $id, $option ) {
	global $mainframe;
	
	$database =& JFactory::getDBO();
	$result = $database->getTableList();
	if (in_array($mainframe->getCfg('dbprefix')."chronoforms_".$id, $result)) {
	//echo $mosConfig_dbprefix."_chronoforms_".$id;
		//echo "A table has already been created for this form";
		HTML_ChronoContact::maketableChronoContact( $id, $option, "exists" );
	} else {
		$row =& JTable::getInstance('chronocontact', 'Table');
		$row->load( $id );
		$typelist = '	<option value="LONGTEXT">Biggest number of text - LONGTEXT</option>
						<option value="VARCHAR(255)">Small number of characters - VARCHAR(255)</option>			
						<option value="TEXT">Medium number of text - TEXT</option>			
						<option value="INT(11)">Medium number of numbers ONLY - INT(11)</option>			
						<option value="INT(22)">Long number of numbers ONLY - INT(22)</option>			
						<option value="INT(6)">Short number of numbers ONLY - INT(6)</option>			
						
					</select>';
		$htmlstring = $row->html;
		$html_message = "";
		preg_match_all('/name=("|\').*?("|\')/i', $htmlstring, $matches);
				$i = 0;
				$col_names = array();
				foreach ($matches[0] as $match)
				{
					$new_match = preg_replace('/name=("|\')/i', '', $match);
					$new_match2 = preg_replace('/("|\')/', '', $new_match);
					$name = preg_replace('/name=("|\')/', '', $new_match2);
					if ($i == 0) {
						$html_message.= "<table><table><tr height='10'><td width='30'><strong>Create column?</strong></td><td width='30'></td><td width='50' class='tablecell1'><strong>Column name</strong></td><td width='30'></td><td class='tablecell2'><strong>Column type</strong></td></tr>";
					}
					if(strpos($name, '[]')){
						$name = str_replace('[]', '', $name);
						//$implodes .= "$"."_POST['".$name."'] = implode(',', $"."_POST['".$name."']);";
					}
					if(in_array($name,$col_names)){
						continue;
					}else{
						$col_names[] = $name;
					}
					$html_message.= "<tr height='10'><td width='30'><input type='checkbox' name='cf_".$name."' id='cf_".$name."' value='1'></td><td width='30'></td><td width='50' class='tablecell1'>";
					$html_message.= $name."</td><td width='30'></td><td class='tablecell2'>";
					$html_message.= '<select name="fieldtype_'.$name.'">'.$typelist."</td></tr>";
					$i++;
				}
				$html_message.= "</table>";
				//echo $html_message ;
	
		HTML_ChronoContact::maketableChronoContact( $row, $option, $html_message );
	}
}
function finalizetableChronoContact( $option ) {
	global $mainframe;	
	$database =& JFactory::getDBO();
	$id = $_POST['formid'];
	$row =& JTable::getInstance('chronocontact', 'Table');
	$row->load( $id );
	$htmlstring = $row->html;
	preg_match_all('/name=("|\').*?("|\')/i', $htmlstring, $matches);
	$i = 1;
	$chrono_fields = array();
	$chrono_posts = "";
	$col_names = array();
	$implodes = '';
	$table_sql_body = "`cf_id` INT( 11 ) NOT NULL AUTO_INCREMENT , `uid` VARCHAR(255) NOT NULL, `recordtime` TEXT NOT NULL , `ipaddress` TEXT NOT NULL ,";
	foreach ($matches[0] as $match)
	{
		$new_match = preg_replace('/name=("|\')/i', '', $match);
		$new_match2 = preg_replace('/("|\')/', '', $new_match);
		$name = preg_replace('/name=("|\')/', '', $new_match2);
		
		if(in_array($name,$col_names)){
			continue;
		}else{
			$col_names[] = $name;
		}
		
		if(strpos($name, '[]')){
			$name = str_replace('[]', '', $name);
			$implodes .= "$"."_POST['".$name."'] = implode(',', $"."_POST['".$name."']);\n";
		}
		/*if ($i == 0) {
			$html_message.= "<table><table><tr height='10'><td width='30'><strong>Create column?</strong></td><td width='30'></td><td width='50' class='tablecell1'><strong>Column name</strong></td><td width='30'></td><td class='tablecell2'><strong>Column type</strong></td></tr>";
		}
		$html_message.= "<tr height='10'><td width='30'><input type='checkbox' name='cf_".$name."' id='cf_".$name."' value=''></td><td width='30'></td><td width='50' class='tablecell1'>";
		$html_message.= $name."</td><td width='30'></td><td class='tablecell2'>";
		$html_message.= $typelist."</td></tr>";
		$i++;*/
		
		if(($_POST['cf_'.$name] == '1')&&trim($name)){
			$chrono_fields[] = $name;			
			if($i > 1) $table_sql_body .= " , ";
			$table_sql_body .= "`".$name."` ".$_POST['fieldtype_'.$name]. " NOT NULL";
			if($i > 1) $chrono_posts .= " , ";
			$chrono_posts .= "'\"."."JRequest::getVar('$name','', 'post', 'string', '' ).\"'";
			$i++;
		}
		//$i++;
	}
	$registry = new JRegistry();
	$registry->loadINI( $row->paramsall );
	$paramsvalues = $registry->toObject( );
	if ( count($chrono_fields) > 0){
		$table_sql = "CREATE TABLE `#__chronoforms_".$id."` (";
		$table_sql .= $table_sql_body ." , PRIMARY KEY ( `cf_id` )";
		if ($paramsvalues->mysql_type == 2){
			$table_sql .= ") TYPE = MYISAM ;";
		} else{ 
			$table_sql .= ") ENGINE = MYISAM ;";
		}
	}
	//echo $table_sql = "CREATE TABLE `jos_chronoforms_1` (`ages` LONGTEXT NOT NULL ,`airline` LONGTEXT NOT NULL) ENGINE = MYISAM ;";
	$database->setQuery( $table_sql );
	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit();
	}
	$chrono_onsubmit = "<?php 
	$"."database =& JFactory::getDBO();
	srand((double)microtime()*10000);
	$"."inum	=	\"I\" . substr(base64_encode(md5(rand())), 0, 16);
	".$implodes."
$"."database->setQuery( \"INSERT INTO #__chronoforms_".$id." VALUES  (
'' , '\".$"."inum.\"','\". date('Y-m-d').\" - \".date(\"H:i:s\").\"', '\".$"."_SERVER['REMOTE_ADDR'].\"' , ".$chrono_posts.");\" );
if (!$"."database->query()) {
echo \"<script> alert('\".$"."database->getErrorMsg().\"'); window.history.go(-1); </script>\n\";
}
?>";
/*
	$database->setQuery( "UPDATE #__chrono_contact SET onsubmitcode='".$chrono_posts."' WHERE id=".$id );
	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit();
	}
	*/
	$row =& JTable::getInstance('chronocontact', 'Table');
	$row->load( $id );
	//$row->name = $row->name."XX";
	$row->autogenerated = $chrono_onsubmit;
	if (!$row->store()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	$mainframe->redirect( 'index2.php?option='.$option );
			
}

/* add menu item */
function addmenuitem( $option ){
global $database;
	if($_POST['menutext']){
		$database->setQuery("SELECT id FROM #__components WHERE name='Chrono Forms'");
		$comid = $database->loadResult();
		$database->setQuery("SELECT MAX(ordering) FROM #__menu WHERE menutype='".$_POST['menuname']."'");
		$maxorder = $database->loadResult();
		$database->setQuery( "INSERT INTO #__menu VALUES  ('' , '".$_POST['menuname']."', '".$_POST['menutext']."', 'index.php?option=com_chronocontact&chronoformname=".$_POST['name']."', 'components', '1', '0', '".$comid."', '0', '".($maxorder + 1)."', '0', '0000-00-00 00:00:00', '0', '0', '0', '3', '')" );
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>";
		}
		
		$row = new mosChronoContact( $database );
		$row->load( $_POST['id'] );
		//$_POST['task'] = 'edit';
		//HTML_ChronoContact::editChronoContact( $row, $option );
		$mainframe->redirect( 'index2.php?option='.$option );
	}
}

/* backup ****************************************************/
function backupChronoContact( $id, $option ){
global $mainframe;	
	$database =& JFactory::getDBO();
	$database->setQuery( "SELECT * FROM #__chrono_contact WHERE id='".$id."'" );
	$rows = $database->loadObjectList();
	$tablename = $mainframe->getCfg('dbprefix')."chrono_contact";
	$tables = array( $tablename );
 	$result = $database->getTableFields( $tables );
	$table_fields = array_keys($result[$tablename]);
	$string = '';
	foreach($table_fields as $table_field){
		$string .= '<++-++-++'.$table_field.'++-++-++>';
		$string .= $rows[0]->$table_field;
		$string .= '<endendend>';
		
	}
	if (ereg('Opera(/| )([0-9].[0-9]{1,2})', $_SERVER['HTTP_USER_AGENT'])) {
		$UserBrowser = "Opera";
	}
	elseif (ereg('MSIE ([0-9].[0-9]{1,2})', $_SERVER['HTTP_USER_AGENT'])) {
		$UserBrowser = "IE";
	} else {
		$UserBrowser = '';
	}
	$mime_type = ($UserBrowser == 'IE' || $UserBrowser == 'Opera') ? 'application/octetstream' : 'application/octet-stream';
	@ob_end_clean();
	ob_start();

	header('Content-Type: ' . $mime_type);
	header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');

	if ($UserBrowser == 'IE') {
		header('Content-Disposition: inline; filename="' . $rows[0]->name.'.cfbak"');
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Pragma: public');
	}
	else {
		header('Content-Disposition: attachment; filename="' . $rows[0]->name.'.cfbak"');
		header('Pragma: no-cache');
	}
	print $string;
	exit();
	
}
function restore1ChronoContact( $id, $option ){
	HTML_ChronoContact::restoreChronoContact( $id, $option );
}
function restore2ChronoContact( $id, $option ){
global $mainframe;	
	$database =& JFactory::getDBO();
	$id = $_POST['formid'];
	//echo $_FILES['file']['type'];
	if(!empty($_FILES['file']['name'])){
		$filename = $_FILES['file']['name'];
		$exten = explode(".",$filename);
		if($exten[count($exten)-1] == 'cfbak'){
		//if($_FILES['file']['type'] == "application/octet-stream"){
			//$filename = $_FILES['file']['name'];
			
			$path = JPATH_BASE.DS.'cache' . '/';
			if( is_writable($path) ) {
	
				if(!move_uploaded_file($_FILES['file']['tmp_name'], $path . $filename)) {
					print "<font class=\"error\">"."UPLAOD FAILED".": " . $_FILES['file']['error'] . "</font><br>\n";
				} else {
					$data = file_get_contents( $path . $filename );					
					$data = str_replace( '&amp;', '&', $data );
					$values = '(';
					$values2 = '(';
					//print $data;
					preg_match_all('/\<++(.*?)\<endendend>/s', $data, $matches);
					$i = 0;
					foreach ( $matches[0] as $match ) {
						if($i != 0){$values .= ',';$values2 .= ',';}
						//echo $match.'x';
						preg_match_all('/\<++(.*?)\++>/s', $match, $match2es);
						$fieldvalue = str_replace($match2es[0][0],'',$match);
						$match2es[0][0] = str_replace('<++-++-++','',$match2es[0][0]);
						$match2es[0][0] = str_replace('++-++-++>','',$match2es[0][0]);
						$values .= $match2es[0][0];
						if($i == 0){
							$values2 .= "''";
						}else{
							$match = str_replace('<++-++-++'.$match2es[0][0].'++-++-++>','',$match);
							$match = str_replace('<endendend>','',$match);
							$match = trim($match," \t.");
							//if(!trim($match)){
								//$match = "''";
							//}
							$values2 .= "'".addslashes($match)."'";
						}
						$i++;
					}
					$values .= ')';
					$values2 .= ')';
					$database->setQuery( "INSERT INTO #__chrono_contact ".$values." VALUES ".$values2 );
					if (!$database->query()) {
						echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>";
					}else{
						$mainframe->redirect( 'index2.php?option='.$option , "Restored successfully");
					}
					/*$handle = fopen($mosConfig_absolute_path.'/tmptxt.txt', 'w+');
					 if (fwrite($handle, "INSERT INTO #__chrono_contact ".$values." VALUES ".$values2) === FALSE) {
							echo "Cannot write to file ($filename)";
							exit;
						}
						fclose($handle);*/
				}
			}
		}else{
			echo "Sorry, But this is not a valid ChronoForms backup file, Backup files should end with .cfbak";
		}
	}
}

function BackupExcel( $id, $option ) {
	global $mainframe;
	$database =& JFactory::getDBO();

	include_once JPATH_BASE.DS.'/components/com_chronocontact/excelwriter/'."Writer.php";
	//echo $_POST['formid'];
	$database->setQuery( "SELECT name FROM #__chrono_contact WHERE id='".$_POST['formid'][0]."'" );
	$formname = $database->loadResult();
	
	$tablename = $mainframe->getCfg('dbprefix')."chronoforms_".$_POST['formid'][0];
	$tables = array( $tablename );
 	$result = $database->getTableFields( $tables );
	$table_fields = array_keys($result[$tablename]);
	
	$database->setQuery( "SELECT * FROM ".$tablename."" );
	$datarows = $database->loadObjectList();
	
	$xls =& new Spreadsheet_Excel_Writer();
	$xls->send("ChronoForms - ".$formname." - ".date("j_n_Y").".xls");
	$format =& $xls->addFormat();
	$format->setBold();
	$format->setColor("blue");
	if (strlen($formname) > 10){$formname = substr($formname,0,10);};
	$sheet =& $xls->addWorksheet($formname.' at '.date("m-d-Y"));
	
	$titcol = 0;
	foreach($table_fields as $table_field){
		$sheet->writeString(0, $titcol, $table_field, $format);
		$titcol++;
	}
			
			
	$datacol = 0;
	$rowcount = 1;
	foreach($datarows as $datarow){
		foreach($table_fields as $table_field){
			$sheet->writeString($rowcount, $datacol, $datarow->$table_field, 0);
			$datacol++;
		}
		$datacol = 0;
		$rowcount++;
	}
			
	$xls->close();
	exit;
	
}
function deleterecordChronoContact( $cid_del, $option ) {
	global $mainframe;
	$database =& JFactory::getDBO();
	//echo $cid_del[0];
	if (!is_array( $cid_del ) || count( $cid_del ) < 1) {
		echo "<script> alert('Please select an entry to delete'); window.history.go(-1);</script>\n";
		exit;
	}
	$cid_del_arr = array();
	foreach($cid_del as $cid_del_1){
		$fids = explode("_",$cid_del_1);
		$cid_del_arr[] = $fids[0];
		$formid = $fids[1];
	}
	$cid_dels = implode( ',', $cid_del_arr );
	$database->setQuery( "DELETE FROM #__chronoforms_".$formid." WHERE cf_id IN ($cid_dels)" );
	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
	}
	showdataChronoContact( $formid, $option );
	//$mainframe->redirect( "index2.php?option=$option" );
	//echo "DELETE FROM #__chronoforms_".$formid." WHERE cf_id IN ($cid_dels)";
}

function BackupCSV( $id, $option ) {
global $mainframe;
	$database =& JFactory::getDBO();

	include_once JPATH_BASE.'/components/com_chronocontact/excelwriter/'."Writer.php";
	//echo $_POST['formid'];
	$database->setQuery( "SELECT name FROM #__chrono_contact WHERE id='".$_POST['formid'][0]."'" );
	$formname = $database->loadResult();
	
	$tablename = $mainframe->getCfg('dbprefix')."chronoforms_".$_POST['formid'][0];
	$tables = array( $tablename );
 	$result = $database->getTableFields( $tables );
	$table_fields = array_keys($result[$tablename]);
	
	$database->setQuery( "SELECT * FROM ".$tablename."" );
	$datarows = $database->loadObjectList();
	
	$titcol = 0;
	foreach($table_fields as $table_field){
		if($titcol){$csvline .=",";}
		$csvline .= $table_field;
		$titcol++;
	}
	$csvline .="\n";
			
	$datacol = 0;
	$rowcount = 1;
	foreach($datarows as $datarow){
		foreach($table_fields as $table_field){
			if($datacol){$csvline .=",";}
			$csvline .= '"'.addslashes($datarow->$table_field).'"';
			$datacol++;
		}
		$csvline .="\n";
		$datacol = 0;
		$rowcount++;
	}
	
	if (ereg('Opera(/| )([0-9].[0-9]{1,2})', $_SERVER['HTTP_USER_AGENT'])) {
		$UserBrowser = "Opera";
	}
	elseif (ereg('MSIE ([0-9].[0-9]{1,2})', $_SERVER['HTTP_USER_AGENT'])) {
		$UserBrowser = "IE";
	} else {
		$UserBrowser = '';
	}
	$mime_type = ($UserBrowser == 'IE' || $UserBrowser == 'Opera') ? 'application/octetstream' : 'application/octet-stream';
	@ob_end_clean();
	ob_start();

	header('Content-Type: ' . $mime_type);
	header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');

	if ($UserBrowser == 'IE') {
		header('Content-Disposition: inline; filename="' . "ChronoForms - ".$formname." - ".date("j_n_Y").'.csv"');
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Pragma: public');
	}
	else {
		header('Content-Disposition: attachment; filename="' . "ChronoForms - ".$formname." - ".date("j_n_Y").'.csv"');
		header('Pragma: no-cache');
	}
	print $csvline;
	exit();
	
}
function deletetableChronoContact(  $id, $option ){
global $mainframe;
	$database =& JFactory::getDBO();
	$result = $database->getTableList();
	if (!in_array($mainframe->getCfg('dbprefix')."chronoforms_".$id, $result)) {
		echo "<script> alert('"."There is no table for this form to delete"."'); window.history.go(-1); </script>\n";
	}else{
		$database->setQuery( "DROP TABLE IF EXISTS `#__chronoforms_".$id."`;" );
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>";
		}else{
			$mainframe->redirect( 'index2.php?option='.$option , "Table Deleted successfully");
		}
	}
}
function menu_creator($option){
	HTML_ChronoContact::menu_creator( $option );
}
function menu_save($option){
	global $mainframe;
	$database =& JFactory::getDBO();
	JTable::addIncludePath(JPATH_SITE.DS.'libraries'.DS.'joomla'.DS.'database'.DS.'table');
	$row =& JTable::getInstance('component', 'JTable');
	//$row->load(1);
	$row->name = $_POST['linktext'];
	$row->parent = $_POST['parent'];
	$row->ordering = $_POST['ordering'];
	$row->admin_menu_link = "option=com_chronocontact&task=show&formid=".$_POST['form_id'];
	$row->admin_menu_img = "js/ThemeOffice/".$_POST['icon'];
	$row->option = "com_chronocontact";
	$row->link = "option=com_chronocontact&task=show&formid=1";
	$row->admin_menu_alt = $_POST['linktext'];
	if (!$row->store()) {
		JError::raiseError(500, $row->getError() );
	}
	$mainframe->redirect( 'index2.php?option='.$option , "Menu Item Created");
}
?>
