<?php
/*主框架文件*/
if(!defined("MODEL_DIR"))
{
	define("MODEL_DIR","model");
}
if(!defined("CTRL_DIR"))
{
	define("CTRL_DIR","ctrl");
}
if(!defined("ADMIN_DIR"))
{
	define("ADMIN_DIR","admin");
}
if(!defined("SKYMVC_DIR"))
{
define("SKYMVC_DIR",basename(dirname(__FILE__)));
}
if(!defined("ROOT_PATH"))
{
	define("ROOT_PATH",str_replace(str_replace("\\","/",SKYMVC_DIR.'/skymvc.php'), '', str_replace('\\', '/', __FILE__)));
	
}
class skymvc
{
	public $tpl;
	public $db;
	public $time;
	function __construct()
	{
		$this->skymvc();
	}
	function skymvc()
	{
		$_POST = $this->_addslashes($_POST);
		$_GET = $this->_addslashes($_GET);
		$_REQUEST = $this->_addslashes($_REQUEST);
		$this->initsmarty();
		$this->initdb();
		$this->time=time();
		
	}
	
	//实例化模板函数
	function initsmarty()
	{
		require_once(SKYMVC_DIR."/template.class.php");
		$this->tpl =new template("1","default");
			
	}
	//实例化数据库函数
	function initdb()
	{
		date_default_timezone_set('PRC'); 
		require_once(SKYMVC_DIR."/mysqldb.php");
		if(defined("MYSQL_HOST"))
		{
		$this->db= new mysqldb(MYSQL_HOST,MYSQL_USER,MYSQL_PWD,MYSQL_DB,CHARSET);
		}
	}
	/**
	 * 邮件发送
	 * $smptArr 邮件配置 array('服务器' ,'端口' ,'邮箱' ,'用户名' ,'密码');
	 * @param: $smtpemailto     接收人邮件地址
	 * @param:  $mailsubject     邮件标题
	 * @param:  $mailbody    邮件内容
	 * @param: $mailtype         0 普通邮件， 1 HTML邮件
	 * @return boolean
	 */
	
