<?php
/**
 * Login of an existing user
 *
 * The login page will allow the existing user to have the further access by
 * getting the user name and password from the user. After proper login the
 * user are redirected to the members home page.
 *
 * PHP version 5.0
 *
 * @category	###Anova###
 * @package		###Login###
 * @author 		senthil_52ag05
 * @copyright	Copyright (c) 2010 {@link http://www.agriya.com Agriya Infoway}
 * @license		http://www.agriya.com Agriya Infoway Licence
 * @version		SVN: $Id:
 * @since 		2008-12-19
 */
require_once('./common/configs/config.inc.php');
$CFG['lang']['include_files'][] = 'languages/%s/root/login.php';
if($CFG['admin']['module']['recaptcha'])
	$CFG['lang']['include_files'][] = 'recaptchalib.php';
$CFG['html']['header'] = 'general/html_header.php';
$CFG['html']['footer'] = 'general/html_footer.php';
//compulsory
$CFG['mods']['is_include_only']['html_header'] = false;
$CFG['html']['is_use_header'] = false;
$CFG['auth']['is_authenticate'] = 'root';
/**
 * To include application top file
 */
require($CFG['site']['project_path'].'common/application_top.inc.php');
if($CFG['admin']['module']['twitter'])
require_once('twitterOAuth.php');

