#!/usr/local/bin/php -q
<?
include (dirname(__FILE__)."/../includes/common.php");


function cErr($msg){
	global $BILLING_EMAIL; 
	@mail($BILLING_EMAIL,"Ошибка при обновлении курсов",$msg,"From:ExChanger CRON<$BILLING_EMAIL>");
}



/* CURRENCY */

$val1_row = mysql_fetch_object(mysql_query("select * from currencies where code='RUR'"));
$time = time();

/* GLOBAL */
$charCode = "";
$xmlTag = "";
$nominal = "";

function startLVLElement($parser, $name, $attrs) {
	global $xmlTag;
	$xmlTag = $name;
}

function endLVLElement($parser, $name) {
}

function characterLVLData($parser, $data) {
   global $xmlTag;
   global $charCode;
   global $val1_row;
   global $time;
   global $nominal;

   if(strtoupper($xmlTag)=="ID" && trim($data)!=""){
		$charCode = trim($data);
   }
   
   if(strtoupper($xmlTag)=="RATE"&&strtoupper($charCode)=="USD"&&trim($data)!=""){
		if(!($data > 0)){
			exit;
		}
		$tmp_row = mysql_fetch_object(mysql_query("select * from currencies where code='LVL'"));
		if($tmp_row->id!=""){
			$value = str_replace(",",".",round(GetCourse("USD")/$data,6))+0;
			if($value > 0){
				mysql_query("INSERT INTO `courses` (`val1_id` ,`val1_number` , `val2_id` ,`val2_number` , `course` , `back_course` , `date`) VALUES ('".($tmp_row->id)."',1,'".$val1_row->id."',1, $value, '".round(1/$value,6)."', '".$time."');");
			}
		}
   }
}

$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
xml_set_element_handler($xml_parser, "startLVLElement", "endLVLElement");
xml_set_character_data_handler($xml_parser, "characterLVLData");
if (!($fp = fopen("http://www.bank.lv/ValutuKursi/XML/xml.cfm?date=20040212","r"))) {
   die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
   if (!xml_parse($xml_parser, $data, feof($fp))) {
       die(sprintf("XML error: %s at line %d",
                   xml_error_string(xml_get_error_code($xml_parser)),
                   xml_get_current_line_number($xml_parser)));
   }
}
xml_parser_free($xml_parser);

exit;
?>