<?php

//记录金钱日志--（目前只记录分红功能）
function insertMoneySql($username,$money,$benmoney,$countmoney,$sql){

	$MoneySql = D('MoneySql');
	$date['username']   = $username;
	$date['benmoney']   = $benmoney;
	$date['money'] 	    = $money;
	$date['countmoney'] = $countmoney;
	$date['sql'] 	    = $sql;
	$MoneySql->add($date);
}

//用账号查询账号ID
function idToUser($username){
	
	$Member = D('Member');
	$date['username']   = $username;
	$result = $Member->field('id')->where($date)->find();	
	return $result['id'];
}



//返回充值订单号
function ordernumber(){
	return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

//返回账号银行
function checkBank($username){

	$Member = D('Member');
	$Result = $Member->where("username = '{$username}'")->find();
	return $Result;
}

//返回项目的分类
function projectName($classid){

	$ProjectClassid = D('ProjectClassid');
	$Result = $ProjectClassid->where("id = {$classid}")->find();
	return $Result['name'];
}

//返回帮助的分类
function helpName($classid){

	$HelpCategory = D('HelpCategory');
	$Result = $HelpCategory->where("id = {$classid}")->find();
	return $Result['name'];
}


//发送msg记录
function sendMsg($username,$compnayN,$title,$content,$memo){

	$MemberMsg = D('MemberMsg');
	$data['username']  = $username;
	$data['title']     = $title;
	$data['content']   = $content;
	$data['from_name'] = $memo;
	$data['posttime']  = time();
	$data['status']    = 0;
	$MemberMsg->add($data);
}

//金额消费记录,$type:加减
function meoneyLog($user,$money,$notice,$type){
 
  	$thisMoney = returnAmount($user);
  	if($type == '+'){
  		$trandMoney = $thisMoney + $money;
  	}else{
  		$trandMoney = $thisMoney - $money;
  	}

	$Moneylog = D('Moneylog');
	$data['moneylog_user']   = $user;
	$data['moneylog_time']   = date('Y-m-d H:i:s',time());
	$data['moneylog_money']  = $money;
	$data['moneylog_ip']     = getip();
	$data['moneylog_notice'] = $notice;
	$data['moneylog_yuanamount'] = floatval($thisMoney);
	$data['moneylog_houamount']  = floatval($trandMoney);
	$Moneylog->add($data);
}

//查询该账户金额
function returnAmount($username){

	$Member = D('Member');
	$result = $Member->field('amount')->where("username = '{$username}'")->find();	
	return $result['amount'];
}


//返回今天星期几
function weekname($time){

	$weekarray=array("日","一","二","三","四","五","六");
	return "星期".$weekarray[$time];
}

function DateAdd($part, $number, $date){
	$date_array = getdate(strtotime($date));
	$hor = $date_array["hours"];
	$min = $date_array["minutes"];
	$sec = $date_array["seconds"];
	$mon = $date_array["mon"];
	$day = $date_array["mday"];
	$yar = $date_array["year"];
	switch($part){
		case "y": $yar += $number; break;
		case "q": $mon += ($number * 3); break;
		case "m": $mon += $number; break;
		case "w": $day += ($number * 7); break;
		case "d": $day += $number; break;
		case "h": $hor += $number; break;
		case "n": $min += $number; break;
		case "s": $sec += $number; break;
	}
	return date("Y-m-d H:i:s", mktime($hor, $min, $sec, $mon, $day, $yar));
}

function mymd5($string,$action="EN")
{
	return $string;
	// global $webdb,$onlineip;
	// $secret_string = $webdb[mymd5].'5*j,.^&;?.%#@!';
	// if($string=="") return "";
	// if($action=="EN") $md5code=substr(md5($string),8,10);
	// else
	// {
	// $md5code=substr($string,-10);
	// $string=substr($string,0,strlen($string)-10);
	// }
	// $key = md5($md5code.$secret_string);
	// $string = ($action=="EN"?$string:base64_decode($string));
	// $len = strlen($key);
	// $code = "";
	// for($i=0;$i<strlen($string);$i++)
	// {
	// $k = $i%$len;
	// $code .= $string[$i]^$key[$k];
	// }
	// $code = ($action == "DE"?(substr(md5($code),8,10)==$md5code?$code:NULL) : base64_encode($code)."$md5code");
	// return $code;
}

function adminmymd5($string,$action="EN")
{
	global $webdb,$onlineip;
	$secret_string = $webdb[mymd5].'5*j,.^&;?.%#@!';
	if($string=="") return "";
	if($action=="EN") $md5code=substr(md5($string),8,10);
	else
	{
	$md5code=substr($string,-10);
	$string=substr($string,0,strlen($string)-10);
	}
	$key = md5($md5code.$secret_string);
	$string = ($action=="EN"?$string:base64_decode($string));
	$len = strlen($key);
	$code = "";
	for($i=0;$i<strlen($string);$i++)
	{
	$k = $i%$len;
	$code .= $string[$i]^$key[$k];
	}
	$code = ($action == "DE"?(substr(md5($code),8,10)==$md5code?$code:NULL) : base64_encode($code)."$md5code");
	return $code;
}

function postData($url) {  
    $ch = curl_init($url) ;  
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回  
	curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回  
	return $output = curl_exec($ch) ; 
}  


/**
 * clearCore()
 * 更新缓存
 */
function clearCore(){
	delFile('./AdminApp/Runtime/Cache');
	delFile('./AdminApp/Runtime/Data/_fields');
	delFile('./AdminApp/Runtime/Logs');
	delFile('./AdminApp/Runtime/Temp');
	@unlink('./AdminApp/Runtime/~app.php');
	@unlink('./AdminApp/Runtime/~runtime.php'); 
}

//返回当天竞彩日期
function raceToday(){
	date_default_timezone_set('PRC');
	return date('Y').sprintf("%05d", date('z'));
}
//查询账号等级
function checkrankname($rank){
	
	$memberLevel = D('memberLevel');
	$rank = $memberLevel->where("id = '{$rank}'")->find();
	return $rank['name'];
}

//
function checkactive($activeId){
	if($activeId == 1){
		return '已激活';
	}else{
		return '未激活';
	}
}

/**
 * getCategory()
 *
 */
function getCategory($array,$parentid = 0,$level = 0,$add = 2,$repeat = '　'){
	$str_repeat = '|-- ';
	if($level) {
		for($j=0;$j<$level;$j++) {
			$str_repeat = $repeat.$str_repeat;
		}
	}
	$newarray = array();
	$temparray = array();
	
	foreach((array)$array as $v) {
		if($v['parentid'] == $parentid) {
			$newarray[] = array(
			'id'=>$v['id'],
			'classname'=>$v['classname'],
			'parentid'=>$v['parentid'],
			'level'=>$level,
			'str_repeat'=>$str_repeat
			);
			$temparray = getCategory($array,$v['id'],($level +$add));
			if($temparray) {
				$newarray = array_merge($newarray,$temparray);
			}
		}
	}
	return $newarray;
}

/**
 * buildSelect()
 *
 */
function buildSelect($data,$parentId = 0,$selected = 0,$str = ''){
	$formatArray = getCategory($data,$parentId);
	foreach ((array)$formatArray as $row){
		if($row['id'] == $selected){
			$str .= '<option value="'.$row['id'] .'" selected="selected">'.$row['str_repeat'] .$row['classname'] .'</option>';
		}
		else{
			$str .= '<option value="'.$row['id'] .'">'.$row['str_repeat'] .$row['classname'] .'</option>';
		}
	}
	return $str;
}

/**
 * selected()
 * 
 */
function selected($string,$param =1,$type = 'select'){
	$str = '';
	if($string == $param){
		$str = $type == 'select' ? 'selected="selected"' : 'checked="checked"';
	}
	return $str;
}

/**
 * explodeRole()
 *
 */
function explodeRole($permission,$inData = '',$field = 'permission'){
	if(!empty($permission)){
		$str = '';
		$pmArray = explode('|',$permission);
		foreach ((array)$pmArray as $row){
			$subRow = explode('=',$row);
			if(in_array($subRow[1],explode(',',$inData))){
				$str .= '<span style="float:left; width:10%;"><input name="'.$field.'[]" type="checkbox" id="'.$field.'[]" value="'.trim($subRow[1]).'" checked="checked"/>'.trim($subRow[0]).'</span>';
			}
			else{
				$str .= '<span style="float:left; width:10%;"><input name="'.$field.'[]" type="checkbox" id="'.$field.'[]" value="'.trim($subRow[1]).'" />'.trim($subRow[0]).'</span>';
			}
		}
		return $str;
	}
}

/**
 * getip()
 *
 */
function getip(){
	if(isset($_SERVER['HTTP_CLIENT_IP']) and !empty($_SERVER['HTTP_CLIENT_IP'])){
		return $_SERVER['HTTP_CLIENT_IP'];
	}
	if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) and !empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
		return strtok($_SERVER['HTTP_X_FORWARDED_FOR'], ',');
	}
	if(isset($_SERVER['HTTP_PROXY_USER']) and !empty($_SERVER['HTTP_PROXY_USER']))	{
		return $_SERVER['HTTP_PROXY_USER'];
	}
	if(isset($_SERVER['REMOTE_ADDR']) and !empty($_SERVER['REMOTE_ADDR'])){
		return $_SERVER['REMOTE_ADDR'];
	}
	else{
		return "0.0.0.0";
	}
}