class LoginFormHandler extends FormHandler
	{
		 /**
		  * @var	array array of user details
		  */
		 private $user_details_arr = array();
		 public $publickey;
		 public $privatekey;
		 public $error = null;
		 public $resp = null;
		 /**
		 * To check whether the browser accepts cookies
		 *
		 * @return 		boolean true/false
		 * @access 		public
		 */
		public function chkIsBrowserAcceptsCookies()
			{
				return count($_COOKIE);
			}

		/**
		 * To check the login session error
		 *
		 * @return 		boolean true/false
		 * @access 		public
		 */
		public function chkIsLoginSessionError()
			{
				return isset($_SESSION['login_error']);
			}

		/**
		 * To check the form inputs alias for clarity
		 *
		 * @return 		boolean true/false
		 * @access 		public
		 */
		public function chkIsNoFormErrors()
			{
				return $this->isValidFormInputs();
			}
		/**
		 * Gets the challenge HTML (javascript and non-javascript version).
		 * This is called from the browser, and the resulting reCAPTCHA HTML widget
		 * is embedded within the HTML form it was called from.
		 * @return string - The HTML to be embedded in the user's form.
		 */

		public function recaptcha_get_html()
			{
				return recaptcha_get_html($this->CFG['captcha']['public_key'], $this->error);
			}

		/**
		 * To check for the valid login
		 *
		 * @param 		string $table_name table name
		 * @param 		string $name name
		 * @param		string $password user password
		 * @param 		string $err_tip error message to display for form fields
		 * @return 		boolean $is_ok valid login
		 * @access 		public
		 */
		public function chkIsValidLoginDetail($table_name, $name, $password, $err_tip='')
			{
				$sql = 'SELECT '.$this->getUserTableFields(array('user_id','name', 'display_name','user_access','last_logged','email', 'time_zone', 'pref_lang', 'num_visits', 'usr_type', 'signup_type', 'expiry_date', 'last_paid_date')).
						' FROM '.$table_name.
						' WHERE '.$this->getUserTableField('name').' = '.$this->dbObj->Param($name).
						' AND password = '.$this->dbObj->Param($password).
						' AND '.$this->getUserTableField('usr_status').' = \'Ok\'';
				// condition fields value arr
				$condition_fields_value_arr = array($this->fields_arr[$name],
										  			md5($this->fields_arr[$password]));
				// prepare sql
				$stmt = $this->dbObj->Prepare($sql);
				// execute sql
				$rs = $this->dbObj->Execute($stmt, $condition_fields_value_arr);
				//raise user error... fatal
				if (!$rs)
					trigger_db_error($this->dbObj);

				if ($rs->PO_RecordCount())
					{
						$is_ok = true;
					    $this->user_details_arr = $rs->FetchRow();
					    $uid = $this->user_details_arr['user_id'];
					}
				else
					{
				     	$is_ok = false;
						$this->fields_err_tip_arr[$name] = $this->fields_err_tip_arr[$password] = $err_tip;
				    }
				return $is_ok;
			}

		public function paymentUserLog($plan_id)
			{
				if(!chkIsPaymentAllowed())
					return true;

				if($plan_id == '0')
					{
						$this->plan_details_arr = $this->CFG['payment']['default_log_array'];
						return;
					}

				$sql = ' SELECT * from '.$this->CFG['db']['tbl']['payment_plan_settings'].''.
				        ' WHERE plan_id = '.$plan_id;

				$stmt = $this->dbObj->Prepare($sql);
				// execute sql
				$rs = $this->dbObj->Execute($stmt);
				//raise user error... fatal
				if (!$rs)
					trigger_db_error($this->dbObj);
				$rs = $this->dbObj->Execute($stmt, $condition_fields_value_arr);
				//raise user error... fatal
				if (!$rs)
					trigger_db_error($this->dbObj);

				if ($rs->PO_RecordCount())
					{
						 $this->plan_details_arr = $rs->FetchRow();
					}
			}
		/**
		 * To update user log information
		 *
		 * @param 		string $table_name table name
		 * @param 		string $ip ip address
		 * @param 		string $session_id session id
		 * @return 		void
		 * @access 		public
		 */
		public function updateUserLog($table_name, $ip, $session_id)
			{
				$sql = 'UPDATE '.$table_name.
						' SET '.$this->getUserTableField('last_logged').' = NOW()'.
						', '.$this->getUserTableField('last_active').' = NOW()'.
						', '.$this->getUserTableField('is_logged_in').' = \'Yes\''.
						', '.$this->getUserTableField('num_visits').' = '.$this->getUserTableField('num_visits').'+1'.
						', '.$this->getUserTableField('ip').' = '.$this->dbObj->Param($ip).
						', '.$this->getUserTableField('session').' = '.$this->dbObj->Param($session_id).
						' WHERE '.$this->getUserTableField('user_id').' = '.$this->dbObj->Param('user_id');
				// prepare sql
				$stmt = $this->dbObj->Prepare($sql);
				// execute sql
				$result = $this->dbObj->Execute($stmt, array($ip, $session_id, $this->user_details_arr['user_id']));
				//raise user error... fatal
				if (!$result)
					trigger_db_error($this->dbObj);
			}

		/**
		 * To save the user information in session
		 *
		 * @param 		string $ip ip address
		 * @return 		void
		 * @access 		public
		 */
		public function saveUserVarsInSession($ip)
			{
				$_SESSION = array(); //reset any variables present
				$_SESSION['user']['user_id'] = $this->user_details_arr['user_id'];
				$_SESSION['user']['name'] = $this->user_details_arr['name'];
				$_SESSION['user']['display_name'] = $this->user_details_arr['display_name'];
				$_SESSION['user']['time_zone'] = $this->user_details_arr['time_zone'];
				$_SESSION['user']['pref_lang'] = $this->user_details_arr['pref_lang'];
				$_SESSION['user']['last_logged'] = $this->user_details_arr['last_logged'];
				$_SESSION['user']['num_visits'] = $this->user_details_arr['num_visits'];
				$_SESSION['user']['email'] = $this->user_details_arr['email'];
				$_SESSION['user']['usr_type'] = $this->user_details_arr['usr_type'];
				$_SESSION['user']['signup_type'] = $this->user_details_arr['signup_type'];
				$_SESSION['user']['expiry_date'] = $this->user_details_arr['expiry_date'];
				$_SESSION['user']['last_paid_date'] = $this->user_details_arr['last_paid_date'];
				$_SESSION['user']['is_logged_in'] = true;
				if ($this->user_details_arr['user_access'] == 'Admin')
					$_SESSION['user']['is_admin'] = true;
				$_SESSION['user']['useragent_hash'] = md5($_SERVER['HTTP_USER_AGENT']);
				$_SESSION['user']['ip'] = $ip;
				$_SESSION['url'] = $this->fields_arr['url'];
				$_SESSION['share_answer'] = $this->fields_arr['share_answer'];
				$_SESSION['light_url'] = $this->fields_arr['light_url'];
			}

		public function savePlanVarsInSession($ip)
			{
				if(!chkIsPaymentAllowed())
					return true;

				$_SESSION['plan']['plan_id'] = $this->plan_details_arr['plan_id'];
				$_SESSION['plan']['plan_name'] = $this->plan_details_arr['plan_name'];
				$_SESSION['plan']['plan_amount'] = $this->plan_details_arr['plan_amount'];
				$_SESSION['plan']['plan_expired'] = $this->plan_details_arr['plan_expired'];
				$_SESSION['plan']['plan_style_switching'] = $this->plan_details_arr['plan_style_switching'];
				$_SESSION['plan']['plan_total_ques'] = $this->plan_details_arr['plan_total_ques'];
				$_SESSION['plan']['plan_ques_perday'] = $this->plan_details_arr['plan_ques_perday'];
				$_SESSION['plan']['plan_total_ans'] = $this->plan_details_arr['plan_total_ans'];
				$_SESSION['plan']['plan_ans_perday'] = $this->plan_details_arr['plan_ans_perday'];
				$_SESSION['plan']['plan_viewans_perques'] = $this->plan_details_arr['plan_viewans_perques'];

				$_SESSION['plan']['plan_ans_characters'] = $this->plan_details_arr['plan_ans_characters'];
				$_SESSION['plan']['plan_rate_ques'] = $this->plan_details_arr['plan_rate_ques'];
				$_SESSION['plan']['plan_rate_ans'] = $this->plan_details_arr['plan_rate_ans'];
				$_SESSION['plan']['plan_view_bestans'] = $this->plan_details_arr['plan_view_bestans'];

				$_SESSION['plan']['plan_total_forum'] = $this->plan_details_arr['plan_total_forum'];
				$_SESSION['plan']['plan_forum_perday'] = $this->plan_details_arr['plan_forum_perday'];
				$_SESSION['plan']['plan_total_forumtopic'] = $this->plan_details_arr['plan_total_forumtopic'];
				$_SESSION['plan']['plan_total_forumresponse'] = $this->plan_details_arr['plan_total_forumresponse'];
				$_SESSION['plan']['plan_total_blog'] = $this->plan_details_arr['plan_total_blog'];
				$_SESSION['plan']['plan_blog_perday'] = $this->plan_details_arr['plan_blog_perday'];

				$_SESSION['plan']['plan_picture_post_count'] = $this->plan_details_arr['plan_picture_post_count'];
				$_SESSION['plan']['plan_video_post_count'] = $this->plan_details_arr['plan_video_post_count'];
				$_SESSION['plan']['plan_audio_post_count'] = $this->plan_details_arr['plan_audio_post_count'];
				$_SESSION['plan']['plan_video_recording_time'] = $this->plan_details_arr['plan_video_recording_time'];
				$_SESSION['plan']['plan_audio_recording_time'] = $this->plan_details_arr['plan_audio_recording_time'];
				$_SESSION['plan']['plan_display_sidebarvideo'] = $this->plan_details_arr['plan_display_sidebarvideo'];
				$_SESSION['plan']['plan_viewvideo_time'] = $this->plan_details_arr['plan_viewvideo_time'];

				$_SESSION['plan']['plan_viewaudio_time'] = $this->plan_details_arr['plan_viewaudio_time'];
				$_SESSION['plan']['plan_featured_video_count'] = $this->plan_details_arr['plan_featured_video_count'];
				$_SESSION['plan']['plan_featured_ques_count'] = $this->plan_details_arr['plan_featured_ques_count'];
				$_SESSION['plan']['plan_added_date'] = $this->plan_details_arr['plan_added_date'];
				$_SESSION['plan']['plan_status'] = $this->plan_details_arr['plan_status'];
				$_SESSION['plan']['plan_type'] = $this->plan_details_arr['plan_type'];
				$_SESSION['plan']['plan_recur_amount'] = $this->plan_details_arr['plan_recur_amount'];
				$_SESSION['plan']['plan_recur_total'] = $this->plan_details_arr['plan_recur_total'];
				$_SESSION['plan']['plan_total_used'] = $this->plan_details_arr['plan_total_used'];

			}
		/**
		 * LoginFormHandler::saveLoginCookie()
		 *
		 * @param mixed $remember
		 * @return
		 */
		public function saveLoginCookie($remember)
			{
				if(!$remember)
					return ;
				$expire = time()+60*60*24*365;
				$cookie_str = $this->fields_arr['user_name'].chr(31).base64_encode($this->fields_arr['user_password']);
				setcookie($this->CFG['cookie']['starting_text'].'_login', $cookie_str, $expire, '/');
			}

		/**
		 * To check for the valid login
		 *
		 * @param 		string $table_name table name
		 * @param 		string $name name
		 * @param		string $password user password
		 * @param 		string $err_tip error message to display for form fields
		 * @return 		boolean $is_ok valid login
		 * @access 		public
		 */
		public function readCookieLogin($table_name, $name, $password, $err_tip='')
			{
				$cookie_parts = explode(chr(31), $_COOKIE[$this->CFG['cookie']['starting_text'].'_login']);
				$Cname = $cookie_parts[0];
				$pass = base64_decode($cookie_parts[1]);
				$this->fields_arr['user_name'] = $Cname;
				$this->fields_arr['user_password'] = $pass;
				$sql = 'SELECT '.$this->getUserTableFields(array('user_id','name', 'display_name','user_access','last_logged','email', 'time_zone', 'pref_lang', 'num_visits', 'usr_type', 'signup_type', 'expiry_date', 'last_paid_date')).
						' FROM '.$table_name.
						' WHERE '.$this->getUserTableField('name').' = '.$this->dbObj->Param($Cname).
						' AND '.$this->getUserTableField('password').' = '.$this->dbObj->Param($pass).
						' AND '.$this->getUserTableField('usr_status').' = \'Ok\'';
				// condition fields value arr
				$condition_fields_value_arr = array($Cname, md5($pass));
				// prepare sql
				$stmt = $this->dbObj->Prepare($sql);
				// execute sql
				$rs = $this->dbObj->Execute($stmt, $condition_fields_value_arr);
				//raise user error... fatal
				if (!$rs)
						trigger_db_error($this->dbObj);
				if ($rs->PO_RecordCount())
					{
						$is_ok = true;
						$this->user_details_arr = $rs->FetchRow();
					}
				else
					{
						$is_ok = false;
						$this->fields_err_tip_arr[$name] = $this->fields_err_tip_arr[$password] = $err_tip;
					}
				return $is_ok;
			}

		/**
		 *
		 * @return 		void
		 * @access 		public
		 */
		public function redirectAjaxPages()
			{
				if($_SESSION['light_url'])
					{
						$_SESSION['url'] = '';
						Redirect2URL($_SESSION['light_url']);
					}
				elseif (strpos($_SESSION['url'], 'avatars'))
					{
						$_SESSION['url'] = '';
						Redirect2URL(getUrl('managesettings'));
					}
				elseif(strpos($_SESSION['url'], 'emailAnswers')
						|| strpos($_SESSION['url'], 'email-answers')
						|| strpos($_SESSION['url'], 'favoriteAnswers')
						|| strpos($_SESSION['url'], 'favoriteanswers')
						|| strpos($_SESSION['url'], 'ratingAnswer'))
					{
						$_SESSION['url'] = '';
						Redirect2URL(getUrl('questions'));
					}
				elseif(strpos($_SESSION['url'], 'audioupload')
						|| strpos($_SESSION['url'], 'audioUpload')
						|| strpos($_SESSION['url'], 'videoupload')
						|| strpos($_SESSION['url'], 'videoUpload')
						|| strpos($_SESSION['url'], 'questions_ajax')
						|| strpos($_SESSION['url'], 'externalAudioUpload')
						|| strpos($_SESSION['url'], 'externalaudioupload')
						|| strpos($_SESSION['url'], 'externalVideoUpload')
						|| strpos($_SESSION['url'], 'externalvideoupload'))
					{
						$_SESSION['url'] = '';
						Redirect2URL(getUrl('questions', '?view=ask', 'ask/'));
					}
				elseif(strpos($_SESSION['url'], 'emailBlogs')
						|| strpos($_SESSION['url'], 'email-blogs')
						|| strpos($_SESSION['url'], 'blogComment')
						|| strpos($_SESSION['url'], 'blogcomment'))
					{
						$_SESSION['url'] = '';
						Redirect2URL(getUrl('blogs'));
					}
				elseif(strpos($_SESSION['url'], 'emailForums') || strpos($_SESSION['url'], 'email-forums'))
					{
						$_SESSION['url'] = '';
						Redirect2URL(getUrl('forums'));
					}
				elseif(strpos($_SESSION['url'], 'ajax_page'))
					{
						$_SESSION['url'] = '';
						Redirect2URL(getUrl($this->CFG['auth']['members_url']['file_name']));
					}
				elseif (isset($_SESSION['url']) and $_SESSION['url'])
					{
						$_SESSION['url'] = '';
						Redirect2URL(urldecode($this->fields_arr['url']));
					}
				else
					{
						Redirect2URL(getUrl($this->CFG['auth']['members_url']['file_name']));
					}
			}

		public function chkIsValidCaptcha($field_name, $err_tip='')
			{
				$is_ok = (isset($_SESSION['signup_captcha']) and
							($_SESSION['signup_captcha']==$this->fields_arr[$field_name]));
				if (!$is_ok)
						$this->fields_err_tip_arr[$field_name] = $err_tip;
				return $is_ok;
			}


		public function chkCaptcha($field_name, $err_tip='')
			{
				if ($this->fields_arr["recaptcha_response_field"])
					{
		        		$resp = recaptcha_check_answer ($this->CFG['captcha']['private_key'],
					 					$_SERVER["REMOTE_ADDR"],
					 					$this->fields_arr["recaptcha_challenge_field"],
										$this->fields_arr["recaptcha_response_field"]);

		        		if ($resp->is_valid)
					 		{
		                			return true;
		                	}
						else
							{
							    $this->fields_err_tip_arr[$field_name] = $err_tip;
								return false;
							}
					}

			}
		public function isUserPlanExpired()
			{
				if(!chkIsPaymentAllowed())
					return true;
				//if expired set default plan as plan for this user..
				if(isset($_SESSION['user']['expiry_date']))
					{
						$exp = $_SESSION['user']['expiry_date'];
						$now = date('Y-m-d H:i:s',time());
						if($exp < $now)
							$_SESSION['user']['signup_type'] = $this->getDefaultPlan();

					}

			}
		public function getDefaultPlan()
			{
				//need to add a default plan for expired users..
				$sql = ' SELECT plan_id from '.$this->CFG['db']['tbl']['payment_plan_settings'].''.
				        ' WHERE plan_amount = \'0\' AND plan_status = \'Yes\' ORDER BY plan_id ASC';

				$stmt = $this->dbObj->Prepare($sql);
				// execute sql
				$rs = $this->dbObj->Execute($stmt);
				//raise user error... fatal
				if (!$rs)
					trigger_db_error($this->dbObj);
				$rs = $this->dbObj->Execute($stmt);
				//raise user error... fatal
				if (!$rs)
					trigger_db_error($this->dbObj);

				if ($rs->PO_RecordCount())
					{
						 $row = $rs->FetchRow();
						 //instead of  return $row['plan_id'] we need to return o to fetch default array..;
						 return '0';
					}
				//instead of  return $row['plan_id'] we need to return o to fetch default array..;
				return '0';
			}
	}
