添加后台代理代码

This commit is contained in:
2026-03-15 01:27:05 +08:00
parent 11f9ac4dc1
commit ea08c9366a
5254 changed files with 721042 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
<?php
define('IN_IA', true);
define('STARTTIME', microtime());// 返回当前 Unix 时间戳和微秒数
// 定义系统根目录
define('IA_ROOT', str_replace("\\", '/', dirname(dirname(__FILE__))));
define('TIMESTAMP', time());
$_W = array();
$_W['charset'] = "utf8";
// 加载系统加载器
require IA_ROOT . '/framework/class/loader.class.php';
require IA_ROOT.'/framework/class/weixin.account.class.php';
load()->func('global');
load()->func('compat');
// 加载用户管理模块
load()->model('user');
// 加载缓存处理器
load()->func('cache');
// 得到客户端的IP
define('CLIENT_IP', getip());
error_reporting(0);
//error_reporting(E_ALL | E_STRICT);
// 获取网站根路径
$sitepath = substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/'));
// 网站访问根url
$_W['siteroot'] = htmlspecialchars('http://' . $_SERVER['HTTP_HOST'] . $sitepath);
if(substr($_W['siteroot'], -1) != '/') {
$_W['siteroot'] .= '/';
}

View File

@@ -0,0 +1,98 @@
<?php
defined('IN_IA') or exit('Access Denied');
function load() {
static $loader;
if(empty($loader)) {
$loader = new Loader();
}
return $loader;
}
class Loader {
// 缓存数组
private $cache = array();
// 加载指定的函数文件,并在$cache中做好已经加载成功的标识
function func($name) {
global $_W;
if (isset($this->cache['func'][$name])) {
return true;
}
$file = IA_ROOT . '/framework/function/' . $name . '.func.php';
if (file_exists($file)) {
include $file;
$this->cache['func'][$name] = true;
return true;
} else {
trigger_error('Invalid Helper Function /framework/function/' . $name . '.func.php', E_USER_ERROR);
return false;
}
}
// 加载指定的model并在$cache用cache['model']的方式标识好是否加载成功
function model($name) {
global $_W;
if (isset($this->cache['model'][$name])) {
return true;
}
$file = IA_ROOT . '/framework/model/' . $name . '.mod.php';
if (file_exists($file)) {
include $file;
$this->cache['model'][$name] = true;
return true;
} else {
trigger_error('Invalid Model /framework/model/' . $name . '.mod.php', E_USER_ERROR);
return false;
}
}
// 加载指定的类,并在$cache用cache['class']的方式标识好是否加载成功
function classs($name) {
global $_W;
if (isset($this->cache['class'][$name])) {
return true;
}
$file = IA_ROOT . '/framework/class/' . $name . '.class.php';
if (file_exists($file)) {
include $file;
$this->cache['class'][$name] = true;
return true;
} else {
trigger_error('Invalid Class /framework/class/' . $name . '.class.php', E_USER_ERROR);
return false;
}
}
function web($name) {
global $_W;
if (isset($this->cache['web'][$name])) {
return true;
}
$file = IA_ROOT . '/web/common/' . $name . '.func.php';
if (file_exists($file)) {
include $file;
$this->cache['web'][$name] = true;
return true;
} else {
trigger_error('Invalid Web Helper /web/common/' . $name . '.func.php', E_USER_ERROR);
return false;
}
}
// 加载指定的前端app函数并在$cache用cache['app']的方式标识好是否加载成功
function app($name) {
global $_W;
if (isset($this->cache['app'][$name])) {
return true;
}
$file = IA_ROOT . '/app/common/' . $name . '.func.php';
if (file_exists($file)) {
include $file;
$this->cache['app'][$name] = true;
return true;
} else {
trigger_error('Invalid App Function /app/common/' . $name . '.func.php', E_USER_ERROR);
return false;
}
}
}

View File

