<?php
!defined('IN_TOA') && exit('Access Denied!');
/*
	[Office 515158] (C) 2009-2015 天生创想 Inc.
	$Id: function_weixin.php 1209087 2015-01-08
*/
function weixin($data=0){
	global $_CACHE;
	get_cache('weixin_config');
	foreach ( $_CACHE['weixin_config'] as $row) {
		if($row['name']==$data){
			$html=$row[value];
		}
	}
	return $html;
		
}
function Access_Token(){
	global $db;
	$assdate=strtotime(get_date('Y-m-d H:i:s',PHP_TIME))-strtotime(weixin('assdate'));
	if($assdate>=7000){
		$url="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".weixin('CorpID')."&corpsecret=".weixin('Secret')."";
		$res = Utility::HttpRequest($url);
		$res=json_decode($res);
		$db->query("UPDATE ".DB_TABLEPRE."weixin_config set value='".$res->access_token."' WHERE name = 'Access_Token'");
		$db->query("UPDATE ".DB_TABLEPRE."weixin_config set value='".get_date('Y-m-d H:i:s',PHP_TIME)."' WHERE name = 'assdate'");
		oa_mana_recache('weixin_config','name','id');
		//sleep(1);
		//header('Location: http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);
	}
	return weixin('Access_Token');
}
function weixin_code($code='',$state=''){
	$token=Access_Token();
	global $db;
	global $_USER;
	if(!$_USER->Id){
		//setcookie("UserId",'', time()-3600);
		$urllist="https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=".$token."&code=".$code."";
		$res1 = Utility::HttpRequest($urllist);
		$res=json_decode($res1);
		$row = $db->fetch_one_array("SELECT a.id,a.jituanid,a.username,a.password FROM ".DB_TABLEPRE."user a,".DB_TABLEPRE."weixin_member b WHERE b.userid=a.id and b.weixinid= '".$res->UserId."'");
		if (trim($row['id'])) {
			$flag = $_USER->publiclogin($row['username'], $row['password']);
			return trim($row['id']);
		}
	}
	return 'error';
}
function weixinsms($person=0,$content){
	global $db;
	global $_USER;
	if(mysql_num_rows(mysql_query("SHOW TABLES LIKE 'toa_weixin_config'"))==1){
		//获取数据，判断在线的不发，没有关注的不发送
		$persons=get_realid($person);
		if($person=='0'){
			$sql = "SELECT weixinid FROM ".DB_TABLEPRE."weixin_member where userid!='0'";
		}else{
			if(trim($persons)!=''){
				$where="  userid in(".$persons.")";
			}else{
				$where=" userid=-1";
			}
			$sql = "SELECT weixinid FROM ".DB_TABLEPRE."weixin_member where ".$where;
		}
		$query = $db->query($sql);
		//$department='';
		$userid='';
		while ($row = $db->fetch_array($query)) {
			//$department.=$row['department'].'|';
			$userid.=$row['weixinid'].'|';
		}
		if(substr($userid, 0, -1)!=''){
			$token=Access_Token();
			$url="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=".$token."";
			$html='{
			   "touser": "'.substr($userid, 0, -1).'",
			   "toparty": "",
			   "totag": "",
			   "msgtype": "text",
			   "agentid": "'.weixin('AppID').'",
			   "text": {
				   "content": "'.$content.'"
			   },
			   "safe":"0"
			}';
			Utility::POST($url,$html);
		}
	}
	return;
}

?>