Current File : //etc/zpanel/panel/modules/mailboxes/code/controller.ext.php
<?php

/**
 * @copyright 2014-2015 Sentora Project (http://www.sentora.org/) 
 * Sentora is a GPL fork of the ZPanel Project whose original header follows:
 *
 * ZPanel - A Cross-Platform Open-Source Web Hosting Control panel.
 *
 * @package ZPanel
 * @version $Id$
 * @author Bobby Allen - ballen@bobbyallen.me
 * @copyright (c) 2008-2014 ZPanel Group - http://www.zpanelcp.com/
 * @license http://opensource.org/licenses/gpl-3.0.html GNU Public License v3
 *
 * This program (ZPanel) is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
class module_controller extends ctrl_module
{

    static $ok;
    static $password;
    static $alreadyexists;
    static $validemail;
    static $noaddress;
    static $editmailbox;
    static $update;
    static $delete;
    static $create;
    static $badpassword;
	static $f_quota;
	static $m_quota;
    /**
     * The 'worker' methods.
     */
	 static function get_client_ip() {
				$ipaddress = '';
				if (getenv('HTTP_CLIENT_IP'))
				$ipaddress = getenv('HTTP_CLIENT_IP');
				else if(getenv('HTTP_X_FORWARDED_FOR'))
				$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
				else if(getenv('HTTP_X_FORWARDED'))
				$ipaddress = getenv('HTTP_X_FORWARDED');
				else if(getenv('HTTP_FORWARDED_FOR'))
				$ipaddress = getenv('HTTP_FORWARDED_FOR');
				else if(getenv('HTTP_FORWARDED'))
				$ipaddress = getenv('HTTP_FORWARDED');
				else if(getenv('REMOTE_ADDR'))
				$ipaddress = getenv('REMOTE_ADDR');
				else
				$ipaddress = 'UNKNOWN';
				return $ipaddress;
		}
    static function ListMailboxes($id)
    {
        global $zdbh;
        global $controller;
        $currentuser = ctrl_users::GetUserDetail($id);
        $sql = "SELECT * FROM x_mailboxes WHERE mb_acc_fk=:userid AND mb_deleted_ts IS NULL ORDER BY mb_address_vc ASC";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':userid', $currentuser['userid']);
        $numrows->execute();
		$count = $numrows->fetchColumn();

        
        
        if ($count > 0) {

            $sql = $zdbh->prepare($sql);
            $sql->bindParam(':userid', $currentuser['userid']);
            $res = array();
            $sql->execute();
            $encrypt_key = self::GetEncryptionKey();
            while ($rowmailboxes = $sql->fetch()) {
		$m_quota= $rowmailboxes['mb_quota'];	
	
		$mail_input = $rowmailboxes['mb_address_vc'];
		$out = $rowmailboxes['mb_size'];
		
                if ($rowmailboxes['mb_enabled_in'] == 1) {
                    $status = '<img src="modules/' . $controller->GetControllerRequest('URL', 'module') . '/assets/up.gif" alt="Up"/>';
                } else {
                    $status = '<img src="modules/' . $controller->GetControllerRequest('URL', 'module') . '/assets/down.gif" alt="Down"/>';
                }

				$m_quota_size = $m_quota * 1024;
				$out==0 ? $out_size=0.0 : $out_size = sprintf('%.2f',$out /1024);
			    	
				$dp = sprintf('%.2f',($out / $m_quota_size) * 100);
                $encrypted_pass = self::GetEncryptedPassword($rowmailboxes['mb_address_vc']); 
		$ip_address = date(ctrl_options::GetSystemOption('server_ip'));
                $res[] = array('address' => $rowmailboxes['mb_address_vc'],
                    'created' => date(ctrl_options::GetSystemOption('sentora_df'), $rowmailboxes['mb_created_ts']),
                    'status' => $status,
					'quota' => $m_quota,
					'used' => $out_size,
					'encrypted_pass' => $encrypted_pass,
					'ip_address' => $ip_address,
					'encrypt_key' => $encrypt_key,
					'progress'=> '<progress value="'.$dp.'" max="100"></progress>',
                    'id' => $rowmailboxes['mb_id_pk']);
            }
	
            return $res;
		
        } else {
            return false;
        }
    }

    static function GetEncryptionKey()
    {
        global $zdbh;
        $numrows = $zdbh->prepare("select * from x_settings WHERE so_desc_tx = 'email_pass_encryption_key' LIMIT 1");
        $numrows->execute();
        $row_count2 = $numrows->rowCount();
        $encrypt_key = null;
        if($row_count2 >0)
        {
            $rowmailbox = $numrows->fetch();
            $encrypt_key = $rowmailbox['so_defvalues_tx'] ;
        }
        return $encrypt_key;
    }
 static function gethelpicon()
{
    global $zdbh;
    global $controller;
    $temp=$controller->GetControllerRequest('URL','module') ;
    $val = '/assets/one.txt';
    $val1 = '/modules/';
   $name=file_get_contents("modules/$temp/assets/helpicon.txt");
   return $name;
}

    static function ListCurrentMailboxes($mid)
    {
        global $zdbh;
		global $controller;		
        $sql = "SELECT * FROM x_mailboxes WHERE mb_id_pk=:mid AND mb_deleted_ts IS NULL ORDER BY mb_address_vc ASC";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':mid', $mid);
        $numrows->execute();
        if ($numrows->fetchColumn() <> 0) {
            $sql = $zdbh->prepare($sql);
            $sql->bindParam(':mid', $mid);
            $res = array();
            $sql->execute();
            while ($rowmailboxes = $sql->fetch()) {
                if ($rowmailboxes['mb_enabled_in'] == 1) {
                    $ischeck = "CHECKED";
                } else {
                    $ischeck = NULL;
                }
					$m_quota=$rowmailboxes['mb_quota'];
	                $res[] = array('address' => $rowmailboxes['mb_address_vc'],
                    'created' => date(ctrl_options::GetSystemOption('sentora_df'), $rowmailboxes['mb_created_ts']),
                    'ischeck' => $ischeck,
					'quota' => $m_quota,
                    'id' => $rowmailboxes['mb_id_pk']);
            }
            return $res;
        } else {
            return false;
        }
    }

    static function ListDomains($uid)
    {
        global $zdbh;
        $currentuser = ctrl_users::GetUserDetail($uid);
        $sql = "SELECT * FROM x_vhosts WHERE vh_acc_fk=:userid AND vh_enabled_in=1 AND vh_deleted_ts IS NULL ORDER BY vh_name_vc ASC";
        //$numrows = $zdbh->query($sql);
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':userid', $currentuser['userid']);
        $numrows->execute();
        if ($numrows->fetchColumn() <> 0) {
            $sql = $zdbh->prepare($sql);
            $sql->bindParam(':userid', $currentuser['userid']);
            $res = array();
            $sql->execute();
            while ($rowdomains = $sql->fetch()) {
                $res[] = array('domain' => ui_language::translate($rowdomains['vh_name_vc']));
            }
            return $res;
        } else {
            return false;
        }
    }

    static function ExecuteAddMailbox($uid, $address, $domain, $password,$quota)
    {
        global $zdbh;
        global $controller;
        $encrypted_pass = self::EncryptPassword($password);
        $currentuser = ctrl_users::GetUserDetail($uid);
        $uid = $currentuser['userid'];
        $query = "SELECT * from x_password_strength WHERE ps_user_vc='$uid'";
        $res = $zdbh->prepare($query);
        $res->execute();
        $results = $res->rowCount();
        if (fs_director::CheckForEmptyValue(self::CheckCreateForErrors($address, $domain, $password,$quota))) {
            return false;
        }
        runtime_hook::Execute('OnBeforeCreateMailbox');
        if($results == 0)
         {
	   if(!preg_match_all('$\S*(?=\S{9,})(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])(?=\S*[\W])\S*$', $password))
	   {
    		self::$badpassword = true;
                return false;
	   }
        $address = strtolower(str_replace(' ', '', $address));
        $fulladdress = strtolower(str_replace(' ', '', $address . "@" . $domain));
        self::$create = true;
        // Include mail server specific file here.
        $MailServerFile = 'modules/' . $controller->GetControllerRequest('URL', 'module') . '/code/' . ctrl_options::GetSystemOption('mailserver_php');
        if (file_exists($MailServerFile))
            include($MailServerFile);

        $sql = "INSERT INTO x_mailboxes (mb_acc_fk,
											 mb_address_vc,mb_quota,
											 mb_created_ts) VALUES (
											 :userid,
											 :fulladdress,
											 :mb_quota,
											 :time)";
        $time = time();
        $sql = $zdbh->prepare($sql);
        $sql->bindParam(':time', $time);
        $sql->bindParam(':userid', $currentuser['userid']);
		$sql->bindParam(':mb_quota',$quota);
        $sql->bindParam(':fulladdress', $fulladdress);
		
        $sql->execute();
        runtime_hook::Execute('OnAfterCreateMailbox');
        if($encrypted_pass)
            self::updateEncryptedPass($fulladdress, $encrypted_pass); 
        self::$ok = true;
        return true;
	 }
        while($rows=$res->fetch())
        {
        $values= ($rows['ps_eaenabled_in'] == 0 ) ? "0" : "1";
	  if($values == 0)
          {
	  if(!preg_match_all('$\S*(?=\S{9,})(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])(?=\S*[\W])\S*$', $password))
           {
             self::$badpassword = true;
             return false;
           }
	$address = strtolower(str_replace(' ', '', $address));
        $fulladdress = strtolower(str_replace(' ', '', $address . "@" . $domain));
        self::$create = true;
        // Include mail server specific file here.
        $MailServerFile = 'modules/' . $controller->GetControllerRequest('URL', 'module') . '/code/' . ctrl_options::GetSystemOption('mailserver_php');
        if (file_exists($MailServerFile))
            include($MailServerFile);

        $sql = "INSERT INTO x_mailboxes (mb_acc_fk,
                                                                                         mb_address_vc,mb_quota,
                                                                                         mb_created_ts) VALUES (
                                                                                         :userid,
                                                                                         :fulladdress,
                                                                                         :mb_quota,
                                                                                         :time)";
        $time = time();
        $sql = $zdbh->prepare($sql);
        $sql->bindParam(':time', $time);
        $sql->bindParam(':userid', $currentuser['userid']);
                $sql->bindParam(':mb_quota',$quota);
        $sql->bindParam(':fulladdress', $fulladdress);

        $sql->execute();
        runtime_hook::Execute('OnAfterCreateMailbox');
        if($encrypted_pass)
            self::updateEncryptedPass($fulladdress, $encrypted_pass); 

        self::$ok = true;
        return true;
          }
        else
           if($values == "1")
           {
            $address = strtolower(str_replace(' ', '', $address));
            $fulladdress = strtolower(str_replace(' ', '', $address . "@" . $domain));
            self::$create = true;
            // Include mail server specific file here.
            $MailServerFile = 'modules/' . $controller->GetControllerRequest('URL', 'module') . '/code/' . ctrl_options::GetSystemOption('mailserver_php');
            if (file_exists($MailServerFile))
            include($MailServerFile);

            $sql = "INSERT INTO x_mailboxes (mb_acc_fk,
                                                                                         mb_address_vc,mb_quota,
                                                                                         mb_created_ts) VALUES (
                                                                                         :userid,
                                                                                         :fulladdress,
                                                                                         :mb_quota,
                                                                                         :time)";
            $time = time();
            $sql = $zdbh->prepare($sql);
            $sql->bindParam(':time', $time);
            $sql->bindParam(':userid', $currentuser['userid']);
            $sql->bindParam(':mb_quota',$quota);
            $sql->bindParam(':fulladdress', $fulladdress);

            $sql->execute();
        
            runtime_hook::Execute('OnAfterCreateMailbox');
            if($encrypted_pass)
                self::updateEncryptedPass($fulladdress, $encrypted_pass); 

            self::$ok = true;
            return true;

           }
        }
    }

    static function GetEncryptedPassword($email_id)
    {
        $mailserver_db = ctrl_options::GetSystemOption('mailserver_db');
        include('cnf/db.php');
        $z_db_user = $user;
        $z_db_pass = $pass;
        try {
            $mail_db = new db_driver("mysql:host=" . $host . ";dbname=" . $mailserver_db . "", $z_db_user, $z_db_pass);
        } catch (PDOException $e) {
            echo $e;
        }
        $numrows = $mail_db->prepare("SELECT encrypted_pass FROM mailbox WHERE username=:email");
        $numrows->bindParam(':email', $email_id);
        $numrows->execute();
        $rowmailbox = $numrows->fetch();
        $encrypted_pass = $rowmailbox['encrypted_pass'];
        return $encrypted_pass;
    }
    
    static function updateEncryptedPass($email_id, $encrypted_pass)
    {
        $mailserver_db = ctrl_options::GetSystemOption('mailserver_db');
        include('cnf/db.php');
        $z_db_user = $user;
        $z_db_pass = $pass;
        try {
            $mail_db = new db_driver("mysql:host=" . $host . ";dbname=" . $mailserver_db . "", $z_db_user, $z_db_pass);
        } catch (PDOException $e) {
            echo $e;
        }
        $numrows = $mail_db->prepare("SELECT * FROM mailbox WHERE username=:email");
        $numrows->bindParam(':email', $email_id);
        $numrows->execute();
        $rowmailbox = $numrows->fetch();
        
        $m_numrows = $mail_db->prepare("UPDATE mailbox SET encrypted_pass=:encrypted_pass WHERE username=:fulladdress");
        $m_numrows->bindParam(':encrypted_pass', $encrypted_pass);
        $m_numrows->bindParam(':fulladdress', $email_id);
        $m_numrows->execute();
    }

    static function EncryptPassword($pass)
    {
        $encrypt_key = self::GetEncryptionKey();
        if($encrypt_key)
        {
            $key = pack('H*', $encrypt_key);
            $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
            $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
            $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $pass, MCRYPT_MODE_CBC, $iv);
            $ciphertext = $iv . $ciphertext;
            $encrypted_pass = base64_encode($ciphertext);
        }
        return $encrypted_pass;         
    }

    static function ExecuteDeleteMailbox($mid)
    {
        global $zdbh;
        global $controller;
        runtime_hook::Execute('OnBeforeDeleteMailbox');
        self::$delete = true;

        //$rowmailbox = $zdbh->query("SELECT * FROM x_mailboxes WHERE mb_id_pk=" . $mid . "")->Fetch();
        $numrows = $zdbh->prepare("SELECT * FROM x_mailboxes WHERE mb_id_pk=:mid");
        $numrows->bindParam(':mid', $mid);
        $numrows->execute();
        $row_count2 = $numrows->rowCount();
        if($row_count2 >0)
        {
            $rowmailbox = $numrows->fetch();
        // Include mail server specific file here.
        
            $MailServerFile = 'modules/' . $controller->GetControllerRequest('URL', 'module') . '/code/' . ctrl_options::GetSystemOption('mailserver_php');
            if (file_exists($MailServerFile)) {
                include($MailServerFile);
            }
            $time = time();
			$ip_deleted =self::get_client_ip();
            $sql = "UPDATE x_mailboxes SET ip_deleted=:ip_deleted,mb_deleted_ts=:time WHERE mb_id_pk=:mid";
            $sql = $zdbh->prepare($sql);
            $sql->bindParam(':time', $time);
			 $sql->bindParam(':ip_deleted', $ip_deleted);
            $sql->bindParam(':mid', $mid);
            $sql->execute();
                
                $auto_email = $rowmailbox['mb_address_vc'];
                $auto_file_path = "/var/spool/autoresponse/responses/".$auto_email;
                if (file_exists($auto_file_path)) 
                {

                    $currentuser = ctrl_users::GetUserDetail();
                    $suid = $currentuser['userid'];
                    if(unlink($auto_file_path))
                    {
                        date_default_timezone_set("UTC");
                        $current_time = date("Y-m-d H:i:s");
                        $current_str_time =  strtotime($current_time);
                        $stmt4 =$zdbh->prepare("update x_autorespond set vh_deleted =:str_time  where  vh_mail =:vhid  and vh_acc_fk =:sid ");
                        $stmt4->bindParam(':str_time',$current_str_time);
                        $stmt4->bindParam(':sid',$suid);
                        $stmt4->bindParam(':vhid',$auto_email);
                        $stmt4->execute();   
                        /*********$affected_rows = $stmt4->rowCount(); *************/
                        
                    }
                    
                }
            
        }
        runtime_hook::Execute('OnAfterDeleteMailbox');
        self::$ok = true;
    }

    static function ExecuteUpdateMailbox($mid, $password, $enabled,$quota,$flag)
    {
        global $zdbh;
        global $controller;
        $currentuser = ctrl_users::GetUserDetail($uid);
		if($flag=="quota")
		{
						if (fs_director::CheckForEmptyValue($quota)) {
						self::$f_quota = true;
						return false;
						}
						$mailserver_db = ctrl_options::GetSystemOption('mailserver_db');
						include('cnf/db.php');
						$z_db_user = $user;
						$z_db_pass = $pass;
						try {
						$mail_db = new db_driver("mysql:host=" . $host . ";dbname=" . $mailserver_db . "", $z_db_user, $z_db_pass);
						} catch (PDOException $e) {
						echo $e;
						}
						$numrows = $zdbh->prepare("SELECT * FROM x_mailboxes WHERE mb_id_pk=:mid");
						$numrows->bindParam(':mid', $mid);
						$numrows->execute();
						$rowmailbox = $numrows->fetch();
					
						$m_numrows = $mail_db->prepare("update mailbox set quota=:quota WHERE username=:fulladdress");
						$m_numrows->bindParam(':quota', $quota);
						$m_numrows->bindParam(':fulladdress', $rowmailbox['mb_address_vc']);
						$m_numrows->execute();
						
						$numrows_update = $zdbh->prepare("update x_mailboxes set mb_quota=:quota WHERE mb_address_vc=:fulladdress");
						$numrows_update->bindParam(':quota', $quota);
						$numrows_update->bindParam(':fulladdress', $rowmailbox['mb_address_vc']);
						$numrows_update->execute();
						
						self::$ok = true;
		}else
		{
					runtime_hook::Execute('OnBeforeUpdateMailbox');
					$numrows = $zdbh->prepare("SELECT * FROM x_mailboxes WHERE mb_id_pk=:mid");
					$numrows->bindParam(':mid', $mid);
					$numrows->execute();
                    $rowmailbox = $numrows->fetch();
                    $fulladdress =  $rowmailbox['mb_address_vc'];
                    $encrypted_pass = self::EncryptPassword($password);
                    if($encrypted_pass)
                        self::updateEncryptedPass($fulladdress, $encrypted_pass);

					if ($enabled <> 0) {
					self::ExecuteEnableMailbox($mid);
					} else {
					self::ExecuteDisableMailbox($mid);
					}
					self::$update = true;
					// Include mail server specific file here.
                                       
                                        $userId = $currentuser['userid'];
        				$query = "SELECT * from x_password_strength WHERE ps_user_vc='$userId'";
       					$res = $zdbh->prepare($query);
        				$res->execute();
   				        $results = $res->rowCount();
					if($results == 0)
					{
	                                  if(!preg_match_all('$\S*(?=\S{9,})(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])(?=\S*[\W])\S*$', $password))
                                            {
                                              self::$badpassword = true;
                                              return false;
                                            }
					$MailServerFile = 'modules/' . $controller->GetControllerRequest('URL', 'module') . '/code/' . ctrl_options::GetSystemOption('mailserver_php');
					if (file_exists($MailServerFile)) {
					include($MailServerFile);
					}
					runtime_hook::Execute('OnAfterUpdateMailbox');
					self::$ok = true;
                                        }
                                        while($rows=$res->fetch())
					 {
					  $values= ($rows['ps_eaenabled_in'] == 0 ) ? "0" : "1";
 					  if($values == 0)
                                            {

						if(!preg_match_all('$\S*(?=\S{9,})(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])(?=\S*[\W])\S*$', $password))
                                            	  {
                                              		self::$badpassword = true;
                                              		return false;
                                            	  }
					$MailServerFile = 'modules/' . $controller->GetControllerRequest('URL', 'module') . '/code/' . ctrl_options::GetSystemOption('mailserver_php');
                                        if (file_exists($MailServerFile)) {
                                        include($MailServerFile);
                                        }
                                        runtime_hook::Execute('OnAfterUpdateMailbox');
                                        self::$ok = true;
                                            }
					else if($values == 1)
                                             {
					$MailServerFile = 'modules/' . $controller->GetControllerRequest('URL', 'module') . '/code/' . ctrl_options::GetSystemOption('mailserver_php');
                                        if (file_exists($MailServerFile)) {
                                        include($MailServerFile);
                                        }
                                        runtime_hook::Execute('OnAfterUpdateMailbox');
                                        self::$ok = true;

                                             }
                                        }


		}
		 

       
        return;
    }

    static function ExecuteEnableMailbox($mid)
    {
        global $zdbh;
        runtime_hook::Execute('OnBeforeEnableMailbox');
        $sql = $zdbh->prepare("UPDATE x_mailboxes SET mb_enabled_in=1 WHERE mb_id_pk=:mid");
        $sql->bindParam(':mid', $mid);
        $sql->execute();
        $retval = true;
        runtime_hook::Execute('OnAfterEnableMailbox');
        return $retval;
    }

    static function ExecuteDisableMailbox($mid)
    {
        global $zdbh;
        runtime_hook::Execute('OnBeforeDisableMailbox');
        $sql = $zdbh->prepare("UPDATE x_mailboxes SET mb_enabled_in=0 WHERE mb_id_pk=:mid");
        $sql->bindParam(':mid', $mid);
        $sql->execute();
        $retval = true;
        runtime_hook::Execute('OnAfterDisableMailbox');
        return $retval;
    }

    static function CheckCreateForErrors($address, $domain, $password,$quota)
    {
        global $zdbh;
        $fulladdress = strtolower(str_replace(' ', '', $address . '@' . $domain));
        if (fs_director::CheckForEmptyValue($address)) {
            self::$noaddress = true;
            return false;
        }
        if (fs_director::CheckForEmptyValue($password)) {
            self::$password = true;
            return false;
        }
        if (!self::IsValidEmail($fulladdress)) {
            self::$validemail = true;
            return false;
        }
        $sql = "SELECT * FROM x_mailboxes WHERE mb_address_vc=:fulladdress AND mb_deleted_ts IS NULL";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':fulladdress', $fulladdress);
        $numrows->execute();
        if ($numrows->fetchColumn() <> 0) {
            self::$alreadyexists = true;
            return false;
        }
        $sql = "SELECT * FROM x_forwarders WHERE fw_address_vc=:fulladdress AND fw_deleted_ts IS NULL";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':fulladdress', $fulladdress);
        $numrows->execute();
        if ($numrows->fetchColumn() <> 0) {
            self::$alreadyexists = true;
            return false;
        }
        $sql = "SELECT * FROM x_distlists WHERE dl_address_vc=:fulladdress AND dl_deleted_ts IS NULL";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':fulladdress', $fulladdress);
        $numrows->execute();
        if ($numrows->fetchColumn() <> 0) {
            self::$alreadyexists = true;
            return false;
        }
        $sql = "SELECT * FROM x_aliases WHERE al_address_vc=:fulladdress AND al_deleted_ts IS NULL";
        $numrows = $zdbh->prepare($sql);
        $numrows->bindParam(':fulladdress', $fulladdress);
        $numrows->execute();
        if ($numrows->fetchColumn() <> 0) {
            self::$alreadyexists = true;
            return false;
        }
		
	if (fs_director::CheckForEmptyValue($quota)) {
            self::$f_quota = true;
            return false;
        }
	$quota = (int)$quota;
	if($quota < 100)
	{
		self::$m_quota = true;
            	return false;
	}
		
        return true;
    }

    static function IsValidEmail($email)
    {
        return preg_match('/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i', $email) == 1;
    }

    /**
     * End 'worker' methods.
     */

    /**
     * Webinterface sudo methods.
     */
    static function doAddMailbox()
    {
        global $controller;
        runtime_csfr::Protect();
        $currentuser = ctrl_users::GetUserDetail();
        $formvars = $controller->GetAllControllerRequests('FORM');
        if (self::ExecuteAddMailbox($currentuser['userid'], $formvars['inAddress'], $formvars['inDomain'], $formvars['inPassword'],$formvars['inQuota']))
            self::$ok = true;
        return true;
    }

    static function doEditMailbox()
    {
        global $controller;
        runtime_csfr::Protect();
        $currentuser = ctrl_users::GetUserDetail();
        $formvars = $controller->GetAllControllerRequests('FORM');
        foreach (self::ListMailboxes($currentuser['userid']) as $row) {
            if (isset($formvars['inDelete_' . $row['id']])) {
                header("location: ./?module=" . $controller->GetCurrentModule() . '&show=Delete&other=' . $row['id']);
                exit;
            }
            if (isset($formvars['inEdit_' . $row['id']])) {
                header('location: ./?module=' . $controller->GetCurrentModule() . '&show=Edit&other=' . $row['id']);
                exit;
            }
			if (isset($formvars['inquotaEdit_' . $row['id']])) {
                header('location: ./?module=' . $controller->GetCurrentModule() . '&show=quotaEdit&other=' . $row['id']);
                exit;
            }
        }
        return true;
    }

    static function doUpdateMailbox()
    {
        global $controller;
        runtime_csfr::Protect();
        $currentuser = ctrl_users::GetUserDetail();
        $formvars = $controller->GetAllControllerRequests('FORM');
        $enabled = (isset($formvars['inEnabled'])) ? fs_director::GetCheckboxValue($formvars['inEnabled']) : 0;
        if (self::ExecuteUpdateMailbox($formvars['inSave'], $formvars['inPassword'],$enabled,$formvars['inQuota'],$formvars['flag']))
            self::$ok = true;
        return true;
    }

    static function doConfirmDeleteMailbox()
    {
        global $controller;
        runtime_csfr::Protect();
        $formvars = $controller->GetAllControllerRequests('FORM');
        return self::ExecuteDeleteMailbox($formvars['inDelete']);
    }

    static function getMailboxList()
    {
        $currentuser = ctrl_users::GetUserDetail();
        return self::ListMailboxes($currentuser['userid']);
    }

    static function getDomainList()
    {
        $currentuser = ctrl_users::GetUserDetail();
        return self::ListDomains($currentuser['userid']);
    }

    static function getCurrentMailboxList()
    {
        global $controller;
        return self::ListCurrentMailboxes($controller->GetControllerRequest('URL', 'other'));
    }

    static function GetMailOption($name)
    {
        global $zdbh;
        $numrows = $zdbh->prepare("SELECT mbs_value_tx FROM x_mail_settings WHERE mbs_name_vc = :name");
        $numrows->bindParam(':name', $name);
        $numrows->execute();
        $result = $numrows->fetch();
        return ($result) ? $result['mbs_value_tx'] : false;
    }

    static function getisCreateMailbox()
    {
        global $controller;
        $urlvars = $controller->GetAllControllerRequests('URL');
        return !isset($urlvars['show']);
    }

    static function getisDeleteMailbox()
    {
        global $controller;
        $urlvars = $controller->GetAllControllerRequests('URL');
        return (isset($urlvars['show'])) && ($urlvars['show'] == "Delete");
    }

    static function getisEditMailbox()
    {
        global $controller;
        $urlvars = $controller->GetAllControllerRequests('URL');
        return (isset($urlvars['show'])) && ($urlvars['show'] == "Edit");
    }

	 static function getisquotaEditMailbox()
    {
        global $controller;
        $urlvars = $controller->GetAllControllerRequests('URL');
        return (isset($urlvars['show'])) && ($urlvars['show'] == "quotaEdit");
    }
	
    static function getEditCurrentMailboxName()
    {
        global $controller;
        if ($controller->GetControllerRequest('URL', 'other')) {
            $current = self::ListCurrentMailboxes($controller->GetControllerRequest('URL', 'other'));
            return $current[0]['address'];
        } else {
            return '';
        }
    }

    static function getEditCurrentMailboxID()
    {
        global $controller;
        if ($controller->GetControllerRequest('URL', 'other')) {
            $current = self::ListCurrentMailboxes($controller->GetControllerRequest('URL', 'other'));
            return $current[0]['id'];
        } else {
            return "";
        }
    }

    static function getQuotaLimit()
    {
        $currentuser = ctrl_users::GetUserDetail();
        return ($currentuser['mailboxquota'] < 0) or //-1 = unlimited
                ($currentuser['mailboxquota'] > ctrl_users::GetQuotaUsages('mailboxes', $currentuser['userid']));
    }

    static function getEmailUsagepChart()
    {
        $currentuser = ctrl_users::GetUserDetail();
        $maximum = $currentuser['mailboxquota'];
        if ($maximum < 0) { //-1 = unlimited
            return '<img src="' . ui_tpl_assetfolderpath::Template() . 'img/misc/unlimited.png" alt="' . ui_language::translate('Unlimited') . '"/>';
        } else {
            $used = ctrl_users::GetQuotaUsages('mailboxes', $currentuser['userid']);
            $free = max($maximum - $used, 0);
            return '<img src="etc/lib/pChart2/sentora/z3DPie.php?score=' . $free . '::' . $used
                    . '&labels=Free: ' . $free . '::Used: ' . $used
                    . '&legendfont=verdana&legendfontsize=8&imagesize=240::190&chartsize=120::90&radius=100&legendsize=150::160"'
                    . ' alt="' . ui_language::translate('Pie chart') . '"/>';
        }
    }


