<?php
/*
	File     : MailAccount.class.php
	Version  : 0.2 Beta
	Copyright: Attila Soki 2001
	e-mail   : atiware@gmx.net
	Date     : 2001-05-12

*/
	include_once("MySql.class.php");
	include_once("Domain.class.php");

	class MailAccount {
		var $_user=null;
		var $_domain=null;
		var $_isalias=false;
		var $_password=null;
		var $_aalias=null; //array of aliases
		var $_aliascount=0;
		var $_exists=false;
		var $domain=null;

		function getUser() {
			return $this->_user;
		}

		function getUsername() {
			return $this->getUser();
		}

		function getDomain() {
			return $this->_domain;
		}

		function getEmail() {
			return $this->getUser()."@".$this->getDomain();
		}

		function getPassword() {
			return $this->_password;
		}

		function isAlias() {
			return ((int)$this->_isalias);
		}

		function checkEmailFormat($email=null) {
			$retval=true;
			if(!ereg("^([0-9,a-z,A-Z,-]+)([.,_]([0-9,a-z,A-Z,-]+))*[@]([0-9,a-z,A-Z,-]+)([.,_,-]([0-9,a-z,A-Z,-]+))*[.]([0-9,a-z,A-Z]){2}([0-9,a-z,A-Z])?$",$email))
				$retval=false;
			if ($retval) {
				if (strpos($email,"@")!=strrpos($email,"@")) {
					$retval=false; //two or more @ sign
				} //end if
				if (@eregi("\\",$email)) {
					$retval=false;
				} //end if
			} //end if
			return $retval;
		}

		function chkEmailFormat($email=null) {
			return $this->checkEmailFormat($email);
		}

		function isAliasToken() {
			$retval="no";
			if ($this->isAlias())
				$retval="yes";
			return $retval;
		}

		function isValid() {
			return $this->_exists;
		}

		function getAliasAt($i=null) {
			return $this->_aalias[$i];
		}

		function getAliasDomainAt($i=null) {
			return stristr("@",$this->_aalias[$i]);
		}

		function getAliasUserAt($i=null) {
			return substr($this->_aalias[$i],0,strpos($this->_aalias[$i],"@"));
		}

		function getAliasCount() {
			return $this->_aliascount;
		}

		function getDomainId() {
			return $this->domain->getId();
		}

		//connect to remote mysql server 
		//because you can work from a central workstation and connect to remote e-mail servers
		function _connectDB(&$dbo) {
			if ($dbo) {
				$dbo->setDbName($this->domain->getMySqlDb());
				$dbo->setPort($this->domain->getMySqlServerPort());
				$dbo->setHost($this->domain->getMySqlServerIp());
				$dbo->setUser($this->domain->getMySqlUser());
				$dbo->setPassword($this->domain->getMySqlPassword());
				$dbo->connect(); //now can connect
			}
		}

		function _connectMainDB(&$dbo) {
			if ($dbo) {
				$dbo->setDbName(MAIL_MYSQL_DB);
				$dbo->setPort(MAIL_MYSQL_PORT);
				$dbo->setHost(MAIL_MYSQL_HOST);
				$dbo->setUser(MAIL_MYSQL_USER);
				$dbo->setPassword(MAIL_MYSQL_PASSWORD);
				$dbo->connect(); //now can connect
			}
		}


		//$domain==string ("qwert.com") or $domain==(int)domainid
		//$user="username"
		function _init($user=null,$domain=null) {
			$this->_user=$user;
			$this->_isalias=false;
			$this->_password=null;
			$this->_aalias=null; //array of aliases
			$this->_aliascount=0;
			$this->_exists=false;
			$this->domain=new Domain($domain);
			$this->_domain=$this->domain->getDomain();

			//locals
			$pass=null;

			if (($user) && ($this->domain->isValid())) {
				$dbo=new MySql(false); //dont connect (maybe on other server)
				$this->_connectDB($dbo);
				$dbo->query("select * from ".$this->domain->getMailTable()." where ".$this->domain->getDomainField()."='".$this->domain->getDomain()."' and ".$this->domain->getUserField()."='".$this->getUser()."'");
				if ($dbo->numRows()) {
					if ((int)$dbo->numRows()>1)
						$this->_isalias=true; //because must duplicate entry for more alias
					else
						$this->_isalias=-1; //last theory wokrs not here, must load the variable
					$this->_exists=true;
					$i=0;
					while ($mr=$dbo->fetchArray()) {
						if ($this->_isalias==-1)
							$this->_isalias=(strcasecmp($mr[$this->domain->getIsAliasField()],"yes")==0) ? true:false;
						$pass=$mr[$this->domain->getPasswordField()];
						if (strlen($pass)!=0)
							$this->_password=stripslashes($pass);
						if ((int)$this->_isalias)
							$this->_aalias[$this->_aliascount++]=$mr[$this->domain->getAliasField()];
					}
					$dbo->freeResult();
				}
				$dbo->close();
			}
		}


		//$domain==string ("qwert.com") or $domain==(int)domainid
		//$user="username"
		function MailAccount($user=null,$domain=null) {
			$this->_init($user,$domain);
		}


		//you can set empty passwords too. this isn't an error!
		function setPassword($wpass=null) {
			$pass=addslashes($wpass);
			$dbo=new MySql(false);
			$this->_connectDB($dbo);
			if ($this->domain->hasCryptedPasswords())
				$dbo->query("update ".$this->domain->getMailTable()." set ".$this->domain->getPasswordField()."=encrypt(\"".$pass."\") where ".$this->domain->getUserField()."='".$this->getUser()."' and ".$this->domain->getDomainField()."='".$this->domain->getDomain()."'");
			else
				$dbo->query("update ".$this->domain->getMailTable()." set ".$this->domain->getPasswordField()."=\"".$pass."\" where ".$this->domain->getUserField()."='".$this->getUser()."' and ".$this->domain->getDomainField()."='".$this->domain->getDomain()."'");
			$dbo->close();
			$this->_init($this->getUser(),$this->domain->getId());
		}

		function setIsAlias($isalias=null) {
			$dbo=new MySql(false);
			$this->_connectDB($dbo);
			if ($isalias) {
				//empty password field too
				$wtoken="yes";
				$dbo->query("update ".$this->domain->getMailTable()." set ".$this->domain->getIsAliasField()."='".$wtoken."',".$this->domain->getPasswordField()."='' where ".$this->domain->getUserField()."='".$this->getUser()."' and ".$this->domain->getDomainField()."='".$this->domain->getDomain()."'");
			}
			else {
				//empty alias field too
				$wtoken="no";
				$dbo->query("update ".$this->domain->getMailTable()." set ".$this->domain->getIsAliasField()."='".$wtoken."',".$this->domain->getAliasField()."='' where ".$this->domain->getUserField()."='".$this->getUser()."' and ".$this->domain->getDomainField()."='".$this->domain->getDomain()."'");
			}
			$dbo->close();
			$this->_init($this->getUser(),$this->domain->getId());
		}

		//return true if user exists @thisdomain
		function userExists($user=null) {
			$retval=true;
			if ($user) {
				$dbo=new MySql(false);
				$this->_connectDB($dbo);
				$dbo->query("select * from ".$this->domain->getMailTable()." where ".$this->domain->getUserField()."='".$user."'  and ".$this->domain->getDomainField()."='".$this->domain->getDomain()."'");
				if ($dbo->numRows()==0)
					$retval=false;
				else
					$dbo->freeResult();
				$dbo->close();
			}
			return $retval;
		}


		//chk username format
		function checkUsername($user=null) {
			$retval=true;
			if ((strlen($user)==0) || (strlen($user)>63))
				$retval=false;

			if (!ereg("[0-9,a-z,@,-,_,.]",$user))
				$retval=false;
			if ($retval) {
				if (@eregi("@",$user))
					$retval=false;
				if (@eregi("\\",$user)) {
					$retval=false;
				} //end if
			} //end if

			if ($retval)
				$retval=!$this->userExists($user);
			return $retval;
		}


		//create((int)isalias,"password",(array)alias);
		//alias array: $aalias[0]="firstalias@xxx.com"; $aalias[1]="secondalias@xxx.com"; ....
		function create($isalias=null,$password=null,$aalias=null) {
			$retval=false;
			if (!$this->isValid()) {
				if ($isalias) {
					//create new alias user
					if (sizeof($aalias)>0) {
						$dbo=new MySql(false);
						$this->_connectDB(&$dbo);
						for ($i=0;$i<sizeof($aalias);$i++) {
							$q="insert into ".$this->domain->getMailTable()." (";
							$q.=$this->domain->getUserField().",";
							$q.=$this->domain->getDomainField().",";
							$q.=$this->domain->getAliasField().",";
							$q.=$this->domain->getIsAliasField().",";
							$q.=$this->domain->getPasswordField().") values(";
							$q.="'".$this->getUser()."',";
							$q.="'".$this->domain->getName()."',";
							$q.="'".$aalias[$i]."',";
							$q.="'yes','')";
							$dbo->query($q);
						}
						$dbo->close();
						$this->_init($this->getUser(),$this->domain->getId());
						$retval=$this->isValid();
					}
				}
				else {
					//create normal user (not alias)
					$dbo=new MySql(false);
					$this->_connectDB(&$dbo);
					$q="insert into ".$this->domain->getMailTable()." (";
					$q.=$this->domain->getUserField().",";
					$q.=$this->domain->getDomainField().",";
					$q.=$this->domain->getAliasField().",";
					$q.=$this->domain->getIsAliasField().",";
					$q.=$this->domain->getPasswordField().") values(";
					$q.="'".$this->getUser()."',";
					$q.="'".$this->domain->getName()."',";
					$q.="'',";
					$q.="'no',";
					if ($this->domain->hasCryptedPasswords())
						$q.="encrypt(\"".addslashes($password)."\"))";
					else
						$q.="\"".addslashes($password)."\")";
					$dbo->query($q);
					$dbo->close();
					$this->_init($this->getUser(),$this->domain->getId());
					$retval=$this->isValid();
				}
			}
			return $retval;
		}

		//delete user from exims mail table
		//if alias, all alias will be deleted
		function kill() {
			$dbo=new MySql(false);
			$this->_connectDB($dbo);
			$dbo->query("delete from ".$this->domain->getMailTable()." where ".$this->domain->getUserField()."='".$this->getUser()."' and ".$this->domain->getDomainField()."='".$this->domain->getDomain()."'");
			$dbo->close();
			$this->_init($this->getUser(),$this->domain->getId());
		}

		//kill one alias
		//killAlias("alias@xxx.com"); (delete from xx where alias="alias@xxx.com" and domain="thisdomain" and user="thisuser")
		//i don't care if the lamer kills the last alias......
		function killAlias($alias=null) {
			$dbo=new MySql(false);
			$this->_connectDB($dbo);
			$dbo->query("delete from ".$this->domain->getMailTable()." where ".$this->domain->getUserField()."='".$this->getUser()."' and ".$this->domain->getDomainField()."='".$this->domain->getDomain()."' and ".$this->domain->getAliasField()."='".$alias."'");
			$dbo->close();
			$this->_init($this->getUser(),$this->domain->getId());
		}


		//add one or more new alias to an existing user
		//if user not alias then will change it to isalias="yes";
		//duplicate alias names will be ignored
		//alias array: $aalias[0]="firstalias@xxx.com"; $aalias[1]="secondalias@xxx.com"; ....
		function addAlias($aalias=null) {
			$dbo=new MySql(false);
			$this->_connectDB($dbo);
			$changed=false;
			for ($i=0;$i<sizeof($aalias);$i++) {
				$notexists=true;
				for ($ii=0;(($ii<$this->getAliasCount()) && ($notexists));$ii++) {
					if (strcmp($aalias[$i],$this->getAliasAt($ii))==0)
						$notexists=false;
				}
				if ($notexists) {
					$changed=true;
					if ($this->isAlias()) {
						$q="insert into ".$this->domain->getMailTable()." (";
						$q.=$this->domain->getUserField().",";
						$q.=$this->domain->getDomainField().",";
						$q.=$this->domain->getAliasField().",";
						$q.=$this->domain->getIsAliasField().",";
						$q.=$this->domain->getPasswordField().") values(";
						$q.="'".$this->getUser()."',";
						$q.="'".$this->domain->getName()."',";
						$q.="'".$aalias[$i]."',";
						$q.="'yes','')";
						$dbo->query($q);
						$this->_aalias[$this->_aliascount++]=$aalias[$i];
					}
					else {
						//changing user to alias
						$q="update ".$this->domain->getMailTable()." set ".$this->domain->getIsAliasField()."='yes',";
						$q.=$this->domain->getPasswordField()."='',";
						$q.=$this->domain->getAliasField()."='".$aalias[$i]."' ";
						$q.="where ".$this->domain->getDomainField()."='".$this->domain->getDomain()."' and ";
						$q.=$this->domain->getUserField()."='".$this->getUser()."'";
						$dbo->query($q);
						$this->_isalias=true; //we dont _init now, later...
						$this->_aalias[$this->_aliascount++]=$aalias[$i];
					}
				}
			}
			$dbo->close();
			if ($changed)
				$this->_init($this->getUser(),$this->domain->getId());
		}


		//convert the isalias="no" user to alias
		//alias array: $aalias[0]="firstalias@xxx.com"; $aalias[1]="secondalias@xxx.com"; ....
		//see addAlias() too....
		function convertToAlias($aalias=null) {
			$this->setPassword(null);
			$this->addAlias($aalias);
		}

		//convert the isalias="yes" user to isalias="no"
		//delete its all aliases and set a password
		//convertToNormal("newuserpassword")
		function convertToNormal($pass=null) {
			//delete all alias except last
			for ($i=0;$i<($this->getAliasCount()-1);$i++) {
				$this->killAlias($this->getAliasAt($i));
			}
			$this->setIsAlias(false);
			$this->setPassword($pass);
		}


		//change the users name (changes the e-mail account name)
		//changeUsername("newname");
		//you must check the new username before you change it
		//! see checkUsername("newusername") too !
		function changeUsername($user=null) {
			if ($user) {
				$dbo=new MySql(false);
				$this->_connectDB($dbo);
				$dbo->query("update ".$this->domain->getMailTable()." set ".$this->domain->getUserField()."='".$user."' where ".$this->domain->getUserField()."='".$this->getUser()."' and ".$this->domain->getDomainField()."='".$this->domain->getDomain()."'");
				$dbo->close();
				$this->_init($user,$this->domain->getId());
			}
		}
	}
?>