Просмотр файла includes/functions.php

Размер файла: 114.33Kb
<?php


/**
 * converts variabale to an unsigned integer
 *
 * @param mixed $var
 * @return unsigned int
 */
function uintval($var)
{
	$var = intval($var);
	if (0 > $var)
	{
		return 0;
	}
	else
	{
		return $var;
	}
}

/**
 * converts variabale to an unsigned float
 *
 * @param mixed $var
 * @return unsigned float
 */
function ufloatval($var)
{
	$var = floatval($var);
	if (0 > $var)
	{
		return 0;
	}
	else
	{
		return $var;
	}
}

function validate_url($url)
{
	return eregi("^http:\/\/.*", $url);
}

function dump($var, $return = 0)
{
	if ($return)
	{
		return "<xmp>".print_r($var, 1)."</xmp>";
	}
	else
	{
		echo "<xmp>".print_r($var, 1)."</xmp>";
	}
}

function get_currency_cources()
{
	global $DEF_CURRENCY;
	$cources = array();

	$val_row = mysql_fetch_object(mysql_query("select * from currencies where code='$DEF_CURRENCY'"));
	$res = mysql_query("select * from currencies where code<>'$DEF_CURRENCY' order by id");
	while($row = mysql_fetch_object($res))
	{
		$query = "select * from courses where val1_id = $row->id and val2_id = $val_row->id order by courses.date desc";
		$tmp_res = mysql_query($query);
		$tmp_row1 = mysql_fetch_object($tmp_res);

		$query = "select * from courses where val1_id = $row->id and val2_id = $val_row->id and date <=".($tmp_row1->date-24*3600)." order by courses.date desc";
		$tmp_res = mysql_query($query);

		if($tmp_row2 = @mysql_fetch_object($tmp_res)){
			$change = round($tmp_row1->course - $tmp_row2->course,4)+0;
			$class = $change >=0?"kursup":"kursdown";
		}
		else{
			$change = "-";
		}

		$cources[] = array("change" => $change,
		"class" => $class,
		"num" => ($tmp_row1->val1_number>1?$tmp_row1->val1_number:""),
		"code" => $row->code,
		"course" => floatval($tmp_row1->course),
		"back_course" => floatval($tmp_row1->back_course)
		);
	}

	return $cources;
}

function get_metal_cources()
{
	$cources = array();

	$res = mysql_query("select * from metals order by id");
	while($row = mysql_fetch_object($res))
	{
		$query = "select * from metal_prices where metal_id = $row->id order by date desc";
		$tmp_res = mysql_query($query);
		$tmp_row1 = mysql_fetch_object($tmp_res);


		$query = "select * from metal_prices where metal_id = $row->id and date<=".($tmp_row1->date-24*3600)." order by date desc";
		$tmp_res = mysql_query($query);

		if($tmp_row2 = @mysql_fetch_object($tmp_res)){
			$change = round($tmp_row1->price - $tmp_row2->price +0,4);
		}
		else{
			$change = "-";
		}
		$class = $change >=0?"kursup":"kursdown";

		$cources[] = array("change" => $change,
		"class" => $class,
		"name" => $row->name,
		"price" => round($tmp_row1->price,4)
		);
	}

	return $cources;
}


/**** EXCHANGE FUNCTIONS BEGIN  ********/

function GetEmailTemplate($code){

	$query = "select * from email_templates where code='$code'";

	$row = @mysql_fetch_object(@mysql_query($query));

	$arr = Array();
	$arr['subject']=stripslashes($row->subject);
	$arr['body']=stripslashes($row->body);
	$arr['from']=stripslashes($row->from_who);
	$arr['format']=$row->format;

	return $arr;
}

function HttpRequest($url){
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,0);

	$fp = tmpfile();
	curl_setopt ($ch, CURLOPT_FILE, $fp);
	curl_exec($ch);
	curl_close($ch);

	fseek($fp,0,SEEK_SET);
	$result = fgets($fp,1024);
	fclose($fp);

	return $result;
}


/* money functions */

function GetCourse($code="USD"){
	$row = mysql_fetch_object(mysql_query("select * from currencies where code='$code'"));
	$ru_row = mysql_fetch_object(mysql_query("select * from currencies where code='RUR'"));

	$row = mysql_fetch_object(mysql_query("select * from courses where val1_id=$row->id and val2_id=$ru_row->id order by date desc"));

	return ($row->course+0);
}
function GetCourseByExID($from,$to){

	global $DEF_CURRENCY;

	$row = mysql_fetch_object(mysql_query("select * from ex_currencies where id=$to"));
	$to = $row->currency_id;

	$row = mysql_fetch_object(mysql_query("select * from currencies where code='$DEF_CURRENCY'"));
	$def = $row->id;

	$row = mysql_fetch_object(mysql_query("select * from ex_currencies where id=$from"));
	$from = $row->currency_id;

	if($to == $from){
		return 1;
	}

	$row = mysql_fetch_object(mysql_query("select * from courses where val1_id=$from and val2_id=$to order by date desc"));

	if($row->course==""){
		$row = mysql_fetch_object(mysql_query("select * from courses where val1_id=$to and val2_id=$from order by date desc"));
		if($row->id!=""){
			return round(($row->val1_number/$row->val2_number)*$row->back_course,6);
		}
		else{
			return round(GetCourseByID($from,$def)*GetCourseByID($def,$to),6);
		}
	}

	return round(($row->val2_number/$row->val1_number)*$row->course,6);
}

function GetCourseByID($from,$to){

	global $DEF_CURRENCY;

	if($to == $from){
		return 1;
	}

	$row = mysql_fetch_object(mysql_query("select * from currencies where code='$DEF_CURRENCY'"));
	$def = $row->id;

	$row = mysql_fetch_object(mysql_query("select * from courses where val1_id=$from and val2_id=$to order by date desc"));

	if($row->course==""){
		$row = mysql_fetch_object(mysql_query("select * from courses where val1_id=$to and val2_id=$from order by date desc"));
		if($row->id!=""){
			return round(($row->val1_number/$row->val2_number)*$row->back_course,6);
		}
		else{
			return round(GetCourseByID($from,$def)*GetCourseByID($def,$to),6);
		}
	}

	return round(($row->val2_number/$row->val1_number)*$row->course,6);;
}

function GetMetalPrice($id){

	$row = mysql_fetch_object(mysql_query("select * from metal_prices where metal_id = $id order by date desc"));

	return ($row->price+0);
}

function GetMetalPriceByName($code){
	$row = mysql_fetch_object(mysql_query("select * from metals where code='".(strtoupper($code))."'"));
	return GetMetalPrice($row->id+0);
}

function OldCountOut($amount,$from_id,$to_id)
{
	$row_from = mysql_fetch_object(mysql_query("select * from ex_currencies where id = $from_id"));
	$row_to = mysql_fetch_object(mysql_query("select * from ex_currencies where id = $to_id"));

	$result_array = Array();

	$result_array['ex_curr_in_id'] = $from_id;
	$result_array['ex_curr_out_id'] = $to_id;

	/* amount */
	$amount = round($amount,$row_from->precision);
	$result_array['in_amount'] = $amount;

	$tmp_arr = CountToCom($row_from->metal_id>0?$amount/GetMetalPrice($row_from->metal_id):$amount,$row_from->code);

	/* comission */
	if($tmp_arr['fix'] > 0){
		$tmp_amount = round(($amount - $tmp_arr['fix'])/(1+$tmp_arr['perc']),$row_from->precision);/*what we get*/
	}
	else{
		$tmp_amount = floor((($amount)/(1+$tmp_arr['perc']))*pow(10,$row_from->precision))/pow(10,$row_from->precision);/*what we get*/
	}

	if($tmp_amount == $amount){
		$tmp_amount -= 0.01;
	}

	// DONT COUNT USER COMISSION IN THIS VERSION
	$tmp_amount = $amount;

	$result_array['tmp_we_get_amount'] = $tmp_amount;

	$ex_from_comission = round($amount - $tmp_amount,$row_from->precision);
	$result_array['ex_from_com'] = $ex_from_comission;

	/* SYSTEM COMISSION */
	$row = mysql_fetch_object(mysql_query("select * from ex_exchanges where ex_currency1_id = $row_from->id and ex_currency2_id = $row_to->id"));

	if($row->sys_comission_fix > 0){
		$sys_comission = round($tmp_amount*$row->sys_comission_perc,$row_from->precision)+$row->sys_comission_fix;
	}
	else{
		$sys_comission = ceil($tmp_amount*$row->sys_comission_perc*pow(10,$row_from->precision))/pow(10,$row_from->precision);
	}
	$result_array['sys_com'] = $sys_comission;

	$tmp_amount = round($tmp_amount-$sys_comission,$row_from->precision);

	$result_array['clear_from_amount'] = $tmp_amount;

	$result_array['cource'] = GetCourseByExID($row_from->id,$row_to->id);
	$tmp_out_amount = round($tmp_amount*GetCourseByExID($row_from->id,$row_to->id),$row_to->precision);

	$result_array['tmp_out_amount'] = $tmp_out_amount;

	$tmp_arr = CountFromCom($row_to->metal_id>0?$tmp_out_amount/GetMetalPrice($row_to->metal_id):$tmp_out_amount,$row_to->code);

	/* send sum depends on who pays comission */
	if($row_to->who_pay_comission==0){/* case sender pays */
		if($tmp_arr['fix'] > 0){
			$out_amount = round(($tmp_out_amount - $tmp_arr['fix'])/(1+$tmp_arr['perc']),$row_to->precision);
		}
		else{
			$out_amount = floor((($tmp_out_amount)/(1+$tmp_arr['perc']))*pow(10,$row_to->precision))/pow(10,$row_to->precision);
		}
		$ex_to_comission = round($tmp_out_amount-$out_amount,$row_to->precision);
	}
	else{/* case receiver pays */
		if($tmp_arr['fix'] > 0){
			$ex_to_comission = round($tmp_out_amount*$tmp_arr['perc'],$row_to->precision)+$tmp_arr['fix'];
		}
		else{
			$ex_to_comission = round($tmp_out_amount*$tmp_arr['perc'],$row_to->precision);
			if($ex_to_comission==0){
				$ex_to_comission = 1/pow(10,$row_to->precision);
			}
		}
		$out_amount = round($tmp_out_amount-$ex_to_comission,$row_to->precision);
	}
	$result_array['ex_to_com'] = $ex_to_comission;
	$result_array['out_amount'] = $out_amount;

	return $result_array;
}

function CountOut($amount,$from_id,$to_id)
{
	$row_from = mysql_fetch_object(mysql_query("select * from ex_currencies where id = $from_id"));
	$row_to = mysql_fetch_object(mysql_query("select * from ex_currencies where id = $to_id"));
	$row_course = mysql_fetch_object(mysql_query("select * from ex_exchanges where ex_currency1_id = $row_from->id and ex_currency2_id = $row_to->id"));
	
	$result_array = Array();

	$result_array['ex_curr_in_id'] = $from_id;
	$result_array['ex_curr_out_id'] = $to_id;
	$result_array['in_amount'] = $amount;
	
	/*
	counting amount that we get after payment of all comissions	
	*/
	if($row_from->who_pay_comission==0){/* case sender pays */
		$we_get_amount = $amount;
	}
	else{
		$we_get_amount = floor($amount*(1-$row_from->payment_system_comission_perc)*100)/100;
	}
	$result_array['tmp_we_get_amount'] = $we_get_amount;
	/*
	*/
	$result_array['ex_from_com'] = $amount-$we_get_amount;
	/*
	*/
	$result_array['cource'] = GetCourseByExID($row_from->id,$row_to->id);
	/*
	*/
	$result_array['ex_course'] = $row_course->course;
	/*
	*/
	$result_array['out_amount'] = round($amount*$row_course->course,$row_to->precision);
	/*
	counting comission that we will pay while sending money to user
	*/
	if($row_to->who_pay_comission==0){/* case sender pays */
		$ex_to_comission = ceil($result_array['out_amount']*$row_to->payment_system_comission_perc*pow(10,$row_to->precision))/pow(10,$row_to->precision);
	}
	else{
		$ex_to_comission = 0;
	}
	$result_array['ex_to_com'] = $ex_to_comission;
	/*
	counting system income
	*/
	$we_pay_user = $result_array['out_amount'] + $result_array['ex_to_com'];
	
	$real_amount_topay = round($we_get_amount * $result_array['cource'],$row_to->precision);
	
	$result_array['sys_com_to'] = round($real_amount_topay-$we_pay_user,$row_to->precision);
	$result_array['sys_com'] = 	round($result_array['sys_com_to']*GetCourseByExID($row_to->id,$row_from->id),$row_from->precision);
	$result_array['clear_from_amount'] = $we_get_amount-$result_array['sys_com'];	

	return $result_array;
}


function CountIn($amount,$from_id,$to_id)
{
	$row_from = mysql_fetch_object(mysql_query("select * from ex_currencies where id = $from_id"));
	$row_to = mysql_fetch_object(mysql_query("select * from ex_currencies where id = $to_id"));

	$result_array = Array();

	$result_array['ex_curr_in_id'] = $from_id;
	$result_array['ex_curr_out_id'] = $to_id;

	/* amount */
	$amount = round($amount,$row_to->precision);
	$result_array['out_amount'] = $amount;
	$out_amount = $amount;

	$tmp_arr = CountToCom($row_to->metal_id>0?$out_amount/GetMetalPrice($row_to->metal_id):$out_amount,$row_to->code);

	/* send sum depends on who pays comission */
	if($row_to->who_pay_comission==0){/* case sender pays */
		if($tmp_arr['fix'] > 0){
			$tmp_out_amount = round($out_amount*(1+$tmp_arr['perc'])+$tmp_arr['fix'],$row_to->precision);
		}
		else{
			$tmp_out_amount = ceil($out_amount*(1+$tmp_arr['perc'])*pow(10,$row_to->precision))/pow(10,$row_to->precision);
		}
		$ex_to_comission = round($tmp_out_amount-$out_amount,$row_to->precision);
	}
	else{/* case receiver pays */
		if($tmp_arr['fix'] > 0){
			$tmp_out_amount = round($out_amount/(1-$tmp_arr['perc']),$row_to->precision)+$tmp_arr['fix'];
		}
		else{
			$tmp_out_amount = round($out_amount/(1-$tmp_arr['perc']),$row_to->precision)+$tmp_arr['fix'];
			if($tmp_out_amount==$out_amount){
				$tmp_out_amount += 1/pow(10,$row_to->precision);
			}
		}
		$ex_to_comission = round($tmp_out_amount-$out_amount,$row_to->precision);
	}
	$result_array['ex_to_com'] = $ex_to_comission;
	$result_array['tmp_out_amount'] = $tmp_out_amount;

	$result_array['cource'] = GetCourseByExID($row_from->id,$row_to->id);
	$tmp_amount = round($tmp_out_amount*GetCourseByExID($row_to->id,$row_from->id),$row_from->precision);

	$result_array['clear_from_amount'] = $tmp_amount;


	/* SYSTEM COMISSION */
	$row = mysql_fetch_object(mysql_query("select * from ex_exchanges where ex_currency1_id = $row_from->id and ex_currency2_id = $row_to->id"));

	if($row->sys_comission_fix > 0){
		$tmp_amount2 = round($tmp_amount/(1-$row->sys_comission_perc),$row_from->precision)+$row->sys_comission_fix;
	}
	else{
		$tmp_amount2 = round($tmp_amount/(1-$row->sys_comission_perc),$row_from->precision)+$row->sys_comission_fix;
		if($tmp_amount2==$tmp_amount){
			$tmp_amount2 += 1/pow(10,$row_from->precision);
		}
	}
	$result_array['tmp_we_get_amount'] = $tmp_amount2;
	$sys_comission = round($tmp_amount2-$tmp_amount,$row_from->precision);
	$tmp_amount = $tmp_amount2;

	$result_array['sys_com'] = $sys_comission;

	//	$tmp_arr = CountToCom($row_from->metal_id>0?$amount/GetMetalPrice($row_from->metal_id):$tmp_amount,$row_from->code);

	// comission
	if($tmp_arr['fix'] > 0){
	$amount = round($tmp_amount*(1+$tmp_arr['perc'])+$tmp_arr['fix'],$row_from->precision);
	}
	else{
	$amount = ceil($tmp_amount*(1+$tmp_arr['perc'])*pow(10,$row_from->precision))/pow(10,$row_from->precision);
	}

	if($tmp_amount == $amount){
	$amount += 0.01;
	}

	// IN THIS VESRION NO IN COMISSION
//	$amount = $tmp_amount;

	//$ex_from_comission = 0;//round($amount-$tmp_amount,$row_from->precision);
	$ex_from_comission = round($amount-$tmp_amount,$row_from->precision);

	$result_array['ex_from_com'] = $ex_from_comission;
	$result_array['in_amount'] = $amount;

	return $result_array;
}


function GetTransferFromComission($amount,$curr_code){
	$res = CountFromCom($amount,$curr_code);
	$com = ceil(($amount*$res['perc'] + $res['fix'])*100)/100 + 0;
	if($com == 0){
		$com = 0.01;
	}

	return $com;
}

function GetTransferToComission($amount,$curr_code){
	/* EGOLD */
	if($curr_code=="EGOLD"||$curr_code=="EPALLADIUM"||$curr_code=="EPLATINUM"||$curr_code=="ESILVER"){
		return 0;
	}


	$res = CountToCom($amount,$curr_code);
	$com = ceil(($amount*$res['perc'] + $res['fix'])*100)/100 + 0;
	if($com == 0){
		$com = 0.01;
	}

	return $com;
}

