<?php 
require_once("$CFG->dirroot/local/badiunet/lib/util.php");
require_once("$CFG->dirroot/local/badiunet/lib/netlib.php");
require_once("$CFG->dirroot/local/badiunet/lib/httpquerystring.php");
require_once("$CFG->dirroot/local/badiunet/fcservice/maccess.php");
require_once("$CFG->dirroot/local/badiunet/fcservice/factorycontent.php");
class local_badiunet_proxy_lib{
 
    private $util = null;

    function __construct() {
        $this->util=new local_badiunet_util();
     }
    public function run(){
     
       
        if(!$this->isloggedin()){return null;}
       
        $uri= $this->clean_uri();
       
        if($this->exception_proxy($uri)){return null;}
       
        $cached=$this->chekcache();
       //  echo "cache: ".$cached;exit;
        if($cached){return null;}
       
        $listprofileproxy=$this->get_profile_proxy();
       
        $context='system';
      
        $role=$this->get_shortnamerole($uri);
       if($role==-1){return null;}
       
        global $USER;
        global $CFG;
        $httpqs=new local_badiunet_httpquerystring();
        $httpqs->add('url',$CFG->wwwroot);
        $httpqs->add('uri',$uri);
        $httpqs->add('userid',$USER->id);
        $httpqs->add('context',$context);
        $httpqs->add('shortnamerole',$role);
        $httpqs->add('isloggedin',1);
        $httpqs->add('time',time());
        $httpqs->add('_key','badiu.admin.proxy.check.service');
        $httpqs->add('_kfunction','sservice');  
      
        if(is_array($listprofileproxy)){
           foreach ($listprofileproxy as $row) {
               $httpqs->add($row['shortname'],$row['data']);
           }
        }
        
    
       
        $factorycontent=new local_badiunet_factorycontent('notformated');
        
        $httpqs->add('sservicid',$factorycontent->getNetlib()->getModuleInstance()); 
        $factorycontent->setService('badiu.system.core.functionality.exec.service');
        $uparam=$httpqs->getParam();
        //$factorycontent->setParamsytemstart($uparam);
        $factorycontent->setParamsytemdefault($uparam);
        $factorycontent->init();
        $response=$factorycontent->getContent();
        
        if(!$factorycontent->getUtil()->isResponseError($response)){
            $message=$factorycontent->getUtil()->getVlueOfArray($response, 'message');
            $status= $factorycontent->getUtil()->getVlueOfArray($response, 'status');
            $message=$factorycontent->getTcript()->decode($message);   
            if($status=='accept' && !empty($message)){ $this->lock($message);}
          
        }else{$this->addCache();}
      
       return null;
      
    }
    