/**
 * msubstr()
 * 字符串截取
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
    $str = strip_tags($str);//去除html标签
    $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
    preg_match_all($re[$charset], $str, $match);
    $str_lenth = count($match[0]);
	if(function_exists("mb_substr")){ 
		if($suffix && $str_lenth>$length){
			return mb_substr($str, $start, $length, $charset)."...";
		}
		else{
			return mb_substr($str, $start, $length, $charset);
		}
	}
	elseif(function_exists('iconv_substr')) {
		if($suffix && $str_lenth>$length){
			return iconv_substr($str,$start,$length,$charset)."...";
		}
		else{
			return iconv_substr($str,$start,$length,$charset); 
		}
	}    
}



/**
 * delFile()
 * 删除文件夹文件
 */
function delFile($directory){
	if(is_dir($directory) != false){
		$handle = opendir($directory);
		while (($file = readdir($handle)) !== false){
			if($file != "." && $file != ".." && is_file("$directory/$file")){
				@unlink("$directory/$file");
			}
		}
		closedir($handle);
	}
}

/**
 * getContent()
 * 
 */
function getContent($file = NULL,$path = NULL){
	$gFile = empty($file) ? exit('error function getFile: file is LOST') : $file ;
	$getPath = empty($path) ? '.' : $path ;
	$getFile = $getPath .'/'.$gFile;
	if(!file_exists($getFile)) die("file:$getFile is LOST");
	return @require($getFile);
}

/**
 * putContent()
 * 
 */
function putContent($data,$file = NULL,$path = NULL){
	$pFile = empty($file) ? exit('error function getFile: file is LOST') : $file ;
	$pPath = empty($path) ? '.' : $path ;
	if ($path != '.'){
		if(!is_dir($pPath)){
			@mk_dir($pPath);
		}
	}
	$putFile = $pPath.'/'.$pFile;
	@file_put_contents($putFile,$data);
}
?>