<?
// Set flag that this is a parent file
	define( '_FEXEC', 1 );
	set_time_limit(0);
	require('includes/sms_application_top.php');
	require(DIR_WS_CLASSES . 'xml_parser.php');

	define("EMAIL_TEXT_SUBJECT","Currency update failure at %s");
	define("EMAIL_TEXT_RECOVER_SUBJECT","Currency update recovery at %s");
	define("EMAIL_TEXT_RECOVERY_SUBJECT","Currency update recovery at %s");

	$perform_update=true;
	$send_failure_mail_flag=false;
	$send_recovery_mail_flag=false;

	if($perform_update)
	{	
		$status_sql="select * from " . TABLE_CURRENCY_UPDATE_HISTORY . "  order by update_time desc limit 3";
		$status_query=tep_db_query($status_sql);
		$update_status=0;
		$fail_status=0;
		$icnt=0;
		if(tep_db_num_rows($status_query)>0) {
			while($status_result=tep_db_fetch_array($status_query)) {
				if($status_result['update_status']=='U' && $icnt==0)
					break;
				else if($status_result['update_status']=='U' && $icnt!=0)
					$update_status++;
				else if($status_result['update_status']=='F')
					$fail_status++;	
			$icnt++;		
			}
		}
		$sql="select code from " . TABLE_CURRENCIES . " order by code";
		$sql_query=tep_db_query($sql);
		$update_result=false;
		while($row=tep_db_fetch_array($sql_query))
			$currency_names[]=$row['code'];
			
		$update_result=get_google_currency_rates($currency_names);
		if(!$update_result){ //is false then try for currencysource.com
			error_notification("Failure Currency Update from Google");
			$update_result=get_currencysource_rates();
		}
		
		if($update_result)  //success update
		{
			update_currency_table($update_result);
			insert_status_record('U'); //currecy_update_history
			if($fail_status==3)	{
				send_recovery_mail();
			}
		}
		else	//failure update
		{
			error_notification("Failure Currency Update from currencysource");
			insert_status_record('F'); //currecy_update_history
			if($fail_status==2){
				send_failure_mail();
			}
		}
    }
function get_google_currency_rates($currency_names){
	$result=array();
	for ($icnt=0,$n=count($currency_names);$icnt<$n;$icnt++){
		if (DEFAULT_CURRENCY!=$currency_names[$icnt]){
			$data=@file_get_contents("http://www.google.co.in/search?hl=en&q=" . urlencode(sprintf("1 %s in %s",DEFAULT_CURRENCY,$currency_names[$icnt])));
			//$data=@file_get_contents("currency_update/simple_google_results.txt");
			$data=strip_tags($data);
			$spos=strpos($data," = ");
			if ($spos===false) return false;
			$spos=$spos+3;
			$epos=strpos($data," ",$spos);
			if ($epos===false) return false;
			$data=(float)substr($data,$spos,$epos-$spos);
			if ($data<0.0) return false;
			$result[$currency_names[$icnt]]=$data;
		} else {
			$result[$currency_names[$icnt]]=1.0;
		}
	}
	return $result;
}
	
function get_currencysource_rates()
{
	$er_url=DEFAULT_CURRENCY . ".xml";
	//$rates = @file_get_contents("currency_update/" . $er_url);
	$rates = "http://currencysource.com/RSS/" . DEFAULT_CURRENCY . ".xml";
	$start_pos=strpos($rates,"<item>");
	$end_pos=strrpos($rates,"</item>");
	if($start_pos>=0 && $end_pos>0) //success result
	{
		$rates=substr($rates,$start_pos,$end_pos-$start_pos);
		$rates='<?xml version="1.0"?><items>' . $rates . "</items></item>";
		$parser=new xml_parser_class;
		$parser->store_positions=0;
		$parser->case_folding=0;
		$parser->target_encoding="ISO-8859-1";
		$parser->simplified_xml=0;
		$parser->fail_on_non_simplified_xml=0;
		
		$parser->parse($rates,true);
		$result=&$parser->structure;
		$n=count($result);
		for ($icnt=0;$icnt<$n;$icnt++){
			if (isset($result["0," . $icnt . ",1,0"]))
			{
				$cur_result=$result["0," . $icnt . ",1,0"];
				$cur_arr=split("=",$cur_result);
				if(count($cur_arr)>1)
				{
					$temp_arr=split('\(',$cur_arr[1]);
					$cur_key=trim($temp_arr[0]);
					$cur_value=trim(substr($temp_arr[1],0,-1));
					if ($cur_value<0.0) return false;
					$currency_update[$cur_key]=$cur_value;
				}
			}
		}
		return $currency_update;
	}
	else
		return false;
}

