<?php
/* 
 * This library contains PoorSession implementation for PHP.
 * 
 * Copyright (c) 2011, Ondřej Tůma (McBig) All rights reserved.
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *     * Neither the name of the University of California, Berkeley nor the names
 *       of its contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *       
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

function hidden($text, $passwd){
    $passwd = sha1($passwd, true);
    $plen = strlen($passwd);
    $tlen = strlen($text);
    $rv = '';

    for($i = 0; $i < $tlen; $i++){
        $rv .= chr(ord($text[$i]) ^ ord($passwd[$i % $plen]));
    }
    return $rv;
}

// Session tvorime samonosnou cookie, pro tyto ucely to staci a je to lepsi
class PoorSession {

    function __construct($secret, $expire = 0, $path = '/', $SID = 'SESSID'){
        $this->secret = $secret;
        $this->SID = $SID;
        $this->expire = $expire;
        $this->path = $path;
        $this->data = array();

        $this->raw = null;
        
        # get SID from cookie
        if (isset($_COOKIE[$SID]))
            $this->raw = $_COOKIE[$SID];   

        if ($this->raw){
            try {
                $this->data = unserialize(hidden(
                        bzdecompress(base64_decode($this->raw)),
                        $this->secret));
                if ($this->data === false || !is_array($this->data))
                    //throw new Exception('');  
                    error_log('Bad session data.');
                    
            } catch (Exception $e) {
                error_log('Bad session data.');
            }

            if (isset($this->data['expire']) && $this->data['expire'] < time()){
                error_log('Session was expired, generating new.');
                $this->data = array();
            }
        }
    }

    function write(){
        if ($this->expire){
            $this->data['expire'] = time() + $this->expire;
        }

        $this->raw = base64_encode(bzcompress(
                hidden(serialize($this->data), $this->secret)));
    }

    function renew(){
        if ($this->expire){
            $this->data['expire'] = time() + $this->expire;
            return;
        }

        if (array_key_exists('expire', $this->data))
            unset($this->data['expire']);
    }

    function destroy(){
        $this->data = array();
        $this->expire = -60*60*24*365;      // year back in time
    }

    function send(){
        $this->write();
        return setcookie(
                $this->SID,     // cookie variable name
                $this->raw,     // cookie data
                ($this->expire) ? $this->data['expire'] : 0,
                $this->path);
    }
}


?>
