<?
    class UserRegistrationClass
    {
        public $useremail;
		public $userfirstname;
		public $userid;
		public $userlastname;
		public $usermobilecountrycode;
		public $usermobileno;
		public $usermobileverified;
		public $username;
		public $userpassword;
		public $userphotocount;
		public $userpostcount;
	    public $userprofiephotopath;
		public $userprofileviews;
		public $userregistereddate;
		public $userregisteredip;
		public $userreplycount;
		public $usersalutation;
		public $usersex;
		public $userstate;
		public $usertelno;
		public $usertype;
		public $userverified;
		public $dateofbirth;
		public $designation;
		public $facebookurl;
		public $invitationcode;
		public $invtationcodegenerationdate;
		public $isUserLoggedIn;
		public $isemailotpverify;
		public $ismobileotpverify;
		public $lastloginIP;
		public $lastlogindatetime;
		public $lastlogindevice;
		public $lastusertoken;
		public $linkedinurl;
		public $loggedoutdatetime;
		public $oauth_provider;
		public $oauth_uid;
		public $occupation;
		public $otpforverifyemail;
		public $otpforverifymobile;
		public $receivediscountoffers;
		public $receiveselloffers;
		public $status;
		public $twitter_oauth_token_secret;
		public $twitterurl;
		public $useraboutme;
		public $usercitycode;
		public $usercityname;
		public $usercountry;
		public $usercountrycode;
		public $userdeleted;
		public $userdeleteddate;
		public $CreatedByName;
		public $CreatedDateTime;
		public $UpdatedDateByName;
		public $UpdatedDateTime;
		public $usercookietoken;   
		public $extra1;
		public $extra2;
		public $extra3;
		public $extra4;
		public $display_name;
		public $magzinesname;
		public $PackageType;
		public $noofmagzinesread;
		public $user_cookieuserid;
		public $user_cookietoken;
		public $provider_name; // social media login provider name
        public $social_token; // token from social media to re-login
	    public $user_gmailpictureUrls; 
  		public $user_fbpictureUrls; 
  		public $user_profileURL;
        
		var $obj1;
		var $con;
		// constructor
		function __construct()
		{
			//$this->obj1 = new dbopenconn();
			//$this->con = $this->obj1-> dbconnect();
			$this->obj1 = new dboperations();
			$this->con = $this->obj1-> dbconnect();
		}
		
		function getUserInfo($userid="",$fields="*",$sql="",$username='')
		{
			if ($userid!="")
			{
				$sqltext = "Select $fields from ".USER_TABLE." where userid='".$userid."' ";
			}
			elseif ($username!="")
			{
				$sqltext = "Select $fields from ".USER_TABLE." where username='".$username."' ";
			   // echo $sqltext; 
			}
			else if ($sql!="")
			{
				$sqltext = $sql;
			}
			else
			{
				$sqltext = "Select $fields from ".USER_TABLE."";
			}
			
			//echo $sqltext;
            $users = $this->obj1->select_query($sqltext);
			if ($users)
			{
				$numrows = $this->obj1->numRows($users);
			    if ($numrows ==1)
			    {
				    while ($userslist = mysqli_fetch_assoc($users))
				    {
					    $userstr[] = $userslist;
				    }   
			    }
			    else
			    {
				    while ($userslist = mysqli_fetch_assoc($users))
				    {
					    $userstr[] = $userslist;
				    }
			    }
			}    
			return $userstr;
		}
		
		function EditUser($usersdata,$wherecondition,$table="mstusers")
		{
			if (is_array($usersdata)== false)
			{
				return false;
			}
			else
			{
				$fieldnamesvalues =  "set ";
				foreach ($usersdata as $k => $v) 
				{
					$fieldnamesvalues .=  ($fieldnamesvalues =="set ")?"$k='$v'":",$k='$v'";
				}
				$sqltext = "update $table ".$fieldnamesvalues." where ".$wherecondition ;
			    // echo $sqltext;
			//	die();
				$users = $this->obj1->update_query($sqltext);
				return ($users == 1)?"true":"false";
			}
		}
		
		// this function will be called to validate login everytime
		function ValidateLogin()
		{
			$returnvalue = "0";
			// first check if user already exists with username
			$username = $this->username;
			//$sqltext = "Select $fields from ".USER_TABLE." where username='".$username."' and isemailotpverify = 1";
			//$userdata = $this->getUserInfo('','*',$sqltext);
			
			$userdata = $this->getUserInfo('','*','',$username);
			$usercount = 0;
			if ($userdata)
			{
			    $usercount = count($userdata);
			}
			if ($usercount > 0 ) // user already exists
			{	
			    if($this->provider_name!='')
				{
					$provider_name_datafield = $this->provider_name.'_token';
					$provider_name_arrayfield = $this->provider_name."_token";
					
					// existing user logged in with social provider
					// update token
					$userid = $userdata[0]['userid'];
					$wherecondition =   " userid = $userid ";
					
					// $wherecondition = array('userid'=> $userdata[0]['userid']);
					$applicationdata[$provider_name_arrayfield]= $this->social_token;
					$applicationdata['userprofiephotopath'] = $this->user_pictureUrls;
					$applicationdata['isemailotpverify'] = '1';
					// check below fields in database -- by rajiv - 11th nov 2020
					//$applicationdata['fbuserprofilephoto'] = $this->user_fbpictureUrls;
					//$applicationdata['gmailuserprofilephoto'] = $this->user_gmailpictureUrls;		
					// end of checking - 
					
					// set site cookie and update in mstuser table and also put cookie					
					$retval = $this->EditUser($applicationdata,$wherecondition);
					//echo 'retval '.$retval;
					if ($retval==true) 
					{
						// user is edited successfully
						//debug_to_console('user edited successfully');
						//$username = $this->username;		
						$userdataUpdated = $this->getUserInfo($userid);
						//print_r($userdataUpdated);
						//exit();
						// added by rajiv to check if social login works with all options
						if($userdataUpdated[0]['usertype'] == '0')
			            {
			                $noofmagzinesread   =   $userdataUpdated[0]['noofmagzinesread'];
			                $packagevalues  =   explode('||',$this->checkPackageValue($userid));
    			            $userdataUpdated[0]['magzinesname']    =   $packagevalues[0];
					        $userdataUpdated[0]['PackageType']     =   $packagevalues[1];
					        $userdataUpdated[0]['UserPackageStatus']     =   $packagevalues[2];
			            }
			            else
			            {
    			            $packagevalues  =   explode('||',$this->checkPackageValue($userid));
    			            $userdataUpdated[0]['magzinesname']    =   $packagevalues[0];
					        $userdataUpdated[0]['PackageType']     =   $packagevalues[1];
					        $userdataUpdated[0]['UserPackageStatus']     =   $packagevalues[2];
                        }
						$retval = $this->updateUserValues($userdataUpdated);
						setCookieLogin($userdataUpdated[0]['userid']);
					    return $userid;
					}
					else
					{
						//debug_to_console($retval);						
						return $returnvalue;
					}							
				}
			    elseif($userdata[0]['isemailotpverify'] == '1')
			    {
			        $cur_date           =   date("Y-m-d");
    	            $userid             =   $userdata[0]['userid'];
			        if($userdata[0]['usertype'] == '0')
			        {
			            $noofmagzinesread   =   $userdata[0]['noofmagzinesread'];
			        }
			        else
			        {
    			        $packagevalues  =   explode('||',$this->checkPackageValue($userid));
    			        $userdata[0]['magzinesname']    =   $packagevalues[0];
					    $userdata[0]['PackageType']     =   $packagevalues[1];
					    $userdata[0]['UserPackageStatus']     =   $packagevalues[2];
                    }
				    $applicationdata = $this->updateUserValuesForDataBase();
				    $applicationdata['lastlogindatetime']=date("Y-m-d H:i:s");
				    $applicationdata['lastloginIP'] = $this->get_user_ip(); 
				    $applicationdata['lastlogindevice']='0'; // use class user_device_info class to store user device info details	
			        // add set cookie login here as well
			        // setCookieLogin($userdata[0]['userid']);
			    
			        if(($this->username!='')&&($this->userpassword!='')&&($this->userfirstName!=''))
				    {
					throw new customException("User Already Exists");
					return $returnvalue;				
				}				
				else if (($this->username!='')&&($this->userpassword!=''))
				{
				    if ($userdata[0]['userid']!="")
					{
						//$userpasswordtotest = md5($this->userpassword);
					    if ($userdata[0]['isOldUser'] == "0")
					    {
					        $userpasswordtotest = $this->userpassword;
    					//	if (($userpasswordtotest) == ($userdata[0]['userpassword']))
    					    if ((password_verify($userpasswordtotest,$userdata[0]['userpassword']))) 
    					    {
    							$retval = $this->updateUserValues($userdata);						
    							setCookieLogin($userdata[0]['userid']);								
    							$returnvalue = 1;							
    							return $returnvalue;
    						}
    						else 
    						{
    							throw new customException("Invalid UserName or Password.");						
    							return $returnvalue;
    						}
					    }
					    else
					    {
					        
                        	$wp_hasher = new PasswordHash(8, TRUE);
                            $password_hashed = $userdata[0]['userpassword'];
                        	$plain_password = $this->userpassword;
                        	
                        	if($wp_hasher->CheckPassword($plain_password, $password_hashed)) {
                        	   // echo "Success";
                        	    $retval = $this->updateUserValues($userdata);
    							setCookieLogin($userdata[0]['userid']);								
    							$returnvalue = 1;	
    							return $returnvalue;
                            }
                            else {
                        	   echo "Failed";
                        	   throw new customException("Invalid UserName or Password.");						
    							return $returnvalue;
                        	}
                            
					    }
					}	
				}
				else 
				{
					// user already exists but trying to register again with same username
					// send error
					throw new customException("User Already Exists");
					return $returnvalue;	
				}
			  }
			    else
			    {
					// user already exists but trying to register again with same username
					// send error
					throw new customException("Verify Your Email Id");
					return $returnvalue;	
			    }
			}
			elseif(($this->username!='')&&($this->userfirstName!='')&&($this->userlastName!='')) // user does not exists add to database
			{
			    // to add userdata in userdatatoadd array

				if ($this->userpassword=='')
				{
				    $sociallogin            =   '1';
				    $this->userpassword = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 8);
				}
				$this->userregistereddate = date("Y-m-d H:i:s");
				$this->userregisteredip = $this->get_user_ip();
				$this->usertype         =   '0';
				$this->noofmagzinesread =   '0';
				$mobileno               =   $this->usermobileno;
				$userdataToAdd = $this->updateUserValuesForDataBase();
			
		
				$lastinsertedID = $this->AddUser($userdataToAdd);
			//	if($lastinsertedID == 'true')
			//	{	
				    $username = $this->username;
			        $userdata = $this->getUserInfo('','*','',$username);
			        $usercount = count($userdata);	
			        if ($this->provider_name!='')
				    {
					    $provider_name_datafield = $this->provider_name.'_token';
					    $provider_name_arrayfield = $this->provider_name."_token";
					
					    $userid = $userdata[0]['userid'];
					    $wherecondition =   " userid = $userid ";
					    
					    $applicationdata[$provider_name_arrayfield]= $this->social_token;
					    $applicationdata['userprofiephotopath'] = $this->user_pictureUrls;
					    $applicationdata['isemailotpverify'] = '1';
					
					    // set site cookie and update in mstuser table and also put cookie					
					    $retval = $this->EditUser($applicationdata,$wherecondition);
					}
			        
			        if($userdata[0]['usertype'] == '0')
			        {
			            $noofmagzinesread   =   $userdata[0]['noofmagzinesread'];
			        }
			        else
			        {
    			        $packagevalues  =   explode('||',$this->checkPackageValue($userdata[0]['userid']));
    			        $userdata[0]['magzinesname']    =   $packagevalues[0];
					    $userdata[0]['PackageType']     =   $packagevalues[1];
					    $userdata[0]['UserPackageStatus']     =   $packagevalues[2];
                    }
                    
                    
			        if($sociallogin != 1)
			        {
			            $sociallogin =   $userdata[0]['userid'];
			            $retval = $this->updateUserValues($userdata);
			            setCookieLogin($userdata[0]['userid']);
			        }   
			        else
			        {
			            $retval = $this->updateUserValues($userdata);
			            setCookieLogin($userdata[0]['userid']);	
			        }
			        // send welcome email to user 
			        // नमस्कार. बहुविध परिवारात आपले स्वागत आहे. निवडक, संपादित साहित्याचा आनंद मिळवा. लॉगिन संबंधी काही अडचण आल्यास 9152255235 या क्रमांकावर संपर्क साधा.
			        // test this mail sending
			        // sendWelcomeMail();
			        return $sociallogin;
			//	}
			}
			else 
			{
					
					throw new customException("Username and Password does not exists. ");
					return $returnvalue;	
			}	
			
		}
		function sendWelcomeMail()
		{
		        $to_name = $this->userfirstname;
		        
				$from_name = 'Bahuvidh.com';
				//$from_name = 'Evergrow Solutions';
				$from_email = ADMIN_EMAIL_ID;
				//$from_email = "rajivatre@gmail.com";
				//$password = $_REQUEST['password'];
				
				$subject = 'बहुविध परिवारात आपले स्वागत';
			    $html_message = '<p>नमस्कार. बहुविध परिवारात आपले स्वागत आहे. 
<br/> 
निवडक, संपादित साहित्याचा आनंद मिळवा. <br/>
लॉगिन संबंधी काही अडचण आल्यास 9152255235 या क्रमांकावर संपर्क साधा.

<br/>
आपला बहुविध सपोर्ट
</p>';
			    $text_message = strip_tags($html_message); 
				$to_email = $this->username;		
				if ($to_email > '')
				{
					$mailsent = sendPHPMail($from_name, $from_email, $to_name, $to_email, $subject, $text_message, $html_message, $attachFile1,$attachFile2,$attachFile3,$attachFile4,$attachFile5,$replyto="");
					//$mailsent = sendPHPMail($from_name, $from_email, $to_name, $to_email, $subject, $text_message="", $html_message, $attachFile);

			        //$mailsent = sendGridMail($from_name, $from_email, $to_name, $to_email, $subject, $text_message="", $html_message,$attachFile1,$attachFile2,$attachFile3,$attachFile4,$attachFile5,$replyto="");
					//echo 'mail sent '.$mailsent;
					// exit;
				}
		    
		}
	    function AddUser($usersdata,$table='mstusers')
		{
			if (!is_array($usersdata))
			{
				return false;
			}
			else
			{
			    $fieldnames =  "(";
				$fieldvalues = "(";
				foreach ($usersdata as $k => $v) 
				{
					
					$fieldnames .=  ($fieldnames=="(")?"$k":",$k";
					$fieldvalues .= ($fieldvalues=="(")?"'$v'":",'$v'";
				}
				$sqltext = "insert into $table ".$fieldnames.") values ".$fieldvalues.")";
				//echo $sqltext;
				//die();
				$users = $this->obj1->insert_query($sqltext);
				return $users;
			//	exit;
			//	return ($users == 1)?"true":"false";
			}
		}
	    
		function updateUserValues($uservalueArray='')
		{
		    //print_r($uservalueArray);
			if(is_array($uservalueArray))
			{
				$this->userid 			= $uservalueArray[0]['userid'];	
				$this->username			= $uservalueArray[0]['username'];
				$this->userfirstName 		= $uservalueArray[0]['userfirstname']; 
      		    $this->userlastName			= $uservalueArray[0]['userlastname'];
      		    $this->display_name			= $uservalueArray[0]['display_name'];
      		    $this->magzinesname			= $uservalueArray[0]['magzinesname'];
      		    $this->PackageType          = $uservalueArray[0]['PackageType']; 
      		    $this->UserPackageStatus          = $uservalueArray[0]['UserPackageStatus']; 
      		    $this->usertype             = $uservalueArray[0]['usertype'];
      		    $this->noofmagzinesread     = $uservalueArray[0]['noofmagzinesread'];
      		    $this->useremail     = $uservalueArray[0]['useremail'];
      		    $this->usermobileno     = $uservalueArray[0]['usermobileno'];
				$this->user_gmailpictureUrls= $uservalueArray[0]['gmailuserprofilephoto']; 
				$this->user_fbpictureUrls= $uservalueArray[0]['fbuserprofilephoto']; 
      		    
      		    session::start_secure_session();
      		    session::add_param('userid',$this->userid);
			    session::add_param('username',$this->username); 
				session::add_param('userfirstname',$this->userfirstName);
			    session::add_param('userlastname',$this->userlastName);
				session::add_param('display_name',$this->display_name);
				session::add_param('magzinesname',$this->magzinesname);
				session::add_param('PackageType',$this->PackageType);
				session::add_param('UserPackageStatus',$this->UserPackageStatus);
				session::add_param('usertype',$this->usertype);
				session::add_param('noofmagzinesread',$this->noofmagzinesread);
				session::add_param('useremail',$this->useremail);
			    session::add_param('usermobileno',$this->usermobileno); 
			    session::add_param('isUser','1');
				$this->UpdateSessionValueToVariables();
			}
		}
		function UpdateSessionValueToVariables()
		{
		     global $isUser;
			global $G_username;
			global $G_userid;
			global $G_displayname;
			global $G_magzinesname;
			
			global $G_usertype;
			global $G_UserPackageStatus;
			global $G_userfirstname;
			global $G_userlastname;
			global $G_PackageType;
			global $G_noofmagzinesread;
			global $G_useremail;
			global $G_usermobileno;
						
		    $isUser   =   session::get_param('isUser');				
			$G_username		= $this->username;
			$G_userid		= $this->userid;
			$G_displayname		= $this->display_name;
			$G_userfirstname	= $this->userfirstName;
			$G_userlastname	= $this->userlastName;
			$G_magzinesname	= $this->magzinesname;
			$G_PackageType  = $this->PackageType;
			$G_UserPackageStatus  = $this->UserPackageStatus;
			$G_usertype     = $this->usertype;
			$G_noofmagzinesread =   $this->noofmagzinesread;
			$G_useremail =   $this->useremail;
			$G_usermobileno =   $this->usermobileno;
		}
			
	    function updateUserValuesForDataBase()
		{
				//$uservalueArray['userid'] = $this->user_id ;
				if ($this->username>'')
				{ 		
					$uservalueArray['username'] = $this->username ;
				}
				if ($this->useremail>'')
				{ 	
					$uservalueArray['useremail'] = $this->useremail ;
				}
				if ($this->usermobileno>'')
				{ 	
					$uservalueArray['usermobileno'] = $this->usermobileno ;
				}
				if ($this->userpassword >'')
				{ 		
				//	$uservalueArray['userpassword'] = password_hash($this->userpassword, PASSWORD_DEFAULT);
					$uservalueArray['userpassword'] = password_hash($this->userpassword,PASSWORD_DEFAULT);
					$uservalueArray['isemailotpverify'] = '1';
				}
				if ($this->userfirstName>'')
				{	
					$uservalueArray['userfirstname'] = $this->userfirstName  ;
				}	 
				if ($this->userlastName>'')
				{
      			    $uservalueArray['userlastname'] = $this->userlastName;
      		    }
      		    if ($this->userfirstName>'' && $this->userlastName>'')
      		    {
      			    $uservalueArray['display_name'] = $this->userfirstName.'_'.$this->userlastName;
      		    }
      		    if ($this->userregistereddate>'')
				{
      			    $uservalueArray['userregistereddate'] = $this->userregistereddate;
      		    }
      		    if ($this->usertype>'')
				{
      			    $uservalueArray['usertype'] = $this->usertype;
      			    $uservalueArray['UserByAdminAuthor'] = $this->usertype;
      			    $uservalueArray['noofmagzinesread'] =   $this->noofmagzinesread;
      		    }  
      		    if ($this->usersex>'')
				{
      			    $uservalueArray['usersex'] = $this->usersex;
      		    }
      		    if ($this->dateofbirth>'')
				{
      			    $uservalueArray['dateofbirth'] = $this->dateofbirth;
      		    }
      		    if ($this->userregisteredip > '')
      		    {
      		        $uservalueArray['userregisteredip'] = $this->userregisteredip;
      		    }
      		    if($this->user_gmailpictureUrls>'')
          		{
          			$uservalueArray['gmailuserprofilephoto'] = $this->user_gmailpictureUrls;
          		}	 
          		if($this->user_fbpictureUrls>'')
          		{
          			$uservalueArray['fbuserprofilephoto'] = $this->user_fbpictureUrls;
          		}	 
      		    $uservalueArray['status'] = '1';
      		    
      		return $uservalueArray;				
			
		}
		private function get_user_ip() {
    	$ipaddress = '';
    	if (isset($_SERVER['HTTP_CLIENT_IP']))
      	$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    	else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
      	$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    	else if(isset($_SERVER['HTTP_X_FORWARDED']))
      	$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    	else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
      	$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    	else if(isset($_SERVER['HTTP_FORWARDED']))
      	$ipaddress = $_SERVER['HTTP_FORWARDED'];
    	else if(isset($_SERVER['REMOTE_ADDR']))
      	$ipaddress = $_SERVER['REMOTE_ADDR'];
    	else
      	$ipaddress = 'UNKNOWN';
    	return $ipaddress;
		}
		
		function updateCookieValueToDatabase () 
		{
			if(($this -> userid > 0)&&($this->user_cookietoken > ''))
			{
				$applicationdata['lastusertoken']=$this->user_cookietoken;
				$useridToUpdate = $this->userid;
			//	$wherecondition=array('userid'=>$useridToUpdate);
				    $wherecondition =   "userid = $useridToUpdate";
				$retval = $this->EditUser($applicationdata,$wherecondition);				
				return $retval;			
			}	
		}
		function checkCookieinDatabase()
		{
			$chklogin = 0;
			if ($this->user_cookietoken!='')
			{
			    $applicationdata = $this->user_cookietoken;
				$sql = "select * from mstusers where lastusertoken = '$applicationdata' ";
				
				//$applicationdata['lastusertoken']= $this->user_cookietoken;
				
				$userdata = $this->getUserInfo('','',$sql);
				if ($userdata)
				{
				    $usercount = count($userdata);					
				    if ($usercount > 0)
				    {
					    $userid = $userdata[0]['userid'];
					    $useridEncDatabase =  hash_hmac('sha1',$userid, SECRET_KEY);
					    $cookieuserid = $this->user_cookietoken;
					    if ($useridEncDatabase==$cookieuserid)
					    {
						    // update cookie and token in database
						    $this->userid = $userid;
						    $retval = $this->updateUserValues($userdata);						
						    $chklogin = 1;
					    }
					    else
					    {
						    $chklogin = 2;
					    }
				    }
				    else 
				    {
					    $chklogin = 3;
				    }			
				}
				    
			}
			return $chklogin;
		}
		function setSiteCookieInDatabase()
		{
				$lastlogindatetime = date("Y-m-d H:i:s");
				$lastloginIP = $this->get_user_ip(); 
				$lastlogindevice = '0'; // keep 0 for time being for desktop once we start identifying devices then we make it 1 for tablet and 2 for mobile
			
				$appData['lastlogindatetime']	= $lastlogindatetime;
				$appData['lastloginIP']			= $lastloginIP;
				$appData['lastlogindevice']		= $lastlogindevice;
				$appData['isUserLoggedIn']		= '1';
				$appData['lastusertoken']		= $this->user_cookietoken;
				
				$useridToUpdate = $this->userid;
			//	$wherecondition=array('userid'=>$useridToUpdate);
				//print_r($wherecondition);
				//print_r($appData);
				$wherecondition =   "userid = $useridToUpdate";
				$retval = $this->EditUser($appData,$wherecondition);
				
				return (($retval!=0)?1:0);		
		}
		function unSetSiteCookieInDatabase()
		{
				$lastlogindatetime = date("Y-m-d H:i:s");
				$lastlogindevice = '0'; // keep 0 for time being for desktop once we start identifying devices then we make it 1 for tablet and 2 for mobile
			
				//$appData['lastlogindatetime']	= $lastlogindatetime;
				$appData['loggedoutdatetime']	= $lastlogindatetime;
				$appData['lastlogindevice']		= $lastlogindevice;
				$appData['isUserLoggedIn']		= '0';
				$appData['lastusertoken']		= '';
				
				$useridToUpdate=$this->userid;
					$wherecondition =   "userid = $useridToUpdate";
				$retval = $this->EditUser($appData,$wherecondition);
				return (($retval!=0)?1:0);		
		}	
	
		function GetUserPostCommentsData($userid,$postid,$returnHtml='1')
		{
				global $G_userid;
				$returnresult = array();			
				$sql = "select * from ".MAGAZINE_POST_COMMENTS_TABLE." a 
                        left join ".POST_TABLE." b on a.comment_post_ID = b.PostID
                        inner join ".MAGZINE_TABLE." mag on mag.MagzineId = b.MagzineId
                        where a.user_id = $userid and a.comment_post_ID = $postid order by a.comment_ID desc limit 0,1";				
                //        exit;
				$eventlisting = $this->getUserInfo('','',$sql,'');
				$i  =   0;	
			    $detailcount++;
				        $content_data                                       =   $eventlisting[$i]['comment_content'];
    				    $contentlength                                      =   strlen($content_data);
    				    $returnresult['commentdetailarray'][$i]['contentlength']	=   $contentlength; 
    				    $returnresult['commentdetailarray'][$i]['comment_ID']	    =   $eventlisting[$i]['comment_ID']; 
    					$returnresult['commentdetailarray'][$i]['PostID']	        =   $eventlisting[$i]['PostID']; 
    					$returnresult['commentdetailarray'][$i]['post_title']	    =   $eventlisting[$i]['post_title']; 
    					$returnresult['commentdetailarray'][$i]['post_status']	=   $eventlisting[$i]['post_status'];
    					$returnresult['commentdetailarray'][$i]['comment_to']	    =   $eventlisting[$i]['comment_author']; 
    					$returnresult['commentdetailarray'][$i]['comment_date']   =   ago(date('d M Y h:i:sa',strtotime($eventlisting[$i]['comment_date'])));
    					$returnresult['commentdetailarray'][$i]['content_data']	=   $content_data;  
    					$returnresult['commentdetailarray'][$i]['MagzineName']    =   $eventlisting[$i]['MagzineName'];
    					$returnresult['commentdetailarraycount']         =   $detailcount;
    				//	print_r($returnresult);
    					
				$dusttemplate = GLOBAL_INCLUDE_PATH."views/feed-comments-block";	
				
			if ($returnHtml=='1')
			{	
				$dust = new Dust\Dust();
				// Use the current directory as the include path
				$dust->includedDirectories = array(GLOBAL_INCLUDE_PATH);
				$template = $dust->compileFile($dusttemplate);			
				// to add and match user post data with template fields			
				$output = $dust->renderTemplate($template, $returnresult);
				
			//	echo $returnresult.$dusttemplate.$output;
			//	exit;
				return $output;			
			}
			else 
			{
				return $returnresult;	
			}	
		}
		// function to check if user has got the package
		function isUserPackage($userid,$packageid)
		{
		   $retval = '0';
		   $cur_date           =   date("Y-m-d"); 
	       $userid = ($userid=='')?$this->userid:$userid;
	       $userid = ($userid > '' )?$userid:0;
	       $sql = " select b.MembershipPackageId
                    from mstusers a 
                    inner join trnUserMembershipPackages b on a.userid = b.UserID
                    inner join mstMembershipPackages c on b.MembershipPackageId = c.MembershipPackageId 
                    left join trnMembershipPackageDetails d on d.MembershipPackageId = c.MembershipPackageId
                    where a.userid = '$userid' and (b.MembershipPackageId = '$packageid' or b.MembershipPackageId = '25') and PackageEndDate >= '$cur_date' ORDER BY packagetype "; 
                // echo $sql;
                $userdata    =   $this->getUserInfo('','',$sql);
                if ($userdata)
                {
                    $retval = ($userdata[0]['MembershipPackageId']!='')?$userdata[0]['MembershipPackageId']:'0';
                }
            // echo   $retval;  
            return $retval;     
		}
	    // function to check if user is allowed to see the post
	    function isPostAllowedForUser($magazineid,$userid)
	    {
	       global $G_noofmagzinesread; 
	       $cur_date           =   date("Y-m-d"); 
	       $userid = ($userid=='')?$this->userid:$userid;
	       $userid = ($userid>'')?$userid:0;
	       $sql = " select d.AllowedMagazineID,c.PackageType, a.noofmagzinesread,PackageEndDate
                    from mstusers a 
                    inner join trnUserMembershipPackages b on a.userid = b.UserID
                    inner join mstMembershipPackages c on b.MembershipPackageId = c.MembershipPackageId 
                    left join trnMembershipPackageDetails d on d.MembershipPackageId = c.MembershipPackageId
                    left join mstMagzine e on d.AllowedMagazineID = e.MagzineID
                    where a.userid = $userid  ORDER BY packagetype "; 
                    // and PackageEndDate >= '$cur_date'
                    // echo $sql;    
                    $usermagzinedata    =   $this->getUserInfo('','',$sql);
                    
                    $retval = '4'; // default value not allowed to read this post
                    
                    $countrow = isset($usermagzinedata)?count($usermagzinedata):0;
                    //echo 'countrow'.$countrow;
                    if($countrow >0)
                    {
                        
                        for($i=0;$i<$countrow;$i++)
                        {
                            $noofmagzinesread = intval($usermagzinedata[$i]['noofmagzinesread']);
                            switch($usermagzinedata[$i]['PackageType'])
                            {
                                case "0": // sarv
                                    if (strtotime($usermagzinedata[$i]['PackageEndDate']) > strtotime(date("Y-m-d")))
                                        {
                                            $retval = '1';
                                            return $retval;
                                            break;
                                        }
                                        else
                                        {
                                            $retval = '6'; // expired member
                                            break;
                                        }
                                case "1": // free user 
                                    $retval = ($noofmagzinesread < 5)?'1':'5';
                                    return $retval;
                                    break;
                                case "2": // no of articles but not defined for any package
                                    return '0';
                                    break;
                                case "3": // single magazine user
                                    if ($usermagzinedata[$i]['AllowedMagazineID']==$magazineid)
                                    {       
                                        if (strtotime($usermagzinedata[$i]['PackageEndDate']) > strtotime(date("Y-m-d")))
                                        {
                                            $retval = '1';
                                            return $retval;
                                            break;
                                        }
                                        else
                                        {
                                            $retval = '6'; // expired member
                                            break;
                                        }
                                        
                                    }
                                    else if ($i==$countrow-1) // last row in loop
                                    {
                                        $retval = '4'; // not allowed to read this magazine
                                        return $retval;
                                        break;
                                    }
                                case "4": // free magazine (sampadakiya)
                                    $retval = '1';
                                    return $retval;
                                    break;
                            }
                        }
                    }
                    else // this is free user  
                    {
                        // retval = 5 if no of magazines read by user is 5 or more
                        $retval = ($G_noofmagzinesread < 5)?'1':'5';
                    }
            // echo 'retval'.$retval;        
            return $retval;       
	    }
	    function checkPackageValue($userid)
	    {
	            $cur_date           =   date("Y-m-d");
	            $sql                =   "select (d.AllowedMagazineID) as MagzineId,c.PackageType ,
	                        CASE 
	                        WHEN packageenddate = 'noexpire' THEN 'activeexpired'
	                        WHEN packageenddate > CURDATE() THEN 'active' 
	                        WHEN packageenddate < CURDATE() THEN 'expired' END AS UserPackageStatus 
	                        from mstusers a 
                                            inner join trnUserMembershipPackages b on a.userid = b.UserID
                                            inner join mstMembershipPackages c on b.MembershipPackageId = c.MembershipPackageId 
                                            left join trnMembershipPackageDetails d on d.MembershipPackageId = c.MembershipPackageId
                                            where a.userid = $userid  and PackageStartDate <= '$cur_date' order by UserPackageStatus";   
                        //exit;  and PackageEndDate >= '$cur_date' and b.UserPackageStatus = 1
                        $usermagzinedata    =   $this->getUserInfo('','',$sql);
                        $magzinename        =   '';
                        $rowcount =0;
                        if ($usermagzinedata)
                        {
                            $rowcount = count($usermagzinedata);
                        }    
                        if($rowcount > 0)
                        {
                            for($i=0;$i<count($usermagzinedata);$i++)
                            {
                                $UserPackageStatu = $usermagzinedata[$i]['UserPackageStatus'];
                                if($UserPackageStatu  == 'activeexpired')
                                    $UserPackageStatu  = 'noexpired';  
                                    
                                if($i==0)
                                {
                                    $UserPackageStatus  .=   $UserPackageStatu;
                                    $magzinename    .=   $usermagzinedata[$i]['MagzineId'];
                                    $PackageType    .=   $usermagzinedata[$i]['PackageType'];
                                }
                                else
                                {
                                    $UserPackageStatus  .=   ','.$UserPackageStatu;
                                    $magzinename    .=   ','.$usermagzinedata[$i]['MagzineId'];
                                    $PackageType    .=   ','.$usermagzinedata[$i]['PackageType'];
                                }
                            }
                            
                        }
                        else
                        {
                            $UserPackageStatus  =   '';
                            $magzinename    =   '';
					        $PackageType     =   '';
                        }
            return $magzinename.'||'.$PackageType.'||'.$UserPackageStatus;
	    }
	    
       //admin login details 
	    
	    function checkAdminCookieinDatabase()
		{
			$chklogin = 0;
			if ($this->user_cookietoken!='')
			{
			    $applicationdata = array($this->user_cookietoken);
				$sql = "select * from mstMagzineAdminUsers where lastusertoken = $applicationdata";
				//$applicationdata['lastusertoken']= $this->user_cookietoken;
				
				$userdata = $this->getUserInfo('','',$sql);
				if(is_array($userdata))
				{
					$usercount = count($userdata);					
				}
				else
				{
					$usercount = 0;		
				}

				if ($usercount > 0)
				{
					$adminid = $userdata[0]['adminid'];
					$adminidEncDatabase =  hash_hmac('sha1',$adminid, SECRET_KEY);
					$cookieadminid = $this->user_cookietoken;
					if ($adminidEncDatabase==$cookieadminid)
					{
						// update cookie and token in database
						$this->userid = $adminid;
						$retval = $this->updateAdminValues($userdata);						
						$chklogin = 1;
					}
					else
					{
						$chklogin = 2;
					}
				}
				else {
					$chklogin = 3;
				}			
			}
			return $chklogin;
		}
		function setSiteAdminCookieInDatabase()
		{
				$lastlogindatetime = date("Y-m-d H:i:s");
				$lastloginIP = $this->get_user_ip(); 
				$lastlogindevice = '0'; // keep 0 for time being for desktop once we start identifying devices then we make it 1 for tablet and 2 for mobile
			
				$appData['lastlogindatetime']	= $lastlogindatetime;
				$appData['lastloginIP']			= $lastloginIP;
				$appData['lastlogindevice']		= $lastlogindevice;
				$appData['isUserLoggedIn']		= '1';
				$appData['lastusertoken']		= $this->user_cookietoken;
				
				$adminidToUpdate = $this->userid;
			//	$wherecondition=array('userid'=>$adminidToUpdate);
				//print_r($wherecondition);
				//print_r($appData);
				  $wherecondition =   "userid = $adminidToUpdate";
				
				$retval = $this->EditUser($appData,$wherecondition,"mstMagzineAdminUsers");
				if ($retval=='true') 
				{    
				     $sql = "select * from ".ADMINUSER_TABLE." where ".$wherecondition."";
				    $admindataUpdated = $this->getUserInfo('','',$sql);
				    //print_r($admindataUpdated);
				    $this->updateAdminValues($admindataUpdated);
				    
				}    
				    return (($retval!=0)?1:0);		
		}
		function unsetSiteAdminCookieInDatabase()
		{       
		     
				$lastlogindatetime = date("Y-m-d H:i:s");
				$lastlogindevice = '0'; // keep 0 for time being for desktop once we start identifying devices then we make it 1 for tablet and 2 for mobile
			
				$appData['lastlogindatetime']	= $lastlogindatetime;
				$appData['loggedoutdatetime']	= $lastlogindatetime;
				$appData['lastlogindevice']		= $lastlogindevice;
				$appData['isUserLoggedIn']		= '0';
				$appData['lastusertoken']		= '';
				
				$adminidToUpdate=$this->userid;
				//die();
					$wherecondition =   "userid = $adminidToUpdate";
				$retval = $this->EditUser($appData,$wherecondition,"mstMagzineAdminUsers");
				return (($retval!=0)?1:0);		
		}	
		
		
		
		function updateAdminValues($admin='')
		{
		    //print_r($admin);
		   // echo $admin;
		    //die();
			if(is_array($admin))
			{   

                session::add_param('adminid',$admin[0]['userid']);
                session::add_param('admin_username',$admin[0]['username']);
                session::add_param('admin_userfirstname',$admin[0]['userfirstname']);
                session::add_param('admin_userlastname',$admin[0]['userlastname']);
                session::add_param('admin_displayname',$admin[0]['display_name']);
                session::add_param('admin_magzinesname',$admin[0]['magzinesname']);
                session::add_param('admin_PackageType',$admin[0]['PackageType']);
                session::add_param('admin_noofmagzinesread',$admin[0]['noofmagzinesread']);
                session::add_param('admin_session_id',$admin[0]['session_id']);
                session::add_param('admin_usertype',$admin[0]['usertype']);
                session::add_param('admin_MagzineId',$admin[0]['MagzineId']);
                session::add_param('admin_useremail',$admin[0]['useremail']);
                session::add_param('admin_usermobileno',$admin[0]['usermobileno']);
                session::add_param('admin_isAdmin','1');
                session::add_param('admin_session_id',session_id());
            
      		    
			    $this->UpdateAdminSessionValueToVariables();
			}
		}
		function UpdateAdminSessionValueToVariables()
		{
			global $G_adminid;
            global $G_admin_username;
            global $G_admin_userfirstname;
            global $G_admin_userlastname;
            global $G_admin_displayname;
            global $G_admin_magzinesname;
            global $G_admin_PackageType;
            global $G_admin_noofmagzinesread;
            global $G_admin_sessionid;
            global $G_admin_usertype;
            global $G_admin_MagzineId;
            global $G_admin_useremail;
            global $G_admin_usermobileno;
			
		 /*	$admin_isAdmin              =   $admin[0]['isAdmin'];
            $G_adminid	                = 	$admin[0]['userid'];
            $G_admin_username	        = 	$admin[0]['username'];
            $G_admin_userfirstname		= 	$admin[0]['userfirstname'];
            $G_admin_userlastname       =   $admin[0]['userlastname'];
            $G_admin_displayname        =   $admin[0]['display_name'];
            $G_admin_magzinesname       =   $admin[0]['magzinesname'];
            $G_admin_PackageType        =   $admin[0]['PackageType'];
            $G_admin_noofmagzinesread   =   $admin[0]['noofmagzinesread'];
            $G_admin_sessionid		    = 	$admin[0]['session_id'];
            $G_admin_usertype           =   $admin[0]['usertype'];
            $G_admin_MagzineId          =   $admin[0]['MagzineId'];
            $G_admin_useremail          =   $admin[0]['useremail'];
            $G_admin_usermobileno       =   $admin[0]['usermobileno'];*/
            $sqlmag = "SELECT mstmag.MagzineId as MagzineId FROM trnMagzineAdminUsersDetails trnadmin 
                    inner join mstMagzineAdminUsers mstadmin on mstadmin.userid = trnadmin.UserID 
                    inner join mstMagzine mstmag on mstmag.MagzineId = trnadmin.MagnizeID
                    where mstadmin.userid = $G_adminid ";
                    
            $usermag = $this->getUserInfo('','',$sqlmag);		
            if($usermag)
        	{
        	    $rowcount1 = count($usermag);
        		if ($rowcount1 > 0)
        		{
        		    session::add_param('admin_MagzineId',$usermag[0]['MagzineId']);
                    
        		}
        	}
            $G_adminid	                    = 	session::get_param('adminid');
            if($G_adminid > '0' ) 
            {
                $G_admin_username	        = 	session::get_param('admin_username');
                $G_admin_userfirstname		= 	session::get_param('admin_userfirstname');
                $G_admin_userlastname       =    session::get_param('admin_userlastname');
                $G_admin_displayname        =    session::get_param('admin_displayname');
                $G_admin_magzinesname       =    session::get_param('admin_magzinesname');
                $G_admin_PackageType        =   session::get_param('admin_PackageType');
                $G_admin_noofmagzinesread   =   session::get_param('admin_noofmagzinesread');
                $G_admin_sessionid		    = 	session::get_param('admin_session_id');
                $G_admin_usertype           = session::get_param('admin_usertype');
                $G_admin_MagzineId          = session::get_param('admin_MagzineId');
                $G_admin_useremail          = session::get_param('admin_useremail');
                $G_admin_usermobileno       = session::get_param('admin_usermobileno');
                $G_admin_isAdmin	        = 	session::get_param('admin_isAdmin');
                $G_admin_sessionid			= 	session::get_param('admin_session_id');
            }
		}
    }
?>