<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/ //
//$Id: AdminuserModel.php, v 1.0 2013/03/14 14:14:14
class AdminuserModel extends Model {
    //Function to get admin details
    function getAdminDetails($adminUserID = '', $adminUserEmail = '', $adminUserLoginName = '', $adminUserLoginPass = '', $status = '') {
        $sql = "
			SELECT 
				* 
			FROM 
					" . DB_PREFIX . "admin_users  AS admUse
				LEFT JOIN
					(
					SELECT 
						resRol.roleID, 
						userID 
					FROM 
							" . DB_PREFIX . "rest_role AS resRol 
						INNER JOIN 
							" . DB_PREFIX . "rest_consumer AS resCon 
								ON 	(
									resRol.roleID =resCon.roleID 
									AND 
									userType='admin' 
								)
				) AS rest
					ON 	(
						rest.userID = admUse.adminUserID 
					)
			WHERE 
				1 ";
        if ($adminUserEmail) {
            $sql .= " 
				AND 
				`adminUserEmail`='" . $this->escape($adminUserEmail) . "' ";
        }
        if ($adminUserID) {
            $sql .= "
				AND `adminUserID`='" . $adminUserID . "' ";
        }
        if ($adminUserLoginName) {
            $sql .= " 
				AND `adminUserLoginName`='" . $this->escape($adminUserLoginName) . "' ";
        }
        if ($status) {
            $sql .= " 
				AND `adminUserStatus`='" . $status . "' ";
        }
        $sql .= " AND adminUserStatus<>'Deleted'";
        $result = $this->ObjDatabase->readValue($sql);
        if ($result) {
            $sql                      = "
			SELECT 
				userTypeStatus,
				userTypeName
			FROM 
				" . DB_PREFIX . "admin_user_type   
			WHERE 
				userTypeID='" . $result['userTypeID'] . "'";
            $result1                  = $this->ObjDatabase->readValue($sql);
            $result['userTypeStatus'] = $result1['userTypeStatus'];
            $result['userTypeName']   = $result1['userTypeName'];
        }
        return $result;
    }
    //End of function
    //Function to list admin roles
    function ListAdminRoles($excludetype = '') {
        $sql = "
		SELECT 
			* 
		FROM  
			" . DB_PREFIX . "admin_user_type 
		WHERE 
			`userTypeStatus`<>'Deleted'";
        if ($excludetype > 0)
            $sql .= " AND userTypeID!='" . $excludetype . "'";
        $sql .= " ORDER BY userTypeName ASC";
        $result = $this->ObjDatabase->readValues($sql);
        return $result;
    }
    //End of function
    //Function to save admin deatils
    function saveAdminDetails($adminUserID = '') {
        if (!$adminUserID) {
            $sql = "
			INSERT INTO 
				" . DB_PREFIX . "admin_users(
						adminUserFirstName,
						adminUserLastName,
						adminUserEmail,
						adminUserLoginName,
						adminUserLoginPass,
						adminUserStatus,
						adminUserCreatedDate,
						userTypeID
					)VALUES(
						'" . $this->escape($_POST['adminUserFirstName']) . "',
						'" . $this->escape($_POST['adminUserLastName']) . "',
						'" . $this->escape($_POST['adminUserEmail']) . "',
						'" . $this->escape($_POST['adminUserLoginName']) . "',
						'" . $this->generateHash(trim($_POST['adminUserConfirmPass'])) . "',
						'" . $_POST['adminUserStatus'] . "',
						NOW(),
						'" . $_POST['adminRole'] . "'
					)";
            return $this->ObjDatabase->setQuery($sql);
        }
        if ($adminUserID) {
            $sql = "
			UPDATE 
				" . DB_PREFIX . "admin_users    
			SET 
				adminUserFirstName='" . $this->escape($_POST['adminUserFirstName']) . "',
				adminUserLastName='" . $this->escape($_POST['adminUserLastName']) . "',
				adminUserEmail='" . $this->escape($_POST['adminUserEmail']) . "' ";
            if (trim($_POST['adminUserConfirmPass']) != '') {
                $sql .= " ,adminUserLoginPass='" . $this->generateHash(trim($_POST['adminUserConfirmPass'])) . "' ";
            }
            $sql .= " ,adminUserStatus='" . $this->escape($_POST['adminUserStatus']) . "',
							 userTypeID='" . $this->escape($_POST['adminRole']) . "' 
			WHERE `adminUserID`='" . $adminUserID . "'";
            return $this->ObjDatabase->setQuery($sql);
        }
    }
    //Function to List administrators
    function listAdmin($limitFrom = 0, $limitTo = "", $sortOrder = "ASC", $status = "") {
        $sql = " 
			SELECT ";
        //IF PAGINATION REQUIRED
        if ($limitTo)
            $sql .= " 
				SQL_CALC_FOUND_ROWS ";
        $sql .= " 
				admUsr.*,
				admUsrTyp.userTypeName";
        $sql .= " 
			FROM  
				" . DB_PREFIX . "admin_users admUsr,
				" . DB_PREFIX . "admin_user_type admUsrTyp ";
        $sql .= " 
			WHERE 
				admUsr.adminUserStatus!='Deleted' 
				AND admUsr.userTypeID=admUsrTyp.userTypeID";
        if ($status)
            $sql .= " 
				AND admUsr.adminUserStatus='" . $status . "'";
        $sql .= " 
			GROUP BY
				admUsr.adminUserID  
			ORDER BY
				admUsr.adminUserFirstName  " . $sortOrder . " ";
        //IF PAGINATION REQUIRED
        if ($limitTo) {
            $sql .= " LIMIT  " . $limitFrom . "," . $limitTo . "";
        }
        $result = $this->ObjDatabase->readValues($sql);
        return $result;
    }
    //End of function
    //Function to change admin status
    function changeAdminStatus($adminUserStatus, $adminUserBulkStatusArray, $deleteprivilage = '') {
        if (is_array($adminUserBulkStatusArray)) {
            $adminUserBulkStatus = implode(',', $adminUserBulkStatusArray);
        } else {
            $adminUserBulkStatus = $adminUserBulkStatusArray;
        }
        if ($adminUserStatus == 'Deleted' && !$deleteprivilage)
            $adminUserStatus = 'Active';
        $result = $this->ObjDatabase->setQuery("
		UPDATE 
			" . DB_PREFIX . "admin_users 
		SET 
			adminUserStatus ='" . $adminUserStatus . "' 
		WHERE 
			adminUserID IN(" . $adminUserBulkStatus . ")");
        return TRUE;
    }
    //End of function
    //Function to save login detils
    function saveLoginDetails($adminUserID) {
        $sql = "
		UPDATE 
			" . DB_PREFIX . "admin_users 
		SET 
			adminUserLastAccessDate=NOW(),
			adminUserAccessCount=adminUserAccessCount+1,
			adminUserInvalidAccessCount='0' 
		WHERE 
			adminUserID='" . $adminUserID . "'";
        return $this->ObjDatabase->setQuery($sql);
    }
    //End of function
    //Function to save invalid access count
    function saveInvalidAccessCount($adminUserLoginName, $blockingAttemps) {
        $resAdminDetails = $this->getAdminDetails('', '', $adminUserLoginName);
        $sql             = "
		UPDATE 
			" . DB_PREFIX . "admin_users 
		SET 
			adminUserInvalidAccessCount=adminUserInvalidAccessCount+1 
		WHERE 
			adminUserID='" . $resAdminDetails['adminUserID'] . "'";
        $result          = $this->ObjDatabase->setQuery($sql);
        if ($result) {
            if (($resAdminDetails['adminUserInvalidAccessCount'] + 1) >= $blockingAttemps) {
                $sql    = "
				UPDATE 
					" . DB_PREFIX . "admin_users 
				SET 
					adminUserStatus='Blocked' 
				WHERE 
					adminUserID='" . $resAdminDetails['adminUserID'] . "' 
					AND  adminUserStatus!='Deleted' ";
                $result = $this->ObjDatabase->setQuery($sql);
            }
        }
        return $resAdminDetails['adminUserInvalidAccessCount'] + 1;
    }
    //End of function
    //Function to activate user account
    function activateUserAccount($adminUserLoginName) {
        $sql    = "
		UPDATE 
			" . DB_PREFIX . "admin_users 
		SET 
			adminUserInvalidAccessCount='0',
			adminUserLockedDate='',
			adminUserStatus='Active' 
		WHERE 
			adminUserLoginName='" . $adminUserLoginName . "' 
			AND adminUserStatus!='Deleted' ";
        $result = $this->ObjDatabase->setQuery($sql);
        return $result;
    }
    //End of function
    //captcha generate
    function CaptchaSecurityImages($ObjSession, $width, $height, $characters = '6', $style) {
        $ObjImage  = new ImageModel();
        $code      = $ObjImage->generateCode($ObjSession, $characters);
        /* font size will be 75% of the image height */
        $font_size = $height * 0.70;
        switch ($style) {
            case 'style 1':
                /// black////
                $font_size = $height * 0.52;
                $image = @imagecreate($width + 9, $height) or die('Cannot initialize new GD image stream');
                $font             = __DIR_PUBLIC . '/font/Kids.ttf';
                $background_color = imagecolorallocate($image, 0, 0, 0);
                $text_color       = imagecolorallocate($image, 255, 255, 255);
                $noise_color      = imagecolorallocate($image, 0, 0, 0);
                break;
            case 'style 2':
                //// blue///	
                $font_size = $height * 0.50;
                $image = @imagecreate($width + 9, $height) or die('Cannot initialize new GD image stream');
                $font             = __DIR_PUBLIC . '/font/Almagro Regular.ttf';
                $background_color = imagecolorallocate($image, 255, 255, 255);
                $text_color       = imagecolorallocate($image, 0, 0, 220);
                $noise_color      = imagecolorallocate($image, 192, 192, 192);
                break;
            case 'style 3':
                /// grey////
                $image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream');
                $font             = __DIR_PUBLIC . '/font/monofont.ttf';
                $background_color = imagecolorallocate($image, 240, 240, 240);
                $text_color       = imagecolorallocate($image, 171, 171, 171);
                $noise_color      = imagecolorallocate($image, 240, 240, 240);
                break;
            case 'style 4':
                $font_size = $height * 0.50;
                $image = @imagecreate($width + 9, $height) or die('Cannot initialize new GD image stream');
                $font             = __DIR_PUBLIC . '/font/Verdana.TTF';
                $background_color = imagecolorallocate($image, 0, 200, 0);
                $text_color       = imagecolorallocate($image, 252, 255, 255);
                $noise_color      = imagecolorallocate($image, 0, 200, 0);
                break;
        }
        /* set the colours */
        /* generate random dots in background */
        for ($i = 0; $i < ($width * $height) / 3; $i++) {
            imagefilledellipse($image, mt_rand(0, $width), mt_rand(0, $height), 1, 1, $noise_color);
        }
        /* generate random lines in background */
        for ($i = 0; $i < ($width * $height) / 150; $i++) {
            imageline($image, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $noise_color);
        }
        /* create textbox and add text */
        $textbox = imagettfbbox($font_size, 0, $font, $code) or die('Error in imagettfbbox function');
        $x = ($width - $textbox[4]) / 2;
        $y = ($height - $textbox[5]) / 2;
        imagettftext($image, $font_size, 0, $x, $y, $text_color, $font, $code) or die('Error in imagettftext function');
        /* output captcha image to browser */
        header('Content-Type: image/jpeg');
        imagejpeg($image);
        imagedestroy($image);
        $ObjSession->setSession("ses_code", $code);
        $ObjSession->setSession("IMAGE_CAPTCHA_CODE", $code);
        return $code;
    }
    public function checkAdminUser($adminUserID = 0, $adminUserTypeID = 0) {
        if ($adminUserID > 1) {
            $sql = "	
						SELECT 
							adminUserID 
						FROM 
							" . DB_PREFIX . "admin_users admUsr
						WHERE
							admUsr.adminUserID='" . $adminUserID . "'
							AND admUsr.adminUserStatus = 'Active'";
            if ($adminUserTypeID > 1) {
                $sql .= "
							AND admUsr.userTypeID IN
							(
								SELECT
									userTypeID
								FROM
									" . DB_PREFIX . "admin_user_type
								WHERE
									userTypeID = admUsr.userTypeID
									AND userTypeStatus = 'Active'
							)";
            }
            $resultUser = $this->ObjDatabase->readValue($sql);
            if ($resultUser['adminUserID'] > 0)
                return true;
        } elseif ($adminUserID == 1)
            return true;
        return false;
    }
    //Get User Type Name
    public function getAdminUserTypeName($userTypeID) {
        $sql    = "
			SELECT 
				userTypeName
			FROM 
				" . DB_PREFIX . "admin_user_type   
			WHERE 
				userTypeID='" . $userTypeID . "'";
        $result = $this->ObjDatabase->readValue($sql);
        return $result['userTypeName'];
    }
    //END OF FUNCTION
    //TO	CHANGE	PASSWORD
    public function ChangeAdminuserPassword($emailID = '') {
        $ObjUser     = new UserModel();
        $newPassword = $ObjUser->generatePassword(10);
        $sql         = $this->ObjDatabase->setQuery("	UPDATE	
														" . DB_PREFIX . "admin_users	
													SET		
														adminUserLoginPass='" . $this->generateHash($newPassword) . "'
													WHERE	
														adminUserEmail='" . $emailID . "'");
        return $newPassword;
    }
    //Get admin details for forgotpassword
    public function getAdminDetailsForgotPwd($adminUserEmail = '') {
        if ($adminUserEmail != '') {
            $sql = "
				SELECT 
					adminUserStatus,
					adminUserLockedDate,
					adminUserLoginName	
				FROM 
					" . DB_PREFIX . "admin_users
				WHERE 
					adminUserEmail ='" . $this->escape($adminUserEmail) . "'
				LIMIT 1";
            return $this->ObjDatabase->readValue($sql);
        }
        return false;
    }
    function verifyPassword($password, $hashedPassword) {
        return crypt($password, $hashedPassword) == $hashedPassword;
    }
	public function getLoginAttemptsInfo($ipAddress,$type='') {
		
		$type = ($type=='')?'L':$type;
		$sql = "SELECT COUNT(*) AS attemptCount, 
									  MIN(attemptTime) AS firstAttemptTime 
							   FROM " . DB_PREFIX . "admin_login_attempts 
							   WHERE ipAddress = '".$this->escape($ipAddress)."'
							   AND attemptTime > (NOW() - INTERVAL 15 MINUTE)";
		if($type!='') {
			$sql  .= " and actionType = '".$this->escape($type)."'";
		}			
		$res = $this->ObjDatabase->readValue($sql);
		return $res;
	}
	public function recordLoginAttempt($ipAddress,$type='') {
		$type = ($type=='')?'L':$type;
		$sql = "INSERT INTO " . DB_PREFIX . "admin_login_attempts (ipAddress,actionType) VALUES ('".$this->escape($ipAddress)."','".$this->escape($type)."')";
		$res = $this->ObjDatabase->setQuery($sql);
		return $res;
	}
	 public function clearOldAttempts($type='',$cron='',$ipAddress='') {
		// $type = ($type=='')?'L':$type;
		$sql = "DELETE FROM " . DB_PREFIX . "admin_login_attempts WHERE ";
		if($cron!='') {
			$sql  .= " attemptTime < (NOW() - INTERVAL 1 DAY)";
		} else {
			$sql  .= " attemptTime < NOW()";
		}
		if($ipAddress!='') {
			$sql  .= " and ipAddress = '".$this->escape($ipAddress)."'";
		}	
		if($type!='') {
			$sql  .= " and actionType = '".$this->escape($type)."'";
		}	
		$res = $this->ObjDatabase->setQuery($sql);
		return $res;
	}
	

}