function CountFromCom($amount,$curr){/* amount = metal_amount case metals*/
	$res = Array();

	$curr_row = mysql_fetch_object(mysql_query("select * from ex_currencies where code='$curr'"));
	$com_row = mysql_fetch_object(mysql_query("select * from ex_currency_comissions where ex_currency_id=$curr_row->id and (($amount>=amount_from and $amount<amount_to) or ($amount>=amount_from and amount_to=0))"));

	if($com_row->id==0){
		$res['perc'] = 0;
		$res['fix'] = 0.01;
	}
	else{
		$res['perc'] = $com_row->perc+0;
		$res['fix'] = round($com_row->fix*($curr_row->metal_id>0?GetMetalPrice($curr_row->metal_id):1),$curr_row->precision);
	}
	return $res;
}

function CountToCom($amount,$curr){/* amount = metal_amount case metals*/
	$res = Array();

	$curr_row = mysql_fetch_object(mysql_query("select * from ex_currencies where code='$curr'"));
	$com_row = mysql_fetch_object(mysql_query("select * from ex_currency_comissions where ex_currency_id=$curr_row->id and (($amount>=amount_from and $amount<amount_to) or ($amount>=amount_from and amount_to=0))"));

	if($com_row->id==0){
		$res['perc'] = 0;
		$res['fix'] = 0.01;
		return $res;
	}
	else{
		$res['perc'] = $com_row->perc+0;
		$res['fix'] = $com_row->fix+0;
	}

	$tmp_amount = ($amount+$res['fix'])/(1-$res['perc']);

	/* checking if tmp_amount is from the same diapason*/
	$tmp_com_row = mysql_fetch_object(mysql_query("select * from ex_currency_comissions where ex_currency_id=$curr_row->id and (($tmp_amount>=amount_from and $tmp_amount<amount_to) or ($tmp_amount>=amount_from and amount_to=0))"));

	if($com_row->id==0){
		$res['fix'] = round($res['fix']*($curr_row->metal_id>0?GetMetalPrice($curr_row->metal_id):1),$curr_row->precision);
		return $res;
	}
	else{
		$res['perc'] = $tmp_com_row->perc+0;
		$res['fix'] = round($tmp_com_row->fix*($curr_row->metal_id>0?GetMetalPrice($curr_row->metal_id):1),$curr_row->precision);
	}

	return $res;
}

/* this function completes exchange */
function CompleteExchange($order_id){
	$query = "select orders.*, ex_currencies.id as curr_id, ex_currencies.code as curr_code, ex_currencies.type as curr_type, ex_currencies.transfare_type as curr_tr_type, ex_currencies.pincode_collection_id as pin_coll_id, `ex_currencies`.`precision` from orders right outer join ex_currencies on orders.ex_currency_to_id = ex_currencies.id where orders.id=$order_id";
	$row = @mysql_fetch_object(@mysql_query($query));

	//echo $query;
	//exit;

	if($row->status==1&&$row->from_status==0&&$row->to_status==1){
		if (($row->partner_id > 0) && (is_numeric($row->partner_id)))
		{
			$partner_transaction = array(
			'partner_id' => $row -> partner_id,
			'amount' => $row -> partner_amount,
			'currency_id' => $row -> partner_currency_id,
			'comments' => "Комиссия с обмена",
			'order_id' => $row -> id,
			//'allow_recursion' => 1
			);
			if (MakePartnerTransaction($partner_transaction))
			{

			}
		}

		/* START WEBMONEY */
		if($row->curr_code=="WMR"||$row->curr_code=="WMZ"||$row->curr_code=="WME"||$row->curr_code=="WMU"){

			$amount = round($row->amount_to,2);

			$to_order_row = @mysql_fetch_object(@mysql_query("select * from wm_orders where id=$row->to_order_id"));

			if(($trans_id=WMTransfer($amount,$to_order_row->payer_purse,$to_order_row->payee_purse,$to_order_row->id,"Exchange operation $row->id.")) > 0){
				@mysql_query("update wm_orders set status = 0, sys_trans_no = '$trans_id' where id=$row->to_order_id");
				@mysql_query("update orders set to_status = 0, status=0, batch_to = '$trans_id' where id = $row->id");

				$comments = "Зачисление средств на кошелек $to_order_row->payee_purse. Операция обмена # $row->id.";
				ChangeBalance($row->ex_currency_to_id,(0-$amount-$row->ex_currency_to_comission),$comments);


				//MakePartnerTrancastion
				/*sending e-mail to user*/
				if($row->email!=""){
					@SendOrderCompleteEmail($row->id);
				}

				return true;
			}
		}/* END WEBMONEY */
		elseif($row->curr_code == "EGOLD"||$row->curr_code == "ESILVER"||$row->curr_code == "EPLATINUM"||$row->curr_code == "EPALLADIUM"){/* EGOLD START */

			$amount = round($row->amount_to+$row->ex_currency_to_comission,2);

			$to_order_row = @mysql_fetch_object(@mysql_query("select * from egold_orders where id=$row->to_order_id"));

			if($row->curr_code == "EGOLD"){
				$metal = "Gold";
			}
			elseif($row->curr_code == "ESILVER"){
				$metal = "Silver";
			}
			elseif($row->curr_code == "EPLATINUM"){
				$metal = "Platinum";
			}
			elseif($row->curr_code == "EPALLADIUM"){
				$metal = "Palladium";
			}

			$desc = $SETTINGS['site_name']." exchange operation # $row->id.";
			if(($res_arr=EGoldTransfer($to_order_row->id,$amount,$to_order_row->payee_account,$metal,$desc))){
				@mysql_query("update egold_orders set status = 0, payment_metal_id = '".$res_arr['PAYMENT_METAL_ID']."', payment_batch_num = '".$res_arr['PAYMENT_BATCH_NUM']."', actual_payment_ounces = '".$res_arr['ACTUAL_PAYMENT_OUNCES']."', usd_per_ounce = '".$res_arr['USD_PER_OUNCE']."',feeweight  = '".$res_arr['PAYMENT_FEE_OUNCES']."', timestampgmt  = '".time()."'  where id=$row->to_order_id");


				@mysql_query("update orders set to_status = 0, status=0, batch_to = '".$res_arr['PAYMENT_BATCH_NUM']."',metal_amount_to = '".(round(($res_arr['ACTUAL_PAYMENT_OUNCES']-$res_arr['PAYMENT_FEE_OUNCES'])*31.1034768,6))."', metal_ex_currency_to_comission = '".(round($res_arr['PAYMENT_FEE_OUNCES']*31.1034768,6))."' where id = $row->id");

				$comments = "Зачисление средств на EGold счет $to_order_row->payee_account. Операция обмена # $row->id.";

				ChangeBalance($row->ex_currency_to_id,(0-(round(($res_arr['ACTUAL_PAYMENT_OUNCES']-$res_arr['PAYMENT_FEE_OUNCES'])*31.1034768,6))),$comments);

				/*sending e-mail to user*/
				if($row->email!=""){
					@SendOrderCompleteEmail($row->id);
				}

				return true;
			}

		}/* E-GOLD END */
		elseif($row->curr_code == "EPD"){/* EPORT START */

			$amount = round($row->amount_to,$row->precision);

			$to_order_row = @mysql_fetch_object(@mysql_query("select * from eport_orders where id=$row->to_order_id"));

			$desc = $SETTINGS['site_name']." exchange operation # $row->id.";
			if(($res_arr=EPortTransfer($to_order_row->id,$amount,$to_order_row->payee_account,$desc))){

				@mysql_query("update eport_orders set status = 0, eport_order_id = '".$res_arr['eport_order']."'  where id=$row->to_order_id");

				@mysql_query("update orders set to_status = 0, status=0, batch_to = '".$res_arr['eport_order']."' where id = $row->id");

				$comments = "Зачисление средств на E-Port счет $to_order_row->payee_account. Операция обмена # $row->id.";

				ChangeBalance($row->ex_currency_to_id,(0-$amount),$comments);

				/*sending e-mail to user*/
				if($row->email!=""){
					@SendOrderCompleteEmail($row->id);
				}

				return true;
			}

		}/* E-GOLD END */
		elseif($row->curr_code == "YMR"||$row->curr_code == "PCE"||$row->curr_code == "PCD"||$row->curr_code == "PCH"||$row->curr_code == "PCL"){/* START YANDEX ORDERS */

			if($row->curr_code=="YMR"){
				$curr_code="RUR";
			}
			elseif($row->curr_code=="PCE"){
				$curr_code="EUR";
			}
			elseif($row->curr_code=="PCD"){
				$curr_code="USD";
			}
			elseif($row->curr_code=="PCH"){
				$curr_code="UAH";
			}
			elseif($row->curr_code=="PCL"){
				$curr_code="LVL";
			}

			$amount = round($row->amount_to+$row->ex_currency_to_comission,2);

			$to_order_row = @mysql_fetch_object(@mysql_query("select * from yandex_orders where id=$row->to_order_id"));

			$desc = $SETTINGS['site_name']." exchange operation # $row->id.";
			if(($res_arr=YMTransfer($to_order_row->id,$to_order_row->payee_account,$amount,$desc,$curr_code))){

				@mysql_query("update yandex_orders set status = 0, paymentid = '".$ResultParams["PayOrderID"]."' where id=$row->to_order_id");


				@mysql_query("update orders set to_status = 0, status=0, batch_to = '".$ResultParams["PayOrderID"]."' where id = $row->id");

				$comments = "Зачисление средств на YANDEX счет $to_order_row->payee_account. Операция обмена # $row->id.";

				ChangeBalance($row->ex_currency_to_id,(0-$amount),$comments);

				/*sending e-mail to user*/
				if($row->email!=""){
					@SendOrderCompleteEmail($row->id);
				}

				return true;
			}

		}
		/* END YANDEX ORDERS */
		elseif($row->curr_type == "pincode")
		{
			$res = mysql_query("select * from pincodes where collection_id=$row->pin_coll_id and status='valid'");

			if(mysql_num_rows($res) <= 0)
			{
				return array("messages"=>array("Нет действительных ПИН-кодов!"));
			}

			$pincodes = array();
			while($pincode = mysql_fetch_object($res))
			{
				$pincodes[] = $pincode;
			}

			$key = array_rand($pincodes);
			$pincode = $pincodes[$key];

			$code = $pincode->code;

			@mysql_query("update pincodes set status='used' where id=$pincode->id");

			@mysql_query("update orders set to_status=0, status=0 where id=$row->id");
			@mysql_query("update pincode_orders set status=0, pincode='$code' where id=$row->to_order_id");

			$collection = @mysql_fetch_object(@mysql_query("select * from pincode_collections where id=$row->pin_coll_id"));
			$res = @mysql_fetch_object(@mysql_query("select count(*) as pincount from pincodes where status='valid' and collection_id=$row->pin_coll_id"));
			$pincount = (integer)$res->pincount;

			@mysql_query("update ex_currencies set amount='".$pincount*$collection->sell_price."' where id=$row->ex_currency_to_id");

			@mail($row->email, "ПИН-код (обмен $row->id:$row->from_order_id-$row->to_order_id", "Здравствуйте, ваш ПИН-код ($collection->name): $code");

			return true;
		}
		elseif($row->curr_tr_type == "manual")
		{
			@mysql_query("update orders set to_status=0, status=0 where id=$row->id");
			@mysql_query("update manual_orders set status=0 where id=$row->to_order_id");

			$comments = "Зачисление средств. Операция обмена # $row->id.";
			ChangeBalance($row->ex_currency_to_id,(0-$amount),$comments);

			return true;
		}
	}
	return false;
}

function ChangeBalance($ex_curr_id,$amount,$comments){
	global $SUPPORT_EMAIL;

	if(($amount+0)!=0){
		$row = @mysql_fetch_object(@mysql_query("select * from ex_currencies where id=$ex_curr_id"));
		if(round($row->amount+$amount,6)>=0){
			$query = "INSERT INTO `balance_history` (`ex_currency_id` , `change_amount` , `comments` , `balance` , `date` ) VALUES ('$ex_curr_id', '$amount', '".addslashes($comments)."', '".round($row->amount+$amount,6)."', '".time()."');";
			mysql_query($query);
			mysql_query("update ex_currencies set amount=".round($row->amount+$amount,6)." where id=$ex_curr_id");

			return true;
		}
		else{
			$msg = "Здравствуйте!\n\nПопытка сделать отрицательный баланс!\n\nВалюта: $row->name\nБаланс: $row->amount\nИзменение: $amount\nКомментарий: $comments";
			@mail($SUPPORT_EMAIL,"Ошибка при изменении баланса!",$msg,"From:".$SETTINGS['site_name']." System<$SUPPORT_EMAIL>");
		}
	}
	return false;
}



/* SENDING E-MAILS */
function SendEMail($email,$subject,$msg,$from){
	$headers  = "From: $from\r\n";
	$headers .= "Reply-To: $from\r\n";
	$headers .= "Content-type: text/plain; charset=windows-1251\r\n";
	@mail($email,$subject,$msg,$headers);
}

function SendOrderCompleteEmail($order_id){
	global $EMAIL_SIGNATURE;
	global $SUPPORT_EMAIL;
	global $MONTH_RUS;
	global $SITE_URL;

	$query = "select orders.*, ex_currencies.code as from_code, curr2.code as to_code, ex_currencies.name as from_name, curr2.name as to_name from (orders left outer join ex_currencies on ex_currencies.id = orders.ex_currency_from_id) left outer join ex_currencies curr2 on curr2.id = orders.ex_currency_to_id where orders.id=$order_id";


	$row = @mysql_fetch_object(@mysql_query($query));

	$tmp_row = @mysql_fetch_object(@mysql_query("select * from hashes where owner_id=$order_id and type=1"));
	$hash = $tmp_row->hash;

	$date = getdate($row->regdate);
	$day = $date['mday'];
	$month = $date['mon'];
	$year = $date['year'];
	$h = $date['hours'];
	$m = $date['minutes'];
	$s = $date['seconds'];
	$year = $date['year'];

	$date = $day." ".$MONTH_RUS[$month-1]." ".$year." ".$h.":".$m.":".$s;


	$headers  = "From: Обменный пункт ".$SETTINGS['site_name']."<$SUPPORT_EMAIL>\r\n";
	$headers .= "Reply-To: $SUPPORT_EMAIL\r\n";
	$headers .= "Content-type: text/plain; charset=windows-1251\r\n";

	$msg = 'Здравствуйте!

Операция обмена в системе '.$SETTINGS['site_name'].' прошла успешно! Проверьте Ваш '.$row->to_name.'
счет, пожалуйста. На него должны быть присланы деньги от '.$SETTINGS['site_name'].'.

Параметры операции
------------------------------------------------------
Номер #: '.$order_id.'
Вы отдали(с учетом всех комиссий): '.($row->amount_from+0).' '.$row->from_name.'
Вы получили: '.($row->amount_to+0).' '.$row->to_name.'
Дата: '.$date.'
------------------------------------------------------

Информацию о данной операции обмена всегда доступна по ссылке
'.$SITE_URL.'/order_info.php?order_id='.$order_id.'&hash='.$hash.'

В случае возникновения вопросов, связанных с данной операцией
обмена, свяжитесь со службой поддержки, пожалуйста. Не забудде
указать номер операции.'.$EMAIL_SIGNATURE;

	@mail($row->email,"Операция обмена # $order_id",$msg,$headers);
}


/* TAKING MONEY FROM USER*/

