<?php

class login {

    var $rows;
    var $configObj;

    function login($configObj) {
        $this->configObj = $configObj;
    }

    function getemaildata() {
        $sql = "Select var_emailid,var_emailid1,var_emailid2 from " . DB_PREFIX . "users where var_emailid= '" . $_POST['ss_username'] . "'";
        $exec = $this->configObj->glDbObj->query($sql);
        $rows = $this->configObj->glDbObj->num_rows($exec);
        if ($rows > 0) {
            $query = "select var_emailid,var_emailid1,var_emailid2,var_password,var_fname,var_lname  from " . DB_PREFIX . "users where var_emailid = '" . $_POST['ss_username'] . "'OR var_emailid1 = '" . $_POST['ss_username'] . "' OR var_emailid2 = '" . $_POST['ss_username'] . "' ";
            $execSQL = $this->configObj->glDbObj->query($query);
            $rows = $this->configObj->glDbObj->get_sql_row($query);
            $noofrows = $this->configObj->glDbObj->num_rows($execSQL);
            $this->rows = $rows;
            $adminname = $rsadmin['var_fname'] . " " . $rows['var_lname'];

            $EmailId1 = $rows['var_emailid1'];
            $EmailId2 = $rows['var_emailid2'];

            $adminEmail = "";
            if ($EmailId1 != "")
                $adminEmail .= $EmailId1;

            if ($EmailId2 != "")
                $adminEmail .= "," . $EmailId2;

            return $adminEmail;
        }
        else {
            $this->configObj->glLibraryObj->header_redirect("index.php?module=login&action=frgtpassword&msg=1");
        }
    }

    function sendmail() {

        $sql = "select * from " . DB_PREFIX . "users where chr_delete='N' and chr_publish='Y' and var_emailid='".$_POST['ss_username']."'";
        $exec = $this->configObj->glDbObj->get_sql_row($sql);

        if ($this->varpostdata['h_save'] == 'T') {
            
            $adminEmail = $this->getemaildata();
            if (!empty($adminEmail)) {
                $imgurl = SITE_PATH ."powerpanel/".GLOBAL_ADMIN_IMAGES_PATH . "logo-email.jpg";
//                $this->configObj->setEmailConfig();
                extract($_REQUEST);
                $subject = "Password Details";
                
                include('../libraries/sendmail/class.phpmailer.php');
                $mail  = new PHPMailer();
                
                $message = "Your Account Detail is:";
//                $message = "Thanking you for registering with us. Please review the following details:";
                $html_message = file_get_contents(GLOBAL_ADMIN_HTML_PATH . '/mailtemplates/forgot_password_powerpanel.html');
//                $html_message = file_get_contents(MAIN_FRONT_MEDIA_URL . 'email-templates/forgot_password_powerpanel.html');
                $html_message = str_replace("@Imagelink",$imgurl,$html_message);
                $html_message = str_replace("@Message",$message,$html_message);
                $html_message = str_replace("@Emailid",$exec['var_emailid'],$html_message);
                $html_message = str_replace("@Password", $this->configObj->glLibraryObj->decryptPass($this->rows['var_password']), $html_message);
                $html_message = str_replace("@SITE_URL_FOR_MAIL_LINKS", SITE_PATH, $html_message);
                $html_message = str_replace("@SITE_NAME_IN_WORDS", SITE_NAME, $html_message);
                $html_message = str_replace("@YEAR", date('Y'), $html_message);
//                $addarr = explode(',', $adminEmail);

                
              
                $setts = "SELECT var_sitename,var_smtpserver,var_smtpusername,var_smtpport,var_smtppassword,var_sitepath,var_emailfrom ,var_mailer,var_adminmailid FROM " . DB_PREFIX . "general_settings LIMIT 1";
                $query = mysql_query($setts);
                $result = mysql_fetch_assoc($query);

                $mail->IsSMTP(); 
                $mail->Host = $result['var_smtpserver']; //"192.168.19.12"; SMTP server mail.caymanrentalsonline.com
                $mail->SMTPAuth = true;
                //$mail->SMTPSecure = 'ssl';
                $mail->Username = $result['var_smtpusername'];
                $mail->Password = $this->configObj->glLibraryObj->decryptPass($result['var_smtppassword']);				  						   // 1 = errors and messages
                $mail->Port = $result['var_smtpport'];
               // $mail->SetLanguage('ca', 'libraries/sendmail/language/' );// 2 = messages only
                $mail->From = $result['var_adminmailid'];
                $mail->FromName = $result['var_smtpusername'];
                $mail->CharSet ="utf-8"; 
                $mail->AddReplyTo($result['var_adminmailid']);
                $mail->Subject = $subject;
                //$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
                $mail->Body = $html_message;
                $mail->IsHTML(true);

                $mail->AddAddress($adminEmail);
                if(!$mail->Send()) {
                    $mailsuccess='no';
                } else {
        	  $mailsuccess='Yes';
                }

                if ($mailsuccess != 'Yes') {
                    $this->configObj->glLibraryObj->header_redirect("index.php?module=login&action=frgtpassword&msg=3");
                } else {
                    $this->configObj->glLibraryObj->header_redirect("index.php?module=login&action=frgtpassword&msg=2");
                }
            }
            return true;
        }
        return false;
    }