static function getCurrentID()
    {
        global $zdbh;
        global $controller;
        $currentuser = ctrl_users::GetUserDetail();
        $uid = $currentuser['userid'];
        $query = "SELECT * from x_password_strength WHERE ps_user_vc='$uid'";
        $res = $zdbh->prepare($query);
        $res->execute();
        $results = $res->rowCount();
        $val = "";
        if($results == 0)
        {
          return "inPassword";
        }
        else
        if($results > 0)
        {
           while($rows=$res->fetch())
           {
                if($rows['ps_eaenabled_in'] == 0)
                {
                  return "inPassword";
                }
                else if($rows['ps_eaenabled_in'] == 1)
                {
                  return $val;
                }
           }
        }
    }

static function getGeneratePass()
    {
        global $zdbh;
        global $controller;
        $currentuser = ctrl_users::GetUserDetail();
        $uid = $currentuser['userid'];
        $query = "SELECT * from x_password_strength WHERE ps_user_vc='$uid'";
        $res = $zdbh->prepare($query);
        $res->execute();
        $results = $res->rowCount();
        $val = "";
        if($results == 0)
        {
          return "Generate Password";
        }
        else
        if($results > 0)
        {
           while($rows=$res->fetch())
           {
                if($rows['ps_eaenabled_in'] == 0)
                {
                  return "Generate Password";
                }
                else if($rows['ps_eaenabled_in'] == 1)
                {
                  return $val;
                }
           }
        }
    }