function GenPurchaseForm($order_id){
	global $WM;
	global $YM;
	global $EGOLD;
	global $EPORT;
	global $SITE_URL;

	/*DEMO VERSION*/
	$html = '<form method="POST" action="./demo_exchange.php">
	<input type="hidden" name="order_id" value="'.$order_id.'">
	<table>
			<tr>
				<td><input type="button" class="button1" value="< Назад" onClick="history.go(-1)" title="Вернуться назад"></td>
				<td width=5>&nbsp;</td>
				<td><input type="submit" value="Оплатить и получить!" class="button1" title="Перейти к оплате"></td>

			</tr>
	</table>
	</form>
	';
	/*END DEMO*/

	$html="";

	$query = "select orders.*, ex_currencies.code as curr_code from orders left outer join ex_currencies on orders.ex_currency_from_id = ex_currencies.id where orders.id = $order_id";
	//	echo $query;
	$row = mysql_fetch_object(mysql_query($query));

	if($row->curr_code == "WMR"||$row->curr_code == "WMZ"||$row->curr_code == "WME"||$row->curr_code=="WMU"){
		if($row->curr_code == "WMR"){
			$purse = $WM['r_purse'];
		}
		elseif($row->curr_code == "WMZ"){
			$purse = $WM['z_purse'];
		}
		elseif($row->curr_code == "WME"){
			$purse = $WM['e_purse'];
		}
		elseif($row->curr_code == "WMU"){
			$purse = $WM['u_purse'];
		}

		$html = '<form method="POST" action="https://merchant.webmoney.ru/lmi/payment.asp">
	<input type="hidden" name="LMI_PAYMENT_AMOUNT" value="'.($row->amount_from-$row->ex_currency_from_comission+0).'">
	<input type="hidden" name="LMI_PAYMENT_DESC" value="Оплата по счету # '.$row->from_order_id.'">
	<input type="hidden" name="LMI_PAYMENT_NO" value="'.$row->from_order_id.'">
	<input type="hidden" name="LMI_PAYEE_PURSE" value="'.$purse.'">
	<input type="hidden" name="LMI_SIM_MODE" value="0">
	<table>
			<tr>
				<td><input type="button" class="button1" value="< Назад" onClick="history.go(-1)" title="Вернуться назад"></td>
				<td width=5>&nbsp;</td>
				<td><input type="submit" value="Оплатить и получить!" class="button1" title="Перейти к оплате"></td>

			</tr>
	</table>
	</form>
	';

	}
	elseif($row->curr_code == "EGOLD"||$row->curr_code == "ESILVER"||$row->curr_code == "EPLATINUM"||$row->curr_code == "EPALLADIUM"){
		if($row->curr_code == "EGOLD"){
			$metal_id = 1;
		}
		elseif($row->curr_code == "ESILVER"){
			$metal_id = 2;
		}
		elseif($row->curr_code == "EPLATINUM"){
			$metal_id = 3;
		}
		elseif($row->curr_code == "EPALLADIUM"){
			$metal_id = 4;
		}

		$html = '<form action="https://www.e-gold.com/sci_asp/payments.asp" method="POST">
<input type="hidden" name="PAYEE_ACCOUNT" value="'.$EGOLD['id'].'">
<input type="hidden" name="PAYEE_NAME" value="'.$SETTINGS['site_name'].' Exchanger">
<input type="hidden" name="PAYMENT_AMOUNT" value="'.$row->amount_from.'">
<input type="hidden" name="PAYMENT_UNITS" value="1">
<input type="hidden" name="PAYMENT_METAL_ID" value="'.$metal_id.'">
<input type="hidden" name="PAYMENT_ID" value="'.$row->from_order_id.'">
<input type="hidden" name="STATUS_URL"  value="'.$SITE_URL.'/scripts/egold.php">
<input type="hidden" name="PAYMENT_URL" value="'.$SITE_URL.'/success.php">
<input type="hidden" name="NOPAYMENT_URL" value="'.$SITE_URL.'/fail.php">
<input type="hidden" name="BAGGAGE_FIELDS" value="">
<input type="hidden" name="SUGGESTED_MEMO" value="'.$SETTINGS['site_name'].' exchange operation # '.$order_id.'">
	<table>
			<tr>
				<td><input type="button" class="button1" value="< Назад" onClick="history.go(-1)" title="Вернуться назад"></td>
				<td width=5>&nbsp;</td>
				<td><input type="submit" value="Оплатить и получить!" class="button1" title="Перейти к оплате"></td>

			</tr>
	</table>
</form>
';

	}
	elseif($row->curr_code=="EPD"){
		$html = '<form action="https://www.e-port.ru/epos/payment_simple.cp" method="GET">
			<input type="hidden" name="ID" value="'.$EPORT['shop_id'].'">
			<input type="hidden" name="SumEYE" value="'.($row->amount_from-$row->ex_currency_from_comission+0).'">
			<input type="hidden" name="ShopOrderID" value="'.$row->from_order_id.'">
			<input type="hidden" name="DESC" value="Payment # '.$row->from_order_id.'">
			<input type="hidden" name="ReturnURL" value="'.$SITE_URL.'/success.php">
			<table>
			<tr>
				<td><input type="button" class="button1" value="< Назад" onClick="history.go(-1)" title="Вернуться назад"></td>
				<td width=5>&nbsp;</td>
				<td><input type="submit" value="Оплатить и получить!" class="button1" title="Перейти к оплате"></td>
			</tr>
	</table>

		
		</form>';
	}
	elseif($row->curr_code == "YMR"||$row->curr_code == "PCE"||$row->curr_code == "PCD"||$row->curr_code == "PCH"||$row->curr_code == "PCL"){

		if($row->curr_code == "YMR"){
			$curr_code = "rur";
		}
		elseif($row->curr_code == "PCE"){
			$curr_code = "eur";
		}
		elseif($row->curr_code == "PCD"){
			$curr_code = "usd";
		}
		elseif($row->curr_code == "PCH"){
			$curr_code = "uah";
		}
		elseif($row->curr_code == "PCL"){
			$curr_code = "lvl";
		}

		parse_str($YM[$curr_code.'_pay_link'], $Array);
		$fields = "";
		foreach($Array as $key=>$value)
		$fields .= "<input type=\"hidden\" name=\"$key\" value=\"$value\">\n";

		srand((double)microtime()*1000000);
		$rnd = md5(rand(0,9999999)); // random param to prevent cash

		$html = '<form method="POST" action="http://127.0.0.1:8129/wallet">
			'.$fields.'
	     <input type="hidden" name="shop_order_id" value="'.$row->from_order_id.'">
		 <input type="hidden" name="rnd" value="'.$rnd.'">
		 &nbsp;<font color="red">Убедитесь, что Ваш Яндекс кошелек запущен!</font>	
		 <table>
			<tr>
				<td><input type="button" class="button1" value="< Назад" onClick="history.go(-1)" title="Вернуться назад"></td>
				<td width=5>&nbsp;</td>
				<td><input type="submit" value="Оплатить и получить!" class="button1" title="Перейти к оплате"></td>
			</tr>
		</table>
		 </form>';
	}


	return $html;
}

function UpdateAmountInfo($ex_curr_id){
	global $SUPPORT_EMAIL;
	global $WM;
	$row = mysql_fetch_object(mysql_query("select * from ex_currencies where id=$ex_curr_id and status=1"));

	$amount = -1;
	if($row->code == "WMR"){
		$arr = WMGetAmount($WM['id']);
		$amount = $arr[$WM['r_purse']];
	}
	elseif($row->code == "WMZ"){
		$arr = WMGetAmount($WM['id']);
		$amount = $arr[$WM['z_purse']];
	}
	elseif($row->code == "WME"){
		$arr = WMGetAmount($WM['id']);
		$amount = $arr[$WM['e_purse']];
	}
	elseif($row->code == "WMU"){
		$arr = WMGetAmount($WM['id']);
		$amount = $arr[$WM['u_purse']];
	}
	elseif($row->code == "EGOLD"){
		$arr = EGoldGetAmount();
		if($arr){
			$amount = $arr['gold_grams']+0;
		}
	}
	elseif($row->code == "ESILVER"){
		$arr = EGoldGetAmount();
		if($arr){
			$amount = $arr['silver_grams']+0;
		}
	}
	elseif($row->code == "EPLATINUM"){
		$arr = EGoldGetAmount();
		if($arr){
			$amount = $arr['platinum_grams']+0;
		}
	}
	elseif($row->code == "EPALLADIUM"){
		$arr = EGoldGetAmount();
		if($arr){
			$amount = $arr['palladium_grams']+0;
		}
	}
	elseif($row->code == "YMR"){
		$amount = YMGetAmount("RUR");
	}
	elseif($row->code == "PCD"){
		$amount = YMGetAmount("USD");
	}
	elseif($row->code == "PCE"){
		$amount = YMGetAmount("EUR");
	}
	elseif($row->code == "PCH"){
		$amount = YMGetAmount("UAH");
	}
	elseif($row->code == "PCL"){
		$amount = YMGetAmount("LVL");
	}

	if(is_numeric($amount)&&$amount>=0){
		$diff = round($amount - $row->amount,6)+0;

		if($diff!=0){
			$comments = "Синхронизация баланса $row->name с реальным счетом.";
			ChangeBalance($ex_curr_id,$diff,$comments);
			$msg = "Здравствуйте!\n\nОшибка при синхронизации счетов, данные различаются.\n\nВалюта: $row->name\nНа ".$SETTINGS['site_name']." счету: ".($row->amount+0)."\nНа реальном счету: $amount\nРазница: $diff\n";

			@mail($SUPPORT_EMAIL,"Данные на реальном и виртуальном счетах различаются!",$msg,"From:".$SETTINGS['site_name']." System<$SUPPORT_EMAIL>");
		}
		return true;
	}
	return false;
}

/* START WEBMONEY FUNCTIONS */
require_once(dirname(__FILE__) . '/wmsystem.class.php');
function WMSign($inStr){
	global $WM;

	$tmp=tempnam("/tmp","wm");
	$fp = popen($WM['signer_path']." >".$tmp, "w");
	$PlanStr = "$inStr\004\r\n";
	fwrite($fp,$PlanStr);
	pclose($fp);
	$fp=fopen($tmp,"r");
	$s = fgets($fp, 133);
	fclose($fp);
	unlink($tmp);
	return $s;
}


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

function WMendElement($parser, $name){}

function WMcharacterData($parser, $data) {
	global $tmp_xml_res;
	global $xmlTag;
	global $tmp_res_arr;

	if(strtoupper($xmlTag)=="PURSENAME"){
		$tmp_xml_res = strtoupper($data);
	}

	if(strtoupper($xmlTag)=="AMOUNT"){
		if($tmp_xml_res!=""&&$data!=""){
			$tmp_res_arr[$tmp_xml_res] = (trim($data)+0);
		}
		$tmp_xml_res = "";
	}
}



function WMGetAmount($wm_id){
	return WMSystem::getAmount($wm_id);
	/*global $WM;

	global $tmp_res_arr;
	$tmp_res_arr = array();


	$url = "https://w3s.webmoney.ru/asp/XMLPurses.asp";
	$reqn = time();
	$sign = WMSign($wm_id.$reqn);

	$str = "<w3s.request><reqn>$reqn</reqn><wmid>".$WM['id']."</wmid><sign>$sign</sign><getpurses><wmid>$wm_id</wmid></getpurses></w3s.request>";

	//	echo htmlspecialchars($str);

	$xml = @shell_exec("/usr/bin/curl -k -d \"".$str."\" $url");

	if($xml==""){
		return false;
	}

	//	echo htmlspecialchars($xml);

	$xmlTag = "";
	$tmp_xml_res="";

	$xml_parser = xml_parser_create();
	xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
	xml_set_element_handler($xml_parser, "WMstartElement", "WMendElement");
	xml_set_character_data_handler($xml_parser, "WMcharacterData");
	if (!xml_parse($xml_parser, $xml)) {
		return false;
	}
	xml_parser_free($xml_parser);

	return $tmp_res_arr;*/
}

function WMReqn(){
	return mktime();
	/*
	$tm = localtime(time(), 1);

	return (sprintf( "%04d%02d%02d%02d%02d%02d", $tm["tm_year"]+1900, $tm["tm_mon"]+1,
	$tm["tm_mday"], $tm["tm_hour"], $tm["tm_min"], $tm["tm_sec"]
	)+1000000);
	*/
}

function WMTransfer($amount,$purse_from,$purse_to,$order_id,$desc){
	global $WM;
	global $SUPPORT_EMAIL;
	
	return WMSystem::transfer($amount, $purse_from, $purse_to, $order_id, $desc);

	/*
	$reqn = WMReqn();

	$url = "https://w3s.webmoney.ru/asp/Trans.asp?TID=".$order_id."&P=".$purse_from."&C=".$purse_to."&IN=0&A=$amount&D=".urlencode($desc)."&RN=".$reqn."&SS=".WMSign($order_id.$purse_from.$purse_to.$amount.$desc."0".$reqn);

	$res = HttpRequest($url);

	if(substr($res,0,6) == "Error:"){
		$errCode = sprintf("%d", substr($res,6));

		$err = "Неизвестная ошибка";
		if ($errCode == "-6")
		{ $err = "Неверная подпись"; }
		elseif ($errCode == "-5")
		{ $err = "R==uestN задан некорректно"; }
		elseif ($errCode == "-4")
		{ $err = "Неверно задана сумма"; }
		elseif ($errCode == "-3")
		{ $err = "Неверно задан кошелек-приемник"; }
		elseif ($errCode == "-2")
		{ $err = "Неверно задан кошелек-источник"; }
		elseif ($errCode == "-1")
		{ $err = "Неверно задан номер операции"; }
		elseif ($errCode == "5")
		{ $err = "Отправителя средств с указанным идентификатором не существует"; }
		elseif ($errCode == "6")
		{ $err = "Покупателя с указанным идентификатором не существует"; }
		elseif ($errCode == "7")
		{ $err = "Кошелька отправителя средств не существует"; }
		elseif ($errCode == "13")
		{ $err = "Слишком маленькая сумма"; }
		elseif ($errCode == "17")
		{ $err = "Недостаточно денег в кошеле-источнике"; }
		elseif ($errCode == "23")
		{ $err = "Ошибка сервера"; }
		elseif ($errCode == "102")
		{ $err = "Параметр R==uestN меньше или равен предыдущему параметру R==uestN"; }
		elseif ($errCode == "103")
		{ $err = "Операция с таким номером (TID) уже выполнялась"; }
		elseif ($errCode == "110")
		{ $err = "Интерфейс недоступен. ".
		"Этот интерфейс доступен только зарегистированным клиентам. ".
		"Для регистрации свяжитесь по внутренней почте ".
		"с WMID 941977853154 (Техническая поддержка)";}


		$msg = "Здравствуйте!\n\nОшибка при переводе WM.\n\nОшибка: $res $err\nСумма: $amount\nКошелек-источник: $purse_from\nКошелек-получатель: $purse_to\nНомер заказа: $order_id\nОписание: $desc";

		@mail($SUPPORT_EMAIL,"Ошибка при WM переводе!",$msg,"From:".$SETTINGS['site_name']." System<$SUPPORT_EMAIL>");

		return -1;
	}

	if (substr($res,0,9) == "WMTranId:"){
		$wmtrn_id = sprintf("%d", substr($res,9));
		return $wmtrn_id+0;
	}
	return -1;*/
}

function WMCheckOrder($order_id,$wm_order_id,$from_purse){

	$reqn = WMReqn();

	$url = "https://w3s.webmoney.ru/asp/GetTran.asp?CTID=$order_id&WTID=$wm_order_id&P=$from_purse&RN=$reqn&SS=".WMSign($wm_order_id.$order_id.$from_purse.$reqn);

	$res = HttpRequest($url);

	if (substr($res,0,10) == "TranState:"){
		$result = sprintf("%d", substr($res,10));
		if($result > 0 ){
			return true;
		}
	}
	return false;
}

function WMCheckInv($order_id,$inv_id,$store_purse,$user_wm_id){
	global $WM;
	return WMSystem::checkInv($order_id, $inv_id, $store_purse, $user_wm_id);
	/*
	$order_id+=0;
	$inv_id+=0;

	$reqn = WMReqn();

	$url = "https://w3s.webmoney.ru/asp/GetInvState.asp?SL=".$WM['id']."&WN=".$inv_id."&SP=".$store_purse."&CL=".$user_wm_id."&IN=".$order_id."&RN=".$reqn."&SS=".WMSign($order_id.$inv_id.$user_wm_id.$store_purse.$reqn);

	$res = HttpRequest($url);

	if (strtolower(substr($res,0,3)) == "ok:"){
		return true;
	}
	return false;*/
}

function WMCheckPurse($wm_id,$purse){
	global $WM;
	
	return WMSystem::checkPurse($wm_id, $purse);
	/*
	$reqn = WMReqn();

	$url = "https://w3s.webmoney.ru/asp/TestPurse.asp?S=".$WM['id']."&I=".$wm_id."&P=".$purse."&RN=".$reqn."&SS=".WMSign($WM['id'].$wm_id.$purse.$reqn);

	$res = HttpRequest($url);

	if (strtolower(substr($res,0,7)) == "result:"){
		$result = sprintf("%d", substr($res,7));
		if($result == 2 ){
			return true;
		}
	}
	return false;
	*/
}

/* END WEBMONET FUNCTIONS   */

/* START EGOLD FUNCTIONS */
function EGoldGetAmount(){
	global $EGOLD;

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "https://www.e-gold.com/acct/balance.asp");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS,"AccountID=".$EGOLD['id']."&PassPhrase=".$EGOLD['pass']);
	$result = curl_exec($ch);
	curl_close($ch);


	preg_match_all("/<input[^>]+>/",$result,$arr);

	$res_arr = array();

	for($i=0; $i < sizeof($arr[0]);$i++){
		preg_match("/name=([0-9A-Za-z_]+)/",$arr[0][$i],$attr);
		preg_match('/value="(.*)"/',$arr[0][$i],$val);
		$key = $attr[1];
		$value = $val[1];

		if(strtolower($key)=="error"){
			return false;
		}
		else{
			$res_arr[strtolower($key)] = $value+0;
		}
	}

	return $res_arr;
}

function EGoldGetCurrencyValue($metal_id,$amount,$curr_code="USD"){
	$row = mysql_fetch_object(mysql_query("select * from metals where id=$metal_id"));

	if($curr_code=="USD"){
		if($row->code=="GOLD"){
			return round($amount*round(GetMetalPrice($metal_id),3)*100)/100;
		}
		if($row->code=="SILVER"){
			return round($amount*round(GetMetalPrice($metal_id),5)*100)/100;
		}
		if($row->code=="PLATINUM"){
			return round($amount*round(GetMetalPrice($metal_id),3)*100)/100;
		}
		if($row->code=="PALLADIUM"){
			return round($amount*round(GetMetalPrice($metal_id),4)*100)/100;
		}
	}
}

function EGoldCheckInv($order_id,$amount){

	global $EGOLD;
	global $SUPPORT_EMAIL;

	$s_date = getdate(time() - 3600*24);
	$e_date = getdate(time() + 3600*24);

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "https://www.e-gold.com/acct/historycsv.asp");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS,"AccountID=".$EGOLD['id']."&PassPhrase=".$EGOLD['pass']."&paymentidfilter=$order_id&startmonth=".$s_date["mon"]."&startday=".$s_date["mday"]."&startyear=".$s_date["year"]."&endmonth=".$e_date["mon"]."&endday=".$e_date["mday"]."&endyear=".$e_date["year"]."&paymentsreceived=1");
	$result = curl_exec($ch);
	curl_close($ch);

	//	$msg = "$result -- $order_id, $amount";
	//	@mail($SUPPORT_EMAIL,"Проверка", $msg,"From:".$SETTINGS['site_name']." System<$SUPPORT_EMAIL>");

	$tmp = explode("\n",$result);
	$arr = explode(",",$tmp[1]);

	if(($arr[7]+0)==($amount+0)&&strtolower($arr[8])=='"usd"'){
		return true;
	}
	else{
		return false;
	}
}

