<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package fusionLib
 * @copyright Copyright (c) 2008 - 2017 fusionLib. All rights reserved.
 * @link http://fusionlib.com
 */

/**
 * flSessionDb Class
 *
 * Class to implement database based sessions.
 *
 * @package fusionLib
 */
class flSessionDb extends flSession {

	/**
	 * The database object.
	 *
	 * @var flDb
	 */
	protected $db;

	/**
	 * Construct and initialize the database session object.
	 *
	 * @param flResponse $response The response object to use.
	 * @param flDb $db The database object.
	 * @param int $life The time in seconds a session should live for, must be greater than 0 or null to use the value of session.gc_maxlifetime.
	 * @param bool $expireCookieOnExit true to expire cookie at the end of the session or false to keep the cookie for the lifetime of the session data.
	 * @param string $cookieName The name of the cookie holding session data.
	 * @param string $cookieDomain The optional domain the cookie is available on, e.g. for all subdomains '.example.com'
	 * @param string $cookiePath The options path the cookie is valid on
	 * @param bool $cookieSecure true to use secure session cookies; else false.
	 */
	function __construct($response, $db, $life = null, $expireCookieOnExit = true, $cookieName = '__sessionid', $cookieDomain = '', $cookiePath = '/', $cookieSecure = false) {
		$this->db = $db;
		parent::__construct($response, $life, $expireCookieOnExit, $cookieName, $cookieDomain, $cookiePath, $cookieSecure);
	}

	/**
	 * @inheritdoc
	 */
	public function read($session_id) {
		$now = new flDate();
		$r = $this->db->fetchOne('SELECT sessiondata FROM fl_session WHERE sessionid=? && sessionexpire>=?', $session_id, $now->toString());
		return $r ? $r : '';
	}

	/**
	 * @inheritdoc
	 */
	public function write($session_id, $session_data) {
		$expire = new flDate('@' . $this->expireat);
		$this->db->query('REPLACE INTO fl_session SET sessionid=?,sessionexpire=?,sessiondata=?', $session_id, $expire->toString(), $session_data);
		return true;
	}

	/**
	 * @inheritdoc
	 */
	public function destroy($session_id) {
		$this->db->query('DELETE FROM fl_session WHERE sessionid=?', $session_id);
		return true;
	}

	/**
	 * @inheritdoc
	 */
	public function gc($maxlifetime) {
		$now = new flDate();
		$this->db->query('DELETE FROM fl_session WHERE sessionexpire<?', $now->toString());
		return true;
	}
}