    function sendmail_notification() {

        if ($this->varpostdata['h_save'] == 'T') {

            $message = mysql_real_escape_string($html_message);
            $fk_emailtype = 1;

            $insertSql = "insert into " . DB_PREFIX . "emails (fk_emailtype,var_login_username,var_from,txt_to,txt_subject,txt_body,dt_createdate,dt_modifydate,var_ipaddress) Values ('" . $fk_emailtype . "','" . $uname . "', '" . MAIL_FROM . "','" . $adminEmail . "','" . $subject . "','" . $message . "',now(),now(),'" . $_SERVER['REMOTE_ADDR'] . "') ";
            $exec = $this->configObj->glDbObj->query($insertSql);
            
            
            $sqlid = "select var_emailid1,var_emailid,chr_delete,chr_publish from " . DB_PREFIX . "users where chr_delete='N' and chr_publish='Y'";
            $exec = $this->configObj->glDbObj->get_sql_row($sqlid);
            $uname = $exec["var_emailid1"];
            $bcc = $exec["var_emailid"];
            $userid = $_REQUEST["ss_username"];
            
            $sql_ipadd="select  var_ipaddress  from ".DB_PREFIX."emails where chr_delete='N' and chr_publish='Y' and var_login_username='".$uname."'";
            $execip = $this->configObj->glDbObj->get_sql_row($sql_ipadd);
            $unameip = $execip["var_ipaddress"];
            
            
            
            if ($userid !== '') {
                $imgurl = SITE_PATH . "/" . powerpanel . "/" . GLOBAL_ADMIN_IMAGES_PATH . "email-logo.png";
                $this->configObj->setEmailConfig();
                $subject = "Password Details";
                $html_message = file_get_contents(GLOBAL_ADMIN_HTML_PATH . '/mailtemplates/email_notification.html');
                $html_message = str_replace("@SITE_URL_FOR_MAIL_LINKS", SITE_PATH, $html_message);
                $html_message = str_replace("@SITE_NAME_IN_WORDS", SITE_NAME, $html_message);
                $html_message = str_replace("@IP_ADDRESS", $unameip, $html_message);
                $html_message = str_replace("@YEAR", date('Y'), $html_message);
                $this->configObj->glMailObj->AddAddress($uname);
                $this->configObj->glMailObj->AddBcc($bcc);
                $this->configObj->glMailObj->Subject = $subject;
                $this->configObj->glMailObj->Body = $html_message;
                if (!$this->configObj->glLibraryObj->sendmail()) {
                    $message = "Error in mail send";
                    $mailsuccess = 'No';
                } else {


                    $message = "Your Mail sent Successfully. we will get you back soon.";
                    $mailsuccess = 'Yes';
                }

//                if ($mailsuccess != 'Yes') {
//                    $this->configObj->glLibraryObj->header_redirect("index.php?module=login&action=frgtpassword&msg=3");
//                } else {
//                    $this->configObj->glLibraryObj->header_redirect("index.php?module=login&action=frgtpassword&msg=2");
//                }
            }
            return true;
        }
        return false;
    }