function EGoldCheckOrder($order_id,$amount){

	global $EGOLD;
	global $SUPPORT_EMAIL;

	$s_date = getdate(time() - 3600*24);
	$e_date = getdate(time() + 3600*24);

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "https://www.e-gold.com/acct/historycsv.asp");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS,"AccountID=".$EGOLD['id']."&PassPhrase=".$EGOLD['pass']."&paymentidfilter=$order_id&startmonth=".$s_date["mon"]."&startday=".$s_date["mday"]."&startyear=".$s_date["year"]."&endmonth=".$e_date["mon"]."&endday=".$e_date["mday"]."&endyear=".$e_date["year"]."&paymentsmade=1");
	$result = curl_exec($ch);
	curl_close($ch);

	//	echo $result;

	//	$msg = "$result -- $order_id, $amount";
	//	@mail($SUPPORT_EMAIL,"Проверка", $msg,"From:ExChanger System<$SUPPORT_EMAIL>");

	$tmp = explode("\n",$result);
	$arr = explode(",",$tmp[1]);

	if(($arr[7]+0)==$amount&&strtolower($arr[8])=='"usd"'){
		return true;
	}
	else{
		return false;
	}
}


function EGoldTransfer($order_id,$amount,$account,$metal_name,$desc){

	global $EGOLD, $SUPPORT_EMAIL;
	global $BILLING_EMAIL, $ROBOT_SIGN;

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "https://www.e-gold.com/acct/confirm.asp");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS,"AccountID=".$EGOLD['id']."&PassPhrase=".$EGOLD['pass']."&Payee_Account=$account&Amount=$amount&PAY_IN=1&WORTH_OF=".$metal_name."&Memo=".urlencode($desc)."&ACTUAL_PAYMENT_OUNCES=&IGNORE_RATE_CHANGE=Y&PAYMENT_ID=$order_id");
	$result = curl_exec($ch);
	curl_close($ch);

	//	echo $result;

	preg_match_all("/<input[^>]+>/",$result,$arr);

	$res_arr = array();

	for($i=0; $i < sizeof($arr[0]);$i++){
		preg_match("/name=([0-9A-Za-z_]+)/",$arr[0][$i],$attr);
		preg_match('/value="(.*)"/',$arr[0][$i],$val);
		$key = $attr[1];
		$value = $val[1];

		if(strtolower($key)=="error")
		{
			$_SESSION["EGOLD_ERROR"] = $value;
			
			$msg = "Здравствуйте!\n\nОшибка при переводе EGOLD.\n\nОшибка: $value\nСумма: $amount\nСчет-отправитель: ".$EGOLD['id']."\nСчет-получатель: $account\nНомер заказа: $order_id\nОписание: $desc";

			@mail($SUPPORT_EMAIL,"Ошибка при EGOLD переводе!",$msg,"From:".$SETTINGS['site_name']." System<$SUPPORT_EMAIL>");

			return false;
		}
		$res_arr[$key] = $value;
	}

	return $res_arr;
}

/* END EGOLD FUNCTIONS */

/* START EPORT FUNCTIONS */
function EPortTransfer($order_id,$amount,$account,$desc){
	global $EPORT, $SUPPORT_EMAIL;
	global $BILLING_EMAIL, $ROBOT_SIGN;

	list($from_acc1,$from_acc2) = explode("-",$EPORT['account']);
	list($to_acc1,$to_acc2) = explode("-",$account);

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "https://www.e-port.ru/add/transfer.cp");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch, CURLOPT_POST, 1);
	$post_str = "AddSerialNumber=$from_acc1&AddCardNumber=$from_acc2&AddCardPin=".$EPORT['account_pin']."&Sum=$amount&OK=1&SerialNumber=$to_acc1&CardNumber=$to_acc2";

	curl_setopt($ch, CURLOPT_POSTFIELDS,$post_str);
	$result = convert_cyr_string(curl_exec($ch),"k","w");
	curl_close($ch);

	//	echo $result;

	$res_arr = array();

	preg_match("/<b>[ ]*Номер заказа:<\/b>[ ]*([0-9]+)/",$result,$arr);
	$res_arr['eport_order'] = $arr[1];

	preg_match("/<b>[ ]*Дата, время операции:<\/b>[ ]*([0-9.: ]+)/",$result,$arr);
	$res_arr['eport_time'] = trim($arr[1]);

	preg_match("/<b>[ ]*Комиссия Системы <span class=tm>e-port<\/span>:<\/b>[ ]*([0-9.]+)/",$result,$arr);
	$res_arr['eport_comission'] = $arr[1];

	if($res_arr['eport_order']==""){
		return false;
	}

	return $res_arr;
}

function EPortCheckInv($order_id,$amount,$type="status"){
	global $EPORT;
	global $SUPPORT_EMAIL;

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "https://www.e-port.ru/epos/report.cp");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS,"ID=".$EPORT['shop_id']."&login=".$EPORT['shop_login']."&password=".$EPORT['shop_pass']."&ShopOrderID=$order_id");
	$result = curl_exec($ch);
	curl_close($ch);

	$fields = explode("\n",$result);
	$sum = explode(" ",$fields[3]);
	$sum_eye = (int)(($sum[1]+0)*1000000);
	$amount = (int)($amount*1000000);

	if(strtolower($fields[0])=="payed yes"&&strtolower($fields[6])=="testmode 0"&&($sum_eye==$amount)){
		if($type=="status"){
			return true;
		}
		else{
			$res_arr = Array();
			$res_arr['order_id'] = $order_id;
			$res_arr['amount'] = $amount;

			$tmp = explode(" ",$fields[1]);
			$res_arr['eport_order_id'] = $tmp[1];

			$tmp = explode(" ",$fields[3]);
			$res_arr['sum_eye'] = $tmp[1];

			$tmp = explode(" ",$fields[4]);
			$res_arr['sum_rur'] = $tmp[1];

			$tmp = explode(" ",$fields[5]);
			$res_arr['pay_date'] = $tmp[1];

			return $res_arr;
		}
	}
	else{
		$msg = "Здравствуйте!\n\nОшибка при повторной проверке оплаты в EPORT ФУНКЦИИ.\nЗаказ # ".$order_id."\n\nResult: $result\nСумма EPORT: $sum_eye\nСумма проверки: $amount";
		@mail($SUPPORT_EMAIL,"EPORT -- Функция повторной проверки", $msg,"From:".$SETTINGS['site_name']." System<$SUPPORT_EMAIL>");
		return false;
	}
}
/* END EPORT FUNCTIONS */

/* START YANDEX NONEY FUNCTIONS */
function YMGetAmount($curr_code="RUR"){
	global $YM;
	global $_SERVER;

	$curr_code = strtolower($curr_code);

	$RequestParams["UserID"] = $YM[$curr_code.'_user_id'];
	$RequestParams["EncryptionKey"] = $YM[$curr_code.'_user_key'];


	$res = GetAccountBalance($RequestParams,$ResultParams);

	if (is_error($res)||strtolower($ResultParams["ErrorCodeStr"])!="success")
	return false;

	if($curr_code=="uah"){
		return round($ResultParams["AccountSum"]/100,2);
	}
	return $ResultParams["AccountSum"]+0;
}
/* END YANDEX NONEY FUNCTIONS */

function YMTransfer($order_id,$account,$amount,$desc,$curr_code="RUR"){

	global $YM;

	$curr_code = strtolower($curr_code);

	$RequestParams["UserID"] = $YM[$curr_code.'_user_id'];
	$RequestParams["EncryptionKey"] = $YM[$curr_code.'_user_key'];

	if($curr_code=="uah"){
		$RequestParams["PaymentSum"] = $amount*100;
	}
	else{
		$RequestParams["PaymentSum"] = $amount;
	}
	$RequestParams["PaymentCurrencyCode"] = $YM[$curr_code.'_currency'];
	$RequestParams["AccountKey"] = $account;
	$RequestParams["ShortDescription"] = $desc;
	$RequestParams["Destination"] = $SETTINGS['site_name']." Exchanger";

	$res = DirectPaymentToAccount($RequestParams, $ResultParams);
	if (is_error($res)){
		$msg = "Здравствуйте!\n\nОшибка при переводе YANDEX $curr_code.\n\nОшибка: ".("DirectPaymentToAccount failed => ".$res->message)."\nСумма: $amount\nСчет-отправитель: ". $RequestParams["UserID"]."\nСчет-получатель: $account\nНомер заказа: $order_id\nОписание: $desc";

		@mail($SUPPORT_EMAIL,"Ошибка при YANDEX переводе!",$msg,"From:".$SETTINGS['site_name']." System<$SUPPORT_EMAIL>");
		return false;
	}

	return $ResultParams;
}
/********** EXCHANGE FUNCTIONS END ***************/
function DeleteClient($client_id){
	$res1 = @mysql_query("delete from orders where client_id=$client_id");
	$res2 = @mysql_query("delete from clients where id=$client_id");

	return $res1&res2;
}

function PartnerPayoutOK($payout_id){
	$p_row = mysql_fetch_object(mysql_query("select * from partner_payouts where id=$payout_id"));

	if($p_row->status==2){
		mysql_query("update partner_payouts  set status=1 where id=$payout_id");
		return true;
	}
	elseif($p_row->status==0){

		$p_params = Array(
		"partner_id" => $p_row->partner_id,
		"amount" => 0-$p_row->amount,
		"currency_id" => $p_row->currency_id,
		"comments" => "Payout # $payout_id"
		);
		MakePartnerTransaction($p_params);

		mysql_query("update partner_payouts  set status=1 where id=$payout_id");
		return true;
	}
	else{
		return false;
	}
}

function PartnerPayoutError($payout_id){
	$p_row = mysql_fetch_object(mysql_query("select * from partner_payouts where id=$payout_id"));

	if($p_row->status==1||$p_row->status==2){

		$p_params = Array(
		"partner_id" => $p_row->partner_id,
		"amount" => $p_row->amount,
		"currency_id" => $p_row->currency_id,
		"comments" => "Return payout # $payout_id"
		);
		MakePartnerTransaction($p_params);

		mysql_query("update partner_payouts  set status= where id=$payout_id");
		return true;
	}
	else{
		return false;
	}
}

function MakePartnerTransaction($params){
	global $SETTINGS;

	$partner_id = $params['partner_id'];
	$amount     = $params['amount'];
	$currency_id = $params['currency_id'];
	$comments   = $params['comments'];
	$ref_partner_id  = $params['ref_partner_id'];

	$row = mysql_fetch_object(mysql_query("SELECT * FROM partners WHERE id='".$partner_id."' " ) );
	$partner_amount = round($amount * $SETTINGS['subpartner_payout_perc'], 2);


	if ((isset($params['allow_recursion']))&&(1==$params['allow_recursion']) && ($partner_amount > 0) && ($ref_partner_id > 0))
	{
		$arr = array(
		'partner_id' => $ref_partner_id,
		'amount' => $partner_amount,
		'currency_id' => $currency_id,
		'comments' => $comments
		);
		MakePartnerTransaction($arr);
	}


	$p_amount = round(GetCourseByID($row->currency_id,$currency_id )*$amount,6);
	$p_amount = str_replace(',','.',$p_amount );

	$lave = $row->amount+$p_amount;
	$lave = str_replace(',','.',$lave);

	$time = time();
	$array = array(
	'partner_id' => $partner_id,
	'description' => addslashes( $comments ),
	'regdate' => $time ,
	'amount' => $amount,
	'currency_id' => $currency_id,
	'rest_amount' => $lave,
	'rest_currency_id' => $row->currency_id,
	'ref_partner_id' =>  $ref_partner_id,
	'partner_amount' => $partner_amount
	);

	if($params["order_id"]>0)
	{
		$array["order_id"] = $params["order_id"];
	}
	else
	{
		$array["order_id"] = "-1";
	}

	if(!($trn_id=addrecord('partner_transactions',$array,true))){
		return false;
	}

	@mysql_query( 'UPDATE partners SET amount = '.$lave.' WHERE id = '.$partner_id );

	if($row->trans_notify==1){
		/* notification e-mail */
		$mail_arr = GetEmailTemplate("PARTNER_TRANS_NOTIF");

		$tmp_row = mysql_fetch_object(mysql_query("select * from currencies where id=$currency_id"));
		$amount = $amount." ".$tmp_row->symbol;
		$tmp_row = mysql_fetch_object(mysql_query("select * from currencies where id=$row->currency_id"));
		$lave = $lave." ".$tmp_row->symbol;

		$msg = str_replace("FIRST_NAME",stripslashes($row->first_name),$mail_arr['body']);
		$msg = str_replace("LAST_NAME",stripslashes($row->last_name),$msg);
		$msg = str_replace("TRANS_ID",$trn_id,$msg);
		$msg = str_replace("REST_AMOUNT",$lave,$msg);
		$msg = str_replace("AMOUNT",$amount,$msg);
		$msg = str_replace("DESCRIPTION",$comments,$msg);
		$msg = str_replace("DATE",strftime("%d %b %Y   %H:%M",$time),$msg);
		SendEMail($row->email,$mail_arr['subject'],$msg,$mail_arr['from'],$mail_arr['format']);
	}

	return true;
}

function IP2CountryStr($ip) {
	$LongIP = sprintf('%u', ip2long($ip));
	$query = "select country_name from ip2country where $LongIP between iplow and iphigh";
	$result = mysql_query($query);
	if (mysql_num_rows($result) > 0){
		$row = mysql_fetch_object($result);
		$country_name = $row->country_name;
	}
	else{
		$country_name = "UNKNOWN";
	}
	return($country_name);
}

function IP2CountryID($ip){

	return 0;

	$LongIP = sprintf('%u', ip2long($ip));
	$query = "select country_name, country_2 from ip2country where $LongIP between iplow and iphigh";
	$result = mysql_query($query);
	if (mysql_num_rows($result) > 0) {
		$c_row = mysql_fetch_object($result);
		$row = mysql_fetch_object(mysql_query("select * from countries where code='$c_row->country_2'"));
		if($row->id!=""){
			return $row->id;
		}
		else{
			return 0;
		}
	}
	else{
		return 0;
	}
}

function GetHTTPParams(){
	global $REMOTE_ADDR;
	global $HTTP_X_FORWARDED_FOR, $HTTP_X_FORWARDED, $HTTP_FORWARDED_FOR, $HTTP_FORWARDED;
	global $HTTP_VIA, $HTTP_X_COMING_FROM, $HTTP_COMING_FROM;
	global $HTTP_SERVER_VARS, $HTTP_ENV_VARS;
	global $_SERVER;


	/* PROXY */
	if(!empty($HTTP_X_FORWARDED_FOR) || !empty($HTTP_X_FORWARDED) || !empty($HTTP_FORWARDED_FOR) || !empty($HTTP_FORWARDED) || !empty($HTTP_VIA) ||!empty($HTTP_X_COMING_FROM) || !empty($HTTP_COMING_FROM)) {
		$proxy_used = true;
	}
	else{
		$proxy_used = false;
	}

	if($ip=PMA_getIp()){
		if($ip!=$_SERVER['REMOTE_ADDR']){
			$proxy_used = true;
		}

		if($proxy_used){
			$proxy_type = 1;
			$proxy_ip   = $_SERVER['REMOTE_ADDR'];
		}
		else{
			$proxy_type = 0;
		}
	}
	else{
		$proxy_type = 2;/* ANONYMOUS */
		$ip = $_SERVER['REMOTE_ADDR'];
		$proxy_ip = $_SERVER['REMOTE_ADDR'];
	}

	$arr = Array(
	"ip" => $ip,
	"proxy_ip" => $proxy_ip,
	"proxy_type" => $proxy_type
	);

	return $arr;
}

function MoneyToStr($sum) //format money string
{
	return number_format($sum,2,"."," ");
}

function GenRandom ($nSize=24){
	// Randomize
	mt_srand ((double) microtime() * 1000000);
	for ($i=1; $i<=$nSize; $i++) {
		// if you wish to add numbers in your string,
		// uncomment the two lines that are commented
		// in the if statement
		$nRandom = mt_rand(1,30);
		if ($nRandom <= 10) {
			// Uppercase letters
			$sessionID .= chr(mt_rand(65,90));
		} elseif ($nRandom <= 20) {
			$sessionID .= mt_rand(0,9);
		} else {
			// Lowercase letters
			$sessionID .= chr(mt_rand(97,122));
		}
	}
	return $sessionID;
}

