<?php
/**
 * 
 * @file history.php
 * @copyright (c) 2005 - 2011 eifr.com
 * @license http://www.gnu.org/copyleft/gpl.html gnu/gpl
 * eifr is free software
 */

class CHistory {
    var $cookieName = 'eifrCookieHistory';
    var $maxNumber = 10;
    var $defExpireTime = 0; //until close browser
    var $historyContents = array();

    function __construct() {
        $historyStr =  stripslashes(getCookie($this -> cookieName));
        if ($historyStr != '') {
            Log_d(__FILE__, __LINE__, 'parse history from cookie');
            $this -> historyContents = unserializeFixed($historyStr);
            if(!is_array($this -> historyContents)) {
                $this -> historyContents = array();
                Log_e(__FILE__, __LINE__, "cookie history broken");
            }
        }
    } 

    function getHistory() {
        return $this -> historyContents;
    } 

    /**
     * add an item into the history and save it to the cookie table
     * id is key
     * for example:
     * $item = array('url'=>'http://www.eifr.com', 'title'=>'histroy 1');
     * 
     * @param array $ 
     * @return bool 
     */
    function addHistory($item = array()) {
        if (! $item) {
            Log_e(__FILE__, __LINE__, "Do not allow empty!");
            return false;
        } 
        foreach($this -> historyContents as $key=>$val) {
            if ($item['url'] == $val['url']) {
                //exists, remove this item
                unset($this -> historyContents[$key]);
            }
        }
        
        if(count($this -> historyContents) > $this -> maxNumber-1) {
            array_shift($this -> historyContents);
        }

        array_unshift($this -> historyContents, $item);
        $this -> _saveHistory();
        return true;
    }


    function emptyHistory() {
        unset($this -> historyContents);
        $this -> historyContents = array();
        delCookie($this -> cookieName);
    }

    function _saveHistory() {
        Log_v(__FILE__, __LINE__, "history count:" . count($this -> historyContents));
        addCookie($this -> cookieName, serialize($this -> historyContents), $this -> defExpireTime);
    }

} 

?>