    public function get_shortnamerole($uri){
        
        #$connlib=new report_badiunet_conn();
        $util=new local_badiunet_util();
        global $CFG;
        global $USER;
        
        $host=$CFG->wwwroot.'/local/badiunet/proxy/service.php';
        $param=array('key'=>'shortnamerole','userid'=>$USER->id,'uri'=>$uri);
        //$result=$connlib->request($host,$param,true);

        $response=$util->request($host,$param);
        $status= $util->getVlueOfArray($response, 'status');
        $info= $util->getVlueOfArray($response, 'info');
        $message=$util->getVlueOfArray($response, 'message');
        $result=-1;
        if($status=='accept' && !empty($message)){
            $result=$message;
         } else { $result=-1;}
        return $result;
    }
     public function get_profile_proxy(){
        global $CFG;
        global $USER;
        
        
        $host=$CFG->wwwroot.'/local/badiunet/proxy/service.php';
        $param=array('key'=>'profileproxy','userid'=>$USER->id);
        $response=$this->util->request($host,$param);
        
        $status= $this->util->getVlueOfArray($response, 'status');
        $info= $this->util->getVlueOfArray($response, 'info');
        $message=$this->util->getVlueOfArray($response, 'message');
       
        if($status=='accept' && !empty($message)){
            $result=$message;
          } else { $result=-1;}
        return $result;
    }
     public function clean_uri(){
         $uri=$_SERVER['REQUEST_URI'];
         global $CFG;
         $host=$CFG->wwwroot;
         $p=explode("//",$host);
         if(!isset($p[1])){ return $uri;}
         $shost=explode("/",$p[1]); 
         
         $suri=explode("/",$uri);
         
         $cont=0;
         $newuri="";
         foreach ($suri as $key => $value) {
            
                $phost=null;
                if(isset($shost[$key])){$phost=$shost[$key];}
                if($key > 0 ){
                    if(empty($value)){$newuri.='/';$cont++;}
                    else if($phost!=$value){
                        if($newuri!='/'){$newuri.='/'.$value;$cont++;}
                    }
                    
                    
                }
                    
                
            
           
         }
         if($cont==0){ return $uri;}
        return $newuri;
     }
   public function lock($proxy){
      
       if(empty($proxy)){$this->addCache();return null;}
       
       if(isset($proxy['exec']) && $proxy['exec']==1){
          $msg="Acesso bloqueado";
           // print_r($proxy);exit;
           if(isset($proxy['proxy']['showmessage']) && !empty($proxy['proxy']['showmessage'])){$msg=$proxy['proxy']['showmessage'];}
           $this->addCache($msg);
           $this->lockshowmessage($msg);
       }else{$this->addCache();}
    } 
   public function lockshowmessage($msg){
          global $OUTPUT;
           echo $OUTPUT->header();
            echo "<div class=\"alert alert-danger\" role=\"alert\">$msg</div>";
            echo $OUTPUT->footer();
           exit;
   }
   
   public function addCache($message=null){
      
        $dto=new stdClass;
        $dto->time=time();
        $dto->locked=false;
        if(!empty($message)){ $dto->locked=true;}
        $dto->message=$message;
        $list=array();
        if(isset($_SESSION['_local_badiunet_proxy_cache'])){$list=$_SESSION['_local_badiunet_proxy_cache'];}
       // $uri=$_SERVER['REQUEST_URI'];
       // $list[$uri]=$dto;
        
        $_SESSION['_local_badiunet_proxy_cache']=$dto;
       
    }

 public function chekcache(){
     $result=false;
      //check if cache exist
    if(!isset($_SESSION['_local_badiunet_proxy_cache'])){return $result;}
    if(empty($_SESSION['_local_badiunet_proxy_cache'])){return $result;}
    
   // $list=$_SESSION['_local_badiunet_proxy_cache'];
   // $uri=$_SERVER['REQUEST_URI'];
    //$dto=null;
   // if(isset($list[$uri])){$dto=$list[$uri];}
  
    $dto=$_SESSION['_local_badiunet_proxy_cache'];
     $limit=time()-(5*60);
   
    if(!empty($dto) && $dto->time > $limit) {
        $result=true;
       if($dto->locked && !empty($dto->message)){
            $msg=$dto->message;
            $this->lockshowmessage($msg);
        }
    }
    
    return $result;
} 
  
  public function isloggedin(){
      global $USER;
     if(!isset($USER) || empty($USER) || empty($USER->id)){ return false;}
     if($USER->id==0 ||  $USER->id==1){ return false;}
     if($USER->id > 2 ){ return true;}
     return false;
  }
  
   public function exception_proxy($uri){
       $excepton=false;
       
       $pos = stripos($uri, "/local/badiunet/proxy/");
       $pos1 = stripos($uri, "/local/badiunet/synchttp/");
       $pos2 = stripos($uri, "/local/badiuws/");
       $pos3 = stripos($uri, "/login/");
       if ($pos !== false) { $excepton=true;}
       else if ($pos1 !== false) { $excepton=true;}
       else if ($pos2 !== false) { $excepton=true;}
       else if ($pos3 !== false) { $excepton=true;}
       return  $excepton;
   }
}