<?
/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
* Class		:	customer
* Version :	1.0
* Date    :	03 October 2009
* Author  :	Darwish A. Khalil
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

// Class Definition
class customer
{
	var $CustomerID;		// Auto increment (Primary Key)
	var $Username;			// Customer username
	var $Password;			// Customer password
	var $Email;					// Customer email address
	var $Enabled;				// Customer Enabled/Disabled
	var $LastLoginDate;	// Customer Last Login Date to the application
	var $PasswordTimestamp;	// Customer password timestamp

	/*
	 * Class constructor
	 */
  function customer($CustomerID = -1)
  {
  	if ((!empty($CustomerID)) && ($CustomerID != -1))
  	{
  		$this->CustomerID = $CustomerID;
			$this->getInfo();
		}
	}

	/*
	 * Retrieves customer information
	 */
	function getInfo()
	{
		$query = "
							Select * From customer
					 	  Where CustomerID = $this->CustomerID
					 	 ";

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

    // Set class data members
    $this->Username = $row->Username;
    $this->Password = $row->Password;
    $this->Email 		= $row->Email;
    $this->Enabled 	= $row->Enabled;
    $this->LastLoginDate = $row->LastLoginDate;
    $this->PasswordTimestamp = $row->PasswordTimestamp;
  }

	/*
	 * Private utility method
	 */
	function populateFromRowObject($row)
	{
		$this->CustomerID = $row->CustomerID;
		$this->Username 	= $row->Username;
    $this->Password 	= $row->Password;
    $this->Email 			= $row->Email;
    $this->Enabled 		= $row->Enabled;
    $this->LastLoginDate = $row->LastLoginDate;
    $this->PasswordTimestamp = $row->PasswordTimestamp;
	}

	/*
	 * Populates the current customer by providing his/her Username
	 */
	function populateByUsername($username)
	{
		$query = "SELECT * FROM customer WHERE Username = '$username' And Enabled = 1 And Deleted = 0";
		// exit($query);
		$result = mysql_query($query);
		if (mysql_num_rows($result) > 0)
		{
			$row = mysql_fetch_object($result);
			$this->populateFromRowObject($row);
			return true;
		}
		return false;
	}

	/*
	 * Populates the current customer by providing his/her Email
	 */
	function populateByEmail($email)
	{
		$query = "SELECT * FROM customer WHERE LTRIM(RTRIM(Email)) = LTRIM(RTRIM('$email'))";
		$result = mysql_query($query);
		if(mysql_num_rows($result) > 0)
		{
			$row = mysql_fetch_object($result);
			$this->populateFromRowObject($row);
			return true;
		}
		return false;
	}

	/*
	 * Sets the last login date for this customer
	 */
	function setLastLoginDate()
  {
  	$today = date("y-m-d H:i:s");
    $query = "Update customer Set LastLoginDate = '$today' Where CustomerID = $this->CustomerID";
		mysql_query($query) or die(mysql_error());
	}

	/*
	 * Checks if this customer has purchased this product before
	 */
  function hasPurchasedThisProduct($ProductID)
  {
		$query  =
							"
								Select LicenseID From customer_license
								Where CustomerID = $this->CustomerID And ProductID = $ProductID
								And Status = 'Activated' And Deleted = 0
							";
		// exit($query);
		$result = mysql_query($query);
		if (mysql_num_rows($result)>0) {
			$row = mysql_fetch_object($result);
			return $row->LicenseID;
		}
		return false;
	}

	/*
   * Retrieves a list of all products purchased by this customer
   */
	function getPurchasedProductsList()
	{
		global $language;

		$query  =
							"
								Select ProductID, Title From product
								Where ProductID in (Select Distinct ProductID From customer_license Where CustomerID = $this->CustomerID And Status = 'Activated' And Deleted = 0)
								And Deleted = 0 And Enabled = 1 And Language = '$language'
							";
		// echo $query;
		$result = mysql_query($query);
		return $result;
	}

	/*
	 * Checks if this customer has asked to send release notifications for a certain product
	 */
  function hasReleasesNotification($ProductID)
  {
		$query  =
							"
								Select ReleasesNotification From customer_product
								Where CustomerID = $this->CustomerID And ProductID = $ProductID
							";
		// echo $query;
		$result = mysql_query($query);
		if (mysql_num_rows($result)>0) {
			$row = mysql_fetch_object($result);
    	return (($row->ReleasesNotification==1) ? true : false);
		}
		return false;
	}