@@ -0,0 +1,504 @@
<?php
defined('IN_IA') or exit('Access Denied');
load()->func('communication');
class WeiXinAccount
{
protected $account = null;// 公众号信息
public function __construct($account = array())
{
// 初始化子公号信息
$this->account = $account;
}
// 通过微信接口获得粉丝信息
public function fansQueryInfo($uniid, $db, $pdo, $isOpen = true)
{
if ($isOpen) {
$openid = $uniid;
} else {
exit('error');
}
$token = $this->getAccessToken($db, $pdo);
if (is_error($token)) {
return $token;
}
$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$token}&openid={$openid}&lang=zh_CN";
$response = ihttp_get($url);
if (is_error($response)) {
return error(-1, "访问公众平台接口失败, 错误: {$response['message']}");
}
$result = @json_decode($response['content'], true);
if (empty($result)) {
return error(-1, "接口调用失败, 元数据: {$response['meta']}");
} elseif (!empty($result['errcode'])) {
return error(-1, "访问微信接口错误, 错误代码: {$result['errcode']}, 错误信息: {$result['errmsg']},错误详情:{$this->error_code($result['errcode'])}");
}
return $result;
}
public function fansBatchQueryInfo($data, $db)
{
if (empty($data)) {
return error(-1, '粉丝openid错误');
}
foreach ($data as $da) {
$post[] = array(
'openid' => trim($da),
'lang' => 'zh-CN',
);
}
$data = array();
$data['user_list'] = $post;
$token = $this->getAccessToken($db);
if (is_error($token)) {
return $token;
}
$url = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token={$token}";
$response = ihttp_post($url, json_encode($data));
if (is_error($response)) {
return error(-1, "访问公众平台接口失败, 错误: {$response['message']}");
}
$result = @json_decode($response['content'], true);
if (empty($result)) {
return error(-1, "接口调用失败, 元数据: {$response['meta']}");
} elseif (!empty($result['errcode'])) {
return error(-1, "访问微信接口错误, 错误代码: {$result['errcode']}, 错误信息: {$result['errmsg']},错误详情:{$this->error_code($result['errcode'])}");
}
return $result['user_info_list'];
}
// 获得微信调用accessToken
public function getAccessToken($db, $pdo)
{
load()->func('communication');
// 此处改动过
$cachekey = "accesstoken:{$this->account['key']}";
$cache = cache_load($cachekey, $db);
$timeFlag = $cache['expire'] > TIMESTAMP;
if (!empty($cache) && !empty($cache['token']) && $cache['expire'] > TIMESTAMP) {
$this->account['access_token'] = $cache;
return $cache['token'];
}
if (empty($this->account['key']) || empty($this->account['secret'])) {
return error('-1', '未填写公众号的 appid 或 appsecret');
}
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->account['key']}&secret={$this->account['secret']}";
$content = ihttp_get($url);
if (is_error($content)) {
return error('-2', '获取微信公众号授权失败, 请稍后重试!错误详情: ' . $content['message']);
}
$token = @json_decode($content['content'], true);
if (empty($token) || !is_array($token) || empty($token['access_token']) || empty(
$token['expires_in'])
) {
$errorinfo = substr($content['meta'], strpos($content['meta'], '{'));
$errorinfo = @json_decode($errorinfo, true);
return error('-3', '获取微信公众号授权失败, 请稍后重试! 公众平台返回原始数据为: 错误代码-' . $errorinfo['errcode'] . ',错误信息-' . $errorinfo['errmsg']);
}
$record = array();
$record['token'] = $token['access_token'];
$record['expire'] = TIMESTAMP + $token['expires_in'] - 200;
$this->account['access_token'] = $record;
cache_write($cachekey, $record, $db, $pdo);
return $record['token'];
}
// 通过微信接口获得调用微信JS接口的临时票据
public function getJsApiTicket($db, $pdo)
{
load()->func('communication');
// 首先从本地缓存中查询未过期的JSApi调用票据
$cachekey = "jsticket:{$this->account['key']}";
$cache = cache_load($cachekey, $db);
if (!empty($cache) && !empty($cache['ticket']) && $cache['expire'] > TIMESTAMP) {
return $cache['ticket'];
}
load()->func('communication');
// 获得微信调用accessToken
$access_token = $this->getAccessToken($db, $pdo);
if (is_error($access_token)) {
return $access_token;
}
// 生成签名之前必须先了解一下jsapi_ticketjsapi_ticket是公众号用于调用
// 微信JS接口的临时票据。正常情况下jsapi_ticket的有效期为7200秒
// 通过access_token来获取。由于获取jsapi_ticket的api调用次数非常有限
// 频繁刷新jsapi_ticket会导致api调用受限影响自身业务开发者必须在自
// 己的服务全局缓存jsapi_ticket。
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi";
$content = ihttp_get($url);
if (is_error($content)) {
return error(-1, '调用接口获取微信公众号 jsapi_ticket 失败, 错误信息: ' . $content['message']);
}
$result = @json_decode($content['content'], true);
if (empty($result) || intval(($result['errcode'])) != 0 || $result['errmsg'] != 'ok') {
return error(-1, '获取微信公众号 jsapi_ticket 结果错误, 错误信息: ' . $result['errmsg']);
}
$record = array();
$record['ticket'] = $result['ticket'];// 临时票据
$record['expire'] = TIMESTAMP + $result['expires_in'] - 200;// 到期时间
$this->account['jsapi_ticket'] = $record;
cache_write($cachekey, $record, $db, $pdo);// 将票据信息回写到缓存中进行缓存
return $record['ticket'];// 返回调用微信JS接口的临时票据
}
// 返回调用微信JS接口的配置数组
public function getJssdkConfig()
{
global $_W;
// 通过微信接口获得调用微信JS接口的临时票据
$jsapiTicket = $this->getJsApiTicket();
if (is_error($jsapiTicket)) {
$jsapiTicket = $jsapiTicket['message'];
}
// 生成指定长度的随机字符
// 第一个参数:要生成的长度
// 第二个参数:是否生成数字形式
$nonceStr = random(16);
$timestamp = TIMESTAMP;// 当前系统时间
$url = $_W['siteurl'];// 当前脚本访问的全路径,包括参数(原始链接)
// 获得jsapi_ticket之后就可以生成JS-SDK权限验证的签名了。
// 拼接待签名的字符串
$string1 = "jsapi_ticket={$jsapiTicket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
// 对字符串进行sha1签名得到signature
$signature = sha1($string1);
// 组装调用配置
$config = array(
"appId" => $this->account['key'],
// 子公号AppId
"nonceStr" => $nonceStr,
// 随机字符
"timestamp" => "$timestamp",
// 当前时间戳
"signature" => $signature,
// 签名
);
// 定义是否为开发者模式
//if(DEVELOPMENT) {
$config['url'] = $url;
$config['string1'] = $string1;
$config['name'] = $this->account['name'];
//}
return $config;
}
// 返回调用微信JS接口的配置数组
public function getAjaxJssdkConfig($siteurl, $db, $pdo)
{
// 通过微信接口获得调用微信JS接口的临时票据
$jsapiTicket = $this->getJsApiTicket($db, $pdo);
if (is_error($jsapiTicket)) {
$jsapiTicket = $jsapiTicket['message'];
}
// 生成指定长度的随机字符
// 第一个参数:要生成的长度
// 第二个参数:是否生成数字形式
$nonceStr = random(16);
$timestamp = TIMESTAMP;// 当前系统时间
$url = $siteurl;// 当前脚本访问的全路径,包括参数(原始链接)
// 获得jsapi_ticket之后就可以生成JS-SDK权限验证的签名了。
// 拼接待签名的字符串
$string1 = "jsapi_ticket={$jsapiTicket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
// 对字符串进行sha1签名得到signature
$signature = sha1($string1);
// 组装调用配置
$config = array(
"appId" => $this->account['key'], // 子公号AppId
"nonceStr" => $nonceStr, // 随机字符
"timestamp" => "$timestamp", // 当前时间戳
"signature" => $signature, // 签名
);
// 定义是否为开发者模式
return $config;
}
// 秘钥错误消息枚举,通过错误消息代码获得消息正文
private function encrypt_error_code($code)
{
$errors = array(
'40001' => '签名验证错误',
'40002' => 'xml解析失败',
'40003' => 'sha加密生成签名失败',
'40004' => 'encodingAesKey 非法',
'40005' => 'appid 校验错误',
'40006' => 'aes 加密失败',
'40007' => 'aes 解密失败',
'40008' => '解密后得到的buffer非法',
'40009' => 'base64加密失败',
'40010' => 'base64解密失败',
'40011' => '生成xml失败',
);
if ($errors[$code]) {
return $errors[$code];
} else {
return '未知错误';
}
}
public function error_code($code)
{
$errors = array(
'-1' => '系统繁忙',
'0' => '请求成功',
'40001' => '获取access_token时AppSecret错误或者access_token无效',
'40002' => '不合法的凭证类型',
'40003' => '不合法的OpenID',
'40004' => '不合法的媒体文件类型',
'40005' => '不合法的文件类型',
'40006' => '不合法的文件大小',
'40007' => '不合法的媒体文件id',
'40008' => '不合法的消息类型',
'40009' => '不合法的图片文件大小',
'40010' => '不合法的语音文件大小',
'40011' => '不合法的视频文件大小',
'40012' => '不合法的缩略图文件大小',
'40013' => '不合法的APPID',
'40014' => '不合法的access_token',
'40015' => '不合法的菜单类型',
'40016' => '不合法的按钮个数',
'40017' => '不合法的按钮个数',
'40018' => '不合法的按钮名字长度',
'40019' => '不合法的按钮KEY长度',
'40020' => '不合法的按钮URL长度',
'40021' => '不合法的菜单版本号',
'40022' => '不合法的子菜单级数',
'40023' => '不合法的子菜单按钮个数',
'40024' => '不合法的子菜单按钮类型',
'40025' => '不合法的子菜单按钮名字长度',
'40026' => '不合法的子菜单按钮KEY长度',
'40027' => '不合法的子菜单按钮URL长度',
'40028' => '不合法的自定义菜单使用用户',
'40029' => '不合法的oauth_code',
'40030' => '不合法的refresh_token',
'40031' => '不合法的openid列表',
'40032' => '不合法的openid列表长度',
'40033' => '不合法的请求字符,不能包含\uxxxx格式的字符',
'40035' => '不合法的参数',
'40038' => '不合法的请求格式',
'40039' => '不合法的URL长度',
'40050' => '不合法的分组id',
'40051' => '分组名字不合法',
'41001' => '缺少access_token参数',
'41002' => '缺少appid参数',
'41003' => '缺少refresh_token参数',
'41004' => '缺少secret参数',
'41005' => '缺少多媒体文件数据',
'41006' => '缺少media_id参数',
'41007' => '缺少子菜单数据',
'41008' => '缺少oauth code',
'41009' => '缺少openid',
'42001' => 'access_token超时',
'42002' => 'refresh_token超时',
'42003' => 'oauth_code超时',
'43001' => '需要GET请求',
'43002' => '需要POST请求',
'43003' => '需要HTTPS请求',
'43004' => '需要接收者关注',
'43005' => '需要好友关系',
'44001' => '多媒体文件为空',
'44002' => 'POST的数据包为空',
'44003' => '图文消息内容为空',
'44004' => '文本消息内容为空',
'45001' => '多媒体文件大小超过限制',
'45002' => '消息内容超过限制',
'45003' => '标题字段超过限制',
'45004' => '描述字段超过限制',
'45005' => '链接字段超过限制',
'45006' => '图片链接字段超过限制',
'45007' => '语音播放时间超过限制',
'45008' => '图文消息超过限制',
'45009' => '接口调用超过限制',
'45010' => '创建菜单个数超过限制',
'45015' => '回复时间超过限制',
'45016' => '系统分组,不允许修改',
'45017' => '分组名字过长',
'45018' => '分组数量超过上限',
'46001' => '不存在媒体数据',
'46002' => '不存在的菜单版本',
'46003' => '不存在的菜单数据',
'46004' => '不存在的用户',
'47001' => '解析JSON/XML内容错误',
'48001' => 'api功能未授权',
'50001' => '用户未授权该api',
'40070' => '基本信息baseinfo中填写的库存信息SKU不合法。',
'41011' => '必填字段不完整或不合法,参考相应接口。',
'40056' => '无效code请确认code长度在20个字符以内且处于非异常状态转赠、删除。',
'43009' => '无自定义SN权限请参考开发者必读中的流程开通权限。',
'43010' => '无储值权限,请参考开发者必读中的流程开通权限。',
'43011' => '无积分权限,请参考开发者必读中的流程开通权限。',
'40078' => '无效卡券,未通过审核,已被置为失效。',
'40079' => '基本信息base_info中填写的date_info不合法或核销卡券未到生效时间。',
'45021' => '文本字段超过长度限制,请参考相应字段说明。',
'40080' => '卡券扩展信息cardext不合法。',
'40097' => '基本信息base_info中填写的url_name_type或promotion_url_name_type不合法。',
'49004' => '签名错误。',
'43012' => '无自定义cell跳转外链权限请参考开发者必读中的申请流程开通权限。',
'40099' => '该code已被核销。',
'61005' => '缺少接入平台关键数据等待微信开放平台推送数据请十分钟后再试或是检查“授权事件接收URL”是否写错index.php?c=account&amp;a=auth&amp;do=ticket地址中的&amp;符号容易被替换成&amp;amp;',
'61023' => '请重新授权接入该公众号',
);
$code = strval($code);
if ($code == '40001' || $code == '42001') {
$cachekey = "accesstoken:{$this->account['acid']}";
cache_delete($cachekey);
return '微信公众平台授权异常, 系统已修复这个错误, 请刷新页面重试.';
}
if ($errors[$code]) {
return $errors[$code];
} else {
return '未知错误';
}
}
// 通过网页授权拉取用户详细信息,非静默授权
public function getOauthUserInfo($accesstoken, $openid)
{
// 网页授权接口调用凭证,注意此access_token与基础支持的access_token不同
$apiurl = "https://api.weixin.qq.com/sns/userinfo?access_token={$accesstoken}&openid={$openid}&lang=zh_CN";
$response = ihttp_get($apiurl);
if (is_error($response)) {
return $response;
}
return @json_decode($response['content'], true);
}
// 通过code换取网页授权access_token
public function getOauthInfo($code)
{
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->account['key']}&secret={$this->account['secret']}&code={$code}&grant_type=authorization_code";
$response = ihttp_get($url);
if (is_error($response)) {
return $response;
}
return @json_decode($response['content'], true);
}
// 返回网页静默授权的授权访问地址
// 参数1回调页面地址
// 参数2重定向后会带上state参数开发者可以填写a-zA-Z0-9的参数值最多128字节
public function getOauthCodeUrl($callback, $state = '')
{
return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->account['key']}&redirect_uri={$callback}&response_type=code&scope=snsapi_base&state={$state}#wechat_redirect";
}
// 返回网页非静默授权的授权访问地址
// 参数1回调页面地址
// 参数2重定向后会带上state参数开发者可以填写a-zA-Z0-9的参数值最多128字节
public function getOauthUserInfoUrl($callback, $state = '')
{
return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->account['key']}&redirect_uri={$callback}&response_type=code&scope=snsapi_userinfo&state={$state}#wechat_redirect";
}
// 发送模板消息
// 参数1要发送的目标用户openId
// 参数2模板标识ID
// 参数3要发送的模板消息内容
// 参数4模板消息跳转地址可以留空
// 参数5模板消息背景颜色(新版本不支持)
public function sendTplNotice($db, $pdo, $touser, $template_id, $postdata, $url = '', $topcolor = '#FF683F')
{
// 要发送给的目标粉丝openid
if (empty($touser))
return error(25000, '参数错误,粉丝openid不能为空');
// 要发送的模板标识
if (empty($template_id))
return error(250001, '参数错误,模板标示不能为空');
// 模板消息内容
if (empty($postdata) || !(is_array($postdata) || is_object($postdata)))
return error(250002, '参数错误,请根据模板规则完善消息内容');
// 获得微信调用accessToken
$token = $this->getAccessToken($db, $pdo);
if (is_error($token)) {
$access_errno = $token['errno'];
return error(250003, '获取AccessToken失败');
}
$data = [
'touser' => trim($touser), /// 要发送给的目标粉丝openid
'template_id' => trim($template_id), // 要发送的模板标识
'url' => trim($url), // 模板消息跳转地址(留空IOS点击显示空白 Android 无法点击 非空跳转至该URL)
//'topcolor' => trim($topcolor), /// 模板背景颜色(新版本中不再支持)
'data' => $postdata, /// 模板消息内容
];
$data = json_encode($data);
// 发送模板消息接口地址
$post_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$token}";
$response = ihttp_request($post_url, $data, false);
if (is_error($response))
return error(250004, "访问公众平台接口失败, 错误: {$response['message']}");
$result = @json_decode($response['content'], true);
if (empty($result))
return error(250006, "接口调用失败, 元数据: {$response['meta']}");
elseif (!empty($result['errcode']))
return error(250007, "访问微信接口错误, 错误代码: {$result['errcode']}, 错误信息: {$result['errmsg']},信息详情:" . $this->error_code($result['errcode']));
else
return true;
}
public function SendTemplateMessage($to_user, $template_id, $target_url, $parameter, $color = '#7b68ee', $db = null, $pdo = null)
{
/// 要发送给的目标粉丝openid
if (empty($to_user))
return error(25000, '参数错误,粉丝openid不能为空');
/// 要发送的模板标识
if (empty($template_id))
return error(250001, '参数错误,模板标示不能为空');
/// 模板消息内容
if (empty($parameter) || !(is_array($parameter) || is_object($parameter)))
return error(250002, '参数错误,请根据模板规则完善消息内容');
/// 获得微信调用accessToken
$token = $this->getAccessToken($db, $pdo);
if (is_error($token))
return error(250003, '获取AccessToken失败');
$data = [];
foreach ((array)$parameter as $key => $value) {
if (is_array($value) || is_object($value))
$data[$key] = (array)$value;
else
$data[$key] = ['value' => $value, 'color' => $color, ];
}
$data = [
'touser' => trim($to_user), /// 要发送给的目标粉丝openid
'template_id' => trim($template_id), // 要发送的模板标识
'url' => trim($target_url), // 模板消息跳转地址(留空IOS点击显示空白 Android 无法点击 非空跳转至该URL)
'data' => $data, /// 模板消息内容
];
$data = json_encode($data);
/// 发送模板消息接口地址
$post_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$token}";
$response = ihttp_request($post_url, $data, false);
if (is_error($response))
return error(250004, "访问公众平台接口失败, 错误: {$response['message']}");
$result = @json_decode($response['content'], true);
if (empty($result))
return error(250006, "接口调用失败, 元数据: {$response['meta']}");
elseif (!empty($result['errcode']))
return error(250007, "访问微信接口错误, 错误代码: {$result['errcode']}, 错误信息: {$result['errmsg']},信息详情:" . $this->error_code($result['errcode']));
else
return true;
}
}

View File

@@ -0,0 +1,20 @@
<?php
defined('IN_IA') or exit('Access Denied');
load()->func('cache.mysql');
// 加载系统指定的配置项(core_cache表中)
function cache_load($key, $db,$unserialize = false) {
global $_W;
if (!empty($_W['cache'][$key])) {
return $_W['cache'][$key];
}
// 读取指定的系统配置项(core_cache表中)
$data = $_W['cache'][$key] = cache_read($key,$db);
return $unserialize ? iunserializer($data) : $data;
}
function &cache_global($key) {
}

View File

@@ -0,0 +1,64 @@
<?php
defined('IN_IA') or exit('Access Denied');
use phprs\ezsql\Sql;
// 读取指定的系统缓存项 core_cache表中
function cache_read($key,$db) {
$val = Sql::select('syweb_core_cache.`value`')
->from('syweb_core_cache')
->where('syweb_core_cache.`key`=?', $key)
->get($db ,null);
if(count($val)>0){
return iunserializer($val[0]["value"]);
}
}
function cache_search($prefix,$db) {
$rs = Sql::select('syweb_core_cache.*')
->from('syweb_core_cache')
->where('syweb_core_cache.`key` like ?', "{$prefix}%")
->get($db ,null);
$result = array();
foreach ((array)$rs as $v) {
$result[$v['key']] = iunserializer($v['value']);
}
return $result;
}
// 存储系统缓存
function cache_write($key, $data,$db,$pdo) {
if (empty($key) || !isset($data)) {
return false;
}
$record = array();
$record['`key`'] = $key;
$record['`value`'] = iserializer($data);
$id = Sql::replaceInto('syweb_core_cache')->values($record)->exec($pdo)->lastInsertId();
return $id;
}
function cache_delete($key) {
return Sql::deleteFrom('syweb_core_cache')->where('`key`=?',$key)->exec($pdo);
}
function cache_clean($prefix = '') {
global $_W;
if (empty($prefix)) {
$sql = 'DELETE FROM ' . tablename('core_cache');
$result = pdo_query($sql);
if ($result) {
unset($_W['cache']);
}
} else {
$sql = 'DELETE FROM ' . tablename('core_cache') . ' WHERE `key` LIKE :key';
$params = array();
$params[':key'] = "{$prefix}:%";
$result = pdo_query($sql, $params);
}
return $result;
}

View File

