<?php
/**
 * DotPay.pl API Payment Module
 *
 * @package paymentMethod
 * @copyright Copyright 2003-2010 Zen Cart Development Team
 * @copyright Portions Copyright 2003 osCommerce
 * @copyright Portions Copyright 2003 Jason LeBaron
 * @license Commercial Zen Cart Professional
 * @version $Id: linkpoint_api.php 18013 2010-10-22 03:38:29Z drbyte $
 */
$dotpaypl_error_serial = 0;

$dotpaypl_instance_id = time();

function dotpaypl_add_error_log($message) {
  global  $dotpaypl_instance_id;
  $log_path = MODULE_PAYMENT_DOTPAYPL_LOGS;
  if(empty($log_path)) {
  	$log_path = DIR_FS_CATALOG.'logs/dotpaypl/'; 
  }
  if($log_path[strlen($log_path)-1] != '/') {
  	$log_path .= '/';
  }
  ;
  if(($fp = @fopen($log_path.'dotpaypl_' . $dotpaypl_instance_id . '.log', 'a')) !== false) {
	  @fwrite($fp, date('Y-m-d H:i:s') . ' -- ' . $message . "\n\n");
	  @fclose($fp);
  }
} 

function dotpaypl_debug_email($message, $email_address = MODULE_PAYMENT_DOTPAYPL_DEBUG_EMAIL, $always_send = false) {
	if (MODULE_PAYMENT_DOTPAYPL_DEBUG == 'Plik i Email' || $always_send) {
		global $dotpaypl_error_serial, $dotpaypl_instance_id;
		if(empty($email_address)) {
			$email_address = STORE_OWNER_EMAIL_ADDRESS;
		}
		$dotpaypl_error_serial ++;
		mail($email_address,'evDotPay DEBUG instance (' . $dotpaypl_instance_id . ') #' . $dotpaypl_error_serial, $message);
	}
	if (MODULE_PAYMENT_DOTPAYPL_DEBUG == 'Plik i Email' || MODULE_PAYMENT_DOTPAYPL_DEBUG == 'Plik') 
		dotpaypl_add_error_log($message);
	if(MODULE_PAYMENT_DOTPAYPL_DIAG == 'Tak') {
		$pos = strpos($message,"\n");
		$pos = (($pos<50) ? $pos : 80);
		print substr($message,0, $pos)."\n";
	}
} 

function dotpaypl_get_stored_session($session_nr) {
	global $db;
	
	if (!preg_match('/[a-z0-9]{32}/',$session_nr)) {
		dotpaypl_debug_email('dotpaypl_get_stored_session:ERROR:: Error data bug.'."\n\nSession stuff=".print_r($session_nr,true));
		return false;
	}
	$sql = "SELECT * FROM " . TABLE_DOTPAYPL_SESSION . " WHERE session_id = :sessionID";
	$sql = $db->bindVars($sql, ':sessionID', $session_nr, 'string');
	$stored_session = $db->Execute($sql);
	dotpaypl_debug_email('dotpaypl_get_stored_session:INFO::'."\n\n".'Session Query='.$sql."\n\nSession_stuff = ".print_r($session_nr, true));
	if ($stored_session->recordCount() < 1) {
		dotpaypl_debug_email('dotpaypl_get_stored_session:ERROR:: Error session.'."\n\nSession stuff=".print_r($session_nr,true));
		return false;
	}
	$_SESSION = unserialize(base64_decode($stored_session->fields['saved_session']));
	return true;
} 

function dotpaypl_store_session($session_nr) {
	global $db;
	
	if (!preg_match('/[a-z0-9]{32}/',$session_nr)) {
		dotpaypl_debug_email('dotpaypl_store_session:ERROR:: Error session.'."\n\nSession stuff=".print_r($session_nr,true));
		return false;
	}
	
	$db->Execute("delete from " . TABLE_DOTPAYPL_SESSION . " where session_id = '" . $session_nr . "'");
	$sql = "insert into " . TABLE_DOTPAYPL_SESSION . " (session_id, saved_session, expiry) values (
	        '" . $session_nr . "',
	        '" . base64_encode(serialize($_SESSION)) . "',
	        '" . (time() + (1*60*60*24*2)) . "')";
	$db->Execute($sql);
	return true;
} 

function dotpaypl_get_status() {
	switch ($_POST['t_status']) {
			case 1: return array('code' => $_POST['t_status'], 'message' => 'nowa'); break;
			case 2: return array('code' => $_POST['t_status'], 'message' => 'wykonana'); break;
			case 3: return array('code' => $_POST['t_status'], 'message' => 'odmowna'); break;
			case 4: return array('code' => $_POST['t_status'], 'message' => 'anulowana'); break;
			case 5: return array('code' => $_POST['t_status'], 'message' => 'reklamacja'); break;
			default: return array('code' => false, 'message' => 'brak statusu'); break;
	}
} 

