<?php
/* libraries/session.php
*
* Copyright (C) by Hugo Leisink <hide@address.com>
* This file is part of the Banshee PHP framework
* http://www.banshee-php.org/
*
* Don't change this file, unless you know what you are doing.
*/
final class session {
private $db = null;
private $settings = null;
private $id = null;
private $session_id = null;
private $use_database = null;
/* Constructor
*
* INPUT: object database
* OUTPUT: -
* ERROR: -
*/
public function __construct($db, $settings) {
$this->db = $db;
$this->settings = $settings;
$this->db->query("delete from sessions where expire<=now()");
$this->use_database = (SESSION_TIMEOUT >= ini_get("session.gc_maxlifetime"));
$this->start();
if ($this->use_database == false) {
return;
}
$query = "select * from sessions where session_id=%s";
if (($result = $this->db->execute($query, $this->session_id)) == false) {
/* New session
*/
$session_data = array(
"id" => null,
"session_id" => $this->session_id,
"content" => null,
"expire" => date("Y-m-d H:i:s", time() + SESSION_TIMEOUT),
"user_id" => null,
"ip_address" => $_SERVER["REMOTE_ADDR"],
"name" => null);
$this->db->insert("sessions", $session_data);
$this->id = $this->db->last_insert_id;
} else {
/* Existing session
*/
$this->id = (int)$result[0]["id"];
$_SESSION = json_decode($result[0]["content"], true);
}
}
/* Destructor
*
* INPUT: -
* OUTPUT: -
* ERROR: -
*/
public function __destruct() {
if ($this->use_database == false) {
return;
}
$session_data = array(
"content" => json_encode($_SESSION),
"expire" => date("Y-m-d H:i:s", time() + SESSION_TIMEOUT),
"ip_address" => $_SERVER["REMOTE_ADDR"]);
$this->db->update("sessions", $this->id, $session_data);
$_SESSION = array();
}
/* Start session
*
* INPUT: -
* OUTPUT: -
* ERROR: -
*/
public function start() {
if ($this->use_database) {
/* Use database
*/
if (isset($_COOKIE[SESSION_NAME]) == false) {
$this->session_id = md5(time().$this->settings->secret_website_code);
$timeout = is_true(SESSION_PERSISTENT) ? time() + SESSION_TIMEOUT : null;
setcookie(SESSION_NAME, $this->session_id, $timeout);
$_COOKIE[SESSION_NAME] = $this->session_id;
} else {
$this->session_id = $_COOKIE[SESSION_NAME];
}
} else {
/* Use PHP's session handling
*/
session_name(SESSION_NAME);
if (is_true(SESSION_PERSISTENT)) {
session_set_cookie_params(SESSION_TIMEOUT);
}
session_start();
$this->session_id = session_id();
}
}
/* Update user_id in session record
*
* INPUT: int user id
* OUTPUT: true
* ERROR: false
*/
public function set_user_id($user_id) {
if ($this->use_database == false) {
return true;
}
$user_data = array("user_id" => (int)$user_id);
return $this->db->update("sessions", $this->id, $user_data) !== false;
}
/* Reset session
*
* INPUT: -
* OUTPUT: -
* ERROR: -
*/
public function reset() {
unset($_COOKIE[SESSION_NAME]);
$_SESSION = array();
if ($this->use_database) {
$this->db->query("delete from sessions where id=%s", $this->id);
} else {
session_destroy();
}
$this->start();
}
}
?>