//<<<<<-------------- Class LoginFormHandler begins ---------------//
//-------------------- Code begins -------------->>>>>//
$request_link = '';
if($CFG['admin']['module']['twitter'])
{
	//session_start();
	unset($_SESSION['oauth_request_token']);
	unset($_SESSION['oauth_request_token_secret']);
	unset($_SESSION['oauth_state']);
	unset($_SESSION['oauth_access_token']);
	unset($_SESSION['oauth_access_token_secret']);
	unset($_SESSION['image_url']);
	unset($_SESSION['disp_name']);
	unset($_SESSION['uname']);
	$consumer_key = $CFG['twitter']['consumer_key'];
	/* Consumer Secret from twitter */
	$consumer_secret = $CFG['twitter']['consumer_secret'];
	/* Set up placeholder */
	$content = NULL;
	/* Set state if previous session */
	$state = isset($_REQUEST['oauth_state'])?$_REQUEST['oauth_state']:'';
	/* Checks if oauth_token is set from returning from twitter */
	$session_token = isset($_REQUEST['oauth_request_token'])?$_REQUEST['oauth_request_token']:'';
	/* Checks if oauth_token is set from returning from twitter */
	$oauth_token = isset($_REQUEST['oauth_token'])?$_REQUEST['oauth_token']:'';
	/* Set section var */
	$section = isset($_REQUEST['section'])?$_REQUEST['section']:'';
	/* If oauth_token is missing get it */
	if ((isset($_REQUEST['oauth_token']) and $_REQUEST['oauth_token'] != NULL) && (isset($_SESSION['oauth_state']) and $_SESSION['oauth_state'] === 'start'))
	{/*{{{*/
	  $_REQUEST['oauth_token'] = '';
	  $_SESSION['oauth_state'] = '';
	  $_SESSION['oauth_state'] = $state = 'returned';
	}/*}}}*/

	/*
	 * Switch based on where in the process you are
	 *
	 * 'default': Get a request token from twitter for new user
	 * 'returned': The user has authorize the app on twitter
	 */
	switch ($state) {/*{{{*/
	  default:

		/* Create TwitterOAuth object with app key/secret */
	    $to = new TwitterOAuth($consumer_key, $consumer_secret);
	    /* Request tokens from twitter */
	    $tok = $to->getRequestToken();

	    /* Save tokens for later */
	    $_SESSION['oauth_request_token'] = $token = $tok['oauth_token'];
	    $_SESSION['oauth_request_token_secret'] = $tok['oauth_token_secret'];
	    $_SESSION['oauth_state'] = "start";

	    /* Build the authorization URL */
	    $request_link = $to->getAuthenticateUrl($token);

	    /* Build link that gets user to twitter to authorize the app */
	     $content = '<br /><a href="'.$request_link.'">'.$request_link.'</a>';
	    break;
	  case 'returned':

	    /* Create TwitterOAuth object with app key/secret */
	    $to = new TwitterOAuth($consumer_key, $consumer_secret);
	    /* Request tokens from twitter */
	    $tok = $to->getRequestToken();

	    /* Save tokens for later */
	    $_SESSION['oauth_request_token'] = $token = $tok['oauth_token'];
	    $_SESSION['oauth_request_token_secret'] = $tok['oauth_token_secret'];
	    $_SESSION['oauth_state'] = "start";

	    /* Build the authorization URL */
	    $request_link = $to->getAuthenticateUrl($token);

	    /* Build link that gets user to twitter to authorize the app */
	     $content = '<br /><a href="'.$request_link.'">'.$request_link.'</a>';
		 break;
	}/*}}}*/
}