static function getcurrentnote()
    {
        global $zdbh;
        global $controller;
        $currentuser = ctrl_users::GetUserDetail();
        $uid = $currentuser['userid'];
        $query = "SELECT * from x_password_strength WHERE ps_user_vc='$uid'";
        $res = $zdbh->prepare($query);
        $res->execute();
        $results = $res->rowCount();
        $val = "";
        if($results == 0)
        {
          return true;
        }
        else
        if($results > 0)
        {
           while($rows=$res->fetch())
           {
                if($rows['ps_eaenabled_in'] == 0)
                {
                  return true;
                }
                else if($rows['ps_eaenabled_in'] == 1)
                {
                  return false;
                }
           }
        }
    }


    static function getResult()
    {
        if (!fs_director::CheckForEmptyValue(self::$alreadyexists)) {
            return ui_sysmessage::shout(ui_language::translate('A mailbox, alias, forwarder or distribution list already exists with that name.'), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$validemail)) {
            return ui_sysmessage::shout(ui_language::translate("Your email address is not valid."), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$password)) {
            return ui_sysmessage::shout(ui_language::translate("Your password cannot be blank."), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$noaddress)) {
            return ui_sysmessage::shout(ui_language::translate("Your email address cannot be blank."), "zannounceerror");
        }
		if (!fs_director::CheckForEmptyValue(self::$f_quota)) {
            return ui_sysmessage::shout(ui_language::translate("Mailbox quota cannot be blank."), "zannounceerror");
        }
	if (!fs_director::CheckForEmptyValue(self::$m_quota)) {
            return ui_sysmessage::shout(ui_language::translate("Mailbox quota size should be minimum 100."), "zannounceerror");
        }
        if (!fs_director::CheckForEmptyValue(self::$ok)) {
            return ui_sysmessage::shout(ui_language::translate("Changes to your mailboxes have been saved successfully!"), "zannounceok");
        }
		if (!fs_director::CheckForEmptyValue(self::$badpassword)) {
            return ui_sysmessage::shout(ui_language::translate("Your password did not meet the minimun length requirements.Characters needed for password length : 9 with atleast 1 uppercase,lowercase,special character.number"), "Error");
			}
        return;
    }

    /**
     * Webinterface sudo methods.
     */
}