<?php
    //Instructions: Each page must include: include 'session.inc.php'; check_login();
    define('INACTIVITY_TIMEOUT',3600); 
     
    ini_set('session.use_cookies', 1);
    ini_set('session.use_only_cookies', 1);
    ini_set('session.use_trans_sid', false);
     
    session_start();
     
    function allIPs() {
        $ip = $_SERVER["REMOTE_ADDR"];
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip=$ip.'_'.$_SERVER['HTTP_X_FORWARDED_FOR']; }
        if (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip=$ip.'_'.$_SERVER['HTTP_CLIENT_IP']; }
        return $ip;
    }
     
    function check_auth($login,$password) {
        include('../database.params.inc.php');
        $link = pg_connect("host=$machine user=$user password=$pwd dbname=$db")or die('Erreur de Connection !<br />'.pg_last_error()) ;
        $query = "SELECT * FROM PERSONNEL WHERE login='$login';";
        $result = pg_query($link, $query) or die("Erreur SQL !<br />$query<br />".pg_last_error());
        $total = pg_num_rows($result);
        if ($total == 1) {
            $passbdd = pg_fetch_result($result, 0, "pass_hash");
            $function = pg_fetch_result($result, 0, "fonction");
        }

        if (password_verify($password,$passbdd)) {
            $_SESSION['uid'] = sha1(uniqid('',true).'_'.mt_rand());
            $_SESSION['ip']=allIPs();
            $_SESSION['username']=$login;
            $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT;
            $_SESSION['function']=$function;
            return True;
        }
        else {
            return False;
        }
    }
     
    function check_login() {
        if (!isset ($_SESSION['uid']) || !$_SESSION['uid'] || $_SESSION['ip']!=allIPs() || time()>=$_SESSION['expires_on']) {
            logout();
        }
        $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT;
    }
     
    function logout() {
        unset($_SESSION['uid'],$_SESSION['ip'],$_SESSION['expires_on'],$_SESSION['function']);
        header('Location: logmein.php');
        exit();
    } 
?>