$loginfrm = new LoginFormHandler();
$loginfrm->setPageBlockNames(array('form_login'));
//default form fields and values...
$loginfrm->setFormField('user_name', '');
$loginfrm->setFormField('user_password', '');
//For sidebar block
$loginfrm->setFormField('username', '');
$loginfrm->setFormField('userpassword', '');
$loginfrm->setFormField('remember', '');
$loginfrm->setFormField('rem', '');
$loginfrm->setFormField('url', (isset($_SESSION['url']) ? $_SESSION['url'] : ''));
$loginfrm->setFormField('share_answer', (isset($_SESSION['share_answer']) ? $_SESSION['share_answer'] : ''));
$loginfrm->setFormField('current_url', (isset($_SESSION['current_url']) ? $_SESSION['current_url'] : ''));
$loginfrm->setFormField('light_url', (isset($_SESSION['light_url']) ? $_SESSION['light_url'] : ''));
$loginfrm->setFormField('msg', '');
$loginfrm->setFormField('captcha', '');
$loginfrm->setFormField('recaptcha_challenge_field', '');
$loginfrm->setFormField('recaptcha_response_field', '');
$loginfrm->setFormField('opt', '');
// Default page block
$loginfrm->setAllPageBlocksHide();

$smartyObj->assign('twitter_login', '<a href="' . $request_link . '">'.$LANG['login_twitter'].'</a>');
$loginfrm->setPageBlockShow('form_login');
$loginfrm->sanitizeFormInputs($_REQUEST);
if($loginfrm->isFormGETed($_GET, 'msg'))
	{
		if($loginfrm->getFormField('msg') == $LANG['user_status_blocked'])
			$loginfrm->setCommonErrorMsg($LANG['user_status_blocked']);
		else
			$loginfrm->setCommonErrorMsg($LANG['invalid']);
		$loginfrm->setPageBlockShow('block_msg_form_error');
	}