@@ -0,0 +1,622 @@
<?php
defined('IN_IA') or exit('Access Denied');
// 请求某个网页,并返回网页返回的内容
// 参数1请求地址
// 参数2请求参数
function ihttp_request($url, $post = '', $needUrlEncode = true, $extra = array(), $timeout = 60)
{
$urlset = parse_url($url);
if (empty($urlset['path'])) {
$urlset['path'] = '/';
}
// 解析后的参数
if (!empty($urlset['query'])) {
$urlset['query'] = "?{$urlset['query']}";
}
// 请求端口
if (empty($urlset['port'])) {
$urlset['port'] = $urlset['scheme'] == 'https' ? '443' : '80';
}
// 假如是https请求则判断是否开启了openssl模块没有开启则提示错误
if (strexists($url, 'https://') && !extension_loaded('openssl')) {
if (!extension_loaded("openssl")) {
message('请开启您PHP环境的openssl');
}
}
if (function_exists('curl_init') && function_exists('curl_exec')) {
$ch = curl_init();
// PHP8兼容性修复CURLOPT_SAFE_UPLOAD在PHP8中已被移除安全上传现在是默认行为
if (version_compare(phpversion(), '5.6') >= 0 && version_compare(phpversion(), '8.0') < 0) {
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
}
if (!empty($extra['ip'])) {
$extra['Host'] = $urlset['host'];
$urlset['host'] = $extra['ip'];
unset($extra['ip']);
}
curl_setopt($ch, CURLOPT_URL, $urlset['scheme'] . '://' . $urlset['host'] . ($urlset['port'] == '80' ? '' : ':' . $urlset['port']) . $urlset['path'] . $urlset['query']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
@curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
if ($post) {
if (is_array($post)) {
$filepost = false;
foreach ($post as $name => $value) {
if ((is_string($value) && substr($value, 0, 1) == '@') || (class_exists('CURLFile') && $value instanceof CURLFile)) {
$filepost = true;
break;
}
}
if (!$filepost) {
$post = http_build_query($post);
}
}
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}
if (!empty($GLOBALS['_W']['config']['setting']['proxy'])) {
$urls = parse_url($GLOBALS['_W']['config']['setting']['proxy']['host']);
if (!empty($urls['host'])) {
curl_setopt($ch, CURLOPT_PROXY, "{$urls['host']}:{$urls['port']}");
$proxytype = 'CURLPROXY_' . strtoupper($urls['scheme']);
if (!empty($urls['scheme']) && defined($proxytype)) {
curl_setopt($ch, CURLOPT_PROXYTYPE, constant($proxytype));
} else {
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
}
if (!empty($GLOBALS['_W']['config']['setting']['proxy']['auth'])) {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['_W']['config']['setting']['proxy']['auth']);
}
}
}
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSLVERSION, 1);
if (defined('CURL_SSLVERSION_TLSv1')) {
curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
}
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1');
if (!empty($extra) && is_array($extra)) {
$headers = array();
foreach ($extra as $opt => $value) {
if (strexists($opt, 'CURLOPT_')) {
curl_setopt($ch, constant($opt), $value);
} elseif (is_numeric($opt)) {
curl_setopt($ch, $opt, $value);
} else {
$headers[] = "{$opt}: {$value}";
}
}
if (!empty($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
}
$data = curl_exec($ch);
$status = curl_getinfo($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
curl_close($ch);
if ($errno || empty($data)) {
return error(1, $error);
} else {
return ihttp_response_parse($data);
}
}
// 设置http请求方式假如没有post参数则使用get方式否则采用post方式
$method = empty($post) ? 'GET' : 'POST';
$fdata = "{$method} {$urlset['path']}{$urlset['query']} HTTP/1.1\r\n";
$fdata .= "Host: {$urlset['host']}\r\n";
if (function_exists('gzdecode')) {
$fdata .= "Accept-Encoding: gzip, deflate\r\n";
}
$fdata .= "Connection: close\r\n";
if (!empty($extra) && is_array($extra)) {
foreach ($extra as $opt => $value) {
if (!strexists($opt, 'CURLOPT_')) {
$fdata .= "{$opt}: {$value}\r\n";
}
}
}
$body = '';
if ($post) {
if (is_array($post)) {
// 构建http请求参数
$body = http_build_query($post);
} else {
if ($needUrlEncode) {
$body = urlencode($post);
} else {
$body = $post;
}
}
$fdata .= 'Content-Length: ' . strlen($body) . "\r\n\r\n{$body}";
} else {
$fdata .= "\r\n";
}
if ($urlset['scheme'] == 'https') {
$fp = fsockopen('ssl://' . $urlset['host'], $urlset['port'], $errno, $error);
} else {
$fp = fsockopen($urlset['host'], $urlset['port'], $errno, $error);
}
stream_set_blocking($fp, true);
stream_set_timeout($fp, $timeout);
if (!$fp) {
return error(1, $error);
} else {
fwrite($fp, $fdata);
$content = '';
while (!feof($fp)) {
$content .= fgets($fp, 512);
}
fclose($fp);
return ihttp_response_parse($content, true);
}
}
function ihttp_response_parse($data, $chunked = false)
{
$rlt = array();
$headermeta = explode('HTTP/', $data);
if (count($headermeta) > 2) {
$data = 'HTTP/' . array_pop($headermeta);
}
$pos = strpos($data, "\r\n\r\n");
$split1[0] = substr($data, 0, $pos);
$split1[1] = substr($data, $pos + 4, strlen($data));
$split2 = explode("\r\n", $split1[0], 2);
preg_match('/^(\S+) (\S+) (\S+)$/', $split2[0], $matches);
$rlt['code'] = $matches[2];
$rlt['status'] = $matches[3];
$rlt['responseline'] = $split2[0];
$header = explode("\r\n", $split2[1]);
$isgzip = false;
$ischunk = false;
foreach ($header as $v) {
$pos = strpos($v, ':');
$key = substr($v, 0, $pos);
$value = trim(substr($v, $pos + 1));
if (is_array($rlt['headers'][$key])) {
$rlt['headers'][$key][] = $value;
} elseif (!empty($rlt['headers'][$key])) {
$temp = $rlt['headers'][$key];
unset($rlt['headers'][$key]);
$rlt['headers'][$key][] = $temp;
$rlt['headers'][$key][] = $value;
} else {
$rlt['headers'][$key] = $value;
}
if (!$isgzip && strtolower($key) == 'content-encoding' && strtolower($value) == 'gzip') {
$isgzip = true;
}
if (!$ischunk && strtolower($key) == 'transfer-encoding' && strtolower($value) == 'chunked') {
$ischunk = true;
}
}
if ($chunked && $ischunk) {
$rlt['content'] = ihttp_response_parse_unchunk($split1[1]);
} else {
$rlt['content'] = $split1[1];
}
if ($isgzip && function_exists('gzdecode')) {
$rlt['content'] = gzdecode($rlt['content']);
}
$rlt['meta'] = $data;
if ($rlt['code'] == '100') {
return ihttp_response_parse($rlt['content']);
}
return $rlt;
}
function ihttp_response_parse_unchunk($str = null)
{
if (!is_string($str) or strlen($str) < 1) {
return false;
}
$eol = "\r\n";
$add = strlen($eol);
$tmp = $str;
$str = '';
do {
$tmp = ltrim($tmp);
$pos = strpos($tmp, $eol);
if ($pos === false) {
return false;
}
$len = hexdec(substr($tmp, 0, $pos));
if (!is_numeric($len) or $len < 0) {
return false;
}
$str .= substr($tmp, ($pos + $add), $len);
$tmp = substr($tmp, ($len + $pos + $add));
$check = trim($tmp);
} while (!empty($check));
unset($tmp);
return $str;
}
function ihttp_get($url)
{
return ihttp_request($url);
}
function ihttp_post($url, $data)
{
$headers = array('Content-Type' => 'application/x-www-form-urlencoded');
return ihttp_request($url, $data, $headers);
}
// 发送邮件
// $to接收人
// $subject邮件主题
// $body邮件正文
function ihttp_email($to, $subject, $body, $global = false)
{
static $mailer;
set_time_limit(0);
if (empty($mailer)) {
if (!class_exists('PHPMailer')) {
require IA_ROOT . '/framework/library/phpmailer/PHPMailerAutoload.php';
}
$mailer = new PHPMailer();
global $_W;
$config = $GLOBALS['_W']['setting']['mail'];
if (!$global) {
$row = pdo_fetch("SELECT `notify` FROM " . tablename('uni_settings') . " WHERE uniacid = :uniacid", array(':uniacid' => $_W['uniacid']));
$row['notify'] = @iunserializer($row['notify']);
if (!empty($row['notify']) && !empty($row['notify']['mail'])) {
$config = $row['notify']['mail'];
}
}
$config['charset'] = 'utf-8';
if ($config['smtp']['type'] == '163') {
$config['smtp']['server'] = 'smtp.163.com';
$config['smtp']['port'] = 25;
} else {
if (!empty($config['smtp']['authmode'])) {
$config['smtp']['server'] = 'ssl://' . $config['smtp']['server'];
}
}
if (!empty($config['smtp']['authmode'])) {
if (!extension_loaded('openssl')) {
return error(1, '请开启 php_openssl 扩展!');
}
}
$mailer->signature = $config['signature'];
$mailer->isSMTP();
$mailer->CharSet = $config['charset'];
$mailer->Host = $config['smtp']['server'];
$mailer->Port = $config['smtp']['port'];
$mailer->SMTPAuth = true;
$mailer->Username = $config['username'];
$mailer->Password = $config['password'];
!empty($config['smtp']['authmode']) && $mailer->SMTPSecure = 'ssl';
$mailer->From = $config['username'];
$mailer->FromName = $config['sender'];
$mailer->isHTML(true);
}
if (!empty($mailer->signature)) {
$body .= htmlspecialchars_decode($mailer->signature);
}
$mailer->Subject = $subject;
$mailer->Body = $body;
$mailer->addAddress($to);
if ($mailer->send()) {
return true;
} else {
return error(1, $mailer->ErrorInfo);
}
}
// 发送POST请求(模板消息尤其适用)
function do_post_request($url, $data, $optional_headers = null)
{
$params = array(
'http' => array(
'method' => 'POST',
'content' => $data,
),
);
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}
// 字符集
define('USEDCHARSET', 'utf-8');
/**
* @note 转换分隔符
* @param string $string
* @return mixed
*/
function ConvertSeparator($string)
{
$result = $string;
while (false !== mb_stripos($result, '\\', 0, USEDCHARSET)) {
$result = str_replace('\\', '/', $result);
}
while (false !== mb_stripos($result, '//', 0, USEDCHARSET)) {
$result = str_replace('//', '/', $result);
}
return $result;
}
/**
* @date 2017-03-04
* @note 获取当前页面的url地址
* @return string
* @auth 应俊
*/
function GetLocaleUrl()
{
if (isset($_SERVER['PHP_SELF'])) {
$objectname = $_SERVER['PHP_SELF'];
} else {
$filename = ConvertSeparator(__FILE__);
$pathname = ConvertSeparator(isset($_SERVER['CONTEXT_DOCUMENT_ROOT']) ? $_SERVER['CONTEXT_DOCUMENT_ROOT'] : '');
$pathlength = mb_strlen($pathname, USEDCHARSET);
$filelength = mb_strlen($filename, USEDCHARSET);
if (false !== stripos($filename, $pathname))
$objectname = mb_substr($filename, $pathlength, $filelength - $pathlength, USEDCHARSET);
else
$objectname = $filename;
}
$https = (isset($_SERVER['REQUEST_SCHEME']) && strcasecmp($_SERVER['REQUEST_SCHEME'], 'https') == 0) ||
(isset($_SERVER['HTTPS']) && (strcasecmp($_SERVER['HTTPS'], 'on') == 0 || strcasecmp($_SERVER['HTTPS'], '1') == 0));
$port = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 0;
$servername = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';
if ($https)
$uri = 'https://' . $servername . (443 == $port ? '' : ':' . $port) . $objectname;
else
$uri = 'http://' . $servername . (80 == $port ? '' : ':' . $port) . $objectname;
return $uri;
}
/**
* @date 2017-03-04
* @note 给参数按key的顺序排序。支持递归
* @param mixed $parameter 要排序的参数
* @return array
* @auth 应俊
*/
function SortParam($parameter)
{
$parameter = (array)$parameter;
foreach ($parameter as $k => $v) {
if (is_array($v) || is_object($v)) {
$parameter[$k] = SortParam($v);
}
}
// 调用strcmp函数来排序该函数区分大小写。
uksort($parameter, 'strcmp');
return $parameter;
}
/**
* @date 2017-03-06
* @note 转换参数成字符串形式按key=value的形式用&分隔)。
* @param mixed $parameter 要转换的参数
* @return string
* @auth 应俊
*/
function ConvertParam($parameter)
{
$parameter = (array)$parameter;
$return = '';
foreach ($parameter as $k => $v) {
if (is_array($v) || is_object($v)) {
$return .= sprintf('&%s={%s}', $k, ConvertParam($v));
} else {
$return .= sprintf('&%s=%s', $k, $v);
}
}
$sublen = mb_strlen('&', USEDCHARSET);
$retlen = mb_strlen($return, USEDCHARSET);
$return = mb_substr($return, $sublen, $retlen - $sublen, USEDCHARSET);
return $return;
}
/**
* @date 2017-03-04
* @note 为参数生成签名
* @param mixed $parameter 要签名的参数
* @param string $signkey 签名key
* @return string
* @auth 应俊
*/
function SignParameter($parameter, $signkey = '')
{
// 1先把参数按参数名key从小到大排序
$parameter = SortParam($parameter);
// 2连接参数成一个字符串按key=value的形式用&分隔)。
$return = ConvertParam($parameter);
// 3结尾加上key=签名key
$return .= '&key=' . $signkey;
// 4md5加密这个字符串
return md5($return);
}
/**
* @note 转换数据编码
* @param $data
* @param string $charset
* @return string
* @auther 应俊
*/
function Characet($data, $charset = USEDCHARSET)
{
if (!empty ($data)) {
$encoding = mb_detect_encoding($data, array('ASCII', 'UTF-8', 'GBK', 'GB2312', 'LATIN1', 'BIG5',));
if (0 != strcasecmp($encoding, $charset))
$data = mb_convert_encoding($data, $charset, $encoding);
}
return $data;
}
/**
* @param mixed $data
* @return array|mixed
*/
function ChangePostData($data)
{
switch (gettype($data)) {
case 'array': {
foreach ($data as $key => $value) {
$data[$key] = ChangePostData($value);
}
break;
}
case 'object': {
$array = (array)$data;
foreach ($array as $key => $value) {
$data->$key = ChangePostData($value);
}
break;
}
default: {
$data = preg_replace_callback('/\+/', function ($r) {
return '%2B';
}, $data);
$data = preg_replace_callback('/\&/', function ($r) {
return '%26';
}, $data);
break;
}
}
return $data;
}
/**
* @note 发送post请求
* @param string $url
* @param mixed $data
* @return string
*/
function SendPost($url, $data)
{
$data = http_build_query(ChangePostData($data));
$opts = array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n" . "Content-Length: " . strlen($data) . "\r\n",
'content' => $data,
),
);
$context = stream_context_create($opts);
$ret = file_get_contents($url, false, $context);
$ret = trim($ret, "\xEF\xBB\xBF");
return $ret;
}
/**
* @note 从参数中过滤不需要的参数
* @param array|null $ignores 要过滤的参数列表(参数名)
* @param array|null $parameters 目标参数列表
* @return array
*/
function GetAttachParameters($ignores = null, $parameters = null)
{
$return = (array)(empty($parameters) ? $_REQUEST : $parameters);
if (!empty($ignores)) {
foreach ($return as $k => $v) {
if (in_array($k, $ignores))
unset($return[$k]);
}
}
return $return;
}
function GetClientAddress()
{
static $_ClientAddress = null;
if ($_ClientAddress !== null)
return $_ClientAddress;
if (isset($_SERVER)) {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$List = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
/// 取X-Forwarded-For中第一个非unknown的有效IP字符串
foreach ($List as $Item) {
$Item = trim($Item);
if (strcasecmp($Item, 'unknown') != 0) {
$_ClientAddress = $Item;
break;
}
}
} elseif (isset($_SERVER['HTTP_CLIENT_IP']))
$_ClientAddress = $_SERVER['HTTP_CLIENT_IP'];
else {
if (isset($_SERVER['REMOTE_ADDR']))
$_ClientAddress = $_SERVER['REMOTE_ADDR'];
else
$_ClientAddress = '0.0.0.0';
}
} else {
if (getenv('HTTP_X_FORWARDED_FOR'))
$_ClientAddress = getenv('HTTP_X_FORWARDED_FOR');
elseif (getenv('HTTP_CLIENT_IP'))
$_ClientAddress = getenv('HTTP_CLIENT_IP');
else
$_ClientAddress = getenv('REMOTE_ADDR');
}
preg_match('/[\d\.]{7,15}/', $_ClientAddress, $List);
$_ClientAddress = !empty($List[0]) ? $List[0] : null;
return $_ClientAddress;
}