	/*
   * Notify by email about any new releases of a certain product
   */
	function setReleasesNotification($ProductID, $ReleasesNotification)
	{
		// Delete existing row if any
		$query  =
							"
								Delete from customer_product
								Where CustomerID = $this->CustomerID And ProductID = $ProductID
							";
		// echo $query;
		mysql_query($query);

		// Insert the new values
		$query  =
							"
								Insert Into customer_product(CustomerID, ProductID, ReleasesNotification)
								Values ($this->CustomerID, $ProductID, $ReleasesNotification);
							";
		// echo $query;
		mysql_query($query);
	}


	/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
	*                             Password Functions
	*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
	function createCode($chars)
	{
	  $n = 0;
		$allowchars = '';
	  srand((double) microtime() * 1000000);
	  $allowchars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@$^&*';
	  while(++$n < ($chars+1)) {
			$password .= $allowchars[rand(0, strlen($allowchars)-1)];
		}
	  return $password;
	}

	/*
	 * Updates the new password in DB
	 */
	function updatePassword($newPassword)
  {
  	$PasswordTimestamp = date('Y-m-d H:i:s');
  	$newPassword = md5($newPassword);

    $query =
    				"
    					Update customer Set Password = '$newPassword', PasswordTimestamp = '$PasswordTimestamp'
    					Where CustomerID = $this->CustomerID
    				";
		mysql_query($query) or die(mysql_error());
	}

	/*
	 * Send the password reset confirmation message of a certain customer to his email
	 */
	function sendPasswordResetMessage()
	{
		global $config;

		$confirmation = $this->createCode(12);
		$query = "INSERT INTO reset_password(rp_username, rp_code) VALUES ('" . $this->Username . "', '" . $confirmation . "')";
		mysql_query($query) or die(mysql_error());

		// Prepare headers for sending an html mail
		$headers  = "MIME-Version: 1.0\r\n";
		$headers .= "Content-type: text/html; charset=windows-1256\r\n";
		$headers .= "From:" . $config['EMAIL_FROM']. "\r\n";
		$headers .= "BCC: " . $config['EMAIL_BCC'] . "\r\n";

		$to = stripslashes($this->Email);
		$subject = "FinFisher - Reset Password Request";
		$message .= "Dear $this->Username,<br/><br/>";
		$message .= "This email is sent upon your request.<br/><br/>";
		$message .= "Please confirm that you want to reset your password by clicking on the link below: ";
		$message .= "<a href='". substr( selfURL(), 0, strrpos(selfURL(), "/") + 1) . "confirmresetpassword.php?cc=$confirmation&username=$this->Username' >" . $confirmation . "</a><br />";
		$message .= "If this message is not sent upon you request, please ignore it.<br />";

		// Send Message
		$message = stripslashes(trim($message));
		if(eregi("win",strtolower(PHP_OS)))
		{
			include_once "mail.class.php";
			$msg = new email();
	 		$msg->send_mail(0, $to, $subject, $message, $headers);
	 		// exit($message);
		}
	  elseif(eregi("linux",strtolower(PHP_OS)))
	  {
			mail($to, $subject, $message, $headers);
		}
	}

	/*
	 * Send the password of a certain customer to his email
	 */
  function sendPassword()
  {
  	global $config;

  	$PasswordTimestamp = date('Y-m-d H:i:s');
    $password = $this->createCode($config['PASSWORD_LENGTH']);

    $query =
    				"
    					Update customer Set Password = '".md5($password)."', PasswordTimestamp = '$PasswordTimestamp'
    					Where Username = '$this->Username'
    				";
    mysql_query($query) or die(mysql_error());

    $query = "DELETE FROM reset_password WHERE rp_username = '" . $this->Username . "'";
    mysql_query($query) or die(mysql_error());

    // Prepare headers for sending an html mail
	  $headers  = "MIME-Version: 1.0\r\n";
	  $headers .= "Content-type: text/html; charset=windows-1256\r\n";
	  $headers .= "From:" . $config['EMAIL_FROM']. "\r\n";
	  $headers .= "BCC: " . $config['EMAIL_BCC'] . "\r\n";

    $to = stripslashes($this->Email);
    $subject  = "FinFisher - Your Requested Login Information";
    $message .= "Dear $this->Username,<br /><br />";
    $message .= "This email is sent upon your request.<br /><br />";
    $message .= "Your new password is: <b>$password</b><br /><br />";

		// Send Message
		$message = stripslashes(trim($message));
		if(eregi("win",strtolower(PHP_OS)))
		{
			include_once "mail.class.php";
			$msg = new email();
	 		$msg->send_mail(0, $to, $subject, $message, $headers);
	 		// exit($message);
		}
	  elseif(eregi("linux",strtolower(PHP_OS)))
	  {
			mail($to, $subject, $message, $headers);
		}
  }