	function send_mail($smptArr, $smtpemailto, $mailsubject, $mailbody , $mailtype="html")
	{
		require_once (SKYMVC_DIR."/smtp.php");
		$smtpserver = $smptArr[0];//SMTP服务器
		$smtpserverport =$smptArr[1];//SMTP服务器端口
		$smtpusermail = $smptArr[2];//SMTP服务器的用户邮箱
		$smtpuser = $smptArr[3];//SMTP服务器的用户帐号
		$smtppass = $smptArr[4];//SMTP服务器的用户密码
		//开始发送
		$smtp = new smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);
		$smtp->debug = TRUE;//是否显示发送的调试信息
		return $smtp->sendmail($smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype);
	
	}
	
	//载入模块函数
	function loadModel($model,$base= NULL )
	{
		$base=$base?$base:$this;
		if(empty($_ENV[$model.'Model']))
		{
			require_once MODEL_DIR."/$model.model.php";
			eval('$_ENV[$model.\'Model\'] =new '.$model.'Model($base);');
		}
		return $_ENV[$model.'Model'];
	}
	//加载后台模块函数
	
	function loadAdminModel($model, $base = NULL) {
		$base = $base ? $base : $this;
		if(empty($_ENV['admin_'.$model.'Model'])) {
			require_once ADMIN_DIR."/model/$model.model.php";
			eval('$_ENV[\'admin_\'.$model.\'Model\'] = new '.$model.'Model($base);');
		}
		return $_ENV['admin_'.$model.'Model'];
	}
	function loadClass($cls)
	{
		@require_once(SKYMVC."/cls/cls_{$cls}.php");
	}

	
	//字符串转义函数	
	function _addslashes($string, $force = 0, $strip = FALSE) {
		if(!MAGIC_QUOTES_GPC || $force) {
			if(is_array($string)) {
				foreach($string as $key => $val) {
					$string[$key] = $this->_addslashes($val, $force, $strip);
				}
			} else {
				$string = addslashes($strip ? stripslashes($string) : $string);
			}
		}
		return $string;
	}
	
	//设置cookie函数
	function _setcookie($key, $value, $life = 0, $httponly = false) {
		if($value == '' || $life < 0) {
			$value = '';
			$life = -1;
		}
		if(!defined("COOKIE_DOMAIN"))
		{
			define("COOKIE_DOMAIN",$_SERVER['HTTP_HOST']);
		}
		$life = $life > 0 ? $this->time + $life : ($life < 0 ? $this->time - 31536000 : 0);
		$path = $httponly && PHP_VERSION < '5.2.0' ? COOKIE_PATH."; HttpOnly" : COOKIE_PATH;
		$secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
		if(PHP_VERSION < '5.2.0') {
			setcookie(COOKIE_PRE.$key, $value, $life, $path, COOKIE_DOMAIN, $secure);
		} else {
			setcookie(COOKIE_PRE.$key, $value, $life, $path, COOKIE_DOMAIN, $secure, $httponly);
		}
	}

	/**
	 * 将数组元素格式化成类似 '1','2','3' 的字符串
	 * @return STRING 字串 否则为 NULL
	*/
	function _implode($array) {
		if(!empty($array)) {
			return "'".implode("','", is_array($array) ? $array : array($array))."'";
		} else {
			return '';
		}
	}
	//获取前一页地址
	function referer() {
		
		$referer = '';
		if(empty($_POST['referer']) && isset($GLOBALS['_SERVER']['HTTP_REFERER'])) {
			$referer = preg_replace("/([\?&])((sid\=[a-z0-9]{6})(&|$))/i", '\\1', $GLOBALS['_SERVER']['HTTP_REFERER']);
			$referer = (substr($referer, -1) == '?') || (substr($referer, -1) == '&') ? substr($referer, 0, -1) : $referer;
		} elseif(!empty($_POST['referer'])) {
			$referer = str_replace('&amp;', '&', htmlspecialchars($_POST['referer']));
		}
		return $referer;
	}
	//跳转函数
	function _header($string, $replace = true, $http_response_code = 0) {
		$redirect = preg_match('/^\s*location:/is', $string) ? true : false;
		$string = str_replace(array("\r", "\n"), array('', ''), $string);
		@header($string, $replace, $http_response_code);
	}
	//截取字符串函数
	function cutstr($string, $length, $dot = ' ...') {
		if(strlen($string) <= $length) {
			return $string;
		}

		$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);

		$strcut = '';
		if(strtolower(CHARSET) == 'utf-8') {

			$n = $tn = $noc = 0;
			while($n < strlen($string)) {

				$t = ord($string[$n]);
				if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
					$tn = 1; $n++; $noc++;
				} elseif(194 <= $t && $t <= 223) {
					$tn = 2; $n += 2; $noc += 2;
				} elseif(224 <= $t && $t < 239) {
					$tn = 3; $n += 3; $noc += 2;
				} elseif(240 <= $t && $t <= 247) {
					$tn = 4; $n += 4; $noc += 2;
				} elseif(248 <= $t && $t <= 251) {
					$tn = 5; $n += 5; $noc += 2;
				} elseif($t == 252 || $t == 253) {
					$tn = 6; $n += 6; $noc += 2;
				} else {
					$n++;
				}

				if($noc >= $length) {
					break;
				}

			}
			if($noc > $length) {
				$n -= $tn;
			}

			$strcut = substr($string, 0, $n);

		} else {
			for($i = 0; $i < $length; $i++) {
				isset($string[$i]) && $strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
			}
		}

		$strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);

		return $strcut.$dot;
	}
	/**
	@分页程序
	@$num	记录总数
	@$perpage 每页记录数
	@$curpage 当前页
	@$mpurl		分页的地址
	@$page		显示多少个分页
	*/
	function multipage($num, $perpage, $curpage, $mpurl,$page=10) {
		
		$shownum = $showkbd = FALSE;
		$multipage = '';
		$mpurl .= strpos($mpurl, '?') ? '&amp;' : '?';
		$page=10;
		$realpages = 1;
		if($num > $perpage) {
			$offset = 2;

			$realpages = @ceil($num / $perpage);
			$pages = $maxpages && $maxpages < $realpages ? $maxpages : $realpages;

			if($page > $pages) {
				$from = 1;
				$to = $pages;
			} else {
				$from = $curpage - $offset;
				$to = $from + $page - 1;
				if($from < 1) {
					$to = $curpage + 1 - $from;
					$from = 1;
					if($to - $from < $page) {
						$to = $page;
					}
				} elseif($to > $pages) {
					$from = $pages - $page + 1;
					$to = $pages;
				}
			}

			$multipage = ($curpage > 1 && !$simple ? '<a href="'.$mpurl.'page='.($curpage - 1).'" class="prev" > 首页</a>' : '').
				($curpage - $offset > 1 && $pages > $page ? '<a href="'.$mpurl.'page=1" class="first" >1 ...</a>' : '');
			for($i = $from; $i <= $to; $i++) {
				$multipage .= $i == $curpage ? '<strong>'.$i.'</strong>' :
				'<a href="'.$mpurl.'page='.$i.'">'.$i.'</a>';
			}

			$multipage .= ($to < $pages ? '<a href="'.$mpurl.'page='.$pages.'" class="last" >... '.$realpages.'</a>' : '').
			($curpage < $pages && !$simple ? '<a href="'.$mpurl.'page='.($curpage + 1).'" class="next" >下一页</a>' : '');

			$multipage = $multipage ? '<div class="pages">'.($shownum && !$simple ? '<em>&nbsp;'.$num.'&nbsp;</em>' : '').$multipage.'</div>' : '';
		}
		$maxpage = $realpages;
		return $multipage;
	}

	
	/**
	*字符编码转换函数
	*@$from 原来的字符编码
	*@$to	后来的字符编码
	*@$str	要转换的字符串
	*/
	function iconvstr($from,$to,$str)
	{
		if(empty($str))
		{
			return false;
		}
		if(is_array($str))
		{
			foreach($str as $key=>$val)
			{
				$str[$key]=iconvstr($from,$to,$val);
			}
			
			
		}else
		{
			$str=iconv($from,$to,$str);
		}
		
		return $str;
	}
	
	/*
	@获取真实ip函数
	*/
	function realip()
	{
	   if(isset($_SERVER['HTTP_CLIENT_IP']))
	   {
		  $realip = $_SERVER['HTTP_CLIENT_IP'];
	   }elseif (isset($_SERVER['REMOTE_ADDR']))
	   {
			$realip = $_SERVER['REMOTE_ADDR'];
	   }
		
	
		preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
		$realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
		return $realip;
	}
	
	/**
	@删除当前目录及文件
	*/
	function deldir($dir)
	{
		if(!is_dir($dir)) return false;
		$dh=opendir($dir);
		while(($file=readdir($dh))!==false)
		{
			if($file!="." && $file!="..")
			{
				if(is_dir($dir."/".$file))
				{
					deldir($dir."/".$file);	
				}else
				{
					unlink($dir."/".$file);
				}
			}
		}
		closedir($dh);
		rmdir($dir);
		
	}
	/**
	@删除目录下的所有文件 保留当前目录
	*/
	function delfile($dir)
	{
		$hd=opendir($dir);
		while(($f=readdir($hd))!=false)
		{
			if($f!=".." and $f!=".")
			{
				if(is_file($dir.$f)){
					unlink($dir.$f);
				}else
				{
					delfile($dir.$f."/");
				}
			}
		}
	}	
	/*创建文件夹*/
	function umkdir($dir)
	{
		$arr=explode("/",$dir);
		foreach($arr as $key=>$val)
		{
			$d="";
			for($i=0;$i<=$key;$i++)
			{
				$d.=$arr[$i]."/";
			}
			if(!file_exists($d) && (strpos($val,":")==false))
			{
				mkdir($d,0755);
			}
		}
	}
	
/**
 * 验证输入的邮件地址是否合法
 *
 * @access  public
 * @param   string      $email      需要验证的邮件地址
 *
 * @return bool
 */
function is_email($user_email)
{
    $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
    if (strpos($user_email, '@') !== false && strpos($user_email, '.') !== false)
    {
        if (preg_match($chars, $user_email))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}


}

?>