function GetPagerParams($params){
	global $_GET;
	global $_POST;
	global $SETTINGS;
	global $DB_LINK;

	/* getting value from params */
	$tables = $params['tables'];
	$query = $params['query'];
	$def_by = $params['def_by']==""?"id":$params['def_by'];
	$def_ord = $params['def_ord']==""?"desc":"";
	$items_per_page = $params['items_per_page']+0==0?$SETTINGS['admin_items_per_page']:$params['items_per_page'];
	$pages_per_block = $params['pages_per_block']+0==0?$SETTINGS['admin_pages_per_block']:$params['pages_per_block'];



	$res_arr = Array();

	$tmp_arr = explode(",",$tables);
	if($query==""){
		$query = "select count(*) from ".$tmp_arr[0];
	}

	/* getting data */
	if(isset($_GET['l_pager'])&&$params['s_prefix']!=""){
		$var_name = $params['s_prefix']."_pager";
		$page = $_SESSION[$var_name]['page'];
		$sort_by = $_SESSION[$var_name]['sort_by'];
		$sort_ord = $_SESSION[$var_name]['sort_ord'];
	}
	else{
		$page = $_GET['page']==""?$_POST['page']:$_GET['page'];
		$sort_by = $_GET['sort_by']==""?$_POST['sort_by']:$_GET['sort_by'];
		$sort_ord = $_GET['sort_ord']==""?$_POST['sort_ord']:$_GET['sort_ord'];
	}

	if (!eregi("^[_0-9a-z]+\.[_0-9a-z]+$", $sort_by))
	{
		$sort_by = "id";
	}


	/* starting counting values */
	$page = (is_numeric($page)&&$page>0)?$page:1;

	$arr = explode(",",$tables);

	$flag=$sort_by?true:false;
	if (!$params[nocheckfield]){
		$flag = false;
		foreach($arr as $value){
			$res = mysql_query("select * from $value");
			for($i=0;$i<mysql_num_fields($res);$i++){
				$col_info = mysql_field_name($res, $i);
				if($sort_by == $value.".".strtolower($col_info['name'])){
					$flag=true;
					break;
				}
			}
		}
	}
	$sort_by = $flag?$sort_by:$arr[0].".$def_by";
	$sort_ord = ($sort_ord=="asc"||$sort_ord=="desc")?$sort_ord:$def_ord;
	$row = mysql_fetch_row(mysql_query($query));
	$total_amount = $row[0];
	$num_pages = floor($total_amount/$items_per_page);
	if(($total_amount > $num_pages*$items_per_page)||$num_pages==0){
		$num_pages++;
	}

	if($page > $num_pages){
		$page = $num_pages;
	}
	$block = ceil($page/$pages_per_block);

	$start_item = ($page-1)*$items_per_page + 1;
	$end_item = $page*$items_per_page;
	if($total_amount==0){
		$start_item = 0;
		$end_item = 0;
	}
	if($end_item > $total_amount){
		$end_item = $total_amont;
	}

	$res_arr['total_amount']=$total_amount;
	$res_arr['num_pages']=$num_pages;
	$res_arr['start_item']=$start_item<=0?1:$start_item;
	$res_arr['end_item']=$end_item;
	$res_arr['page'] = $page;
	$res_arr['block'] = $block;
	$res_arr['sort_by'] = $sort_by;
	$res_arr['sort_ord'] = $sort_ord;
	$res_arr['pages_per_block'] = $pages_per_block;
	$res_arr['items_per_page'] = $items_per_page;
	$res_arr['first_page'] = (($block-1)*$pages_per_block+1);
	$res_arr['last_page'] = $block*$pages_per_block > $num_pages?$num_pages:$block*$pages_per_block;
	$res_arr['sort'] = "page=$page&sort_by=$sort_by&sort_ord=$sort_ord";
	$res_arr['new_sort'] = $_SERVER['PHP_SELF']."?page=$page&sort_ord=".($sort_ord=="desc"?"asc":"desc")."&sort_by=";

	/* storing data to session */
	if($params['s_prefix']!=""){
		$var_name = $params['s_prefix']."_pager";
		$_SESSION[$var_name] = $res_arr;
	}

	return $res_arr;
}

function AddRecord($table,$arr,$return_id=true){
	global $DB_LINK;

	$arr=array_change_key_case($arr,CASE_LOWER);

	foreach($arr as $key=>$value){
		if (!is_null($value)&&!(is_string($value)&&($value=="NULL"))){
			$fields .= '`'.strtolower($key).'`,';
			$values .= "'".$value."',";
		}
	}
	$query = "INSERT INTO `$table` (".substr($fields,0,strlen($fields)-1).") VALUES (".substr($values,0,strlen($values)-1).");";

	$res = mysql_query($query);
	if (!$res) {
		error_log(mysql_error());
		$_SESSION['ERROR_MSG'] = "Error. Probably there is an interdiction on this operation in DATABASE.";
		@mail("[email protected]","Partner MYSQLAddRecord error",$query);
	}
	elseif($return_id){
		$query="select max(id) from `$table`;";
		$res=@mysql_fetch_assoc(@mysql_query($query));
	}
	return $res["max(id)"];
}

function UpdateRecord($table,$arr,$data){
	global $DB_LINK;

	$q_str = "";
	foreach($arr as $key=>$value)
	{
		if ((strval($value)!="id")&&(!is_null($value)&&(strval($value)!="NULL")))
		{
			$q_str .= "`".($key)."`='".($value)."',";
		}
	}

	//$query = "INSERT INTO $table (".substr($fields,0,strlen($fields)-1).") VALUES (".substr($values,0,strlen($values)-1).");";
	$query = "UPDATE `$table` SET ".substr($q_str, 0, strlen($q_str) - 1)." WHERE `id` = '".$data."'";
	/*$arr=array_change_key_case($arr,CASE_LOWER);
	if (!is_array($data)) {
	$data=array("id"=>$data);
	}*/
	$res=mysql_query($query);

	return $res;
}

function DeleteRecord($table,$data,$k="id"){
	global $DB_LINK;
	//$arr=array_change_key_case($data,CASE_LOWER);
	/*if (!is_array($data)) {
	$data=array("id"=>$data);
	}*/
	$res=mysql_query("delete from `$table` where `$k`='$data'");
	return $res;
}

CLASS TCheckForm
{

	/*Check form fields*/
	function LocalCheck(){
		global $_POST;
		global $fields;

		$error = "";
		$this->fields=$this->fields?$this->fields:$fields;
		foreach($this->fields as $key=>$value){
			if($value[3]!=""&&is_array($value)){
				if(!eregi($value[3],$_POST[$key])){
					$error .= $value[2]."<br>\n";
				}
			}
			elseif($value[2]!=""&&trim($_POST[$key])==""&&is_array($value)){
				$error .=$value[2]."<br>\n";
			}
		}
		return $error;
	}
	function TCheckForm($fld=null){
		$this->fields=$fld;
	}
}

function FormatArticul(&$rec){
	global $SETTINGS;
	$articul=$rec->articul;
	if ($SETTINGS[articul_signs_count]-strlen($rec->articul)>0) {
		$articul=$articul.str_repeat("0",$SETTINGS[articul_signs_count]-strlen($rec->articul));
	}
	/* if ($rec->category_type==2) {
	$articul=substr($rec->articul,0,strlen($rec->articul)-2)."-".substr($articul,strlen($rec->articul)-2);
	}*/
	$rec->articul=$articul;

	return $rec;
}

/* loading settings */
function LoadSettings(){
	global $DB_LINK;

	$res_arr = Array(
	"admin_email"=>'',
	"admin_items_per_page"=>'',
	"admin_pages_per_block"=>'',
	"min_login_length"=>'',
	"max_password_length"=>'',
	"invalid_request_msg"=>'',
	"client_session_timeout"=>'',
	"html_editor_path"=>'',
	"articul_signs_count"=>'',
	"catalog_separator"=>'',
	"catalog_separator1"=>'',
	"use_wysiwyg"=>'',
	"error_404_url"=>'',
	"school_category_path"=>'',
	"thematic_category_path"=>'',
	"full_tree_category_path"=>'',
	"remember_login_timeout"=>'',
	'client_remember_login_timeout'=>'',
	'max_client_logo_width'=>'',
	'max_client_logo_height'=>'',
	'client_logo_max_size'=>'',
	'client_logo_dir'=>'',
	'second_subscription_discount' =>'',
	'second_subscription_discount_expiration' =>'',
	'second_subscription_vendor_id' => ''
	);

	$res = mysql_query("select * from system_settings");

	while($row = mysql_fetch_object($res)){
		$res_arr[strtolower($row->param_name)] = stripslashes(trim($row->param_value));
	}

	return $res_arr;
}

function ValidateEmail($email){
	global $REG_EXP;
	if(eregi("^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z0-9]{2,6})$", $email)){
		return true;
	}
	else{
		return false;
	}
}

function GetCatalogOptions($cat_type=0,$mark_final=false,$val_for_simple=true,$arr_val=null){
	global $DB_LINK,$SETTINGS;
	$style_able=" class=\"cat_able_to_add\" ";
	$style_not_able=" class=\"cat_notable_to_add\" ";

	$res=mysql_query("select * from proc_catalog($cat_type,null,'')" );
	while($row=mysql_fetch_object($res)){
		$school_categories.="<option ";
		if (is_array($arr_val)&&in_array($row->id,$arr_val)) {
			$school_categories.="selected ";
		}
		$school_categories.=$val_for_simple||($row->category_type!=0)?"value=\"$row->id\" ":"value=\"#\" ";
		$school_categories.=($mark_final&&($row->category_type==0)?$style_not_able:$style_able);
		$school_categories.=">".str_repeat($SETTINGS[catalog_separator1],intval(strlen($row->articul)/2)-1).$row->name."</option>\n";
		/*		$school_categories.="<option ".($row->category_type==0?$style_not_able." value=\"#\" ":$style_able." value=\"$row->id\" ").">".
		$school_categories.="<option ".($row->category_type==0?$style_not_able." value=\"#\" ":$style_able." value=\"$row->id\" ").">".
		str_repeat($SETTINGS[catalog_separator],intval(strlen($row->articul)/2)-1).$row->name
		."</option>\n";*/
	} // while
	return $school_categories;
}

function MakeInstallFile($id){
	//zip

}

function GetProbability($prob){
	if ($prob) {
		$n  = intval(1/$prob);
		$res= rand(1,$n);
		$res=$res==$n;
	}
	return $res;
}

function GetTemplateCode($params){
	global $smarty;

	if(is_numeric($params['tpl_id'])){
		$row = mysql_fetch_object(mysql_query("select * from html_templates where id='$params[tpl_id]'"));
	}

	if($row->id==""){
		$row = mysql_fetch_object(mysql_query("select * from html_templates where is_default=1"));
	}

	$smarty->assign("page_title",$params[page_title]);
	$smarty->assign("browser_title",$params[browser_title]);
	$smarty->assign("meta_keywords",$params[meta_keywords]);
	$smarty->assign("meta_description",$params[meta_description]);

	$html_result = $smarty->fetch("db:$row->code");

	return $html_result;
}

function GetContent($params){
	global $smarty;

	$smarty->assign("page_title",$params[page_title]);
	$smarty->assign("browser_title",$params[browser_title]);
	$smarty->assign("meta_keywords",$params[meta_keywords]);
	$smarty->assign("meta_description",$params[meta_description]);
	$smarty->assign("nav_str_arr",$params[nav_str_arr]);

	/* PAGE CONTENT */
	$content = str_replace("<?","<",$params[content]);

	$smarty->assign("page_content",$content);


	$html_result = $smarty->fetch($params[tpl_code]);

	return $html_result;
}


/* htaccess management functions start */
function CheckHtaccess($static_name,$page=""){
	global $SITE_DOCUMENT_ROOT;
	$file = file($SITE_DOCUMENT_ROOT."/.htaccess");
	$str = implode('',$file);

	$reg_exp = "RewriteRule[ ]+\^".$static_name."[/{}01,$]+[ ]+".($page!=""?str_replace("?","\?",$page):"");

	if(eregi($reg_exp,$str)){
		return true;
	}
	else{
		return false;
	}

}

function AddPageToHtaccess($static_name,$page){
	global $SITE_DOCUMENT_ROOT;
	$str .='
RewriteRule    ^'.$static_name.'/{0,1}$  '.$page.'&%{QUERY_STRING}&rw [L]';
	$fp = fopen($SITE_DOCUMENT_ROOT."/.htaccess","a+");
	fputs($fp,$str);
	fclose($fp);
}

function DeletePageFromHtaccess($static_name){
	global $SITE_DOCUMENT_ROOT;
	$file = file($SITE_DOCUMENT_ROOT."/.htaccess");
	$ht_content = "";

	foreach($file as $value){
		if(!(eregi("RewriteRule[ ]+\^$static_name"."[/{}01,$]+",$value))){
			$ht_content .= $value;
		}
	}
	$fp = fopen($SITE_DOCUMENT_ROOT."/.htaccess","w");
	fputs($fp,$ht_content);
	fclose($fp);
}
/* htaccess management functions end */

function GetCategoryByPath($path_arr,$type){
	$url = "/".implode("/",$path_arr);

	$row = mysql_fetch_object(mysql_query("select * from proc_catalog($type,NULL,'') where url='$url'"));
	return $row->id+0;
}

function RegisterClient($params){
	global $DB_LINK;
	global $_SERVER;
	global $SITE_URL;

	$add_arr = Array(
	"title" => $params["title"],
	"first_name" => $params["first_name"],
	"last_name" => $params["last_name"],
	"email"  => $params["email"],
	"password" => md5(strtolower($params["password"])),
	"country_id" =>$params["country_id"],
	"postcode" => $params["zip"],
	"city" => $params["city"],
	"address1"=>$params["address1"],
	"address2"=>$params["address2"],
	"county"=>$params["county"],
	"phone"  =>$params["phone"],
	"regdate"    =>time(),
	"reg_ip"    =>$_SERVER['REMOTE_ADDR'],
	"http_referer"    =>$params['http_referer'],
	"status" => $params["status"]
	);

	$id = AddRecord("clients",$add_arr,true);

	if($id<=0){
		return 0;
	}

	if($params['send_confirmation_email']){

		$l_link = $SITE_URL."/login";
		$l_link = "<a href='$l_link'>".$l_link."</a>";

		$p_link = $SITE_URL."/purchase_subscription";
		$p_link = "<a href='$p_link'>".$p_link."</a>";


		$mail_arr = GetEmailTemplate('NEW_CLIENT_REG');
		$msg = $mail_arr['body'];
		$msg = str_replace("FIRST_NAME",stripslashes($params['first_name']),$msg);
		$msg = str_replace("LAST_NAME",stripslashes($params['last_name']),$msg);
		$msg = str_replace("MEMBER_ID",$id,$msg);
		$msg = str_replace("EMAIL",stripslashes($params['email']),$msg);
		$msg = str_replace("PASSWORD",stripslashes($params['password']),$msg);
		$msg = str_replace("LOGIN_LINK",$l_link,$msg);
		$msg = str_replace("PURCHASE_LINK",$p_link,$msg);

		SendEMail($params['email'],$mail_arr['subject'],$msg,$mail_arr['from'],$mail_arr['format']);

	}

	return $id;
}

function RegisterPartner($params){
	global $DB_LINK;
	global $_SERVER;
	global $SITE_URL;
	global $SETTINGS;
	global $PARTNER_URL;

	$add_arr = Array(
	"title" => $params["title"],
	"first_name" => $params["first_name"],
	"last_name" => $params["last_name"],
	"email"  => $params["email"],
	"password" => md5($params["password"]),
	"country_id" =>$params["country_id"],
	"currency_id" =>$params["currency_id"],
	"site_name" =>$params["site_name"],
	"site_url" =>$params["site_url"],
	"amount" =>0,
	"city" => $params["city"],
	"regdate"    =>time(),
	"comission_perc"    =>$params["comission_perc"],
	"reg_ip"    =>$_SERVER['REMOTE_ADDR'],
	"http_referer"    =>$params['http_referer'],
	"status" => $params["status"]
	);

	$id = AddRecord("partners",$add_arr,true);

	if($id<=0){
		return 0;
	}

	if($params['send_confirmation_email']){

		$l_link = $PARTNER_URL;
		$l_link = "<a href='$l_link'>".$l_link."</a>";

		$mail_arr = GetEmailTemplate('NEW_PARTNER_REG');
		$msg = $mail_arr['body'];
		$msg = str_replace("FIRST_NAME",stripslashes($params['first_name']),$msg);
		$msg = str_replace("LAST_NAME",stripslashes($params['last_name']),$msg);
		$msg = str_replace("PARTNER_ID",$id,$msg);
		$msg = str_replace("PARTNER_EMAIL",stripslashes($params['email']),$msg);
		$msg = str_replace("PARTNER_PASSWORD",stripslashes($params['password']),$msg);
		$msg = str_replace("LOGIN_LINK",$l_link,$msg);

		SendEMail($params['email'],$mail_arr['subject'],$msg,$mail_arr['from'],$mail_arr['format']);

	}

	return $id;
}
/*
function SendEMail($email,$subject,$msg,$from,$format="text"){
$headers  = "From: $from\r\n";
$headers .= "Reply-To: $from\r\n";
if(strtolower($format)=="html"){
$headers .= "Content-type: text/html; charset=windows-1251\r\n";
}
else{
$headers .= "Content-type: text/plain; charset=windows-1251\r\n";
}
$res=mail($email,$subject,$msg,$headers);
//	echo $email;
return $res;
}*/

function SendAttachMail($params){

	$attach_str=chunk_split(base64_encode($params['attach_str']));

	$content = convert_cyr_string($params['body'],w,k);

	$Headers = "";
	$Headers.="From: ".$params['from']."\n";
	$Headers.="MIME-Version: 1.0\n";
	$Headers.="Content-Type: multipart/mixed; charset=windows-1251; boundary=\"MIME_BOUNDRY\"\n";
	$Headers.="X-Mailer: PHP4\n";
	$Headers.="X-Priority: 3\n";
	$Headers.="This is a multi-part Contentin MIME format.\n";
	// Set the Content of the e-mail
	$Content="--MIME_BOUNDRY\n";
	$Content.="Content-Transfer-Encoding: quoted-printable\n";
	$Content.="\n";
	$Content.="$content\n";
	$Content.="\n";
	$Content.="--MIME_BOUNDRY\n";
	$Content.="Content-Type: ".$params['content-type']."; name=\"".$params['attach-name']."\"\n";
	$Content.="Content-disposition: attachment\n";
	$Content.="Content-Transfer-Encoding: base64\n";
	$Content.="\n";
	$Content.="$attach_str\n";
	$Content.="\n";
	$Content.="--MIME_BOUNDRY--\n";
	// Send the e-mail

	@mail($params['email'],$params['subject'],$Content, $Headers);
}


function RecursiveMkdir($path)
{
	// This function creates the specified directory using mkdir().  Note
	// that the recursive feature on mkdir() is broken with PHP 5.0.4 for
	// Windows, so I have to do the recursion myself.
	if (!file_exists($path))
	{
		// The directory doesn't exist.  Recurse, passing in the parent
		// directory so that it gets created.
		RecursiveMkdir(dirname($path));
		$oldmask=umask();
		mkdir($path);
		chmod($path,0777);
		umask($oldmask);
	}
}


