<?php
$aModel = array();

function openSession($userdata)
{
  $uid = $userdata['rowid'];
  $urole = $userdata['fk_role'];

  $sql = "DELETE FROM z_sessions WHERE fk_user=" . $uid . ";";
  qSQL($sql, "gen");

  session_regenerate_id();

  if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
    $uip = $_SERVER["HTTP_CLIENT_IP"];
  } elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
    $uip = $_SERVER["HTTP_X_FORWARDED_FOR"];
  } else {
    $uip = $_SERVER["REMOTE_ADDR"];
  }
  $utime = time();

  //! en session on récupère son prénom et nom, son id, son ip et son rôle
  $_SESSION['uname'] = ucfirst($userdata["prenom"]) . " " . strtoupper($userdata["libelle"]);
  $_SESSION['uid'] = $uid;
  $_SESSION['urole'] = $urole;
  $_SESSION['umodified'] = $utime;
  $_SESSION['uip'] = $uip;
  session_write_close();

  $sql = "INSERT INTO z_sessions (sid, fk_user, role, date_modified, ip, browser) VALUES ('" . session_id() . "', " . $uid . ", '" . $urole . "', '" . date("Y-m-d H:i:s") . "', '" . $uip . "', '" . $_SERVER['HTTP_USER_AGENT'] . "');";
  qSQL($sql, "gen");

  // et on en profite pour purger les logs
  $sql = "DELETE FROM z_logs WHERE DATEDIFF(CURDATE(), z_logs.date)>5;";
  qSQL($sql);
  // ainsi que les sessions qui ont une date antérieure à 1 jour
  $sql = "DELETE FROM z_sessions WHERE DATEDIFF(CURDATE(), z_sessions.date_modified)>1;";
  qSQL($sql, "gen");

  envoieMail("support@unikoffice.com", "Ouverture de session", "Ouverture de session pour " . $uid);

  return TRUE;
}