<?php
/**
 * SessionHandler storage implementation for PHP's built-in session handler.
 * This doesn't do any session handling itself - instead, it exists to allow
 * utility features to be used with the built-in PHP handler.
 *
 * Copyright 2005-2017 Horde LLC (http://www.horde.org/)
 *
 * See the enclosed file COPYING for license information (LGPL). If you
 * did not receive this file, see http://www.horde.org/licenses/lgpl21.
 *
 * @author   Matt Selsky <selsky@columbia.edu>
 * @category Horde
 * @license  http://www.horde.org/licenses/lgpl21 LGPL 2.1
 * @package  SessionHandler
 */
class Horde_SessionHandler_Storage_Builtin extends Horde_SessionHandler_Storage
{
    /**
     * Directory with session files.
     *
     * @var string
     */
    protected $_path;

    /**
     */
    public function __construct(array $params = array())
    {
        parent::__construct($params);

        $this->_path = session_save_path();
        if (!$this->_path) {
            $this->_path = sys_get_temp_dir();
        }
    }

    /**
     */
    public function open($save_path = null, $session_name = null)
    {
    }

     /**
      */
    public function close()
    {
    }

    /**
     */
    public function read($id)
    {
        return strval(@file_get_contents($this->_path . '/sess_' . $id));
    }

    /**
     */
    public function write($id, $session_data)
    {
        return false;
    }

    /**
     */
    public function destroy($id)
    {
        try {
            $di = new DirectoryIterator($this->_path);
        } catch (UnexpectedValueException $e) {
            return false;
        }

        foreach ($di as $val) {
            /* Make sure we're dealing with files that start with sess_. */
            if ($val->isFile() &&
                ($val->getFilename() == 'sess_' . $id)) {
                return unlink($val->getPathname());
            }
        }

        return false;
    }

    /**
     */
    public function gc($maxlifetime = 300)
    {
        return false;
    }

    /**
     */
    public function getSessionIDs()
    {
        $sessions = array();

        try {
            $di = new DirectoryIterator($this->_path);
        } catch (UnexpectedValueException $e) {
            return $sessions;
        }

        foreach ($di as $val) {
            /* Make sure we're dealing with files that start with sess_. */
            if ($val->isFile() &&
                (strpos($val->getFilename(), 'sess_') === 0)) {
                $sessions[] = substr($val->getFilename(), strlen('sess_'));
            }
        }

        return $sessions;
    }

}