function dotpaypl_validate_URLC_Call() {

	$md5str = MODULE_PAYMENT_DOTPAYPL_PIN_URLC.':'.MODULE_PAYMENT_DOTPAYPL_ID_SPRZEDAWCY.':'.$_POST['control'].':'.$_POST['t_id'].
			':'.$_POST['amount'].':'.$_POST['email'].':'.$_POST['service'].':'.$_POST['code'].':'.$_POST['username'].
			':'.$_POST['password'].':'.$_POST['t_status'];
	
	$md5 = md5($md5str);
	$result = true;
	
	if($_SERVER['REMOTE_ADDR']!='217.17.41.5' && $_SERVER['REMOTE_ADDR']!='195.150.9.37') {
		dotpaypl_debug_email('dotpaypl_validate_URLC_Call:ERROR:: Validate 0. Error IP : '.$_SERVER['id']."\n\nPOST : ".print_r($_POST,true));
		$result = false;
	}
	
	elseif ($_POST['id'] != MODULE_PAYMENT_DOTPAYPL_ID_SPRZEDAWCY) {
		dotpaypl_debug_email('dotpaypl_validate_URLC_Call:ERROR:: Validate 1. ('.MODULE_PAYMENT_DOTPAYPL_ID_SPRZEDAWCY.') Error ID shop: '.$_POST['id']."\n\nPOST : ".print_r($_POST,true));
		$result = false;
	}
	
	elseif(!preg_match('/[0-9]+-[0-9A-Za-z]{6}/',$_POST['control'])) {
		dotpaypl_debug_email('dotpaypl_validate_URLC_Call:ERROR:: Validate 2a. Error ref_id: '.$_POST['control']."\n\nPOST : ".print_r($_POST,true));
		$result = false;
	}
	
	elseif($_SESSION['dotpaypl_ref_id'] !== $_POST['control']) {
		dotpaypl_debug_email('dotpaypl_validate_URLC_Call:ERROR:: Validate 2b. ref_id error: '.$_POST['control']."\n\nPOST : ".print_r($_POST,true));
		$result = false;
	}
	
	elseif (!preg_match('/[1-5]/',$_POST['t_status'])) {
		dotpaypl_debug_email('dotpaypl_validate_URLC_Call:ERROR:: Validate 3. Error transaction status : '.$_POST['t_status']."\n\nPOST : ".print_r($_POST,true));
		$result = false;
	}
	
	elseif(!preg_match('/[0-9]+\.[0-9]{2}/',$_POST['amount'])) {
		dotpaypl_debug_email('dotpaypl_validate_URLC_Call:ERROR:: Validate 4. Error currency: '.$_POST['amount']."\n\nPOST : ".print_r($_POST,true));
		$result = false;
	}
	
	elseif($_POST['status']!='OK' && $_POST['status']!='FAIL') {
		dotpaypl_debug_email('dotpaypl_handler:ERROR:: Error \'status\': '.$_POST['status']."\n\nPOST : ".print_r($_POST,true));
		$result = false;
	}
	
	elseif($_POST['md5']!=$md5) {
		dotpaypl_debug_email('dotpaypl_handler:ERROR:: Error hash: '.$md5."\n\n$md5str\n\nPOST : ".print_r($_POST,true));
		$result = false;
	}	
	return $result;
} 

function dotpaypl_get_orders_id($ref_id) {
	global $db;

	$sql = "SELECT * FROM " . TABLE_DOTPAYPL . " WHERE ref_id = :refID  LIMIT 1";
	$sql = $db->bindVars($sql, ':refID', $ref_id, 'string');
	$stored_transaction = $db->Execute($sql);
	dotpaypl_debug_email('dotpaypl_get_orders_id:INFO::'."\n\n".'Query='.$sql);
	if ($stored_transaction->recordCount() < 1) {
		dotpaypl_debug_email('dotpaypl_get_orders_id:ERROR:: Error search ref_id .');
		return false;
	}
	$orders_id = $stored_transaction->fields['orders_id'];
	if(empty($orders_id)) {
			dotpaypl_debug_email('dotpaypl_get_orders_id:ERROR:: Error ref_id, bug orders_id .');
		return false;
	}
	dotpaypl_debug_email('dotpaypl_get_orders_id:SUCCESS:: Search success ref_id = '.$ref_id.'.'."\n\n".'orders_id='.$orders_id);
	return $orders_id;
} 