View File

@@ -0,0 +1,77 @@
<?php
defined('IN_IA') or exit('Access Denied');
if (!function_exists('json_encode')) {
function json_encode($value) {
static $jsonobj;
if (!isset($jsonobj)) {
include_once (IA_ROOT . '/framework/library/json/JSON.php');
$jsonobj = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
}
return $jsonobj->encode($value);
}
}
if (!function_exists('json_decode')) {
// 将传入的字符串解码为一个json字符串
function json_decode($jsonString) {
// decode解码为一个JSON字符串
static $jsonobj;
if (!isset($jsonobj)) {
include_once (IA_ROOT . '/framework/library/json/JSON.php');
$jsonobj = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
}
return $jsonobj->decode($jsonString);
}
}
if (!function_exists('http_build_query')) {
// 构建http请求参数
function http_build_query($formdata, $numeric_prefix = null, $arg_separator = null) {
// 假如参数不是数组的话则直接返回false
if (!is_array($formdata))
return false;
// 假如没有设置参数分割符,则默认设置为&
if ($arg_separator == null)
$arg_separator = '&';
return http_build_recursive($formdata, $arg_separator);
}
// 采用递归的方式拼接参数为字符串
// 参数1要拼接的参数数组
// 参数2要拼接使用的参数分割符
function http_build_recursive($formdata, $separator, $key = '', $prefix = '') {
$rlt = '';
foreach ($formdata as $k => $v) {
if (is_array($v)) {
if ($key)
$rlt .= http_build_recursive($v, $separator, $key . '[' . $k . ']', $prefix);
else
$rlt .= http_build_recursive($v, $separator, $k, $prefix);
} else {
if ($key)
$rlt .= $prefix . $key . '[' . urlencode($k) . ']=' . urldecode($v) . '&';
else
$rlt .= $prefix . urldecode($k) . '=' . urldecode($v) . '&';
}
}
return $rlt;
}
}
if (!function_exists('file_put_contents')) {
function file_put_contents($file, $string) {
$fp = @fopen($file, 'w') or exit("Can not open $file");
flock($fp, LOCK_EX);
$stringlen = @fwrite($fp, $string);
flock($fp, LOCK_UN);
@fclose($fp);
return $stringlen;
}
}
if (!function_exists('getimagesizefromstring')) {
function getimagesizefromstring($string_data) {
$uri = 'data://application/octet-stream;base64,' . base64_encode($string_data);
return getimagesize($uri);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,806 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Converts to and from JSON format.
*
* JSON (JavaScript Object Notation) is a lightweight data-interchange
* format. It is easy for humans to read and write. It is easy for machines
* to parse and generate. It is based on a subset of the JavaScript
* Programming Language, Standard ECMA-262 3rd Edition - December 1999.
* This feature can also be found in Python. JSON is a text format that is
* completely language independent but uses conventions that are familiar
* to programmers of the C-family of languages, including C, C++, C#, Java,
* JavaScript, Perl, TCL, and many others. These properties make JSON an
* ideal data-interchange language.
*
* This package provides a simple encoder and decoder for JSON notation. It
* is intended for use with client-side Javascript applications that make
* use of HTTPRequest to perform server communication functions - data can
* be encoded into JSON notation for use in a client-side javascript, or
* decoded from incoming Javascript requests. JSON format is native to
* Javascript, and can be directly eval()'ed with no further parsing
* overhead
*
* All strings should be in ASCII or UTF-8 format!
*
* LICENSE: Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met: Redistributions of source code must retain the
* above copyright notice, this list of conditions and the following
* disclaimer. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* @category
* @package Services_JSON
* @author Michal Migurski <mike-json@teczno.com>
* @author Matt Knapp <mdknapp[at]gmail[dot]com>
* @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
* @copyright 2005 Michal Migurski
* @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
* @license http://www.opensource.org/licenses/bsd-license.php
* @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
*/
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_SLICE', 1);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_STR', 2);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_ARR', 3);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_OBJ', 4);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_CMT', 5);
/**
* Behavior switch for Services_JSON::decode()
*/
define('SERVICES_JSON_LOOSE_TYPE', 16);
/**
* Behavior switch for Services_JSON::decode()
*/
define('SERVICES_JSON_SUPPRESS_ERRORS', 32);
/**
* Converts to and from JSON format.
*
* Brief example of use:
*
* <code>
* // create a new instance of Services_JSON
* $json = new Services_JSON();
*
* // convert a complexe value to JSON notation, and send it to the browser
* $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
* $output = $json->encode($value);
*
* print($output);
* // prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
*
* // accept incoming POST data, assumed to be in JSON notation
* $input = file_get_contents('php://input', 1000000);
* $value = $json->decode($input);
* </code>
*/
class Services_JSON
{
/**
* constructs a new JSON instance
*
* @param int $use object behavior flags; combine with boolean-OR
*
* possible values:
* - SERVICES_JSON_LOOSE_TYPE: loose typing.
* "{...}" syntax creates associative arrays
* instead of objects in decode().
* - SERVICES_JSON_SUPPRESS_ERRORS: error suppression.
* Values which can't be encoded (e.g. resources)
* appear as NULL instead of throwing errors.
* By default, a deeply-nested resource will
* bubble up with an error, so all return values
* from encode() should be checked with isError()
*/
function Services_JSON($use = 0)
{
$this->use = $use;
}
/**
* convert a string from one UTF-16 char to one UTF-8 char
*
* Normally should be handled by mb_convert_encoding, but
* provides a slower PHP-only method for installations
* that lack the multibye string extension.
*
* @param string $utf16 UTF-16 character
* @return string UTF-8 character
* @access private
*/
function utf162utf8($utf16)
{
// oh please oh please oh please oh please oh please
if(function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
}
$bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
switch(true) {
case ((0x7F & $bytes) == $bytes):
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x7F & $bytes);
case (0x07FF & $bytes) == $bytes:
// return a 2-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xC0 | (($bytes >> 6) & 0x1F))
. chr(0x80 | ($bytes & 0x3F));
case (0xFFFF & $bytes) == $bytes:
// return a 3-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xE0 | (($bytes >> 12) & 0x0F))
. chr(0x80 | (($bytes >> 6) & 0x3F))
. chr(0x80 | ($bytes & 0x3F));
}
// ignoring UTF-32 for now, sorry
return '';
}
/**
* convert a string from one UTF-8 char to one UTF-16 char
*
* Normally should be handled by mb_convert_encoding, but
* provides a slower PHP-only method for installations
* that lack the multibye string extension.
*
* @param string $utf8 UTF-8 character
* @return string UTF-16 character
* @access private
*/
function utf82utf16($utf8)
{
// oh please oh please oh please oh please oh please
if(function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
}
switch(strlen($utf8)) {
case 1:
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return $utf8;
case 2:
// return a UTF-16 character from a 2-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x07 & (ord($utf8{0}) >> 2))
. chr((0xC0 & (ord($utf8{0}) << 6))
| (0x3F & ord($utf8{1})));
case 3:
// return a UTF-16 character from a 3-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr((0xF0 & (ord($utf8{0}) << 4))
| (0x0F & (ord($utf8{1}) >> 2)))
. chr((0xC0 & (ord($utf8{1}) << 6))
| (0x7F & ord($utf8{2})));
}
// ignoring UTF-32 for now, sorry
return '';
}
/**
* encodes an arbitrary variable into JSON format
*
* @param mixed $var any number, boolean, string, array, or object to be encoded.
* see argument 1 to Services_JSON() above for array-parsing behavior.
* if var is a strng, note that encode() always expects it
* to be in ASCII or UTF-8 format!
*
* @return mixed JSON string representation of input var or an error if a problem occurs
* @access public
*/
function encode($var)
{
switch (gettype($var)) {
case 'boolean':
return $var ? 'true' : 'false';
case 'NULL':
return 'null';
case 'integer':
return (int) $var;
case 'double':
case 'float':
return (float) $var;
case 'string':
// STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
$ascii = '';
$strlen_var = strlen($var);
/*
* Iterate over every character in the string,
* escaping with a slash or encoding to UTF-8 where necessary
*/
for ($c = 0; $c < $strlen_var; ++$c) {
$ord_var_c = ord($var{$c});
switch (true) {
case $ord_var_c == 0x08:
$ascii .= '\b';
break;
case $ord_var_c == 0x09:
$ascii .= '\t';
break;
case $ord_var_c == 0x0A:
$ascii .= '\n';
break;
case $ord_var_c == 0x0C:
$ascii .= '\f';
break;
case $ord_var_c == 0x0D:
$ascii .= '\r';
break;
case $ord_var_c == 0x22:
case $ord_var_c == 0x2F:
case $ord_var_c == 0x5C:
// double quote, slash, slosh
$ascii .= '\\'.$var{$c};
break;
case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
// characters U-00000000 - U-0000007F (same as ASCII)
$ascii .= $var{$c};
break;
case (($ord_var_c & 0xE0) == 0xC0):
// characters U-00000080 - U-000007FF, mask 110X XX XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c, ord($var{$c + 1}));
$c += 1;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xF0) == 0xE0):
// characters U-00000800 - U-0000FFFF, mask 1110X XX X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}));
$c += 2;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xF8) == 0xF0):
// characters U-00010000 - U-001FFFFF, mask 11110X XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}));
$c += 3;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xFC) == 0xF8):
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}),
ord($var{$c + 4}));
$c += 4;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xFE) == 0xFC):
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}),
ord($var{$c + 4}),
ord($var{$c + 5}));
$c += 5;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
}
}
return '"'.$ascii.'"';
case 'array':
/*
* As per JSON spec if any array key is not an integer
* we must treat the the whole array as an object. We
* also try to catch a sparsely populated associative
* array with numeric keys here because some JS engines
* will create an array with empty indexes up to
* max_index which can cause memory issues and because
* the keys, which may be relevant, will be remapped
* otherwise.
*
* As per the ECMA and JSON specification an object may
* have any string as a property. Unfortunately due to
* a hole in the ECMA specification if the key is a
* ECMA reserved word or starts with a digit the
* parameter is only accessible using ECMAScript's
* bracket notation.
*/
// treat as a JSON object
if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
$properties = array_map(array($this, 'name_value'),
array_keys($var),
array_values($var));
foreach($properties as $property) {
if(Services_JSON::isError($property)) {
return $property;
}
}
return '{' . join(',', $properties) . '}';
}
// treat it like a regular array
$elements = array_map(array($this, 'encode'), $var);
foreach($elements as $element) {
if(Services_JSON::isError($element)) {
return $element;
}
}
return '[' . join(',', $elements) . ']';
case 'object':
$vars = get_object_vars($var);
$properties = array_map(array($this, 'name_value'),
array_keys($vars),
array_values($vars));
foreach($properties as $property) {
if(Services_JSON::isError($property)) {
return $property;
}
}
return '{' . join(',', $properties) . '}';
default:
return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
? 'null'
: new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
}
}
/**
* array-walking function for use in generating JSON-formatted name-value pairs
*
* @param string $name name of key to use
* @param mixed $value reference to an array element to be encoded
*
* @return string JSON-formatted name-value pair, like '"name":value'
* @access private
*/
function name_value($name, $value)
{
$encoded_value = $this->encode($value);
if(Services_JSON::isError($encoded_value)) {
return $encoded_value;
}
return $this->encode(strval($name)) . ':' . $encoded_value;
}
/**
* reduce a string by removing leading and trailing comments and whitespace
*
* @param $str string string value to strip of comments and whitespace
*
* @return string string value stripped of comments and whitespace
* @access private
*/
function reduce_string($str)
{
$str = preg_replace(array(
// eliminate single line comments in '// ...' form
'#^\s*//(.+)$#m',
// eliminate multi-line comments in '/* ... */' form, at start of string
'#^\s*/\*(.+)\*/#Us',
// eliminate multi-line comments in '/* ... */' form, at end of string
'#/\*(.+)\*/\s*$#Us'
), '', $str);
// eliminate extraneous space
return trim($str);
}
/**
* decodes a JSON string into appropriate variable
*
* @param string $str JSON-formatted string
*
* @return mixed number, boolean, string, array, or object
* corresponding to given JSON input string.
* See argument 1 to Services_JSON() above for object-output behavior.
* Note that decode() always returns strings
* in ASCII or UTF-8 format!
* @access public
*/
function decode($str)
{
$str = $this->reduce_string($str);
switch (strtolower($str)) {
case 'true':
return true;
case 'false':
return false;
case 'null':
return null;
default:
$m = array();
if (is_numeric($str)) {
// Lookie-loo, it's a number
// This would work on its own, but I'm trying to be
// good about returning integers where appropriate:
// return (float)$str;
// Return float or int, as appropriate
return ((float)$str == (integer)$str)
? (integer)$str
: (float)$str;
} elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) {
// STRINGS RETURNED IN UTF-8 FORMAT
$delim = substr($str, 0, 1);
$chrs = substr($str, 1, -1);
$utf8 = '';
$strlen_chrs = strlen($chrs);
for ($c = 0; $c < $strlen_chrs; ++$c) {
$substr_chrs_c_2 = substr($chrs, $c, 2);
$ord_chrs_c = ord($chrs{$c});
switch (true) {
case $substr_chrs_c_2 == '\b':
$utf8 .= chr(0x08);
++$c;
break;
case $substr_chrs_c_2 == '\t':
$utf8 .= chr(0x09);
++$c;
break;
case $substr_chrs_c_2 == '\n':
$utf8 .= chr(0x0A);
++$c;
break;
case $substr_chrs_c_2 == '\f':
$utf8 .= chr(0x0C);
++$c;
break;
case $substr_chrs_c_2 == '\r':
$utf8 .= chr(0x0D);
++$c;
break;
case $substr_chrs_c_2 == '\\"':
case $substr_chrs_c_2 == '\\\'':
case $substr_chrs_c_2 == '\\\\':
case $substr_chrs_c_2 == '\\/':
if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
($delim == "'" && $substr_chrs_c_2 != '\\"')) {
$utf8 .= $chrs{++$c};
}
break;
case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
// single, escaped unicode character
$utf16 = chr(hexdec(substr($chrs, ($c + 2), 2)))
. chr(hexdec(substr($chrs, ($c + 4), 2)));
$utf8 .= $this->utf162utf8($utf16);
$c += 5;
break;
case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
$utf8 .= $chrs{$c};
break;
case ($ord_chrs_c & 0xE0) == 0xC0:
// characters U-00000080 - U-000007FF, mask 110XX X XX
//see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 2);
++$c;
break;
case ($ord_chrs_c & 0xF0) == 0xE0:
// characters U-00000800 - U-0000FFFF, mask 1110X X XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 3);
$c += 2;
break;
case ($ord_chrs_c & 0xF8) == 0xF0:
// characters U-00010000 - U-001FFFFF, mask 11110X XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 4);
$c += 3;
break;
case ($ord_chrs_c & 0xFC) == 0xF8:
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 5);
$c += 4;
break;
case ($ord_chrs_c & 0xFE) == 0xFC:
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 6);
$c += 5;
break;
}
}
return $utf8;
} elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
// array, or object notation
if ($str{0} == '[') {
$stk = array(SERVICES_JSON_IN_ARR);
$arr = array();
} else {
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$stk = array(SERVICES_JSON_IN_OBJ);
$obj = array();
} else {
$stk = array(SERVICES_JSON_IN_OBJ);
$obj = new stdClass();
}
}
array_push($stk, array('what' => SERVICES_JSON_SLICE,
'where' => 0,
'delim' => false));
$chrs = substr($str, 1, -1);
$chrs = $this->reduce_string($chrs);
if ($chrs == '') {
if (reset($stk) == SERVICES_JSON_IN_ARR) {
return $arr;
} else {
return $obj;
}
}
//print("\nparsing {$chrs}\n");
$strlen_chrs = strlen($chrs);
for ($c = 0; $c <= $strlen_chrs; ++$c) {
$top = end($stk);
$substr_chrs_c_2 = substr($chrs, $c, 2);
if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
// found a comma that is not inside a string, array, etc.,
// OR we've reached the end of the character list
$slice = substr($chrs, $top['where'], ($c - $top['where']));
array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
//print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
if (reset($stk) == SERVICES_JSON_IN_ARR) {
// we are in an array, so just push an element onto the stack
array_push($arr, $this->decode($slice));
} elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
// we are in an object, so figure
// out the property name and set an
// element in an associative array,
// for now
$parts = array();
if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
// "name":value pair
$key = $this->decode($parts[1]);
$val = $this->decode($parts[2]);
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$obj[$key] = $val;
} else {
$obj->$key = $val;
}
} elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
// name:value pair, where name is unquoted
$key = $parts[1];
$val = $this->decode($parts[2]);
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$obj[$key] = $val;
} else {
$obj->$key = $val;
}
}
}
} elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
// found a quote, and we are not inside a string
array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c}));
//print("Found start of string at {$c}\n");
} elseif (($chrs{$c} == $top['delim']) &&
($top['what'] == SERVICES_JSON_IN_STR) &&
((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) {
// found a quote, we're in a string, and it's not escaped
// we know that it's not escaped becase there is _not_ an
// odd number of backslashes at the end of the string so far
array_pop($stk);
//print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
} elseif (($chrs{$c} == '[') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a left-bracket, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
//print("Found start of array at {$c}\n");
} elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
// found a right-bracket, and we're in an array
array_pop($stk);
//print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
} elseif (($chrs{$c} == '{') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a left-brace, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
//print("Found start of object at {$c}\n");
} elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
// found a right-brace, and we're in an object
array_pop($stk);
//print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
} elseif (($substr_chrs_c_2 == '/*') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a comment start, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false));
$c++;
//print("Found start of comment at {$c}\n");
} elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
// found a comment end, and we're in one now
array_pop($stk);
$c++;
for ($i = $top['where']; $i <= $c; ++$i)
$chrs = substr_replace($chrs, ' ', $i, 1);
//print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
}
}
if (reset($stk) == SERVICES_JSON_IN_ARR) {
return $arr;
} elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
return $obj;
}
}
}
}
/**
* @t odo Ultimately, this should just call PEAR::isError()
*/
function isError($data, $code = null)
{
if (class_exists('pear')) {
return PEAR::isError($data, $code);
} elseif (is_object($data) && (get_class($data) == 'services_json_error' ||
is_subclass_of($data, 'services_json_error'))) {
return true;
}
return false;
}
}
if (class_exists('PEAR_Error')) {
class Services_JSON_Error extends PEAR_Error
{
function Services_JSON_Error($message = 'unknown error', $code = null,
$mode = null, $options = null, $userinfo = null)
{
parent::PEAR_Error($message, $code, $mode, $options, $userinfo);
}
}
} else {
/**
* @t odo Ultimately, this class shall be descended from PEAR_Error
*/
class Services_JSON_Error
{
function Services_JSON_Error($message = 'unknown error', $code = null,
$mode = null, $options = null, $userinfo = null)
{
}
}
}
?>