if($loginfrm->isFormGETed($_GET, 'opt'))
	{
		if($loginfrm->chkIsAllowedModule(array('twitter')))
			Redirect2URL($request_link);
		else
			Redirect2URL($loginfrm->getUrl('login'));
	}
if (isset($_COOKIE[$CFG['cookie']['starting_text'].'_login']))
	{
		$loginfrm->readCookieLogin($CFG['db']['tbl']['users'], 'user_name', 'user_password', $LANG['login_err_tip_invalid']) or
		$loginfrm->setCommonErrorMsg($LANG['login_err_invalid_login']);
		if ($loginfrm->isValidFormInputs())
			{
				$loginfrm->updateUserLog($CFG['db']['tbl']['users'], $CFG['remote_client']['ip'], session_id());
				$loginfrm->saveUserVarsInSession($CFG['remote_client']['ip']);
				$loginfrm->isUserPlanExpired();
				$loginfrm->paymentUserLog($_SESSION['user']['signup_type']);
				$loginfrm->savePlanVarsInSession($CFG['remote_client']['ip']);
				if ($current_url = $loginfrm->getFormField('current_url'))
					Redirect2URL($current_url);
				$loginfrm->redirectAjaxPages();
			}
		else //error in form inputs
			{
				$loginfrm->setFormField('user_password', ''); //reset
				$loginfrm->setAllPageBlocksHide();
				$loginfrm->setPageBlockShow('block_msg_form_error');
				$loginfrm->setCommonErrorMsg($LANG['common_msg_error_sorry']);
				$loginfrm->setPageBlockShow('form_login');
			}
	}