/* CLIENT FUNCTIONS START */
function CheckClientLogin(){
	global $_SERVER;
	global $SITE_URL;
	global $CLIENT_DIR;
	global $SITE_DOMAIN;

	$client_id = -1;
	if (is_numeric($_SESSION["CLIENT_ID"])&&$_SESSION["CLIENT_ID"]>0){
		$row = mysql_fetch_object(mysql_query("select * from clients where status=1 and id=".($_SESSION["CLIENT_ID"]+0)));
		if($row->id==""){
			$_SESSION['CLIENT_ID'] = 0;
			header("Location: $SITE_URL/logout.php");
			exit;
		}

		$client_id = $row->id;
	}
	elseif(isset($_COOKIE['REM_LOGIN'])&&eregi("^[A-Za-z0-9_]{32}$",$_COOKIE['REM_LOGIN'])){
		$row = mysql_fetch_object(mysql_query("select * from clients where status=1 and md5(email||password)='".$_COOKIE['REM_LOGIN']."'"));
		if($row->id!=""){
			MakeClientLogin($row->id);
			$client_id = $row->id;
		}
	}

	return $client_id+0;
}

function CheckClientLoginData($login, $password){

	$login=addslashes(trim(substr($login,0,255)));
	$password=trim(substr($password,0,255));

	$query ="SELECT * FROM clients where status=1 and UPPER(email)='".strtoupper($login)."' and (\"password\"='".md5(strtolower($password))."' OR \"password\"='".md5($password)."')";

	$row = mysql_fetch_object(mysql_query($query));

	if($row->id!=""){
		return $row->id;
	}
	else{
		return 0;
	}
}

function MakeClientLogin($client_id,$rem_login=false){
	global $_SERVER;
	global $SETTINGS;
	global $SITE_DOMAIN;

	$_SESSION['CLIENT_ID']=$client_id+0;

	//logging
	@mysql_query("update clients set last_login_date=".time()." where id=$client_id");


	/*setting user login preferences*/

	if($rem_login){
		$row = mysql_fetch_object(mysql_query("select * from clients where id=$client_id"));
		$hash = md5($row->email.$row->password);
		@setcookie("REM_LOGIN",$hash,time()+$SETTINGS['client_remember_login_timeout']*86400,"/",".".$SITE_DOMAIN);
	}
}

function MakeClientLogout($client_id){
	global $SITE_URL;
	global $DB_LINK;
	global $SITE_DOMAIN;

	//	unset($_SESSION["CLIENT_ID"]);
	setcookie("REM_LOGIN", "", time()-100,"/",$SITE_DOMAIN);
	session_unset();
	session_destroy();
	header ("Cache-Control: no-cache, must-revalidate");
	header ("Location: $SITE_URL");
	exit;
}
/* CLIENT FUNCTIONS END */

function GetCategoryStaticPath($cat_id,$cat_type){

	$cat_names_arr = Array();
	$path = "";

	$row = mysql_fetch_object(mysql_query("select * from ".($cat_type==0?"school_categories":"thematic_categories")." where id=$cat_id"));

	$path = "/".$row->pseudo_name;

	if($row->parent_id>0){
		$path = GetCategoryStaticPath($row->parent_id,$cat_type).$path;
	}

	return $path;
}

function GetComissionStr($comission_fix,$comission_perc,$curr_symbol=""){
	$comission = "";
	$com_fix = "$curr_symbol ".($comission_fix+0);
	$com_perc = ($comission_perc+0)."%";

	if($comission_fix>0&&$comission_perc<=0){
		$comission = $com_fix;
	}
	elseif($comission_fix<=0&&$comission_perc>0){
		$comission = $com_perc;
	}
	else{
		$comission = $com_fix." + ".$com_perc;
	}

	return $comission;
}

function CreateNewOrder($params){
	$order_id = -1;
	global $SITE_URL;

	/* partner programm start */
	$partner_click_id = $_COOKIE[PARTNER_CLICK]+0;

	if(is_numeric($partner_click_id)&&$partner_click_id>0){
		$p_row = mysql_fetch_object(mysql_query("select partners.* from partners inner join partner_clicks on partners.id = partner_clicks.partner_id where partner_clicks.id=$partner_click_id and partners.status=1"));

		$partner_id = $p_row->id+0;
	}
	else{
		$partner_id = 0;
	}
	//	print_r($params);

	if($params['promo_code_id']>0){
		$p_row = mysql_fetch_object(mysql_query("select partners.* from partners inner join promo_codes on partners.id = promo_codes.partner_id where promo_codes.id=".$params['promo_code_id']." and partners.status=1"));

		//		print_r($p_row);

		$partner_id = $p_row->id+0;
	}

	/* partner programm end   */

	$arr = Array(
	"client_id" =>$params['client_id'],
	"tariff_id" =>$params['tariff_id'],
	"amount" =>$params['amount'],
	"currency_id" =>$params['currency_id'],
	"discount_amount" =>$params['discount_amount'],
	"description" =>$params['description'],
	"is_repeat" =>$params['is_repeat']+0,
	"regdate" =>time(),
	"status" =>0
	);

	if($partner_id>0){
		$arr['partner_payout_status'] = 0;
		$arr['partner_id'] = $partner_id;
		$arr['partner_currency_id'] = $p_row->currency_id;
		$arr['partner_amount'] = round((($params['amount']-$params['discount_amount'])*$p_row->comission_perc)*GetCourseByID($p_row->currency_id,$params['currency_id']),6);


	}

	if($params['promo_code_id']>0){
		$arr['promo_code_id'] = $params['promo_code_id'];
	}

	$order_id=AddRecord("orders",$arr,true);

	if($order_id>0 && $partner_click_id >0){
		$arr = Array(
		"click_id" =>$partner_click_id,
		"order_id" =>$order_id
		);
		AddRecord("partner_clicks2orders",$arr);
	}

	/* sending mail to client
	if($params['notify_client']){

	$user_row = mysql_fetch_object(mysql_query("select * from clients where id=".$params['client_id']));
	$tariff_row = mysql_fetch_object(mysql_query("select * from tariffs where id=".$params['tariff_id']));
	$curr_row = mysql_fetch_object(mysql_query("select * from currencies where id=".$params['currency_id']));

	$mail_arr = GetEmailTemplate('NEW_ORDER_CLIENT_NOTIF');

	$price = stripslashes($curr_row->symbol)." ".MoneyToStr(($params['amount']-$params['discount_amount']));

	$p_link = $SITE_URL."/purchase_subscription?order_id=$order_id&step=3&hash=".md5($order_id.$user_row->email.$user_row->password);
	$p_link = "<a href='$p_link'>".$p_link."</a>";

	$msg = $mail_arr['body'];
	$msg = str_replace("FIRST_NAME",stripslashes($user_row->first_name),$msg);
	$msg = str_replace("LAST_NAME",stripslashes($user_row->last_name),$msg);
	$msg = str_replace("ORDER_ID",$order_id,$msg);
	$msg = str_replace("SUBSCRIPTION_NAME",stripslashes($tariff_row->name),$msg);
	$msg = str_replace("PRICE",$price,$msg);
	$msg = str_replace("PURCHASE_LINK",$p_link,$msg);

	SendEMail($user_row->email,$mail_arr['subject'],$msg,$mail_arr['from'],$mail_arr['format']);

	}
	*/

	return $order_id;
}

function GetNextPeriodDate($date_ot,$period_id){
	$date_ot+=0;
	$period_id+=0;
	if (!$date_ot||!$period_id) {
		return false;
	}
	$period_row=mysql_fetch_object(mysql_query("select * from tariff_periods where id='$period_id'"));
	$days=$period_row->days;
	$monthes=$period_row->monthes;
	$years=$period_row->years;

	$date_params=getdate($date_ot);
	if ($monthes||$years){
		$mon_nums=$years*12+$monthes+$date_params[mon];
		$monthes=fmod($mon_nums,12);
		$years=intval($mon_nums/12);
		$control_date=mktime(0,0,0,$monthes,$date_params[mday],$date_params[year]+$years);
	}
	else{
		$control_date=$date_ot;
	}
	$date_params=getdate($control_date);
	$control_date+=$days*86400;
	return $control_date;
}