View File

@@ -0,0 +1,145 @@
<?php
/**
* [Weizan System] Copyright (c) 2014 012WZ.COM
* Weizan is NOT a free software, it under the license terms, visited http://www.012wz.com/ for more details.
*/
function cache_build_template() {
load()->func('file');
rmdirs(IA_ROOT . '/data/tpl', true);
}
function cache_build_setting() {
$sql = 'SELECT * FROM ' . tablename('core_settings');
$setting = pdo_fetchall($sql, array(), 'key');
if (is_array($setting)) {
foreach ($setting as $k => $v) {
$setting[$v['key']] = iunserializer($v['value']);
}
cache_write("setting", $setting);
}
}
// 删除指定公众号的缓存
function cache_build_account_modules() {
$uniacid_arr = pdo_fetchall('SELECT uniacid FROM ' . tablename('uni_account'));
foreach($uniacid_arr as $account){
cache_delete("unimodules:{$account['uniacid']}:1");
cache_delete("unimodules:{$account['uniacid']}:");
cache_delete("unimodulesappbinding:{$account['uniacid']}");
}
}
// 删除指定公众号的应用缓存
function cache_build_account_outapps() {
$uniacid_arr = pdo_fetchall('SELECT uniacid FROM ' . tablename('uni_account'));
foreach($uniacid_arr as $account){
cache_delete("unioutapps:{$account['uniacid']}:1");
cache_delete("unioutapps:{$account['uniacid']}:");
}
}
function cache_build_account() {
global $_W;
$uniacid_arr = pdo_fetchall('SELECT uniacid FROM ' . tablename('uni_account'));
foreach($uniacid_arr as $account){
cache_delete("uniaccount:{$account['uniacid']}");
cache_delete("unisetting:{$account['uniacid']}");
cache_delete("defaultgroupid:{$account['uniacid']}");
}
}
function cache_build_accesstoken() {
global $_W;
$uniacid_arr = pdo_fetchall('SELECT acid FROM ' . tablename('account_wechats'));
foreach($uniacid_arr as $account){
cache_delete("accesstoken:{$account['acid']}");
cache_delete("jsticket:{$account['acid']}");
cache_delete("cardticket:{$account['acid']}");
}
}
function cache_build_users_struct() {
$struct = array();
$result = pdo_fetchall("SHOW COLUMNS FROM " . tablename('mc_members'));
if (!empty($result)) {
foreach ($result as $row) {
$struct[] = $row['Field'];
}
cache_write('usersfields', $struct);
}
return $struct;
}
// 更新系统菜单缓存
function cache_build_frame_menu() {
$data = pdo_fetchall('SELECT * FROM ' . tablename('core_menu') . ' WHERE pid = 0 AND is_display = 1 ORDER BY is_system DESC, displayorder DESC, id ASC');
$frames =array();
if(!empty($data)) {
foreach($data as $da) {
$frames[$da['name']] = array();
$childs = pdo_fetchall('SELECT * FROM ' . tablename('core_menu') . ' WHERE pid = :pid AND is_display = 1 ORDER BY is_system DESC, displayorder DESC, id ASC', array(':pid' => $da['id']));
if(!empty($childs)) {
foreach($childs as $child) {
$temp = array();
$temp['title'] = $child['title'];
$grandchilds = pdo_fetchall('SELECT * FROM ' . tablename('core_menu') . ' WHERE pid = :pid AND is_display = 1 AND type = :type ORDER BY is_system DESC, displayorder DESC, id ASC', array(':pid' => $child['id'], ':type' => 'url'));
if(!empty($grandchilds)) {
foreach($grandchilds as $grandchild) {
$item = array();
$item['id'] = $grandchild['id'];
$item['title'] = $grandchild['title'];
$item['url'] = $grandchild['url'];
$item['permission_name'] = $grandchild['permission_name'];
if(!empty($grandchild['append_title'])) {
$item['append']['title'] = '<i class="'.$grandchild['append_title'].'"></i>';
$item['append']['url'] = $grandchild['append_url'];
}
$temp['items'][] = $item;
}
}
$frames[$da['name']][] = $temp;
}
}
}
}
cache_delete('system_frame');
cache_write('system_frame', $frames);
}
// 更新订阅的消息类型缓存对象
function cache_build_module_subscribe_type() {
global $_W;
// 按订阅的消息类型分组统计哪些模块订阅了当前消息类型
$modules = pdo_fetchall("SELECT name, subscribes FROM ".tablename('modules')." WHERE subscribes <> ''");
$subscribe = array();
if (!empty($modules)) {
foreach ($modules as $module) {
$module['subscribes'] = unserialize($module['subscribes']);
if (!empty($module['subscribes'])) {
foreach ($module['subscribes'] as $event) {
if ($event == 'text') {
continue;
}
$subscribe[$event][] = $module['name'];
}
}
}
}
$module_ban = $_W['setting']['module_receive_ban'];
foreach ($subscribe as $event => $module_group) {
if (!empty($module_group)) {
foreach ($module_group as $index => $module) {
if (!empty($module_ban[$module])) {
unset($subscribe[$event][$index]);
}
}
}
}
// 订阅的消息类型缓存对象
cache_write('module_receive_enable', $subscribe);
}
function cache_build_platform() {
return pdo_query("DELETE FROM ".tablename('core_cache')." WHERE `key` LIKE 'account%' AND `key` <> 'account:ticket';");
}

