<?php
	// osCommRes web service
	//require_once('nusoap.php');
	
	require('../includes/configure.php');
	require('english.php');
	error_reporting(~E_ALL & ~E_STRICT);


	// get the database parameters from stored config file
	$db["name"]=DB_DATABASE;
	$db["server"]=DB_SERVER;
	$db["username"]=DB_SERVER_USERNAME;
	$db["password"]=DB_SERVER_PASSWORD;
	
	$response = array(
		"errorCode"	=>	0,
		"errorMsg"	=>	""
	);	
	
	
	
	// definition for customer details
	class customer{
		var $gender;
		var $firstname;
		var $lastname;
		var $dob;
		var $emailaddress;
		var $telephone;
		var $mobile;
		var $newsletter;
		var $second_email_address;
		var $second_telephone;
		var $reserve_newsletter;
		var $subscription_newsletter;
		var $type;
		var $street_address;
		var $city;
		var $state;
		var $country;
		var $suburb;
		var $company;
		var $password;
		var $postcode;
		var $admin_id;
		var $customer_id;
		var $default_address_id;
	}
	
	
	// function to connect to database
	function db_connect(){
		global $db;
		$link=mysql_connect($db["server"],$db["username"],$db["password"]);
		if (!$link){
			log_error("1000",sprintf(TEXT_CANNOT_CONNECT,$db["server"],$db["username"],$db["password"]));
			return false;
		} else {
			if (!mysql_select_db($db["name"])){
				log_error("1001",sprintf(TEXT_SELECT_DB,$db["name"]));
				return false;
			} else {
				return $link;
			}
		}
	}
	// function to execute query
	function db_query($query,$link){
		$result=mysql_query($query,$link);

		if (!$result){
			log_error(1002,sprintf(TEXT_EXECUTE_QUERY,mysql_error($link)));
			return false;
		} else {
			return $result;
		}
	}
	// function to give no of rows
	function db_num_rows($query){
		$rows=mysql_num_rows($query);
		return $rows;
	}
	// function to fetch details of current record
	function db_fetch_array($query){
		$result=mysql_fetch_assoc($query);
		return $result;
	}
	
	$link = db_connect();
		if ($link) 
			$web_service_sql="select * from configuration where configuration_key='ENABLE_WEB_SERVICE' ";
	$web_service_query=db_query($web_service_sql,$link);
	if($web_service_query)
	{
		if(db_num_rows($web_service_query)>0)
		{
			$web_service_result=db_fetch_array($web_service_query);
			define('ENABLE_WEB_SERVICE',$web_service_result['configuration_value']);
			}
		}	

	
	function getSessionID($userID){
		$link = db_connect();
		if (!$link) return 0;	

        $key = "t3_".substr(md5($userID.time()+1),2,29);
	    $expiry = time()+30*60;
        db_query("INSERT INTO sessions VALUES ('" . db_input($key) . "', '" . db_input($expiry) . "', '')", $link);
		return $key;
	}
	
	function getSubscriptionsGroups($customer_id){
		if(defined('ENABLE_WEB_SERVICE'))
		{
			if(ENABLE_WEB_SERVICE!=1)
				return 0;
		}	
		$link = db_connect();
		if (!$link) return 0;	
	
		$check_sql = "SELECT su.subscription_group,max(date_add(o.date_purchased,interval if(op.products_price>0,su.subscription_period,su.subscription_free_days) day)) as expiry_date from orders o, orders_products op, subscriptions su".
					 " where o.orders_status>1 and op.products_id=su.subscription_id and op.products_type='S' and o.orders_id=op.orders_id and o.customers_id='$customer_id' ".
					 " group by o.customers_id,su.subscription_group having now()>=max(o.date_purchased) and now()<=expiry_date order by su.subscription_group";


		$check_query=db_query($check_sql,$link);
		

		if (!$check_query) return "";
		$groups=array();
		if (db_num_rows($check_query)>0){
			while($check_result=db_fetch_array($check_query)){
				$groups[]=$check_result["subscription_group"];
			}
		} 
		
		return implode(",",$groups);
	}
	
	function getMemberDetails($userID){
		if(defined('ENABLE_WEB_SERVICE'))
		{
			if(ENABLE_WEB_SERVICE!=1)
				return "";
		}	
		$link = db_connect();
		if (!$link) return array();	
		$check_query = db_query("select * from customers where customers_id = " . db_input($userID,$link)." LIMIT 1",$link);		
		if (!$check_query) return array();		
		$user = array();
		if (db_num_rows($check_query)>0){
			$user = db_fetch_array($check_query);
		}
		return $user;
	}
	
	
	// get the session data from the database for the osc
	function GetUserIdSession($key){
		if(defined('ENABLE_WEB_SERVICE'))
		{
			if(ENABLE_WEB_SERVICE!=1)
				return 0;
		}	
		$link = db_connect();
		if (!$link) return 0;
		$check_sql="select value from sessions where sesskey = '" . $key . "' and expiry > '" . time() . "'";
		$check_query=db_query($check_sql,$link);
		
		if (!$check_query) return "0";
		if (db_num_rows($check_query)<=0) return "0";
		
		$check_result=db_fetch_array($check_query);
		return GetStoredValue($check_result["value"],"login_id");
	}
	
	function GetStoredValue($text,$key){
		$splt_1=split(";",$text);
		for ($icnt=0;$icnt<count($splt_1);$icnt++){
			$splt_2=split("\||:",$splt_1[$icnt]);
			if ($splt_2[0]==$key){
				return str_replace("\"","",$splt_2[3]);
			}
		}
		return "";
	}
	// validate given member details in customers table 
	function ValidateMember($detail){
		global $response;
		if(defined('ENABLE_WEB_SERVICE'))
		{
			if(ENABLE_WEB_SERVICE!=1)
			{
				$response["errorCode"] = 300;
				$response["errorMsg"] = "Web Service disabled";
				return $response;
				}
		}	
		$user_id = $detail->userID;
		$password = $detail->userPass;
		
		$link=db_connect();
		if (!$link){
			$response["errorCode"] = 301;
			$response["errorMsg"] = "Data base connection error";
			return $response;
		}
		
		// first check the user name for valid
		$customer_sql = "SELECT customers_password from customers where customers_id='" . $user_id . "'";
		$customer_query = db_query($customer_sql, $link);

		if (!$customer_query){
			$response["errorCode"] = 302;
			$response["errorMsg"] = "Query error";
			return $response;
		}

		if (db_num_rows($customer_query)<=0){
			$response["errorCode"] = 500;
			$response["errorMsg"] = "User not found";
			return $response;
		}

		$customer_result=db_fetch_array($customer_query);
		
		// validate for password
		if (validate_password($password,$customer_result["customers_password"])){
			$response["results"] = array(
				"sessionID"	=>	getSessionID($user_id),
				"userSubscriptionGroups"	=>	getSubscriptionsGroups($user_id)
			);
			return $response;
		} else{
			$response["errorCode"] = 501;
			$response["errorMsg"] = "Wrong password";
			return $response;
		}
	}
	
	
	function ValidateAndGetMemberDetails($details){
		global $response;
		$response = ValidateMember($details);
		if($response['errorCode'] == 0){
			$response["results"]['customer'] = getMemberDetails($details->userID);
		}
		return $response;
	}
	
	function ValidateUserSession($details){
		global $response;
		if(defined('ENABLE_WEB_SERVICE'))
		{
			if(ENABLE_WEB_SERVICE!=1)
			{
				$response["errorCode"] = 300;
				$response["errorMsg"] = "Web Service disabled";
				return $response;
				}
		}	
		$cur_date="now()";
		$customer_id=db_prepare_input($details->userID);
		$session_key=db_prepare_input($details->sessionKey);
		$link=db_connect();
		if (!$link){
			$response["errorCode"] = 301;
			$response["errorMsg"] = "Data base connection error";
			return $response;		
		}
		
		// first check the user name for valid
		$customer_sql="SELECT customers_id,customers_password from customers where customers_id='" . db_input($customer_id,$link) . "'";

		$customer_query=db_query($customer_sql,$link);
		
		//modified webservice start
		if (!$customer_query) {
			$response["errorCode"] = 302;
			$response["errorMsg"] = "Query error";
			return $response;
		}
		//modified webservice end

		if (db_num_rows($customer_query)<=0)  {
			$response["errorCode"] = 502;
			$response["errorMsg"] = "Invalid User id";
			return $response;
		}

 		// check the session key
		$session_sql="SELECT * from sessions where sesskey='" . db_input($session_key,$link) . "' and expiry > '" . time() . "'";

		$session_query=db_query($session_sql,$link);

		if (!$session_query) {
			$response["errorCode"] = 302;
			$response["errorMsg"] = "Query error";
			return $response;
		}

		if (db_num_rows($session_query)<=0)  {
			$response["errorCode"] = 503;
			$response["errorMsg"] = "Invalid session key";
			return $response;
		}
 		
		$response['results']['userSubscriptionGroups'] = getSubscriptionsGroups($customer_id);

		return $response;
	}
	
	function ValidateUserSessionAndGetDetails($details){
		global $response;
		
		$response = ValidateUserSession($details);
		if($response['errorCode'] == 0){
			$response["results"]['customer'] = getMemberDetails($details->userID);
		}
		return $response;		
	}	

	// function to valdate given password
	function validate_password($plain, $encrypted) {
		if ($plain!="" && $encrypted!="") {
		// split apart the hash / salt
		  $stack = explode(':', $encrypted);
		
		  if (sizeof($stack) != 2) return false;
		
		  if (md5($stack[1] . $plain) == $stack[0]) {
			return true;
		  }
		}
		
		return false;
	}
	// function to log error
	function log_error($error_code,$error_text){
		global $response;
		$resultData["errorCode"]=$error_code;
		$resultData["errorMsg"]=$error_text;
	}
	
	// function to add or update customer details to the database
	function AddCustomer($cust){
		$error="";
		if(defined('ENABLE_WEB_SERVICE'))
		{
		if(ENABLE_WEB_SERVICE!=1)
			{
			return 0;
				}
		}	
		
		$link=db_connect();
		if (!$link){
			return 0;	
		}
		// check for rights to add the user
		$admin_query=db_query("SELECT admin_firstname,admin_lastname from admin where admin_id='" . $cust->admin_id . "'",$link);

		if (db_num_rows($admin_query)<=0) return TEXT_NO_ADMIN_USER;
		$admin_files_query=db_query("SELECT admin_groups_id from admin_files where admin_files_name='create_account.php'",$link);
		$admin_files_result=db_fetch_array($admin_files_query);
		$admin_files_result["admin_groups_id"]="," . $admin_files_result["admin_groups_id"] .",";

		if (strpos($admin_files_result["admin_groups_id"],"," . $cust->admin_id . ",")===false) return TEXT_NO_RIGHTS;

		$cust->gender=strtolower($cust->gender);
		if (($cust->gender != 'm') && ($cust->gender != 'f')) {
			$error.=ERR_GENDER;
		}
		if ($cust->firstname=="") $error.= ERR_FIRSTNAME;
		
		if ($cust->lastname=="") $error.= ERR_LASTNAME;
		
		if ($cust->dob=="") $error.= ERR_DOB;
		
		if ($cust->emailaddress==""){
			$error.=ERR_EMAIL_ADDRESS;
		} else {
			$email_option="";
			if (isset($cust->customer_id) && ((int)$cust->customer_id)>0) $email_option=" and customers_id!='" . $cust->customer_id . "' ";
			$check_email = db_query("select customers_email_address from customers where customers_email_address = '" . db_input($cust->emailaddress,$link) . "'" . $email_option,$link);
			if (db_num_rows($check_email)>0) {
				$error.= ERR_EMAIL_EXISTS;
			}
		}
		if ($cust->street_address=="") $error.=ERR_STREET_ADDRESS;		
		if ($cust->postcode=="") $error.=ERR_POSTCODE;
		if ($cust->city=="") $error.=ERR_CITY;
		if ($cust->country=="") $error.=ERR_COUNTRY;
		$zone_id = 0;
		$entry_state_error = false;
		$check_query = db_query("select count(*) as total from zones where zone_country_id = '" . db_input($cust->country,$link) . "'",$link);
		$check_value = db_fetch_array($check_query);
		$entry_state_has_zones = ($check_value['total'] > 0);
		if ($entry_state_has_zones) {
			$zone_query = db_query("select zone_id from zones where zone_country_id = '" . $cust->country . "' and zone_name = '" . $cust->state . "'",$link);
			if (db_num_rows($zone_query) == 1) {
				$zone_values = db_fetch_array($zone_query);
				$zone_id = $zone_values['zone_id'];
			} else {
				$zone_query = db_query("select zone_id from zones where zone_country_id = '" . $cust->country . "' and zone_code = '" . $cust->state . "'",$link);
				if (db_num_rows($zone_query) == 1) {
					$zone_values = db_fetch_array($zone_query);
					$zone_id = $zone_values['zone_id'];
				} else {
					$error.= ERR_STATE;
				}
			}
		} else {
			if (!$cust->state) {
				$error.= ERR_STATE;
			}
		}
		
		if ($cust->telephone=="") $error.=ERR_TELEPHONE;
		
		if ($error!="") return $error;
		
		$sql_data_array = array('customers_firstname' => $cust->firstname,
								'customers_lastname' => $cust->lastname,
								'customers_email_address' => $cust->emailaddress,
								'customers_telephone' => $cust->telephone,
								'customers_fax' => $cust->mobile,
								'customers_newsletter' => $cust->newsletter,
								'customers_type' =>$cust->type,
								'customers_reserve_newsletter'=>$cust->reserve_newsletter,
								'customers_subscription_newsletter'=>$cust->subscription_newsletter,
								'customers_password' =>  encrypt_password($cust->password),
								'customers_second_email_address' => $cust->second_emailaddress,
								'customers_second_telephone'=>$cust->second_telephone,
								'customers_gender' => $cust->gender,
								'customers_dob'=>$cust->dob
								);
		
		// update in customers table
		if (isset($cust->customer_id) && ((int)$cust->customer_id)>0){
			db_perform('customers', $sql_data_array,'update',$link,"customers_id='" . $cust->customer_id ."'");
			$customer_id=$cust->customer_id;
		} else {
			db_perform('customers', $sql_data_array,'insert',$link);
			$customer_id=db_insert_id();
		}
	

		
		$sql_data_array = array('customers_id' => $customer_id,
								'entry_firstname' => $cust->firstname,
								'entry_lastname' => $cust->lastname,
								'entry_street_address' => $cust->street_address,
								'entry_postcode' => $cust->postcode,
								'entry_city' => $cust->city,
								'entry_country_id' => $cust->country,
								'entry_gender'=>$cust->gender,
								'entry_company'=>$cust->company,
								'entry_suburb'=>$cust->suburb
								);
		if ($zone_id > 0) {
			$sql_data_array['entry_zone_id'] = $zone_id;
			$sql_data_array['entry_state'] = '';
		} else {
			$sql_data_array['entry_zone_id'] = '0';
			$sql_data_array['entry_state'] = $cust_state;
		}

		// update in address book table
		if (isset($cust->customer_id) && ((int)$cust->customer_id)>0){
			db_perform('address_book', $sql_data_array,'update',$link,"customers_id = '" . (int)$customer_id . "' and address_book_id = '" . (int)$cust->default_address_id . "'");
		} else {
			db_perform('address_book', $sql_data_array,'insert',$link);
			$address_id = db_insert_id();
			db_query("update customers set customers_default_address_id = '" . (int)$address_id . "' where customers_id = '" . (int)$customer_id . "'",$link);
			db_query("insert into customers_info (customers_info_id, customers_info_number_of_logons, customers_info_date_account_created, customers_info_source_id) values ('" . (int)$customer_id . "', '0', now(), '3')",$link);
		}
		return 1;
	}

	// function to get id of newly created record
	function db_insert_id() {
		return mysql_insert_id();
	}
	
	// function to insert or update given data 
	function db_perform($table, $data, $action, $link,$parameters="") {
		reset($data);
		if ($action == 'insert') {
		  $query = 'insert into ' . $table . ' (';
		  while (list($columns, ) = each($data)) {
			$query .= $columns . ', ';
		  }
		  $query = substr($query, 0, -2) . ') values (';
		  reset($data);
		  while (list(, $value) = each($data)) {
			switch ((string)$value) {
			  case 'now()':
				$query .= 'now(), ';
				break;
			  case 'null':
				$query .= 'null, ';
				break;
			  default:
				$query .= '\'' . db_input($value,$link) . '\', ';
				break;
			}
		  }
		  $query = substr($query, 0, -2) . ')';
		} elseif ($action == 'update') {
		  $query = 'update ' . $table . ' set ';
		  while (list($columns, $value) = each($data)) {
			switch ((string)$value) {
			  case 'now()':
				$query .= $columns . ' = now(), ';
				break;
			  case 'null':
				$query .= $columns .= ' = null, ';
				break;
			  default:
				$query .= $columns . ' = \'' . db_input($value,$link) . '\', ';
				break;
			}
		  }
		  $query = substr($query, 0, -2) . ' where ' . $parameters;
		}
		
		return db_query($query, $link);
	}

	// validate for special chars in the string
	function db_input($string, $link) {
		
		if (function_exists('mysql_real_escape_string')) {
			return mysql_real_escape_string($string, $link);
		} elseif (function_exists('mysql_escape_string')) {
			return mysql_escape_string($string);
		}
		
		return addslashes($string);
	}
	
	// encrypt given password
	function encrypt_password($plain) {
		$password = '';
		
		for ($i=0; $i<10; $i++) {
		  $password .= mt_rand();
		}
		
		$salt = substr(md5($password), 0, 2);
		
		$password = md5($salt . $plain) . ':' . $salt;
		
		return $password;
	}
	
	function db_prepare_input($string) {
		$string = ereg_replace(' +', ' ', trim($string));
		return preg_replace("/[<>]/", '_', $string);
	}

	// create the server

	$server= new soap_server("subscription2.wsdl");
	
	$server->debug_flag = true;

	// Register the functions
	$server->addFunction(array("ValidateMember","AddCustomer","ValidateAndGetMemberDetails","ValidateUserSession","ValidateUserSession","ValidateUserSessionAndGetDetails"));

if(isset($_GET['debugMethod'])){
	var_dump($_GET['debugMethod']());
	return;
} 
 
	//$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
	// make server to handle the incoming data
	//$server->service($HTTP_RAW_POST_DATA);
	$server->handle();  
//validateMember()
/*	class test{
		var $userID;
		var $userPass;
	}
	class test1{
		var $userID;
		var $userPass;
	}

	$test=new test();
	$test->userID=1;
	$test->userPass="admin";  */
	//print_r($test);
//	t3_9d580752fc04e0423fedd60deb8ab 
	//print_r(ValidateAndGetMemberDetails($test));
	
/*	print_r(ValidateUserSession($test)) . '<br>';
	print_r(ValidateMember($test)) . '<br>';
	print_r(AddCustomer($test)) .'<br>';
	print_r(ValidateUserSessionAndGetDetails($test)) .'<br>';
	print_r(ValidateAndGetMemberDetails($test)) . '<br>';  */
	
?>