function RunOrder($id){
	global $SITE_URL;
	$id+=0;
	$order_row=mysql_fetch_object(mysql_query(
	"select orders.*, clients2tariffs.id as client_tariff_id, tariffs.period_id, tariffs.name as tariff_name, currencies.symbol
	   from ((orders 
	   inner join tariffs on orders.tariff_id=tariffs.id)
	   left join clients2tariffs on clients2tariffs.order_id=orders.id) inner join currencies on orders.currency_id = currencies.id
	   where orders.id='".($id+0)."'
	  "));
	if (!$order_row->id) {
		return false;
	}
	$res=mysql_query("begin");
	if ($order_row->client_tariff_id) {
		$res=$res&&mysql_query("update clients2tariffs set status=1 where id='$order_row->client_tariff_id'");
	}
	else{
		$exp_date=GetNextPeriodDate(time(),$order_row->period_id);
		$res=$exp_date&&$res&&mysql_query("insert into clients2tariffs(client_id,tariff_id,regdate,expdate,order_id,status)
                                    	  values($order_row->client_id,$order_row->tariff_id,".time().",$exp_date,$id,1)");
	}
	$res=$res&&mysql_query("update orders set status=1 where id='$id'");

	/* partner */
	if($order_row->partner_id>0&&$order_row->partner_payout_status==0){
		$p_params = Array(
		"partner_id" => $order_row->partner_id,
		"amount" => $order_row->partner_amount,
		"currency_id" => $order_row->partner_currency_id,
		"comments" => "Payment for order # $order_row->id",
		"order_id" => $order_row->id
		);
		MakePartnerTransaction($p_params);
		mysql_query("update orders set partner_payout_status=1 where id = $order_row->id");
	}


	if ($res) {
		$res=$res&&mysql_query("commit");
		/* sending e-mail to client */
		$cl_row = mysql_fetch_object(mysql_query("select * from clients where id=$order_row->client_id"));

		$l_link = $SITE_URL."/login";
		$l_link = "<a href='$l_link'>".$l_link."</a>";

		$mail_arr = GetEmailTemplate('NEW_ORDER_CLIENT_NOTIF');
		$msg = $mail_arr['body'];
		$msg = str_replace("FIRST_NAME",stripslashes($cl_row->first_name),$msg);
		$msg = str_replace("LAST_NAME",stripslashes($cl_row->last_name),$msg);
		$msg = str_replace("ORDER_ID",$order_row->id,$msg);
		$msg = str_replace("SUBSCRIPTION_NAME",stripslashes($order_row->tariff_name),$msg);
		$msg = str_replace("PRICE",$order_row->symbol." ".($order_row->amount-$order_row->discount_amount),$msg);
		$msg = str_replace("CLIENT_EMAIL",$cl_row->email,$msg);
		$msg = str_replace("LOGIN_LINK",$l_link,$msg);

		SendEMail($cl_row->email,$mail_arr['subject'],$msg,$mail_arr['from'],$mail_arr['format']);

	}
	else{
		$res=$res&&mysql_query("rollback");
	}
	return $res;
}

function ErrorOrder($id,$stat=0){
	$id+=0;
	$stat+=0;


	$order_row=mysql_fetch_object(mysql_query("select * from orders where orders.id='".($id+0)."'"));
	if (!$order_row->id){
		return false;
	}


	if (!$id||($stat==1)) {
		return false;
	}
	$res=mysql_query("update orders set status=$stat where id=$id");


	/* partner */

	/* partner */
	if($order_row->partner_id>0&&$order_row->partner_payout_status==1){
		$p_params = Array(
		"partner_id" => $order_row->partner_id,
		"amount" => 0-$order_row->partner_amount,
		"currency_id" => $order_row->partner_currency_id,
		"comments" => "Return payment for order # $order_row->id",
		"order_id" => $order_row->id
		);
		MakePartnerTransaction($p_params);
		mysql_query("update orders set partner_payout_status=0 where id = $order_row->id");
	}



	return $res;
}

function GetMonNames()
{
	for ($n=1;$n<=12;$n++)
	{
		$res[$n]=strftime("%B",mktime(0,0,0,$n,1,2000));
	}
	return $res;
}

function FormGetDate($min_year=1901,$max_year=2010,$dt=0,$prefix="")
{
	$mon_names=GetMonNames();
	// echo $dt;
	$d=1;
	$dt_params=getdate($dt);
	$dd_sel="<select name=\"{$prefix}dd\">";
	while ($d<=31){
		$selected=$dt_params[mday]==$d?"selected":"1";
		$dd_sel.="<option value=\"$d\" $selected>".$d."</option>";
		$d++;
	}
	$dd_sel.="</select>";

	$dd_sel.="<select name=\"{$prefix}mm\">";
	$d=1;
	while ($d<=12){
		$selected=$dt_params[mon]==$d?"selected":"";
		$dd_sel.="<option value=\"$d\" $selected>".$mon_names[$d]."</option>";
		$d++;
	}
	$dd_sel.="</select>";

	$dd_sel.="<select name=\"{$prefix}yy\">";
	$d=$min_year;
	while ($d<=$max_year){
		$selected=$dt_params[year]==$d?"selected":"";
		$dd_sel.="<option value=\"$d\" $selected>".$d."</option>";
		$d++;
	}
	$dd_sel.="</select>";
	// echo htmlspecialchars($dd_sel);
	return $dd_sel;
}

/** merhcnat auth */
function CheckMerchantLogin()
{
	global $_SERVER;
	global $_COOKIE;

	$MERCHANT_ID = -1;
	if (is_numeric($_SESSION["MERCHANT_ID"])&&$_SESSION["MERCHANT_ID"]>0){
		$row = mysql_fetch_object(mysql_query("select * from merchant_users where status=1 and id=".($_SESSION["MERCHANT_ID"]+0)));
		if($row->id==""){
			$_SESSION["MERCHANT_ID"] = 0;
			header("Location: /merchant/cabinet/logout.php");
			exit;
		}
		$MERCHANT_ID = $_SESSION["MERCHANT_ID"];
	}
	elseif(isset($_COOKIE['REM_MERCHANT_LOGIN'])&&eregi("^[A-Za-z0-9_]{32}$",$_COOKIE['REM_MERCHANT_LOGIN'])){
		$row = mysql_fetch_object(mysql_query("select * from merchant_users where  md5(email||password)='".$_COOKIE['REM_MERCHANT_LOGIN']."'"));
		if($row->id!=""){
			MakeMerchantLogin($row->id,true);
			$MERCHANT_ID = $row->id;
		}
	}
	return $MERCHANT_ID;
}

function CheckMerchantLoginData($login, $password){
	$login=addslashes(htmlspecialchars(trim(substr($login,0,255))));
	$password=addslashes(htmlspecialchars(trim(substr($password,0,255))));

	$query ="SELECT * FROM merchant_users where status=1 and email='".$login."' and password='".md5($password)."'";
	$res = mysql_query($query);

	if(mysql_num_rows($res)==1){
		$row = mysql_fetch_object($res);
		return $row->id;
	}
	else{
		return 0;
	}
}

function MakeMerchantLogin($merchant_id,$remember=true){
	global $SETTINGS;
	global $SITE_DOMAIN;
	$_SESSION['MERCHANT_ID']=$merchant_id+0;
	/*setting user login preferences*/
	$row = mysql_fetch_object(mysql_query("select * from merchant_users where id=$merchant_id"));
	if($remember){
		@setcookie("REM_MERCHANT_LOGIN",md5($row->email.$row->password),time()+$SETTINGS[remember_login_timeout]*3600,"/",$SITE_DOMAIN);
	}
	else{
		@setcookie("REM_MERCHANT_LOGIN","",time-100,"/",$SITE_DOMAIN);
	}
}

function MakeMerchantLogout($merhcnat_id){
	global $SITE_DOMAIN;
	global $ADMIN_DIR;
	global $SITE_URL;
	setcookie("REM_MERCHANT_LOGIN", "", time()-100,"/",$SITE_DOMAIN);
	session_start();
	$_SESSION['MERCHANT_ID'] = -1;
	//session_destroy();
	//session_unset();
	header ("Cache-Control: no-cache, must-revalidate");
	header ("Location: $SITE_URL");
}


/*** admin auth*/
function CheckAdminLogin()
{
	global $_SERVER;
	global $_COOKIE;
	global $ADMIN_URL;

	$admin_id = -1;
	if (is_numeric($_SESSION["ADMIN_ID"])&&$_SESSION["ADMIN_ID"]>0){
		$row = mysql_fetch_object(mysql_query("select * from administrators where status=1 and id=".($_SESSION["ADMIN_ID"]+0)));
		if($row->id==""){
			$_SESSION["ADMIN_ID"] = 0;
			header("Location: $ADMIN_URL/logout.php");
			exit;
		}
		$ADMIN_ID = $_SESSION["ADMIN_ID"];
	}
	elseif(isset($_COOKIE['REM_ADMIN_LOGIN'])&&eregi("^[A-Za-z0-9_]{32}$",$_COOKIE['REM_ADMIN_LOGIN'])){
		$row = mysql_fetch_object(mysql_query("select * from administrators where  md5(concat(login,password))='".$_COOKIE['REM_ADMIN_LOGIN']."'"));
		if($row->id!=""){
			$row_ip = mysql_fetch_object(mysql_query("select * from system_settings where param_name='block_on_ip';"));
			if($row_ip->param_name!=""&&$row_ip->param_value==$_SERVER["REMOTE_ADDR"]){
				MakeAdminLogin($row->id,true);
				$ADMIN_ID = $row->id;
			}
		}
	}
	return $ADMIN_ID;
}

function CheckAdminLoginData($login, $password){
	$login=addslashes(htmlspecialchars(trim(substr($login,0,20))));
	$password=addslashes(htmlspecialchars(trim(substr($password,0,20))));

	$query ="SELECT * FROM administrators where status=1 and login='".$login."' and password='".md5($password)."'";
	$res = mysql_query($query);

	if(mysql_num_rows($res)==1){
		$row = mysql_fetch_object($res);

		return $row->id;

		/* CHECK ADMIN IP */
		/*
		$row_ip = mysql_fetch_object(mysql_query("select * from system_settings where param_name='block_on_ip';"));
		if($row_ip->param_name!=""&&$row_ip->param_value==$_SERVER["REMOTE_ADDR"]){
			return $row->id;
		}else{
			return 0;
		}
		*/
	}
	else{
		return 0;
	}
}

function MakeAdminLogin($admin_id,$remember=true){
	global $SETTINGS;
	global $SITE_DOMAIN;

	$_SESSION['ADMIN_ID']=$admin_id+0;
	/*setting user login preferences*/

	$row = mysql_fetch_object(mysql_query("select * from administrators where id=$admin_id"));
	if($remember){
		@setcookie("REM_ADMIN_LOGIN",md5($row->login.$row->password),time()+720*3600,"/",$SITE_DOMAIN);
	}
	else{
		@setcookie("REM_ADMIN_LOGIN","",time-100,"/",$SITE_DOMAIN);
	}
}

function MakeAdminLogout($admin_id){
	global $SITE_DOMAIN;
	global $ADMIN_DIR;
	global $SITE_URL;
	setcookie("REM_ADMIN_LOGIN", "", time()-100,"/",$SITE_DOMAIN);
	session_start();
	session_destroy();
	session_unset();
	header ("Cache-Control: no-cache, must-revalidate");
	header ("Location: $SITE_URL");
}


/** partner auth */
function CheckPartnerLoginData($login, $password){
	$login=addslashes(htmlspecialchars(trim(substr($login,0,200))));
	$password=addslashes(htmlspecialchars(trim(substr($password,0,200))));

	$query ="SELECT * FROM partners where status=1 and upper(login)='".strtoupper($login)."' and password='".md5($password)."'";
	$res = mysql_query($query);

	if(mysql_num_rows($res)==1){
		$row = mysql_fetch_object($res);
		return $row->id;
	}
	else{
		return 0;
	}
}

function MakePartnerLogin($partner_id,$remember=true){
	global $SETTINGS;
	global $SITE_DOMAIN;

	$_SESSION['PARTNER_ID']=$partner_id+0;
	/*setting user login preferences*/

	$row = mysql_fetch_object(mysql_query("select * from partners where id=$partner_id"));
	if($remember){
		@setcookie("REM_PARTNER_LOGIN",md5($row->email.$row->password),time()+$SETTINGS[remember_login_timeout]*3600,"/",$SITE_DOMAIN);
	}
	else{
		@setcookie("REM_PARTNER_LOGIN","",time-100,"/",$SITE_DOMAIN);
	}
}

function CheckPartnerLogin(){
	global $_SERVER;
	global $_COOKIE;
	global $PARTNER_URL;

	$PARTNER_ID = -1;
	if (is_numeric($_SESSION["PARTNER_ID"])&&$_SESSION["PARTNER_ID"]>0){

		$row = mysql_fetch_object(mysql_query("select * from partners where status=1 and id=".($_SESSION["PARTNER_ID"]+0)));

		if($row->id==""){
			$_SESSION["PARTNER_ID"] = 0;
			header("Location: $PARTNER_URL/logout.php");
			exit;
		}
		$PARTNER_ID = $_SESSION["PARTNER_ID"];
	}
	elseif(isset($_COOKIE['REM_PARTNER_LOGIN'])&&eregi("^[A-Za-z0-9_]{32}$",$_COOKIE['REM_PARTNER_LOGIN'])){
		$row = mysql_fetch_object(mysql_query("select * from partners where status=1 and  md5(email||password)='".$_COOKIE['REM_PARTNER_LOGIN']."'"));
		if($row->id!=""){
			MakePartnerLogin($row->id,true);
			$PARTNER_ID = $row->id;
		}
	}
	return $PARTNER_ID;
}

function MakePartnerLogout($partner_id){
	global $SITE_DOMAIN;
	global $SITE_URL;
	setcookie("REM_PARTNER_LOGIN", "", time()-100,"/",$SITE_DOMAIN);
	session_start();
	session_destroy();
	session_unset();
	header ("Cache-Control: no-cache, must-revalidate");
	header ("Location: $SITE_URL");
}

/*
* Zip and UnZip functions
*/
function ZipDir(){
	$exec_str = "zip -P $BACKUP_PASSWORD $TMP_ROOT/$zip_fname -j $backup_filename";
	@exec($exec_str);

}

function UnzipDir(){

}

function GetExt($filename) {
	$tmpStr=$filename;
	$arr = split ("\.",$tmpStr);
	$res=$arr[sizeof($arr)-1];
	if (strlen($tmpStr)==strlen($res))
	return "";
	else
	return $res;
}

/*GRAPHICS LIBRARY FUNCTIONS START*/
function CopyResizedImage($src_path,$out_path,$out_width,$out_height){

	global $SETTINGS;
	global $DOCUMENT_ROOT;
	$NO_PHOTO_PATH = $DOCUMENT_ROOT.$SETTINGS['no_photo_path'];
	$size_img = @getimagesize($src_path);

	if(($out_width==0&&$out_height==0)||!file_exists($src_path)||($size_img[0]==0||$size_img[1]==0)){
		$src_path = $NO_PHOTO_PATH;
		$size_img = @getimagesize($src_path);
	}
	elseif($out_width==0){
		$out_width = $out_height*($size_img[0]/$size_img[1]);
	}
	elseif($out_height==0){

		$out_height = $out_width*($size_img[1]/$size_img[0]);
	}

	if($size_img[0]/$size_img[1] > $out_width/$out_height){
		$src_x = ($size_img[0] - ($out_width/$out_height)*$size_img[1])/2;
		$src_y = 0;
		$src_w = ($out_width/$out_height)*$size_img[1];
		$src_h = $size_img[1];
	}
	else{
		$src_x = 0;
		$src_y = ($size_img[1] - ($out_height/$out_width)*$size_img[0])/2;
		$src_w = $size_img[0];
		$src_h = ($out_height/$out_width)*$size_img[0];
	}

	ob_start();

	$dst_img = imagecreatetruecolor($out_width, $out_height);
	switch($size_img[2]){
		case 1:
			$src_img = imagecreatefromgif($src_path);
			break;
		case 2:
			$src_img = imagecreatefromjpeg($src_path);
			break;
		case 3:
			$src_img = imagecreatefrompng($src_path);
			break;
		default:
			$src_img = imagecreatefromjpeg($NO_PHOTO_PATH);
			break;
	}


	imagecopyresampled($dst_img,$src_img,0,0,$src_x,$src_y,$out_width,$out_height,$src_w,$src_h);

	imagejpeg($dst_img, '', 80);
	imagedestroy($dst_img);

	$p = ob_get_contents();
	ob_end_clean();

	$fp = fopen($out_path,"w");
	fwrite($fp,$p);
	fclose($fp);
}

/*GRAPHICS LIBRARY FUNCTIONS END*/

function CategoryGetNavStr($cat_id,$cat_type){
	$arr = Array();
	global $SITE_URL;
	global $CATEGORY_DIR;
	global $SETTINGS;

	$row = mysql_fetch_object(mysql_query("select * from ".($cat_type==0?"school_categories":"thematic_categories")." where id=$cat_id"));

	$tmp_arr = Array(
	"name" => stripslashes($row->name),
	"title" => stripslashes($row->name),
	"url" => $SITE_URL.$CATEGORY_DIR.($cat_type==0?$SETTINGS['school_category_path']:$SETTINGS['thematic_category_path']).GetCategoryStaticPath($cat_id,$cat_type)
	);
	array_push($arr,$tmp_arr);

	if($row->parent_id>0){
		$arr = array_merge($arr,CategoryGetNavStr($row->parent_id,$cat_type));
	}
	return $arr;
}

function RegisterWorksheet($params){

	$res = mysql_query("select * from worksheets where params='".serialize($params['params'])."'");

	if(mysql_num_rows($res)>0){
		$row = mysql_fetch_object($res);
		return $row->id;
	}

	$arr = Array(
	"name" => $params['name'],
	"sys_id" => GenWorksheetSystemId($params['params'],$params['template_id'],$params['client_id']),
	"template_id" => $params['template_id'],
	"regdate" => time(),
	"params" => serialize($params['params']),
	"is_default" => $params['is_default']==1?1:0
	);

	if($params['client_id']>0){
		$arr['client_id'] = $params['client_id'];
	}

	if(($id=AddRecord("worksheets",$arr,true))){
		return $id;
	}

	return -1;
}

function CalcOrders($client_id){
	$client_id+=0;
	$res=mysql_query("select amount, currency_id from orders where client_id='$client_id' and status=1");
	// echo "select amount, currency_id from orders where client_id='$client_id' and status=1";
	$count=0;
	$curr_rates=Array();
	$amount=0;
	$default_currency_id=mysql_fetch_object(mysql_query("select id from currencies where is_default=true"));
	$default_currency_id=$default_currency_id->id;
	while($row=mysql_fetch_object($res)){
		if (!$curr_rates[$row->currency_id]) {
			$curr_rates[$row->currency_id]=GetCourseByID($row->currency_id,$default_currency_id);
		}
		$amount+=round($row->amount*$curr_rates[$row->currency_id]);
		$count++;
	} // while
	$res=Array();
	$res[cnt]=$count;
	$res[amount]=$amount;
	return $res;
}

function CalcDiscount($client_id){
	$client_id+=0;
	$client_row=mysql_fetch_object(mysql_query("select * from clients where id=$client_id and discount_autocalc=true"));
	if (!$client_row->id) {
		return false;
	}
	$orders=CalcOrders($client_id);
	$res=mysql_query("select * from discounts where status=1");
	$control_sum=0;
	while($row=mysql_fetch_object($res)){
		switch(intval($row->type)){
			case 0:
				if ($orders[amount]<$row->amount) {
					$row->discount_fix=0;
					$row->discount_perc=0;
				};
				break;
			case 1:
				if ($orders[cnt]<$row->amount) {
					$row->discount_fix=0;
					$row->discount_perc=0;
				};
				break;
		} // switch
		$curr_id=$row->currency_id+0;
		$tmp_sum=100*$row->discount_perc+$row->discount_fix;
		if ($tmp_sum>$control_sum) {
			$control_sum=$tmp_sum;
			$discount_perc=$row->discount_perc;
			$discount_fix=$row->discount_perc;
		}
	} // while
	if ((floatval($client_row->discount_perc)!=floatval($discount_perc))||(floatval($client_row->discount_fix)!=floatval($discount_fix))) {
		UpdateRecord("clients",Array("discount_perc"=>$discount_perc+0,"discount_fix"=>$discount_fix+0,"discount_currency_id"=>$curr_id),$client_id);
	}
}

function DeleteDirectory($file) {
	if (!is_dir($file)&&!is_file($file)) {
		return false;
	}
	chmod($file,0777);

	if (is_dir($file)) {
		$handle = opendir($file);
		while($filename = readdir($handle)) {
			if ($filename != "." && $filename != "..") {
				deleteDirectory($file."/".$filename);
			}
		}
		closedir($handle);
		rmdir($file);
	} else {
		unlink($file);
	}
}


function GetModuleDirs($module_code){
	global $MODULE_DIRS;
	$module_code=trim($module_code);
	if (!$module_code) {
		return false;
	}
	$res=array();
	foreach ($MODULE_DIRS as $key=>$val){
		$res[$key]=str_replace("_MODULE_CODE_",$module_code,$val);
	}
	return $res;
}


function CreateModuleObject($id=null,$template_id=null){
	global $MODULE_DIR,$PROJECT_ROOT;
	$id+=0;
	$template_id+=0;
	if (($template_id>0)&&($id<=0)) {
		// 	echo "select module_id from worksheet_templates2modules where id='$template_id'";
		$id=mysql_fetch_object(mysql_query("select module_id from worksheet_templates2modules where id='$template_id'"));
		//	 echo $id->$id->module_id;
		$id=$id->module_id+0;
	}

	$m_row = mysql_fetch_object(mysql_query("select * from task_modules where id=$id"));

	if(!$m_row->id){
		die("Module not found.");
	}

	$dirs=GetModuleDirs($m_row->code);
	if (file_exists($dirs[source_dir]."/class.php")) {
		include_once($dirs[source_dir]."/class.php");
	}
	else{
		return null;
	}

	$var_name = "TModule_".$m_row->code;
	$module = new $var_name($id,$template_id);
	$module->code   = $m_row->code;
	$module->description  = $m_row->description;

	return $module;
}

function GenerateDefaultWorksheet($template_id){
	$template_row=mysql_fetch_object(mysql_query("select name from worksheet_templates where id='".($template_id+0)."'"));
	$template_name=$template_row->name;
	$worksheet=new TWorkSheet($template_id);
	$ws_id=mysql_fetch_object(mysql_query("select id from worksheets where template_id='".($template_id+0)."' and is_default=true"));
	$ws_id=$ws_id->id;
	$sys_id="D".sprintf('%05d',$template_id)."-00001";
	$ws_arr=     Array("template_id"=>$template_id,
	"regdate"=>time(),
	"is_default"=>1,
	"name"=>$template_name,
	"sys_id"=>$sys_id,
	"params"=>serialize($worksheet->GetParameters())
	);
	if (!$ws_id) {
		$res=AddRecord("worksheets",$ws_arr);
	}
	else{
		$res=UpdateRecord("worksheets",$ws_arr,$ws_id);
	}
	return $res;
}

function GenWorksheetSystemId($params,$template_id,$client_id=null){

	$res = mysql_query("select * from worksheets where params = '".addslashes(serialize($params))."' and ".($template_id>0?"template_id=$template_id":"client_id=$client_id"));

	//	echo "select * from worksheets where params = '".serialize($params)."' and ".($template_id>0?"template_id=$template_id":"client_id=$client_id");

	if(mysql_num_rows($res)>0){
		$row = mysql_fetch_object($res);
		return $row->sys_id;
	}
	else{
		$flag = true;
		while($flag){
			$sys_id = ($template_id>0?"T".sprintf("%05d",$template_id):"C".sprintf("%05d",$client_id))."-".GenRandom(5);
			$res = mysql_query("select * from worksheets where sys_id = '$sys_id'");
			if(mysql_num_rows($res)==0){
				$flag = false;
				return $sys_id;
			}
		}
	}
}

function CheckCatSubscription($school_category_id,$client_id){
	/*	if($school_category_id==49){
	echo $query;
	}*/
	$cat_row = mysql_fetch_object(mysql_query("select * from school_categories where id=$school_category_id"));

	$query = "select * from
	((clients2tariffs inner join tariffs on tariffs.id = clients2tariffs.tariff_id)
	left outer join tariffs2categories on tariffs2categories.tariff_id = clients2tariffs.tariff_id) left outer join school_categories on school_categories.id = tariffs2categories.category_id where (school_categories.articul like '$cat_row->articul%' or substr('$cat_row->articul',1,length(school_categories.articul)) = school_categories.articul or tariffs.tariff_type=0) and clients2tariffs.client_id=$client_id and clients2tariffs.status=1";

	$res = mysql_query($query);

	if(mysql_num_rows($res)>0){
		return true;
	}
	else{
		return false;
	}
}

function IsActiveMember($client_id){
	$query = "select * from clients2tariffs where clients2tariffs.client_id=$client_id and clients2tariffs.status=1";
	$res = mysql_query($query);
	if(mysql_num_rows($res)>0){
		return true;
	}
	else{
		return false;
	}
}

function ExtDbConnect(){
	global $EXT_DB_HOST,
	$EXT_DB_NAME,
	$EXT_DB_USER,
	$EXT_DB_PASS;
	if (!defined("EXT_DB_LINK")) {
		define("EXT_DB_LINK", mysql_pconnect("host=$EXT_DB_HOST dbname=$EXT_DB_NAME user=$EXT_DB_USER password=$EXT_DB_PASS"));
	}
	if (!EXT_DB_LINK) {
		die("Could not connect to external database.");
	}
	return EXT_DB_LINK;
}

function CompareExtDb(){
	global $DB_LINK;
	ExtDbConnect();
	//	echo EXT_DB_LINK;
	$res=mysql_query(EXT_DB_LINK,"select id, last_change_date from worksheet_templates");
	while($row=mysql_fetch_object($res)){
		$ext_ws[$row->id]=$row;
		//		echo $row->id."<br>";
	} // while

	$res=mysql_query("select id, last_change_date from worksheet_templates");

	while($row=mysql_fetch_object($res)){
		$int_ws[$row->id]=$row;
	} // while

	$dfr_arr=Array();
	foreach ($int_ws as $key=>$val){
		/*if ($key==255) {
		print_r($ext_val[$key]);
		echo "<br>";
		echo $ext_ws[$key]->last_change_date." !".$int_ws[$key]->last_change_date."<br>";
		echo (strtotime($ext_ws[$key]->last_change_date)+29400)." ".strtotime($int_ws[$key]->last_change_date)."<br>";
		}*/
		if (!$ext_ws[$key]){
			$dfr_arr[$val->id]=array($val->id,1);
		}
		elseif(strtotime($ext_ws[$key]->last_change_date)+29000<strtotime($int_ws[$key]->last_change_date)){
			$dfr_arr[$val->id]=array($val->id,0);
		}
	}
	return $dfr_arr;
}


function MakeQuery($table,$arr,$action=0){
	if ($action==0) {
		foreach ($arr as $key=>$val){
			$fields.=", $key";
			if (is_null($val)) {
				$val="null";
			}
			else{
				$val="'".addslashes($val)."'";
			}

			$values.=", ".$val;
		}
		$fields=substr($fields,1);
		$values=substr($values,1);
		$str="insert into $table ($fields) values($values);";
		return $str;
	}
	elseif($action=1){
		foreach ($arr as $key=>$val){
			if (is_null($val)) {
				$val="null";
			}
			else{
				$val="'".addslashes($val)."'";
			}
			$fields.=", $key=".$val."";
		}
		$fields=substr($fields,1);
		$str="update $table set $fields where id='".($arr[id]+0)."';";
		return $str;
	}
}

function UploadWorkSheet($ws_id){
	global $DB_LINK;
	ExtDbConnect();

	$res=mysql_query("select * from worksheet_templates where id='".($ws_id+0)."'");
	$row=mysql_fetch_assoc($res);
	$res_ch=mysql_query(EXT_DB_LINK,"select * from worksheet_templates where id='".($ws_id+0)."'");
	//	echo $res_ch;
	//	print_r(mysql_fetch_object($res_ch));
	$res_ch=$res_ch&&mysql_fetch_object($res_ch);
	if ($res_ch) {
		$query=MakeQuery("worksheet_templates",$row,1);
	}
	else{
		$query=MakeQuery("worksheet_templates",$row,0);
	}
	//	$row_ch=mysql_fetch_assoc($res);

	$query.="\nDelete from worksheet_templates2modules where template_id='".($ws_id+0)."';";
	$res=mysql_query("select * from worksheet_templates2modules where template_id='".($ws_id+0)."'");
	while($row=mysql_fetch_assoc($res)){
		$query.="\n".MakeQuery("worksheet_templates2modules",$row,0);
		$modules[]=$row[module_id];
		//		echo "<br>111 $row->module_id<br>";
	} // while
	$query.="\nDelete from worksheets where template_id='$ws_id' and is_default='t';";
	/*	$res=mysql_query(EXT_DB_LINK,"select * from worksheets where template_id='$ws_id' and is_default='t'");
	if ($res) {
	$query.="\n".MakeQuery("worksheets",$row,1);
	}
	else{*/
	//	}
	//	$res=mysql_query(EXT_DB_LINK,$query);
	$res=mysql_query("select * from worksheets where template_id='$ws_id' and is_default='t'");
	$row=mysql_fetch_assoc($res);
	unset($row[id]);
	//	array_splice($row,0 ,1);
	$query.="\n".MakeQuery("worksheets",$row,0);

	$res=array("modules"=>$modules,"query"=>$query);
	//	echo $query."<br><Br><Br>";
	return $res;
}

function FTPmkdir($conn_id,$dir){
	global $CONN_ID;
	@ftp_mkdir($CONN_ID,"/".$dir);
	$dirs=split("/",$dir);
	$dd="";
	foreach ($dirs as $val){
		if (trim($val)) {
			$dd.="/".$val;
			//			echo $dd."<br>";
			@ftp_mkdir($CONN_ID,$dd);
		}
	}
}

function FtpConnect(){
	global $FTP_SERVER,$FTP_USER_NAME, $FTP_USER_PASS,$CONN_ID;
	$CONN_ID=ftp_connect($FTP_SERVER);
	//	$conn_id = ;
	$login_result = ftp_login($CONN_ID, $FTP_USER_NAME, $FTP_USER_PASS);
	if ((!$CONN_ID) || (!$login_result)) {
		$res=false;
	}
	else{
		$res=true;
	}
	return $res;
}

function FtpDisconnect(){
	global $CONN_ID;
	if ($CONN_ID) {
		$res=@ftp_close($CONN_ID);
		unset($CONN_ID);
	}
	return $res;
}

function FTPPutFile($source_file,$destination_file=""){
	global $CONN_ID;
	$res=true;
	if ($res) {
		//		echo $destination_file." ".$source_file."<br>\n";
		$res=ftp_put($CONN_ID, $destination_file, $source_file, FTP_BINARY);
	}
	return $res;
}

function SynchronizeDirs($localdir,$ftpdir){
	GLOBAL $CONN_ID;
	$res=true;
	if (is_dir($localdir)&&($handle = opendir($localdir))) {
		$res=true;
		$all_dirs=array();
		while (false !== ($file = readdir($handle))) {
			if (is_file($localdir."/".$file)) {
				//		echo $localdir."/".$file."<br>";
				@chmod($localdir."/".$file,0777);

				$dir=$ftpdir;
				//substr($ftpdir,0,strrpos($destination_file,"/")+1);
				//			echo $ftpdir."<bR>";
				if (!in_array($dir,$all_dirs)) {
					FTPmkdir($CONN_ID,$dir);
					$all_dirs[]=$dir;
				}
				$res=$res&&FTPPutFile($localdir."/".$file,$ftpdir."/".$file);
			}
		}
		closedir($handle);
	}
	return $res;
}

function UploadModule($module_id){
	global $FTP_DIRS,$DB_LINK,$CONN_ID;
	FtpDisconnect();
	unset($CONN_ID);
	ExtDbConnect();
	$res=true;
	$module_id+=0;
	$res=mysql_query("select * from task_modules where id='".($module_id+0)."'");
	$module_row=mysql_fetch_assoc($res);
	if (!is_array($module_row)) {
		return false;
	}
	/*	echo "<br> $module_id module_row=";
	print_r($module_row);
	echo "<br>";*/
	//	print_r($module_row);
	$res_ch=@mysql_fetch_object(mysql_query(EXT_DB_LINK,"select * from task_modules where id='".($module_id+0)."'"));
	if ($res_ch) {
		$query=MakeQuery("task_modules",$module_row,1)."\n";
	}
	else{
		$query=MakeQuery("task_modules",$module_row,0)."\n";
	}
	include_once("em_install_functions.php");
	$query=MakeModuleTablesDump($module_row[code],true).$query;
	$module_dirs=GetModuleDirs($module_row[code]);
	//	echo "<br>fconn_id=".$CONN_ID."<br>";
	if (!$CONN_ID) {
		FtpConnect();
	}
	foreach ($module_dirs as $key=>$val){
		$ftp_dir=str_replace("_MODULE_CODE_",$module_row[code],$FTP_DIRS[$key]);
		$res=$res&&SynchronizeDirs($val,$ftp_dir );
	}
	FtpDisconnect();
	$res=$res&&mysql_query(EXT_DB_LINK,$query);
	//	echo $query."<br>";
	return $res;
}


function PMA_getIp(){
	global $REMOTE_ADDR;
	global $HTTP_X_FORWARDED_FOR, $HTTP_X_FORWARDED, $HTTP_FORWARDED_FOR, $HTTP_FORWARDED;
	global $HTTP_VIA, $HTTP_X_COMING_FROM, $HTTP_COMING_FROM;
	global $HTTP_SERVER_VARS, $HTTP_ENV_VARS;

	// Get some server/environment variables values
	if (empty($REMOTE_ADDR)) {
		if (!empty($_SERVER) && isset($_SERVER['REMOTE_ADDR'])) {
			$REMOTE_ADDR = $_SERVER['REMOTE_ADDR'];
		}
		else if (!empty($_ENV) && isset($_ENV['REMOTE_ADDR'])) {
			$REMOTE_ADDR = $_ENV['REMOTE_ADDR'];
		}
		else if (!empty($HTTP_SERVER_VARS) && isset($HTTP_SERVER_VARS['REMOTE_ADDR'])) {
			$REMOTE_ADDR = $HTTP_SERVER_VARS['REMOTE_ADDR'];
		}
		else if (!empty($HTTP_ENV_VARS) && isset($HTTP_ENV_VARS['REMOTE_ADDR'])) {
			$REMOTE_ADDR = $HTTP_ENV_VARS['REMOTE_ADDR'];
		}
		else if (@getenv('REMOTE_ADDR')) {
			$REMOTE_ADDR = getenv('REMOTE_ADDR');
		}
	} // end if
	if (empty($HTTP_X_FORWARDED_FOR)) {
		if (!empty($_SERVER) && isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
			$HTTP_X_FORWARDED_FOR = $_SERVER['HTTP_X_FORWARDED_FOR'];
		}
		else if (!empty($_ENV) && isset($_ENV['HTTP_X_FORWARDED_FOR'])) {
			$HTTP_X_FORWARDED_FOR = $_ENV['HTTP_X_FORWARDED_FOR'];
		}
		else if (!empty($HTTP_SERVER_VARS) && isset($HTTP_SERVER_VARS['HTTP_X_FORWARDED_FOR'])) {
			$HTTP_X_FORWARDED_FOR = $HTTP_SERVER_VARS['HTTP_X_FORWARDED_FOR'];
		}
		else if (!empty($HTTP_ENV_VARS) && isset($HTTP_ENV_VARS['HTTP_X_FORWARDED_FOR'])) {
			$HTTP_X_FORWARDED_FOR = $HTTP_ENV_VARS['HTTP_X_FORWARDED_FOR'];
		}
		else if (@getenv('HTTP_X_FORWARDED_FOR')) {
			$HTTP_X_FORWARDED_FOR = getenv('HTTP_X_FORWARDED_FOR');
		}
	} // end if
	if (empty($HTTP_X_FORWARDED)) {
		if (!empty($_SERVER) && isset($_SERVER['HTTP_X_FORWARDED'])) {
			$HTTP_X_FORWARDED = $_SERVER['HTTP_X_FORWARDED'];
		}
		else if (!empty($_ENV) && isset($_ENV['HTTP_X_FORWARDED'])) {
			$HTTP_X_FORWARDED = $_ENV['HTTP_X_FORWARDED'];
		}
		else if (!empty($HTTP_SERVER_VARS) && isset($HTTP_SERVER_VARS['HTTP_X_FORWARDED'])) {
			$HTTP_X_FORWARDED = $HTTP_SERVER_VARS['HTTP_X_FORWARDED'];
		}
		else if (!empty($HTTP_ENV_VARS) && isset($HTTP_ENV_VARS['HTTP_X_FORWARDED'])) {
			$HTTP_X_FORWARDED = $HTTP_ENV_VARS['HTTP_X_FORWARDED'];
		}
		else if (@getenv('HTTP_X_FORWARDED')) {
			$HTTP_X_FORWARDED = getenv('HTTP_X_FORWARDED');
		}
	} // end if
	if (empty($HTTP_FORWARDED_FOR)) {
		if (!empty($_SERVER) && isset($_SERVER['HTTP_FORWARDED_FOR'])) {
			$HTTP_FORWARDED_FOR = $_SERVER['HTTP_FORWARDED_FOR'];
		}
		else if (!empty($_ENV) && isset($_ENV['HTTP_FORWARDED_FOR'])) {
			$HTTP_FORWARDED_FOR = $_ENV['HTTP_FORWARDED_FOR'];
		}
		else if (!empty($HTTP_SERVER_VARS) && isset($HTTP_SERVER_VARS['HTTP_FORWARDED_FOR'])) {
			$HTTP_FORWARDED_FOR = $HTTP_SERVER_VARS['HTTP_FORWARDED_FOR'];
		}
		else if (!empty($HTTP_ENV_VARS) && isset($HTTP_ENV_VARS['HTTP_FORWARDED_FOR'])) {
			$HTTP_FORWARDED_FOR = $HTTP_ENV_VARS['HTTP_FORWARDED_FOR'];
		}
		else if (@getenv('HTTP_FORWARDED_FOR')) {
			$HTTP_FORWARDED_FOR = getenv('HTTP_FORWARDED_FOR');
		}
	} // end if
	if (empty($HTTP_FORWARDED)) {
		if (!empty($_SERVER) && isset($_SERVER['HTTP_FORWARDED'])) {
			$HTTP_FORWARDED = $_SERVER['HTTP_FORWARDED'];
		}
		else if (!empty($_ENV) && isset($_ENV['HTTP_FORWARDED'])) {
			$HTTP_FORWARDED = $_ENV['HTTP_FORWARDED'];
		}
		else if (!empty($HTTP_SERVER_VARS) && isset($HTTP_SERVER_VARS['HTTP_FORWARDED'])) {
			$HTTP_FORWARDED = $HTTP_SERVER_VARS['HTTP_FORWARDED'];
		}
		else if (!empty($HTTP_ENV_VARS) && isset($HTTP_ENV_VARS['HTTP_FORWARDED'])) {
			$HTTP_FORWARDED = $HTTP_ENV_VARS['HTTP_FORWARDED'];
		}
		else if (@getenv('HTTP_FORWARDED')) {
			$HTTP_FORWARDED = getenv('HTTP_FORWARDED');
		}
	} // end if
	if (empty($HTTP_VIA)) {
		if (!empty($_SERVER) && isset($_SERVER['HTTP_VIA'])) {
			$HTTP_VIA = $_SERVER['HTTP_VIA'];
		}
		else if (!empty($_ENV) && isset($_ENV['HTTP_VIA'])) {
			$HTTP_VIA = $_ENV['HTTP_VIA'];
		}
		else if (!empty($HTTP_SERVER_VARS) && isset($HTTP_SERVER_VARS['HTTP_VIA'])) {
			$HTTP_VIA = $HTTP_SERVER_VARS['HTTP_VIA'];
		}
		else if (!empty($HTTP_ENV_VARS) && isset($HTTP_ENV_VARS['HTTP_VIA'])) {
			$HTTP_VIA = $HTTP_ENV_VARS['HTTP_VIA'];
		}
		else if (@getenv('HTTP_VIA')) {
			$HTTP_VIA = getenv('HTTP_VIA');
		}
	} // end if
	if (empty($HTTP_X_COMING_FROM)) {
		if (!empty($_SERVER) && isset($_SERVER['HTTP_X_COMING_FROM'])) {
			$HTTP_X_COMING_FROM = $_SERVER['HTTP_X_COMING_FROM'];
		}
		else if (!empty($_ENV) && isset($_ENV['HTTP_X_COMING_FROM'])) {
			$HTTP_X_COMING_FROM = $_ENV['HTTP_X_COMING_FROM'];
		}
		else if (!empty($HTTP_SERVER_VARS) && isset($HTTP_SERVER_VARS['HTTP_X_COMING_FROM'])) {
			$HTTP_X_COMING_FROM = $HTTP_SERVER_VARS['HTTP_X_COMING_FROM'];
		}
		else if (!empty($HTTP_ENV_VARS) && isset($HTTP_ENV_VARS['HTTP_X_COMING_FROM'])) {
			$HTTP_X_COMING_FROM = $HTTP_ENV_VARS['HTTP_X_COMING_FROM'];
		}
		else if (@getenv('HTTP_X_COMING_FROM')) {
			$HTTP_X_COMING_FROM = getenv('HTTP_X_COMING_FROM');
		}
	} // end if
	if (empty($HTTP_COMING_FROM)) {
		if (!empty($_SERVER) && isset($_SERVER['HTTP_COMING_FROM'])) {
			$HTTP_COMING_FROM = $_SERVER['HTTP_COMING_FROM'];
		}
		else if (!empty($_ENV) && isset($_ENV['HTTP_COMING_FROM'])) {
			$HTTP_COMING_FROM = $_ENV['HTTP_COMING_FROM'];
		}
		else if (!empty($HTTP_COMING_FROM) && isset($HTTP_SERVER_VARS['HTTP_COMING_FROM'])) {
			$HTTP_COMING_FROM = $HTTP_SERVER_VARS['HTTP_COMING_FROM'];
		}
		else if (!empty($HTTP_ENV_VARS) && isset($HTTP_ENV_VARS['HTTP_COMING_FROM'])) {
			$HTTP_COMING_FROM = $HTTP_ENV_VARS['HTTP_COMING_FROM'];
		}
		else if (@getenv('HTTP_COMING_FROM')) {
			$HTTP_COMING_FROM = getenv('HTTP_COMING_FROM');
		}
	} // end if

	// Gets the default ip sent by the user
	if (!empty($REMOTE_ADDR)) {
		$direct_ip = $REMOTE_ADDR;
	}

	// Gets the proxy ip sent by the user
	$proxy_ip     = '';
	if (!empty($HTTP_X_FORWARDED_FOR)) {
		$proxy_ip = $HTTP_X_FORWARDED_FOR;
	} else if (!empty($HTTP_X_FORWARDED)) {
		$proxy_ip = $HTTP_X_FORWARDED;
	} else if (!empty($HTTP_FORWARDED_FOR)) {
		$proxy_ip = $HTTP_FORWARDED_FOR;
	} else if (!empty($HTTP_FORWARDED)) {
		$proxy_ip = $HTTP_FORWARDED;
	} else if (!empty($HTTP_VIA)) {
		$proxy_ip = $HTTP_VIA;
	} else if (!empty($HTTP_X_COMING_FROM)) {
		$proxy_ip = $HTTP_X_COMING_FROM;
	} else if (!empty($HTTP_COMING_FROM)) {
		$proxy_ip = $HTTP_COMING_FROM;
	} // end if... else if...

	// Returns the true IP if it has been found, else FALSE
	if (empty($proxy_ip)) {
		// True IP without proxy
		return $direct_ip;
	} else {
		$is_ip = ereg('^([0-9]{1,3}\.){3,3}[0-9]{1,3}', $proxy_ip, $regs);
		if ($is_ip && (count($regs) > 0)) {
			// True IP behind a proxy
			return $regs[0];
		} else {
			// Can't define IP: there is a proxy but we don't have
			// information about the true IP
			return FALSE;
		}
	} // end if... else...
} // end of the 'PMA_getIp()' function
//	echo phpinfo();
?>