View File

@@ -0,0 +1,149 @@
<?php
defined('IN_IA') or exit('Access Denied');
define('ALIPAY_GATEWAY', 'https://mapi.alipay.com/gateway.do');
function alipay_build($params, $alipay = array()) {
global $_W;
$tid = $params['uniontid'];
$set = array();
$set['service'] = 'alipay.wap.create.direct.pay.by.user';
$set['partner'] = $alipay['partner'];
$set['_input_charset'] = 'utf-8';
$set['sign_type'] = 'MD5';
$set['notify_url'] = $_W['siteroot'] . 'payment/alipay/notify.php';
$set['return_url'] = $_W['siteroot'] . 'payment/alipay/return.php';
$set['out_trade_no'] = $tid;
$set['subject'] = $params['title'];
$set['total_fee'] = $params['fee'];
$set['seller_id'] = $alipay['account'];
$set['payment_type'] = 1;
$set['body'] = $_W['uniacid'];
$prepares = array();
foreach($set as $key => $value) {
if($key != 'sign' && $key != 'sign_type') {
$prepares[] = "{$key}={$value}";
}
}
sort($prepares);
$string = implode('&', $prepares);
$string .= $alipay['secret'];
$set['sign'] = md5($string);
$response = ihttp_request(ALIPAY_GATEWAY . '?' . http_build_query($set, '', '&'), array(), array('CURLOPT_FOLLOWLOCATION' => 0));
return array('url' => $response['headers']['Location']);
}
function wechat_build($params, $wechat) {
global $_W;
load()->func('communication');
if (empty($wechat['version']) && !empty($wechat['signkey'])) {
$wechat['version'] = 1;
}
$wOpt = array();
if ($wechat['version'] == 1) {// 旧版微信支付接口
$wOpt['appId'] = $wechat['appid']; // 商户APPID
$wOpt['timeStamp'] = TIMESTAMP; // 当前时间戳
$wOpt['nonceStr'] = random(8); // 8位随机字符
$package = array();
$package['bank_type'] = 'WX';
$package['body'] = $params['title'];
$package['attach'] = $_W['uniacid'];
$package['partner'] = $wechat['partner'];
$package['out_trade_no'] = $params['uniontid'];
$package['total_fee'] = $params['fee'] * 100;
$package['fee_type'] = '1';
$package['notify_url'] = $_W['siteroot'] . 'payment/wechat/notify.php';
$package['spbill_create_ip'] = CLIENT_IP;
$package['time_start'] = date('YmdHis', TIMESTAMP);
$package['time_expire'] = date('YmdHis', TIMESTAMP + 600);
$package['input_charset'] = 'UTF-8';
ksort($package);
$string1 = '';
foreach($package as $key => $v) {
if (empty($v)) {
continue;
}
$string1 .= "{$key}={$v}&";
}
$string1 .= "key={$wechat['key']}";
$sign = strtoupper(md5($string1));
$string2 = '';
foreach($package as $key => $v) {
$v = urlencode($v);
$string2 .= "{$key}={$v}&";
}
$string2 .= "sign={$sign}";
$wOpt['package'] = $string2;
$string = '';
$keys = array('appId', 'timeStamp', 'nonceStr', 'package', 'appKey');
sort($keys);
foreach($keys as $key) {
$v = $wOpt[$key];
if($key == 'appKey') {
$v = $wechat['signkey'];
}
$key = strtolower($key);
$string .= "{$key}={$v}&";
}
$string = rtrim($string, '&');
$wOpt['signType'] = 'SHA1';
$wOpt['paySign'] = sha1($string);
return $wOpt;
} else {
$package = array();
$package['appid'] = $wechat['appid']; // 支付商户APPID
$package['mch_id'] = $wechat['mchid']; // 微信支付商户号(MchId)
$package['nonce_str'] = random(8); // 8位随机字符
$package['body'] = $params['title']; // 支付标题
$package['attach'] = $params['attach']; // 支付回调内容
$package['out_trade_no'] = $params['uniontid'];// 订单编号
$package['total_fee'] = $params['fee'] * 100;// 微信支付单位为分
$package['spbill_create_ip'] = CLIENT_IP; // 支付客户端IP
$package['time_start'] = date('YmdHis', TIMESTAMP);// 支付发起时间戳
$package['time_expire'] = date('YmdHis', TIMESTAMP + 600);// 支付有效期
$package['notify_url'] = $_W['siteroot'] . 'callback/';// 支付回调地址
$package['trade_type'] = 'JSAPI';
$package['openid'] = $params['from_user'];
ksort($package, SORT_STRING);
$string1 = '';
foreach($package as $key => $v) {
if (empty($v)) {
continue;
}
$string1 .= "{$key}={$v}&";
}
$string1 .= "key={$wechat['signkey']}";
$package['sign'] = strtoupper(md5($string1));
$dat = array2xml($package);
$response = ihttp_request('https://api.mch.weixin.qq.com/pay/unifiedorder', $dat,false);
if (is_error($response)) {
return $response;
}
$xml = @isimplexml_load_string($response['content'], 'SimpleXMLElement', LIBXML_NOCDATA);
if (strval($xml->return_code) == 'FAIL') {
return error(-1, strval($xml->return_msg));
}
if (strval($xml->result_code) == 'FAIL') {
return error(-1, strval($xml->err_code).': '.strval($xml->err_code_des));
}
$prepayid = $xml->prepay_id;
$wOpt['appId'] = $wechat['appid'];
$wOpt['timeStamp'] = TIMESTAMP;
$wOpt['nonceStr'] = random(8);
$wOpt['package'] = 'prepay_id='.$prepayid;
$wOpt['signType'] = 'MD5';
ksort($wOpt, SORT_STRING);
foreach($wOpt as $key => $v) {
$string .= "{$key}={$v}&";
}
$string .= "key={$wechat['signkey']}";
$wOpt['paySign'] = strtoupper(md5($string));
return $wOpt;
}
}

View File

