<?php
/* 
 * Classe du monitoring du webservice
 */

/**
 * Description of monitoringclass
 *
 * @author rr
 * @date 27/07/2011
 */

class monitoringWS {

    public $tabConfig;

    function  __construct($sPathConfig) {
        $this->tabConfig = $this->readConfig($sPathConfig);
    }

    public function readConfig($sPathConfig) {
        $tabConfig = @parse_ini_file($sPathConfig, true);
        return $tabConfig;
    }

    public function verifyLock($sDirname) {
        $error = false;
        if (file_exists($sDirname.'/lock')) {
            $infos = stat($sDirname.'/lock');
            $total = time() - $infos['mtime'];
            $jours = floor($total/86400);
            if ($jours > 2) {
                $error = true;
                unlink($sDirname.'/lock');
            }
        }
        return $error;
    }

    public function verifyExports($sDirname, $limit, $aExtensions = array()) {
        $error = false;
        $tabFiles = $this->listDir($sDirname, $aExtensions);
        foreach ($tabFiles as $ext => $file) {
            if (count($file) > $limit) $error = true;
            if ($error) break;
        }
        return $error;
    }

    public function verifyErrorsNotices($sFileNameLog) {
        if (file_exists($sFileNameLog)) {
            $retour = '<ul>';
            $listNotices = '';
            $tabNotices = explode("\n", trim(file_get_contents($sFileNameLog)));
            if (count($tabNotices) > 0) $listNotices = implode("</li><li>", $tabNotices);
            if (!empty($listNotices)) {
                $retour .= '<li>'.$listNotices.'</li></ul>';
                return $retour;
            }
            else return false;
        }
        else return false;
    }

    public function rotateLog($aFilesLog, $iMaxFilesize) {
        $operations = 0;
        foreach ($aFilesLog as $file) {
            if (file_exists($file) && (filesize($file) > $iMaxFilesize)) {
                $pathFile = substr($file, 0, strrpos($file, "/") + 1);
                $nameFile = substr(strrchr($file, "/"), 1);
                $nameFileNoExt = substr($nameFile, 0, strrpos($nameFile, "."));
                $ExtFile = substr(strrchr($nameFile, "."), 1);
                if (!file_exists($pathFile.'rotate')) mkdir($pathFile.'rotate');
                $tabFiles = $this->listDir($pathFile.'rotate', array());
                $nbLog = 1;
                if (isset($tabFiles['log'])) {
                    foreach ($tabFiles['log'] as $fileLog) {
                        if (strpos($fileLog, $nameFileNoExt) !== FALSE) $nbLog++;
                    }
                }
                copy($file, $pathFile.'rotate/'.$nameFileNoExt.'-'.$nbLog.'.'.$ExtFile);
                if ($lastLine = $this->readlastline($file)) file_put_contents($file, $lastLine."\n"); //Remplacement du fichier original avec sa dernière ligne
                $operations++;
            }
        }
        if ($operations > 0) return true;
        else return false;
    }

    private function readlastline($file)
    {
        $fp = @fopen($file, "r");
        if ($fp) {
            $pos = -3;
            $t = " ";
            while ($t != "\n") {
                if (!fseek($fp, $pos, SEEK_END)) {
                    $t = fgetc($fp);
                    $pos = $pos - 1;
                }
                else {
                    rewind($fp);
                    break;
                }
            }
            $t = fgets($fp);
            fclose($fp);
            return trim($t);
        }
        else return false;
    }

    public function sendMail($client, $aTo, $content) {
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=utf8\r\n";
        $headers .= "To: $aTo <$aTo>\r\n";
        $headers .= "From: Monitoring OPAC 3D <monitoring@e-sezhame.fr>\r\n";
        $post = array('key' => md5($this->tabConfig['mail']['key'].date('Ymd')), 'to' => base64_encode($aTo), 'subject' => base64_encode('[OPAC 3D / Agent SIGB] Rapport d\'erreur du client '.$client), 'body' => base64_encode($content), 'headers' => base64_encode($headers));
        return $this->curl_send($post);
    }

    private function curl_send($post) {
        $ch = curl_init('http://'.$this->tabConfig['mail']['service'].'/webservices/pub/sendMail.php');
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $ret = curl_exec($ch);
        curl_close($ch);
        if (!$ret) {
            return curl_error($ch);
        }
        else return $ret;
    }

    public function infosClient() {
        $content = '';
        foreach ($_SERVER as $param => $value) {
            $content .= '<strong>'.$param.' : </strong>'.htmlentities(is_array($value) ? implode(",", $value) : $value).'<br />';
        }
        return $content;
    }

    private function listDir($sDirname, $aExtensions) {
        try {
            $tabFiles = array();
            $handle = @opendir($sDirname);
            if (!$handle) throw new Exception('Ouverture du répertoire');
            while ($file = @readdir($handle)) {
                if (substr($file, 0, 1) != ".") {
                    if (!empty($aExtensions) && in_array(substr(strrchr($file, "."), 1), $aExtensions)) $tabFiles[substr(strrchr($file, "."), 1)][] = $file;
                    elseif (empty($aExtensions)) $tabFiles[substr(strrchr($file, "."), 1)][] = $file;
                }
            }
            closedir($handle);
            return $tabFiles;
        }
        catch (Exception $e) {
            return 'Erreur listDir : '.$e->getMessage();
        }
    }

    public function remote_file_exists($sURL) {
        $ch = curl_init($sURL);
        try {
            if (!curl_setopt($ch, CURLOPT_NOBODY, true)) throw new Exception('Options CURL');
            if (!curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5)) throw new Exception('Options CURL');
            if (!curl_exec($ch)) throw new Exception('Execution CURL');
        }
        catch (Exception $e) {
            return false;
        }
        $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $retcode;
    }

}
?>