function dotpaypl_store_orders_status_history($orders_id, $orders_status_id, $customer_notified, $comments) {
	global $db;
	
	$check_status = $db->Execute("select customers_name, customers_email_address, orders_status,
	                              date_purchased from " . TABLE_ORDERS . "
	                              where orders_id = '" . (int)$orders_id . "'");
	
dotpaypl_debug_email("dotpaypl_store_orders_status_history:\ncheck_status:".print_r($check_status,true));

	if ( ($check_status->fields['orders_status'] != $orders_status_id)) {
		$db->Execute("update " . TABLE_ORDERS . " set orders_status = '" . $orders_status_id . "', last_modified = now() where orders_id = '" . (int)$orders_id . "'");
	
		$sql_data_array= array(
								array(
										'fieldName'=>'orders_id',
										'value'=>$orders_id, 
										'type'=>'integer'
									),
								array(
										'fieldName'=>'orders_status_id',
										'value'=>$orders_status_id,
										'type'=>'integer'
									),
								array(
										'fieldName'=>'date_added',
										'value'=>'now()',
										'type'=>'noquotestring'
									),
								array(
										'fieldName'=>'customer_notified',
										'value'=>$customer_notified,
										'type'=>'integer'
									),
								array(
										'fieldName'=>'comments',
										'value'=>$comments,
										'type'=>'string'
									),
							);
dotpaypl_debug_email("dotpaypl_store_orders_status_history: \nsql_data_array:".print_r($sql_data_array,true));
		$db->perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
	}
} 

function dotpaypl_store_URL_transaction($orders_id, $session_id, $ref_id, $status, $amount) {
	global $db;
	
	$sql_data_array = array (
							array(
								'fieldName' => 'orders_id',
								'value' => $orders_id,
								'type' => 'integer',
							),
							array(
								'fieldName' => 'amount',
								'value' => zen_db_input(str_replace(',','.',$amount)),
								'type' => 'string',
							),
							array(
								'fieldName' => 'session_id',
								'value' => zen_db_input($session_id),
								'type' => 'string',
							),
							array(
								'fieldName' => 'ref_id',
								'value' => zen_db_input($ref_id),
								'type' => 'string',
							),
							array(
								'fieldName' => 'last_modified',
								'value'=>'now()',
								'type'=>'noquotestring'
							)
						);

	$db->perform(TABLE_DOTPAYPL, $sql_data_array);

} 

function dotpaypl_store_URLC_transaction($orders_id, $session_id, $ref_id, $urlc_data) {
	global $db;
	
	$sql_data_array = array (
							array(
								'fieldName' => 'orders_id',
								'value' => $orders_id,
								'type' => 'integer',
							),
							array(
								'fieldName' => 'amount',
								'value' => zen_db_input(str_replace(',','.',$urlc_data['amount'])), 
								'type' => 'string',
							),
							array(
								'fieldName' => 'session_id',
								'value' => zen_db_input($session_id),
								'type' => 'string',
							),
							array(
								'fieldName' => 'ref_id',
								'value' => zen_db_input($ref_id),
								'type' => 'string',
							),
							array(
								'fieldName' => 'status',
								'value' => zen_db_input($urlc_data['status']),
								'type' => 'string',
							),
							array(
								'fieldName' => 't_id',
								'value' => zen_db_input($urlc_data['t_id']),
								'type' => 'string',
							),
							array(
								'fieldName' => 'original_amount',
								'value' => zen_db_input($urlc_data['orginal_amount']),
								'type' => 'string',
							),
							array(
								'fieldName' => 'channel',
								'value' => zen_db_input($urlc_data['channel']),
								'type' => 'string',
							),
							array(
								'fieldName' => 'email',
								'value' => zen_db_input($urlc_data['email']),
								'type' => 'string',
							),
							array(
								'fieldName' => 'service',
								'value' => zen_db_input($urlc_data['service']),
								'type' => 'string',
							),
							array(
								'fieldName' => 'code',
								'value' => zen_db_input($urlc_data['code']),
								'type' => 'string',
							),
							array(
								'fieldName' => 'username',
								'value' => zen_db_input($urlc_data['username']),
								'type' => 'string',
							),
							array(
								'fieldName' => 'password',
								'value' => zen_db_input($urlc_data['password']),
								'type' => 'string',
							),
							array(
								'fieldName' => 't_status',
								'value' => zen_db_input($urlc_data['t_status']),
								'type' => 'string',
							),
							array(
								'fieldName' => 'description',
								'value' => zen_db_input($urlc_data['description']),
								'type' => 'string',
							),
							array(
								'fieldName' => 'p_info',
								'value' => zen_db_input($urlc_data['p_info']),
								'type' => 'string',
							),
							array(
								'fieldName' => 'p_email',
								'value' => zen_db_input($urlc_data['p_email']),
								'type' => 'string',
							),
							array(
								'fieldName' => 't_date',
								'value' => zen_db_input($urlc_data['t_date']),
								'type' => 'string',
							),
							array(
								'fieldName' => 'last_modified',
								'value'=>'now()',
								'type'=>'noquotestring'
							)
						);
dotpaypl_debug_email("dotpaypl_store_URLC_transaction\n".print_r($sql_data_array,true));
	$db->perform(TABLE_DOTPAYPL, $sql_data_array);

} 

function dotpaypl_get_orders_status_name($orders_status_id, $language_id = '') {
	global $db;
	
	if (!$language_id) $language_id = $_SESSION['languages_id'];
	$orders_status = $db->Execute("select orders_status_name
	                               from " . TABLE_ORDERS_STATUS . "
	                               where orders_status_id = '" . (int)$orders_status_id . "'
	                               and language_id = '" . (int)$language_id . "'");
	
	return $orders_status->fields['orders_status_name'];
} 