@@ -0,0 +1,454 @@
<?php
defined('IN_IA') or exit('Access Denied');
use phprs\ezsql\Sql;
define('AUTHTYPE_WECHAT', 0);
define('AUTHTYPE_QQ', 1);
define('AUTHTYPE_JKX', 2);
define('AUTHTYPE_MEMBER', 3);
define('AUTHTYPE_NIUNIUGAME', 4);
// 查询指定的openId和门店Key查询是否存在全局用户信息
function getUserByOpenId($market_key, $UId, $type, $db)
{
$userInfo = array();
switch ($type)
{
case AUTHTYPE_WECHAT: // 微信用户信息查询
$userInfo = Sql::select('a.*')
->from('syweb_users a,syweb_users_weixin b')
->where('b.uid=a.id and b.openid=? and a.market_key=?', $UId, $market_key)
->get($db, null);
break;
case AUTHTYPE_QQ: // QQ用户信息查询
$userInfo = Sql::select('a.*')
->from('syweb_users a,syweb_users_qq b')
->where('b.uid=a.id and b.openid=? and a.market_key=?', $UId, $market_key)
->get($db, null);
break;
case AUTHTYPE_JKX: // 聚开心会员信息查询
$userInfo = Sql::select('a.*')
->from('syweb_users a,syweb_users_jkx b')
->where('b.uid=a.id and b.username=? and a.market_key=?', $UId, $market_key)
->get($db, null);
break;
case AUTHTYPE_MEMBER: // 会员注册登录
$userInfo = Sql::select('a.*')
->from('syweb_users a,syweb_users_normal b')
->where('b.uid=a.id and b.username=? and a.market_key=?', $UId, $market_key)
->get($db, null);
break;
case AUTHTYPE_NIUNIUGAME: // 友乐牛牛注册登录
$userInfo = Sql::select('a.*')
->from('syweb_users a,syweb_users_ylnn b')
->where('b.uid=a.id and b.user_key=? and a.market_key=?', $UId, $market_key)
->get($db, null);
break;
default:
break;
}
if (!empty($userInfo) && count($userInfo) > 0)
return $userInfo[0];
else
return null;
}
function get_wechat_by_user_id($market_key, $open_id, $union_id, $db)
{
if (!empty($union_id))
$userInfo = Sql::select('a.*')
->from('syweb_users a,syweb_users_weixin b')
->where('b.uid = a.id and a.market_key = ? and b.unionid = ?', $market_key, $union_id)
->get($db, null);
else
$userInfo = Sql::select('a.*')
->from('syweb_users a,syweb_users_weixin b')
->where('b.uid = a.id and a.market_key = ? and b.openid = ?', $market_key, $open_id)
->get($db, null);
if (!empty($userInfo) && count($userInfo) > 0)
return $userInfo[0];
else
return null;
}
// 查询指定的openId微信用户是否存在
function getUserById($id, $db)
{
$userInfo = Sql::select('a.*')
->from('syweb_users a')
->where('a.id=?', $id)
->get($db, null);
if (count($userInfo) > 0)
{
return $userInfo[0];
}
return null;
}
// 根据UID查询微信粉丝详细信息
function getWeixinUserByUId($uid, $db)
{
$weixinUserInfo = Sql::select('a.*')
->from('syweb_users_weixin a')
->where('a.uid=?', $uid)
->get($db, null);
if (count($weixinUserInfo) > 0)
{
return $weixinUserInfo[0];
}
return null;
}
// 根据UID查询聚开心粉丝详细信息
function getJkxUserByUId($uid, $db)
{
$weixinUserInfo = Sql::select('a.*')
->from('syweb_users_jkx a')
->where('a.uid=?', $uid)
->get($db, null);
if (count($weixinUserInfo) > 0)
{
return $weixinUserInfo[0];
}
return null;
}
// 根据UID查询友乐牛牛粉丝详细信息
function getYlnnUserByUId($uid, $db)
{
$userInfo = Sql::select('a.*')
->from('syweb_users_ylnn a')
->where('a.uid=?', $uid)
->get($db, null);
if (count($userInfo) > 0)
{
return $userInfo[0];
}
return null;
}
// 根据UID查询微信粉丝详细信息
function getQqUserByUId($uid, $db)
{
$qqUserInfo = Sql::select('syweb_users_qq.*')
->from('syweb_users_qq')
->where('syweb_users_qq.uid=?', $uid)
->get($db, null);
if (!empty($qqUserInfo) > 0 && count($qqUserInfo) > 0)
{
return $qqUserInfo[0];
}
return null;
}
// 增加/更新用户信息
function updateUserInfo($scode, $auth_type, $open_id, $union_id, $market_key, $db, $pdo)
{
// 首先验证指定的账号在全局用户信息中是否存在对应的记录
if (!empty($union_id))
$user_exist = Sql::select('a.id')
->from('syweb_users a')
->where('a.unionid = ? and a.market_key = ? and a.auth_type = ?', $union_id, $market_key, $auth_type)
->get($db, null);
else
$user_exist = Sql::select('a.id')
->from('syweb_users a')
->where('a.openid = ? and a.market_key = ? and a.auth_type = ?', $open_id, $market_key, $auth_type)
->get($db, null);
// 循环创建用户全局唯一ID(临时绑定20分钟有效)
$sid = random(32, false);
while (true)
{
$sid_exist = Sql::select('a.sid')
->from('syweb_users a')
->where('a.sid=?', $sid)
->get($db, null);
if ($sid_exist)
$sid = random(32, false);
else
break;
}
// 循环创建access_id(长时间绑定30天有效)
$access_id = "gm_" . random(13, false);
while (true)
{
$access_id_exist = Sql::select('a.sid')
->from('syweb_users a')
->where('a.access_id=?', $access_id)
->get($db, null);
if ($access_id_exist)
$access_id = "gm_" . random(13, false);
else
break;
}
$access_key = random(36, false);
while (true)
{
$access_key_exist = Sql::select('a.sid')
->from('syweb_users a')
->where('a.access_key=?', $access_key)
->get($db, null);
if ($access_key_exist)
$access_key = random(36, false);
else
break;
}
//SID过期时间(默认2天内有效)
$sid_expire_time = time() + (2 * 24 * 60 * 60);
//AccessToken过期时间(默认两个月内有效)
$access_expire_time = time() + (60 * 24 * 60 * 60);
// 假如当前username不存在则新增一条对应的全局用户记录
if (empty($user_exist) || count($user_exist) <= 0)
{
$data = array(
'main_account_id' => '', /// 默认没有绑定主账户
'sid' => $sid,
'scode' => $scode,
'sid_expire_time' => $sid_expire_time,
'access_id' => $access_id,
'access_key' => $access_key,
'access_expire_time' => $access_expire_time,
'market_key' => $market_key,
'auth_type' => $auth_type,
'openid' => $open_id,
'unionid' => $union_id,
'market_jifen' => 0,
'create_time' => TIMESTAMP,
);
$id = Sql::insertInto('syweb_users')->values($data)->exec($pdo)->lastInsertId();
if (!$id)
return -1;
else
return $id;
}
else
{
// 假如当前username存在则修改一条对应的全局用户记录
$data = array(
'sid' => $sid,
'scode' => $scode,
'sid_expire_time' => $sid_expire_time,
'access_id' => $access_id,
'access_key' => $access_key,
'access_expire_time' => $access_expire_time,
'auth_type' => $auth_type,
);
Sql::update('syweb_users')->setArgs($data)->where('id = ?', $user_exist[0]['id'])->exec($pdo);
return $user_exist[0]['id'];
}
}
// 更新微信用户信息
function updateWeixinUserInfo($weixinUserInfo, $db, $pdo)
{
$uid_exist = Sql::select('a.id')
->from('syweb_users_weixin a')
->where('a.uid=? and a.openid=?', $weixinUserInfo["uid"], $weixinUserInfo["openid"])
->get($db, null);
if (empty($uid_exist) || count($uid_exist) <= 0)
{
// 假如当前uid不存在
$insertData = array();
$insertData['uid'] = $weixinUserInfo["uid"];
$insertData['nickname'] = $weixinUserInfo["nickname"];
$insertData['sex'] = $weixinUserInfo["sex"];
$insertData['province'] = $weixinUserInfo["province"];
$insertData['city'] = $weixinUserInfo["city"];
$insertData['country'] = $weixinUserInfo["country"];
$insertData['headimgurl'] = $weixinUserInfo["headimgurl"];
$insertData['privilege'] = $weixinUserInfo["privilege"];
$insertData['subscribe'] = $weixinUserInfo["subscribe"];
$insertData['subscribe_time'] = $weixinUserInfo["subscribe_time"];
$insertData['openid'] = $weixinUserInfo["openid"];
$insertData['unionid'] = $weixinUserInfo["unionid"];
$id = Sql::insertInto('syweb_users_weixin')->values($insertData)->exec($pdo)->lastInsertId();
if (!$id)
{
return -1;
}
return $id;
}
else
{
$updateData = array();
$updateData['nickname'] = $weixinUserInfo["nickname"];
$updateData['sex'] = $weixinUserInfo["sex"];
$updateData['province'] = $weixinUserInfo["province"];
$updateData['city'] = $weixinUserInfo["city"];
$updateData['country'] = $weixinUserInfo["country"];
$updateData['headimgurl'] = $weixinUserInfo["headimgurl"];
$updateData['privilege'] = $weixinUserInfo["privilege"];
$updateData['subscribe'] = $weixinUserInfo["subscribe"];
$updateData['subscribe_time'] = $weixinUserInfo["subscribe_time"];
$updateData['unionid'] = $weixinUserInfo["unionid"];
Sql::update('syweb_users_weixin')->setArgs($updateData)->where('uid=? and openid=?', $weixinUserInfo["uid"], $weixinUserInfo["openid"])->exec($pdo);
return $uid_exist["id"];
}
}
// 更新QQ用户信息
function updateQqUserInfo($qqUserInfo, $db, $pdo)
{
$uid_exist = Sql::select('syweb_users_qq.id')
->from('syweb_users_qq')
->where('syweb_users_qq.uid=? and syweb_users_qq.openid=?', $qqUserInfo["uid"], $qqUserInfo["openid"])
->get($db, null);
if (empty($uid_exist))
{
// 假如当前uid不存在
$insertData = array();
$insertData['uid'] = $qqUserInfo["uid"];
$insertData['gender'] = $qqUserInfo["gender"];
$insertData['nickname'] = $qqUserInfo["nickname"];
$insertData['province'] = $qqUserInfo["province"];
$insertData['city'] = $qqUserInfo["city"];
$insertData['year'] = $qqUserInfo["year"];
$insertData['figureurl_qq_1'] = $qqUserInfo["figureurl_qq_1"];
$insertData['figureurl_qq_2'] = $qqUserInfo["figureurl_qq_2"];
$insertData['figureurl'] = $qqUserInfo["figureurl"];
$insertData['figureurl_1'] = $qqUserInfo["figureurl_1"];
$insertData['figureurl_2'] = $qqUserInfo["figureurl_2"];
$insertData['vip'] = $qqUserInfo["vip"];
$insertData['level'] = $qqUserInfo["level"];
$insertData['is_yellow_year_vip'] = $qqUserInfo["is_yellow_year_vip"];
$insertData['yellow_vip_level'] = $qqUserInfo["yellow_vip_level"];
$insertData['openid'] = $qqUserInfo["openid"];
$id = Sql::insertInto('syweb_users_qq')->values($insertData)->exec($pdo)->lastInsertId();
if (!$id)
{
return -1;
}
return $id;
}
else
{
$updateData = array();
$updateData['gender'] = $qqUserInfo["gender"];
$updateData['nickname'] = $qqUserInfo["nickname"];
$updateData['province'] = $qqUserInfo["province"];
$updateData['city'] = $qqUserInfo["city"];
$updateData['year'] = $qqUserInfo["year"];
$updateData['figureurl_qq_1'] = $qqUserInfo["figureurl_qq_1"];
$updateData['figureurl_qq_2'] = $qqUserInfo["figureurl_qq_2"];
$updateData['figureurl'] = $qqUserInfo["figureurl"];
$updateData['figureurl_1'] = $qqUserInfo["figureurl_1"];
$updateData['figureurl_2'] = $qqUserInfo["figureurl_2"];
$updateData['vip'] = $qqUserInfo["vip"];
$updateData['level'] = $qqUserInfo["level"];
$updateData['is_yellow_year_vip'] = $qqUserInfo["is_yellow_year_vip"];
$updateData['yellow_vip_level'] = $qqUserInfo["yellow_vip_level"];
Sql::update('syweb_users_qq')->setArgs($updateData)->where('uid=? and openid=?', $qqUserInfo["uid"], $qqUserInfo["openid"])->exec($pdo);
return $uid_exist["id"];
}
}
// 更新聚开心用户信息
function updateJkxUserInfo($userInfo, $db, $pdo)
{
$uid_exist = Sql::select('a.id')
->from('syweb_users_jkx a')
->where('a.uid=? and a.username=?', $userInfo["uid"], $userInfo["username"])
->get($db, null);
if (empty($uid_exist) || count($uid_exist) <= 0)
{
// 假如当前uid不存在
$insertData = array();
$insertData['uid'] = $userInfo["uid"];
$insertData['level'] = $userInfo["level"];
$insertData['enum'] = $userInfo["enum"];
$insertData['realname'] = $userInfo["realname"];
$insertData['tel'] = $userInfo["tel"];
$insertData['headimgurl'] = $userInfo["headimgurl"];
$insertData['username'] = $userInfo["username"];
$insertData['integral'] = $userInfo["integral"];
$id = Sql::insertInto('syweb_users_jkx')->values($insertData)->exec($pdo)->lastInsertId();
if (!$id)
{
return -1;
}
return $id;
}
else
{
$updateData = array();
$updateData['level'] = $userInfo["level"];
$updateData['enum'] = $userInfo["enum"];
$updateData['realname'] = $userInfo["realname"];
$updateData['tel'] = $userInfo["tel"];
$updateData['headimgurl'] = $userInfo["headimgurl"];
$updateData['integral'] = $userInfo["integral"];
Sql::update('syweb_users_jkx')->setArgs($updateData)->where('uid=? and username=?', $userInfo["uid"], $userInfo["username"])->exec($pdo);
return $uid_exist["id"];
}
}
// 更新友乐牛牛用户信息
function updateYlnnUserInfo($userInfo, $db, $pdo)
{
$uid_exist = Sql::select('a.id')
->from('syweb_users_ylnn a')
->where('a.uid=? and a.user_key=?', $userInfo["uid"], $userInfo["user_key"])
->get($db, null);
if (empty($uid_exist) || count($uid_exist) <= 0)
{
// 假如当前uid不存在
$insertData = array();
$insertData['uid'] = $userInfo["uid"];
$insertData['user_key'] = $userInfo["user_key"];
$insertData['agent_key'] = $userInfo["agent_key"];
$insertData['game_key'] = $userInfo["game_key"];
$insertData['player_key'] = $userInfo["player_key"];
$insertData['headimgurl'] = $userInfo["headimgurl"];
$insertData['nickname'] = $userInfo["nickname"];
$id = Sql::insertInto('syweb_users_ylnn')->values($insertData)->exec($pdo)->lastInsertId();
if (!$id)
{
return -1;
}
return $id;
}
else
{
$updateData = array();
$updateData['agent_key'] = $userInfo["agent_key"];
$updateData['game_key'] = $userInfo["game_key"];
$updateData['player_key'] = $userInfo["player_key"];
$updateData['headimgurl'] = $userInfo["headimgurl"];
$updateData['nickname'] = $userInfo["nickname"];
Sql::update('syweb_users_ylnn')->setArgs($updateData)->where('uid=? and user_key=?', $userInfo["uid"], $userInfo["user_key"])->exec($pdo);
return $uid_exist["id"];
}
}

View File

