<?php

class Supervision {
    
    public $configFile;
    private $out = 8000;
    
    function __construct() {
        $this->configFile = @parse_ini_file('config/config.ini', true);
    }
    
    public function connectBddSupervision() {
        $link = mysql_connect($this->configFile['supervision']['host'], $this->configFile['supervision']['user'], $this->configFile['supervision']['pass']);
        if ($link) {
            $db_selected = mysql_select_db($this->configFile['supervision']['basename'], $link);
        }
        return $db_selected;
    }
    
    public function connectBddOpac() {
        $link = mysql_connect($this->configFile['opac']['host'], $this->configFile['opac']['user'], $this->configFile['opac']['pass']);
        if ($link) {
            $db_selected = mysql_select_db($this->configFile['opac']['basename'], $link);
        }
        return $db_selected;
    }
    
    public function getAllClients($tri = '') {
        $selection = "SELECT id, client, url_opac3d, ip_agent, url_testconfig, url_monitoring, url_infosclass, erreur_agent, erreur_config, last_complet, last_partiel, infos_monitoring, class_name, class_version, date_check FROM client $tri";
        $resultSelection = mysql_query($selection);
        $returnSelection =  $this->returnTabObjectFromResult($resultSelection,'Client');
        return $returnSelection;
    }
    
    public function searchClients($search, $tri = '') {
        $selection = "SELECT id, client, url_opac3d, ip_agent, url_testconfig, url_monitoring, url_infosclass, erreur_agent, erreur_config, last_complet, last_partiel, infos_monitoring, class_name, class_version, date_check FROM client WHERE client LIKE '%$search%' $tri";
        $resultSelection = mysql_query($selection);
        $returnSelection =  $this->returnTabObjectFromResult($resultSelection,'Client');
        return $returnSelection;
    }
    
    public function getClientByName($name) {
        $selection = "SELECT id, client, url_opac3d, ip_agent, url_testconfig, url_monitoring, url_infosclass, erreur_agent, erreur_config, last_complet, last_partiel, infos_monitoring, class_name, class_version, date_check FROM client WHERE client = '$name'";
        $resultSelection = mysql_query($selection);
        $returnSelection =  $this->returnTabObjectFromResult($resultSelection,'Client');
        return $returnSelection[0];
    }
    
    private function returnTabObjectFromResult($resultSelection, $objet) {
        $returnTab = array();
        $existsObject = false;
        while($obj = mysql_fetch_object($resultSelection, $objet)) {
            $existsObject = true;
            $returnTab[] = $obj;
        }

        if ($existsObject) {
            return $returnTab;
        }
        return false;
    }
    
    public function updateInDay($date) {
        if(trim($date)=='') return (-1);
        $out = time()- $this->myStrtotime($date);
        $out = $out/60; //min
        $out = $out/60; //hours
        $out = $out/24; //days
        return(floor($out));
    }

    public function myStrtotime($date) {
      $out = substr($date,0,4).'-'.substr($date,4,2).'-'.substr($date,6,2);
      return(strtotime($out));
    }


    public function check_url($url) {
        $ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_TIMEOUT, $this->out/1000);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

	$res = curl_exec($ch);
	
	if($res === false)$res = 1;
	else $res = 0;
	
	curl_close($ch);
	
	return $res;
    }

    public function check_infosclass($url){
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_TIMEOUT, $this->out/1000);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

	$res = curl_exec($ch);
	
	curl_close($ch);
	
	return $res;
    }

    public function check_config($url) {
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_TIMEOUT, $this->out/1000);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

	$res = curl_exec($ch);
	$errors = "";
	if($res === false){
		return $errors;
	}
	else {
            if(trim($res)=="")$errors .= "Fichier vide!";
            if(strpos($res,'Vérification du système')===FALSE) $errors .= ' Vérification impossible du système!<br>';
            if(strpos($res,'Fichier de configuration introuvable')!==FALSE) $errors .= ' Fichier de configuration introuvable<br>';
            if(strpos($res,'zip</em> n\'est pas chargée')!==FALSE) $errors .= 'ZIP pour PHP n\'est pas chargée<br>';
            if(strpos($res,'interbase</em> n\'est pas chargée')!==FALSE) $errors .= 'INTERBASE pour PHP n\'est pas chargée<br>';
            if(strpos($res,'en version 5.2.X')!==FALSE) $errors .= 'La version de PHP n\'est pas la bonne<br>';
            if(strpos($res,'ABLOGIN_TYPE</acronym> : N')!==FALSE) $errors .= 'ABLOGIN_TYPE mal configuré<br>';
            if(strpos($res,'ABLOGIN_UPDATEPWD</acronym> : F')!==FALSE) $errors .= 'ABLOGIN_UPDATEPWD mal configuré<br>';
            if(strpos($res,'allowedExportTime=*|*')!==FALSE) $errors .= 'La plage d\'heure d\'export est mal configurée (*|*)<br>';
            if(strpos($res,'La taille de la mémoire alouée à PHP est <')!==FALSE) $errors .= 'La taille de la mémoire alouée à PHP est < 128mo<br>';
            if(strpos($res,'PHP doit être en version')!==FALSE) $errors .= 'la version de PHP ne semble pas correcte.<br>';
            if(strpos($res,'Apache doit être en version')!==FALSE) $errors .= 'Apache ne semble pas dans la bonne version.<br>';
            if(strpos($res,'<b>Warning</b>:  fsockopen()')!==FALSE) $errors .= 'La connexion au SIGB (Agate) semble poser problème. (fsockopen)<br>';

            if(strpos($res,'Impossible de se connecter')!==FALSE) {
                    if(strpos($res,'la base Carthame')!==FALSE) $errors .= 'La connexion au SIGB (Carthame/Paprika) semble poser problème.';
                    if(strpos($res,'Agate')!==FALSE) $errors .= 'La connexion au SIGB (Agate) semble poser problème.';
                    if(strpos($res,'Karvi')!==FALSE) $errors .= 'La connexion au SIGB (Karvi) semble poser problème.';
            }

            return $errors;
	}
	curl_close($ch);
	return $res;
    }
    
    public function check_monitoring($url) {
        $ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_TIMEOUT, $this->out/1000);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	$res = curl_exec($ch);
	curl_close($ch);
        
        if (strpos($res, 'Dev/Opac2/Arbo')) {
            $res = 'Monitoring non configuré';
        }
	return $res;
    }
    
    public function getVersionClassServer($classname) {
        $allowedClass = array('agate', 'gabi', 'karvi', 'ktm', 'aloes', 'koha');
        if (in_array($classname, $allowedClass)) {
            if ($classname == 'eppk') {
                $classname = 'gabi';
            }
            require_once($this->configFile['serveur']['url']."/sigb_class/sigb.class.php");
            require_once($this->configFile['serveur']['url']."/sigb_class/Stats.class.php");
            require_once($this->configFile['serveur']['url']."/sigb_class/".$classname.".class.php");
            $classnameBK = $classname.'BK';
            $sigb = new $classnameBK();
            return $sigb->version();
        }
        else {
            return '?';
        }
    }
    
    public function reinstallAgent($client, $class) {
        if ($class == 'eppk') {
            $class = 'gabi';
        }
        $ch = curl_init($this->configFile['serveur']['ws'].'?idclient='.$client.'&sigb='.$class.'&action=forceUpdate');
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_TIMEOUT, $this->out/1000);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	$res = curl_exec($ch);
	curl_close($ch);
    }
    
}