    function logincounter($message) {
        $_SESSION['no_tries'] = $_SESSION['no_tries'] + 1;
        if ($_SESSION['no_tries'] > 5) {
            $_SESSION["pin_value"] = md5(rand(2, 99999999));
            $generated_pin = $this->configObj->glLibraryObj->generate_pin($_SESSION["pin_value"]);
            $_SESSION["cpatcha_code"] = $generated_pin;

            $path = 'html/';
            $pin_image_output = $this->configObj->glLibraryObj->show_pin_image($sessPinvalue, $generated_pin, $path);

            $captcha .= '<tr><td width="128" align="left" valign="middle" class="add-new-user-text" >&nbsp;&nbsp;' . $pin_image_output . '</td>
                                <td  width="220" align="left" valign="middle"><input  class="login-textbox" id="enqcap" name="enqcap" type="text"  />
                                <input name="pin_value_hdn" type="hidden" class="contentfont" id="pin_value_hdn" value="' . $generated_pin . '" size="20" />';
            $this->configObj->glTplObj->set('captcha', $captcha);
        }



        if ($_SESSION['no_tries'] > 10) {
            $this->sendmail_notification();
        }



        $this->configObj->glTplObj->set('message', $message);
        $this->configObj->glLibraryObj->requestRemoveCookie('tml_CookieLogin');
        $username = $_POST['ss_username'];
        $this->configObj->glTplObj->set('username', $username);
    }

    function checkServerValidation() {
        $temp = 0;
        if ($_REQUEST['ss_username'] == '') {
            $temp = 1;
        } else if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_REQUEST['ss_username'])) {
            $temp = 1;
        } else if ($_REQUEST['ss_username'] == '') {
            $temp = 1;
        }
        if ($temp == 1) {
            $message = "Incorrect Entered Code";
            $this->logincounter($message);
            $flag = 1;
        }
    }

    function userlogin() {

        $flag = 0;
        if ($this->varpostdata['h_save'] == 'T') {
            $this->checkServerValidation();
            if (!empty($this->varpostdata['enqcap'])) {

                if ($_SESSION["cpatcha_code"] != $this->varpostdata['enqcap']) {
                    $message = "Incorrect Entered Code";
                    $this->logincounter($message);
                    $flag = 1;
                }
            }
            if (empty($this->varpostdata['enqcap']) || $flag == 0) {
                $adminid = $_POST['ss_username'];
                $password = $this->configObj->glLibraryObj->cryptPass($_POST['ss_password']);

                $SQL = "SELECT u.*,ug.fk_groups,ug.int_glcode as group_id,gps.var_name as group_name FROM " . DB_PREFIX . "users u left join " . DB_PREFIX . "users_groups ug on u.int_glcode=ug.fk_users left join " . DB_PREFIX . "groups gps on gps.int_glcode=ug.fk_groups  WHERE u.var_emailid = '" . $adminid . "' AND u.var_password = '" . $password . "' AND u.chr_delete='N' and u.chr_publish = 'Y' and chr_usertype in ('N','A','S')";
                $rsCount = $this->configObj->glDbObj->get_sql_number($SQL);

                if ($rsCount > 0) {
                    $rsLogin = $this->configObj->glDbObj->query($SQL);
                    $rowLogin = $this->configObj->glDbObj->fetch_array($rsLogin);

                    $this->configObj->glSessionObj->set('adminarea', 'Active');
                    $this->configObj->glSessionObj->set('admin_fname', $rowLogin['var_fname']);
                    $this->configObj->glSessionObj->set('admin_lname', $rowLogin['var_lname']);
                    $this->configObj->glSessionObj->set('admin_email', $rowLogin['var_emailid']);
                    $this->configObj->glSessionObj->set('chr_user', $rowLogin['chr_usertype']);
                    $this->configObj->glSessionObj->set('admin_id', $rowLogin['int_glcode']);
                    $this->configObj->glSessionObj->set('admin_login', '1');
                    $this->configObj->glSessionObj->set('group_id', $rowLogin['fk_groups']);
                    $this->configObj->glSessionObj->set('group_name', $rowLogin['group_name']);
                    $this->configObj->glDbObj->admin_id = $rowLogin['int_glcode'];

                    $ip = $_SERVER['REMOTE_ADDR'];

                    $takemeto = ($_POST['gotopath'] != "") ? $_POST['gotopath'] : "index.php";
                    if (isset($_POST["chkrememberme"])) {
                        $oneyear = 365 * 24 * 3600; // one year's time.
                        $usercookie_info = array('user' => $_POST["ss_username"], 'time' => time(), 'pwd' => $_POST["ss_password"], 'takemeto' => $takemeto, 'chkrememberme' => '1');
                        $this->configObj->glLibraryObj->requestSetCookie('tml_CookieLogin', $usercookie_info, $oneyear);
                    } else {
                        $this->configObj->glLibraryObj->requestRemoveCookie('tml_CookieLogin');
                    }
                    $this->configObj->glLibraryObj->header_redirect($takemeto);
                    
                    
                } else {
                    $message = "Incorrect Username or Password..";
                    $this->logincounter($message);
                }
            }
        }
    }

}

?>