  /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
	*                    Manage Customer Licenses Functions
	*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/
	/*
	 * Gets the licenses of this customer that will expire within a certain period of time
	 * By default: 3 months
	 */
	function getLicesesToExpire()
	{
		global $config;

		$BeforeExpiryDays = $config['LICENSES_BEFORE_EXPIRY_PERIOD'];

		$query  =
						"
							Select cl.LicenseID, cl.ValidityEnd, DATEDIFF(ValidityEnd, NOW()) RemainingDays,
							cl.ProductID, p.Title ProductName
							From customer_license cl Inner Join product p
							On cl.ProductID = p.ProductID
							Where cl.CustomerID = $this->CustomerID And DATEDIFF(ValidityEnd, NOW()) <= $BeforeExpiryDays
							And cl.Deleted = 0 And cl.Status = 'Activated'
						";
		// echo $query;
		$result = mysql_query($query);
		return $result;
	}

	/*
	 * Gets a list of all customers who have licenses to expire soon
	 */
	function getCustomersListWithLicensesToExpire()
	{
		global $config;

		$BeforeExpiryDays = $config['LICENSES_BEFORE_EXPIRY_PERIOD'];

		$query  =
						"
							Select Distinct CustomerID
							From customer_license
							Where DATEDIFF(ValidityEnd, NOW()) <= $BeforeExpiryDays
							And Deleted = 0 And `Status` = 'Activated'
						";
		// echo $query;
		$result = mysql_query($query);
		return $result;
	}

	/*
	 * Sends email alert to customer about licenses to expire soon
	 */
	function sendExpiryEmailAlert()
	{
		global $config;

		// Prepare headers for sending an html mail
		$headers  = "MIME-Version: 1.0\r\n";
		$headers .= "Content-type: text/html; charset=windows-1256\r\n";
		$headers .= "From: " . $config['EMAIL_FROM'] . "\r\n";
		$headers .= "BCC: " . $config['EMAIL_BCC'] . "\r\n";

		$to = $this->Email;

		$subject = "FinFisher - License(s) Renewal Email Alert";

		$message = $this->generateAlertMessage();

		// Send Message
		if(eregi("win",strtolower(PHP_OS)))
		{
			include_once "mail.class.php";
			$msg = new email();
	 		// $msg->send_mail(0, $to, $subject, $message, $headers);
			echo($message . "<br>");
		}
	  elseif(eregi("linux",strtolower(PHP_OS)))
	  {
			mail($to, $subject, $message, $headers);
		}
	}

	/*
	 * Generates the contents of the email to be sent to the customer
	 */
	function generateAlertMessage()
	{
		global $config;

		$result = $this->getLicesesToExpire();

		$body = "<table border='0' cellpadding='3' cellspacing='0' width='410' class='AlertBox'>";
		while($row = mysql_fetch_object($result))
		{
    	$body .=
    					'
    						<tr>
				    			<td>
				    				<b>'.$row->ProductName.'</b> will expire on <span class="ExpiryDate">'.$row->ValidityEnd.'</span><br>
				    			</td>
				    		</tr>
				    		<tr>
				    			<td class="warning" style="padding-top:0px;">
				    				Remaining: '.$row->RemainingDays.' days
				    			</td>
				    		</tr>
			    		';
		}
		$body .= "</table>";

		$msg =
					'
						<html>
							<head>
								<link href="'.$config['ROOT_URL'].'/Styles/style.css.php?Lang=en" rel="stylesheet" type="text/css">
							</head>
							<body class="en">
								<table border="0" cellpadding="3" cellspacing="0" width="100%">
									<tr>
										<td>Dear Customer '.$this->Username.',</td>
									</tr>
									<tr>
										<td>This is to notify you that the following product(s) are going to expire soon:</td>
									</tr>
									<tr>
										<td>'.$body.'</td>
									</tr>
									<tr>
										<td>
											Sincerely yours,<br>
											FinFisher Customer Support
										</td>
									</tr>
								</table>
							</body>
						</html>
					';
		return stripslashes(trim($msg));
	}
}
?>