<?php
/**************************************************
*  Created:  2010-06-28
*
*  用户配置项管理类
*
*  @Xweibo (C)1996-2099 SINA Inc.
*  @Author zhenquan <zhenquan@staff.sina.com.cn>
*
***************************************************/
class sysConfig{
	var $data = array();

	/**
	 * 更新缓存数据
	 */
	function rebuild() {
		$db = APP::ADP('db');
		$data = $db->query('SELECT *FROM ' . $db->getTable(T_SYS_CONFIG));
		
		$this->data = array();
		if (!empty($data) && is_array($data)) {
		foreach  ($data as $r) {
			$this->data[$r['key']] = $r['value'];
		}
		CACHE::set(CACHE_SYS_CONFIG, $this->data);
		}
	}

	/**
	 * 得到所有缓存数据
	 * @param $rebuild 是否更新缓存数据
	 */
	function getCache($rebuild=false) {
		static $d = null;
		if ($rebuild) {
			$this->rebuild();
		}
		if ($d === null || $rebuild) { 
			$d = CACHE::get(CACHE_SYS_CONFIG);
		}
		return $d;
	}

	/**
	 * 设置一配置项
	 * @param $key string 要设置的键值
	 * @param $value string 要设置的值
	 */
	function set($key, $value='') {
		if (!is_array($key)) {
			$key = array($key => $value);
		}
		$this->data = array_merge($this->data, $key);
	}

	/**
	 * 返回设置项
	 * @param $index 配置项键名
	 * @param $default 默认值
	 */
	function get($index = null, $default=null) {
		$d = $this->getCache();
		if ($d === null || $d === false) {
			$d = $this->getCache(true);
		}
		if ($index === null) {
			return $d;
		}
		if (is_array($index)) {
			$data = array();
			foreach ($index as $k) {
				if (isset($d[$k])) {
					$data[$key] = $d[$k];
				}
			}
			return $data;
		}
		if (isset($d[$index])) {
			return $d[$index];
		}
		if ($default !== null) {
			return $default;
		}
		return null;
	}

	/**
	 * 删除设置项
	 * @param $key string 要删除的键值
	 */
	function delete($key) {
		if (!isset($this->data[$key])) {
			return true;
		}
		unset($this->data[$key]);
	}

	/**
	 * 清空配置项
	 */
	function reset() {
		$this->data = array();
	}

	/**
	 * 向数据库添加数据
	 */
	function save($clear = false) {
		$db = APP::ADP('db');
		
		$data = array();
		if (empty($this->data)) {
			return false;
		}
		if ($clear) {
			$db->execute('TRUNCATE ' . $db->getTable(T_SYS_CONFIG));
		}
		foreach ($this->data as $key=>$value) {
			$data[] = '("' . $db->escape($key) . '","' . $db->escape($value) .'")';
		}
		$sql = 'REPLACE ' . $db->getTable(T_SYS_CONFIG) . '(`key`,`value`) VALUES' . implode(',', $data);
		$db->execute($sql);
		$this->rebuild();
	}
	
	/// set to global 
	function initToGlobal(){
		$GLOBALS[V_CFG_GLOBAL_NAME]['sysConfig'] = $this->get();
	}
}
