<?php
/**
 * @Cscms 3.5 open source management system
 * @copyright 2009-2013 chshcms.com. All rights reserved.
 * @Author:Cheng Jie
 * @Dtime:2013-04-27
 */
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/*
   ÍøÕ¾»º´æ¼¼Êõ²Ù×÷
*/
 class CsdjCache extends CI_Model
 {
    var $_dir  = '/cache/';
    var $_time = 60;
    var $_id;
    function __construct ()
	{
	   parent:: __construct ();

		$options=array('_dir'=>FCPATH."/cache/".Cache_Name."/index/",'_time'=>Cache_Time);
			$available_options = array('_dir','_time');
			foreach($options as $key => $value){
				if(in_array($key,$available_options)){
					$this->$key = $value;
				}
			}
	}

	function models($dir='index'){
               $this->_dir=FCPATH."/cache/".Cache_Name."/".$dir."/";
        }

	function get($id){
		$this->_id = md5($id."848769359");
		if(file_exists($this->_dir.$this->_id) && ((time() - filemtime($this->_dir.$this->_id)) < $this->_time)){
			if(PHP_VERSION >= '4.3.0'){
				$data = file_get_contents($this->_dir.$this->_id);
			}else{
				$handle = fopen($this->_dir.$this->_id,'rb');
				$data = fread($handle,filesize($this->_dir.$this->_id));
				fclose($handle);
			}
			return $data;
		}else{
			return false;
		}
	}  


	function save($data){
		if(!is_writable($this->_dir)){
			if(!@mkdir($this->_dir,0777,true)){
				echo 'Cache directory not writable';
				exit;
			}
		}
                if(!file_exists($this->_dir.'index.html')){
		    @file_put_contents($this->_dir.'index.html','cscms');
                }
		if(PHP_VERSION >= '5'){
			@file_put_contents($this->_dir.$this->_id,$data);
		}else{
			$handle = fopen($this->_dir.$this->_id,'wb');
			fwrite($handle,$data);
			fclose($handle);
		}
		return true;
	}

	function start($id){
		$data = $this->get($id);
		if($data !== false && Cache_Is==1){
			echo($data);
			return true;
		}
		ob_start();
		ob_implicit_flush(false);
		return false;
	}

	function end(){
		$data = ob_get_contents();
		ob_end_clean();
		if(Cache_Is==1) $this->save($data);
		echo($data);
	}

}