else if ($loginfrm->isFormPOSTed($_POST, 'login_submit'))
	{
		if($loginfrm->getFormField('username') || $loginfrm->getFormField('userpassword'))
			{
				$loginfrm->setFormField('user_name', $loginfrm->getFormField('username'));
				$loginfrm->setFormField('user_password', $loginfrm->getFormField('userpassword'));
			}
		$loginfrm->chkIsNotEmpty('user_name', $LANG['err_tip_compulsory']) or $loginfrm->setCommonErrorMsg($LANG['common_msg_error_sorry']);
		$loginfrm->chkIsNotEmpty('user_password', $LANG['err_tip_compulsory']) or $loginfrm->setCommonErrorMsg($LANG['common_msg_error_sorry']);
		$loginfrm->chkIsBrowserAcceptsCookies() or $loginfrm->setCommonErrorMsg($LANG['login_err_cookies_not_set']);
		//no errors yet? if so, do a DB lookup for PIK..
		$loginfrm->chkIsNoFormErrors() and
				($loginfrm->chkIsValidLoginDetail($CFG['db']['tbl']['users'], 'user_name', 'user_password', $LANG['login_err_tip_invalid'])
					or
				$loginfrm->setCommonErrorMsg($LANG['login_err_invalid_login']));

		if($CFG['login']['captcha'])
			{
				if($CFG['admin']['module']['recaptcha'])
					{
						if($CFG['login']['re_captcha'] and $CFG['captcha']['public_key'] and $CFG['captcha']['private_key'])
							{
								$loginfrm->chkIsNotEmpty('recaptcha_response_field', $LANG['err_tip_compulsory']) and
								$loginfrm->chkCaptcha('recaptcha_response_field', $LANG['login_err_tip_invalid_captcha']);
							}
					}
				else
					{
						$loginfrm->chkIsNotEmpty('captcha', $LANG['err_tip_compulsory']) and
						$loginfrm->chkIsValidCaptcha('captcha', $LANG['login_err_tip_invalid_captcha']);
					}
			}

		//Important: shouldn't re-show password according to web standards...
		if ($loginfrm->isValidFormInputs())
			{
				$loginfrm->updateUserLog($CFG['db']['tbl']['users'], $CFG['remote_client']['ip'], session_id());
				$loginfrm->saveUserVarsInSession($CFG['remote_client']['ip']);
				$loginfrm->isUserPlanExpired();
				$loginfrm->paymentUserLog($_SESSION['user']['signup_type']);
				$loginfrm->savePlanVarsInSession($CFG['remote_client']['ip']);
				$loginfrm->saveLoginCookie($loginfrm->getFormField('remember'));
				$loginfrm->redirectAjaxPages();
			}
		else //error in form inputs
			{
				$loginfrm->setFormField('user_password', ''); //reset
				$loginfrm->setAllPageBlocksHide();
				$loginfrm->setPageBlockShow('block_msg_form_error');
				$loginfrm->setCommonErrorMsg($LANG['common_msg_error_sorry']);
				$loginfrm->setPageBlockShow('form_login');
			}
	}
