<?php
  /**
   * User Class
   *
   * @package Digital Downloads Pro
   * @author wojoscripts.com
   * @copyright 2010
   * @version $Id: class_user.php, v2.00 2011-07-10 10:12:05 gewa Exp $
   */
  
  if (!defined("_VALID_PHP"))
      die('. دسترسی مستقیم به این محل مجاز نمی باشد');

  class Users
  {
	  private $uTable = "users";
	  public $logged_in = null;
	  public $uid = 0;
	  public $userid = 0;
	  public $cookie_id = 0;
      public $username;
	  public $sesid;
	  public $email;
	  public $name;
      public $userlevel;
	  private $lastlogin = "NOW()";
      

      /**
       * Users::__construct()
       * 
       * @return
       */
      function __construct()
      {
		  $this->getUserId();
		  $this->startSession();
      }

	  /**
	   * Users::getUserId()
	   * 
	   * @return
	   */
	  private function getUserId()
	  {
	  	  global $core;
		  if (isset($_GET['userid'])) {
			  $userid = (is_numeric($_GET['userid']) && $_GET['userid'] > -1) ? intval($_GET['userid']) : false;
			  $userid = sanitize($userid);
			  
			  if ($userid == false) {
				  $core->error("آی دی کاربر انتخـاب شـده نامعتبـر می باشـد","Users::getUserId()");
			  } else
				  return $this->userid = $userid;
		  }
	  }  

      /**
       * Users::startSession()
       * 
       * @return
       */
      private function startSession()
      {
		session_start();
		
		$this->logged_in = $this->loginCheck();
		
		if (!$this->logged_in) {
			$this->username = $_SESSION['DDP_USERNAME'] = "مهمـان گـرامـی";
			$this->sesid = sha1(session_id());
			$this->userlevel = 0;
		}
      }

	  /**
	   * Users::loginCheck()
	   * 
	   * @return
	   */
	  private function loginCheck()
	  {

          if (isset($_COOKIE['DDP_COOKIE']) && isset($_COOKIE['DDP_COOKIE_ID'])) {
              $this->username = $_SESSION['DDP_USERNAME'] = $_COOKIE['DDP_COOKIE'];
              $this->cookie_id = $_SESSION['cookie_id'] = $_COOKIE['DDP_COOKIE_ID'];
          }
		  
          if (isset($_SESSION['DDP_USERNAME']) && isset($_SESSION['cookie_id']) && $_SESSION['DDP_USERNAME'] != "مهمـان گـرامـی") {
              if (!$this->confirmCookie($_SESSION['DDP_USERNAME'], $_SESSION['cookie_id'])) {
                  unset($_SESSION['DDP_USERNAME']);
                  unset($_SESSION['cookie_id']);
				  unset($_SESSION['name']);
				  unset($_SESSION['uid']);
                  return false;
              }
			  
              $row = $this->getUserInfo($_SESSION['DDP_USERNAME']);
			  $this->uid = $row['id'];
              $this->username = $row['username'];
			  $this->email = $row['email'];
			  $this->name = $row['fname'].' '.$row['lname'];
              $this->userlevel = $row['userlevel'];
			  $this->sesid = sha1(session_id());
              return true;
          } else {
              return false;
          }  
	  }

	  /**
	   * Users::is_Admin()
	   * 
	   * @return
	   */
	  public function is_Admin()
	  {
		  return($this->userlevel == 9);
	  
	  }	

	  /**
	   * Users::login()
	   * 
	   * @param mixed $username
	   * @param mixed $pass
	   * @param bool $uremember
	   * @return
	   */
	  public function login($username, $pass, $uremember = false)
	  {
		  global $db, $core;

		  if ($username == "" && $pass == "") {
			  $core->msgs['username'] = '.لطفـا نام کاربری و کلمه عبور معتبر را وارد نمائیـد';
		  } else {
			  $status = $this->checkStatus($username, $pass);
			  
			  switch ($status) {
				  case 0:
					  $core->msgs['username'] = '.کلمه های عبور به پایگاه داده مطابقت ندارد';
					  break;
					  
				  case 1:
					  $core->msgs['username'] = '..حساب کاربری شما توقیف شـده';
					  break;
					  
				  case 2:
					  $core->msgs['username'] = '.حساب کاربری شمـا فعـال نمی باشـد';
					  break;
					  
				  case 3:
					  $core->msgs['username'] = '.لازم اسـت که ایـمیـل خود را بررسی نمائیـد';
					  break;
			  }
		  }
		  if (empty($core->msgs) && $status == 5) {
			  $row = $this->getUserInfo($username);
			  $this->uid = $_SESSION['userid'] = $row['id'];
			  $this->username = $_SESSION['DDP_USERNAME'] = $row['username'];
			  $this->email = $_SESSION['email'] = $row['email'];
			  $this->name = $_SESSION['userlevel'] = $row['userlevel'];
			  $this->cookie_id = $_SESSION['cookie_id'] = $this->generateRandID();
			  $this->userlevel = $_SESSION['userlevel'] = $row['userlevel'];

			  $data = array(
					'lastlogin' => $this->lastlogin, 
					'cookie_id' => $this->cookie_id,
					'lastip' => sanitize($_SERVER['REMOTE_ADDR'])
			  );
			  $db->update($this->uTable, $data, "username='" . $this->username . "'");

			  if ($uremember) {
				  setcookie("DDP_COOKIE", $this->username, time() + COOKIE_EXPIRE, COOKIE_PATH);
				  setcookie("DDP_COOKIE_ID", $this->cookie_id, time() + COOKIE_EXPIRE, COOKIE_PATH);
			  }
				    
			  return true;
		  } else
			  $core->msgStatus();
	  }

      /**
       * Users::logout()
       * 
       * @return
       */
      public function logout()
      {
		if (isset($_COOKIE['DDP_COOKIE']) && isset($_COOKIE['DDP_COOKIE_ID'])) {
			setcookie("DDP_COOKIE", "", time() - COOKIE_EXPIRE, COOKIE_PATH);
			setcookie("DDP_COOKIE_ID", "", time() - COOKIE_EXPIRE, COOKIE_PATH);
		}
		  
          unset($_SESSION['DDP_USERNAME']);
		  unset($_SESSION['email']);
		  unset($_SESSION['name']);
		  unset($_SESSION['cookie_id']);
          unset($_SESSION['userid']);
          session_destroy();
		  session_regenerate_id();
          
          $this->logged_in = false;
          $this->username = "مهمـان گـرامـی";
          $this->userlevel = 0;
      }

	  /**
	   * Users::getUserInfo()
	   * 
	   * @param mixed $username
	   * @return
	   */
	  private function getUserInfo($username)
	  {
		  global $db;
		  $username = sanitize($username);
		  $username = $db->escape($username);
		  
		  $sql = "SELECT * FROM " . $this->uTable . " WHERE username = '" . $username . "'";
		  $row = $db->first($sql);
		  if (!$username)
			  return false;
		  
		  return ($row) ? $row : 0;
	  }

	  /**
	   * Users::checkStatus()
	   * 
	   * @param mixed $username
	   * @param mixed $pass
	   * @return
	   */
	  public function checkStatus($username, $pass)
	  {
		  global $db;
		  
		  $username = sanitize($username);
		  $username = $db->escape($username);
		  $pass = sanitize($pass);
		  
          $sql = "SELECT password, active FROM " . $this->uTable
		  . "\n WHERE username = '".$username."'";
          $result = $db->query($sql);
          
		  if ($db->numrows($result) == 0)
			  return 0;
			  
		  $row = $db->fetch($result);
		  $entered_pass = sha1($pass);
		  
		  switch ($row['active']) {
			  case "b":
				  return 1;
				  break;
				  
			  case "n":
				  return 2;
				  break;
				  
			  case "t":
				  return 3;
				  break;
				  
			  case "y" && $entered_pass == $row['password']:
				  return 5;
				  break;
		  }
	  }

	  /**
	   * Users::getUsers()
	   * 
	   * @param bool $from
	   * @return
	   */
	  public function getUsers($from = false)
	  {
		  global $db, $pager, $core;
		  
		  require_once(BASEPATH . "lib/class_paginate.php");
          $pager = new Paginator();
		  
          $counter = countEntries($this->uTable);
          $pager->items_total = $counter;
          $pager->default_ipp = $core->perpage;
          $pager->paginate();
          
          if ($counter == 0) {
              $pager->limit = null;
          }

		  if (isset($_GET['sort'])) {
			  list($sort, $order) = explode("-", $_GET['sort']);
			  $sort = sanitize($sort);
			  $order = sanitize($order);
			  if (in_array($sort, array("username", "fname", "lname", "email","created"))) {
				  $ord = ($order == 'DESC') ? " DESC" : " ASC";
				  $sorting = " " . $sort . $ord;
			  } else {
				  $sorting = " created DESC";
			  }
		  } else {
			  $sorting = " created DESC";
		  }
		  
		  $clause = (isset($clause)) ? $clause : null;
		  
          if (isset($_POST['fromdate']) && $_POST['fromdate'] <> "" || isset($from) && $from != '') {
              $enddate = date("Y-m-d");
              $fromdate = (empty($from)) ? $_POST['fromdate'] : $from;
              if (isset($_POST['enddate']) && $_POST['enddate'] <> "") {
                  $enddate = $_POST['enddate'];
              }
              $clause .= " WHERE created BETWEEN '" . trim($fromdate) . "' AND '" . trim($enddate) . " 23:59:59'";
          } 
		  
          $sql = "SELECT *, CONCAT(fname,' ',lname) as name,"
		  . "\n DATE_FORMAT(created, '" . $core->short_date . "') as cdate,"
		  . "\n DATE_FORMAT(lastlogin, '" . $core->short_date . "') as adate,"
		  . "\n (SELECT COUNT(transactions.uid) FROM transactions WHERE transactions.uid = users.id) as totalitems"
		  . "\n FROM " . $this->uTable
		  . "\n " . $clause
		  . "\n ORDER BY " . $sorting . $pager->limit;
          $row = $db->fetch_all($sql);
          
		  return ($row) ? $row : 0;
	  }

	  /**
	   * Users::processUser()
	   * 
	   * @return
	   */
	  public function processUser()
	  {
		  global $db, $core;

		  if (!$this->userid) {
			  if (empty($_POST['username']))
				  $core->msgs['username'] = '.لطفـا نام کاربری معتبـر خود را وارد نمائیـد';
			  
			  if ($value = $this->usernameExists($_POST['username'])) {
				  if ($value == 1)
					  $core->msgs['username'] = '..نام کاربری کوتـاه اسـت، حداقـل 4 کارکتـر';
				  if ($value == 2)
					  $core->msgs['username'] = '..کارکتـرهـای نامعتبـر در نام کاربری وجـود دارد';
				  if ($value == 3)
					  $core->msgs['username'] = '.با عرض پوزش، این نام کاربری قبـلا ثبـت شـده اسـت';
			  }
		  }

		  if (empty($_POST['fname']))
			  $core->msgs['fname'] = '..لطفـا نـام خود را وارد نمائیـد';
			  
		  if (empty($_POST['lname']))
			  $core->msgs['lname'] = '..لطفـا نـام خـانوادگـی خود را وارد نمائیـد';
			  
		  if (!$this->userid) {
			  if (empty($_POST['password']))
				  $core->msgs['password'] = '..لطفـا رمز عبـور معتبـر خود را وارد نمائیـد';
		  }

		  if (empty($_POST['email']))
			  $core->msgs['email'] = '..لطفـا ایـمیـل معتبـر خود را وارد نمائیـد';
		  if (!$this->userid) {
			  if ($this->emailExists($_POST['email']))
				  $core->msgs['email'] = '..این ایـمیـل قبلا ثبـت شـده و در حال استفـاده می باشـد';
		  }
		  if (!$this->isValidEmail($_POST['email']))
			  $core->msgs['email'] = '..ایـمیـل وارد شـده معتبـر نمی باشـد';

		  if (empty($core->msgs)) {
			  
			  $data = array(
				  'username' => sanitize($_POST['username']), 
				  'email' => sanitize($_POST['email']), 
				  'lname' => sanitize($_POST['lname']), 
				  'fname' => sanitize($_POST['fname']), 
				  'newsletter' => intval($_POST['newsletter']),
				  'userlevel' => intval($_POST['userlevel']), 
				  'active' => sanitize($_POST['active'])
			  );

			  if (!$this->userid)
				  $data['created'] = "NOW()";
				   
			  if ($this->userid)
				  $userrow = $core->getRowById($this->uTable, $this->userid);
			  
			  if ($_POST['password'] != "") {
				  $data['password'] = sha1($_POST['password']);
			  } else {
				  $data['password'] = $userrow['password'];
			  }
				  
			  ($this->userid) ? $db->update($this->uTable, $data, "id='" . (int)$this->userid . "'") : $db->insert($this->uTable, $data);
			  $message = ($this->userid) ? '<span>!موفقیـت</span>!کـاربـر با موفقیـت بروز رسـانی شـد' : '<span>!موفقیـت</span>!کـاربـر با موفقیـت اضـافـه شـد';

			  if ($db->affected()) {
				  $core->msgOk($message);
				  
				  if (isset($_POST['notify']) && intval($_POST['notify']) == 1) {
					  
					  require_once(BASEPATH . "lib/class_mailer.php");
					  $mailer = $mail->sendMail();	
								  
					  $row = $core->getRowById("email_templates", 3);
					  
					  $body = str_replace(array('[USERNAME]', '[PASSWORD]', '[NAME]', '[SITE_NAME]', '[URL]'), 
					  array($data['username'], $_POST['password'], $data['fname'].' '.$data['lname'], $core->site_name, $core->site_url), $row['body']);
			
					  $message = Swift_Message::newInstance()
								->setSubject($row['subject'])
								->setTo(array($data['email'] => $data['fname'].' '.$data['lname']))
								->setFrom(array($core->site_email => $core->site_name))
								->setBody(cleanOut($body), 'text/html');
								
					   $mailer->send($message);
				  }
			  } else
				  $core->msgAlert('<span>!تـوجـه</span>.چیزی برای پـردازش وجود ندارد');
		  } else
			  print $core->msgStatus();
	  } 

	  /**
	   * Users::updateProfile()
	   * 
	   * @return
	   */
	  public function updateProfile()
	  {
		  global $db, $core;

		  if (empty($_POST['fname']))
			  $core->msgs['fname'] = '..لطفـا نـام خود را وارد نمائیـد';
			  
		  if (empty($_POST['lname']))
			  $core->msgs['lname'] = '..لطفـا نـام خـانوادگـی خود را وارد نمائیـد';

		  if (empty($_POST['email']))
			  $core->msgs['email'] = '..لطفـا ایـمیـل معتبـر خود را وارد نمائیـد';

		  if (!$this->isValidEmail($_POST['email']))
			  $core->msgs['email'] = '..ایـمیـل وارد شـده معتبـر نمی باشـد';

		  if (empty($core->msgs)) {
			  
			  $data = array(
				  'email' => sanitize($_POST['email']), 
				  'lname' => sanitize($_POST['lname']), 
				  'fname' => sanitize($_POST['fname']), 
				  'newsletter' => intval($_POST['newsletter'])
			  );
				   
			  $userpass = getValue("password", $this->uTable, "id = '".$this->uid."'");
			  
			  if ($_POST['password'] != "") {
				  $data['password'] = sha1($_POST['password']);
			  } else
				  $data['password'] = $userpass;
			  
			  $db->update($this->uTable, $data, "id='" . (int)$this->uid . "'");

			  ($db->affected()) ? $core->msgOk('<span>!موفقیـت</span> .مشخصـات شمـا با موفقیـت بروز رسـانی شـد ') : $core->msgAlert('<span>!تـوجـه</span>.چیزی برای پـردازش وجود ندارد');
		  } else
			  print $core->msgStatus();
	  } 

      /**
       * User::register()
       * 
       * @return
       */
	  public function register()
	  {
		  global $db, $core;
		  
		  if (empty($_POST['username']))
			  $core->msgs['username'] = '..لطفـا نام کاربری معتبـر خود را وارد نمائیـد';
		  
		  if ($value = $this->usernameExists($_POST['username'])) {
			  if ($value == 1)
				  $core->msgs['username'] = '..نام کاربری کوتـاه اسـت، حداقـل 4 کارکتـر';
			  if ($value == 2)
				  $core->msgs['username'] = '..کارکتـرهـای نامعتبـر در نام کاربری وجـود دارد';
			  if ($value == 3)
				  $core->msgs['username'] = '.با عرض پوزش، این نام کاربری قبـلا ثبـت شـده اسـت';
		  }

		  if (empty($_POST['fname']))
			  $core->msgs['fname'] = '..لطفـا نـام خود را وارد نمائیـد';
			  
		  if (empty($_POST['lname']))
			  $core->msgs['lname'] = '..لطفـا نـام خـانوادگـی خود را وارد نمائیـد';
			  
		  if (empty($_POST['pass']))
			  $this->msgs['pass'] = '.لطفـا کلمه عبـور معتبـر خود را وارد نمائیـد';
		  
		  if (strlen($_POST['pass']) < 6)
			  $core->msgs['pass'] = '..کلمه عبـور کوتـاه اسـت.. حداقـل 6 حـرف';
		  elseif (!preg_match("/^([0-9a-z])+$/i", ($_POST['pass'] = trim($_POST['pass']))))
			  $core->msgs['pass'] = '!کلمه عبـور وارد شـده نه عددی اسـت و نه حروفـی';
		  elseif ($_POST['pass'] != $_POST['pass2'])
			  $core->msgs['pass'] = '!کلمه های عبـور با یکدیگـر مطابقـت ندارنـد';
		  
		  if (empty($_POST['email']))
			  $core->msgs['email'] = '..لطفـا ایـمیـل معتبـر خود را وارد نمائیـد';
		  
		  if ($this->emailExists($_POST['email']))
			  $core->msgs['email'] = '..این ایـمیـل قبلا ثبـت شـده و در حال استفـاده می باشـد ';
		  
		  if (!$this->isValidEmail($_POST['email']))
			  $core->msgs['email'] = '..ایـمیـل وارد شـده معتبـر نمی باشـد';
			  		  
		  if ((int)empty($_POST['captcha']))
			  $core->msgs['captcha'] = '..لطفـا جـمـع کـل را وارد نمائیـد';
		  
		  if ($_POST['captcha'] != "9")
			  $core->msgs['captcha'] = '..مقـدار جـمـع کـل وارد شـده صحیـح نمی باشـد';
		  
		  if (empty($core->msgs)) {

			  $token = ($core->reg_verify == 1) ? $this->generateRandID() : 0;
			  $pass = sanitize($_POST['pass']);
			  
			  if($core->reg_verify == 1) {
				  $active = "t";
			  } elseif($core->auto_verify == 0) {
				  $active = "n";
			  } else {
				  $active = "y";
			  }
				  
			  $data = array(
					  'username' => sanitize($_POST['username']), 
					  'password' => sha1($_POST['pass']),
					  'email' => sanitize($_POST['email']), 
					  'fname' => sanitize($_POST['fname']),
					  'lname' => sanitize($_POST['lname']),
					  'token' => $token,
					  'active' => $active, 
					  'created' => "NOW()"
			  );
			  
			  $db->insert($this->uTable, $data);
		
			  require_once(BASEPATH . "lib/class_mailer.php");
			  
			  if ($core->reg_verify == 1) {
				  $actlink = $core->site_url . "/activate.php";
				  $row = $core->getRowById("email_templates", 1);
				  
				  $body = str_replace(
						array('[NAME]', '[USERNAME]', '[PASSWORD]', '[TOKEN]', '[EMAIL]', '[URL]', '[LINK]', '[SITE_NAME]'), 
						array($data['fname'].' '.$data['lname'], $data['username'], $_POST['pass'], $token, $data['email'], $core->site_url, $actlink, $core->site_name), $row['body']
						);
						
				 $newbody = cleanOut($body);	
					 
				  $mailer = $mail->sendMail();
				  $message = Swift_Message::newInstance()
							->setSubject($row['subject'])
							->setTo(array($data['email'] => $data['username']))
							->setFrom(array($core->site_email => $core->site_name))
							->setBody($newbody, 'text/html');
							
				 $mailer->send($message);
				 
			  } elseif ($core->auto_verify == 0) {
				  $row = $core->getRowById("email_templates", 14);
				  
				  $body = str_replace(
						array('[NAME]', '[USERNAME]', '[PASSWORD]', '[URL]', '[SITE_NAME]'), 
						array($data['fname'].' '.$data['lname'], $data['username'], $_POST['pass'], $core->site_url, $core->site_name), $row['body']
						);
						
				 $newbody = cleanOut($body);	

				  $mailer = $mail->sendMail();
				  $message = Swift_Message::newInstance()
							->setSubject($row['subject'])
							->setTo(array($data['email'] => $data['username']))
							->setFrom(array($core->site_email => $core->site_name))
							->setBody($newbody, 'text/html');
							
				 $mailer->send($message); 
				  
			  } else {
				  $row = $core->getRowById("email_templates", 7);
				  
				  $body = str_replace(
						array('[NAME]', '[USERNAME]', '[PASSWORD]', '[URL]', '[SITE_NAME]'), 
						array($data['fname'].' '.$data['lname'], $data['username'], $_POST['pass'], $core->site_url, $core->site_name), $row['body']
						);
						
				 $newbody = cleanOut($body);	

				  $mailer = $mail->sendMail();
				  $message = Swift_Message::newInstance()
							->setSubject($row['subject'])
							->setTo(array($data['email'] => $data['username']))
							->setFrom(array($core->site_email => $core->site_name))
							->setBody($newbody, 'text/html');
							
				 $mailer->send($message);

			  }
			  if($core->notify_admin) {
				$arow = $core->getRowById("email_templates", 13);
  
					$abody = str_replace(
						  array('[USERNAME]', '[EMAIL]', '[NAME]', '[IP]'), 
						  array($data['username'], $data['email'], $data['fname'].' '.$data['lname'], $_SERVER['REMOTE_ADDR']), $arow['body']
						  );
						  
				   $anewbody = cleanOut($abody);	
  
					$amailer = $mail->sendMail();
					$amessage = Swift_Message::newInstance()
							  ->setSubject($arow['subject'])
							  ->setTo(array($core->site_email => $core->site_name))
							  ->setFrom(array($core->site_email => $core->site_name))
							  ->setBody($anewbody, 'text/html');
							  
				   $amailer->send($amessage);
			  }
			  
			  ($db->affected() && $mailer) ?  print "OK" : $core->msgError('<span>!خـطا</span>..خـطایی در فراینـد ثبـت نـام وجود دارد، لطفـا با مدیریـت تماس بگیـریـد',false);
		  } else
			  print $core->msgStatus();
	  } 
	  
      /**
       * User::passReset()
       * 
       * @return
       */
	  public function passReset()
	  {
		  global $db, $core;
		  
		  if (empty($_POST['uname']))
			  $core->msgs['uname'] = '..لطفـا نام کاربری معتبـر خود را وارد نمائیـد';
		  
		  $uname = $this->usernameExists($_POST['uname']);
		  if (strlen($_POST['uname']) < 4 || strlen($_POST['uname']) > 30 || !preg_match("/^([0-9a-z])+$/i", $_POST['uname']) || $uname != 3)
			  $core->msgs['uname'] = '..با عرض پوزش، نام کاربری وارد شـده در بانک اطلاعـاتی ما وجود ندارد';

		  if (empty($_POST['email']))
			  $core->msgs['email'] = '..لطفـا ایـمیـل معتبـر خود را وارد نمائیـد';

		  if (!$this->emailExists($_POST['email']))
			  $core->msgs['uname'] = '..ایـمیـل وارد شـده وجـود ندارد';
			    
		  if (empty($_POST['captcha']))
			  $core->msgs['captcha'] = '..لطفـا جـمـع کـل را وارد نمائیـد';
		  
		  if ($_POST['captcha'] != "10")
			  $core->msgs['captcha'] = '..مقـدار جـمـع کـل وارد شـده صحیـح نمی باشـد';
		  
		  if (empty($core->msgs)) {
			  
              $user = $this->getUserInfo($_POST['uname']);
			  $randpass = $this->getUniqueCode(12);
			  $newpass = sha1($randpass);
			  
			  $data['password'] = $newpass;
			  
			  $db->update($this->uTable, $data, "username = '" . $user['username'] . "'");
		  
			  require_once(BASEPATH . "lib/class_mailer.php");
			  $row = $core->getRowById("email_templates", 2);
			  
			  $body = str_replace(
					array('[USERNAME]', '[PASSWORD]', '[URL]', '[LINK]', '[IP]', '[SITE_NAME]'), 
					array($user['username'], $randpass, $core->site_url, $core->site_url, $_SERVER['REMOTE_ADDR'], $core->site_name), $row['body']
					);
					
			  $newbody = cleanOut($body);

			  $mailer = $mail->sendMail();
			  $message = Swift_Message::newInstance()
						->setSubject($row['subject'])
						->setTo(array($user['email'] => $user['username']))
						->setFrom(array($core->site_email => $core->site_name))
						->setBody($newbody, 'text/html');
						
			  ($db->affected() && $mailer->send($message)) ? $core->msgOk('<span>!موفقیـت</span>!تغییـر کلمه عبـور شمـا با موفقیـت انجـام شـد، لطفـا ایمیـل خود را برای اطلاعـات بیشتـر بررسی نمائیـد',false) : $core->msgError('<span>!خـطا</span>.یک خطا در اجرای این فراینـد وجود دارد، لطفـا با مدیریـت تماس بگیـریـد',false);

		  } else
			  print $core->msgStatus();
	  }
	  
      /**
       * User::activateUser()
       * 
       * @return
       */
	  public function activateUser()
	  {
		  global $db, $core;
		  
		  if (empty($_POST['email']))
			  $core->msgs['email'] = '..لطفـا ایـمیـل معتبـر خود را وارد نمائیـد';
		  
		  if (!$this->emailExists($_POST['email']))
			  $core->msgs['email'] = '..ایـمیـل وارد شـده وجـود ندارد';
		  
		  if (empty($_POST['token']))
			  $core->msgs['token'] = 'کـد رمـز معتبـر نیسـت';
		  
		  if (!$this->validateToken($_POST['token']))
			  $core->msgs['token'] = '!این حسـاب در حال حاضـر فعـال شـده اسـت';
		  
		  if (empty($core->msgs)) {
			  $email = sanitize($_POST['email']);
			  $token = sanitize($_POST['token']);
			  $message = ($core->auto_verify == 1) ? '<span>!موفقیـت</span>!حسـاب شمـا با موفقیـت فعـال شـد' : '<span>!موفقیـت</span>.حسـاب کاربری شمـا در حال حاضـر فعـال اسـت، با این حـال شمـا هنـوز می بایسـت در انتظـار تائیـد بمانیـد';
			  
			  $data = array(
					'token' => 0, 
					'active' => ($core->auto_verify) ? "y" : "n"
			  );
			  
			  $db->update($this->uTable, $data, "email = '" . $email . "' AND token = '" . $token . "'");
			  ($db->affected()) ? $core->msgOk($message,false) : $core->msgError('<span>!خـطا</span>.خـطایی در فراینـد فعـال سـازی حسـاب کاربری وجود دارد، لطفـا با مدیریـت تماس بگیریـد',false);
		  } else
			  print $core->msgStatus();
	  }

	  /**
	   * Users::getUserData()
	   * 
	   * @return
	   */
	  public function getUserData()
	  {
		  global $db, $core;
		  
		  $sql = "SELECT *, DATE_FORMAT(created, '%a. %d, %M %Y') as cdate,"
		  . "\n DATE_FORMAT(lastlogin, '%a. %d, %M %Y') as ldate"
		  . "\n FROM " . $this->uTable
		  . "\n WHERE id = '" . $this->uid . "'";
		  $row = $db->first($sql);

		  return ($row) ? $row : 0;
	  }
	  	  	  	  	  	  	  	  
	  /**
	   * Users::usernameExists()
	   * 
	   * @param mixed $username
	   * @return
	   */
	  private function usernameExists($username)
	  {
		  global $db;
		  
		  $username = sanitize($username);
		  if (strlen($db->escape($username)) < 4)
			  return 1;
		  
		  $alpha_num = str_replace(" ", "", $username);
		  if (!ctype_alnum($alpha_num))
			  return 2;
		  
		  $sql = $db->query("SELECT username" 
		  . "\n FROM users" 
		  . "\n WHERE username = '" . $username . "'" 
		  . "\n LIMIT 1");
		  
		  $count = $db->numrows($sql);
		  
		  return ($count > 0) ? 3 : false;
	  }  	
	  
	  /**
	   * User::emailExists()
	   * 
	   * @param mixed $email
	   * @return
	   */
	  private function emailExists($email)
	  {
		  global $db;
		  
		  $sql = $db->query("SELECT email" 
		  . "\n FROM users" 
		  . "\n WHERE email = '" . sanitize($email) . "'" 
		  . "\n LIMIT 1");
		  
		  if ($db->numrows($sql) == 1) {
			  return true;
		  } else
			  return false;
	  }
	  
	  /**
	   * User::isValidEmail()
	   * 
	   * @param mixed $email
	   * @return
	   */
	  private function isValidEmail($email)
	  {
		  if (function_exists('filter_var')) {
			  if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
				  return true;
			  } else
				  return false;
		  } else
			  return preg_match('/^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/', $email);
	  } 	

	  /**
	   * User::confirmCookie()
	   * 
	   * @param mixed $username
	   * @param mixed $cookie_id
	   * @return
	   */
	  private function confirmCookie($username, $cookie_id)
	  {
		  global $db;
		  
		  $sql = "SELECT cookie_id FROM users WHERE username = '" . $db->escape($username) . "'";
		  $row = $db->first($sql);
		  
		  $row['cookie_id'] = sanitize($row['cookie_id']);
		  $cookie_id = sanitize($cookie_id);
		  
		  if ($cookie_id == $row['cookie_id']) {
			  return true;
		  } else
			  return false;
	  }
	  
      /**
       * User::validateToken()
       * 
       * @param mixed $token
       * @return
       */
     private function validateToken($token)
      {
          global $db;
          $token = sanitize($token,40);
          $sql = "SELECT token" 
		  . "\n FROM ".$this->uTable 
		  . "\n WHERE token ='" . $db->escape($token) . "'" 
		  . "\n LIMIT 1";
          $result = $db->query($sql);
          
          if ($db->numrows($result))
              return true;
      }
	  
	  /**
	   * Users::getUniqueCode()
	   * 
	   * @param string $length
	   * @return
	   */
	  private function getUniqueCode($length = "")
	  {
		  $code = sha1(uniqid(rand(), true));
		  if ($length != "") {
			  return substr($code, 0, $length);
		  } else
			  return $code;
	  }

	  /**
	   * Users::generateRandID()
	   * 
	   * @return
	   */
	  private function generateRandID()
	  {
		  return sha1($this->getUniqueCode(24));
	  }

	  /**
	   * Users::levelCheck()
	   * 
	   * @param string $levels
	   * @return
	   */
	  public function levelCheck($levels)
	  {
		  global $db;
		  $m_arr = explode(",", $levels);
		  reset($m_arr);
		  
		  if ($this->logged_in and in_array($this->userlevel, $m_arr))
		  return true;
	  }
	  
      /**
       * Users::getUserLevels()
       * 
       * @return
       */
      public function getUserLevels($level = false)
	  {
		  $arr = array(
				 9 => 'Super Admin',
				 1 => 'Registered User',
				 2 => 'User Level 2',
				 3 => 'User Level 3',
				 4 => 'User Level 4',
				 5 => 'User Level 5',
				 6 => 'User Level 6',
				 7 => 'User Level 7'
		  );
		  
		  $list = '';
		  foreach ($arr as $key => $val) {
				  if ($key == $level) {
					  $list .= "<option selected=\"selected\" value=\"$key\">$val</option>\n";
				  } else
					  $list .= "<option value=\"$key\">$val</option>\n";
		  }
		  unset($val);
		  return $list;
	  } 
	  	  	  
      /**
       * Users::getUserFilter()
       * 
       * @return
       */
      public function getUserFilter()
	  {
		  $arr = array(
				 'username-ASC' => 'Username &uarr;',
				 'username-DESC' => 'Username & &darr;',
				 'fname-ASC' => 'First Name &uarr;',
				 'fname-DESC' => 'First Name &darr;',
				 'lname-ASC' => 'Last Name &uarr;',
				 'lname-DESC' => 'Last Name &darr;',
				 'email-ASC' => 'Email Address &uarr;',
				 'email-DESC' => 'Email Address &darr;',
				 'created-ASC' => 'Registered &uarr;',
				 'created-DESC' => 'Registered &darr;',
		  );
		  
		  $filter = '';
		  foreach ($arr as $key => $val) {
				  if ($key == get('sort')) {
					  $filter .= "<option selected=\"selected\" value=\"$key\">$val</option>\n";
				  } else
					  $filter .= "<option value=\"$key\">$val</option>\n";
		  }
		  unset($val);
		  return $filter;
	  } 	  	  	  	   
  }
?>