function insert_status_record($update_status)
{
	global $send_failure_mail_flag,$send_recovery_mail_flag;
	$update_time=date("Y-m-d h:i:s");
	/*$sql="select * from " . TABLE_CURRENCY_UPDATE_HISTORY . " where currency_name='" . DEFAULT_CURRENCY . "' order by update_time desc limit 3";
	$sql_query=tep_db_query($sql);
	if(tep_db_num_rows($sql_query)>0)
	{
		$row=tep_db_fetch_array($sql_query);
		if($row['update_status']=='U' && $update_status=='U')  //successive success updates no change
		{
			$step_val=0;
		}
		elseif($row['update_status']=='U' && $update_status=='F') //first failure
		{
			$step_val=1;
		}
		elseif($row['update_status']=='F' && $update_status=='U') //prev failure and now success
		{
			$send_recovery_mail_flag=true;
			$step_val=0;
		}
		elseif($row['update_status']=='F' && $row['counter_track']==2 && $update_status=='F') //two failures 
		{
			$send_failure_mail_flag=true;
			$step_val=$row['counter_track']+1;
		}
		elseif($row['update_status']=='F' && $update_status=='F') //count the successive failures 
		{
			$step_val=$row['counter_track']+1;
		}
	}
	else
	{
		if($update_status=='U')
			$step_val=0;
		else
			$step_val=1;
	} */
	$sql="insert into " . TABLE_CURRENCY_UPDATE_HISTORY . " (update_time,update_status) values('" . $update_time . "','" . $update_status  . "')";
	tep_db_query($sql);
}
	
function update_currency_table($cur_update)
{
	while(list($key,$value)=each($cur_update))
	{
		$sql="update " . TABLE_CURRENCIES . " set value='$value',last_updated=now() where code='$key'";
		tep_db_query($sql);
	}
}

function send_failure_mail()
{
	$sql="select * from " . TABLE_CURRENCY_UPDATE_HISTORY . " where update_status='F' order by update_time desc limit 3";
	$sql_query=tep_db_query($sql);
	$max_cnt=0;
	$min_cnt=2;
	while($row=tep_db_fetch_array($sql_query))
	{
		if($max_cnt==0)
			$max_time=$row['update_time'];
		elseif($min_cnt==0)
			$min_time=$row['update_time'];
		$max_cnt++;
		$min_cnt--;
	}

	$subject=sprintf(EMAIL_TEXT_SUBJECT, STORE_NAME);
	$email ="This is an automated email. Please do not reply. " . "\n\n" .
			"The automatic currency update at " . STORE_NAME . " failed after three attempts between " . $min_time . " to " . $max_time . ".It is strongly recommended that you try a manual update. " . "\n\n" . "with thanks, " . "\n\n" . "osCommRes system	";
	$sql="select a.admin_firstname,a.admin_lastname,a.admin_email_address from " . TABLE_ADMIN . " a," . TABLE_ADMIN_GROUPS . " ag where ag.admin_groups_id=a.admin_groups_id and ag.admin_groups_name='" . TEXT_ADMINISTRATOR_ENTRY . "'";
	$sql_query=tep_db_query($sql);
	while($row=tep_db_fetch_array($sql_query))
		tep_mail($row['admin_lastname'] . ' ' . $row['admin_firstname'] , $row['admin_email_address'], $subject, $email, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);
	return true;
}
function send_recovery_mail()
{
	$sql="select * from " . TABLE_CURRENCY_UPDATE_HISTORY . "  order by update_time desc";
	$sql_query=tep_db_query($sql);
	$cunt=0;
	while($row=tep_db_fetch_array($sql_query))
	{
		if($row['update_status']=='U' && $cunt==0)
			$update_time=$row['update_time'];
		elseif($row['update_status']=='U' && $cunt!=0)
			break;
		elseif($row['update_status']=='F' && $cunt==0)
		{
			$max_date=$row['update_time'];
			$cunt++;
		}
		$min_date=$row['update_time'];
	}

	$subject=sprintf(EMAIL_TEXT_RECOVER_SUBJECT, STORE_NAME);
	$email ="This is an automated email. Please do not reply. " . "\n\n" .
			"The automatic currency update at " .STORE_NAME  . " has recovered as at " . $update_time . ". It was in a failed state between " . $min_date . " to " .  $max_date . ". It is strongly recommended that you check your systems to avoid further outages." . "\n\n" . "with thanks, " . "\n\n" . "osCommRes system	"; 
	$sql="select a.admin_firstname,a.admin_lastname,a.admin_email_address from " . TABLE_ADMIN . " a," . TABLE_ADMIN_GROUPS . " ag where ag.admin_groups_id=a.admin_groups_id and ag.admin_groups_name='" . TEXT_ADMINISTRATOR_ENTRY . "'";
	$sql_query=tep_db_query($sql);
	while($row=tep_db_fetch_array($sql_query))
        tep_mail($row['admin_lastname'] . ' ' . $row['admin_firstname'] , $row['admin_email_address'], $subject, $email, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);
	return true;
}
function error_notification($error){
	global $HTTP_SERVER_VARS;
	$error_array = array(
						'cron_jobs_error_action' => basename($HTTP_SERVER_VARS['PHP_SELF']),
						'cron_jobs_error_text' => $error,
						'cron_jobs_error_date' => 'now()'
						);
	tep_db_perform(TABLE_CRON_JOBS_ERROR,$error_array);
}
?>