elseif ($loginfrm->chkIsLoginSessionError())
	{
	    $loginfrm->setCommonErrorMsg($LANG[$_SESSION['login_error']]);
		//now unset session...
		unset($_SESSION['login_error']);
		$loginfrm->setPageBlockShow('block_msg_form_error');
	}
elseif ($loginfrm->isFormGETed($_GET, 'inv'))
	{
		$loginfrm->setCommonErrorMsg($LANG['plan_changeby_admin']);
		$loginfrm->setPageBlockShow('block_msg_form_error');
	}
if($loginfrm->isFormGETed($_GET, 'msg'))
	{
		$loginfrm->setAllPageBlocksHide();
		$loginfrm->setCommonErrorMsg($LANG['user_status_blocked']);
		$loginfrm->setPageBlockShow('block_msg_form_error');
		$loginfrm->setPageBlockShow('form_login');
	}
//--------------------Page block templates begins-------------------->>>>>//
if (isAjaxPage())
	{
		//include the header file
		$loginfrm->includeAjaxHeader();
		$smartyObj->assign('tabindex', 900);
	}
else
	{
		//include the header file
		$loginfrm->includeHeader();
	}
//include the content of the page
setTemplateFolder('root/');
$smartyObj->display('login.tpl');
//<<<<<<--------------------Page block templates Ends--------------------//
?>
<script type="text/javascript">
	needLiveValidation('user_name',Array('Presence'));
	needLiveValidation('user_password',Array('Presence'));
	<?php
	if($CFG['login']['captcha'])
		{
			if($CFG['admin']['module']['recaptcha'])
				{
					if($CFG['login']['re_captcha'] and $CFG['captcha']['public_key'] and $CFG['captcha']['private_key'])
						{
						?>
						//needLiveValidation('recaptcha_response_field',Array('Presence'));
						<?php
						}
				}
			else
				{
				?>
				var img_count=1;
				function changeCaptchaImage(){
					document.getElementById('captchaImage').src = '<?php echo $CFG['site']['url'];?>captchaSignup.php?img_count='+img_count;
					document.getElementById('captcha').value = '';
					img_count++;
					return false;
				}
				needLiveValidation('captcha',Array('Presence'));
				<?php
				}
		}
?>
</script>
<?php
if (isAjaxPage())
	{
		//include the header file
		$loginfrm->includeAjaxFooter();
	}
else
	{
		//includd the footer of the page
		$loginfrm->includeFooter();
	}
?>