@@ -0,0 +1,439 @@
<?php
defined('IN_IA') or exit('Access Denied');
use phprs\ezsql\Sql;
define('AUTHTYPE_WECHAT', 0);
define('AUTHTYPE_QQ', 1);
define('AUTHTYPE_JKX', 2);
define('AUTHTYPE_MEMBER', 3);
define('AUTHTYPE_NIUNIUGAME', 4);
// 查询指定的openId和门店Key查询是否存在全局用户信息
function getUserByOpenId($market_key, $UId, $type, $db)
{
$userInfo = array();
switch ($type)
{
case AUTHTYPE_WECHAT: // 微信用户信息查询
$userInfo = Sql::select('a.*')
->from('syweb_users a,syweb_users_weixin b')
->where('b.uid=a.id and b.openid=? and a.market_key=?', $UId, $market_key)
->get($db, null);
break;
case AUTHTYPE_QQ: // QQ用户信息查询
$userInfo = Sql::select('a.*')
->from('syweb_users a,syweb_users_qq b')
->where('b.uid=a.id and b.openid=? and a.market_key=?', $UId, $market_key)
->get($db, null);
break;
case AUTHTYPE_JKX: // 聚开心会员信息查询
$userInfo = Sql::select('a.*')
->from('syweb_users a,syweb_users_jkx b')
->where('b.uid=a.id and b.username=? and a.market_key=?', $UId, $market_key)
->get($db, null);
break;
case AUTHTYPE_MEMBER: // 会员注册登录
$userInfo = Sql::select('a.*')
->from('syweb_users a,syweb_users_normal b')
->where('b.uid=a.id and b.username=? and a.market_key=?', $UId, $market_key)
->get($db, null);
break;
case AUTHTYPE_NIUNIUGAME: // 友乐牛牛注册登录
$userInfo = Sql::select('a.*')
->from('syweb_users a,syweb_users_ylnn b')
->where('b.uid=a.id and b.user_key=? and a.market_key=?', $UId, $market_key)
->get($db, null);
break;
default:
break;
}
if (!empty($userInfo) && count($userInfo) > 0)
{
return $userInfo[0];
}
return null;
}
// 查询指定的openId微信用户是否存在
function getUserById($id, $db)
{
$userInfo = Sql::select('a.*')
->from('syweb_users a')
->where('a.id=?', $id)
->get($db, null);
if (count($userInfo) > 0)
{
return $userInfo[0];
}
return null;
}
// 根据UID查询微信粉丝详细信息
function getWeixinUserByUId($uid, $db)
{
$weixinUserInfo = Sql::select('a.*')
->from('syweb_users_weixin a')
->where('a.uid=?', $uid)
->get($db, null);
if (count($weixinUserInfo) > 0)
{
return $weixinUserInfo[0];
}
return null;
}
// 根据UID查询聚开心粉丝详细信息
function getJkxUserByUId($uid, $db)
{
$weixinUserInfo = Sql::select('a.*')
->from('syweb_users_jkx a')
->where('a.uid=?', $uid)
->get($db, null);
if (count($weixinUserInfo) > 0)
{
return $weixinUserInfo[0];
}
return null;
}
// 根据UID查询友乐牛牛粉丝详细信息
function getYlnnUserByUId($uid, $db)
{
$userInfo = Sql::select('a.*')
->from('syweb_users_ylnn a')
->where('a.uid=?', $uid)
->get($db, null);
if (count($userInfo) > 0)
{
return $userInfo[0];
}
return null;
}
// 根据UID查询微信粉丝详细信息
function getQqUserByUId($uid, $db)
{
$qqUserInfo = Sql::select('syweb_users_qq.*')
->from('syweb_users_qq')
->where('syweb_users_qq.uid=?', $uid)
->get($db, null);
if (!empty($qqUserInfo) > 0 && count($qqUserInfo) > 0)
{
return $qqUserInfo[0];
}
return null;
}
// 增加/更新用户信息
function updateUserInfo($scode, $auth_type, $username, $market_key, $db, $pdo)
{
// 首先验证指定的账号在全局用户信息中是否存在对应的记录
$user_exist = Sql::select('a.id')
->from('syweb_users a')
->where('a.openid=? and a.market_key=? and a.auth_type=?', $username, $market_key, $auth_type)
->get($db, null);
// 循环创建用户全局唯一ID(临时绑定20分钟有效)
$sid = random(32, false);
while (true)
{
$sid_exist = Sql::select('a.sid')
->from('syweb_users a')
->where('a.sid=?', $sid)
->get($db, null);
if ($sid_exist)
{
$sid = random(32, false);
}
else
{
break;
}
}
// 循环创建access_id(长时间绑定30天有效)
$access_id = "gm_" . random(13, false);
while (true)
{
$access_id_exist = Sql::select('a.sid')
->from('syweb_users a')
->where('a.access_id=?', $access_id)
->get($db, null);
if ($access_id_exist)
{
$access_id_exist = "gm_" . random(13, false);
}
else
{
break;
}
}
$access_key = random(36, false);
while (true)
{
$access_key_exist = Sql::select('a.sid')
->from('syweb_users a')
->where('a.access_key=?', $access_key)
->get($db, null);
if ($access_key_exist)
{
$access_key = random(36, false);
}
else
{
break;
}
}
//SID过期时间(默认2天内有效)
$sid_expire_time = time() + (2 * 24 * 60 * 60);
//AccessToken过期时间(默认两个月内有效)
$access_expire_time = time() + (60 * 24 * 60 * 60);
// 假如当前username不存在则新增一条对应的全局用户记录
if (empty($user_exist) || count($user_exist) <= 0)
{
$insertData = array();
$insertData['main_account_id'] = ""; // 默认没有绑定主账户
$insertData['sid'] = $sid;
$insertData['scode'] = $scode;
$insertData['sid_expire_time'] = $sid_expire_time;
$insertData['access_id'] = $access_id;
$insertData['access_key'] = $access_key;
$insertData['access_expire_time'] = $access_expire_time;
$insertData['market_key'] = $market_key;
$insertData['auth_type'] = $auth_type;
$insertData['openid'] = $username;
$insertData['market_jifen'] = 0;
$insertData['create_time'] = TIMESTAMP;
$id = Sql::insertInto('syweb_users')->values($insertData)->exec($pdo)->lastInsertId();
if (!$id)
{
return -1;
}
return $id;
}
else
{
// 假如当前username存在则修改一条对应的全局用户记录
$updateData = array();
$updateData['sid'] = $sid;
$updateData['scode'] = $scode;
$updateData['sid_expire_time'] = $sid_expire_time;
$updateData['access_id'] = $access_id;
$updateData['access_key'] = $access_key;
$updateData['access_expire_time'] = $access_expire_time;
$updateData['auth_type'] = $auth_type;
Sql::update('syweb_users')->setArgs($updateData)->where('openid=? and market_key=? and auth_type=?', $username, $market_key, $auth_type)->exec($pdo);
return $user_exist[0]["id"];
}
}
// 更新微信用户信息
function updateWeixinUserInfo($weixinUserInfo, $db, $pdo)
{
$uid_exist = Sql::select('a.id')
->from('syweb_users_weixin a')
->where('a.uid=? and a.openid=?', $weixinUserInfo["uid"], $weixinUserInfo["openid"])
->get($db, null);
if (empty($uid_exist) || count($uid_exist) <= 0)
{
// 假如当前uid不存在
$insertData = array();
$insertData['uid'] = $weixinUserInfo["uid"];
$insertData['nickname'] = $weixinUserInfo["nickname"];
$insertData['sex'] = $weixinUserInfo["sex"];
$insertData['province'] = $weixinUserInfo["province"];
$insertData['city'] = $weixinUserInfo["city"];
$insertData['country'] = $weixinUserInfo["country"];
$insertData['headimgurl'] = $weixinUserInfo["headimgurl"];
$insertData['privilege'] = $weixinUserInfo["privilege"];
$insertData['subscribe'] = $weixinUserInfo["subscribe"];
$insertData['subscribe_time'] = $weixinUserInfo["subscribe_time"];
$insertData['openid'] = $weixinUserInfo["openid"];
$insertData['unionid'] = $weixinUserInfo["unionid"];
$id = Sql::insertInto('syweb_users_weixin')->values($insertData)->exec($pdo)->lastInsertId();
if (!$id)
{
return -1;
}
return $id;
}
else
{
$updateData = array();
$updateData['nickname'] = $weixinUserInfo["nickname"];
$updateData['sex'] = $weixinUserInfo["sex"];
$updateData['province'] = $weixinUserInfo["province"];
$updateData['city'] = $weixinUserInfo["city"];
$updateData['country'] = $weixinUserInfo["country"];
$updateData['headimgurl'] = $weixinUserInfo["headimgurl"];
$updateData['privilege'] = $weixinUserInfo["privilege"];
$updateData['subscribe'] = $weixinUserInfo["subscribe"];
$updateData['subscribe_time'] = $weixinUserInfo["subscribe_time"];
$updateData['unionid'] = $weixinUserInfo["unionid"];
Sql::update('syweb_users_weixin')->setArgs($updateData)->where('uid=? and openid=?', $weixinUserInfo["uid"], $weixinUserInfo["openid"])->exec($pdo);
return $uid_exist["id"];
}
}
// 更新QQ用户信息
function updateQqUserInfo($qqUserInfo, $db, $pdo)
{
$uid_exist = Sql::select('syweb_users_qq.id')
->from('syweb_users_qq')
->where('syweb_users_qq.uid=? and syweb_users_qq.openid=?', $qqUserInfo["uid"], $qqUserInfo["openid"])
->get($db, null);
if (empty($uid_exist))
{
// 假如当前uid不存在
$insertData = array();
$insertData['uid'] = $qqUserInfo["uid"];
$insertData['gender'] = $qqUserInfo["gender"];
$insertData['nickname'] = $qqUserInfo["nickname"];
$insertData['province'] = $qqUserInfo["province"];
$insertData['city'] = $qqUserInfo["city"];
$insertData['year'] = $qqUserInfo["year"];
$insertData['figureurl_qq_1'] = $qqUserInfo["figureurl_qq_1"];
$insertData['figureurl_qq_2'] = $qqUserInfo["figureurl_qq_2"];
$insertData['figureurl'] = $qqUserInfo["figureurl"];
$insertData['figureurl_1'] = $qqUserInfo["figureurl_1"];
$insertData['figureurl_2'] = $qqUserInfo["figureurl_2"];
$insertData['vip'] = $qqUserInfo["vip"];
$insertData['level'] = $qqUserInfo["level"];
$insertData['is_yellow_year_vip'] = $qqUserInfo["is_yellow_year_vip"];
$insertData['yellow_vip_level'] = $qqUserInfo["yellow_vip_level"];
$insertData['openid'] = $qqUserInfo["openid"];
$id = Sql::insertInto('syweb_users_qq')->values($insertData)->exec($pdo)->lastInsertId();
if (!$id)
{
return -1;
}
return $id;
}
else
{
$updateData = array();
$updateData['gender'] = $qqUserInfo["gender"];
$updateData['nickname'] = $qqUserInfo["nickname"];
$updateData['province'] = $qqUserInfo["province"];
$updateData['city'] = $qqUserInfo["city"];
$updateData['year'] = $qqUserInfo["year"];
$updateData['figureurl_qq_1'] = $qqUserInfo["figureurl_qq_1"];
$updateData['figureurl_qq_2'] = $qqUserInfo["figureurl_qq_2"];
$updateData['figureurl'] = $qqUserInfo["figureurl"];
$updateData['figureurl_1'] = $qqUserInfo["figureurl_1"];
$updateData['figureurl_2'] = $qqUserInfo["figureurl_2"];
$updateData['vip'] = $qqUserInfo["vip"];
$updateData['level'] = $qqUserInfo["level"];
$updateData['is_yellow_year_vip'] = $qqUserInfo["is_yellow_year_vip"];
$updateData['yellow_vip_level'] = $qqUserInfo["yellow_vip_level"];
Sql::update('syweb_users_qq')->setArgs($updateData)->where('uid=? and openid=?', $qqUserInfo["uid"], $qqUserInfo["openid"])->exec($pdo);
return $uid_exist["id"];
}
}
// 更新聚开心用户信息
function updateJkxUserInfo($userInfo, $db, $pdo)
{
$uid_exist = Sql::select('a.id')
->from('syweb_users_jkx a')
->where('a.uid=? and a.username=?', $userInfo["uid"], $userInfo["username"])
->get($db, null);
if (empty($uid_exist) || count($uid_exist) <= 0)
{
// 假如当前uid不存在
$insertData = array();
$insertData['uid'] = $userInfo["uid"];
$insertData['level'] = $userInfo["level"];
$insertData['enum'] = $userInfo["enum"];
$insertData['realname'] = $userInfo["realname"];
$insertData['tel'] = $userInfo["tel"];
$insertData['headimgurl'] = $userInfo["headimgurl"];
$insertData['username'] = $userInfo["username"];
$insertData['integral'] = $userInfo["integral"];
$id = Sql::insertInto('syweb_users_jkx')->values($insertData)->exec($pdo)->lastInsertId();
if (!$id)
{
return -1;
}
return $id;
}
else
{
$updateData = array();
$updateData['level'] = $userInfo["level"];
$updateData['enum'] = $userInfo["enum"];
$updateData['realname'] = $userInfo["realname"];
$updateData['tel'] = $userInfo["tel"];
$updateData['headimgurl'] = $userInfo["headimgurl"];
$updateData['integral'] = $userInfo["integral"];
Sql::update('syweb_users_jkx')->setArgs($updateData)->where('uid=? and username=?', $userInfo["uid"], $userInfo["username"])->exec($pdo);
return $uid_exist["id"];
}
}
// 更新友乐牛牛用户信息
function updateYlnnUserInfo($userInfo, $db, $pdo)
{
$uid_exist = Sql::select('a.id')
->from('syweb_users_ylnn a')
->where('a.uid=? and a.user_key=?', $userInfo["uid"], $userInfo["user_key"])
->get($db, null);
if (empty($uid_exist) || count($uid_exist) <= 0)
{
// 假如当前uid不存在
$insertData = array();
$insertData['uid'] = $userInfo["uid"];
$insertData['user_key'] = $userInfo["user_key"];
$insertData['agent_key'] = $userInfo["agent_key"];
$insertData['game_key'] = $userInfo["game_key"];
$insertData['player_key'] = $userInfo["player_key"];
$insertData['headimgurl'] = $userInfo["headimgurl"];
$insertData['nickname'] = $userInfo["nickname"];
$id = Sql::insertInto('syweb_users_ylnn')->values($insertData)->exec($pdo)->lastInsertId();
if (!$id)
{
return -1;
}
return $id;
}
else
{
$updateData = array();
$updateData['agent_key'] = $userInfo["agent_key"];
$updateData['game_key'] = $userInfo["game_key"];
$updateData['player_key'] = $userInfo["player_key"];
$updateData['headimgurl'] = $userInfo["headimgurl"];
$updateData['nickname'] = $userInfo["nickname"];
Sql::update('syweb_users_ylnn')->setArgs($updateData)->where('uid=? and user_key=?', $userInfo["uid"], $userInfo["user_key"])->exec($pdo);
return $uid_exist["id"];
}
}