<?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( '_VALID_MOS' ) or die( 'Direct access to this file is prohibited.' );

// Here a check is performed to see whether the logged in user has the rights
if (!($acl->acl_check( 'administration', 'edit', 'users', $my->usertype, 'components', 'all' )
		| $acl->acl_check( 'administration', 'edit', 'users', $my->usertype, 'components', 'com_contact' ))) {
	mosRedirect( 'index2.php', _NOT_AUTH );
}
global $mosConfig_lang, $mosConfig_absolute_path, $chronocontact_params;
// Loading of the database class and the HTML class
require_once( $mainframe->getPath( 'admin_html' ) );
require_once( $mainframe->getPath( 'class' ) );

$ChronoContact = new mosChronoContact($database);

$id 	= mosGetParam( $_GET, 'id', 0 );
$cid 	= mosGetParam( $_POST, 'cid', array(0) );
if (!is_array( $cid )) {
	$cid = array(0);
}
$cid_del 	= mosGetParam( $_POST, 'cid_del', array(0) );
if (!is_array( $cid_del )) {
	$cid_del = array(0);
}

// case differentiation
switch ($task) {
	case "publish":
		publishChronoContact( $cid, 1, $option );
		break;
	case "unpublish":
		publishChronoContact( $cid, 0, $option );
		break;
	case "new":
		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 );
		mosRedirect( "index2.php?option=".$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:
		$switch = 1;
		if(strpos("x".$task,"plugin_")){
			$directory = $mosConfig_absolute_path.'/components/com_chronocontact/plugins/';
			$results = array();
			$handler = opendir($directory);
			while ($file = readdir($handler)) {
				if ( $file != '.' && $file != '..' && substr($file, -4) == '.php' )
					$results[] = str_replace(".php","", $file);
			}
			closedir($handler);
			foreach($results as $result){
				if($task == 'plugin_'.$result){
					require_once($mosConfig_absolute_path."/components/com_chronocontact/plugins/".$result.".php");
					${$result} = new $result();
					$switch = 0;
					global $database;
					$database->setQuery( "SELECT id FROM #__chrono_contact_plugins WHERE form_id='".$cid[0]."' AND name='".$result."'" );
					$id = $database->loadResult();
					$row = new mosChronoContact_Plugins( $database );
					$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 ){
global $mosConfig_absolute_path;
	require_once($mosConfig_absolute_path."/components/com_chronocontact/plugins/".$_POST['name'].".php");
	${$_POST['name']} = new $_POST['name']();
	${$_POST['name']}->save_conf($option);
}
// Publishing of the entries
function publishChronoContact( $cid, $publish, $option ) {
	global $database;
	if (count( $cid ) < 1) {
		$action = $publish ? 'publish' : 'unpublish';
		echo "<script> alert('Select an 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 = new mosChronoContact( $database );
		$row->checkin( $cid[0] );
	}
	mosRedirect( "index2.php?option=$option" );
}
// create a new entry (id = 0)
// or change entry with id = n
function editChronoContact( $id, $option ) {
	global $database;
	$row = new mosChronoContact( $database );
	$row->load( $id );

	HTML_ChronoContact::editChronoContact( $row, $option );
}
// deletion of entries
function removeChronoContact( $cid, $option ) {
	global $database;
	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";
	}
	mosRedirect( "index2.php?option=$option" );
}
function copyChronoContact( $id , $option ) {
	global $database;	
	$row = new mosChronoContact( $database );
	$row->load( $id );
	$row->id = '';
	$row->name = $row->name."_".date("dmY_Hisu");
	if (!$row->store()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	mosRedirect( "index2.php?option=".$option );
}
// save entry
function saveChronoContact( $option ) {
	global $database;	
	
	
	$row = new mosChronoContact( $database );
	if (!$row->bind( $_POST )) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	
	$params = mosGetParam( $_POST, 'params', '' );
	if (is_array( $params )) {
		$txt = array();
		foreach ( $params as $k=>$v) {
			$txt[] = "$k=$v";
		}
		$plugins = mosgetparam($_POST, 'plugins', array(0));
		if($plugins){
			$txt[] = "plugins=".implode(",",$plugins);
		}
		$mplugins_order = mosgetparam($_POST, 'mplugins_order', 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();
	}
	//mosRedirect( "index2.php?option=".$option );
}
// abort the current action
function cancelChronoContact( $option ) {
	global $database;
	$row = new mosChronoContact( $database );
	$row->bind( $_POST );
	$row->checkin();
	mosRedirect( "index2.php?option=$option" );
}
// list entries
function showChronoContact($option) {
	global $database,$mosConfig_absolute_path, $mainframe, $mosConfig_list_limit;
	//josSpoofCheck();
	$limit 			= intval( $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit ) );
	$limitstart 	= intval( $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 ) );
	// count entries
	$database->setQuery( "SELECT count(*) FROM #__chrono_contact" );
	$total = $database->loadResult();
	echo $database->getErrorMsg();
	require_once( $mosConfig_absolute_path . '/administrator/includes/pageNavigation.php' );
	$pageNav = new mosPageNav( $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';
	mosRedirect( 'index2.php?option='. $option, $msg );
}
function cancelSettings( $option='com_chronocontact'){
	mosRedirect( 'index2.php?option='.$option );
}



///////////////////////////////
function showdataChronoContact($id, $option) {
	global $database, $mainframe,$mosConfig_absolute_path, $mosConfig_dbprefix, $mosConfig_list_limit;
	if(!$id){
		if(is_array(mosGetParam($_POST, 'formid', array(0)))){
			$id_arr = mosGetParam($_POST, 'formid', array(0));
			$id = $id_arr[0];
		}else{
			$id = mosGetParam($_POST, 'formid', 0);
		}
	}
	if(!$id){
		$id = mosGetParam($_GET, 'formid', 0);
	}
	$result = $database->getTableList();
	if (!in_array($mosConfig_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 			= intval( $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit ) );
		$limitstart 	= intval( $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 ) );
		// count entries
		$database->setQuery( "SELECT count(*) FROM #__chronoforms_".$id );
		$total = $database->loadResult();
		echo $database->getErrorMsg();
		require_once( $mosConfig_absolute_path . '/administrator/includes/pageNavigation.php' );
		$pageNav = new mosPageNav( $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 $database, $mosConfig_dbprefix;
	$fids = explode("_",$ids);
	$database->setQuery( "SELECT * FROM #__chronoforms_".$fids[1]." WHERE cf_id=".$fids[0] );
	$rows = $database->loadObjectList();
	$row = $rows[0];
	$tablename = $mosConfig_dbprefix."chronoforms_".$fids[1];
	HTML_ChronoContact::viewdataChronoContact( $row, $option, $tablename, $fids[1] );
}
function maketableChronoContact( $id, $option ) {
	global $database, $mosConfig_dbprefix;
	$result = $database->getTableList();
	if (in_array($mosConfig_dbprefix."chronoforms_".$id, $result)) {
	//echo $mosConfig_dbprefix."_chronoforms_".$id;
		//echo "A table has already been created for this form";
		HTML_ChronoContact::maketableChronoContact( $row, $option, "exists" );
	} else {
		$row = new mosChronoContact( $database );
		$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 $database, $chronocontact_params;
	$id = $_POST['formid'];
	$row = new mosChronoContact( $database );
	$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 .= "'\"."."mosGetParam($"."_POST,'$name','').\"'";
			$i++;
		}
		//$i++;
	}
	$paramsvalues = mosParseParams( $row->paramsall );
	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 
	global $"."database;
	
	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 = new mosChronoContact( $database );
	$row->load( $id );
	$row->autogenerated = $chrono_onsubmit;
	if (!$row->store()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	mosRedirect( '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 );
		mosRedirect( 'index2.php?option='.$option );
	}
}

/* backup ****************************************************/
function backupChronoContact( $id, $option ){
global $database, $mosConfig_dbprefix;
	$database->setQuery( "SELECT * FROM #__chrono_contact WHERE id='".$id."'" );
	$rows = $database->loadObjectList();
	$tablename = $mosConfig_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 $database, $mosConfig_cachepath, $mosConfig_absolute_path;
	$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 = $mosConfig_cachepath . '/';
			if( is_writable($path) ) {
	
				if(!move_uploaded_file($_FILES['file']['tmp_name'], $path . $filename)) {
					print "<font class=\"error\">".LM_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{
						mosRedirect( '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 $mosConfig_absolute_path, $database, $mosConfig_dbprefix;

	include_once $mosConfig_absolute_path.'/administrator/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 = $mosConfig_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 $database;
	//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 );
	//mosRedirect( "index2.php?option=$option" );
	//echo "DELETE FROM #__chronoforms_".$formid." WHERE cf_id IN ($cid_dels)";
}

function BackupCSV( $id, $option ) {
global $mosConfig_absolute_path, $database, $mosConfig_dbprefix;

	include_once $mosConfig_absolute_path.'/administrator/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 = $mosConfig_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 $database, $mosConfig_dbprefix;
	$result = $database->getTableList();
	if (!in_array($mosConfig_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{
			mosRedirect( 'index2.php?option='.$option , "Table Deleted successfully");
		}
	}
}
function menu_creator($option){
	HTML_ChronoContact::menu_creator( $option );
}
function menu_save($option){
	global $database;
	$row = new mosComponent( $database );
	$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->admin_menu_alt = $_POST['linktext'];
	if (!$row->store()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	mosRedirect( 'index2.php?option='.$option , "Menu Item Created");
}
?>
