Browse Source

部署到git

master
wanghongjun 2 years ago
parent
commit
10af7b9dd5
  1. 189
      app/common/bootstrap.app.inc.php
  2. 47
      app/common/common.func.php
  3. 60
      app/index.php
  4. 279
      app/source/auth/oauth.ctrl.php
  5. 40
      app/source/entry/__init.php
  6. 10
      app/source/entry/site.ctrl.php
  7. 171
      framework/bootstrap.inc.php
  8. 1
      framework/builtin/core/index.html
  9. 353
      framework/builtin/core/module.php
  10. 170
      framework/builtin/core/processor.php
  11. 133
      framework/builtin/core/receiver.php
  12. 272
      framework/builtin/core/site.php
  13. 863
      framework/builtin/core/template/display.html
  14. 88
      framework/builtin/core/template/mobile/detail.html
  15. 91
      framework/builtin/core/template/mobile/pay.html
  16. 60
      framework/builtin/core/wxapp.php
  17. 40
      framework/builtin/cover/processor.php
  18. 29
      framework/builtin/default/processor.php
  19. 2313
      framework/class/account/account.class.php
  20. 1810
      framework/class/account/weixin.account.class.php
  21. 376
      framework/class/account/weixin.platform.class.php
  22. 187
      framework/class/captcha.class.php
  23. 835
      framework/class/db.class.php
  24. 304
      framework/class/image.class.php
  25. 308
      framework/class/loader.class.php
  26. 212
      framework/class/oauth2/mobile.class.php
  27. 191
      framework/class/oauth2/oauth2client.class.php
  28. 139
      framework/class/oauth2/system.class.php
  29. 490
      framework/class/query.class.php
  30. 115
      framework/class/slave.db.class.php
  31. 457
      framework/class/table.class.php
  32. 252
      framework/class/uploadedfile.class.php
  33. 565
      framework/class/validator.class.php
  34. 206
      framework/class/wesession.class.php
  35. 293
      framework/const.inc.php
  36. 61
      framework/function/cache.file.func.php
  37. 614
      framework/function/cache.func.php
  38. 169
      framework/function/cache.memcache.func.php
  39. 112
      framework/function/cache.mysql.func.php
  40. 153
      framework/function/cache.redis.func.php
  41. 500
      framework/function/communication.func.php
  42. 139
      framework/function/compat.biz.func.php
  43. 173
      framework/function/compat.func.php
  44. 320
      framework/function/db.func.php
  45. 891
      framework/function/file.func.php
  46. 1350
      framework/function/global.func.php
  47. 59
      framework/function/logging.func.php
  48. 143
      framework/function/pdo.func.php
  49. 245
      framework/function/safe.func.php
  50. 44
      framework/function/system.func.php
  51. 577
      framework/function/tpl.func.php
  52. 193
      framework/library/agent/agent.class.php
  53. 57
      framework/library/alioss/CHANGELOG.md
  54. 21
      framework/library/alioss/LICENSE.md
  55. 152
      framework/library/alioss/README.md
  56. 11
      framework/library/alioss/autoload.php
  57. 3
      framework/library/alioss/index.php
  58. 262
      framework/library/alioss/src/OSS/Core/MimeTypes.php
  59. 54
      framework/library/alioss/src/OSS/Core/OssException.php
  60. 448
      framework/library/alioss/src/OSS/Core/OssUtil.php
  61. 25
      framework/library/alioss/src/OSS/Http/LICENSE
  62. 937
      framework/library/alioss/src/OSS/Http/RequestCore.php
  63. 8
      framework/library/alioss/src/OSS/Http/RequestCore_Exception.php
  64. 56
      framework/library/alioss/src/OSS/Http/ResponseCore.php
  65. 78
      framework/library/alioss/src/OSS/Model/BucketInfo.php
  66. 39
      framework/library/alioss/src/OSS/Model/BucketListInfo.php
  67. 99
      framework/library/alioss/src/OSS/Model/CnameConfig.php
  68. 113
      framework/library/alioss/src/OSS/Model/CorsConfig.php
  69. 150
      framework/library/alioss/src/OSS/Model/CorsRule.php
  70. 88
      framework/library/alioss/src/OSS/Model/LifecycleAction.php
  71. 107
      framework/library/alioss/src/OSS/Model/LifecycleConfig.php
  72. 126
      framework/library/alioss/src/OSS/Model/LifecycleRule.php
  73. 134
      framework/library/alioss/src/OSS/Model/ListMultipartUploadInfo.php
  74. 97
      framework/library/alioss/src/OSS/Model/ListPartsInfo.php
  75. 86
      framework/library/alioss/src/OSS/Model/LoggingConfig.php
  76. 93
      framework/library/alioss/src/OSS/Model/ObjectInfo.php
  77. 126
      framework/library/alioss/src/OSS/Model/ObjectListInfo.php
  78. 63
      framework/library/alioss/src/OSS/Model/PartInfo.php
  79. 36
      framework/library/alioss/src/OSS/Model/PrefixInfo.php
  80. 93
      framework/library/alioss/src/OSS/Model/RefererConfig.php
  81. 55
      framework/library/alioss/src/OSS/Model/UploadInfo.php
  82. 76
      framework/library/alioss/src/OSS/Model/WebsiteConfig.php
  83. 27
      framework/library/alioss/src/OSS/Model/XmlConfig.php
  84. 2230
      framework/library/alioss/src/OSS/OssClient.php
  85. 33
      framework/library/alioss/src/OSS/Result/AclResult.php
  86. 27
      framework/library/alioss/src/OSS/Result/AppendResult.php
  87. 19
      framework/library/alioss/src/OSS/Result/BodyResult.php
  88. 35
      framework/library/alioss/src/OSS/Result/ExistResult.php
  89. 34
      framework/library/alioss/src/OSS/Result/GetCnameResult.php
  90. 35
      framework/library/alioss/src/OSS/Result/GetCorsResult.php
  91. 41
      framework/library/alioss/src/OSS/Result/GetLifecycleResult.php
  92. 41
      framework/library/alioss/src/OSS/Result/GetLoggingResult.php
  93. 41
      framework/library/alioss/src/OSS/Result/GetRefererResult.php
  94. 40
      framework/library/alioss/src/OSS/Result/GetWebsiteResult.php
  95. 23
      framework/library/alioss/src/OSS/Result/HeaderResult.php
  96. 29
      framework/library/alioss/src/OSS/Result/InitiateMultipartUploadResult.php
  97. 33
      framework/library/alioss/src/OSS/Result/ListBucketsResult.php
  98. 55
      framework/library/alioss/src/OSS/Result/ListMultipartUploadResult.php
  99. 71
      framework/library/alioss/src/OSS/Result/ListObjectsResult.php
  100. 42
      framework/library/alioss/src/OSS/Result/ListPartsResult.php

189
app/common/bootstrap.app.inc.php

@ -0,0 +1,189 @@
<?php
defined('IN_IA') or exit('Access Denied');
load()->app('common');
load()->model('mc');
load()->model('account');
load()->model('attachment');
load()->model('permission');
load()->model('module');
$_W['uniacid'] = intval($_GPC['i']);
if (empty($_W['uniacid'])) {
$_W['uniacid'] = intval($_GPC['weid']);
}
if (empty($_W['uniacid'])) {
header('HTTP/1.1 404 Not Found');
header("status: 404 Not Found");
exit;
}
$_W['uniaccount'] = $_W['account'] = uni_fetch($_W['uniacid']);
if (is_error($_W['account'])) {
message($_W['account']['message']);
}
if (!empty($_W['account']['isdeleted'])) {
message('指定公众号已被删除');
}
if (!empty($_W['uniaccount']['endtime']) && TIMESTAMP > $_W['uniaccount']['endtime'] && !in_array($_W['uniaccount']['endtime'], array(USER_ENDTIME_GROUP_EMPTY_TYPE, USER_ENDTIME_GROUP_UNLIMIT_TYPE))) {
message('抱歉,您的平台账号服务已过期,请及时联系管理员');
}
$_W['acid'] = $_W['uniaccount']['acid'];
if (!empty($_W['account']['setting']['bind_domain']) && !empty($_W['account']['setting']['bind_domain']['domain']) && strpos($_W['account']['setting']['bind_domain']['domain'], $_SERVER['HTTP_HOST']) === false) {
header('Location:' . $_W['account']['setting']['bind_domain']['domain'] . $_SERVER['REQUEST_URI']);
exit;
}
$_W['session_id'] = '';
if (isset($_GPC['state']) && !empty($_GPC['state']) && strexists($_GPC['state'], 'we7sid-')) {
$pieces = explode('-', $_GPC['state']);
$_W['session_id'] = $pieces[1];
unset($pieces);
}
if (empty($_W['session_id'])) {
$_W['session_id'] = $_COOKIE[session_name()];
}
if (empty($_W['session_id'])) {
$_W['session_id'] = "{$_W['uniacid']}-" . random(20);
$_W['session_id'] = md5($_W['session_id']);
setcookie(session_name(), $_W['session_id'], 0, '/');
}
session_id($_W['session_id']);
load()->classs('wesession');
WeSession::start($_W['uniacid'], $_W['clientip']);
if (!empty($_GPC['j'])) {
$acid = intval($_GPC['j']);
$_W['account'] = account_fetch($acid);
if (is_error($_W['account'])) {
$_W['account'] = account_fetch($_W['acid']);
} else {
$_W['acid'] = $acid;
}
$_SESSION['__acid'] = $_W['acid'];
$_SESSION['__uniacid'] = $_W['uniacid'];
}
if (!empty($_SESSION['__acid']) && $_SESSION['__uniacid'] == $_W['uniacid']) {
$_W['acid'] = intval($_SESSION['__acid']);
$_W['account'] = uni_fetch($_W['uniacid']);
}
if (strpos($_SERVER['QUERY_STRING'], 'favicon.ico') === false && ((!empty($_SESSION['acid']) && $_W['acid'] != $_SESSION['acid']) || (!empty($_SESSION['uniacid']) && $_W['uniacid'] != $_SESSION['uniacid']))) {
$keys = array_keys($_SESSION);
foreach ($keys as $key) {
unset($_SESSION[$key]);
}
unset($keys, $key);
}
$_SESSION['acid'] = $_W['acid'];
$_SESSION['uniacid'] = $_W['uniacid'];
if (!empty($_SESSION['openid'])) {
$_W['openid'] = $_SESSION['openid'];
$_W['fans'] = mc_fansinfo($_W['openid']);
$_W['fans']['from_user'] = $_W['fans']['openid'] = $_W['openid'];
}
if (!empty($_SESSION['uid']) || (!empty($_W['fans']) && !empty($_W['fans']['uid']))) {
$uid = intval($_SESSION['uid']);
if (empty($uid)) {
$uid = $_W['fans']['uid'];
}
_mc_login(array('uid' => $uid));
unset($uid);
}
if (empty($_W['openid']) && !empty($_SESSION['oauth_openid'])) {
$_W['openid'] = $_SESSION['oauth_openid'];
$_W['fans'] = array(
'openid' => $_SESSION['oauth_openid'],
'from_user' => $_SESSION['oauth_openid'],
'follow' => 0
);
}
$_W['oauth_account'] = $_W['account']['oauth'] = array(
'key' => $_W['account']['key'],
'secret' => $_W['account']['secret'],
'acid' => $_W['account']['acid'],
'type' => $_W['account']['type'],
'level' => $_W['account']['level'],
'support_oauthinfo' => $_W['account']->supportOauthInfo,
'support_jssdk' => $_W['account']->supportJssdk,
);
$unisetting = uni_setting_load();
if (empty($unisetting['oauth']) && $_W['account']->typeSign == 'account' && $_W['account']['level'] != ACCOUNT_SERVICE_VERIFY) {
$global_oauth = uni_account_global_oauth();
$unisetting['oauth'] = (array)$global_oauth['oauth'];
}
if (!empty($unisetting['oauth']['account'])) {
$oauth = uni_fetch($unisetting['oauth']['account']);
if (!empty($oauth) && $_W['account']['level'] <= $oauth['level']) {
$_W['oauth_account'] = $_W['account']['oauth'] = array(
'key' => $oauth['key'],
'secret' => $oauth['secret'],
'acid' => $oauth['acid'],
'type' => $oauth['type'],
'level' => $oauth['level'],
'support_oauthinfo' => $oauth->supportOauthInfo,
'support_jssdk' => $oauth->supportJssdk,
);
unset($oauth);
}
}
if ($controller != 'utility') {
$_W['token'] = token();
}
if (!empty($_W['account']['oauth']) && $_W['account']['oauth']['support_oauthinfo'] && empty($_W['isajax']) &&
(($_W['container'] == 'baidu' && $_W['account']->typeSign != 'account') || $_W['container'] != 'baidu')) {
if (($_W['platform'] == 'account' && !$_GPC['logout'] && empty($_W['openid']) && ($controller != 'auth' || ($controller == 'auth' && !in_array($action, array('forward', 'oauth'))))) ||
($_W['platform'] == 'account' && !$_GPC['logout'] && empty($_SESSION['oauth_openid']) && ($controller != 'auth'))) {
$state = 'we7sid-' . $_W['session_id'];
if (empty($_SESSION['dest_url'])) {
$_SESSION['dest_url'] = urlencode($_W['siteurl']);
}
$oauth_type = 'snsapi_base';
if ($controller == 'entry' && !empty($_GPC['m'])) {
$module_info = module_fetch($_GPC['m']);
if ($module_info['oauth_type'] == OAUTH_TYPE_USERINFO) {
$oauth_type = 'snsapi_userinfo';
}
}
if (intval($_W['account']['level']) != ACCOUNT_SERVICE_VERIFY) {
$oauth_type = 'snsapi_userinfo';
}
$oauth_url = uni_account_oauth_host();
$url = $oauth_url . "app/index.php?i={$_W['uniacid']}&c=auth&a=oauth&scope=" . $oauth_type;
$callback = urlencode($url);
$oauth_account = WeAccount::create($_W['account']['oauth']);
if ($oauth_type == 'snsapi_base') {
$forward = $oauth_account->getOauthCodeUrl($callback, $state);
} else {
$forward = $oauth_account->getOauthUserInfoUrl($callback, $state);
}
header('Location: ' . $forward);
exit();
}
}
if ($_W['platform'] == 'account' && $_W['account']->supportJssdk && $controller != 'utility') {
if (!empty($unisetting['jsauth_acid'])) {
$jsauth_acid = $unisetting['jsauth_acid'];
} else {
if ($_W['account']['level'] < ACCOUNT_SUBSCRIPTION_VERIFY && !empty($unisetting['oauth']['account'])) {
$jsauth_acid = $unisetting['oauth']['account'];
} else {
$jsauth_acid = $_W['acid'];
}
}
if (!empty($jsauth_acid)) {
$account_api = WeAccount::create($jsauth_acid);
if (!empty($account_api)) {
$_W['account']['jssdkconfig'] = $account_api->getJssdkConfig();
$_W['account']['jsauth_acid'] = $jsauth_acid;
}
}
unset($jsauth_acid, $account_api);
}
$_W['attachurl'] = attachment_set_attach_url();

47
app/common/common.func.php

@ -0,0 +1,47 @@
<?php
defined('IN_IA') or exit('Access Denied');
function url($segment, $params = array(), $noredirect = false)
{
return murl($segment, $params, $noredirect);
}
function message($msg, $redirect = '', $type = '')
{
global $_W;
if ($redirect == 'refresh') {
$redirect = $_W['script_name'] . '?' . $_SERVER['QUERY_STRING'];
} elseif (!empty($redirect) && !strexists($redirect, 'http://') && !strexists($redirect, 'https://')) {
$urls = parse_url($redirect);
$redirect = $_W['siteroot'] . 'app/index.php?' . $urls['query'];
} else {
$redirect = safe_gpc_url($redirect);
}
if ($redirect == '') {
$type = in_array($type, array('success', 'error', 'info', 'warning', 'ajax', 'sql')) ? $type : 'info';
} else {
$type = in_array($type, array('success', 'error', 'info', 'warning', 'ajax', 'sql')) ? $type : 'success';
}
if ($_W['isajax'] || $type == 'ajax') {
$vars = array();
$vars['message'] = $msg;
$vars['redirect'] = $redirect;
$vars['type'] = $type;
exit(json_encode($vars));
}
if (empty($msg) && !empty($redirect)) {
header('location: ' . $redirect);
}
$label = $type;
if ($type == 'error') {
$label = 'danger';
}
if ($type == 'ajax' || $type == 'sql') {
$label = 'warning';
}
if (defined('IN_API')) {
exit($msg);
}
include template('common/message', TEMPLATE_INCLUDEPATH);
exit();
}

60
app/index.php

@ -0,0 +1,60 @@
<?php
define('IN_MOBILE', true);
require '../framework/bootstrap.inc.php';
require IA_ROOT . '/app/common/bootstrap.app.inc.php';
$acl = array(
'home' => array(
'default' => 'home',
),
'mc' => array(
'default' => 'home'
)
);
if ($_W['setting']['copyright']['status'] == 1) {
$_W['siteclose'] = true;
message('抱歉,站点已关闭,关闭原因:' . $_W['setting']['copyright']['reason']);
}
$controllers = array();
$handle = opendir(IA_ROOT . '/app/source/');
if (!empty($handle)) {
while ($dir = readdir($handle)) {
if ($dir != '.' && $dir != '..') {
$controllers[] = $dir;
}
}
}
if (!in_array($controller, $controllers)) {
$controller = 'home';
}
$init = IA_ROOT . "/app/source/{$controller}/__init.php";
if (is_file($init)) {
require $init;
}
$actions = array();
$handle = opendir(IA_ROOT . '/app/source/' . $controller);
if (!empty($handle)) {
while ($dir = readdir($handle)) {
if ($dir != '.' && $dir != '..' && strexists($dir, '.ctrl.php')) {
$dir = str_replace('.ctrl.php', '', $dir);
$actions[] = $dir;
}
}
}
if (!in_array($action, $actions)) {
$action = $acl[$controller]['default'];
}
if (!in_array($action, $actions)) {
$action = $actions[0];
}
require _forward($controller, $action);
function _forward($c, $a)
{
$file = IA_ROOT . '/app/source/' . $c . '/' . $a . '.ctrl.php';
return $file;
}

279
app/source/auth/oauth.ctrl.php

@ -0,0 +1,279 @@
<?php
defined('IN_IA') or exit('Access Denied');
load()->func('communication');
$code = $_GPC['code'];
$scope = $_GPC['scope'];
if (empty($_W['account']['oauth']) || empty($code)) {
exit('通信错误,请在微信中重新发起请求');
}
$oauth_account = WeAccount::create($_W['account']['oauth']);
$oauth = $oauth_account->getOauthInfo($code);
if (is_error($oauth) || empty($oauth['openid'])) {
$state = '';
if (isset($_GPC['state']) && !empty($_GPC['state']) && strexists($_GPC['state'], 'we7sid-')) {
$state = $_GPC['state'];
}
$url = "{$_W['siteroot']}app/index.php?i={$_W['uniacid']}&c=auth&a=oauth&scope=snsapi_base";
$callback = urlencode($url);
$forward = $oauth_account->getOauthCodeUrl($callback, $state);
header('Location: ' . $forward);
exit;
}
$_SESSION['oauth_openid'] = $oauth['openid'];
$_SESSION['oauth_acid'] = $_W['account']['oauth']['acid'];
if (intval($_W['account']['level']) == ACCOUNT_SERVICE_VERIFY) {
$fan = mc_fansinfo($oauth['openid']);
if (!empty($fan)) {
$_SESSION['openid'] = $oauth['openid'];
if (empty($_SESSION['uid'])) {
if (!empty($fan['uid'])) {
$member = mc_fetch($fan['uid'], array('uid'));
if (!empty($member) && $member['uniacid'] == $_W['uniacid']) {
$_SESSION['uid'] = $member['uid'];
}
}
}
} else {
$accObj = WeAccount::createByUniacid($_W['uniacid']);
$userinfo = $accObj->fansQueryInfo($oauth['openid']);
if (!is_error($userinfo) && !empty($userinfo) && !empty($userinfo['subscribe'])) {
$userinfo['nickname'] = stripcslashes($userinfo['nickname']);
$userinfo['avatar'] = $userinfo['headimgurl'];
$_SESSION['userinfo'] = base64_encode(iserializer($userinfo));
$record = array(
'openid' => $userinfo['openid'],
'uid' => 0,
'acid' => $_W['acid'],
'uniacid' => $_W['uniacid'],
'salt' => random(8),
'updatetime' => TIMESTAMP,
'nickname' => stripslashes($userinfo['nickname']),
'follow' => $userinfo['subscribe'],
'followtime' => $userinfo['subscribe_time'],
'unfollowtime' => 0,
'unionid' => $userinfo['unionid'],
'tag' => base64_encode(iserializer($userinfo)),
'user_from' => $_W['account']->typeSign == 'wxapp' ? 1 : 0,
);
if (!isset($unisetting['passport']) || empty($unisetting['passport']['focusreg'])) {
$email = md5($oauth['openid']) . '@we7.cc';
$email_exists_member = table('mc_members')
->where(array(
'email' => $email,
'uniacid' => $_W['uniacid']
))
->getcolumn('uid');
if (!empty($email_exists_member)) {
$uid = $email_exists_member;
} else {
$default_groupid = table('mc_groups')
->where(array(
'uniacid' => $_W['uniacid'],
'isdefault' => 1
))
->getcolumn('groupid');
$data = array(
'uniacid' => $_W['uniacid'],
'email' => $email,
'salt' => random(8),
'groupid' => $default_groupid,
'createtime' => TIMESTAMP,
'password' => md5($message['from'] . $data['salt'] . $_W['config']['setting']['authkey']),
'nickname' => stripslashes($userinfo['nickname']),
'avatar' => $userinfo['headimgurl'],
'gender' => $userinfo['sex'],
'nationality' => $userinfo['country'],
'resideprovince' => $userinfo['province'] . '省',
'residecity' => $userinfo['city'] . '市',
);
table('mc_members')->fill($data)->save();
$uid = pdo_insertid();
}
$record['uid'] = $uid;
$_SESSION['uid'] = $uid;
}
table('mc_mapping_fans')->fill($record)->save();
$mc_fans_tag_table = table('mc_fans_tag');
$mc_fans_tag_fields = mc_fans_tag_fields();
$fans_tag_update_info = array();
foreach ($userinfo as $fans_field_key => $fans_field_info) {
if (in_array($fans_field_key, array_keys($mc_fans_tag_fields))) {
$fans_tag_update_info[$fans_field_key] = $fans_field_info;
}
$fans_tag_update_info['tagid_list'] = iserializer($fans_tag_update_info['tagis_list']);
}
$fans_tag_exists = $mc_fans_tag_table->getByOpenid($fans_tag_update_info['openid']);
if (!empty($fans_tag_exists)) {
table('mc_fans_tag')
->where(array('openid' => $fans_tag_update_info['openid']))
->fill($fans_tag_update_info)
->save();
} else {
table('mc_fans_tag')->fill($fans_tag_update_info)->save();
}
} else {
$record = array(
'openid' => $oauth['openid'],
'nickname' => '',
'subscribe' => '0',
'subscribe_time' => '',
'headimgurl' => '',
);
}
$_SESSION['openid'] = $oauth['openid'];
$_W['fans'] = $record;
$_W['fans']['from_user'] = $record['openid'];
}
}
if (intval($_W['account']['level']) != ACCOUNT_SERVICE_VERIFY) {
$mc_oauth_fan = mc_oauth_fans($oauth['openid'], $_W['uniacid']);
if (empty($mc_oauth_fan)) {
$data = array(
'uniacid' => $_W['uniacid'],
'oauth_openid' => $oauth['openid'],
'uid' => intval($_SESSION['uid']),
'openid' => $_SESSION['openid']
);
table('mc_oauth_fans')->fill($data)->save();
}
if (!empty($oauth['unionid'])) {
$fan = table('mc_mapping_fans')
->searchWithUnionid($oauth['unionid'])
->searchWithUniacid($_W['uniacid'])
->get();
if (!empty($fan)) {
if (!empty($fan['uid'])) {
$_SESSION['uid'] = intval($fan['uid']);
}
if (!empty($fan['openid'])) {
$_SESSION['openid'] = strval($fan['openid']);
}
}
} else {
if (!empty($mc_oauth_fan)) {
if (empty($_SESSION['uid']) && !empty($mc_oauth_fan['uid'])) {
$_SESSION['uid'] = intval($mc_oauth_fan['uid']);
}
if (empty($_SESSION['openid']) && !empty($mc_oauth_fan['openid'])) {
$_SESSION['openid'] = strval($mc_oauth_fan['openid']);
}
}
}
}
if ($scope == 'userinfo' || $scope == 'snsapi_userinfo') {
$userinfo = $oauth_account->getOauthUserInfo($oauth['access_token'], $oauth['openid']);
if (!is_error($userinfo)) {
$userinfo['nickname'] = stripcslashes($userinfo['nickname']);
$userinfo['avatar'] = $userinfo['headimgurl'];
$_SESSION['userinfo'] = base64_encode(iserializer($userinfo));
$fan = table('mc_mapping_fans')->searchWithOpenid($oauth['openid'])->searchWithUniacid($_W['uniacid'])->get();
if (!empty($fan)) {
$record = array();
$record['updatetime'] = TIMESTAMP;
$record['nickname'] = stripslashes($userinfo['nickname']);
$record['tag'] = base64_encode(iserializer($userinfo));
if (empty($fan['unionid'])) {
$record['unionid'] = !empty($userinfo['unionid']) ? $userinfo['unionid'] : '';
}
table('mc_mapping_fans')
->where(array(
'openid' => $fan['openid'],
'uniacid' => $_W['uniacid']
))
->fill($record)
->save();
if (!empty($fan['uid']) || !empty($_SESSION['uid'])) {
$uid = $fan['uid'];
if (empty($uid)) {
$uid = $_SESSION['uid'];
}
$user = mc_fetch($uid, array('nickname', 'gender', 'residecity', 'resideprovince', 'nationality', 'avatar'));
$record = array();
if (empty($user['nickname']) && !empty($userinfo['nickname'])) {
$record['nickname'] = stripslashes($userinfo['nickname']);
}
if (empty($user['gender']) && !empty($userinfo['sex'])) {
$record['gender'] = $userinfo['sex'];
}
if (empty($user['residecity']) && !empty($userinfo['city'])) {
$record['residecity'] = $userinfo['city'] . '市';
}
if (empty($user['resideprovince']) && !empty($userinfo['province'])) {
$record['resideprovince'] = $userinfo['province'] . '省';
}
if (empty($user['nationality']) && !empty($userinfo['country'])) {
$record['nationality'] = $userinfo['country'];
}
if (empty($user['avatar']) && !empty($userinfo['headimgurl'])) {
$record['avatar'] = $userinfo['headimgurl'];
}
if (!empty($record)) {
mc_update($user['uid'], $record);
}
}
} else {
$record = array(
'openid' => $oauth['openid'],
'uid' => 0,
'acid' => $_W['acid'],
'uniacid' => $_W['uniacid'],
'salt' => random(8),
'updatetime' => TIMESTAMP,
'nickname' => $userinfo['nickname'],
'follow' => 0,
'followtime' => 0,
'unfollowtime' => 0,
'tag' => base64_encode(iserializer($userinfo)),
'unionid' => !empty($userinfo['unionid']) ? $userinfo['unionid'] : '',
'user_from' => $_W['account']->typeSign == 'wxapp' ? 1 : 0,
);
if (!isset($unisetting['passport']) || empty($unisetting['passport']['focusreg'])) {
$default_groupid = table('mc_groups')
->where(array(
'uniacid' => $_W['uniacid'],
'isdefault' => 1
))
->getcolumn('groupid');
$data = array(
'uniacid' => $_W['uniacid'],
'email' => md5($oauth['openid']) . '@we7.cc',
'salt' => random(8),
'groupid' => $default_groupid,
'createtime' => TIMESTAMP,
'password' => md5($message['from'] . $data['salt'] . $_W['config']['setting']['authkey']),
'nickname' => $userinfo['nickname'],
'avatar' => $userinfo['headimgurl'],
'gender' => $userinfo['sex'],
'nationality' => $userinfo['country'],
'resideprovince' => $userinfo['province'] . '省',
'residecity' => $userinfo['city'] . '市',
);
table('mc_members')
->fill($data)
->save();
$uid = pdo_insertid();
$record['uid'] = $uid;
$_SESSION['uid'] = $uid;
}
table('mc_mapping_fans')->fill($record)->save();
}
} else {
message('微信授权获取用户信息失败,错误信息为: ' . $userinfo['message']);
}
}
$forward = urldecode($_SESSION['dest_url']);
$forward = strexists($forward, 'i=') ? $forward : "{$forward}&i={$_W['uniacid']}";
if (strpos($forward, '&wxref=mp.weixin.qq.com')) {
$forward = str_replace('&wxref=mp.weixin.qq.com', '', $forward) . '&wxref=mp.weixin.qq.com#wechat_redirect';
} else {
$forward .= '&wxref=mp.weixin.qq.com#wechat_redirect';
}
header('Location: ' . $forward);
exit;

40
app/source/entry/__init.php

@ -0,0 +1,40 @@
<?php
/**
* [WeEngine System] Copyright (c) 2014 WE7.CC
* WeEngine is NOT a free software, it under the license terms, visited http://www.we7.cc/ for more details.
*/
defined('IN_IA') or exit('Access Denied');
load()->model('module');
if (empty($action)) {
$action = 'site';
}
$eid = intval($_GPC['eid']);
if (!empty($eid)) {
$entry = module_entry($eid);
} else {
$entry = array(
'module' => $_GPC['m'],
'do' => $_GPC['do'],
'state' => $_GPC['state'],
'direct' => 0,
);
}
//$module_exist_in_account = table('uni_modules')->where(array('uniacid' => $_W['uniacid'], 'module_name' => $entry['module']))->get();
//if (empty($module_exist_in_account) && !in_array($entry['module'], module_system())) {
// message('您访问的功能模块不存在,请重新进入');
//}
if (empty($entry) || empty($entry['do'])) {
message('非法访问.');
}
$_GPC['__entry'] = $entry['title'];
$_GPC['__state'] = $entry['state'];
$_GPC['state'] = $entry['state'];
$_GPC['m'] = $entry['module'];
$_GPC['do'] = $entry['do'];
$_W['current_module'] = module_fetch($entry['module']);
define('IN_MODULE', $entry['module']);

10
app/source/entry/site.ctrl.php

@ -0,0 +1,10 @@
<?php
defined('IN_IA') or exit('Access Denied');
$site = WeUtility::createModuleSite($entry['module']);
if(!is_error($site)) {
$do_function = $site instanceof WeModuleSite ? 'doMobile' : 'doPage';
$method = $do_function . ucfirst($entry['do']);
exit($site->$method());
}
exit();

171
framework/bootstrap.inc.php

@ -0,0 +1,171 @@
<?php
define('IN_IA', true);
define('STARTTIME', microtime());
define('IA_ROOT', str_replace('\\', '/', dirname(dirname(__FILE__))));
define('MAGIC_QUOTES_GPC', (function_exists('get_magic_quotes_gpc') && @get_magic_quotes_gpc()) || @ini_get('magic_quotes_sybase'));
define('TIMESTAMP', time());
$_W = $_GPC = array();
$configfile = IA_ROOT . '/data/config.php';
if (!file_exists($configfile)) {
if (file_exists(IA_ROOT . '/install.php')) {
header('Location: ' . '/install.php');
exit();
} else {
header('Content-Type: text/html; charset=utf-8');
exit('配置文件不存在或是不可读,请检查“data/config”文件或是重新安装!');
}
}
require $configfile;
require IA_ROOT . '/framework/version.inc.php';
require IA_ROOT . '/framework/const.inc.php';
require IA_ROOT . '/framework/class/loader.class.php';
load()->func('global');
load()->func('compat');
load()->func('compat.biz');
load()->func('pdo');
load()->classs('account');
load()->model('cache');
load()->model('account');
load()->model('setting');
load()->model('module');
load()->library('agent');
load()->classs('db');
load()->func('communication');
define('CLIENT_IP', getip());
$_W['config'] = $config;
$_W['config']['db']['tablepre'] = !empty($_W['config']['db']['master']['tablepre']) ? $_W['config']['db']['master']['tablepre'] : $_W['config']['db']['tablepre'];
$_W['timestamp'] = TIMESTAMP;
$_W['charset'] = $_W['config']['setting']['charset'];
$_W['clientip'] = CLIENT_IP;
unset($configfile, $config);
define('ATTACHMENT_ROOT', IA_ROOT . '/attachment/');
error_reporting(0);
if (!in_array($_W['config']['setting']['cache'], array('mysql', 'memcache', 'redis'))) {
$_W['config']['setting']['cache'] = 'mysql';
}
load()->func('cache');
if (function_exists('date_default_timezone_set')) {
date_default_timezone_set($_W['config']['setting']['timezone']);
}
if (!empty($_W['config']['setting']['memory_limit']) && function_exists('ini_get') && function_exists('ini_set')) {
if ($_W['config']['setting']['memory_limit'] != @ini_get('memory_limit')) {
@ini_set('memory_limit', $_W['config']['setting']['memory_limit']);
}
}
if (isset($_W['config']['setting']['https']) && $_W['config']['setting']['https'] == '1') {
$_W['ishttps'] = $_W['config']['setting']['https'];
} else {
$_W['ishttps'] = isset($_SERVER['SERVER_PORT']) && 443 == $_SERVER['SERVER_PORT'] ||
isset($_SERVER['HTTP_FROM_HTTPS']) && 'on' == strtolower($_SERVER['HTTP_FROM_HTTPS']) ||
(isset($_SERVER['HTTPS']) && 'off' != strtolower($_SERVER['HTTPS'])) ||
isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && 'https' == strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) ||
isset($_SERVER['HTTP_X_CLIENT_SCHEME']) && 'https' == strtolower($_SERVER['HTTP_X_CLIENT_SCHEME']) ? true : false;
}
$_W['isajax'] = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 'xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH']);
$_W['ispost'] = isset($_SERVER['REQUEST_METHOD']) && 'POST' == $_SERVER['REQUEST_METHOD'];
$_W['sitescheme'] = $_W['ishttps'] ? 'https://' : 'http://';
$_W['script_name'] = htmlspecialchars(scriptname());
$sitepath = substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/'));
$_W['siteroot'] = htmlspecialchars($_W['sitescheme'] . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $sitepath);
if ('/' != substr($_W['siteroot'], -1)) {
$_W['siteroot'] .= '/';
}
$urls = parse_url($_W['siteroot']);
$urls['path'] = str_replace(array('/web', '/app', '/payment/wechat', '/payment/alipay', '/payment/jueqiymf', '/api'), '', $urls['path']);
$urls['scheme'] = !empty($urls['scheme']) ? $urls['scheme'] : 'http';
$urls['host'] = !empty($urls['host']) ? $urls['host'] : '';
$_W['siteroot'] = $urls['scheme'] . '://' . $urls['host'] . ((!empty($urls['port']) && '80' != $urls['port']) ? ':' . $urls['port'] : '') . $urls['path'];
if (MAGIC_QUOTES_GPC) {
$_GET = istripslashes($_GET);
$_POST = istripslashes($_POST);
$_COOKIE = istripslashes($_COOKIE);
}
foreach ($_GET as $key => $value) {
if (is_string($value) && !is_numeric($value)) {
$value = safe_gpc_string($value);
}
$_GET[$key] = $_GPC[$key] = $value;
}
$cplen = strlen($_W['config']['cookie']['pre']);
foreach ($_COOKIE as $key => $value) {
if ($_W['config']['cookie']['pre'] == substr($key, 0, $cplen)) {
$_GPC[substr($key, $cplen)] = $value;
}
}
unset($cplen, $key, $value);
$_GPC = array_merge($_GPC, $_POST);
$_GPC = ihtmlspecialchars($_GPC);
$_W['siteurl'] = $urls['scheme'] . '://' . $urls['host'] . ((!empty($urls['port']) && '80' != $urls['port']) ? ':' . $urls['port'] : '') . $_W['script_name'] . '?' . http_build_query($_GET, '', '&');
if (!$_W['isajax']) {
$input = file_get_contents('php://input');
if (!empty($input)) {
$__input = @json_decode($input, true);
if (!empty($__input)) {
$_GPC['__input'] = $__input;
$_W['isajax'] = true;
}
}
unset($input, $__input);
}
$_W['uniacid'] = $_W['uid'] = 0;
if ($_W['config']['setting']['development'] == 1) {
ini_set('display_errors', '1');
error_reporting(E_ALL ^ E_NOTICE);
}
setting_load();
define('DEVELOPMENT', $_W['config']['setting']['development'] == 1 || $_W['setting']['copyright']['develop_status'] ==1);
if (empty($_W['setting']['upload'])) {
$_W['setting']['upload'] = array_merge($_W['config']['upload']);
}
$_W['os'] = Agent::deviceType();
if (Agent::DEVICE_MOBILE == $_W['os']) {
$_W['os'] = 'mobile';
} elseif (Agent::DEVICE_DESKTOP == $_W['os']) {
$_W['os'] = 'windows';
} else {
$_W['os'] = 'unknown';
}
$_W['container'] = Agent::browserType();
if (Agent::MICRO_MESSAGE_YES == Agent::isMicroMessage()) {
$_W['container'] = 'wechat';
} elseif (Agent::BROWSER_TYPE_ANDROID == $_W['container']) {
$_W['container'] = 'android';
} elseif (Agent::BROWSER_TYPE_IPAD == $_W['container']) {
$_W['container'] = 'ipad';
} elseif (Agent::BROWSER_TYPE_IPHONE == $_W['container']) {
$_W['container'] = 'iphone';
} elseif (Agent::BROWSER_TYPE_IPOD == $_W['container']) {
$_W['container'] = 'ipod';
}else {
$_W['container'] = 'unknown';
}
if ('wechat' == $_W['container'] || 'baidu' == $_W['container']) {
$_W['platform'] = 'account';
}
$controller = !empty($_GPC['c']) ? $_GPC['c'] : '';
$action = !empty($_GPC['a']) ? $_GPC['a'] : '';
$do = !empty($_GPC['do']) ? $_GPC['do'] : '';
header('Content-Type: text/html; charset=' . $_W['charset']);

1
framework/builtin/core/index.html

@ -0,0 +1 @@

353
framework/builtin/core/module.php

@ -0,0 +1,353 @@
<?php
defined('IN_IA') or exit('Access Denied');
class CoreModule extends WeModule {
public $modules = array('basic', 'news', 'image', 'music', 'voice', 'video', 'wxcard', 'keyword', 'module');
public $tablename = array(
'basic' => 'basic_reply',
'news' => 'news_reply',
'image' => 'images_reply',
'music' => 'music_reply',
'voice' => 'voice_reply',
'video' => 'video_reply',
'wxcard' => 'wxcard_reply',
'keyword' => 'basic_reply',
);
private $options = array(
'basic' => true,
'news' => true,
'image' => true,
'music' => true,
'voice' => true,
'video' => true,
'wxcard' => true,
'keyword' => true,
'module' => true,
);
private $replies = array();
public function fieldsFormDisplay($rid = 0, $option = array()) {
global $_GPC, $_W, $setting_keyword;
load()->model('material');
load()->model('reply');
$module_name = safe_gpc_string($_GPC['module_name']) ?: safe_gpc_string($_GPC['m']);
$replies = array();
switch ($_GPC['a']) {
case 'mass':
if (!empty($rid) && $rid > 0) {
$isexists = table('mc_mass_record')->getById($rid);
}
if (!empty($isexists['media_id']) && !empty($isexists['msgtype'])) {
$wechat_attachment = material_get($isexists['media_id']);
switch ($isexists['msgtype']) {
case 'news':
if (!empty($wechat_attachment['news'])) {
foreach ($wechat_attachment['news'] as &$item) {
$item['thumb_url'] = tomedia($item['thumb_url']);
$item['media_id'] = $isexists['media_id'];
$item['attach_id'] = $item['attach_id'];
$item['perm'] = $wechat_attachment['model'];
}
unset($item);
}
$replies['news'] = $wechat_attachment['news'];
break;
case 'image':
$replies['image'][0]['img_url'] = tomedia($wechat_attachment['attachment']);
$replies['image'][0]['mediaid'] = $isexists['media_id'];
break;
case 'voice':
$replies['voice'][0]['title'] = $wechat_attachment['filename'];
$replies['voice'][0]['mediaid'] = $isexists['media_id'];
break;
case 'video':
$replies['video'][0] = iunserializer($wechat_attachment['tag']);
$replies['video'][0]['mediaid'] = $isexists['media_id'];
break;
}
}
break;
default:
if (!empty($rid)) {
$rule_rid = $rid;
if (in_array($module_name, array('welcome', 'default'))) {
$rule_rid = table('rule_keyword')->where(array('rid' => $rid))->getcolumn('rid');
}
$isexists = reply_single($rule_rid);
}
if ('special' == $module_name) {
$default_setting = uni_setting_load('default_message', $_W['uniacid']);
$default_setting = $default_setting['default_message'] ? $default_setting['default_message'] : array();
$reply_type = $default_setting[$_GPC['type']]['type'];
if (empty($reply_type)) {
if (!empty($default_setting[$_GPC['type']]['keyword'])) {
$reply_type = 'keyword';
}
if (!empty($default_setting[$_GPC['type']]['module'])) {
$reply_type = 'module';
}
if (empty($reply_type)) {
break;
}
}
if ('module' == $reply_type) {
$replies['module'][0]['name'] = $default_setting[$_GPC['type']]['module'];
$module_info = table('modules')->getByName($default_setting[$_GPC['type']]['module']);
$replies['module'][0]['title'] = $module_info['title'];
if (file_exists(IA_ROOT . '/addons/' . $module_info['name'] . '/custom-icon.jpg')) {
$replies['module'][0]['icon'] = '../addons/' . $module_info['name'] . '/custom-icon.jgp';
} else {
$replies['module'][0]['icon'] = '../addons/' . $module_info['name'] . '/icon.jpg';
}
} else {
$replies['keyword'][0]['name'] = $isexists['name'];
$replies['keyword'][0]['content'] = $setting_keyword;
$replies['keyword'][0]['rid'] = $rid;
}
break;
}
if (!empty($isexists)) {
$module = $isexists['module'];
$module = 'images' == $module ? 'image' : $module;
if ('reply' == $_GPC['a'] && (!empty($module_name) && 'keyword' == $module_name)) {
foreach ($this->tablename as $key => $tablename) {
if ('keyword' != $key) {
$replies[$key] = table($tablename)->where(array('rid' => $rid))->orderby('id')->getall();
switch ($key) {
case 'image':
foreach ($replies[$key] as &$img_value) {
$img = table('wechat_attachment')->getByMediaId($img_value['mediaid']);
$img_value['img_url'] = tomedia($img['attachment'], true);
}
unset($img_value);
break;
case 'news':
foreach ($replies[$key] as &$news_value) {
if (!empty($news_value) && !empty($news_value['media_id'])) {
$news_material = material_get($news_value['media_id']);
if (!is_error($news_material)) {
$news_value['attach_id'] = $news_material['id'];
$news_value['model'] = $news_material['model'];
$news_value['description'] = $news_material['news'][0]['digest'];
$news_value['thumb'] = tomedia($news_material['news'][0]['thumb_url']);
}
} else {
$news_value['thumb'] = tomedia($news_value['thumb']);
}
}
unset($news_value);
break;
case 'video':
foreach ($replies[$key] as &$video_value) {
$video_material = material_get($video_value['mediaid']);
$video_value['filename'] = $video_material['filename'];
}
unset($video_value);
break;
}
}
}
} else {
$replies['keyword'][0]['name'] = $isexists['name'];
$replies['keyword'][0]['rid'] = $rid;
$replies['keyword'][0]['content'] = $setting_keyword;
}
}
break;
}
if (!is_array($option)) {
$option = array();
}
$options = array_merge($this->options, $option);
include $this->template('display');
}
public function fieldsFormValidate($rid = 0) {
global $_GPC;
$ifEmpty = 1;
$reply = '';
foreach ($this->modules as $key => $value) {
if ('' != trim($_GPC['reply']['reply_' . $value])) {
$ifEmpty = 0;
}
if (('music' == $value || 'video' == $value || 'wxcard' == $value || 'news' == $value) && !empty($_GPC['reply']['reply_' . $value])) {
$reply = ltrim($_GPC['reply']['reply_' . $value], '{');
$reply = rtrim($reply, '}');
$reply = explode('},{', $reply);
foreach ($reply as &$val) {
$val = htmlspecialchars_decode('{' . $val . '}');
}
$this->replies[$value] = $reply;
} else {
$this->replies[$value] = htmlspecialchars_decode($_GPC['reply']['reply_' . $value], ENT_QUOTES);
}
}
if ($ifEmpty) {
return error(1, '必须填写有效的回复内容.');
}
return '';
}
public function fieldsFormSubmit($rid = 0) {
global $_GPC, $_W;
permission_check_account_user('platform_reply_keyword');
$delsql = '';
foreach ($this->modules as $k => $val) {
$tablename = $this->tablename[$val];
if (!empty($tablename)) {
table($tablename)->where(array('rid' => $rid))->delete();
}
}
foreach ($this->modules as $val) {
$replies = array();
$tablename = $this->tablename[$val];
if ($this->replies[$val]) {
if (is_array($this->replies[$val])) {
foreach ($this->replies[$val] as $value) {
$replies[] = json_decode($value, true);
}
} else {
$replies = explode(',', $this->replies[$val]);
foreach ($replies as &$v) {
$v = json_decode($v);
}
}
}
switch ($val) {
case 'basic':
if (!empty($replies)) {
foreach ($replies as $reply) {
table($tablename)->fill(array('rid' => $rid, 'content' => $reply))->save();
}
}
break;
case 'news':
if (!empty($replies)) {
$parent_id = 0;
$attach_id = 0;
foreach ($replies as $k => $reply) {
if (!empty($attach_id) && $reply['attach_id'] == $attach_id) {
$reply['parent_id'] = $parent_id;
}
if ('local' == $reply['model']) {
$reply['mediaid'] = $reply['attach_id'];
}
table($tablename)
->fill(array(
'rid' => $rid,
'parent_id' => $reply['parent_id'],
'title' => $reply['title'],
'thumb' => tomedia($reply['thumb']),
'createtime' => $reply['createtime'],
'media_id' => $reply['mediaid'],
'displayorder' => $reply['displayorder'],
'description' => $reply['description'],
'url' => $reply['url']
))
->save();
if (empty($attach_id) || $reply['attach_id'] != $attach_id) {
$parent_id = pdo_insertid();
}
$attach_id = $reply['attach_id'] ? $reply['attach_id'] : 0;
}
}
break;
case 'image':
if (!empty($replies)) {
foreach ($replies as $reply) {
table($tablename)
->fill(array(
'rid' => $rid,
'mediaid' => $reply,
'createtime' => time()
))
->save();
}
}
break;
case 'music':
if (!empty($replies)) {
foreach ($replies as $reply) {
table($tablename)
->fill(array(
'rid' => $rid,
'title' => $reply['title'],
'url' => $reply['url'],
'hqurl' => $reply['hqurl'],
'description' => $reply['description']
))
->save();
}
}
break;
case 'voice':
if (!empty($replies)) {
foreach ($replies as $reply) {
table($tablename)
->fill(array(
'rid' => $rid,
'mediaid' => $reply,
'createtime' => time()
))
->save();
}
}
break;
case 'video':
if (!empty($replies)) {
foreach ($replies as $reply) {
table($tablename)
->fill(array(
'rid' => $rid,
'mediaid' => $reply['mediaid'],
'title' => $reply['title'],
'description' => $reply['description'],
'createtime' => time()
))
->save();
}
}
break;
case 'wxcard':
if (!empty($replies)) {
foreach ($replies as $reply) {
table($tablename)
->fill(array(
'rid' => $rid,
'title' => $reply['title'],
'card_id' => $reply['mediaid'],
'cid' => $reply['cid'],
'brand_name' => $reply['brandname'],
'logo_url' => $reply['logo_url'],
'success' => $reply['success'],
'error' => $reply['error']
))
->save();
}
}
break;
}
}
return true;
}
public function ruleDeleted($rid = 0) {
global $_W;
permission_check_account_user('platform_reply_keyword');
$reply_modules = array('basic', 'news', 'music', 'images', 'voice', 'video', 'wxcard');
foreach ($this->tablename as $tablename) {
table($tablename)
->where(array(
'rid' => $rid,
'uniacid' => $_W['uniacid']
))
->delete();
}
}
}

170
framework/builtin/core/processor.php

@ -0,0 +1,170 @@
<?php
defined('IN_IA') or exit('Access Denied');
class CoreModuleProcessor extends WeModuleProcessor {
public function respond() {
$reply_type = $this->reply_type;
$key = array_rand($reply_type);
$type = $reply_type[$key];
switch ($type) {
case 'basic':
$result = $this->basic_respond();
return $this->respText($result);
break;
case 'images':
$result = $this->image_respond();
return $this->respImage($result);
break;
case 'music':
$result = $this->music_respond();
return $this->respMusic(array(
'Title' => $result['title'],
'Description' => $result['description'],
'MusicUrl' => $result['url'],
'HQMusicUrl' => $result['hqurl'],
));
break;
case 'news':
$result = $this->news_respond();
return $this->respNews($result);
break;
case 'voice':
$result = $this->voice_respond();
return $this->respVoice($result);
break;
case 'video':
$result = $this->video_respond();
return $this->respVideo(array(
'MediaId' => $result['mediaid'],
'Title' => $result['title'],
'Description' => $result['description'],
));
break;
}
}
private function basic_respond() {
$rids = !is_array($this->rule) ? explode(',', $this->rule) : $this->rule;
$reply = table('basic_reply')->where(array('rid IN' => $rids))->orderby('RAND()')->get();
if (empty($reply)) {
return false;
}
$reply['content'] = htmlspecialchars_decode($reply['content']);
$reply['content'] = str_replace(array('<br>', '&nbsp;'), array("\n", ' '), $reply['content']);
$reply['content'] = strip_tags($reply['content'], '<a>');
return $reply['content'];
}
private function image_respond() {
global $_W;
$rid = $this->rule;
$mediaid = table('images_reply')->where(array('rid' => $rid))->orderby('RAND()')->getcolumn('mediaid');
if (empty($mediaid)) {
return false;
}
return $mediaid;
}
private function music_respond() {
global $_W;
$rid = $this->rule;
$item = table('music_reply')->where(array('rid' => $rid))->orderby('RAND()')->get();
if (empty($item['id'])) {
return false;
}
return $item;
}
private function news_respond() {
global $_W;
load()->model('material');
$rid = $this->rule;
$commends = table('news_reply')
->where(array('rid' => $rid, 'parent_id' => -1))
->orderby(array('displayorder' => 'DESC', 'id' => 'ASC'))
->limit(8)
->getall();
if (empty($commends)) {
$main = table('news_reply')
->where(array(
'rid' => $rid,
'parent_id' => 0
))
->orderby('RAND()')
->get();
if (empty($main['id'])) {
return false;
}
$commends = table('news_reply')
->where(array('id' => $main['id']))
->whereor(array('parent_id' => $main['id']))
->orderby(array(
'displayorder' => 'ASC',
'id' => 'ASC'
))
->limit(8)
->getall();
}
if (empty($commends)) {
return false;
}
$news = array();
if (!empty($commends[0]['media_id'])) {
$news = material_build_reply($commends[0]['media_id']);
}
foreach ($commends as $key => $commend) {
$row = array();
if (!empty($commend['media_id'])) {
if (empty($news[$key]['url'])) {
$news[$key]['url'] = $this->createMobileUrl('detail', array('id' => $commend['id']));
}
} else {
$row['title'] = $commend['title'];
$row['description'] = $commend['description'];
!empty($commend['thumb']) && $row['picurl'] = tomedia($commend['thumb']);
$row['url'] = empty($commend['url']) ? $this->createMobileUrl('detail', array('id' => $commend['id'])) : $commend['url'];
$news[] = $row;
}
}
return $news;
}
private function voice_respond() {
global $_W;
$rid = $this->rule;
$mediaid = table('voice_reply')
->where(array('rid' => $rid))
->orderby('RAND()')
->getcolumn('mediaid');
if (empty($mediaid)) {
return false;
}
return $mediaid;
}
private function video_respond() {
global $_W;
$rid = $this->rule;
$item = table('video_reply')
->where(array('rid' => $rid))
->orderby('RAND()')
->get();
if (empty($item)) {
return false;
}
return $item;
}
}

133
framework/builtin/core/receiver.php

@ -0,0 +1,133 @@
<?php
defined('IN_IA') or exit('Access Denied');
class CoreModuleReceiver extends WeModuleReceiver {
public function receive() {
global $_W;
if ('subscribe' == $this->message['event'] && !empty($this->message['ticket'])) {
$sceneid = $this->message['scene'];
$acid = $this->acid;
$uniacid = $this->uniacid;
$ticket = trim($this->message['ticket']);
if (!empty($ticket)) {
$qr = table('qrcode')
->select(array('id', 'keyword', 'name', 'acid'))
->where(array(
'uniacid' => $uniacid,
'ticket' => $ticket
))
->getall();
if (!empty($qr)) {
if (1 != count($qr)) {
$qr = array();
} else {
$qr = $qr[0];
}
}
}
if (empty($qr)) {
$sceneid = trim($this->message['scene']);
$where = array(
'uniacid' => $_W['uniacid']
);
if (is_numeric($sceneid)) {
$where['qrcid'] = $sceneid;
} else {
$where['scene_str'] = $sceneid;
}
$qr = table('qrcode')
->select(array('id', 'keyword', 'name', 'acid'))
->where($where)
->get();
}
$insert = array(
'uniacid' => $_W['uniacid'],
'acid' => $qr['acid'],
'qid' => $qr['id'],
'openid' => $this->message['from'],
'type' => 1,
'qrcid' => intval($sceneid),
'scene_str' => $sceneid,
'name' => $qr['name'],
'createtime' => TIMESTAMP,
);
table('qrcode_stat')->fill($insert)->save();
} elseif ('SCAN' == $this->message['event']) {
$sceneid = trim($this->message['scene']);
$where = array('uniacid' => $_W['uniacid']);
if (is_numeric($sceneid)) {
$where['qrcid'] = $sceneid;
} else {
$where['scene_str'] = $sceneid;
}
$row = table('qrcode')
->select(array('id', 'keyword', 'name', 'acid'))
->where($where)
->get();
$insert = array(
'uniacid' => $_W['uniacid'],
'acid' => $row['acid'],
'qid' => $row['id'],
'openid' => $this->message['from'],
'type' => 2,
'qrcid' => intval($sceneid),
'scene_str' => $sceneid,
'name' => $row['name'],
'createtime' => TIMESTAMP,
);
if ($_W['setting']['qr_status']['status'] == 1) {
$qrLog = table('qrcode_stat')->where(array('uniacid' => $_W['uniacid'], 'qid' => $row['id'], 'openid' => $this->message['from']))->get();
if (empty($qrLog)) table('qrcode_stat')->fill($insert)->save();
} else {
table('qrcode_stat')->fill($insert)->save();
}
} elseif ('user_get_card' == $this->message['event']) {
$sceneid = $this->message['outerid'];
$row = table('qrcode')->where(array('qrcid' => $sceneid))->get();
if (!empty($row)) {
$insert = array(
'uniacid' => $_W['uniacid'],
'acid' => $row['acid'],
'qid' => $row['id'],
'openid' => $this->message['from'],
'type' => 2,
'qrcid' => $sceneid,
'scene_str' => $sceneid,
'name' => $row['name'],
'createtime' => TIMESTAMP,
);
table('qrcode_stat')->fill($insert)->save();
}
}
if ('subscribe' == $this->message['event'] && !empty($_W['account']) && ($_W['account']['level'] == ACCOUNT_SERVICE_VERIFY || $_W['account']['level'] == ACCOUNT_SUBSCRIPTION_VERIFY)) {
$account_obj = WeAccount::createByUniacid();
$userinfo = $account_obj->fansQueryInfo($this->message['from']);
if (!is_error($userinfo) && !empty($userinfo) && !empty($userinfo['subscribe'])) {
$userinfo['nickname'] = stripcslashes($userinfo['nickname']);
$userinfo['avatar'] = $userinfo['headimgurl'];
$fans = array(
'unionid' => $userinfo['unionid'],
'nickname' => strip_emoji($userinfo['nickname']),
'tag' => base64_encode(iserializer($userinfo)),
);
table('mc_mapping_fans')
->where(array('openid' => $this->message['from']))
->fill($fans)
->save();
$uid = !empty($_W['member']['uid']) ? $_W['member']['uid'] : $this->message['from'];
if (!empty($uid)) {
$member = array();
if (!empty($userinfo['nickname'])) {
$member['nickname'] = $fans['nickname'];
}
if (!empty($userinfo['headimgurl'])) {
$member['avatar'] = $userinfo['headimgurl'];
}
load()->model('mc');
mc_update($uid, $member);
}
}
}
}
}

272
framework/builtin/core/site.php

@ -0,0 +1,272 @@
<?php
defined('IN_IA') or exit('Access Denied');
class CoreModuleSite extends WeModuleSite {
public function doMobilePaymethod() {
global $_W, $_GPC;
$params = array(
'fee' => floatval($_GPC['fee']),
'tid' => safe_gpc_string($_GPC['tid']),
'module' => safe_gpc_string($_GPC['module']),
);
if (empty($params['tid']) || empty($params['fee']) || empty($params['module'])) {
message(error(1, '支付参数不完整'));
}
if ($params['fee'] <= 0) {
$notify_params = array(
'form' => 'return',
'result' => 'success',
'type' => '',
'tid' => $params['tid'],
);
$site = WeUtility::createModuleSite($params['module']);
$method = 'payResult';
if (method_exists($site, $method)) {
$site->$method($notify_params);
message(error(-1, '支付成功'));
}
}
$log = table('core_paylog')
->searWithUniacid($_W['uniacid'])
->SearWithModule($params['module'])
->searWithTid($params['tid'])
->get();
if (empty($log)) {
$log = array(
'uniacid' => $_W['uniacid'],
'acid' => $_W['acid'],
'openid' => $_W['member']['uid'],
'module' => $params['module'],
'tid' => $params['tid'],
'fee' => $params['fee'],
'card_fee' => $params['fee'],
'status' => '0',
'is_usecard' => '0',
);
table('core_paylog')->fill($log)->save();
}
if ('1' == $log['status']) {
message(error(1, '订单已经支付'));
}
$setting = uni_setting($_W['uniacid'], array('payment', 'creditbehaviors'));
if (!is_array($setting['payment'])) {
message(error(1, '暂无有效支付方式'));
}
$pay = $setting['payment'];
if (empty($_W['member']['uid'])) {
$pay['credit']['switch'] = false;
}
if (!empty($pay['credit']['switch'])) {
$credtis = mc_credit_fetch($_W['member']['uid']);
}
include $this->template('pay');
}
public function doMobilePay() {
global $_W, $_GPC;
$moduels = uni_modules();
$params = $_POST;
if (empty($params) || !array_key_exists($params['module'], $moduels)) {
message(error(1, '模块不存在'), '', 'ajax', true);
}
$setting = uni_setting($_W['uniacid'], 'payment');
$dos = array();
if (!empty($setting['payment']['credit']['pay_switch'])) {
$dos[] = 'credit';
}
if (!empty($setting['payment']['alipay']['pay_switch'])) {
$dos[] = 'alipay';
}
if (!empty($setting['payment']['wechat']['pay_switch'])) {
$dos[] = 'wechat';
}
if (!empty($setting['payment']['delivery']['pay_switch'])) {
$dos[] = 'delivery';
}
if (!empty($setting['payment']['unionpay']['pay_switch'])) {
$dos[] = 'unionpay';
}
if (!empty($setting['payment']['baifubao']['pay_switch'])) {
$dos[] = 'baifubao';
}
$type = in_array($params['method'], $dos) ? $params['method'] : '';
if (empty($type)) {
message(error(1, '暂无有效支付方式,请联系商家'), '', 'ajax', true);
}
$moduleid = table('modules')
->where(array('name' => $params['module']))
->getcolumn('mid');
$moduleid = empty($moduleid) ? '000000' : sprintf('%06d', $moduleid);
$uniontid = date('YmdHis') . $moduleid . random(8, 1);
$paylog = table('core_paylog')
->where(array('uniacid' => $uniacid))
->searchWithModule($params['module'])
->searchWithTid($params['tid'])
->get();
if (empty($paylog)) {
$paylog = array(
'uniacid' => $_W['uniacid'],
'acid' => $_W['acid'],
'openid' => $_W['member']['uid'],
'type' => $type,
'module' => $params['module'],
'tid' => $params['tid'],
'uniontid' => $uniontid,
'fee' => $params['fee'],
'card_fee' => $params['fee'],
'status' => '0',
'is_usecard' => '0',
);
table('core_paylog')->fill($paylog)->save();
$paylog['plid'] = pdo_insertid();
}
if (!empty($paylog) && '0' != $paylog['status']) {
message(error(1, '这个订单已经支付成功, 不需要重复支付.'), '', 'ajax', true);
}
if (!empty($paylog) && empty($paylog['uniontid'])) {
table('core_paylog')
->where(array('plid' => $paylog['plid']))
->fill(array('uniontid' => $uniontid))
->save();
}
$paylog['title'] = $params['title'];
if (intval($_GPC['iswxapp'])) {
message(error(2, $_W['siteroot'] . "app/index.php?i={$_W['uniacid']}&c=wxapp&a=home&do=go_paycenter&title={$params['title']}&plid={$paylog['plid']}"), '', 'ajax', true);
}
if ('wechat' == $params['method']) {
return $this->doMobilePayWechat($paylog);
} elseif ('alipay' == $params['method']) {
return $this->doMobilePayAlipay($paylog);
} else {
$params['tid'] = $paylog['plid'];
$sl = base64_encode(json_encode($params));
$auth = sha1($sl . $_W['uniacid'] . $_W['config']['setting']['authkey']);
message(error(0, $_W['siteroot'] . "/payment/{$type}/pay.php?i={$_W['uniacid']}&auth={$auth}&ps={$sl}"), '', 'ajax', true);
exit();
}
}
private function doMobilePayWechat($paylog = array()) {
global $_W;
load()->model('payment');
table('core_paylog')
->where(array('plid' => $paylog['plid']))
->fill(array(
'openid' => $_W['openid'],
'tag' => iserializer(array('acid' => $_W['acid'], 'uid' => $_W['member']['uid'])),
))
->save();
$_W['uniacid'] = $paylog['uniacid'];
$setting = uni_setting($_W['uniacid'], array('payment'));
$wechat_payment = $setting['payment']['wechat'];
$account = table('account_wechats')
->where(array('acid' => $wechat_payment['account']))
->get();
$wechat_payment['appid'] = $account['key'];
$wechat_payment['secret'] = $account['secret'];
$params = array(
'tid' => $paylog['tid'],
'fee' => $paylog['card_fee'],
'user' => $paylog['openid'],
'title' => urldecode($paylog['title']),
'uniontid' => $paylog['uniontid'],
);
if (PAYMENT_WECHAT_TYPE_SERVICE == intval($wechat_payment['switch']) || PAYMENT_WECHAT_TYPE_BORROW == intval($wechat_payment['switch'])) {
if (!empty($_W['openid'])) {
$params['sub_user'] = $_W['openid'];
$wechat_payment_params = wechat_proxy_build($params, $wechat_payment);
} else {
$params['tid'] = $paylog['plid'];
$params['title'] = urlencode($params['title']);
$sl = base64_encode(json_encode($params));
$auth = sha1($sl . $paylog['uniacid'] . $_W['config']['setting']['authkey']);
$callback = urlencode($_W['siteroot'] . "payment/wechat/pay.php?i={$_W['uniacid']}&auth={$auth}&ps={$sl}");
$proxy_pay_account = payment_proxy_pay_account();
if (!is_error($proxy_pay_account)) {
$forward = $proxy_pay_account->getOauthCodeUrl($callback, 'we7sid-' . $_W['session_id']);
message(error(2, $forward), $forward, 'ajax');
exit;
}
}
} else {
unset($wechat_payment['sub_mch_id']);
$wechat_payment_params = wechat_build($params, $wechat_payment);
}
if (is_error($wechat_payment_params)) {
message($wechat_payment_params, '', 'ajax', true);
} else {
message(error(0, $wechat_payment_params), '', 'ajax', true);
}
}
private function doMobilePayAlipay($paylog = array()) {
global $_W;
load()->model('payment');
load()->func('communication');
$_W['uniacid'] = $paylog['uniacid'];
$setting = uni_setting($_W['uniacid'], array('payment'));
$params = array(
'tid' => $paylog['tid'],
'fee' => $paylog['card_fee'],
'user' => $paylog['openid'],
'title' => urldecode($paylog['title']),
'uniontid' => $paylog['uniontid'],
);
$alipay_payment_params = alipay_build($params, $setting['payment']['alipay']);
if ($alipay_payment_params['url']) {
message(error(0, $alipay_payment_params['url']), '', 'ajax', true);
exit();
}
}
public function doMobileDetail() {
global $_W, $_GPC;
$id = intval($_GPC['id']);
$row = table('news_reply')->getById($id);
$createtime = $row['createtime'];
if (!empty($row['url'])) {
header('Location: ' . $row['url']);
exit;
}
if (!empty($row['media_id']) && 0 != intval($row['media_id'])) {
$row = table('wechat_news')
->where(array(
'attach_id' => $row['media_id'],
'displayorder' => $row['displayorder']
))
->get();
$row['createtime'] = $createtime;
if (!empty($row['content_source_url'])) {
header('Location: ' . $row['content_source_url']);
exit;
}
}
$row = istripslashes($row);
$title = $row['title'];
if ('android' == $_W['os'] && 'wechat' == $_W['container'] && $_W['account']['account']) {
$subscribeurl = "weixin://profile/{$_W['account']['account']}";
} else {
$subscribeurl = table('account_wechats')
->where(array('uniacid' => intval($_W['uniacid'])))
->getcolumn('subscribeurl');
}
include $this->template('detail');
}
}

863
framework/builtin/core/template/display.html

@ -0,0 +1,863 @@
<div class="panel we7-panel panel-reply">
<div class="panel-heading">
{if $_GPC['a'] == 'qr'}二维码触发的关键字
{elseif $_GPC['a'] == 'mass'}群发内容
{else}
{if $_GPC['c'] == 'mc' && $_GPC['a'] == 'chats'}发送聊天内容{else}触发后回复内容{/if}
{if $_GPC['a'] == 'reply' && $_GPC['m'] == 'keyword'}<span class="pull-right color-gray">添加多条回复内容时, 随机回复其中一条</span>{/if}
{/if}
</div>
<div class="panel-body we7-padding">
<input type="hidden" name="reply[reply_basic]" value="">
<input type="hidden" name="reply[reply_news]" value="">
<input type="hidden" name="reply[reply_image]" value="">
<input type="hidden" name="reply[reply_music]" value="">
<input type="hidden" name="reply[reply_voice]" value="">
<input type="hidden" name="reply[reply_video]" value="">
<input type="hidden" name="reply[reply_wxcard]" value="">
<input type="hidden" name="reply[reply_keyword]" value="">
<input type="hidden" name="reply[reply_module]" value="">
<ul class="keywords-list">
</ul>
<div class="we7-select-msg">
<ul class="tab-navs">
<li class="tab-nav tab-appmsg active {if $options['news']}hidden{/if}">
<a href="javascript:void(0);"{if $_GPC['a'] == 'mass'} onclick="select_mediaid('news', 'wx')"{else} onclick="select_mediaid('news')"{/if}>
<img src="./resource/images/reply/appmsg-icon.png" alt="">
<span class="msg-tab-title">图文</span>
</a>
</li>
<li class="tab-nav tab-text {if $options['basic']}hidden{/if}">
<a href="javascript:void(0);" onclick="select_mediaid('basic');">
<img src="./resource/images/reply/text-icon.png" alt="">
</i><span class="msg-tab-title">文字</span>
</a>
</li>
<li class="tab-nav tab-img {if $options['image']}hidden{/if}">
<a href="javascript:void(0);" onclick="select_mediaid('image');">
<img src="./resource/images/reply/image-icon.png" alt="">
<span class="msg-tab-title">微信图片</span>
</a>
</li>
<li class="tab-nav tab-audio {if $options['music']}hidden{/if}">
<a href="javascript:void(0);" onclick="select_mediaid('music');">
<img src="./resource/images/reply/music-icon.png" alt="">
<span class="msg-tab-title">音乐</span>
</a>
</li>
<li class="tab-nav tab-audio {if $options['voice']}hidden{/if}">
<a href="javascript:void(0);" onclick="select_mediaid('voice');">
<img src="./resource/images/reply/radio-icon.png" alt="">
<span class="msg-tab-title">语音</span>
</a>
</li>
<li class="tab-nav tab-video {if $options['video']}hidden{/if}">
<a href="javascript:void(0);" onclick="select_mediaid('video');">
<img src="./resource/images/reply/vedio-icon.png" alt="">
<span class="msg-tab-title">视频</span>
</a>
</li>
<li class="tab-nav tab-cardmsg {if $options['wxcard']}hidden{/if}">
<a href="javascript:void(0);" onclick="select_mediaid('wxcard');">
<img src="./resource/images/reply/image-card.png" alt="">
<span class="msg-tab-title">卡劵</span>
</a>
</li>
<li class="tab-nav tab-cardmsg {if $options['keyword']}hidden{/if}">
<a href="javascript:void(0);" onclick="select_mediaid('keyword');">
<img src="./resource/images/reply/keyword-icon.png" alt="">
<span class="msg-tab-title">{if $_GPC['m'] == 'welcome'}匹配{else}触发{/if}关键字</span>
</a>
</li>
<li class="tab-nav tab-cardmsg {if $options['module']}hidden{/if}">
<a href="javascript:void(0);" onclick="select_mediaid('module');">
<img src="./resource/images/reply/module-icon.png" alt="">
<span class="msg-tab-title">模块</span>
</a>
</li>
</ul>
</div>
</div>
</div>
<script>
var action = "{php echo $_GPC['a']}";
var m = "{php echo $_GPC['m']}";
//删除已选素材
var delmedia = function(type, ele) {
var oldVal = $(':hidden[name="reply[reply_'+type+']"]').val();
var newVal;
var media = $(ele).attr('data-media');
switch(type) {
case 'basic':
var middleVal = oldVal.split(',');
newVal = angular.copy(middleVal);
angular.forEach(middleVal, function(val, key) {
middleVal[key] = htmlEncode(angular.toJson(val));
});
var index = _.indexOf(middleVal, htmlEncode(angular.toJson(media)));
newVal = _.without(newVal, newVal[index]);
$(':hidden[name="reply[reply_'+type+']"]').val(newVal);
break;
case 'image':
var middleVal = oldVal.split(',');
newVal = angular.copy(middleVal);
angular.forEach(middleVal, function(val, key) {
if(val.match(media)) {
newVal = _.without(newVal, middleVal[key]);
}
});
$(':hidden[name="reply[reply_'+type+']"]').val(newVal);
break;
case 'news':
var middleVal = oldVal.slice(1, -1).split('},{');
newVal = angular.copy(middleVal);
angular.forEach(middleVal, function(val, key){
if(val.match('"mediaid":"'+media)) {
newVal = _.without(newVal, middleVal[key]);
}
});
angular.forEach(newVal, function(val, key) {
newVal[key] = '{'+val+'}';
});
$(':hidden[name="reply[reply_'+type+']"]').val(newVal);
break;
case 'music':
var middleVal = oldVal.slice(1, -1).split('},{');
newVal = angular.copy(middleVal);
angular.forEach(middleVal, function(val, key){
if(val.match(media)) {
newVal = _.without(newVal, middleVal[key]);
}
});
angular.forEach(newVal, function(val, key) {
newVal[key] = '{'+val+'}';
});
$(':hidden[name="reply[reply_'+type+']"]').val(newVal);
break;
case 'voice':
var middleVal = oldVal.split(',');
newVal = angular.copy(middleVal);
angular.forEach(middleVal, function(val, key) {
if(val.match(media)) {
newVal = _.without(newVal, middleVal[key]);
}
});
$(':hidden[name="reply[reply_'+type+']"]').val(newVal);
break;
case 'video':
var middleVal = oldVal.slice(1, -1).split('},{');
newVal = angular.copy(middleVal);
angular.forEach(middleVal, function(val, key){
if(val.match(media)) {
newVal = _.without(newVal, middleVal[key]);
}
});
angular.forEach(newVal, function(val, key) {
newVal[key] = '{'+val+'}';
});
$(':hidden[name="reply[reply_'+type+']"]').val(newVal);
break;
case 'wxcard':
var middleVal = oldVal.slice(1, -1).split('},{');
newVal = angular.copy(middleVal);
angular.forEach(middleVal, function(val, key){
if(val.match(media)) {
newVal = _.without(newVal, middleVal[key]);
}
});
angular.forEach(newVal, function(val, key) {
newVal[key] = '{'+val+'}';
});
$(':hidden[name="reply[reply_'+type+']"]').val(newVal);
break;
case 'keyword':
oldVal = oldVal.split(',');
index = _.indexOf(oldVal, media);
oldVal.splice(index, 1);
$(':hidden[name="reply[reply_'+type+']"]').val(oldVal);
break;
case 'module':
oldVal = oldVal.split(',');
index = _.indexOf(oldVal, media);
oldVal.splice(index, 1);
$(':hidden[name="reply[reply_'+type+']"]').val(oldVal);
break;
}
//显示隐藏-start
if((action == 'qr' || action == 'mass' || m == 'special' || m == 'welcome' || m == 'default') && $(':hidden[name="reply[reply_'+type+']"]').val().length == 0) {
$('.we7-select-msg').removeClass('hide');
}
//显示隐藏-end
$(ele).parent().parent('.del-'+type+'-media').parent('li').remove();
};
window.select_mediaid = function(type, otherVal){
var option = {
type: type,
isWechat : true, // 默认显示微信
needType : 3, // 除了图文 其他只能微信
otherVal : otherVal,//
others: {
image: {
needType : 1
},
video : {
needType : 1
},
voice : {
needType : 3
}
}
};
if (type == 'module'){
document.cookie = "special_reply_type={$_GPC['type']}";
}
util.material(function(material){
var replyVal = [];
$(':hidden[name="reply[reply_'+type+']"]').val() == '' ? '' : replyVal.push($(':hidden[name="reply[reply_'+type+']"]').val());
if (type == 'basic') {
if (angular.isDefined(otherVal)) {
var editmedia = $(".del-basic-media");
for (var i = 0; i < editmedia.length; i++) {
if (htmlEncode($(editmedia.get(i)).find('.edit-gray').data('media')) == htmlEncode(angular.toJson(otherVal))) {
var inputVal = $(':hidden[name="reply[reply_'+type+']"]').val();
var inputValArr = inputVal.split(',');
var middleVal = angular.copy(inputValArr);
angular.forEach(inputValArr, function(val, key) {
inputValArr[key] = htmlEncode(val);
});
var index = _.indexOf(inputValArr, htmlEncode(angular.toJson(otherVal)));
material.content = material.content.replace(/,/g, ',');
middleVal[index] = angular.toJson(material.content);
replyVal = middleVal.join(',');
$(':hidden[name="reply[reply_'+type+']"]').val(replyVal);
$(editmedia.get(i)).html(
' <div class="desc">'+
' <div class="media-content">'+
' <span data-toggle="tooltip" data-placement="bottom" title="'+htmlEncode(material.content)+'">'+htmlEncode(cutStr(material.content,60))+
' </span>'+
' </div>'+
' </div>'+
' <div class="opr">'+
' <a href="javascript:;" data-media="'+htmlEncode(angular.toJson(material.content))+'" class="edit-gray" onclick="select_mediaid(\'basic\', '+htmlEncode(angular.toJson(material.content))+')">编辑</a>'+
' <a href="javascript:;" data-media="'+htmlEncode(angular.toJson(material.content))+'" class="del-gray" onclick="delmedia(\''+type+'\', this)">删除</a>'+
' </div>'
);
break;
}
}
} else {
if($.trim(material.content).length == 0) {
return false;
}
material.content = material.content.replace(/,/g, ',');
replyVal.push(angular.toJson(material.content));
$(':hidden[name="reply[reply_'+type+']"]').val(replyVal);
$('.keywords-list').append(
'<li>'+
'<div class="del-'+type+'-media">'+
' <div class="desc">'+
' <div class="media-content">'+
' <span data-toggle="tooltip" data-placement="bottom" title="'+htmlEncode(material.content)+'">'+htmlEncode(cutStr(material.content,60))+'</span>'+
' </div>'+
' </div>'+
' <div class="opr">'+
' <a href="javascript:;" data-media="'+htmlEncode(angular.toJson(material.content))+'" class="edit-gray" onclick="select_mediaid(\'basic\', '+htmlEncode(angular.toJson(material.content))+')">编辑</a>'+
' <a href="javascript:;" data-media="'+htmlEncode(angular.toJson(material.content))+'" class="del-gray" onclick="delmedia(\''+type+'\', this)">删除</a>'+
' </div>'+
'</div>'+
'</li>'
);
}
} else if(type == 'keyword') {
if($.trim(material.id).length == 0) {
return false;
}
replyVal.push(angular.toJson(material.id));
$(':hidden[name="reply[reply_'+type+']"]').val(replyVal);
var keywords = [];
for(var i = 0; i < material.length; i++) {
keywords += '&nbsp;&nbsp;' + material.content;
}
$('.keywords-list').append(
'<li>'+
'<div class="del-'+type+'-media">'+
' <div class="desc">'+
' <div class="media-content">'+
' <a class="title-wrp" href="javascript:;">'+
' <span class="title">[关键字]'+material.content+'</span>'+
' </a>'+
' <p class="desc"><a href="javascript:;" class="appmsg-desc">'+keywords+'</a></p>'+
' </div>'+
' </div>'+
' <div class="opr">'+
'<a href="./index.php?c=platform&a=reply&do=post&m=keyword&rid=' + material.rid + '" target="_blank" class="del-gray">编辑</a> ' +
' <a href="javascript:;" data-media="'+material.content+'" class="del-gray" onclick="delmedia(\''+type+'\', this)">删除</a>'+
' </div>'+
'</div>'+
'</li>'
);
} else if(type == 'module') {
if($.trim(material.name).length == 0) {
return false;
}
replyVal.push(angular.toJson(material.name));
$(':hidden[name="reply[reply_'+type+']"]').val(replyVal);
$('.keywords-list').append(
'<li>'+
'<div class="del-'+type+'-media">'+
' <div class="desc">'+
' <div class="media-content">'+
' <div class="appmsgSendedItem">'+
' <a class="title-wrp" href="javascript:;">'+
' <span class="icon cover" style="background-image:url('+material.icon+');"></span>'+
' <span class="title">[模块]'+material.title+'</span>'+
' </a>'+
' </div>'+
' </div>'+
' </div>'+
' <div class="opr">'+
' <a href="javascript:;" data-media="'+material.name+'" class="del-gray" onclick="delmedia(\''+type+'\', this)">删除</a>'+
' </div>'+
'</div>'+
'</li>'
);
} else {
if(type != 'music' && $.trim(material.media_id).length == 0 && !(type == 'news' && material.model == 'local')) {
return false;
};
switch(type) {
case 'image':
replyVal.push(angular.toJson(material.media_id));
$('.keywords-list').append(
'<li>'+
'<div class="del-'+type+'-media">'+
' <div class="desc">'+
' <div class="media-content">'+
' <div class="appmsgSendedItem">'+
' <a class="title-wrp" href="javascript:;">'+
' <span class="icon cover" style="background-image:url('+material.url+');"></span>'+
' <span class="title">[图片]</span>'+
' </a>'+
' </div>'+
' </div>'+
' </div>'+
' <div class="opr">'+
' <a href="javascript:;" data-media="'+material.media_id+'" class="del-gray" onclick="delmedia(\''+type+'\', this)">删除</a>'+
' </div>'+
'</div>'+
'</li>'
);
break;
case 'news':
angular.forEach(material.items, function(newsV, newsK){
replyVal.push(angular.toJson({
title: newsV.title,
author: newsV.author,
description: newsV.digest,
thumb: newsV.thumb_url,
url: newsV.content_source_url ? newsV.content_source_url : newsV.url,
createtime: material.createtime,
displayorder: newsV.displayorder ? newsV.displayorder : 0,
mediaid: material.media_id,
model: material.model,
attach_id: newsV.attach_id
}));
});
$('.keywords-list').append(
'<li>'+
'<div class="del-'+type+'-media">'+
' <div class="desc">'+
' <div class="media-content">'+
' <div class="appmsgSendedItem">'+
' <a class="title-wrp" href="javascript:;">'+
' <span class="icon cover" style="background-image:url('+material.items[0].thumb_url+');"></span>'+
' <span class="title">[图文消息]'+material.items[0].title+'<span class="color-red">(多条图文只显示一条,不影响实际回复效果)</span></span>'+
' </a>'+
' <p class="desc"><a href="javascript:;" class="appmsg-desc">'+material.items[0].digest+'</a></p>'+
' </div>'+
' </div>'+
' </div>'+
' <div class="opr">'+
' <a href="./index.php?c=platform&a=material-post&type=reply&newsid='+material.id+'" target="_blank" class="del-gray">编辑</a>'+
' <a href="javascript:;" data-media="'+material.media_id+'" class="del-gray" onclick="delmedia(\''+type+'\', this)">删除</a>'+
' </div>'+
'</div>'+
'</li>'
);
break;
case 'voice':
replyVal.push(angular.toJson(material.media_id));
$('.keywords-list').append(
'<li>'+
'<div class="del-'+type+'-media">'+
' <div class="desc">'+
' <div class="media-content">'+
' <div class="audio-msg">'+
' <div class="icon-audio-wrp">'+
' <span class="icon-audio-msg"></span>'+
' </div>'+
' <div class="audio-content">'+
' <div class="audio-title">[语音]'+material.filename+'</div>'+
' </div>'+
' </div>'+
' </div>'+
' </div>'+
' <div class="opr">'+
' <a href="javascript:;" data-media="'+material.media_id+'" class="del-gray" onclick="delmedia(\''+type+'\', this)">删除</a>'+
' </div>'+
'</div>'+
'</li>'
);
break;
case 'video':
replyVal.push(angular.toJson({
mediaid: material.media_id,
title: material.tag.title,
description: material.tag.description
}));
$('.keywords-list').append(
'<li>'+
'<div class="del-'+type+'-media">'+
' <div class="desc">'+
' <div class="media-content">'+
' <div class="appmsgSendedItem">'+
' <a class="title-wrp" href="javascript:;">'+
' <span class="icon cover" data-contenturl="'+material.tag.down_url+'"></span>'+
' <span class="title">[视频]'+material.filename+'</span>'+
' <p class="desc"><a href="javascript:;" class="appmsg-desc">'+(material.tag.description ? material.tag.description : '--')+'</a></p>'+
' </a>'+
' </div>'+
' </div>'+
' </div>'+
' <div class="opr">'+
' <a href="javascript:;" data-media="'+material.media_id+'" class="del-gray" onclick="delmedia(\''+type+'\', this)">删除</a>'+
' </div>'+
'</div>'+
'</li>'
);
break;
case 'music':
replyVal.push(angular.toJson({
title: material.title,
url: material.url,
hqurl: material.HQUrl,
description: material.description,
}));
$('.keywords-list').append(
'<li>'+
'<div class="del-'+type+'-media">'+
' <div class="desc">'+
' <div class="media-content">'+
' <div class="appmsgSendedItem">'+
' <a class="title-wrp" href="javascript:;">'+
' <span class="icon cover" style="background-image:'+material.url+';"></span>'+
' <span class="title">[音乐]'+material.title+'</span>'+
' </a>'+
' <p class="desc"><a href="javascript:;" class="appmsg-desc">'+material.description+'</a></p>'+
' </div>'+
' </div>'+
' </div>'+
' <div class="opr">'+
' <a href="javascript:;" data-media="'+material.url+'" class="del-gray" onclick="delmedia(\''+type+'\', this)">删除</a>'+
' </div>'+
'</div>'+
'</li>'
);
break;
case 'wxcard':
replyVal.push(angular.toJson({
mediaid: material.card_id,
title: material.title,
cid: material.id,
brandname: material.brand_name,
logo_url: material.logo_url,
success: '成功',
error: '失败'
}));
$('.keywords-list').append(
'<li>'+
'<div class="del-'+type+'-media">'+
' <div class="desc">'+
' <div class="media-content">'+
' <div class="appmsgSendedItem">'+
' <a class="title-wrp" href="javascript:;">'+
' <span class="icon cover" style="background-image:url('+material.logo_url+');"></span>'+
' <span class="title">[卡券]'+material.title+'</span>'+
' <p class="desc"><a href="javascript:;" class="appmsg-desc">'+(material.brand_name ? material.brand_name : '--')+'</a></p>'+
' </a>'+
' </div>'+
' </div>'+
' </div>'+
' <div class="opr">'+
' <a href="javascript:;" data-media="'+material.card_id+'" class="del-gray" onclick="delmedia(\''+type+'\', this)">删除</a>'+
' </div>'+
'</div>'+
'</li>'
);
break;
}
$(':hidden[name="reply[reply_'+type+']"]').val(replyVal);
}
//显示隐藏-start
if((action == 'qr' || action == 'mass' || m == 'special' || m == 'welcome' || m == 'default') && replyVal.length > 0) {
$('.we7-select-msg').addClass('hide');
}
//显示隐藏-end
}, option);
};
window.initReplyController = function($scope) {
$scope.context = {};
$scope.context.items = {php echo json_encode($replies)};
var newsMediaIds = [];
angular.forEach($scope.context.items, function(val, key){
var replyVal = [];
var type = key;
switch(type) {
case 'basic':
angular.forEach(val, function(basicVal, basicKey) {
replyVal.push(angular.toJson(basicVal.content));
$('.keywords-list').append(
'<li>'+
'<div class="del-'+type+'-media">'+
' <div class="desc">'+
' <div class="media-content">'+
' <span data-toggle="tooltip" data-placement="bottom" title="'+htmlEncode(basicVal.content)+'">'+htmlEncode(cutStr(basicVal.content,60))+'</span>'+
' </div>'+
' </div>'+
' <div class="opr">'+
' <a href="javascript:;" data-media="'+htmlEncode(angular.toJson(basicVal.content))+'" class="edit-gray" onclick="select_mediaid(\'basic\', '+htmlEncode(angular.toJson(basicVal.content))+')">编辑</a>'+
' <a href="javascript:;" data-media="'+htmlEncode(angular.toJson(basicVal.content))+'" class="del-gray" onclick="delmedia(\''+type+'\', this)">删除</a>'+
' </div>'+
'</div>'+
'</li>'
);
});
$(':hidden[name="reply[reply_'+type+']"]').val(replyVal);
break;
case 'news':
angular.forEach(val, function(newsVal, newsKey) {
var index = _.indexOf(newsMediaIds, newsVal.media_id);
replyVal.push(angular.toJson({
title: newsVal.title,
author: newsVal.author,
description: newsVal.description ? newsVal.description : newsVal.digest,
thumb: newsVal.thumb ? newsVal.thumb : newsVal.thumb_url,
url: newsVal.url,
createtime: newsVal.createtime,
displayorder: newsVal.displayorder ? newsVal.displayorder : 0,
incontent: newsVal.incontent ? newsVal.incontent : 0,
parent_id: newsVal.parent_id ? newsVal.parent_id : 0,
mediaid: newsVal.media_id,
attach_id: newsVal.attach_id,
model: newsVal.model
}));
if (index == -1) {
$('.keywords-list').append(
'<li>'+
'<div class="del-'+type+'-media">'+
' <div class="desc">'+
' <div class="media-content">'+
' <div class="appmsgSendedItem">'+
' <a class="title-wrp" href="javascript:;">'+
' <span class="icon cover" style="background-image:url('+(newsVal.thumb ? newsVal.thumb : newsVal.thumb_url)+');"></span>'+
' <span class="title">[图文消息]'+newsVal.title+(!newsVal.attach_id ? '<span class="color-red">(素材不存在或已被删除)</span>' : '')+
' </span>'+
' </a>'+
' <p class="desc"><a href="javascript:;" class="appmsg-desc">'+(newsVal.description ? newsVal.description : '')+'</a></p>'+
' </div>'+
' </div>'+
' </div>'+
' <div class="opr">'+
'<a href="./index.php?c=platform&a=material-post&type=reply&newsid='+(newsVal.attach_id ? newsVal.attach_id : '')+'&reply_news_id='+newsVal.id+'" target="_blank" class="del-gray">编辑</a>' +
' <a href="javascript:;" data-media="'+newsVal.media_id+'" class="del-gray" onclick="delmedia(\''+type+'\', this)">删除</a>'+
' </div>'+
'</div>'+
'</li>'
);
newsMediaIds.push(newsVal.media_id);
}
});
$(':hidden[name="reply[reply_'+type+']"]').val(replyVal);
break;
case 'image':
angular.forEach(val, function(imageVal, imageKey) {
replyVal.push(angular.toJson(imageVal.mediaid));
$('.keywords-list').append(
'<li>'+
'<div class="del-'+type+'-media">'+
' <div class="desc">'+
' <div class="media-content">'+
' <div class="appmsgSendedItem">'+
' <a class="title-wrp" href="javascript:;">'+
' <span class="icon cover" style="background-image:url('+imageVal.img_url+');"></span>'+
' <span class="title">[图片]</span>'+
' </a>'+
' </div>'+
' </div>'+
' </div>'+
' <div class="opr">'+
' <a href="javascript:;" data-media="'+imageVal.mediaid+'" class="del-gray" onclick="delmedia(\''+type+'\', this)">删除</a>'+
' </div>'+
'</div>'+
'</li>'
);
});
$(':hidden[name="reply[reply_'+type+']"]').val(replyVal);
break;
case 'voice':
angular.forEach(val, function(voiceVal, voiceKey) {
replyVal.push(angular.toJson(voiceVal.mediaid));
$('.keywords-list').append(
'<li>'+
'<div class="del-'+type+'-media">'+
' <div class="desc">'+
' <div class="media-content">'+
' <div class="audio-msg">'+
' <div class="icon-audio-wrp">'+
' <span class="icon-audio-msg"></span>'+
' </div>'+
' <div class="audio-content">'+
' <div class="audio-title">[语音]'+voiceVal.title+'</div>'+
' </div>'+
' </div>'+
' </div>'+
' </div>'+
' <div class="opr">'+
' <a href="javascript:;" data-media="'+voiceVal.mediaid+'" class="del-gray" onclick="delmedia(\''+type+'\', this)">删除</a>'+
' </div>'+
'</div>'+
'</li>'
);
});
$(':hidden[name="reply[reply_'+type+']"]').val(replyVal);
break;
case 'video':
angular.forEach(val, function(videoVal, videoKey) {
replyVal.push(angular.toJson({
mediaid: videoVal.mediaid,
title: videoVal.title,
description: videoVal.description
}));
$('.keywords-list').append(
'<li>'+
'<div class="del-'+type+'-media">'+
' <div class="desc">'+
' <div class="media-content">'+
' <div class="appmsgSendedItem">'+
' <a class="title-wrp" href="javascript:;">'+
' <span class="icon cover" data-contenturl="'+videoVal.down_url+'"></span>'+
' <span class="title">[视频]'+(videoVal.filename ? videoVal.filename : '--')+'</span>'+
' <p class="desc"><a href="javascript:;" class="appmsg-desc">'+(videoVal.description ? videoVal.description : '--')+'</a></p>'+
' </a>'+
' </div>'+
' </div>'+
' </div>'+
' <div class="opr">'+
' <a href="javascript:;" data-media="'+videoVal.mediaid+'" class="del-gray" onclick="delmedia(\''+type+'\', this)">删除</a>'+
' </div>'+
'</div>'+
'</li>'
);
});
$(':hidden[name="reply[reply_'+type+']"]').val(replyVal);
break;
case 'wxcard':
angular.forEach(val, function(wxcardVal, wxcardKey) {
replyVal.push(angular.toJson({
mediaid: wxcardVal.card_id,
title: wxcardVal.title,
cid: wxcardVal.cid,
brandname: wxcardVal.brand_name,
logo_url: wxcardVal.logo_url,
success: wxcardVal.success,
error: wxcardVal.error
}));
$('.keywords-list').append(
'<li>'+
'<div class="del-'+type+'-media">'+
' <div class="desc">'+
' <div class="media-content">'+
' <div class="appmsgSendedItem">'+
' <a class="title-wrp" href="javascript:;">'+
' <span class="icon cover" style="background-image:url('+wxcardVal.logo_url+');"></span>'+
' <span class="title">[卡券]'+(wxcardVal.title ? wxcardVal.title : '--')+'</span>'+
' <p class="desc"><a href="javascript:;" class="appmsg-desc">'+(wxcardVal.brand_name ? wxcardVal.brand_name : '--')+'</a></p>'+
' </a>'+
' </div>'+
' </div>'+
' </div>'+
' <div class="opr">'+
' <a href="javascript:;" data-media="'+wxcardVal.card_id+'" class="del-gray" onclick="delmedia(\''+type+'\', this)">删除</a>'+
' </div>'+
'</div>'+
'</li>'
);
});
$(':hidden[name="reply[reply_'+type+']"]').val(replyVal);
break;
case 'keyword':
angular.forEach(val, function(keywordVal, keywordKey) {
replyVal.push(angular.toJson(keywordVal.id));
var keywords = '&nbsp;&nbsp;' + keywordVal.content;
$('.keywords-list').append(
'<li>'+
'<div class="del-'+type+'-media">'+
' <div class="desc">'+
' <div class="media-content">'+
' <a class="title-wrp" href="javascript:;">'+
' <span class="title">[关键字]'+keywordVal.name+'</span>'+
' </a>'+
' <p class="desc"><a href="javascript:;" class="appmsg-desc">'+keywords+'</a></p>'+
' </div>'+
' </div>'+
' <div class="opr">'+
'<a href="./index.php?c=platform&a=reply&do=post&m=keyword&rid=' + keywordVal.rid + '" target="_blank" class="del-gray">编辑</a> ' +
'<a href="javascript:;" data-media="'+keywordVal.name+'" class="del-gray" onclick="delmedia(\''+type+'\', this)">删除</a>'+
' </div>'+
'</div>'+
'</li>'
);
});
$(':hidden[name="reply[reply_'+type+']"]').val(replyVal[0]);
break;
case 'module':
angular.forEach(val, function(keywordVal, keywordKey) {
replyVal.push(angular.toJson(keywordVal.rid));
var keywords = '&nbsp;&nbsp;' + keywordVal.content;
$('.keywords-list').append(
'<li>'+
'<div class="del-'+type+'-media">'+
' <div class="desc">'+
' <div class="media-content">'+
' <div class="appmsgSendedItem">'+
' <a class="title-wrp" href="javascript:;">'+
' <span class="icon cover" style="background-image:url('+keywordVal.icon+');"></span>'+
' <span class="title">[模块]'+keywordVal.title+'</span>'+
' </a>'+
' </div>'+
' </div>'+
' </div>'+
' <div class="opr">'+
' <a href="javascript:;" data-media="'+keywordVal.name+'" class="del-gray" onclick="delmedia(\''+type+'\', this)">删除</a>'+
' </div>'+
'</div>'+
'</li>'
);
});
$(':hidden[name="reply[reply_'+type+']"]').val(val[0]['name']);
break;
case 'music':
angular.forEach(val, function(musicVal, musicKey) {
replyVal.push(angular.toJson({
title: musicVal.title,
url: musicVal.url,
hqurl: musicVal.hqurl,
description: musicVal.description,
}));
$('.keywords-list').append(
'<li>'+
'<div class="del-'+type+'-media">'+
' <div class="desc">'+
' <div class="media-content">'+
' <div class="appmsgSendedItem">'+
' <a class="title-wrp" href="javascript:;">'+
' <span class="icon cover" style="background-image:'+musicVal.url+';"></span>'+
' <span class="title">[音乐]'+musicVal.title+'</span>'+
' </a>'+
' <p class="desc"><a href="javascript:;" class="appmsg-desc">'+musicVal.description+'</a></p>'+
' </div>'+
' </div>'+
' </div>'+
' <div class="opr">'+
' <a href="javascript:;" data-media="'+musicVal.url+'" class="del-gray" onclick="delmedia(\''+type+'\', this)">删除</a>'+
' </div>'+
'</div>'+
'</li>'
);
});
$(':hidden[name="reply[reply_'+type+']"]').val(replyVal);
break;
}
//显示隐藏-start
if((action == 'qr' || action == 'mass' || m == 'special' || m == 'welcome' || m == 'default') && replyVal.length > 0) {
$('.we7-select-msg').addClass('hide');
}
//显示隐藏-end
});
};
window.validateReplyForm = function(form, $, _, util, $scope) {
var allEmpty = true;
var modules = ['basic', 'news', 'image', 'music', 'voice', 'video', 'wxcard', 'keyword', 'module'];
if($scope.reply.entry.module == 'reply') {
angular.forEach(modules, function(val, key){
if($(':hidden[name="reply[reply_'+val+']"]').val() != '') {
allEmpty = false;
};
});
}else {
if($(':hidden[name="reply[reply_'+$scope.reply.entry.module+']"]').val() != ''){
allEmpty = false;
};
}
if(allEmpty) {
util.message('请添加有效的回复内容。');
return false;
}
return true;
};
function htmlEncode(str) {
var s = "";
if(str.length == 0) return "";
s = str.replace(/&/g,"&amp;");
s = s.replace(/</g,"&lt;");
s = s.replace(/>/g,"&gt;");
s = s.replace(/\'/g,"&#039;");
s = s.replace(/\"/g,"&quot;");
s = s.replace(/\n/g, "\\n");
return s;
}
function htmlDecode(str) {
var s = "";
if(str.length == 0) return "";
s = str.replace(/&amp;/g,"&");
s = s.replace(/&lt;/g,"<");
s = s.replace(/&gt;/g,">");
s = s.replace(/&#039;/g,"'");
s = s.replace(/&quot;/g,'"');
s = s.replace(/\\n/g,'\n');
return s;
}
function cutStr(str, len) {
var str_length = 0;
var str_len = 0;
str_cut = new String();
str_len = str.length;
for (var i = 0; i < str_len; i++) {
a = str.charAt(i);
str_length++;
if (escape(a).length > 4) {
//中文字符的长度经编码之后大于4
str_length++;
}
str_cut = str_cut.concat(a);
if (str_length >= len) {
str_cut = str_cut.concat("...");
return str_cut;
}
}
//如果给定字符串小于指定长度,则返回源字符串;
if (str_length < len) {
return str;
}
}
$(document).on("mouseover","body",function(){
$("[data-toggle='tooltip']").tooltip();
});
</script>

88
framework/builtin/core/template/mobile/detail.html

@ -0,0 +1,88 @@
{template 'header'}
<div id="activity-detail">
<style type="text/css">
@charset "utf-8";
html{background:#FFF;color:#000;}
body, div, dl, dt, dd, h1, h2, h3, h4, h5, h6, pre, code, form, fieldset, legend, input, textarea, p, blockquote, th, td{margin:0;padding:0;}
table{border-collapse:collapse;border-spacing:0;}
fieldset, img{border:0;}
address, caption, cite, code, dfn, th, var{font-style:normal;font-weight:normal;}
ol, ul{list-style:none;}
caption, th{text-align:left;}
h1, h2, h3, h4, h5, h6{font-size:100%;font-weight:normal;}
q:before, q:after{content:'';}
abbr, acronym{border:0;font-variant:normal;}
sup{vertical-align:text-top;}
sub{vertical-align:text-bottom;}
input, textarea, select{font-family:inherit;font-size:inherit;font-weight:inherit;}
input, textarea, select{font-size:100%;}
legend{color:#000;}
html{background-color:#f8f7f5;}
body{background:#f8f7f5;color:#222;font-family:Helvetica, STHeiti STXihei, Microsoft JhengHei, Microsoft YaHei, Tohoma, Arial;height:100%;position:relative;}
body > .tips{display:none;left:50%;padding:20px;position:fixed;text-align:center;top:50%;width:200px;z-index:100;}
.page{padding:15px;}
.page .page-error, .page .page-loading{line-height:30px;position:relative;text-align:center;}
#activity-detail .page-bizinfo{border-bottom:2px solid #EEE;}
#activity-detail .page-bizinfo .header{padding: 15px 15px 10px; border-bottom:1px solid #CCC;}
#activity-detail .page-bizinfo .header #activity-name{color:#000;font-size:20px;font-weight:bold;word-break:normal;word-wrap:break-word;}
#activity-detail .page-bizinfo .header #post-date{color:#8c8c8c;font-size:11px;margin:0;}
#activity-detail .page-content{padding:15px;}
#activity-detail .page-content .media{margin-bottom:18px;}
#activity-detail .page-content .media img{width:100%;}
#activity-detail .page-content .text{color:#3e3e3e;font-size:1.5;line-height:1.5;width: 100%;overflow: hidden;zoom:1;}
#activity-detail .page-content .text p{min-height:1.5em;min-height: 1.5em;word-wrap: break-word;word-break:break-all;}
#activity-list .header{font-size:20px;}
#activity-list .page-list{border:1px solid #ccc;border-radius:5px;margin:18px 0;overflow:hidden;}
#activity-list .page-list .line.btn{border-radius:0;margin:0;text-align:left;}
#activity-list .page-list .line.btn .checkbox{height:25px;line-height:25px;padding-left:35px;position:relative;}
#activity-list .page-list .line.btn .checkbox .icons{background-color:#ccc;left:0;position:absolute;top:0;}
#activity-list .page-list .line.btn.off .icons{background-image:none;}
#activity-list #save.btn{background-image:linear-gradient(#22dd22, #009900);background-image:-moz-linear-gradient(#22dd22, #009900);background-image:-ms-linear-gradient(#22dd22, #009900);background-image:-o-linear-gradient(#22dd22, #009900);background-image:-webkit-gradient(linear, left top, left bottom, from(#22dd22), to(#009900));background-image:-webkit-linear-gradient(#22dd22, #009900);}
.vm{vertical-align:middle;}
.tc{text-align:center;}
.db{display:block;}
.dib{display:inline-block;}
.b{font-weight:700;}
.clr{clear:both;}
.text img{max-width:100%;}
.page-url{padding-top:18px;}
.page-url-link{color:#607FA6;font-size:14px;text-decoration:none;text-shadow:0 1px #ffffff;-webkit-text-shadow:0 1px #ffffff;-moz-text-shadow:0 1px #ffffff;}
#footer{text-align:center; background-color:#DADADA; border-top:1px solid #B9B9B9;}
#footer .copyright{border-top: 1px solid #CACACA;color: #7B7B7B;height: 35px;line-height: 35px;font-size: 12px;}
#footer .copyright a{display: block;width: 100%;height: 100%;}
#mbutton{padding:15px 10px 15px 10px; overflow:hidden; border-bottom:1px #DDD solid;}
#mbutton > span{float:right; display:inline-block; background:#58a3ff; border:1px #63a0eb solid; color:#FFF; height:30px; line-height:30px; padding:0 10px; margin-left:10px;}
#mcover{position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0, 0, 0, 0.7);display:none;z-index:20000;}
#mcover img{position:fixed;right: 18px;top:5px;width:260px;height:180px;z-index:20001;}
</style>
<div class="page-bizinfo">
<div class="header">
<h1 id="activity-name">{$row['title']}</h1>
<span id="post-date">
<span>{php echo date('Y-m-d', $row['createtime'])}</span>
<span>{$row['author']}</span>
<a href="{$subscribeurl}">
{if empty($_W['account']['name'])}
微擎团队
{else}
{$_W['account']['name']}
{/if}
</a>
</span>
</div>
</div>
<div class="page-content">
{if $row['incontent'] != 0}
<div class="media">
<img onerror="this.parentNode.removeChild(this)" src="{php echo tomedia($row['thumb']);}">
</div>
{/if}
<div class="text">
{$row['content']}
</div>
</div>
</div>
{php $_share = array('content' => $row['description'], 'title' => $row['title'], 'imgUrl' => tomedia($row['thumb']));}
{template 'footer'}

91
framework/builtin/core/template/mobile/pay.html

@ -0,0 +1,91 @@
<header class="mui-bar mui-bar-nav">
<a class="mui-icon mui-icon-back mui-pull-left js-switch-modal" href="javascript:;"></a>
<a class="mui-icon mui-icon-close mui-pull-right js-switch-pay-close"></a>
<h1 class="mui-title">付款详情</h1>
</header>
<div class="mui-content">
<div id="pay-main-modal" class="js-main-modal">
<ul class="mui-table-view mui-table-view-chevron">
<li class="mui-table-view-cell">
<span class="mui-text-muted">支付宝账号</span>
<span class="mui-pull-right">188****1234</span>
</li>
<li class="mui-table-view-cell js-switch-pay">
<a class="mui-navigate-right mui-media">
<span class="mui-text-muted">付款方式</span>
<span class="mui-pull-right js-pay-default-method"></span>
</a>
</li>
</ul>
<div class="mui-row mui-pa15">
<div class="mui-col-xs-6">需付款</div>
<div class="mui-col-xs-6 mui-text-right mui-big"><span class="js-pay-fee"></span></div>
</div>
<div class="mui-content-padded">
<form action="{php echo url('mc/cash/');}" method="post">
<input type="hidden" name="params" value="{php echo base64_encode(json_encode($params));}" />
<input type="hidden" name="code" value="" />
<input type="hidden" name="coupon_id" value="" />
<input type="hidden" name="do" value="wechat" />
<button type="submit" class="mui-btn mui-btn-success mui-btn-block" data-payparams="{php echo base64_encode(json_encode($params));}" value="确认支付">确认支付</button>
</form>
</div>
</div>
<ul id="pay-method-modal" class="mui-table-view mui-table-view-chevron js-switch-pay-modal" style="display:none;">
{if !empty($pay['credit']['switch'])}
<li class="mui-table-view-cell" data-method="credit" data-title="余额">
<a class="mui-navigate-right mui-media" href="javascript:;">
<img src="./resource/images/money.png" alt="" class="mui-media-object mui-pull-left"/>
<span class="mui-media-body mui-block">
余额
<span class="mui-block mui-text-muted mui-rmb mui-mt5">{php echo sprintf('%.2f', $credtis[$setting['creditbehaviors']['currency']]);}</span>
</span>
</a>
</li>
{/if}
{if $pay['baifubao']['switch']}
<li class="mui-table-view-cell" data-method="baifubao" data-title="百度钱包">
<a class="mui-navigate-right mui-media" href="javascript:;">
<img src="./resource/images/baidu-pay.png" alt="" class="mui-media-object mui-pull-left"/>
<span class="mui-media-body mui-block">
百度钱包
<span class="mui-block mui-text-muted mui-mt5">百度安全支付服务</span>
</span>
</a>
</li>
{/if}
{if $pay['unionpay']['switch']}
<li class="mui-table-view-cell" data-method="unionpay" data-title="银联支付">
<a class="mui-navigate-right mui-media" href="javascript:;">
<img src="./resource/images/yl-icon.png" alt="" class="mui-media-object mui-pull-left"/>
<span class="mui-media-body mui-block">
银联支付
<span class="mui-block mui-text-muted mui-mt5">银联安全支付服务</span>
</span>
</a>
</li>
{/if}
{if !empty($pay['wechat']['switch'])}
<li class="mui-table-view-cell" data-method="wechat" data-title="微信支付">
<a class="mui-navigate-right mui-media" href="javascript:;">
<img src="./resource/images/wx-icon.png" alt="" class="mui-media-object mui-pull-left"/>
<span class="mui-media-body mui-block">
微信支付
<span class="mui-block mui-text-muted mui-mt5">微信支付,安全快捷</span>
</span>
</a>
</li>
{/if}
{if !empty($pay['alipay']['switch'])}
<li class="mui-table-view-cell" data-method="alipay" data-title="支付宝">
<a class="mui-navigate-right mui-media" href="javascript:;">
<img src="./resource/images/zfb-icon.png" alt="" class="mui-media-object mui-pull-left"/>
<span class="mui-media-body mui-block">
支付宝
<span class="mui-block mui-text-muted mui-mt5">简单、安全、快速</span>
</span>
</a>
</li>
{/if}
</ul>
</div>

60
framework/builtin/core/wxapp.php

@ -0,0 +1,60 @@
<?php
class CoreModuleWxapp extends WeModuleWxapp {
public function doPagePay() {
global $_W, $_GPC;
$order_info = table('core_paylog')
->searchWithUniacid($_W['uniacid'])
->searchWithModule(safe_gpc_string($_GPC['module_name']))
->searchWithTid(safe_gpc_string($_GPC['orderid']))
->get();
$order = array(
'tid' => $order_info['tid'],
'user' => $_SESSION['openid'],
'fee' => $order_info['fee'],
'title' => trim($_GPC['title']),
);
$this->module = array('name' => $order_info['module']);
$paydata = $this->pay($order);
$this->result(0, '', $paydata);
}
public function doPagePayResult() {
global $_GPC, $_W;
$log = table('core_paylog')
->searchWithUniacid($_W['uniacid'])
->searchWithModule(safe_gpc_string($_GPC['module_name']))
->searchWithTid(safe_gpc_string($_GPC['orderid']))
->get();
if (!empty($log) && !empty($log['status'])) {
if (!empty($log['tag'])) {
$tag = iunserializer($log['tag']);
$log['uid'] = $tag['uid'];
}
$site = WeUtility::createModuleSite($log['module']);
if (!is_error($site)) {
$method = 'payResult';
if (method_exists($site, $method)) {
$ret = array();
$ret['weid'] = $log['uniacid'];
$ret['uniacid'] = $log['uniacid'];
$ret['result'] = 'success';
$ret['type'] = $log['type'];
$ret['from'] = 'return';
$ret['tid'] = $log['tid'];
$ret['uniontid'] = $log['uniontid'];
$ret['user'] = $log['openid'];
$ret['fee'] = $log['fee'];
$ret['tag'] = $tag;
$ret['is_usecard'] = $log['is_usecard'];
$ret['card_type'] = $log['card_type'];
$ret['card_fee'] = $log['card_fee'];
$ret['card_id'] = $log['card_id'];
exit($site->$method($ret));
}
}
}
}
}

40
framework/builtin/cover/processor.php

@ -0,0 +1,40 @@
<?php
defined('IN_IA') or exit('Access Denied');
class CoverModuleProcessor extends WeModuleProcessor {
public function respond() {
global $_W;
$content = $this->message['content'];
$reply = table('cover_reply')->where(array('rid' => $this->rule))->get();
if (!empty($reply)) {
load()->model('module');
$module = module_fetch($reply['module']);
if (empty($module) && !in_array($reply['module'], array('site', 'mc', 'card', 'page', 'clerk'))) {
return '';
}
$url = $reply['url'];
if (empty($reply['url'])) {
$entry = table('modules_bindings')
->select('eid')
->where(array(
'module' => $reply['module'],
'do' => $reply['do']
))
->get();
$url = url('entry', array('eid' => $entry['eid']));
}
$news = array();
$news[] = array(
'title' => $reply['title'],
'description' => $reply['description'],
'picurl' => $reply['thumb'],
'url' => $url,
);
return $this->respNews($news);
}
return '';
}
}

29
framework/builtin/default/processor.php

@ -0,0 +1,29 @@
<?php
defined('IN_IA') or exit('Access Denied');
class DefaultModuleProcessor extends WeModuleProcessor {
public function respond() {
global $_W, $engine;
if ('trace' == $this->message['type']
|| 'view_miniprogram' == $this->message['event']
|| 'VIEW' == $this->message['event']
) {
return $this->respText('');
}
$setting = uni_setting($_W['uniacid'], array('default'));
if (!empty($setting['default'])) {
$flag = array('image' => 'url', 'link' => 'url', 'text' => 'content');
$message = $this->message;
$message['type'] = 'text';
$message['content'] = $setting['default'];
$message['redirection'] = true;
$message['source'] = 'default';
$message['original'] = $this->message[$flag[$this->message['type']]];
$pars = $engine->analyzeText($message);
if (is_array($pars)) {
return array('params' => $pars);
}
}
}
}

2313
framework/class/account/account.class.php

File diff suppressed because it is too large

1810
framework/class/account/weixin.account.class.php

File diff suppressed because it is too large

376
framework/class/account/weixin.platform.class.php

@ -0,0 +1,376 @@
<?php
defined('IN_IA') or exit('Access Denied');
define('ACCOUNT_PLATFORM_API_ACCESSTOKEN', 'https://api.weixin.qq.com/cgi-bin/component/api_component_token');
define('ACCOUNT_PLATFORM_API_PREAUTHCODE', 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=');
define('ACCOUNT_PLATFORM_API_LOGIN', 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=%s&pre_auth_code=%s&redirect_uri=%s&auth_type=%s');
define('ACCOUNT_PLATFORM_API_QUERY_AUTH_INFO', 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=');
define('ACCOUNT_PLATFORM_API_ACCOUNT_INFO', 'https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=');
define('ACCOUNT_PLATFORM_API_REFRESH_AUTH_ACCESSTOKEN', 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=');
define('ACCOUNT_PLATFORM_API_OAUTH_CODE', 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&component_appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=%s#wechat_redirect');
define('ACCOUNT_PLATFORM_API_OAUTH_USERINFO', 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=%s&component_appid=%s#wechat_redirect');
define('ACCOUNT_PLATFORM_API_OAUTH_INFO', 'https://api.weixin.qq.com/sns/oauth2/component/access_token?appid=%s&component_appid=%s&code=%s&grant_type=authorization_code&component_access_token=');
define('ACCOUNT_PLATFORM_API_LOGIN_ACCOUNT', 1); define('ACCOUNT_PLATFORM_API_LOGIN_WXAPP', 2); load()->classs('weixin.account');
load()->func('communication');
class WeixinPlatform extends WeixinAccount {
public $appid;
protected $appsecret;
public $token;
public $encodingaeskey;
protected $refreshtoken;
protected $tablename = 'account_wechats';
protected $menuFrame = 'account';
protected $type = ACCOUNT_TYPE_OFFCIAL_AUTH;
protected $typeName = '公众号';
protected $typeSign = ACCOUNT_TYPE_SIGN;
public function __construct($uniaccount = array()) {
$setting = setting_load('platform');
$this->appid = $setting['platform']['appid'];
$this->appsecret = $setting['platform']['appsecret'];
$this->token = $setting['platform']['token'];
$this->encodingaeskey = $setting['platform']['encodingaeskey'];
parent::__construct($uniaccount);
}
protected function getAccountInfo($uniacid) {
if ('wx570bc396a51b8ff8' == $this->account['key']) {
$this->account['key'] = $this->appid;
$this->openPlatformTestCase();
}
$account = table('account_wechats')->getAccount($uniacid);
$account['encrypt_key'] = $this->appid;
return $account;
}
public function fetchSameAccountByAppid($appid) {
return pdo_get($this->tablename, array('key' => $appid));
}
public function getComponentAccesstoken() {
$accesstoken = cache_load(cache_system_key('account_component_assesstoken'));
if (empty($accesstoken) || empty($accesstoken['value'])) {
$ticket = $GLOBALS['_W']['setting']['account_ticket'];
if (empty($ticket)) {
return error(1, '缺少接入平台关键数据,等待微信开放平台推送数据,请十分钟后再试或是检查“授权事件接收URL”是否写错(index.php?c=account&amp;a=auth&amp;do=ticket地址中的&amp;符号容易被替换成&amp;amp;)');
}
$data = array(
'component_appid' => $this->appid,
'component_appsecret' => $this->appsecret,
'component_verify_ticket' => $ticket,
);
$response = $this->request(ACCOUNT_PLATFORM_API_ACCESSTOKEN, $data);
if (is_error($response)) {
return $response;
}
$accesstoken = array(
'value' => $response['component_access_token'],
);
$record_expire = intval($response['expires_in']) - 200;
cache_write(cache_system_key('account_component_assesstoken'), $accesstoken, $record_expire);
}
return $accesstoken['value'];
}
public function getPreauthCode() {
$preauthcode = cache_load(cache_system_key('account_preauthcode'));
if (empty($preauthcode) || empty($preauthcode['value'])) {
$component_accesstoken = $this->getComponentAccesstoken();
if (is_error($component_accesstoken)) {
return $component_accesstoken;
}
$data = array(
'component_appid' => $this->appid,
);
$response = $this->request(ACCOUNT_PLATFORM_API_PREAUTHCODE . $component_accesstoken, $data);
if (is_error($response)) {
return $response;
}
$preauthcode = array(
'value' => $response['pre_auth_code'],
);
$record_expire = intval($response['expires_in']) - 200;
cache_write(cache_system_key('account_preauthcode'), $preauthcode, $record_expire);
}
return $preauthcode['value'];
}
public function getAuthInfo($code) {
$component_accesstoken = $this->getComponentAccesstoken();
if (is_error($component_accesstoken)) {
return $component_accesstoken;
}
$post = array(
'component_appid' => $this->appid,
'authorization_code' => $code,
);
$response = $this->request(ACCOUNT_PLATFORM_API_QUERY_AUTH_INFO . $component_accesstoken, $post);
if (is_error($response)) {
return $response;
}
$this->setAuthRefreshToken($response['authorization_info']['authorizer_refresh_token']);
return $response;
}
public function getAuthorizerInfo($appid = '') {
$component_accesstoken = $this->getComponentAccesstoken();
if (is_error($component_accesstoken)) {
return $component_accesstoken;
}
$appid = !empty($appid) ? $appid : $this->account['key'];
$post = array(
'component_appid' => $this->appid,
'authorizer_appid' => $appid,
);
return $this->request(ACCOUNT_PLATFORM_API_ACCOUNT_INFO . $component_accesstoken, $post);
}
public function getAuthorizerList() {
$token = $this->getComponentAccesstoken();
if (is_error($token)) {
return $token;
}
$data = array(
'component_appid' => $this->appid,
'offset' => 0,
'count' => 500
);
$url = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_list?component_access_token={$token}";
return $this->request($url, $data);
}
public function getAccessToken() {
$cachekey = cache_system_key('account_auth_accesstoken', array('key' => $this->account['key']));
$auth_accesstoken = cache_load($cachekey);
if (empty($auth_accesstoken) || empty($auth_accesstoken['value'])) {
$component_accesstoken = $this->getComponentAccesstoken();
if (is_error($component_accesstoken)) {
return $component_accesstoken;
}
$this->refreshtoken = $this->getAuthRefreshToken();
$data = array(
'component_appid' => $this->appid,
'authorizer_appid' => $this->account['key'],
'authorizer_refresh_token' => $this->refreshtoken,
);
$response = $this->request(ACCOUNT_PLATFORM_API_REFRESH_AUTH_ACCESSTOKEN . $component_accesstoken, $data);
if (is_error($response)) {
return $response;
}
if ($response['authorizer_refresh_token'] != $this->refreshtoken) {
$this->setAuthRefreshToken($response['authorizer_refresh_token']);
}
$auth_accesstoken = array(
'value' => $response['authorizer_access_token'],
);
$record_expire = intval($response['expires_in']) - 200;
cache_write($cachekey, $auth_accesstoken, $record_expire);
}
return $auth_accesstoken['value'];
}
public function fetch_token() {
return $this->getAccessToken();
}
public function getAuthLoginUrl() {
$preauthcode = $this->getPreauthCode();
if (is_error($preauthcode)) {
$authurl = "javascript:alert('{$preauthcode['message']}');";
} else {
$authurl = sprintf(ACCOUNT_PLATFORM_API_LOGIN, $this->appid,
$preauthcode, urlencode($GLOBALS['_W']['siteroot'] . 'index.php?c=account&a=auth&do=forward'), ACCOUNT_PLATFORM_API_LOGIN_ACCOUNT);
}
return $authurl;
}
public function getOauthCodeUrl($callback, $state = '') {
return sprintf(ACCOUNT_PLATFORM_API_OAUTH_CODE, $this->account['key'], $this->appid, $callback, $state);
}
public function getOauthUserInfoUrl($callback, $state = '') {
return sprintf(ACCOUNT_PLATFORM_API_OAUTH_USERINFO, $this->account['key'], $callback, $state, $this->appid);
}
public function getOauthInfo($code = '') {
$component_accesstoken = $this->getComponentAccesstoken();
if (is_error($component_accesstoken)) {
return $component_accesstoken;
}
$apiurl = sprintf(ACCOUNT_PLATFORM_API_OAUTH_INFO . $component_accesstoken, $this->account['key'], $this->appid, $code);
$response = $this->request($apiurl);
if (is_error($response)) {
return $response;
}
cache_write('account_oauth_refreshtoken' . $this->account['key'], $response['refresh_token']);
return $response;
}
public function getJsApiTicket() {
$cachekey = cache_system_key('jsticket', array('uniacid' => $this->account['uniacid']));
$js_ticket = cache_load($cachekey);
if (empty($js_ticket) || empty($js_ticket['value'])) {
$access_token = $this->getAccessToken();
if (is_error($access_token)) {
return $access_token;
}
$apiurl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi";
$response = $this->request($apiurl);
if (is_error($response)) {
return $response;
}
$js_ticket = array(
'value' => $response['ticket'],
);
$record_expire = $response['expires_in'] - 200;
cache_write($cachekey, $js_ticket, $record_expire);
}
$this->account['jsapi_ticket'] = $js_ticket;
return $js_ticket['value'];
}
public function getJssdkConfig($url = '') {
global $_W, $urls;
$jsapiTicket = $this->getJsApiTicket();
if (is_error($jsapiTicket)) {
$jsapiTicket = $jsapiTicket['message'];
}
$nonceStr = random(16);
$timestamp = TIMESTAMP;
$url = empty($url) ? $urls['scheme'] . '://' . $urls['host'] . $_SERVER['REQUEST_URI'] : $url;
$string1 = "jsapi_ticket={$jsapiTicket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
$signature = sha1($string1);
$config = array(
'appId' => $this->account['key'],
'nonceStr' => $nonceStr,
'timestamp' => "$timestamp",
'signature' => $signature,
);
if (DEVELOPMENT) {
$config['url'] = $url;
$config['string1'] = $string1;
$config['name'] = $this->account['name'];
}
return $config;
}
public function openPlatformTestCase() {
global $_GPC;
$post = file_get_contents('php://input');
WeUtility::logging('platform-test-message', $post);
$encode_message = $this->xmlExtract($post);
$message = aes_decode($encode_message['encrypt'], $this->encodingaeskey);
$message = $this->parse($message);
$response = array(
'ToUserName' => $message['from'],
'FromUserName' => $message['to'],
'CreateTime' => TIMESTAMP,
'MsgId' => TIMESTAMP,
'MsgType' => 'text',
);
if ('TESTCOMPONENT_MSG_TYPE_TEXT' == $message['content']) {
$response['Content'] = 'TESTCOMPONENT_MSG_TYPE_TEXT_callback';
}
if ('event' == $message['msgtype']) {
$response['Content'] = $message['event'] . 'from_callback';
}
if (strexists($message['content'], 'QUERY_AUTH_CODE')) {
list($sufixx, $authcode) = explode(':', $message['content']);
$auth_info = $this->getAuthInfo($authcode);
WeUtility::logging('platform-test-send-message', var_export($auth_info, true));
$url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $auth_info['authorization_info']['authorizer_access_token'];
$data = array(
'touser' => $message['from'],
'msgtype' => 'text',
'text' => array('content' => $authcode . '_from_api'),
);
$response = ihttp_request($url, urldecode(json_encode($data)));
exit('');
}
$xml = array(
'Nonce' => $_GPC['nonce'],
'TimeStamp' => $_GPC['timestamp'],
'Encrypt' => aes_encode(array2xml($response), $this->encodingaeskey, $this->appid),
);
$signature = array($xml['Encrypt'], $this->token, $_GPC['timestamp'], $_GPC['nonce']);
sort($signature, SORT_STRING);
$signature = implode($signature);
$xml['MsgSignature'] = sha1($signature);
exit(array2xml($xml));
}
public function openGet($appid = '') {
$token = $this->getAccessToken();
if (is_error($token)) {
return $token;
}
$data = array(
'appid' => !empty($appid) ? $appid : $this->account['key'],
);
$url = "https://api.weixin.qq.com/cgi-bin/open/get?access_token={$token}";
return $this->request($url, $data);
}
public function openBind($appid = '') {
$token = $this->getAccessToken();
if (is_error($token)) {
return $token;
}
$data = array(
'appid' => !empty($appid) ? $appid : $this->account['key'],
'open_appid' => $this->appid,
);
$url = "https://api.weixin.qq.com/cgi-bin/open/bind?access_token={$token}";
return $this->request($url, $data);
}
protected function request($url, $post = array()) {
if (!empty($post)) {
$response = ihttp_request($url, json_encode($post, JSON_UNESCAPED_UNICODE));
} else {
$response = ihttp_request($url);
}
$response = json_decode($response['content'], true);
if (empty($response) || !empty($response['errcode'])) {
return error($response['errcode'], $this->errorCode($response['errcode'], $response['errmsg']));
}
return $response;
}
protected function getAuthRefreshToken() {
$auth_refresh_token = cache_load(cache_system_key('account_auth_refreshtoken', array('uniacid' => $this->account['uniacid'])));
if (empty($auth_refresh_token)) {
$auth_refresh_token = $this->account['auth_refresh_token'];
cache_write(cache_system_key('account_auth_refreshtoken', array('uniacid' => $this->account['uniacid'])), $auth_refresh_token);
}
return $auth_refresh_token;
}
protected function setAuthRefreshToken($token) {
$tablename = 'account_wechats';
pdo_update($tablename, array('auth_refresh_token' => $token), array('uniacid' => $this->account['uniacid']));
cache_write(cache_system_key('account_auth_refreshtoken', array('uniacid' => $this->account['uniacid'])), $token);
}
public function result($errno, $message = '', $data = '') {
exit(json_encode(array(
'errno' => $errno,
'message' => $message,
'data' => $data,
)));
}
}

187
framework/class/captcha.class.php

@ -0,0 +1,187 @@
<?php
defined('IN_IA') or exit('Access Denied');
class Captcha {
public $maxAngle = 15;
public $maxOffset = 5;
public $phrase = '';
public function build($width, $height) {
$image = @imagecreatetruecolor($width, $height);
if (empty($image)) {
return error('1', 'Not supplied GD');
}
$bg = imagecolorallocate($image, $this->rand(200, 255), $this->rand(200, 255), $this->rand(200, 255));
imagefill($image, 0, 0, $bg);
$square = $width * $height * 3;
$effects = $this->rand($square / 2000, $square / 1000);
for ($e = 0; $e < $effects; ++$e) {
$this->drawLine($image, $width, $height);
}
$this->phrase = $this->phrase();
$color = $this->writePhrase($image, $this->phrase, $this->font(), $width, $height);
$square = $width * $height;
$effects = $this->rand($square / 3000, $square / 2000);
if (0 !== $this->maxFrontLines) {
for ($e = 0; $e < $effects; ++$e) {
$this->drawLine($image, $width, $height, $color);
}
}
$image = $this->distort($image, $width, $height, $bg);
$this->image = $image;
return $this;
}
public function output($quality = 90) {
header('content-type: image/png');
imagepng($this->image);
imagedestroy($this->image);
}
protected function phrase() {
return random(4, true);
}
protected function rand($min, $max) {
mt_srand((float) microtime() * 1000000);
return mt_rand($min, $max);
}
protected function drawLine($image, $width, $height, $tcol = null) {
if (null === $tcol) {
$tcol = imagecolorallocate($image, $this->rand(100, 255), $this->rand(100, 255), $this->rand(100, 255));
}
if ($this->rand(0, 1)) {
$Xa = $this->rand(0, $width / 2);
$Ya = $this->rand(0, $height);
$Xb = $this->rand($width / 2, $width);
$Yb = $this->rand(0, $height);
} else {
$Xa = $this->rand(0, $width);
$Ya = $this->rand(0, $height / 2);
$Xb = $this->rand(0, $width);
$Yb = $this->rand($height / 2, $height);
}
imagesetthickness($image, $this->rand(1, 3));
imageline($image, $Xa, $Ya, $Xb, $Yb, $tcol);
}
protected function writePhrase($image, $phrase, $font, $width, $height) {
$size = $width / strlen($phrase) - $this->rand(0, 3) - 1;
$box = imagettfbbox($size, 0, $font, $phrase);
$textWidth = $box[2] - $box[0];
$textHeight = $box[1] - $box[7];
$x = ($width - $textWidth) / 2;
$y = ($height - $textHeight) / 2 + $size;
$textColor = array($this->rand(0, 150), $this->rand(0, 150), $this->rand(0, 150));
$col = imagecolorallocate($image, $textColor[0], $textColor[1], $textColor[2]);
$length = strlen($phrase);
for ($i = 0; $i < $length; ++$i) {
$box = imagettfbbox($size, 0, $font, $phrase[$i]);
$w = $box[2] - $box[0];
$angle = $this->rand(-$this->maxAngle, $this->maxAngle);
$offset = $this->rand(-$this->maxOffset, $this->maxOffset);
imagettftext($image, $size, $angle, $x, $y + $offset, $col, $font, $phrase[$i]);
$x += $w;
}
return $col;
}
public function distort($image, $width, $height, $bg) {
$contents = imagecreatetruecolor($width, $height);
$X = $this->rand(0, $width);
$Y = $this->rand(0, $height);
$phase = $this->rand(0, 10);
$scale = 1.1 + $this->rand(0, 10000) / 30000;
for ($x = 0; $x < $width; ++$x) {
for ($y = 0; $y < $height; ++$y) {
$Vx = $x - $X;
$Vy = $y - $Y;
$Vn = sqrt($Vx * $Vx + $Vy * $Vy);
if (0 != $Vn) {
$Vn2 = $Vn + 4 * sin($Vn / 30);
$nX = $X + ($Vx * $Vn2 / $Vn);
$nY = $Y + ($Vy * $Vn2 / $Vn);
} else {
$nX = $X;
$nY = $Y;
}
$nY = $nY + $scale * sin($phase + $nX * 0.2);
$p = $this->interpolate(
$nX - floor($nX),
$nY - floor($nY),
$this->getCol($image, floor($nX), floor($nY), $bg),
$this->getCol($image, ceil($nX), floor($nY), $bg),
$this->getCol($image, floor($nX), ceil($nY), $bg),
$this->getCol($image, ceil($nX), ceil($nY), $bg)
);
if (0 == $p) {
$p = $bg;
}
imagesetpixel($contents, $x, $y, $p);
}
}
return $contents;
}
protected function interpolate($x, $y, $nw, $ne, $sw, $se) {
list($r0, $g0, $b0) = $this->getRGB($nw);
list($r1, $g1, $b1) = $this->getRGB($ne);
list($r2, $g2, $b2) = $this->getRGB($sw);
list($r3, $g3, $b3) = $this->getRGB($se);
$cx = 1.0 - $x;
$cy = 1.0 - $y;
$m0 = $cx * $r0 + $x * $r1;
$m1 = $cx * $r2 + $x * $r3;
$r = (int) ($cy * $m0 + $y * $m1);
$m0 = $cx * $g0 + $x * $g1;
$m1 = $cx * $g2 + $x * $g3;
$g = (int) ($cy * $m0 + $y * $m1);
$m0 = $cx * $b0 + $x * $b1;
$m1 = $cx * $b2 + $x * $b3;
$b = (int) ($cy * $m0 + $y * $m1);
return ($r << 16) | ($g << 8) | $b;
}
protected function getRGB($col) {
return array(
(int) ($col >> 16) & 0xff,
(int) ($col >> 8) & 0xff,
(int) ($col) & 0xff,
);
}
protected function getCol($image, $x, $y, $background) {
$L = imagesx($image);
$H = imagesy($image);
if ($x < 0 || $x >= $L || $y < 0 || $y >= $H) {
return $background;
}
return imagecolorat($image, $x, $y);
}
protected function font() {
return IA_ROOT . '/web/resource/fonts/captcha.ttf';
}
}

835
framework/class/db.class.php

@ -0,0 +1,835 @@
<?php
defined('IN_IA') or exit('Access Denied');
define('PDO_DEBUG', true);
class DB {
protected $pdo;
protected $cfg;
protected $tablepre;
protected $result;
protected $statement;
protected $errors = array();
protected $link = array();
protected $name = '';
public function getPDO() {
return $this->pdo;
}
public function __construct($name = 'master') {
global $_W;
$this->cfg = $_W['config']['db'];
$this->name = $name;
unset($_W['config']['db']);
$_W['config']['db'] = array(
'tablepre' => $this->cfg['master']['tablepre'] ?: $this->cfg['tablepre'],
'slave_status' => $this->cfg['slave_status']
);
$this->connect($name);
}
public function reConnect($errorInfo,$params) {
if (in_array($errorInfo[1], array(1317, 2013))) {
$this->pdo = null;
$this->connect($this->name);
$method = $params['method'];
unset($params['method']);
return call_user_func_array(array($this, $method), $params);
}
return false;
}
public function connect($name = 'master') {
if (is_array($name)) {
$cfg = $name;
} else {
$cfg = $this->cfg[$name];
}
$this->tablepre = $cfg['tablepre'];
if (empty($cfg)) {
exit("The master database is not found, Please checking 'data/config.php'");
}
$dsn = "mysql:dbname={$cfg['database']};host={$cfg['host']};port={$cfg['port']};charset={$cfg['charset']}";
$dbclass = '';
$options = array();
if (class_exists('PDO')) {
if (extension_loaded('pdo_mysql') && in_array('mysql', PDO::getAvailableDrivers())) {
$dbclass = 'PDO';
$options = array(PDO::ATTR_PERSISTENT => $cfg['pconnect']);
} else {
if (!class_exists('_PDO')) {
load()->library('pdo');
}
$dbclass = '_PDO';
}
} else {
load()->library('pdo');
$dbclass = 'PDO';
}
$pdo = new $dbclass($dsn, $cfg['username'], $cfg['password'], $options);
$this->pdo = $pdo;
$sql = "SET NAMES '{$cfg['charset']}';";
$this->pdo->exec($sql);
$this->pdo->exec("SET sql_mode='';");
if ('root' == $cfg['username'] && in_array($cfg['host'], array('localhost', '127.0.0.1'))) {
$this->pdo->exec('SET GLOBAL max_allowed_packet = 2*1024*1024*10;');
}
if (is_string($name)) {
$this->link[$name] = $this->pdo;
}
$this->logging($sql);
}
public function prepare($sql) {
$sqlsafe = SqlPaser::checkquery($sql);
if (is_error($sqlsafe)) {
trigger_error($sqlsafe['message'], E_USER_ERROR);
return false;
}
if ($GLOBALS['_W']['config']['setting']['development'] == 3) {
if ($GLOBALS['error_handler'] instanceof Raven_ErrorHandler) {
$GLOBALS['error_handler']->handleError(E_USER_ERROR, $sql);
}
}
$statement = $this->pdo->prepare($sql);
return $statement;
}
public function query($sql, $params = array()) {
$sqlsafe = SqlPaser::checkquery($sql);
if (is_error($sqlsafe)) {
trigger_error($sqlsafe['message'], E_USER_ERROR);
return false;
}
$starttime = intval(microtime(true));
if (empty($params)) {
$result = $this->pdo->exec($sql);
$error_info = $this->pdo->errorInfo();
$this->logging($sql, array(), $this->pdo->errorInfo());
if (in_array($error_info[1], array(1317, 2013))) {
$reConnect = $this->reConnect($error_info, array(
'method'=> __METHOD__,
'sql' => $sql,
'params' => $params,
));
return empty($reConnect) ? false : $reConnect;
}
return $result;
}
$statement = $this->prepare($sql);
$result = $statement->execute($params);
$this->logging($sql, $params, $statement->errorInfo());
$endtime = intval(microtime(true));
$this->performance($sql, $endtime - $starttime);
$error_info = $statement->errorInfo();
if (in_array($error_info[1], array(1317, 2013))) {
$reConnect = $this->reConnect($error_info, array(
'method' => __METHOD__,
'sql' => $sql,
'params' => $params,
));
return empty($reConnect) ? false : $reConnect;
} else {
return $statement->rowCount();
}
}
public function fetchcolumn($sql, $params = array(), $column = 0) {
$starttime = intval(microtime(true));
$statement = $this->prepare($sql);
$result = $statement->execute($params);
$this->logging($sql, $params, $statement->errorInfo());
$endtime = intval(microtime(true));
$this->performance($sql, $endtime - $starttime);
$error_info = $statement->errorInfo();
if (in_array($error_info[1], array(1317, 2013))) {
$reConnect = $this->reConnect($error_info, array(
'method' => __METHOD__,
'sql' => $sql,
'params' => $params,
'column' => $column,
));
return empty($reConnect) ? false : $reConnect;
} else {
$data = $statement->fetchColumn($column);
return $data;
}
}
public function fetch($sql, $params = array()) {
$starttime = intval(microtime(true));
$statement = $this->prepare($sql);
$result = $statement->execute($params);
$this->logging($sql, $params, $statement->errorInfo());
$endtime = intval(microtime(true));
$this->performance($sql, intval($endtime - $starttime));
$error_info = $statement->errorInfo();
if (in_array($error_info[1], array(1317, 2013))) {
$reConnect = $this->reConnect($error_info, array(
'method' => __METHOD__,
'sql' => $sql,
'params' => $params,
));
return empty($reConnect) ? false : $reConnect;
} else {
$data = $statement->fetch(pdo::FETCH_ASSOC);
return $data;
}
}
public function fetchall($sql, $params = array(), $keyfield = '') {
$starttime = intval(microtime(true));
$statement = $this->prepare($sql);
$result = $statement->execute($params);
$this->logging($sql, $params, $statement->errorInfo());
$endtime = intval(microtime(true));
$this->performance($sql, $endtime - $starttime);
$error_info = $statement->errorInfo();
if (in_array($error_info[1], array(1317, 2013))) {
$reConnect = $this->reConnect($error_info, array(
'method'=> __METHOD__,
'sql' => $sql,
'params' => $params,
'keyfield' => $keyfield,
));
return empty($reConnect) ? false : $reConnect;
} else {
if (empty($keyfield)) {
$result = $statement->fetchAll(pdo::FETCH_ASSOC);
} else {
$temp = $statement->fetchAll(pdo::FETCH_ASSOC);
$result = array();
if (!empty($temp)) {
foreach ($temp as $key => &$row) {
if (isset($row[$keyfield])) {
$result[$row[$keyfield]] = $row;
} else {
$result[] = $row;
}
}
}
}
return $result;
}
}
public function get($tablename, $params = array(), $fields = array(), $orderby = array()) {
$select = SqlPaser::parseSelect($fields);
$condition = SqlPaser::parseParameter($params, 'AND');
$orderbysql = SqlPaser::parseOrderby($orderby);
$sql = "{$select} FROM " . $this->tablename($tablename) . (!empty($condition['fields']) ? " WHERE {$condition['fields']}" : '') . " $orderbysql LIMIT 1";
return $this->fetch($sql, $condition['params']);
}
public function getall($tablename, $params = array(), $fields = array(), $keyfield = '', $orderby = array(), $limit = array()) {
$select = SqlPaser::parseSelect($fields);
$condition = SqlPaser::parseParameter($params, 'AND');
$limitsql = SqlPaser::parseLimit($limit);
$orderbysql = SqlPaser::parseOrderby($orderby);
$sql = "{$select} FROM " . $this->tablename($tablename) . (!empty($condition['fields']) ? " WHERE {$condition['fields']}" : '') . $orderbysql . $limitsql;
return $this->fetchall($sql, $condition['params'], $keyfield);
}
public function getslice($tablename, $params = array(), $limit = array(), &$total = null, $fields = array(), $keyfield = '', $orderby = array()) {
$select = SqlPaser::parseSelect($fields);
$condition = SqlPaser::parseParameter($params, 'AND');
$limitsql = SqlPaser::parseLimit($limit);
if (!empty($orderby)) {
if (is_array($orderby)) {
$orderbysql = implode(',', $orderby);
} else {
$orderbysql = $orderby;
}
}
$sql = "{$select} FROM " . $this->tablename($tablename) . (!empty($condition['fields']) ? " WHERE {$condition['fields']}" : '') . (!empty($orderbysql) ? " ORDER BY $orderbysql " : '') . $limitsql;
$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename($tablename) . (!empty($condition['fields']) ? " WHERE {$condition['fields']}" : ''), $condition['params']);
return $this->fetchall($sql, $condition['params'], $keyfield);
}
public function getcolumn($tablename, $params = array(), $field = '') {
$result = $this->get($tablename, $params, $field);
if (!empty($result)) {
if (strexists($field, '(')) {
return array_shift($result);
} else {
return $result[$field];
}
} else {
return false;
}
}
public function update($table, $data = array(), $params = array(), $glue = 'AND') {
$fields = SqlPaser::parseParameter($data, ',');
$condition = SqlPaser::parseParameter($params, $glue);
$params = array_merge($fields['params'], $condition['params']);
$sql = 'UPDATE ' . $this->tablename($table) . " SET {$fields['fields']}";
$sql .= $condition['fields'] ? ' WHERE ' . $condition['fields'] : '';
return $this->query($sql, $params);
}
public function insert($table, $data = array(), $replace = false) {
$cmd = $replace ? 'REPLACE INTO' : 'INSERT INTO';
$condition = SqlPaser::parseParameter($data, ',');
return $this->query("$cmd " . $this->tablename($table) . " SET {$condition['fields']}", $condition['params']);
}
public function insertid() {
return $this->pdo->lastInsertId();
}
public function delete($table, $params = array(), $glue = 'AND') {
$condition = SqlPaser::parseParameter($params, $glue);
$sql = 'DELETE FROM ' . $this->tablename($table);
$sql .= $condition['fields'] ? ' WHERE ' . $condition['fields'] : '';
return $this->query($sql, $condition['params']);
}
public function exists($tablename, $params = array()) {
$row = $this->get($tablename, $params);
if (empty($row) || !is_array($row) || 0 == count($row)) {
return false;
} else {
return true;
}
}
public function count($tablename, $params = array(), $cachetime = 30) {
$total = pdo_getcolumn($tablename, $params, 'count(*)');
return intval($total);
}
public function begin() {
$this->pdo->beginTransaction();
}
public function commit() {
$this->pdo->commit();
}
public function rollback() {
$this->pdo->rollBack();
}
public function run($sql, $stuff = 'ims_') {
if (!isset($sql) || empty($sql)) {
return;
}
$sql = str_replace("\r", "\n", str_replace(' ' . $stuff, ' ' . $this->tablepre, $sql));
$sql = str_replace("\r", "\n", str_replace(' `' . $stuff, ' `' . $this->tablepre, $sql));
$ret = array();
$num = 0;
$sql = preg_replace("/\;[ \f\t\v]+/", ';', $sql);
foreach (explode(";\n", trim($sql)) as $query) {
$ret[$num] = '';
$queries = explode("\n", trim($query));
foreach ($queries as $query) {
$ret[$num] .= (isset($query[0]) && '#' == $query[0]) || (isset($query[1]) && isset($query[1]) && $query[0] . $query[1] == '--') ? '' : $query;
}
++$num;
}
unset($sql);
foreach ($ret as $query) {
$query = trim($query);
if ($query) {
$this->query($query, array());
}
}
return true;
}
public function fieldexists($tablename, $fieldname) {
if (!$this->tableexists($tablename)) {
return false;
}
$fields = $this->fetchall("SHOW COLUMNS FROM " . $this->tablename($tablename));
if (empty($fields)) {
return false;
}
foreach ($fields as $field) {
if ($fieldname === $field['Field']) {
return true;
}
}
return false;
}
public function fieldmatch($tablename, $fieldname, $datatype = '', $length = '') {
$datatype = strtolower($datatype);
$field_info = $this->fetch('DESCRIBE ' . $this->tablename($tablename) . " `{$fieldname}`", array());
if (empty($field_info)) {
return false;
}
if (!empty($datatype)) {
$find = strexists($field_info['Type'], '(');
if (empty($find)) {
$length = '';
}
if (!empty($length)) {
$datatype .= ("({$length})");
}
return 0 === strpos($field_info['Type'], $datatype) ? true : -1;
}
return true;
}
public function indexexists($tablename, $indexname) {
if (!$this->tableexists($tablename)) {
return false;
}
if (!empty($indexname)) {
$indexs = $this->fetchall('SHOW INDEX FROM ' . $this->tablename($tablename), array(), '');
if (!empty($indexs) && is_array($indexs)) {
foreach ($indexs as $row) {
if ($row['Key_name'] == $indexname) {
return true;
}
}
}
}
return false;
}
public function tablename($table) {
return (0 === strpos($table, $this->tablepre) || 0 === strpos($table, 'ims_')) ? $table : "`{$this->tablepre}{$table}`";
}
public function debug($output = true, $append = array()) {
if (!empty($append)) {
$output = false;
array_push($this->errors, $append);
}
if ($output) {
print_r($this->errors);
} else {
if (!empty($append['error'][1])) {
$traces = debug_backtrace();
$ts = '';
foreach ($traces as $trace) {
$trace['file'] = str_replace('\\', '/', $trace['file']);
$trace['file'] = str_replace(IA_ROOT, '', $trace['file']);
$ts .= "file: {$trace['file']}; line: {$trace['line']}; <br />";
}
$params = var_export($append['params'], true);
trigger_error("SQL: <br/>{$append['sql']}<hr/>Params: <br/>{$params}<hr/>SQL Error: <br/>{$append['error'][2]}<hr/>Traces: <br/>{$ts}", E_USER_WARNING);
}
}
return $this->errors;
}
private function logging($sql, $params = array(), $message = '') {
if (PDO_DEBUG) {
$info = array();
$info['sql'] = $sql;
$info['params'] = $params;
$info['error'] = empty($message) ? $this->pdo->errorInfo() : $message;
$this->debug(false, $info);
}
return true;
}
public function tableexists($table) {
if (!empty($table)) {
$real_table = preg_match('/[a-zA-Z0-9_]{' . strlen($table) . '}/', $table);
if (1 !== $real_table) {
return false;
}
$tablename = (0 === strpos($table, $this->tablepre)) ? ($table) : ($this->tablepre . $table);
$data = $this->fetch("SHOW TABLES LIKE '{$tablename}'", array());
if (!empty($data)) {
$data = array_values($data);
if (in_array($tablename, $data)) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
private function performance($sql, $runtime = 0) {
global $_W;
if (0 == $runtime) {
return false;
}
if (strexists($sql, 'core_performance')) {
return false;
}
if (empty($_W['config']['setting']['maxtimesql'])) {
$_W['config']['setting']['maxtimesql'] = 5;
}
if ($runtime > $_W['config']['setting']['maxtimesql']) {
$sqldata = array(
'type' => '2',
'runtime' => $runtime,
'runurl' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'],
'runsql' => $sql,
'createtime' => time(),
);
$this->insert('core_performance', $sqldata);
}
return true;
}
}
class SqlPaser {
private static $checkcmd = array('SELECT', 'UPDATE', 'INSERT', 'REPLAC', 'DELETE');
private static $disable = array(
'function' => array('load_file', 'floor', 'hex', 'substring', 'if', 'ord', 'char', 'benchmark', 'reverse', 'strcmp', 'datadir', 'updatexml', 'extractvalue', 'name_const', 'multipoint', 'database', 'user'),
'action' => array('@', 'intooutfile', 'intodumpfile', 'unionselect', 'uniondistinct', 'information_schema', 'current_user', 'current_date'),
'note' => array('/*', '*/', '#', '--'),
);
public static function checkquery($sql) {
$cmd = strtoupper(substr(trim($sql), 0, 6));
if (in_array($cmd, self::$checkcmd)) {
$mark = $clean = '';
$sql = str_replace(array('\\\\', '\\\'', '\\"', '\'\''), '', $sql);
if (false === strpos($sql, '/') && false === strpos($sql, '#') && false === strpos($sql, '-- ') && false === strpos($sql, '@') && false === strpos($sql, '`')) {
$cleansql = preg_replace("/'(.+?)'/s", '', $sql);
} else {
$cleansql = self::stripSafeChar($sql);
}
$clean_function_sql = preg_replace("/\s+/", '', strtolower($cleansql));
if (is_array(self::$disable['function'])) {
foreach (self::$disable['function'] as $fun) {
if (false !== strpos($clean_function_sql, $fun . '(')) {
return error(1, 'SQL中包含禁用函数 - ' . $fun);
}
}
}
$cleansql = preg_replace("/[^a-z0-9_\-\(\)#\*\/\"]+/is", '', strtolower($cleansql));
if (is_array(self::$disable['action'])) {
foreach (self::$disable['action'] as $action) {
if (false !== strpos($cleansql, $action)) {
return error(2, 'SQL中包含禁用操作符 - ' . $action);
}
}
}
if (is_array(self::$disable['note'])) {
foreach (self::$disable['note'] as $note) {
if (false !== strpos($cleansql, $note)) {
return error(3, 'SQL中包含注释信息');
}
}
}
} elseif ('/*' === substr($cmd, 0, 2)) {
return error(3, 'SQL中包含注释信息');
}
}
private static function stripSafeChar($sql) {
$len = strlen($sql);
$mark = $clean = '';
for ($i = 0; $i < $len; ++$i) {
$str = $sql[$i];
switch ($str) {
case '\'':
if (!$mark) {
$mark = '\'';
$clean .= $str;
} elseif ('\'' == $mark) {
$mark = '';
}
break;
case '/':
if (empty($mark) && '*' == $sql[$i + 1]) {
$mark = '/*';
$clean .= $mark;
++$i;
} elseif ('/*' == $mark && '*' == $sql[$i - 1]) {
$mark = '';
$clean .= '*';
}
break;
case '#':
if (empty($mark)) {
$mark = $str;
$clean .= $str;
}
break;
case "\n":
if ('#' == $mark || '--' == $mark) {
$mark = '';
}
break;
case '-':
if (empty($mark) && '-- ' == substr($sql, $i, 3)) {
$mark = '-- ';
$clean .= $mark;
}
break;
default:
break;
}
$clean .= $mark ? '' : $str;
}
return $clean;
}
public static function parseParameter($params, $glue = ',', $alias = '') {
$result = array('fields' => ' 1 ', 'params' => array());
$split = '';
$suffix = '';
$allow_operator = array('>', '<', '<>', '!=', '>=', '<=', '+=', '-=', 'LIKE', 'like');
if (in_array(strtolower($glue), array('and', 'or'))) {
$suffix = '__';
}
if (!is_array($params)) {
$result['fields'] = $params;
return $result;
}
if (is_array($params)) {
$result['fields'] = '';
foreach ($params as $fields => $value) {
if (',' == $glue) {
$value = null === $value ? '' : $value;
}
$operator = '';
if (false !== strpos($fields, ' ')) {
list($fields, $operator) = explode(' ', $fields, 2);
if (!in_array($operator, $allow_operator)) {
$operator = '';
}
}
if (empty($operator)) {
$fields = trim($fields);
if (is_array($value) && !empty($value)) {
$operator = 'IN';
} elseif ('NULL' === $value) {
$operator = 'IS';
} else {
$operator = '=';
}
} elseif ('+=' == $operator) {
$operator = " = `$fields` + ";
} elseif ('-=' == $operator) {
$operator = " = `$fields` - ";
} elseif ('!=' == $operator || '<>' == $operator) {
if (is_array($value) && !empty($value)) {
$operator = 'NOT IN';
} elseif ('NULL' === $value) {
$operator = 'IS NOT';
}
}
$select_fields = self::parseFieldAlias($fields, $alias);
if (is_array($value) && !empty($value)) {
$insql = array();
$value = array_values($value);
foreach ($value as $v) {
$placeholder = self::parsePlaceholder($fields, $suffix);
$insql[] = $placeholder;
$result['params'][$placeholder] = is_null($v) ? '' : $v;
}
$result['fields'] .= $split . "$select_fields {$operator} (" . implode(',', $insql) . ')';
$split = ' ' . $glue . ' ';
} else {
$placeholder = self::parsePlaceholder($fields, $suffix);
$result['fields'] .= $split . "$select_fields {$operator} " . ('NULL' === $value ? 'NULL' : $placeholder);
$split = ' ' . $glue . ' ';
if ('NULL' !== $value) {
$result['params'][$placeholder] = is_array($value) ? '' : $value;
}
}
}
}
return $result;
}
private static function parsePlaceholder($field, $suffix = '') {
static $params_index = 0;
++$params_index;
$illegal_str = array('(', ')', ',', '.', '*');
$placeholder = ":{$suffix}" . str_replace($illegal_str, '_', $field) . "_{$params_index}";
return $placeholder;
}
private static function parseFieldAlias($field, $alias = '') {
if (strexists($field, '.') || strexists($field, '*')) {
return $field;
}
if (strexists($field, '(')) {
$select_fields = str_replace(array('(', ')'), array('(' . (!empty($alias) ? "`{$alias}`." : '') . '`', '`)'), $field);
} else {
$select_fields = (!empty($alias) ? "`{$alias}`." : '') . "`$field`";
}
return $select_fields;
}
public static function parseSelect($field = array(), $alias = '') {
if (empty($field) || '*' == $field) {
return ' SELECT *';
}
if (!is_array($field)) {
$field = array($field);
}
$select = array();
$index = 0;
foreach ($field as $field_row) {
if (strexists($field_row, '*')) {
if (!strexists(strtolower($field_row), 'as')) {
}
} elseif (strexists(strtolower($field_row), 'select')) {
if ('(' != $field_row[0]) {
$field_row = "($field_row) AS '{$index}'";
}
} elseif (strexists($field_row, '(')) {
$field_row = str_replace(array('(', ')'), array('(' . (!empty($alias) ? "`{$alias}`." : '') . '`', '`)'), $field_row);
if (!strexists(strtolower($field_row), 'as')) {
$field_row .= " AS '{$index}'";
}
} else {
$field_row = self::parseFieldAlias($field_row, $alias);
}
$select[] = $field_row;
++$index;
}
return ' SELECT ' . implode(',', $select);
}
public static function parseLimit($limit, $inpage = true) {
$limitsql = '';
if (empty($limit)) {
return $limitsql;
}
if (is_array($limit)) {
if (empty($limit[0]) && !empty($limit[1])) {
$limitsql = ' LIMIT 0, ' . $limit[1];
} else {
$limit[0] = max(intval($limit[0]), 1);
!empty($limit[1]) && $limit[1] = max(intval($limit[1]), 1);
if (empty($limit[0]) && empty($limit[1])) {
$limitsql = '';
} elseif (!empty($limit[0]) && empty($limit[1])) {
$limitsql = ' LIMIT ' . $limit[0];
} else {
$limitsql = ' LIMIT ' . ($inpage ? ($limit[0] - 1) * $limit[1] : $limit[0]) . ', ' . $limit[1];
}
}
} else {
$limit = trim($limit);
if (preg_match('/^(?:limit)?[\s,0-9]+$/i', $limit)) {
$limitsql = strexists(strtoupper($limit), 'LIMIT') ? " $limit " : " LIMIT $limit";
}
}
return $limitsql;
}
public static function parseOrderby($orderby, $alias = '') {
$orderbysql = '';
if (empty($orderby)) {
return $orderbysql;
}
if (!is_array($orderby)) {
$orderby = explode(',', $orderby);
}
foreach ($orderby as $i => &$row) {
if (strtoupper($row) == 'RAND()') {
$row = strtoupper($row);
} else {
$row = strtolower($row);
list($field, $orderbyrule) = explode(' ', $row);
if ('asc' != $orderbyrule && 'desc' != $orderbyrule) {
unset($orderby[$i]);
}
$field = self::parseFieldAlias($field, $alias);
$row = "{$field} {$orderbyrule}";
}
}
$orderbysql = implode(',', $orderby);
return !empty($orderbysql) ? " ORDER BY $orderbysql " : '';
}
public static function parseGroupby($statement, $alias = '') {
if (empty($statement)) {
return $statement;
}
if (!is_array($statement)) {
$statement = explode(',', $statement);
}
foreach ($statement as $i => &$row) {
$row = self::parseFieldAlias($row, $alias);
if (strexists($row, ' ')) {
unset($statement[$i]);
}
}
$statementsql = implode(', ', $statement);
return !empty($statementsql) ? " GROUP BY $statementsql " : '';
}
}

304
framework/class/image.class.php

@ -0,0 +1,304 @@
<?php
defined('IN_IA') or exit('Access Denied');
class Image
{
private $src;
private $actions = array();
private $resize_width = 0;
private $resize_height = 0;
private $image = null;
private $imageinfo = array();
private $crop_width = 0;
private $crop_height = 0;
private $crop_position = 1;
private $ext = '';
public function __construct($src)
{
$this->src = $src;
$this->ext = pathinfo($src, PATHINFO_EXTENSION);
}
public static function create($src)
{
return new self($src);
}
public function resize($width = 0, $height = 0)
{
if ($width > 0 || $height > 0) {
$this->actions[] = 'resize';
}
if ($width > 0 && 0 == $height) {
$height = $width;
}
if ($height > 0 && 0 == $width) {
$width = $height;
}
$this->resize_width = $width;
$this->resize_height = $height;
return $this;
}
public function crop($width = 400, $height = 300, $position = 1)
{
if ($width > 0 || $height > 0) {
$this->actions[] = 'crop';
}
if ($width > 0 && 0 == $height) {
$height = $width;
}
if ($height > 0 && 0 == $width) {
$width = $height;
}
$this->crop_width = $width;
$this->crop_height = $height;
$this->crop_position = min(intval($position), 9);
return $this;
}
public function getExt()
{
return in_array($this->ext, array('jpg', 'jpeg', 'png', 'gif')) ? $this->ext : 'jpeg';
}
public function isPng()
{
return file_is_image($this->src) && 'png' == $this->getExt();
}
public function isJPEG()
{
return file_is_image($this->src) && in_array($this->getExt(), array('jpg', 'jpeg'));
}
public function isGif()
{
return file_is_image($this->src) && 'gif' == $this->getExt();
}
public function saveTo($path, $quality = null)
{
$path = safe_gpc_path($path);
if (empty($path)) {
return false;
}
$result = $this->handle();
if (!$result) {
return false;
}
$ext = $this->getExt();
if ('jpg' == $ext) {
$ext = 'jpeg';
}
$func = 'image' . $ext;
$real_quality = $this->realQuality($quality);
$saved = false;
$image = $this->image();
imagealphablending($image, false);
imagesavealpha($image, true);
if (is_null($real_quality)) {
$saved = $func($image, $path);
} else {
if (!$this->isGif()) {
$saved = $func($image, $path, $real_quality);
}
}
$this->destroy();
return $saved ? $path : $saved;
}
private function realQuality($quality = null)
{
if (is_null($quality)) {
return null;
}
$quality = min($quality, 100);
if ($this->isJPEG()) {
return $quality * 0.75;
}
if ($this->isPng()) {
return round(abs((100 - $quality) / 11.111111));
}
return null;
}
protected function handle()
{
if (!function_exists('gd_info')) {
return false;
}
$this->image = $this->createResource();
if (!$this->image) {
return false;
}
$this->imageinfo = getimagesize($this->src);
$actions = array_unique($this->actions);
$src_image = $this->image;
foreach ($actions as $action) {
$method = 'do' . ucfirst($action);
$src_image = $this->{$method}($src_image);
}
$this->image = $src_image;
return true;
}
protected function doCrop($src_image)
{
list($dst_x, $dst_y) = $this->getCropDestPoint();
if (version_compare(PHP_VERSION, '5.5.0') >= 0) {
$new_image = imagecrop($src_image, array('x' => $dst_x, 'y' => $dst_y, 'width' => $this->crop_width, 'height' => $this->crop_height));
imagedestroy($src_image);
} else {
$new_image = $this->modify($src_image, $this->crop_width, $this->crop_height, $this->crop_width, $this->crop_height, 0, 0, $dst_x, $dst_y);
}
$this->imageinfo[0] = $this->crop_width;
$this->imageinfo[1] = $this->crop_height;
return $new_image;
}
protected function doResize($src_image)
{
$newimage = $this->modify($src_image, $this->resize_width, $this->resize_height, $this->imageinfo[0], $this->imageinfo[1]);
$this->imageinfo[0] = $this->resize_width;
$this->imageinfo[1] = $this->resize_height;
return $newimage;
}
protected function modify($src_image, $width, $height, $src_width, $src_height, $dst_x = 0, $dst_y = 0, $src_x = 0, $src_y = 0)
{
$image = imagecreatetruecolor($width, $height);
imagealphablending($image, false);
imagesavealpha($image, true);
imagecopyresampled($image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $width, $height, $src_width, $src_height);
imagedestroy($src_image);
return $image;
}
private function image()
{
return $this->image;
}
private function destroy()
{
if ($this->image) {
imagedestroy($this->image);
}
}
private function createResource()
{
if (file_exists($this->src) && !is_readable($this->src)) {
return null;
}
if ($this->isPng()) {
return imagecreatefrompng($this->src);
}
if ($this->isJPEG()) {
return imagecreatefromjpeg($this->src);
}
if ($this->isGif()) {
return imagecreatefromgif($this->src);
}
return null;
}
public function toBase64($prefix = 'data:image/%s;base64,')
{
$filename = tempnam('tmp', 'base64');
$prefix = sprintf($prefix, $this->getExt());
$result = $this->saveTo($filename);
if (!$result) {
return false;
}
$content = file_get_contents($filename);
$base64 = base64_encode($content);
unlink($filename);
return $prefix . $base64;
}
private function getCropDestPoint()
{
$s_width = $this->imageinfo[0];
$s_height = $this->imageinfo[1];
$dst_x = $dst_y = 0;
if ('0' == $this->crop_width || $this->crop_width > $s_width) {
$this->crop_width = $s_width;
}
if ('0' == $this->crop_height || $this->crop_height > $s_height) {
$this->crop_height = $s_height;
}
switch ($this->crop_position) {
case 0:
case 1:
$dst_x = 0;
$dst_y = 0;
break;
case 2:
$dst_x = ($s_width - $this->crop_width) / 2;
$dst_y = 0;
break;
case 3:
$dst_x = $s_width - $this->crop_width;
$dst_y = 0;
break;
case 4:
$dst_x = 0;
$dst_y = ($s_height - $this->crop_height) / 2;
break;
case 5:
$dst_x = ($s_width - $this->crop_width) / 2;
$dst_y = ($s_height - $this->crop_height) / 2;
break;
case 6:
$dst_x = $s_width - $this->crop_width;
$dst_y = ($s_height - $this->crop_height) / 2;
break;
case 7:
$dst_x = 0;
$dst_y = $s_height - $this->crop_height;
break;
case 8:
$dst_x = ($s_width - $this->crop_width) / 2;
$dst_y = $s_height - $this->crop_height;
break;
case 9:
$dst_x = $s_width - $this->crop_width;
$dst_y = $s_height - $this->crop_height;
break;
default:
$dst_x = 0;
$dst_y = 0;
}
if ($this->crop_width == $s_width) {
$dst_x = 0;
}
if ($this->crop_height == $s_height) {
$dst_y = 0;
}
return array(intval($dst_x), intval($dst_y));
}
}

308
framework/class/loader.class.php

@ -0,0 +1,308 @@
<?php
defined('IN_IA') or exit('Access Denied');
function load() {
static $loader;
if (empty($loader)) {
$loader = new Loader();
}
return $loader;
}
function table($name) {
$table_classname = '\\We7\\Table\\';
$subsection_name = explode('_', $name);
if (1 == count($subsection_name)) {
$table_classname .= ucfirst($subsection_name[0]) . '\\' . ucfirst($subsection_name[0]);
} else {
foreach ($subsection_name as $key => $val) {
if (0 == $key) {
$table_classname .= ucfirst($val) . '\\';
} else {
$table_classname .= ucfirst($val);
}
}
}
if (in_array($name, array(
'account',
'account_aliapp',
'account_baiduapp',
'account_toutiaoapp',
'account_wxapp',
'account_phoneapp',
'account_webapp',
'account_wechats',
'article_category',
'activity_clerks',
'article_news',
'article_notice',
'article_comment',
'basic_reply',
'core_profile_fields',
'core_sendsms_log',
'core_attachment',
'core_attachment_group',
'core_cron',
'core_paylog',
'core_performance',
'core_refundlog',
'core_settings',
'core_cover_reply',
'core_message_notice_log',
'core_menu_shortcut',
'core_job',
'core_menu',
'coupon',
'coupon_record',
'cover_reply',
'custom_reply',
'images_reply',
'mc_card',
'mc_card_members',
'mc_card_notices',
'mc_card_notices_unread',
'mc_card_record',
'mc_card_sign_record',
'mc_credits_recharge',
'mc_credits_record',
'mc_cash_record',
'mc_chats_record',
'mc_groups',
'mc_handsel',
'mc_mass_record',
'mc_mapping_fans',
'mc_fans_tag_mapping',
'mc_mapping_ucenter',
'mc_members',
'mc_member_fields',
'mc_member_address',
'mc_fans_groups',
'mc_oauth_fans',
'mc_fans_tag',
'modules_rank',
'modules_bindings',
'modules_plugin',
'modules_plugin_rank',
'modules_cloud',
'modules_recycle',
'modules',
'modules_ignore',
'music_reply',
'news_reply',
'paycenter_order',
'phoneapp_versions',
'qrcode',
'qrcode_stat',
'rule',
'rule_keyword',
'site_article',
'site_article_comment',
'site_category',
'site_templates',
'site_multi',
'site_nav',
'site_page',
'site_slide',
'site_store_cash_log',
'site_store_cash_order',
'site_store_create_account',
'site_store_goods',
'site_store_goods_cloud',
'site_store_order',
'site_styles',
'site_styles_vars',
'stat_visit',
'stat_visit_ip',
'system_stat_visit',
'system_welcome_binddomain',
'uni_account',
'uni_account_menus',
'uni_account_modules',
'uni_account_users',
'uni_account_modules_shortcut',
'uni_verifycode',
'uni_group',
'uni_modules',
'uni_settings',
'userapi_reply',
'userapi_cache',
'users',
'users_group',
'users_profile',
'users_bind',
'users_create_group',
'users_extra_group',
'users_extra_limit',
'users_extra_modules',
'users_extra_templates',
'users_lastuse',
'users_founder_group',
'users_founder_own_users',
'users_founder_own_users_groups',
'users_founder_own_uni_groups',
'users_founder_own_create_groups',
'users_permission',
'users_login_logs',
'users_operate_history',
'users_operate_star',
'voice_reply',
'video_reply',
'wechat_news',
'wechat_attachment',
'wxapp_versions',
'wxcard_reply',
'uni_link_uniacid',
'wxapp_general_analysis',
'wxapp_register_version',
))) {
return new $table_classname();
}
load()->classs('table');
load()->table($name);
$service = false;
$class_name = "{$name}Table";
if (class_exists($class_name)) {
$service = new $class_name();
}
return $service;
}
class Loader {
private $cache = array();
private $singletonObject = array();
private $libraryMap = array(
'agent' => 'agent/agent.class',
'captcha' => 'captcha/captcha.class',
'pdo' => 'pdo/PDO.class',
'qrcode' => 'qrcode/phpqrcode',
'ftp' => 'ftp/ftp',
'pinyin' => 'pinyin/pinyin',
'pkcs7' => 'pkcs7/pkcs7Encoder',
'json' => 'json/JSON',
'phpmailer' => 'phpmailer/PHPMailerAutoload',
'oss' => 'alioss/autoload',
'qiniu' => 'qiniu/autoload',
'cosv5' => 'cosv5/index',
'sentry' => 'sentry/Raven/Autoloader',
);
private $loadTypeMap = array(
'func' => '/framework/function/%s.func.php',
'model' => '/framework/model/%s.mod.php',
'classs' => '/framework/class/%s.class.php',
'library' => '/framework/library/%s.php',
'table' => '/framework/table/%s.table.php',
'web' => '/web/common/%s.func.php',
'app' => '/app/common/%s.func.php',
);
private $accountMap = array(
'pay' => 'pay/pay',
'account' => 'account/account',
'weixin.account' => 'account/weixin.account',
'weixin.platform' => 'account/weixin.platform',
'aliapp.account' => 'account/aliapp.account',
'baiduapp.account' => 'account/baiduapp.account',
'toutiaoapp.account' => 'account/toutiaoapp.account',
'phoneapp.account' => 'account/phoneapp.account',
'webapp.account' => 'account/webapp.account',
'wxapp.account' => 'account/wxapp.account',
'wxapp.platform' => 'account/wxapp.platform',
'wxapp.work' => 'account/wxapp.work',
);
public function __construct() {
$this->registerAutoload();
}
public function registerAutoload() {
spl_autoload_register(array($this, 'autoload'));
}
public function autoload($class) {
$section = array(
'Table' => '/framework/table/',
);
$classmap = array(
'We7Table' => 'table',
);
if (isset($classmap[$class])) {
load()->classs($classmap[$class]);
} elseif (preg_match('/^[0-9a-zA-Z\-\\\\_]+$/', $class)
&& (0 === stripos($class, 'We7') || 0 === stripos($class, '\We7'))
&& false !== stripos($class, '\\')) {
$group = explode('\\', $class);
$path = IA_ROOT . $section[$group[1]];
unset($group[0]);
unset($group[1]);
$file_path = $path . implode('/', $group) . '.php';
if (is_file($file_path)) {
include $file_path;
}
$file_path = $path . 'Core/' . implode('', $group) . '.php';
if (is_file($file_path)) {
include $file_path;
}
}
}
public function __call($type, $params) {
global $_W;
$name = $cachekey = array_shift($params);
$accountMapKey = array_search($name, $this->accountMap);
if (!empty($accountMapKey)) {
$name = $cachekey = $accountMapKey;
}
if (!empty($this->cache[$type]) && isset($this->cache[$type][$cachekey])) {
return true;
}
if (empty($this->loadTypeMap[$type])) {
return true;
}
if ('library' == $type && !empty($this->libraryMap[$name])) {
$name = $this->libraryMap[$name];
}
if ('classs' == $type && !empty($this->accountMap[$name])) {
$filename = sprintf($this->loadTypeMap[$type], $this->accountMap[$name]);
if (file_exists(IA_ROOT . $filename)) {
$name = $this->accountMap[$name];
}
}
$file = sprintf($this->loadTypeMap[$type], $name);
if (file_exists(IA_ROOT . $file)) {
include IA_ROOT . $file;
$this->cache[$type][$cachekey] = true;
}
return true;
}
public function singleton($name) {
if (isset($this->singletonObject[$name])) {
return $this->singletonObject[$name];
}
$this->singletonObject[$name] = $this->object($name);
return $this->singletonObject[$name];
}
public function object($name) {
$this->classs(strtolower($name));
if (class_exists($name)) {
return new $name();
} else {
return false;
}
}
}

212
framework/class/oauth2/mobile.class.php

@ -0,0 +1,212 @@
<?php
defined('IN_IA') or exit('Access Denied');
class Mobile extends OAuth2Client {
public function __construct($ak, $sk) {
parent::__construct($ak, $sk);
$this->stateParam['from'] = 'mobile';
}
public function showLoginUrl($calback_url = '') {
}
public function user() {
global $_GPC, $_W;
$mobile = trim($_GPC['username']);
$member['password'] = $_GPC['password'];
pdo_delete('users_failed_login', array('lastupdate <' => TIMESTAMP - 3600));
$failed = pdo_get('users_failed_login', array('username' => $mobile, 'ip' => $_W['clientip']));
if ($failed['count'] >= 5) {
return error('-1', '输入密码错误次数超过5次,请在1小时后再登录');
}
if (!empty($_W['setting']['copyright']['verifycode'])) {
$verify = trim($_GPC['verify']);
if (empty($verify)) {
return error('-1', '请输入验证码');
}
$result = checkcaptcha($verify);
if (empty($result)) {
return error('-1', '输入验证码错误');
}
}
if (empty($mobile)) {
return error('-1', '请输入要登录的手机号');
}
if (!preg_match(REGULAR_MOBILE, $mobile)) {
return error(-1, '手机号格式不正确');
}
if (empty($member['password'])) {
return error('-1', '请输入密码');
}
$user_profile = table('users_profile')->getByMobile($mobile);
if (empty($user_profile)) {
return error(-1, '手机号未注册');
}
$member['uid'] = $user_profile['uid'];
$member['type'] = $this->user_type;
return $member;
}
public function validateMobile() {
global $_GPC;
$mobile = $_GPC['mobile'];
if (empty($mobile)) {
return error(-1, '手机号不能为空');
}
if (!preg_match(REGULAR_MOBILE, $mobile)) {
return error(-1, '手机号格式不正确');
}
$mobile_exists = table('users_profile')->getByMobile($mobile);
if (!empty($mobile_exists)) {
return error(-1, '手机号已存在');
}
return true;
}
public function register() {
global $_GPC;
load()->model('user');
$member = array();
$profile = array();
$smscode = trim($_GPC['smscode']);
$mobile = trim($_GPC['mobile']);
$member['password'] = $_GPC['password'];
if (empty($smscode)) {
return error(-1, '短信验证码不能为空');
}
load()->model('utility');
$verify_info = utility_smscode_verify(0, $mobile, $smscode);
if (is_error($verify_info)) {
return error(-1, $verify_info['message']);
}
if (istrlen($member['password']) < 8) {
return error(-1, '必须输入密码,且密码长度不得低于8位。');
}
$member['username'] = $mobile;
$member['openid'] = $mobile;
$member['register_type'] = USER_REGISTER_TYPE_MOBILE;
$member['owner_uid'] = intval($_GPC['owner_uid']);
$profile['mobile'] = $mobile;
$register = array(
'member' => $member,
'profile' => $profile,
);
return parent::user_register($register);
}
public function login() {
return $this->user();
}
public function bind() {
global $_GPC, $_W;
$mobile = safe_gpc_string($_GPC['mobile']);
$user = table('users')->getById($_W['uid']);
if (empty($user)) {
return error(-1, '请先登录');
}
$user_profile = table('users_profile')->getByUid($_W['uid']);
$user_bind = table('users_bind')->getByTypeAndUid(USER_REGISTER_TYPE_MOBILE, $_W['uid']);
$need_checkcaptcha = true;
if (isset($_GPC['need_checkcaptcha']) && empty($_GPC['need_checkcaptcha'])) {
$need_checkcaptcha = false;
}
if (!$need_checkcaptcha && !empty($user_bind)) {
$check_authcode = safe_gpc_string($_GPC['check_authcode']);
if (empty($check_authcode)) {
return error(-1, '请先验证旧手机!');
}
$old_mobile = authcode($check_authcode);
if ($old_mobile != $user_bind['bind_sign']) {
return error(-1, '请先验证旧手机!');
}
}
$param_validate = $this->paramValidate();
if (is_error($param_validate)) {
return $param_validate;
}
if (empty($user_profile)) {
pdo_insert('users_profile', array('uid' => $_W['uid'], 'mobile' => $mobile));
} else {
pdo_update('users_profile', array('mobile' => $mobile), array('id' => $user_profile['id']));
}
if (empty($user_bind)) {
pdo_insert('users_bind', array('uid' => $_W['uid'], 'bind_sign' => $mobile, 'third_type' => USER_REGISTER_TYPE_MOBILE, 'third_nickname' => $mobile));
} else {
table('users_bind')->where(array('uid' => $_W['uid'], 'third_type' => USER_REGISTER_TYPE_MOBILE))->fill(array('bind_sign' => $mobile, 'third_nickname' => $mobile))->save();
}
return error(0, '绑定成功');
}
public function unbind() {
global $_GPC, $_W;
$mobile = safe_gpc_string($_GPC['mobile']);
$user_profile = table('users_profile')->getByUid($_W['uid']);
$param_validate = $this->paramValidate();
if (is_error($param_validate)) {
return $param_validate;
}
pdo_update('users', array('openid' => ''), array('uid' => $_W['uid']));
pdo_update('users_profile', array('mobile' => ''), array('id' => $user_profile['id']));
pdo_delete('users_bind', array('uid' => $_W['uid'], 'bind_sign' => $mobile, 'third_type' => USER_REGISTER_TYPE_MOBILE));
return error(0, '解除绑定成功');
}
public function isbind() {
global $_W;
$bind_info = table('users_bind')->getByTypeAndUid(USER_REGISTER_TYPE_MOBILE, $_W['uid']);
return !empty($bind_info['bind_sign']);
}
public function paramValidate() {
global $_GPC;
$mobile = trim($_GPC['mobile']);
$image_code = trim($_GPC['imagecode']);
$sms_code = trim($_GPC['smscode']);
$need_checkcaptcha = true;
if (isset($_GPC['need_checkcaptcha']) && empty($_GPC['need_checkcaptcha'])) {
$need_checkcaptcha = false;
}
if (empty($sms_code)) {
return error(-1, '短信验证码不能为空');
}
if ($need_checkcaptcha && empty($image_code)) {
return error(-1, '图形验证码不能为空');
}
if ($need_checkcaptcha) {
$captcha = checkcaptcha($image_code);
if (empty($captcha)) {
return error(-1, '图形验证码错误,请重新获取');
}
}
load()->model('utility');
$verify_info = utility_smscode_verify(0, $mobile, $sms_code);
if (is_error($verify_info)) {
return error(-1, $verify_info['message']);
}
}
}

191
framework/class/oauth2/oauth2client.class.php

@ -0,0 +1,191 @@
<?php
abstract class OAuth2Client {
protected $ak;
protected $sk;
protected $login_type;
protected $user_type = USER_TYPE_COMMON;
protected $stateParam = array(
'state' => '',
'from' => '',
'mode' => '',
);
public function __construct($ak, $sk) {
$this->ak = $ak;
$this->sk = $sk;
}
public function stateParam() {
global $_W;
$this->stateParam['state'] = $_W['token'];
if (!empty($_W['user'])) {
$this->stateParam['mode'] = 'bind';
} else {
$this->stateParam['mode'] = 'login';
}
return base64_encode(http_build_query($this->stateParam, '', '&'));
}
public function getLoginType($login_type) {
$this->login_type = $login_type;
}
public function setUserType($user_type) {
$this->user_type = $user_type;
return $this;
}
public static function supportLoginType() {
return array('system', 'qq', 'wechat', 'mobile');
}
public static function supportThirdLoginType() {
return array('qq', 'wechat');
}
public static function supportBindTypeInfo($type = '') {
$data = array(
'qq' => array(
'type' => 'qq',
'title' => 'QQ',
),
'wechat' => array(
'type' => 'wechat',
'title' => '微信',
),
'mobile' => array(
'type' => 'mobile',
'title' => '手机号',
),
);
if (!empty($type)) {
return $data[$type];
} else {
return $data;
}
}
public static function supportThirdLoginBindType() {
return array('qq', 'wechat');
}
public static function supportThirdMode() {
return array('bind', 'login');
}
public static function supportParams($state) {
$state = urldecode($state);
$param = array();
if (!empty($state)) {
$state = base64_decode($state);
parse_str($state, $third_param);
$modes = self::supportThirdMode();
$types = self::supportThirdLoginType();
if (in_array($third_param['mode'], $modes) && in_array($third_param['from'], $types)) {
return $third_param;
}
}
return $param;
}
public static function create($type, $appid = '', $appsecret = '') {
$types = self::supportLoginType();
if (in_array($type, $types)) {
load()->classs('oauth2/' . $type);
$type_name = ucfirst($type);
$obj = new $type_name($appid, $appsecret);
$obj->getLoginType($type);
return $obj;
}
return null;
}
abstract public function showLoginUrl($calback_url = '');
abstract public function user();
abstract public function login();
abstract public function bind();
abstract public function unbind();
abstract public function isbind();
abstract public function register();
public function user_register($register) {
global $_W;
load()->model('user');
if (is_error($register)) {
return $register;
}
$member = $register['member'];
$profile = $register['profile'];
$member['type'] = $this->user_type;
if (USER_TYPE_CLERK == $member['type']) {
$member['status'] = !empty($_W['setting']['register']['clerk']['verify']) ? 1 : 2;
} else {
$member['status'] = !empty($_W['setting']['register']['verify']) ? 1 : 2;
}
$member['remark'] = '';
$member['groupid'] = intval($_W['setting']['register']['groupid']);
if (empty($member['groupid'])) {
$member['groupid'] = pdo_fetchcolumn('SELECT id FROM ' . tablename('users_group') . ' ORDER BY id ASC LIMIT 1');
$member['groupid'] = intval($member['groupid']);
}
$group = user_group_detail_info($member['groupid']);
$timelimit = intval($group['timelimit']);
if ($timelimit > 0) {
$member['endtime'] = strtotime($timelimit . ' days');
}
$member['starttime'] = TIMESTAMP;
$user_id = user_register($member, $this->stateParam['from']);
if (in_array($member['register_type'], array(USER_REGISTER_TYPE_QQ, USER_REGISTER_TYPE_WECHAT))) {
pdo_update('users', array('username' => $member['username'] . $user_id . rand(100, 999)), array('uid' => $user_id));
}
if ($user_id > 0) {
unset($member['password']);
$member['uid'] = $user_id;
if (!empty($profile)) {
$profile['uid'] = $user_id;
$profile['createtime'] = TIMESTAMP;
pdo_insert('users_profile', $profile);
}
if (in_array($member['register_type'], array(USER_REGISTER_TYPE_QQ, USER_REGISTER_TYPE_WECHAT, USER_REGISTER_TYPE_MOBILE))) {
pdo_insert('users_bind', array('uid' => $user_id, 'bind_sign' => $member['openid'], 'third_type' => $member['register_type'], 'third_nickname' => $member['username']));
}
if (in_array($member['register_type'], array(USER_REGISTER_TYPE_QQ, USER_REGISTER_TYPE_WECHAT))) {
return $user_id;
}
$message = '注册成功';
if (USER_STATUS_CHECK == $member['status']) {
$message .= ',请等待管理员审核!';
} elseif (USER_TYPE_CLERK != $member['type']) {
$message .= ',请重新登录!';
}
return array(
'errno' => 0,
'message' => $message,
'uid' => $user_id,
);
}
return error(-1, '增加用户失败,请稍候重试或联系网站管理员解决!');
}
}

139
framework/class/oauth2/system.class.php

@ -0,0 +1,139 @@
<?php
class System extends OAuth2Client {
private $calback_url;
public function __construct($ak, $sk) {
parent::__construct($ak, $sk);
$this->stateParam['from'] = 'system';
}
public function showLoginUrl($calback_url = '') {
return '';
}
public function user() {
global $_GPC, $_W;
$username = trim($_GPC['username']);
$refused_login_limit = $_W['setting']['copyright']['refused_login_limit'];
pdo_delete('users_failed_login', array('lastupdate <' => TIMESTAMP - $refused_login_limit * 60));
$failed = pdo_get('users_failed_login', array('username' => $username));
if ($failed['count'] >= 5) {
return error('-1', "输入密码错误次数超过5次,请在{$refused_login_limit}分钟后再登录");
}
$need_check_captcha = true;
if ($_W['setting']['copyright']['login_verify_status'] && !empty($_GPC['smscode'])) {
$need_check_captcha = false;
}
if (!empty($_W['setting']['copyright']['verifycode']) && $need_check_captcha) {
$verify = trim($_GPC['verify']);
if (empty($verify)) {
return error('-1', '请输入验证码');
}
$result = checkcaptcha($verify);
if (empty($result)) {
return error('-1', '输入验证码错误');
}
}
if (empty($username)) {
return error('-1', '请输入要登录的用户名');
}
$member['username'] = $username;
$member['password'] = $_GPC['password'];
$member['type'] = $this->user_type;
if (empty($member['password'])) {
return error('-1', '请输入密码');
}
return $member;
}
public function register() {
global $_W, $_GPC;
load()->model('user');
$member = array();
$profile = array();
$member['username'] = trim($_GPC['username']);
$member['owner_uid'] = intval($_GPC['owner_uid']);
$member['password'] = $_GPC['password'];
if (!preg_match(REGULAR_USERNAME, $member['username'])) {
return error(-1, '必须输入用户名,格式为 3-15 位字符,可以包括汉字、字母(不区分大小写)、数字、下划线和句点。');
}
if (user_check(array('username' => $member['username']))) {
return error(-1, '非常抱歉,此用户名已经被注册,你需要更换注册名称!');
}
if (!empty($_W['setting']['register']['code'])) {
if (!checkcaptcha($_GPC['code'])) {
return error(-1, '你输入的验证码不正确, 请重新输入.');
}
}
if (istrlen($member['password']) < 8) {
return error(-1, '必须输入密码,且密码长度不得低于8位。');
}
$extendfields = $this->systemFields();
if (!empty($extendfields)) {
$fields = array_keys($extendfields);
if (in_array('birthyear', $fields)) {
$extendfields[] = array('field' => 'birthmonth', 'title' => '出生生日', 'required' => $extendfields['birthyear']['required']);
$extendfields[] = array('field' => 'birthday', 'title' => '出生生日', 'required' => $extendfields['birthyear']['required']);
$_GPC['birthyear'] = $_GPC['birth']['year'];
$_GPC['birthmonth'] = $_GPC['birth']['month'];
$_GPC['birthday'] = $_GPC['birth']['day'];
}
if (in_array('resideprovince', $fields)) {
$extendfields[] = array('field' => 'residecity', 'title' => '居住地址', 'required' => $extendfields['resideprovince']['required']);
$extendfields[] = array('field' => 'residedist', 'title' => '居住地址', 'required' => $extendfields['resideprovince']['required']);
$_GPC['resideprovince'] = $_GPC['reside']['province'];
$_GPC['residecity'] = $_GPC['reside']['city'];
$_GPC['residedist'] = $_GPC['reside']['district'];
}
foreach ($extendfields as $row) {
if (!empty($row['required']) && empty($_GPC[$row['field']])) {
return error(-1, '“' . $row['title'] . '”此项为必填项,请返回填写完整!');
}
if ($row['field'] == 'mobile') {
$mobile = safe_gpc_int($_GPC['mobile']);
if (!preg_match(REGULAR_MOBILE, $mobile)) {
return error(-1, '手机号格式不正确');
}
$mobile_exists = table('users_profile')->getByMobile($mobile);
if (!empty($mobile_exists)) {
return error(-1, '手机号已存在');
}
}
$profile[$row['field']] = $_GPC[$row['field']];
}
}
$register = array(
'member' => $member,
'profile' => $profile,
);
return parent::user_register($register);
}
public function systemFields() {
return table('core_profile_fields')->getAvailableAndShowableFields();
}
public function login() {
return $this->user();
}
public function bind() {
return true;
}
public function unbind() {
return true;
}
public function isbind() {
return true;
}
}

490
framework/class/query.class.php

@ -0,0 +1,490 @@
<?php
defined('IN_IA') or exit('Access Denied');
class Query {
private $clauses;
private $statements = array();
private $parameters = array();
private $mainTable = '';
private $currentTableAlias = '';
private $error = array();
private $lastsql = '';
private $lastparams = '';
private $values;
public $fixTable;
public function __construct() {
$this->initClauses();
}
private function initClauses() {
$this->clauses = array(
'SELECT' => array(),
'DELETE' => '',
'UPDATE' => '',
'INSERT INTO' => '',
'FROM' => '',
'LEFTJOIN' => array(),
'INNERJOIN' => array(),
'ON' => array(),
'SET' => '',
'WHERE' => array(),
'WHEREOR' => array(),
'GROUPBY' => array(),
'HAVING' => array(),
'ORDERBY' => array(),
'LIMIT' => '',
'PAGE' => '',
);
foreach ($this->clauses as $clause => $value) {
$this->statements[$clause] = $value;
}
$this->parameters = array();
if (!empty($this->fixTable)) {
$this->from($this->fixTable);
}
}
private function resetClause($clause = '') {
if (empty($clause)) {
$this->initClauses();
return $this;
}
$this->statements[$clause] = null;
$this->parameters = array();
$this->values = array();
if (isset($this->clauses[$clause]) && is_array($this->clauses[$clause])) {
$this->statements[$clause] = array();
}
return $this;
}
private function addStatement($clause, $statement, $parameters = array()) {
if (null === $statement) {
return $this->resetClause($clause);
}
if (isset($this->statements[$clause]) && is_array($this->statements[$clause])) {
if (is_array($statement)) {
$this->statements[$clause] = array_merge($this->statements[$clause], $statement);
} else {
if (empty($parameters) && is_array($parameters)) {
$this->statements[$clause][] = $statement;
} else {
$this->statements[$clause][$statement] = empty($parameters) && is_array($parameters) ? '' : $parameters;
}
}
} else {
$this->statements[$clause] = $statement;
}
return $this;
}
public function __call($clause, $statement = array()) {
$origin_clause = $clause;
$clause = strtoupper($clause);
if ('HAVING' == $clause) {
array_unshift($statement, $clause);
return call_user_func_array(array($this, 'condition'), $statement);
}
if ('LEFTJOIN' == $clause || 'INNERJOIN' == $clause) {
array_unshift($statement, $clause);
return call_user_func_array(array($this, 'join'), $statement);
}
return $this->addStatement($clause, $statement);
}
public function where($condition, $parameters = array(), $operator = 'AND') {
if (!is_array($condition) && !($condition instanceof Closure)) {
$condition = array($condition => $parameters);
}
$this->addStatement('WHERE', array(array($operator, $condition)));
return $this;
}
public function whereor($condition, $parameters = array()) {
return $this->where($condition, $parameters, 'OR');
}
public function from($tablename, $alias = '') {
if (empty($tablename)) {
return $this;
}
$this->mainTable = $tablename;
$this->currentTableAlias = $alias;
$this->statements['FROM'] = $this->mainTable;
return $this;
}
public function join($clause, $tablename, $alias = '') {
if (empty($tablename)) {
return $this;
}
$this->joinTable = $tablename;
return $this->addStatement($clause, $tablename . ' ' . $alias);
}
public function on($condition, $parameters = array()) {
if (null === $condition) {
return $this->resetClause('ON');
}
if (empty($condition)) {
return $this;
}
if (is_array($condition)) {
foreach ($condition as $key => $val) {
$this->on($key, $val);
}
return $this;
}
if (empty($this->statements['ON'][$this->joinTable])) {
$this->statements['ON'][$this->joinTable] = array();
}
$this->statements['ON'][$this->joinTable][$condition] = $parameters;
return $this;
}
public function select($field) {
if (is_string($field)) {
$field = func_get_args();
}
if (empty($field)) {
return $this;
}
if (1 == count($this->statements['SELECT'])) {
$this->resetClause('SELECT');
}
return $this->addStatement('SELECT', $field);
}
private function condition($operator, $condition, $parameters = array()) {
if (null === $condition) {
return $this->resetClause('WHERE');
}
if (empty($condition)) {
return $this;
}
if (is_array($condition)) {
foreach ($condition as $key => $val) {
$this->condition($operator, $key, $val);
}
return $this;
}
return $this->addStatement($operator, $condition, $parameters);
}
public function orderby($field, $direction = 'ASC') {
if (is_array($field)) {
foreach ($field as $column => $order) {
$this->orderby($column, $order);
}
return $this;
}
if (strtoupper($field) == 'RAND()') {
return $this->addStatement('ORDERBY', $field);
}
$direction = strtoupper($direction);
$direction = in_array($direction, array('ASC', 'DESC')) ? $direction : 'ASC';
return $this->addStatement('ORDERBY', $field . ' ' . $direction);
}
public function fill($field, $value = '') {
if (is_array($field)) {
foreach ($field as $column => $val) {
$this->fill($column, $val);
}
return $this;
}
$this->values[$field] = $value;
return $this;
}
public function hasWhere() {
return count($this->statements['WHERE']) > 0;
}
public function get() {
if (empty($this->statements['SELECT'])) {
$this->addStatement('SELECT', '*');
}
$this->lastsql = $this->buildQuery();
$this->lastparams = $this->parameters;
$result = pdo_fetch($this->lastsql, $this->parameters);
$this->resetClause();
return $result;
}
public function getcolumn($field = '') {
if (!empty($field)) {
$this->select($field);
}
if (empty($this->statements['SELECT'])) {
$this->addStatement('SELECT', '*');
}
$this->lastsql = $this->buildQuery();
$this->lastparams = $this->parameters;
$result = pdo_fetchcolumn($this->lastsql, $this->parameters);
$this->resetClause();
return $result;
}
public function getall($keyfield = '') {
if (empty($this->statements['SELECT'])) {
$this->addStatement('SELECT', '*');
}
$this->lastsql = $this->buildQuery();
$this->lastparams = $this->parameters;
$result = pdo_fetchall($this->lastsql, $this->parameters, $keyfield);
$this->resetClause();
return $result;
}
public function getLastQueryTotal() {
$lastquery = $this->getLastQuery();
$countsql = str_replace(substr($lastquery[0], 0, strpos($lastquery[0], 'FROM')), 'SELECT COUNT(*) ', $lastquery[0]);
if (false !== strpos($countsql, 'LIMIT')) {
$countsql = substr($countsql, 0, strpos($countsql, 'LIMIT'));
}
if (strexists(strtoupper($countsql), 'GROUP BY')) {
$result = pdo_fetchall($countsql, $this->lastparams);
$result = count($result);
} else {
$result = pdo_fetchcolumn($countsql, $this->lastparams);
}
return $result;
}
public function count() {
$where = array();
if (!empty($this->statements['WHERE'])) {
foreach ($this->statements['WHERE'] as $row) {
$where = array_merge($where, $row[1]);
}
}
return pdo_count($this->statements['FROM'], $where);
}
public function exists() {
$where = array();
if (!empty($this->statements['WHERE'])) {
foreach ($this->statements['WHERE'] as $row) {
$where = array_merge($where, $row[1]);
}
}
return pdo_exists($this->statements['FROM'], $where);
}
public function delete() {
$where = $this->buildWhereArray();
$result = pdo_delete($this->statements['FROM'], $where);
$this->resetClause();
return $result;
}
public function insert($replace = false) {
$result = pdo_insert($this->statements['FROM'], $this->values, $replace);
$this->resetClause();
return $result;
}
public function update() {
$where = $this->buildWhereArray();
if (empty($where)) {
return error(-1, '未指定更新条件');
}
$result = pdo_update($this->statements['FROM'], $this->values, $where);
$this->resetClause();
return $result;
}
private function buildQuery() {
$query = '';
foreach ($this->clauses as $clause => $separator) {
if (!empty($this->statements[$clause])) {
if (method_exists($this, 'buildQuery' . $clause)) {
$query .= call_user_func(array($this, 'buildQuery' . $clause), $this->statements[$clause]);
} elseif (is_string($separator)) {
$query .= " $clause " . implode($separator, $this->statements[$clause]);
} elseif (null === $separator) {
$query .= " $clause " . $this->statements[$clause];
}
}
}
return trim($query);
}
private function buildQueryWhere() {
$closure = array();
$sql = '';
foreach ($this->statements['WHERE'] as $i => $wheregroup) {
$where = array();
if (!empty($wheregroup[1]) && $wheregroup[1] instanceof Closure) {
$closure[] = $wheregroup;
} else {
$where = \SqlPaser::parseParameter($wheregroup[1], 'AND', $this->currentTableAlias);
$this->parameters = array_merge($this->parameters, $where['params']);
$sql .= ' ' . $wheregroup[0] . ' ' . $where['fields'];
}
unset($this->statements['WHERE'][$i]);
}
foreach ($closure as $callback) {
$callback[1]($this);
$subsql = '';
$where = array();
foreach ($this->statements['WHERE'] as $i => $wheregroup) {
$where = \SqlPaser::parseParameter($wheregroup[1], 'AND', $this->currentTableAlias);
$this->parameters = array_merge($this->parameters, $where['params']);
$subsql .= ' ' . $wheregroup[0] . ' ' . $where['fields'];
unset($this->statements['WHERE'][$i]);
}
$subsql = ltrim(ltrim($subsql, ' AND '), ' OR ');
$sql .= " {$callback[0]} ( $subsql )";
}
return empty($where['fields']) ? '' : ' WHERE ' . ltrim(ltrim($sql, ' AND '), ' OR ');
}
private function buildQueryWhereor() {
$where = \SqlPaser::parseParameter($this->statements['WHEREOR'], 'OR', $this->currentTableAlias);
$this->parameters = array_merge($this->parameters, $where['params']);
if (empty($where['fields'])) {
return '';
}
if (empty($this->statements['WHERE'])) {
return " WHERE {$where['fields']} ";
} else {
return " OR {$where['fields']} ";
}
}
private function buildQueryHaving() {
$where = \SqlPaser::parseParameter($this->statements['HAVING'], 'AND', $this->currentTableAlias);
$this->parameters = array_merge($this->parameters, $where['params']);
return empty($where['fields']) ? '' : " HAVING {$where['fields']} ";
}
private function buildQueryFrom() {
return ' FROM ' . tablename($this->statements['FROM']) . ' ' . $this->currentTableAlias;
}
private function buildQueryLeftjoin() {
return $this->buildQueryJoin('LEFTJOIN');
}
private function buildQueryInnerjoin() {
return $this->buildQueryJoin('INNERJOIN');
}
private function buildQueryJoin($clause) {
if (empty($this->statements[$clause])) {
return '';
}
$clause_operator = array(
'LEFTJOIN' => ' LEFT JOIN ',
'INNERJOIN' => ' INNER JOIN ',
);
$sql = '';
foreach ($this->statements[$clause] as $tablename) {
list($tablename, $alias) = explode(' ', $tablename);
$sql .= $clause_operator[$clause] . tablename($tablename) . ' ' . $alias;
if (!empty($this->statements['ON'][$tablename])) {
$sql .= ' ON ';
$split = '';
foreach ($this->statements['ON'][$tablename] as $field => $condition) {
$operator = '';
if (strexists($field, ' ')) {
list($field, $operator) = explode(' ', $field);
}
$operator = $operator ? $operator : '=';
$field = '`' . str_replace('.', '`.`', $field) . '`';
if (strexists($condition, '.')) {
$condition = '`' . str_replace('.', '`.`', $condition) . '`';
}
$sql .= " $split $field $operator $condition ";
$split = ' AND ';
}
}
}
return $sql;
}
private function buildQuerySelect() {
return \SqlPaser::parseSelect($this->statements['SELECT'], $this->currentTableAlias);
}
private function buildQueryLimit() {
return \SqlPaser::parseLimit($this->statements['LIMIT'], false);
}
private function buildQueryPage() {
return \SqlPaser::parseLimit($this->statements['PAGE'], true);
}
private function buildQueryOrderby() {
return \SqlPaser::parseOrderby($this->statements['ORDERBY'], $this->currentTableAlias);
}
private function buildQueryGroupby() {
return \SqlPaser::parseGroupby($this->statements['GROUPBY'], $this->currentTableAlias);
}
private function buildWhereArray() {
$where = array();
if (!empty($this->statements['WHERE'])) {
foreach ($this->statements['WHERE'] as $row) {
$where = array_merge($where, $row[1]);
}
}
return $where;
}
public function getLastQuery() {
return array($this->lastsql, $this->lastparams);
}
}

115
framework/class/slave.db.class.php

@ -0,0 +1,115 @@
<?php
defined('IN_IA') or exit('Access Denied');
load()->classs('db');
class SlaveDb extends DB {
private $weight;
private $slavequery = 0;
private $slaveid = null;
public function prepare($sql) {
$this->init_connect($sql);
return parent::prepare($sql);
}
public function query($sql, $params = array()) {
$starttime = microtime();
if (!empty($params)) {
return parent::query($sql, $params);
}
$this->init_connect($sql);
$result = $this->pdo->exec($sql);
if (PDO_DEBUG) {
$info = array();
$info['sql'] = $sql;
$info['error'] = $this->pdo->errorInfo();
$this->debug(false, $info);
}
return $result;
}
public function slave_connect() {
$this->slave_choose();
if ($this->slaveid) {
if (!isset($this->link[$this->slaveid])) {
$this->connect($this->slaveid);
}
++$this->slavequery ;
$this->pdo = $this->link[$this->slaveid];
}
return true;
}
protected function slave_choose() {
if (!isset($this->weight)) {
foreach ($this->cfg['slave'] as $key => $value) {
$this->weight .= str_repeat($key, 1 + intval($value['weight']));
}
}
$sid = $this->weight[mt_rand(0, strlen($this->weight) - 1)];
$this->slaveid = 'slave_' . $sid;
if (!isset($this->cfg[$this->slaveid])) {
$this->cfg[$this->slaveid] = $this->cfg['slave'][$sid];
}
}
public function init_connect($sql) {
if (!(true == $this->cfg['slave_status'] && !empty($this->cfg['slave']))) {
$this->master_connect();
} else {
$sql = trim($sql);
$sql_lower = strtolower($sql);
$slave_except = false;
if (!strexists($sql_lower, 'where ')) {
$tablename = substr($sql_lower, strpos($sql_lower, 'from ') + 5);
} else {
$tablename = substr($sql_lower, strpos($sql_lower, 'from ') + 5, strpos($sql_lower, ' where') - strpos($sql_lower, 'from ') - 5);
}
$tablename = trim($tablename, '`');
$tablename = str_replace($this->tablepre, '', $tablename);
if (!empty($this->cfg['common']['slave_except_table']) && in_array(strtolower($tablename), $this->cfg['common']['slave_except_table'])) {
$slave_except = true;
}
if (!(!$slave_except && 'SELECT' === strtoupper(substr($sql, 0, 6)) && $this->slave_connect())) {
$this->master_connect();
}
}
return true;
}
public function master_connect() {
if (!isset($this->link['master'])) {
$this->connect('master');
}
$this->pdo = $this->link['master'];
}
public function insertid() {
$this->master_connect();
return parent::insertid();
}
public function begin() {
$this->master_connect();
return parent::begin();
}
public function commit() {
$this->master_connect();
return parent::commit();
}
public function rollback() {
$this->master_connect();
return parent::rollback();
}
}

457
framework/class/table.class.php

@ -0,0 +1,457 @@
<?php
defined('IN_IA') or exit('Access Denied');
abstract class We7Table {
const ONE_TO_ONE = 'ONE_TO_ONE';
const ONE_TO_MANY = 'ONE_TO_MANY';
const BELONGS_TO = 'BELONGS_TO';
const MANY_TO_MANY = 'MANY_TO_MANY';
protected $tableName = '';
protected $primaryKey = 'id';
protected $field = array('group_id');
protected $rule = array();
protected $default = array();
protected $cast = array();
protected $query;
private $attribute = array();
private $relationDefine = array();
public function __construct() {
load()->classs('validator');
$this->query = load()->object('Query');
$this->query->fixTable = $this->tableName;
$this->query->from($this->tableName);
}
public function searchWithPage($pageindex, $pagesize) {
if (!empty($pageindex) && !empty($pagesize)) {
$this->query->page($pageindex, $pagesize);
}
return $this;
}
public function getLastQueryTotal() {
return $this->query->getLastQueryTotal();
}
public function count() {
return $this->query->count();
}
public function fill($field, $value = '') {
if (is_array($field)) {
foreach ($field as $column => $val) {
$this->fillField($column, $val);
}
return $this;
}
$this->fillField($field, $value);
return $this;
}
private function fillField($column, $val) {
if (in_array($column, $this->field)) {
$val = $this->getColumnVal($column, $val);
$this->attribute[$column] = $val;
$this->query->fill($column, $val);
}
}
private function getColumnVal($column, $val) {
$method = 'set' . $this->studly($column) . 'Field';
if (method_exists($this, $method)) {
return $this->{$method}($val);
}
return $this->cast($column, $val);
}
private function cast($column, $val) {
if (isset($this->cast[$column])) {
switch ($this->cast[$column]) {
case 'int': return intval($val); break;
case 'string': return strval($val); break;
case 'float': return floatval($val); break;
case 'double': return doubleval($val); break;
case 'bool': return boolval($val); break;
}
}
return $val;
}
private function appendDefault() {
foreach ($this->default as $field => $value) {
if (!isset($this->attribute[$field])) {
if ('custom' === $value) {
$method = 'default' . $this->studly($field);
if (!method_exists($this, $method)) {
trigger_error($method . '方法未找到');
}
$value = call_user_func(array($this, $method));
}
$this->fillField($field, $value);
}
}
}
protected function valid($data) {
if (count($this->rule) <= 0) {
return error(0);
}
$validator = Validator::create($data, $this->rule);
$result = $validator->valid();
return $result;
}
public function select($fields = '*') {
return $this->query->select($fields);
}
public function limit($limit) {
return $this->query->limit($limit);
}
public function get() {
$data = $this->query->get();
if (!$data || empty($data)) {
return $data;
}
$this->loadRelation($data);
return $data;
}
public function getall($keyfield = '') {
$data = $this->query->getall($keyfield);
if (!$data || empty($data)) {
return $data;
}
$this->loadRelation($data, true);
return $data;
}
public function getQuery() {
return $this->query;
}
public function getTableName() {
return $this->tableName;
}
public function with($relation) {
$relations = is_string($relation) ? func_get_args() : $relation;
foreach ($relations as $relation => $val) {
if (is_numeric($relation)) {
$relation = $val;
}
if (!is_callable($val)) {
$val = null;
}
$this->relationDefine[$relation] = $val;
}
return $this;
}
private function loadRelation(array &$data, $muti = false) {
foreach ($this->relationDefine as $relation => $closure) {
$this->doload($relation, $data, $muti, $closure); }
}
private function doload($relation, &$data, $muti = false, callable $closure = null) {
if (method_exists($this, $relation)) {
$relation_param = call_user_func(array($this, $relation));
list($type, $table, $foreign_key, $owner_key) = $relation_param;
if (self::MANY_TO_MANY == $type) {
$this->doManyToMany($relation, $relation_param, $data, $muti);
return;
}
$single = $this->isGetSingle($type);
$foreign_vals = $this->getForeignVal($data, $owner_key, $muti);
$second_table_data = $this->getSecondTableData($table, $foreign_key, $foreign_vals, $single, $closure);
if (!$muti) {
$data[$relation] = $second_table_data;
return;
}
if ($single) {
$second_table_data = array($second_table_data);
}
$second_table_data = $this->groupBy($foreign_key, $second_table_data);
foreach ($data as &$item) {
$relation_val = isset($second_table_data[$item[$owner_key]]) ? $second_table_data[$item[$owner_key]] : array();
if ($single) {
$relation_val = count($relation_val) > 0 ? current($relation_val) : array();
}
$item[$relation] = $relation_val;
}
}
}
private function doManyToMany($relation, $relation_param, &$data, $muti = false) {
list($type, $table, $foreign_key, $owner_key, $center_table, $center_foreign_key, $center_owner_key)
= $relation_param;
$foreign_vals = $this->getForeignVal($data, $owner_key, $muti);
$three_table = table($table);
$nativeQuery = $three_table->getQuery();
$nativeQuery->from($three_table->getTableName(), 'three')
->innerjoin($center_table, 'center')
->on(array('center.' . $center_foreign_key => 'three.' . $foreign_key))
->select('center.*')
->where('center.' . $center_owner_key, $foreign_vals);
$three_table_data = $three_table->getall(); if (!$muti) {
$data[$relation] = $three_table_data;
return;
}
$three_table_data = $this->groupBy($center_owner_key, $three_table_data);
foreach ($data as &$item) {
$three_val = isset($three_table_data[$item[$owner_key]]) ? $three_table_data[$item[$owner_key]] : array();
$item[$relation] = $three_val;
}
}
private function isGetSingle($type) {
return in_array($type, array(self::ONE_TO_ONE, self::BELONGS_TO)) ? true : false;
}
private function getForeignVal($data, $owner_key, $muti = false) {
if (!$muti) {
return $data[$owner_key];
}
return array_map(function ($item) use ($owner_key) {
return $item[$owner_key];
}, $data);
}
private function getSecondTableData($table, $foreign_key, $foreign_vals, $single = false, $closure = null) {
$table_instance = table($table)->where($foreign_key, $foreign_vals);
if ($closure) {
call_user_func($closure, $table_instance->getQuery()); }
if ($single) {
return $table_instance->get();
}
return $table_instance->getall();
}
private function groupBy($key, $array) {
$result = array();
foreach ($array as $item) {
$val = $item[$key];
if (isset($result[$val])) {
$result[$val][] = $item;
} else {
$result[$val] = array($item);
}
}
return $result;
}
protected function hasOne($table, $foreign_key, $owner_key = false) {
return $this->relationArray(self::ONE_TO_ONE, $table, $foreign_key, $owner_key);
}
protected function hasMany($table, $foreign_key, $owner_key = false) {
return $this->relationArray(self::ONE_TO_MANY, $table, $foreign_key, $owner_key);
}
protected function belongsTo($table, $foreign_key, $owner_key = false) {
return $this->relationArray(self::BELONGS_TO, $table, $foreign_key, $owner_key);
}
protected function belongsMany($table, $foreign_key, $owner_key, $center_table, $center_foreign_key = false,
$center_owner_key = false) {
if (!$owner_key) {
$owner_key = $this->primaryKey;
}
if (!$center_foreign_key) {
$center_foreign_key = $foreign_key;
}
if (!$center_owner_key) {
$center_owner_key = $owner_key;
}
return array(self::MANY_TO_MANY, $table, $foreign_key, $owner_key, $center_table, $center_foreign_key, $center_owner_key);
}
private function relationArray($type, $table, $foreign_key, $owner_key) {
if (!$owner_key) {
$owner_key = $this->primaryKey;
}
if (!in_array($type, array(self::ONE_TO_ONE, self::ONE_TO_MANY, self::BELONGS_TO), true)) {
trigger_error('不支持的关联类型');
}
return array($type, $table, $foreign_key, $owner_key);
}
public function getById($id, $uniacid = 0) {
$this->query->from($this->tableName)->where($this->primaryKey, $id);
if (!empty($uniacid)) {
$this->where('uniacid', $uniacid);
}
if (is_array($id)) {
return $this->getall();
}
return $this->get();
}
public function getcolumn($field = '') {
$data = $this->query->getcolumn($field);
return $data;
}
public function where($condition, $parameters = array(), $operator = 'AND') {
$this->query->where($condition, $parameters, $operator);
return $this;
}
public function whereor($condition, $parameters = array()) {
return $this->where($condition, $parameters, 'OR');
}
public function orderby($field, $direction = 'ASC') {
return $this->query->orderby($field, $direction);
}
public function save($replace = false) {
if ($this->query->hasWhere()) {
$result = $this->valid($this->attribute);
if (is_error($result)) {
return $result;
}
return $this->query->update();
}
$this->appendDefault();
$result = $this->valid($this->attribute);
if (is_error($result)) {
return $result;
}
return $this->query->insert($replace);
}
public function delete() {
if ($this->query->hasWhere()) {
return $this->query->delete();
}
return false;
}
private function doWhere($field, $params, $operator = 'AND') {
if (0 == $params) {
return $this;
}
$value = $params[0];
if (count($params) > 1) {
$field = $field . ' ' . $params[1];
}
$this->query->where($field, $value, $operator);
return $this;
}
private function snake($value) {
$delimiter = '_';
if (!ctype_lower($value)) {
$value = preg_replace('/\s+/u', '', ucwords($value));
$value = strtolower(preg_replace('/(.)(?=[A-Z])/u', '$1' . $delimiter, $value));
}
return $value;
}
private function studly($value) {
$value = ucwords(str_replace(array('-', '_'), ' ', $value));
return str_replace(' ', '', $value);
}
public function __call($method, $params) {
$actions = array(
'searchWith',
'whereor',
'where',
'fill',
);
foreach ($actions as $action) {
$fields = explode($action, $method);
if (count($fields) > 1 && empty($fields[0]) && !empty($fields[1])) {
$field = $this->snake($fields[1]);
switch ($action) {
case 'whereor':
return $this->doWhere($field, $params, 'OR');
case 'fill':
$this->fill($field, $params[0]);
return $this;
default:
return $this->doWhere($field, $params);
}
}
}
return $this;
}
}

252
framework/class/uploadedfile.class.php

@ -0,0 +1,252 @@
<?php
class UploadedFile extends SplFileInfo {
private static $errors = array(
UPLOAD_ERR_OK,
UPLOAD_ERR_INI_SIZE,
UPLOAD_ERR_FORM_SIZE,
UPLOAD_ERR_PARTIAL,
UPLOAD_ERR_NO_FILE,
UPLOAD_ERR_NO_TMP_DIR,
UPLOAD_ERR_CANT_WRITE,
UPLOAD_ERR_EXTENSION,
);
private $clientFilename;
private $clientMediaType;
private $error;
private $file;
private $moved = false;
private $size;
public function __construct(
$streamOrFile,
$size,
$errorStatus,
$clientFilename = null,
$clientMediaType = null
) {
$this->setError($errorStatus);
$this->setSize($size);
$this->setClientFilename($clientFilename);
$this->setClientMediaType($clientMediaType);
parent::__construct($streamOrFile);
if ($this->isOk()) {
$this->setStreamOrFile($streamOrFile);
}
}
private function setStreamOrFile($streamOrFile) {
if (is_string($streamOrFile)) {
$this->file = $streamOrFile;
} else {
throw new InvalidArgumentException(
'Invalid stream or file provided for UploadedFile'
);
}
}
private function setError($error) {
if (false === is_int($error)) {
throw new InvalidArgumentException(
'Upload file error status must be an integer'
);
}
if (false === in_array($error, self::$errors)) {
throw new InvalidArgumentException(
'Invalid error status for UploadedFile'
);
}
$this->error = $error;
}
private function setSize($size) {
if (false === is_int($size)) {
throw new InvalidArgumentException(
'Upload file size must be an integer'
);
}
$this->size = $size;
}
private function isStringOrNull($param) {
return in_array(gettype($param), array('string', 'NULL'));
}
private function isStringNotEmpty($param) {
return is_string($param) && false === empty($param);
}
private function setClientFilename($clientFilename) {
if (false === $this->isStringOrNull($clientFilename)) {
throw new InvalidArgumentException(
'Upload file client filename must be a string or null'
);
}
$this->clientFilename = $clientFilename;
}
private function setClientMediaType($clientMediaType) {
if (false === $this->isStringOrNull($clientMediaType)) {
throw new InvalidArgumentException(
'Upload file client media type must be a string or null'
);
}
$this->clientMediaType = $clientMediaType;
}
public function isOk() {
return UPLOAD_ERR_OK === $this->error;
}
public function isMoved() {
return $this->moved;
}
private function validateActive() {
if (false === $this->isOk()) {
throw new RuntimeException('Cannot retrieve stream due to upload error');
}
if ($this->isMoved()) {
throw new RuntimeException('Cannot retrieve stream after it has already been moved');
}
}
public function moveTo($targetPath) {
$this->validateActive();
if (false === $this->isStringNotEmpty($targetPath)) {
throw new InvalidArgumentException(
'Invalid path provided for move operation; must be a non-empty string'
);
}
if ($this->file) {
$this->moved = 'cli' == php_sapi_name()
? rename($this->file, $targetPath)
: move_uploaded_file($this->file, $targetPath);
}
if (false === $this->moved) {
throw new RuntimeException(
sprintf('Uploaded file could not be moved to %s', $targetPath)
);
}
}
public function getSize() {
return $this->size;
}
public function getError() {
return $this->error;
}
public function getClientFilename() {
return $this->clientFilename;
}
public function getClientMediaType() {
return $this->clientMediaType;
}
public function isImage() {
return $this->isOk() && in_array($this->clientMediaType, array());
}
public function clientExtension() {
return pathinfo($this->getClientFilename(), PATHINFO_EXTENSION);
}
public function allowExt($ext) {
return $this->clientExtension() === $ext;
}
public function getContent() {
return file_get_contents($this->file);
}
public static function createFromGlobal() {
$files = array();
foreach ($_FILES as $key => $file) {
$createFiles = static::create($file);
$files[$key] = $createFiles;
}
return $files;
}
private static function create($file) {
if (is_array($file['tmp_name'])) {
return static::createArrayFile($file);
}
return static::createUploadedFile($file);
}
public static function createArrayFile($files) {
$data = array();
foreach (array_keys($files['tmp_name']) as $key) {
$file = array(
'tmp_name' => $files['tmp_name'][$key],
'size' => $files['size'][$key],
'error' => $files['error'][$key],
'name' => $files['name'][$key],
'type' => $files['type'][$key],
);
$data[$key] = self::createUploadedFile($file);
}
return $data;
}
private static function createUploadedFile($value) {
$upfile = new static(
$value['tmp_name'],
$value['size'],
$value['error'],
$value['name'],
$value['type']
);
return $upfile;
}
}

565
framework/class/validator.class.php

@ -0,0 +1,565 @@
<?php
class Validator
{
const IMG = 'jpg, jepg, png, gif, bmp';
const IMG_MIMETYPE = 'image/jpeg,image/jpeg,image/png,image/gif,image/bmp';
private $defaults = array(
'required' => ':attribute 必须填写',
'integer' => ':attribute必须是整数',
'int' => ':attribute必须是整数',
'numeric' => ':attribute必须是数字',
'string' => ':attribute必须是字符串',
'json' => ':attribute 必须是json',
'array' => ':attribute必须是数组',
'min' => ':attribute不能小于%s',
'max' => ':attribute不能大于%s',
'between' => ':attribute 必须在 %s %s 范围内',
'size' => ':attribute 大小必须是 %s',
'url' => ':attribute不是有效的url', 'email' => ':attribute不是有效的邮箱',
'mobile' => ':attribute不是有效的手机号',
'file' => ':attribute必须是一个文件',
'image' => ':attribute必须是一个图片',
'ip' => ':attribute不是有效的ip',
'in' => ':attribute 必须在 %s 内',
'notin' => ':attribute 不在 %s 内',
'date' => ':attribute 必须是有效的日期',
'after' => ':attribute 日期不能小于 %s',
'before' => ':attribute 日期不能大于 %s',
'regex' => ':attribute 不是有效的数据', 'same' => ':attribute 和 %s 不一致', 'bool' => ':attribute 必须是bool值',
'path' => ':attribute 不是有效的路径',
);
private $custom = array();
private $rules = array();
private $messages = array();
private $data = array();
private $errors = array();
public function __construct($data, $rules = array(), $messages = array())
{
$this->data = $data;
$this->rules = $this->parseRule($rules);
$this->messages = $messages;
}
public static function create($data, $rules, array $messages = array())
{
return new self($data, $rules, $messages);
}
public function addRule($name, callable $callable)
{
if (!$name) {
throw new InvalidArgumentException('无效的参数');
}
if (!is_callable($callable)) {
throw new InvalidArgumentException('无效的callable 对象');
}
$this->custom[$name] = $callable;
}
public function isError()
{
return 0 !== count($this->errors);
}
public function error()
{
return $this->errors;
}
public function message()
{
$init = array();
$errmsg = array_reduce($this->error(), function ($result, $value) {
return array_merge($result, array_values($value));
}, $init);
return implode(',', array_values($errmsg));
}
public function getData()
{
return $this->data;
}
protected function parseRule(array $rules)
{
$result = array();
if (0 == count($rules)) {
throw new InvalidArgumentException('无效的rules');
}
foreach ($rules as $key => $rule) {
$result[$key] = $this->parseSingleRule($rule);
}
return $result;
}
protected function parseSingleRule($value)
{
if (is_string($value)) {
$rules = explode('|', $value);
$result = array();
foreach ($rules as $dataKey => $rule) {
$kv = explode(':', $rule);
$params = array();
if (count($kv) > 1) {
$params = explode(',', $kv[1]);
}
$result[] = array('name' => $kv[0], 'params' => $params);
}
return $result;
}
if (is_array($value)) {
$value = array_map(function ($item) {
if (is_string($item)) {
$name_params = explode(':', $item);
$params = array();
if (count($name_params) > 1) {
$params = explode(',', $name_params[1]);
}
return array('name' => $name_params[0], 'params' => $params);
}
if (!is_array($item)) {
throw new InvalidArgumentException('无效的rule参数');
}
$newitem = $item;
if (!isset($item['name'])) {
$newitem = array();
$newitem['name'] = $newitem[0];
$newitem['params'] = count($item) > 1 ? $item[1] : array();
}
return $newitem;
}, $value);
return $value;
}
throw new InvalidArgumentException('无效的rule配置项');
}
private function getRules($key)
{
return isset($this->rules[$key]) ? $this->rules[$key] : array();
}
public function valid()
{
$this->errors = array();
foreach ($this->data as $key => $value) {
$rules = $this->getRules($key);
foreach ($rules as $rule) {
$this->doValid($key, $value, $rule);
}
}
return $this->isError() ? error(1, $this->message()) : error(0);
}
private function doSingle($callback, $dataKey, $value, $rule)
{
$valid = call_user_func($callback, $dataKey, $value, $rule['params']);
if (!$valid) {
$this->errors[$dataKey][$rule['name']] = $this->getMessage($dataKey, $rule);
return false;
}
return true;
}
private function doCustom($callback, $dataKey, $value, $rule)
{
$valid = call_user_func($callback, $dataKey, $value, $rule['params'], $this);
if (!$valid) {
$this->errors[$dataKey][$rule['name']] = $this->getMessage($dataKey, $rule);
return false;
}
return true;
}
private function doValid($dataKey, $value, $rule)
{
$ruleName = $rule['name'];
if (isset($this->defaults[$ruleName])) {
$callback = array($this, 'valid' . ucfirst($ruleName));
return $this->doSingle($callback, $dataKey, $value, $rule);
}
if (isset($this->custom[$ruleName])) {
$callback = $this->custom[$ruleName];
return $this->doCustom($callback, $dataKey, $value, $rule, $this);
}
throw new InvalidArgumentException('valid' . $rule['name'] . ' 方法未定义');
}
private function getValue($key)
{
return isset($this->data[$key]) ? $this->data[$key] : null;
}
protected function getMessage($dataKey, $rule)
{
$message = $this->getErrorMessage($dataKey, $rule['name']);
if ($message) {
$message = str_replace(':attribute', $dataKey, $message);
$message = vsprintf($message, $rule['params']);
}
return $message;
}
protected function getErrorMessage($dataKey, $ruleName)
{
$dr = $dataKey . '.' . $ruleName;
if ($this->messages[$dr]) {
return $this->messages[$dr];
}
if (isset($this->messages[$dataKey])) {
return $this->messages[$dataKey];
}
return isset($this->defaults[$ruleName]) ? $this->defaults[$ruleName] : '错误';
}
public function validRequired($key, $value, $params)
{
if (is_null($value)) {
return false;
}
if (is_array($value)) {
return 0 != count($value);
}
if (is_string($value)) {
return '' !== $value;
}
return true;
}
public function validInteger($key, $value, $params)
{
return false !== filter_var($value, FILTER_VALIDATE_INT);
}
public function validInt($key, $value, $params)
{
return $this->validInteger($key, $value, $params);
}
public function validNumeric($key, $value, $params)
{
return is_numeric($value);
}
public function validString($key, $value, $params)
{
return is_string($value);
}
public function validJson($key, $value, $params)
{
if (!is_scalar($value) && !method_exists($value, '__toString')) {
return false;
}
json_decode($value);
return JSON_ERROR_NONE === json_last_error();
}
public function validArray($key, $value, $params)
{
return is_array($value);
}
public function validFile($key, $value, $params)
{
return is_file($value);
}
public function validImage($key, $value, $params)
{
return $this->isImage($value);
}
public function validEmail($key, $value, $params)
{
return filter_var($value, FILTER_VALIDATE_EMAIL);
}
public function validMobile($key, $value, $params)
{
return $this->validRegex($key, $value, array('/^1[34578]\d{9}$/'));
}
public function validRegex($key, $value, $params)
{
$this->checkParams(1, $params, 'regex');
return preg_match($params[0], $value);
}
public function validIp($key, $value, $params)
{
if (!is_null($value)) {
return filter_var($value, FILTER_VALIDATE_IP);
}
return false;
}
public function validSize($key, $value, $params)
{
$this->checkParams(1, $params, 'size');
return $this->getSize($key, $value) == $params[0];
}
public function validMax($key, $value, $params)
{
$this->checkParams(1, $params, 'max');
$size = $this->getSize($key, $value);
return $size <= $params[0];
}
public function validMin($key, $value, $params)
{
$this->checkParams(1, $params, 'min');
$size = $this->getSize($key, $value);
return $size >= $params[0];
}
public function validUrl($key, $value, $params)
{
if (!filter_var($value, FILTER_VALIDATE_URL)) {
return false;
}
$parseData = parse_url($value);
$scheme = $parseData['scheme'];
$allowSchemes = array('http', 'https');
if (!in_array($scheme, $allowSchemes)) {
return false;
}
if (!isset($parseData['host'])) {
return false;
}
$host = $parseData['host'];
if (strexists($host, '@')) {
return false;
}
$pattern = '/^(10|172|192|127)/';
if (preg_match($pattern, $host)) {
return false;
}
return parse_path($value);
}
public function validDate($key, $value, $params)
{
return $this->checkDate($value);
}
public function validIn($key, $value, $params)
{
if (is_array($params)) {
return in_array($value, $params, true);
}
return false;
}
public function validNotin($key, $value, $params)
{
return !$this->validIn($key, $value, $params);
}
public function validSame($key, $value, $params)
{
$this->checkParams(1, $params, 'same');
$otherField = $params[0];
$otherValue = isset($this->data[$otherField]) ? $this->data[$otherField] : null;
return (is_string($value) || is_numeric($value)) && $value === $otherValue;
}
public function validBetween($key, $value, $params)
{
$this->checkParams(2, $params, 'between');
$size = $this->getSize($key, $value);
return $size >= $params[0] && $size <= $params[1];
}
public function validAfter($key, $value, $params)
{
$this->checkParams(1, $params, 'afterdate');
$date = $params[0];
return $this->compareDate($value, $date, '>');
}
public function validBefore($key, $value, $params)
{
$this->checkParams(1, $params, 'beforedate');
$date = $params[0];
return $this->compareDate($value, $date, '<');
}
private function compareDate($value, $param, $operator = '=')
{
if (!$this->checkDate($param)) {
$param = $this->getValue($param);
}
if ($this->checkDate($value) && $this->checkDate($param)) {
$currentTime = $this->getDateTimestamp($value);
$paramTime = $this->getDateTimestamp($param);
return $this->compare($currentTime, $paramTime, $operator);
}
return false;
}
public function validBool($key, $value, $params)
{
$acceptable = array(true, false, 0, 1, '0', '1');
return in_array($value, $acceptable, true);
}
public function validPath($key, $value, $params)
{
return parse_path($value);
}
protected function getSize($key, $value)
{
if (is_numeric($value)) {
return $value;
} elseif (is_array($value)) {
return count($value);
} elseif (is_file($value)) {
return filesize($value) / 1024;
} elseif ($value instanceof SplFileInfo) {
return $value->getSize() / 1024;
} elseif (is_string($value)) {
return mb_strlen($value);
}
return false;
}
private function isImage($value)
{
if (is_file($value)) {
$filename = $value;
if ($value instanceof SplFileInfo) {
$filename = $value->getFilename();
}
if (is_string($filename)) {
$pathinfo = pathinfo($filename);
$extension = strtolower($pathinfo['extension']);
return !empty($extension) && in_array($extension, array('jpg', 'jpeg', 'gif', 'png'));
}
}
return false;
}
private function mimeTypeIsImage($mimeType)
{
$imgMimeType = explode(',', static::IMG_MIMETYPE);
return in_array($mimeType, $imgMimeType);
}
private function checkDate($value)
{
if ($value instanceof DateTimeInterface) {
return true;
}
if ((!is_string($value) && !is_numeric($value)) || false === strtotime($value)) {
return false;
}
$date = date_parse($value);
return checkdate($date['month'], $date['day'], $date['year']);
}
private function checkParams($count, $params, $ruleName)
{
if (count($params) != $count) {
throw new InvalidArgumentException("$ruleName 参数个数必须为 $count 个");
}
}
private function getDateTimestamp($date)
{
return $date instanceof DateTimeInterface ? $date->getTimestamp() : strtotime($date);
}
protected function compare($first, $second, $operator)
{
switch ($operator) {
case '<':
return $first < $second;
case '>':
return $first > $second;
case '<=':
return $first <= $second;
case '>=':
return $first >= $second;
case '=':
return $first == $second;
default:
throw new InvalidArgumentException();
}
}
}

206
framework/class/wesession.class.php

@ -0,0 +1,206 @@
<?php
defined('IN_IA') or exit('Access Denied');
class WeSession implements SessionHandlerInterface
{
public static $uniacid;
public static $openid;
public static $expire;
public static function start($uniacid, $openid, $expire = 3600)
{
self::$uniacid = $uniacid;
self::$openid = $openid;
self::$expire = $expire;
$cache_setting = $GLOBALS['_W']['config']['setting'];
if (extension_loaded('memcache') && !empty($cache_setting['memcache']['server']) && !empty($cache_setting['memcache']['session'])) {
self::setHandler('memcache');
} elseif (extension_loaded('redis') && !empty($cache_setting['redis']['server']) && !empty($cache_setting['redis']['session'])) {
self::setHandler('redis');
} else {
self::setHandler('mysql');
}
register_shutdown_function('session_write_close');
session_start();
}
public static function setHandler($type = 'mysql')
{
$classname = "WeSession{$type}";
if (class_exists($classname)) {
$sess = new $classname();
}
if (version_compare(PHP_VERSION, '5.5') >= 0) {
session_set_save_handler($sess, true);
} else {
session_set_save_handler(
array(&$sess, 'open'),
array(&$sess, 'close'),
array(&$sess, 'read'),
array(&$sess, 'write'),
array(&$sess, 'destroy'),
array(&$sess, 'gc')
);
}
return true;
}
public function open($save_path, $session_name)
{
return true;
}
public function close()
{
return true;
}
public function read($sessionid)
{
return '';
}
public function write($sessionid, $data)
{
return true;
}
public function destroy($sessionid)
{
return true;
}
public function gc($expire)
{
return true;
}
}
class WeSessionMemcache extends WeSession
{
protected $session_name;
protected function key($sessionid)
{
return $this->session_name . ':' . $sessionid;
}
public function open($save_path, $session_name)
{
$this->session_name = $session_name;
if ('memcache' != cache_type()) {
trigger_error('Memcache 扩展不可用或是服务未开启,请将 \$config[\'setting\'][\'memcache\'][\'session\'] 设置为0 ');
return false;
}
return true;
}
public function read($sessionid)
{
$row = cache_read($this->key($sessionid));
if (empty($row) || $row['expiretime'] < TIMESTAMP) {
return '';
}
if (is_array($row) && !empty($row['data'])) {
return $row['data'];
}
return '';
}
public function write($sessionid, $data)
{
$row = array();
$row['data'] = $data;
$row['uniacid'] = WeSession::$uniacid;
$row['openid'] = WeSession::$openid;
$row['expiretime'] = TIMESTAMP + WeSession::$expire;
return cache_write($this->key($sessionid), $row);
}
public function destroy($sessionid)
{
return cache_write($this->key($sessionid), '');
}
}
class WeSessionRedis extends WeSessionMemcache
{
public function open($save_path, $session_name)
{
$this->session_name = $session_name;
if ('redis' != cache_type()) {
trigger_error('Redis 扩展不可用或是服务未开启,请将 \$config[\'setting\'][\'redis\'][\'session\'] 设置为0 ');
return false;
}
return true;
}
}
class WeSessionMysql extends WeSession
{
public function open($save_path, $session_name)
{
return true;
}
public function read($sessionid)
{
$sql = 'SELECT * FROM ' . tablename('core_sessions') . ' WHERE `sid`=:sessid AND `expiretime`>:time';
$params = array();
$params[':sessid'] = $sessionid;
$params[':time'] = TIMESTAMP;
$row = pdo_fetch($sql, $params);
if (is_array($row) && !empty($row['data'])) {
return $row['data'];
}
return '';
}
public function write($sessionid, $data)
{
$row = array();
$row['sid'] = $sessionid;
$row['uniacid'] = WeSession::$uniacid;
$row['openid'] = WeSession::$openid;
$row['data'] = $data;
$row['expiretime'] = TIMESTAMP + WeSession::$expire;
return pdo_insert('core_sessions', $row, true) >= 1;
}
public function destroy($sessionid)
{
$row = array();
$row['sid'] = $sessionid;
return 1 == pdo_delete('core_sessions', $row);
}
public function gc($expire)
{
$sql = 'DELETE FROM ' . tablename('core_sessions') . ' WHERE `expiretime`<:expire';
return 1 == pdo_query($sql, array(':expire' => TIMESTAMP));
}
}

293
framework/const.inc.php

@ -0,0 +1,293 @@
<?php
defined('IN_IA') or exit('Access Denied');
define('REGULAR_EMAIL', '/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/i');
define('REGULAR_MOBILE', '/1[3456789][0-9]{9}/');
define('REGULAR_USERNAME', '/^[\x{4e00}-\x{9fa5}a-z\d_\.]{3,30}$/iu');
define('TEMPLATE_DISPLAY', 0);
define('TEMPLATE_FETCH', 1);
define('TEMPLATE_INCLUDEPATH', 2);
define('ACCOUNT_SUBSCRIPTION', 1);
define('ACCOUNT_SUBSCRIPTION_VERIFY', 3);
define('ACCOUNT_SERVICE', 2);
define('ACCOUNT_SERVICE_VERIFY', 4);
define('ACCOUNT_TYPE_OFFCIAL_NORMAL', 1);
define('ACCOUNT_TYPE_OFFCIAL_AUTH', 3);
define('ACCOUNT_TYPE_APP_NORMAL', 4);
define('ACCOUNT_TYPE_WEBAPP_NORMAL', 5);
define('ACCOUNT_TYPE_PHONEAPP_NORMAL', 6);
define('ACCOUNT_TYPE_APP_AUTH', 7);
define('ACCOUNT_TYPE_WXAPP_WORK', 8);
define('ACCOUNT_TYPE_ALIAPP_NORMAL', 11);
define('ACCOUNT_TYPE_BAIDUAPP_NORMAL', 12);
define('ACCOUNT_TYPE_TOUTIAOAPP_NORMAL', 13);
define('ACCOUNT_TYPE_SIGN', 'account');
define('WXAPP_TYPE_SIGN', 'wxapp');
define('WEBAPP_TYPE_SIGN', 'webapp');
define('PHONEAPP_TYPE_SIGN', 'phoneapp');
define('WELCOMESYSTEM_TYPE_SIGN', 'welcome');
define('ALIAPP_TYPE_SIGN', 'aliapp');
define('BAIDUAPP_TYPE_SIGN', 'baiduapp');
define('TOUTIAOAPP_TYPE_SIGN', 'toutiaoapp');
define('ACCOUNT_OAUTH_LOGIN', 3);
define('ACCOUNT_NORMAL_LOGIN', 1);
define('ACCOUNT_OPERATE_ONLINE', 1);
define('ACCOUNT_OPERATE_MANAGER', 2);
define('ACCOUNT_OPERATE_CLERK', 3);
define('ACCOUNT_MANAGE_NAME_CLERK', 'clerk');
define('ACCOUNT_MANAGE_TYPE_OPERATOR', 1);
define('ACCOUNT_MANAGE_NAME_OPERATOR', 'operator');
define('ACCOUNT_MANAGE_TYPE_MANAGER', 2);
define('ACCOUNT_MANAGE_NAME_MANAGER', 'manager');
define('ACCOUNT_MANAGE_TYPE_OWNER', 3);
define('ACCOUNT_MANAGE_NAME_OWNER', 'owner');
define('ACCOUNT_MANAGE_NAME_FOUNDER', 'founder');
define('ACCOUNT_MANAGE_GROUP_FOUNDER', 1);
define('ACCOUNT_MANAGE_TYPE_VICE_FOUNDER', 4);
define('ACCOUNT_MANAGE_NAME_VICE_FOUNDER', 'vice_founder');
define('ACCOUNT_MANAGE_GROUP_VICE_FOUNDER', 2);
define('ACCOUNT_MANAGE_GROUP_GENERAL', 0);
define('ACCOUNT_MANAGE_NAME_UNBIND_USER', 'unbind_user');
define('ACCOUNT_NO_OWNER_UID', 0);
define('ACCOUNT_MANAGE_NAME_EXPIRED', 'expired');
define('SYSTEM_COUPON', 1);
define('WECHAT_COUPON', 2);
define('COUPON_TYPE_DISCOUNT', '1');
define('COUPON_TYPE_CASH', '2');
define('COUPON_TYPE_GROUPON', '3');
define('COUPON_TYPE_GIFT', '4');
define('COUPON_TYPE_GENERAL', '5');
define('COUPON_TYPE_MEMBER', '6');
define('COUPON_TYPE_SCENIC', '7');
define('COUPON_TYPE_MOVIE', '8');
define('COUPON_TYPE_BOARDINGPASS', '9');
define('COUPON_TYPE_MEETING', '10');
define('COUPON_TYPE_BUS', '11');
define('ATTACH_FTP', 1);
define('ATTACH_OSS', 2);
define('ATTACH_QINIU', 3);
define('ATTACH_COS', 4);
define('ATTACH_TYPE_IMAGE', 1);
define('ATTACH_TYPE_VOICE', 2);
define('ATTACH_TYPE_VEDIO', 3);
define('ATTACH_TYPE_NEWS', 4);
define('ATTACHMENT_IMAGE', 'image');
define('ATTACH_SAVE_TYPE_FIXED', 1);
define('ATTACH_SAVE_TYPE_TEMP', 2);
define('STATUS_OFF', 0);
define('STATUS_ON', 1);
define('STATUS_SUCCESS', 0);
define('CACHE_EXPIRE_SHORT', 60);
define('CACHE_EXPIRE_MIDDLE', 300);
define('CACHE_EXPIRE_LONG', 3600);
define('CACHE_KEY_LENGTH', 100);
define('APPLICATION_TYPE_MODULE', 1);
define('APPLICATION_TYPE_TEMPLATES', 2);
define('MODULE_SYSTEM', 1);
define('MODULE_NONSYSTEM', 0);
define('MODULE_SUPPORT_WXAPP', 2);
define('MODULE_NONSUPPORT_WXAPP', 1);
define('MODULE_SUPPORT_ACCOUNT', 2);
define('MODULE_NONSUPPORT_ACCOUNT', 1);
define('MODULE_NOSUPPORT_WEBAPP', 1);
define('MODULE_SUPPORT_WEBAPP', 2);
define('MODULE_NOSUPPORT_PHONEAPP', 1);
define('MODULE_SUPPORT_PHONEAPP', 2);
define('MODULE_SUPPORT_SYSTEMWELCOME', 2);
define('MODULE_NONSUPPORT_SYSTEMWELCOME', 1);
define('MODULE_NOSUPPORT_ANDROID', 1);
define('MODULE_SUPPORT_ANDROID', 2);
define('MODULE_NOSUPPORT_IOS', 1);
define('MODULE_SUPPORT_IOS', 2);
define('MODULE_SUPPORT_ALIAPP', 2);
define('MODULE_NOSUPPORT_ALIAPP', 1);
define('MODULE_SUPPORT_BAIDUAPP', 2);
define('MODULE_NOSUPPORT_BAIDUAPP', 1);
define('MODULE_SUPPORT_TOUTIAOAPP', 2);
define('MODULE_NOSUPPORT_TOUTIAOAPP', 1);
define('MODULE_SUPPORT_WXAPP_NAME', 'wxapp_support');
define('MODULE_SUPPORT_ACCOUNT_NAME', 'account_support');
define('MODULE_SUPPORT_WEBAPP_NAME', 'webapp_support');
define('MODULE_SUPPORT_PHONEAPP_NAME', 'phoneapp_support');
define('MODULE_SUPPORT_SYSTEMWELCOME_NAME', 'welcome_support');
define('MODULE_SUPPORT_ALIAPP_NAME', 'aliapp_support');
define('MODULE_SUPPORT_BAIDUAPP_NAME', 'baiduapp_support');
define('MODULE_SUPPORT_TOUTIAOAPP_NAME', 'toutiaoapp_support');
define('MODULE_LOCAL_INSTALL', '1');
define('MODULE_LOCAL_UNINSTALL', '2');
define('MODULE_CLOUD_INSTALL', '3');
define('MODULE_CLOUD_UNINSTALL', '4');
define('MODULE_CLOUD_UNINSTALL_NORMAL', '1');
define('MODULE_CLOUD_UNINSTALL_CHECKED', '2');
define('MODULE_CLOUD_UNINSTALL_IGNORE', '3');
define('MODULE_RECYCLE_INSTALL_DISABLED', '1');
define('MODULE_RECYCLE_UNINSTALL_IGNORE', '2');
define('PERMISSION_ACCOUNT', 'system');
define('PERMISSION_WXAPP', 'wxapp');
define('PERMISSION_WEBAPP', 'webapp');
define('PERMISSION_PHONEAPP', 'phoneapp');
define('PERMISSION_ALIAPP', 'aliapp');
define('PERMISSION_BAIDUAPP', 'baiduapp');
define('PERMISSION_TOUTIAOAPP', 'toutiaoapp');
define('PERMISSION_SYSTEM', 'site');
define('PERMISSION_MODULES', 'modules');
define('PAYMENT_WECHAT_TYPE_NORMAL', 1);
define('PAYMENT_WECHAT_TYPE_BORROW', 2);
define('PAYMENT_WECHAT_TYPE_SERVICE', 3);
define('PAYMENT_WECHAT_TYPE_CLOSE', 4);
define('FANS_CHATS_FROM_SYSTEM', 1);
define('WXAPP_STATISTICS_DAILYVISITTREND', 2);
define('WXAPP_DIY', 1);
define('WXAPP_TEMPLATE', 2);
define('WXAPP_MODULE', 3);
define('WXAPP_CREATE_MODULE', 1);
define('WXAPP_CREATE_MUTI_MODULE', 2);
define('WXAPP_CREATE_DEFAULT', 0);
define('MATERIAL_LOCAL', 'local');
define('MATERIAL_WEXIN', 'perm');
define('MENU_CURRENTSELF', 1);
define('MENU_HISTORY', 2);
define('MENU_CONDITIONAL', 3);
define('USER_STATUS_CHECK', 1);
define('USER_STATUS_NORMAL', 2);
define('USER_STATUS_BAN', 3);
define('USER_TYPE_COMMON', 1);
define('USER_TYPE_CLERK', 3);
define('PERSONAL_BASE_TYPE', 1);
define('PERSONAL_AUTH_TYPE', 2);
define('PERSONAL_LIST_TYPE', 3);
define('PERSONAL_BIND_TYPE', 4);
define('PERSONAL_LIMIT_TYPE', 5);
define('STORE_TYPE_ACCOUNT', 2);
define('STORE_TYPE_WXAPP', 3);
define('STORE_TYPE_WEBAPP', 17);
define('STORE_TYPE_PHONEAPP', 18);
define('STORE_TYPE_ALIAPP', 20);
define('STORE_TYPE_BAIDUAPP', 21);
define('STORE_TYPE_TOUTIAOAPP', 22);
define('STORE_TYPE_ACCOUNT_RENEW', 7);
define('STORE_TYPE_WXAPP_RENEW', 8);
define('STORE_TYPE_WEBAPP_RENEW', 23);
define('STORE_TYPE_PHONEAPP_RENEW', 24);
define('STORE_TYPE_ALIAPP_RENEW', 26);
define('STORE_TYPE_BAIDUAPP_RENEW', 27);
define('STORE_TYPE_TOUTIAOAPP_RENEW', 28);
define('STORE_TYPE_MODULE', 1);
define('STORE_TYPE_WXAPP_MODULE', 4);
define('STORE_TYPE_WEBAPP_MODULE', 11);
define('STORE_TYPE_PHONEAPP_MODULE', 12);
define('STORE_TYPE_ALIAPP_MODULE', 14);
define('STORE_TYPE_BAIDUAPP_MODULE', 15);
define('STORE_TYPE_TOUTIAOAPP_MODULE', 16);
define('STORE_TYPE_PACKAGE', 5);
define('STORE_TYPE_API', 6);
define('STORE_TYPE_USER_PACKAGE', 9);
define('STORE_TYPE_ACCOUNT_PACKAGE', 10);
define('STORE_TYPE_USER_RENEW', 29);
define('STORE_ORDER_PLACE', 1);
define('STORE_ORDER_DELETE', 2);
define('STORE_ORDER_FINISH', 3);
define('STORE_ORDER_DEACTIVATE', 4);
define('STORE_ORDER_APPLY_REFUND', 5);
define('STORE_ORDER_REFUND_FAIL', 6);
define('STORE_ORDER_REFUNDED', 7);
define('STORE_ORDER_FOUNDER_REFUND', 8);
define('STORE_ORDER_WISH', 1);
define('STORE_ORDER_NORMAL', 0);
define('STORE_ORDER_ALL', 3);
define('STORE_GOODS_STATUS_OFFlINE', 0);
define('STORE_GOODS_STATUS_ONLINE', 1);
define('STORE_GOODS_STATUS_DELETE', 2);
define('ARTICLE_PCATE', 0);
define('ARTICLE_CCATE', 0);
define('USER_REGISTER_TYPE_QQ', 1);
define('USER_REGISTER_TYPE_WECHAT', 2);
define('USER_REGISTER_TYPE_MOBILE', 3);
define('USER_REGISTER_TYPE_OPEN_WECHAT', 4);
define('MESSAGE_ORDER_TYPE', 1);
define('MESSAGE_ORDER_WISH_TYPE', 13);
define('MESSAGE_ORDER_PAY_TYPE', 9);
define('MESSAGE_ACCOUNT_EXPIRE_TYPE', 2);
define('MESSAGE_WECHAT_EXPIRE_TYPE', 5);
define('MESSAGE_WEBAPP_EXPIRE_TYPE', 6);
define('MESSAGE_WORKORDER_TYPE', 3);
define('MESSAGE_REGISTER_TYPE', 4);
define('MESSAGE_USER_EXPIRE_TYPE', 7);
define('MESSAGE_WXAPP_MODULE_UPGRADE', 8);
define('MESSAGE_SYSTEM_UPGRADE', 10);
define('MESSAGE_OFFICIAL_DYNAMICS', 11);
define('MESSAGE_ORDER_APPLY_REFUND_TYPE', 12);
define('MESSAGE_ENABLE', 1);
define('MESSAGE_DISABLE', 2);
define('MESSAGE_NOREAD', 1);
define('MESSAGE_READ', 2);
define('FILE_NO_UNIACID', -1);
define('OAUTH_TYPE_BASE', 1);
define('OAUTH_TYPE_USERINFO', 2);
define('ARTICLE_COMMENT_DEFAULT', 0);
define('ARTICLE_NOCOMMENT', 1);
define('ARTICLE_COMMENT', 2);
define('ARTICLE_COMMENT_NOREAD', 1);
define('ARTICLE_COMMENT_READ', 2);
define('COMMENT_STATUS_OFF', 0);
define('COMMENT_STATUS_ON', 1);
define('WELCOME_DISPLAY_TYPE', 9);
define('PLATFORM_DISPLAY_TYPE', 6);
define('MODULE_DISPLAY_TYPE', 7);
define('USER_CREATE_PERMISSION_ALL_TYPE', 1);
define('USER_CREATE_PERMISSION_GROUP_TYPE', 2);
define('USER_ENDTIME_GROUP_EMPTY_TYPE', 0);
define('USER_ENDTIME_GROUP_DELETE_TYPE', 1);
define('USER_ENDTIME_GROUP_UNLIMIT_TYPE', 2);
define('USERS_OPERATE_TYPE_ACCOUNT', 1);
define('USERS_OPERATE_TYPE_MODULE', 2);
define('WXAPP_REGISTER_CHECK_STATUS_FAIL', 3);
define('WXAPP_REGISTER_VERSION_STATUS_DEVELOP', 0);
define('WXAPP_REGISTER_VERSION_STATUS_CHECKFAIL', 1);
define('WXAPP_REGISTER_VERSION_STATUS_CHECKING', 2);
define('WXAPP_REGISTER_VERSION_STATUS_RETRACT', 3);
define('WXAPP_REGISTER_VERSION_STATUS_RELEASE', 4);
define('WXAPP_REGISTER_VERSION_STATUS_CHECKSUCCESS', 5);

61
framework/function/cache.file.func.php

@ -0,0 +1,61 @@
<?php
defined('IN_IA') or exit('Access Denied');
load()->func('file');
define('CACHE_FILE_PATH', IA_ROOT . '/data/cache/');
function cache_read($key, $dir = '', $include = true) {
$key = str_replace(':', '@', $key);
$key = CACHE_FILE_PATH . $key;
if (!is_file($key)) {
return array();
}
return $include ? include $key : file_get_contents($key);
}
function cache_write($key, $data, $dir = '') {
global $_W;
if (empty($key) || !isset($data)) {
return false;
}
$key = str_replace(':', '@', $key);
if (!is_string($data)) {
$data = "<?php \r\ndefined('IN_IA') or exit('Access Denied');\r\nreturn " . var_export($data, true) . ';';
}
$key = CACHE_FILE_PATH . $key;
mkdirs(dirname($key));
file_put_contents($key, $data);
@chmod($key, $_W['config']['setting']['filemode']);
return is_file($key);
}
function cache_delete($key, $dir = '') {
$cache_relation_keys = cache_relation_keys($key);
if (is_error($cache_relation_keys)) {
return $cache_relation_keys;
}
if (is_array($cache_relation_keys) && !empty($cache_relation_keys)) {
foreach ($cache_relation_keys as $key) {
$cache_info = cache_load($key);
if (!empty($cache_info)) {
$key = str_replace(':', '@', $key);
$key = CACHE_FILE_PATH . $key;
$result = file_delete($key);
if (!$result) {
return error(1, '缓存: ' . $key . ' 删除失败!');
}
}
}
}
return true;
}
function cache_clean($dir = '') {
return rmdirs(CACHE_FILE_PATH, true);
}

614
framework/function/cache.func.php

@ -0,0 +1,614 @@
<?php
defined('IN_IA') or exit('Access Denied');
load()->func('cache.' . cache_type());
function cache_type() {
global $_W;
$cacher = $connect = '';
$cache_type = strtolower($_W['config']['setting']['cache']);
if (extension_loaded($cache_type)) {
$config = $_W['config']['setting'][$cache_type];
if (!empty($config['server']) && !empty($config['port'])) {
if ('memcache' == $cache_type) {
$cacher = new Memcache();
} elseif ('redis' == $cache_type) {
$cacher = new Redis();
}
$connect = $cacher->connect($config['server'], $config['port']);
}
}
if (empty($cacher) || empty($connect)) {
$cache_type = 'mysql';
}
return $cache_type;
}
function cache_load($key, $unserialize = false) {
global $_W;
static $we7_cache;
if (is_error($key)) {
trigger_error($key['message'], E_USER_WARNING);
return false;
}
if (!empty($we7_cache[$key])) {
return $we7_cache[$key];
}
$data = $we7_cache[$key] = cache_read($key);
if ('setting' == $key) {
$_W['setting'] = $data;
return $_W['setting'];
} elseif ('modules' == $key) {
$_W['modules'] = $data;
return $_W['modules'];
} elseif ('module_receive_enable' == $key && empty($data)) {
cache_build_module_subscribe_type();
return cache_read($key);
} else {
return $unserialize ? iunserializer($data) : $data;
}
}
function &cache_global($key) {
}
function cache_system_key($cache_key) {
$cache_key_all = cache_key_all();
$params = array();
$args = func_get_args();
if (empty($args[1])) {
$args[1] = '';
}
if (!is_array($args[1])) {
$cache_key = $cache_key_all['caches'][$cache_key]['key'];
preg_match_all('/\%([a-zA-Z\_\-0-9]+)/', $cache_key, $matches);
for ($i = 0; $i < func_num_args() - 1; ++$i) {
$cache_key = str_replace($matches[0][$i], $args[$i + 1], $cache_key);
}
return 'we7:' . $cache_key;
} else {
$params = $args[1];
}
if (empty($params)) {
$res = preg_match_all('/([a-zA-Z\_\-0-9]+):/', $cache_key, $matches);
if ($res) {
$key = count($matches[1]) > 0 ? $matches[1][0] : $matches[1];
} else {
$key = $cache_key;
}
if (empty($cache_key_all['caches'][$key])) {
return error(1, '缓存' . $key . ' 不存在!');
} else {
$cache_info_key = $cache_key_all['caches'][$key]['key'];
preg_match_all('/\%([a-zA-Z\_\-0-9]+)/', $cache_info_key, $key_params);
preg_match_all('/\:([a-zA-Z\_\-0-9]+)/', $cache_key, $val_params);
if (count($key_params[1]) != count($val_params[1])) {
foreach ($key_params[1] as $key => $val) {
if (in_array($val, array_keys($cache_key_all['common_params']))) {
$cache_info_key = str_replace('%' . $val, $cache_key_all['common_params'][$val], $cache_info_key);
unset($key_params[1][$key]);
}
}
if (count($key_params[1]) == count($val_params[1])) {
$arr = array_combine($key_params[1], $val_params[1]);
foreach ($arr as $key => $val) {
if (preg_match('/\%' . $key . '/', $cache_info_key)) {
$cache_info_key = str_replace('%' . $key, $val, $cache_info_key);
}
}
}
if (strexists($cache_info_key, '%')) {
return error(1, '缺少缓存参数或参数不正确!');
} else {
return 'we7:' . $cache_info_key;
}
} else {
return 'we7:' . $cache_key;
}
}
}
$cache_info = $cache_key_all['caches'][$cache_key];
$cache_common_params = $cache_key_all['common_params'];
if (empty($cache_info)) {
return error(2, '缓存 ' . $cache_key . ' 不存在!');
} else {
$cache_key = $cache_info['key'];
}
foreach ($cache_common_params as $param_name => $param_val) {
preg_match_all('/\%([a-zA-Z\_\-0-9]+)/', $cache_key, $matches);
if (in_array($param_name, $matches[1]) && !in_array($param_name, array_keys($params))) {
$params[$param_name] = $cache_common_params[$param_name];
}
}
if (is_array($params) && !empty($params)) {
foreach ($params as $key => $param) {
$cache_key = str_replace('%' . $key, $param, $cache_key);
}
if (strexists($cache_key, '%')) {
return error(1, '缺少缓存参数或参数不正确!');
}
}
$cache_key = 'we7:' . $cache_key;
if (strlen($cache_key) > CACHE_KEY_LENGTH) {
trigger_error('Cache name is over the maximum length');
}
return $cache_key;
}
function cache_relation_keys($key) {
if (!is_string($key)) {
return $key;
}
if (!strexists($key, 'we7:')) {
return array($key);
}
$cache_param_values = explode(':', $key);
$cache_name = $cache_param_values[1];
unset($cache_param_values[0]);
unset($cache_param_values[1]);
if (empty($cache_param_values)) {
preg_match_all('/\:([a-zA-Z\_\-0-9]+)/', $key, $matches);
$cache_name = $matches[1][0];
}
$cache_key_all = cache_key_all();
$cache_relations = $cache_key_all['groups'];
$cache_common_params = $cache_key_all['common_params'];
$cache_info = $cache_key_all['caches'][$cache_name];
if (empty($cache_info)) {
return error(2, '缓存 : ' . $key . '不存在');
}
if (!empty($cache_info['group'])) {
if (empty($cache_relations[$cache_info['group']])) {
return error(1, '关联关系未定义');
}
$relation_keys = $cache_relations[$cache_info['group']]['relations'];
$cache_keys = array();
foreach ($relation_keys as $key => $val) {
if ($val == $cache_name) {
$relation_cache_key = $cache_key_all['caches'][$val]['key'];
} else {
$relation_cache_key = $cache_key_all['caches'][$cache_name]['key'];
}
foreach ($cache_common_params as $param_name => $param_val) {
preg_match_all('/\%([a-zA-Z\_\-0-9]+)/', $relation_cache_key, $matches);
if (in_array($param_name, $matches[1])) {
$cache_key_params[$param_name] = $cache_common_params[$param_name];
}
if (!empty($cache_prams_values) || count($matches[1]) == count($cache_param_values)) {
$cache_key_params = array_combine($matches[1], $cache_param_values);
} else {
$cache_key_params = array();
}
}
$cache_key = cache_system_key($val, $cache_key_params);
if (!is_error($cache_key)) {
$cache_keys[] = $cache_key;
} else {
return error(1, $cache_key['message']);
}
}
} else {
$cache_keys[] = $key;
}
return $cache_keys;
}
function cache_key_all() {
global $_W;
$caches_all = array(
'common_params' => array(
'uniacid' => $_W['uniacid'],
'uid' => $_W['uid'],
),
'caches' => array(
'module_info' => array(
'key' => 'module_info:%module_name',
'group' => 'module',
),
'module_main_info' => array(
'key' => 'module_main_info:%module_name',
'group' => 'module',
),
'module_setting' => array(
'key' => 'module_setting:%module_name:%uniacid',
'group' => 'module',
),
'last_account' => array(
'key' => 'last_account:%switch:%uid',
'group' => '',
),
'last_account_type' => array(
'key' => 'last_account_type',
'group' => '',
),
'user_modules' => array(
'key' => 'user_modules:%uid',
'group' => '',
),
'user_accounts' => array(
'key' => 'user_accounts:%type:%uid',
'group' => '',
),
'unimodules' => array(
'key' => 'unimodules:%uniacid',
'group' => '',
),
'unimodules_binding' => array(
'key' => 'unimodules_binding:%uniacid',
'group' => '',
),
'uni_groups' => array(
'key' => 'uni_groups:%groupids',
'group' => '',
),
'permission' => array(
'key' => 'permission:%uniacid:%uid',
'group' => '',
),
'memberinfo' => array(
'key' => 'memberinfo:%uid',
'group' => '',
),
'statistics' => array(
'key' => 'statistics:%uniacid',
'group' => '',
),
'uniacid_visit' => array(
'key' => 'uniacid_visit:%uniacid:%today',
'group' => '',
),
'material_reply' => array(
'key' => 'material_reply:%attach_id',
'group' => '',
),
'keyword' => array(
'key' => 'keyword:%content:%uniacid',
'group' => '',
),
'back_days' => array(
'key' => 'back_days',
'group' => '',
),
'miniapp_version' => array(
'key' => 'miniapp_version:%version_id',
'group' => '',
),
'site_store_buy' => array(
'key' => 'site_store_buy:%type:%uniacid',
'group' => '',
),
'proxy_wechatpay_account' => array(
'key' => 'proxy_wechatpay_account',
'group' => '',
),
'recycle_module' => array(
'key' => 'recycle_module',
'group' => '',
),
'random' => array(
'key' => 'random',
'group' => '',
),
'sync_fans_pindex' => array(
'key' => 'sync_fans_pindex:%uniacid',
'group' => '',
),
'uniaccount' => array(
'key' => 'uniaccount:%uniacid',
'group' => 'uniaccount',
),
'unisetting' => array(
'key' => 'unisetting:%uniacid',
'group' => 'uniaccount',
),
'defaultgroupid' => array(
'key' => 'defaultgroupid:%uniacid',
'group' => 'uniaccount',
),
'uniaccount_type' => array(
'key' => 'uniaccount_type:%account_type',
'group' => '',
),
'accesstoken' => array(
'key' => 'accesstoken:%uniacid',
'group' => 'accesstoken',
),
'jsticket' => array(
'key' => 'jsticket:%uniacid',
'group' => 'accesstoken',
),
'cardticket' => array(
'key' => 'cardticket:%uniacid',
'group' => 'accesstoken',
),
'accesstoken_key' => array(
'key' => 'accesstoken_key:%key',
'group' => '',
),
'account_oauth_refreshtoken' => array(
'key' => 'account_oauth_refreshtoken:%acid',
'group' => '',
),
'account_auth_refreshtoken' => array(
'key' => 'account_auth_refreshtoken:%uniacid',
'group' => '',
),
'account_tags' => array(
'key' => 'account_tags:%uniacid',
'group' => '',
),
'unicount' => array(
'key' => 'unicount:%uniacid',
'group' => '',
),
'checkupgrade' => array(
'key' => 'checkupgrade',
'group' => '',
),
'cloud_transtoken' => array(
'key' => 'cloud_transtoken',
'group' => '',
),
'cloud_w7_request_token' => array(
'key' => 'cloud_w7_request_token',
'group' => '',
),
'upgrade' => array(
'key' => 'upgrade',
'group' => '',
),
'account_ticket' => array(
'key' => 'account_ticket',
'group' => '',
),
'oauthaccesstoken' => array(
'key' => 'oauthaccesstoken:%acid',
'group' => '',
),
'account_component_assesstoken' => array(
'key' => 'account_component_assesstoken',
'group' => '',
),
'cloud_api' => array(
'key' => 'cloud_api:%method',
'group' => '',
),
'cloud_ad_uniaccount' => array(
'key' => 'cloud_ad_uniaccount:%uniacid',
'group' => '',
),
'cloud_ad_uniaccount_list' => array(
'key' => 'cloud_ad_uniaccount_list',
'group' => '',
),
'cloud_flow_master' => array(
'key' => 'cloud_flow_master',
'group' => '',
),
'cloud_ad_tags' => array(
'key' => 'cloud_ad_tags',
'group' => '',
),
'cloud_ad_type_list' => array(
'key' => 'cloud_ad_type_list',
'group' => '',
),
'cloud_ad_app_list' => array(
'key' => 'cloud_ad_app_list:%uniacid',
'group' => '',
),
'cloud_ad_app_support_list' => array(
'key' => 'cloud_ad_app_support_list',
'group' => '',
),
'cloud_ad_site_finance' => array(
'key' => 'cloud_ad_site_finance',
'group' => '',
),
'cloud_ad_store_notice' => array(
'key' => 'cloud_ad_store_notice',
'group' => '',
),
'cloud_file_permission_pass' => array(
'key' => 'cloud_file_permission_pass',
'group' => '',
),
'couponsync' => array(
'key' => 'couponsync:%uniacid',
'group' => '',
),
'storesync' => array(
'key' => 'storesync:%uniacid',
'group' => '',
),
'cloud_auth_transfer' => array(
'key' => 'cloud_auth_transfer',
'group' => '',
),
'modulesetting' => array(
'key' => 'modulesetting:%module:%acid',
'group' => '',
),
'scan_config' => array(
'key' => 'scan_config',
'group' => 'scan_file',
),
'scan_file' => array(
'key' => 'scan_file',
'group' => 'scan_file',
),
'scan_badfile' => array(
'key' => 'scan_badfile',
'group' => 'scan_file',
),
'bomtree' => array(
'key' => 'bomtree',
'group' => '',
),
'setting' => array(
'key' => 'setting',
'group' => '',
),
'stat_todaylock' => array(
'key' => 'stat_todaylock:%uniacid',
'group' => '',
),
'account_preauthcode' => array(
'key' => 'account_preauthcode',
'group' => '',
),
'account_auth_accesstoken' => array(
'key' => 'account_auth_accesstoken:%key',
'group' => '',
),
'usersfields' => array(
'key' => 'usersfields',
'group' => '',
),
'userbasefields' => array(
'key' => 'userbasefields',
'group' => '',
),
'system_frame' => array(
'key' => 'system_frame:%uniacid',
'group' => '',
),
'module_receive_enable' => array(
'key' => 'module_receive_enable',
'group' => '',
),
'module_entry_call' => array(
'key' => 'module_entry_call:%module_name',
'group' => '',
),
'system_check' => array(
'key' => 'system_check',
'group' => '',
),
'delete_visit_ip' => array(
'key' => 'delete_visit_ip:%date',
'group' => '',
),
),
'groups' => array(
'uniaccount' => array(
'relations' => array('uniaccount', 'unisetting', 'defaultgroupid'),
),
'accesstoken' => array(
'relations' => array('accesstoken', 'jsticket', 'cardticket'),
),
'scan_file' => array(
'relations' => array('scan_file', 'scan_config', 'scan_badfile'),
),
'module' => array(
'relations' => array('module_info', 'module_setting', 'module_main_info'),
),
),
);
return $caches_all;
}

169
framework/function/cache.memcache.func.php

@ -0,0 +1,169 @@
<?php
defined('IN_IA') or exit('Access Denied');
function cache_memcache() {
global $_W;
static $memcacheobj;
if (!extension_loaded('memcache')) {
return error(1, 'Class Memcache is not found');
}
if (empty($memcacheobj)) {
$config = $_W['config']['setting']['memcache'];
$memcacheobj = new Memcache();
if ($config['pconnect']) {
$connect = $memcacheobj->pconnect($config['server'], $config['port']);
} else {
$connect = $memcacheobj->connect($config['server'], $config['port']);
}
if (!$connect) {
return error(-1, 'Memcache is not in work');
}
}
return $memcacheobj;
}
function cache_read($key, $forcecache = true) {
$key = cache_namespace($key);
$memcache = cache_memcache();
if (is_error($memcache)) {
return $memcache;
}
$result = $memcache->get(cache_prefix($key));
if (empty($result) && empty($forcecache)) {
$dbcache = pdo_get('core_cache', array('key' => $key), array('value'));
if (!empty($dbcache['value'])) {
$result = iunserializer($dbcache['value']);
$memcache->set(cache_prefix($key), $result);
}
}
return $result;
}
function cache_search($key) {
return cache_read(cache_prefix($key));
}
function cache_write($key, $value, $ttl = 0, $forcecache = true) {
$key = cache_namespace($key);
$memcache = cache_memcache();
if (is_error($memcache)) {
return $memcache;
}
if (empty($forcecache)) {
$record = array();
$record['key'] = $key;
$record['value'] = iserializer($value);
pdo_insert('core_cache', $record, true);
}
if ($memcache->set(cache_prefix($key), $value, MEMCACHE_COMPRESSED, $ttl)) {
return true;
} else {
return false;
}
}
function cache_delete($key, $forcecache = true) {
$memcache = cache_memcache();
if (is_error($memcache)) {
return $memcache;
}
$cache_relation_keys = cache_relation_keys($key);
if (is_error($cache_relation_keys)) {
return $cache_relation_keys;
}
if (is_array($cache_relation_keys) && !empty($cache_relation_keys)) {
foreach ($cache_relation_keys as $key) {
$cache_info = cache_load($key);
if (!empty($cache_info)) {
$origins_cache_key = $key;
$key = cache_namespace($key);
if (empty($forcecache)) {
pdo_delete('core_cache', array('key' => $key));
}
$result = $memcache->delete(cache_prefix($key));
unset($GLOBALS['_W']['cache'][$origins_cache_key]);
if (!$result) {
return error(1, '缓存: ' . $key . ' 删除失败!');
}
}
}
}
return true;
}
function cache_clean($prefix = '') {
if (!empty($prefix)) {
$cache_relation_keys = cache_relation_keys($prefix);
if (is_error($cache_relation_keys)) {
return $cache_relation_keys;
}
if (is_array($cache_relation_keys) && !empty($cache_relation_keys)) {
foreach ($cache_relation_keys as $key) {
preg_match_all('/\:([a-zA-Z0-9\-\_]+)/', $key, $matches);
$cache_namespace = cache_namespace('we7:' . $matches[1][0]);
pdo_delete('core_cache', array('key LIKE' => $cache_namespace . '%'));
unset($GLOBALS['_W']['cache']);
cache_namespace('we7:' . $matches[1][0], true);
}
}
return true;
}
$memcache = cache_memcache();
if (is_error($memcache)) {
return $memcache;
}
if ($memcache->flush()) {
unset($GLOBALS['_W']['cache']);
pdo_delete('core_cache');
return true;
} else {
return false;
}
}
function cache_namespace($key, $forcenew = false) {
if (!strexists($key, ':')) {
$namespace_cache_key = $key;
} else {
list($key1, $key2) = explode(':', $key);
if ('we7' == $key1) {
$namespace_cache_key = $key2;
} else {
$namespace_cache_key = $key1;
}
}
if (!in_array($namespace_cache_key, array('unimodules', 'user_modules', 'system_frame'))) {
return $key;
}
$namespace_cache_key = 'cachensl:' . $namespace_cache_key;
$memcache = cache_memcache();
if (is_error($memcache)) {
return $memcache;
}
$namespace = $memcache->get(cache_prefix($namespace_cache_key));
if (empty($namespace) || $forcenew) {
$namespace = random(5);
$memcache->set(cache_prefix($namespace_cache_key), $namespace, MEMCACHE_COMPRESSED, 0);
}
return $namespace . ':' . $key;
}
function cache_prefix($key) {
return $GLOBALS['_W']['config']['setting']['authkey'] . $key;
}

112
framework/function/cache.mysql.func.php

@ -0,0 +1,112 @@
<?php
defined('IN_IA') or exit('Access Denied');
function cache_read($key) {
$cachedata = pdo_getcolumn('core_cache', array('key' => $key), 'value');
if (empty($cachedata)) {
return '';
}
$cachedata = iunserializer($cachedata);
if (is_array($cachedata) && !empty($cachedata['expire']) && false !== $cachedata['data']) {
if ($cachedata['expire'] > TIMESTAMP) {
return $cachedata['data'];
} else {
return '';
}
} else {
return $cachedata;
}
}
function cache_search($prefix) {
$sql = 'SELECT * FROM ' . tablename('core_cache') . ' WHERE `key` LIKE :key';
$params = array();
$params[':key'] = "{$prefix}%";
$rs = pdo_fetchall($sql, $params);
$result = array();
foreach ((array) $rs as $v) {
$result[$v['key']] = iunserializer($v['value']);
}
return $result;
}
function cache_write($key, $data, $expire = 0) {
if (empty($key) || !isset($data)) {
return false;
}
$record = array();
$record['key'] = $key;
if (!empty($expire)) {
$cache_data = array(
'expire' => TIMESTAMP + $expire,
'data' => $data,
);
} else {
$cache_data = $data;
}
$record['value'] = iserializer($cache_data);
return pdo_insert('core_cache', $record, true);
}
function cache_delete($key) {
$cache_relation_keys = cache_relation_keys($key);
if (is_error($cache_relation_keys)) {
return $cache_relation_keys;
}
if (is_array($cache_relation_keys) && !empty($cache_relation_keys)) {
foreach ($cache_relation_keys as $key) {
$cache_info = cache_load($key);
if (!empty($cache_info)) {
$sql = 'DELETE FROM ' . tablename('core_cache') . ' WHERE `key`=:key';
$params = array();
$params[':key'] = $key;
$result = pdo_query($sql, $params);
if (!$result) {
return error(1, '缓存:' . $key . ' 删除失败!');
}
}
}
return true;
}
}
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 {
$cache_relation_keys = cache_relation_keys($prefix);
if (is_error($cache_relation_keys)) {
return $cache_relation_keys;
}
if (is_array($cache_relation_keys) && !empty($cache_relation_keys)) {
foreach ($cache_relation_keys as $key) {
preg_match_all('/\:([a-zA-Z0-9\-\_]+)/', $key, $matches);
$sql = 'DELETE FROM ' . tablename('core_cache') . ' WHERE `key` LIKE :key';
$params = array();
$params[':key'] = "we7:{$matches[1][0]}%";
$result = pdo_query($sql, $params);
if (!$result) {
return error(-1, '缓存 ' . $key . '删除失败!');
}
}
}
}
return true;
}

153
framework/function/cache.redis.func.php

@ -0,0 +1,153 @@
<?php
defined('IN_IA') or exit('Access Denied');
function cache_redis() {
global $_W;
static $redisobj;
if (!extension_loaded('redis')) {
return error(1, 'Class Redis is not found');
}
$config = $_W['config']['setting']['redis'];
if (empty($redisobj)) {
$redisobj = new Redis();
try {
if ($config['pconnect']) {
$connect = $redisobj->pconnect($config['server'], $config['port']);
} else {
$connect = $redisobj->connect($config['server'], $config['port']);
}
if (!empty($config['requirepass'])) {
$auth = $redisobj->auth($config['requirepass']);
}
} catch (Exception $e) {
return error(-1, 'redis连接失败,错误信息:' . $e->getMessage());
}
}
if (defined('IN_MODULE') && !empty($config['db']) && is_array($config['db']) && in_array(IN_MODULE, array_keys($config['db']))) {
$redisobj->select($config['db'][IN_MODULE]);
}
return $redisobj;
}
function cache_read($key) {
$redis = cache_redis();
if (is_error($redis)) {
return $redis;
}
if ($redis->exists(cache_prefix($key))) {
$data = $redis->get(cache_prefix($key));
$data = iunserializer($data);
return $data;
}
return '';
}
function cache_search($key) {
$redis = cache_redis();
if (is_error($redis)) {
return $redis;
}
$search_keys = $redis->keys(cache_prefix($key) . '*');
$search_data = array();
if (!empty($search_keys)) {
foreach ($search_keys as $search_key => $search_value) {
$search_data[$search_value] = iunserializer($redis->get($search_value));
}
}
return $search_data;
}
function cache_write($key, $value, $ttl = CACHE_EXPIRE_LONG) {
$redis = cache_redis();
if (is_error($redis)) {
return $redis;
}
$value = iserializer($value);
if ($redis->set(cache_prefix($key), $value, $ttl)) {
return true;
}
return false;
}
function cache_delete($key) {
$redis = cache_redis();
if (is_error($redis)) {
return $redis;
}
$cache_relation_keys = cache_relation_keys($key);
if (is_error($cache_relation_keys)) {
return $cache_relation_keys;
}
if (is_array($cache_relation_keys) && !empty($cache_relation_keys)) {
foreach ($cache_relation_keys as $key) {
$cache_info = cache_load($key);
if (!empty($cache_info)) {
if (method_exists($redis, 'del')) {
$result = $redis->del(cache_prefix($key));
} else {
$result = $redis->delete(cache_prefix($key));
}
if ($result) {
unset($GLOBALS['_W']['cache'][$key]);
} else {
return error(1, '缓存:' . $key . ' 删除失败!');
}
}
}
}
return true;
}
function cache_clean($key = '') {
$redis = cache_redis();
if (is_error($redis)) {
return $redis;
}
if (!empty($key)) {
$cache_relation_keys = cache_relation_keys($key);
if (is_error($cache_relation_keys)) {
return $cache_relation_keys;
}
if (is_array($cache_relation_keys) && !empty($cache_relation_keys)) {
foreach ($cache_relation_keys as $key) {
preg_match_all('/\:([a-zA-Z0-9\-\_]+)/', $key, $matches);
if ($keys = $redis->keys(cache_prefix('we7:' . $matches[1][0]) . '*')) {
unset($GLOBALS['_W']['cache']);
$res = $redis->delete($keys);
if (!$res) {
return error(-1, '缓存 ' . $key . ' 删除失败');
}
}
}
}
return true;
}
if ($redis->flushDB()) {
unset($GLOBALS['_W']['cache']);
return true;
}
return false;
}
function cache_prefix($key) {
return $GLOBALS['_W']['config']['setting']['authkey'] . $key;
}

500
framework/function/communication.func.php

@ -0,0 +1,500 @@
<?php
defined('IN_IA') or exit('Access Denied');
function ihttp_request($url, $post = '', $extra = array(), $timeout = 60) {
if (function_exists('curl_init') && function_exists('curl_exec') && $timeout > 0) {
$ch = ihttp_build_curl($url, $post, $extra, $timeout);
if (is_error($ch)) {
return $ch;
}
$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($errno, $error);
} else {
return ihttp_response_parse($data);
}
}
$urlset = ihttp_parse_url($url, true);
if (!empty($urlset['ip'])) {
$urlset['host'] = $urlset['ip'];
}
$body = ihttp_build_httpbody($url, $post, $extra);
if ('https' == $urlset['scheme']) {
$fp = ihttp_socketopen('ssl://' . $urlset['host'], $urlset['port'], $errno, $error);
} else {
$fp = ihttp_socketopen($urlset['host'], $urlset['port'], $errno, $error);
}
stream_set_blocking($fp, $timeout > 0 ? true : false);
stream_set_timeout($fp, ini_get('default_socket_timeout'));
if (!$fp) {
return error(1, $error);
} else {
fwrite($fp, $body);
$content = '';
if ($timeout > 0) {
while (!feof($fp)) {
$content .= fgets($fp, 512);
}
}
fclose($fp);
return ihttp_response_parse($content, true);
}
}
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);
}
function ihttp_multi_request($urls, $posts = array(), $extra = array(), $timeout = 60) {
if (!is_array($urls)) {
return error(1, '请使用ihttp_request函数');
}
$curl_multi = curl_multi_init();
$curl_client = $response = array();
foreach ($urls as $i => $url) {
if (isset($posts[$i]) && is_array($posts[$i])) {
$post = $posts[$i];
} else {
$post = $posts;
}
if (!empty($url)) {
$curl = ihttp_build_curl($url, $post, $extra, $timeout);
if (is_error($curl)) {
continue;
}
if (CURLM_OK === curl_multi_add_handle($curl_multi, $curl)) {
$curl_client[] = $curl;
}
}
}
if (!empty($curl_client)) {
$active = null;
do {
$mrc = curl_multi_exec($curl_multi, $active);
} while (CURLM_CALL_MULTI_PERFORM == $mrc);
while ($active && CURLM_OK == $mrc) {
do {
$mrc = curl_multi_exec($curl_multi, $active);
} while (CURLM_CALL_MULTI_PERFORM == $mrc);
}
}
foreach ($curl_client as $i => $curl) {
$response[$i] = curl_multi_getcontent($curl);
curl_multi_remove_handle($curl_multi, $curl);
}
curl_multi_close($curl_multi);
return $response;
}
function ihttp_socketopen($hostname, $port = 80, &$errno, &$errstr, $timeout = 15) {
$fp = '';
if (function_exists('fsockopen')) {
$fp = @fsockopen($hostname, $port, $errno, $errstr, $timeout);
} elseif (function_exists('pfsockopen')) {
$fp = @pfsockopen($hostname, $port, $errno, $errstr, $timeout);
} elseif (function_exists('stream_socket_client')) {
$fp = @stream_socket_client($hostname . ':' . $port, $errno, $errstr, $timeout);
}
return $fp;
}
function ihttp_response_parse($data, $chunked = false) {
$rlt = array();
$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+) (.*)$/', $split2[0], $matches);
$rlt['code'] = !empty($matches[2]) ? $matches[2] : 200;
$rlt['status'] = !empty($matches[3]) ? $matches[3] : 'OK';
$rlt['responseline'] = !empty($split2[0]) ? $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 (isset($rlt['headers'][$key]) && 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 && 'content-encoding' == strtolower($key) && 'gzip' == strtolower($value)) {
$isgzip = true;
}
if (!$ischunk && 'transfer-encoding' == strtolower($key) && 'chunked' == strtolower($value)) {
$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 ('100' == $rlt['code']) {
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 (false === $pos) {
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_parse_url($url, $set_default_port = false) {
if (empty($url)) {
return error(1);
}
$urlset = parse_url($url);
if (!empty($urlset['scheme']) && !in_array($urlset['scheme'], array('http', 'https'))) {
return error(1, '只能使用 http 及 https 协议');
}
if (empty($urlset['path'])) {
$urlset['path'] = '/';
}
if (!empty($urlset['query'])) {
$urlset['query'] = "?{$urlset['query']}";
}
if (strexists($url, 'https://') && !extension_loaded('openssl')) {
if (!extension_loaded('openssl')) {
return error(1, '请开启您PHP环境的openssl', '');
}
}
if (empty($urlset['host'])) {
$current_url = parse_url($GLOBALS['_W']['siteroot']);
$urlset['host'] = $current_url['host'];
$urlset['scheme'] = $current_url['scheme'];
$urlset['path'] = $current_url['path'] . 'web/' . str_replace('./', '', $urlset['path']);
$urlset['ip'] = '127.0.0.1';
} elseif (!ihttp_allow_host($urlset['host'])) {
return error(1, 'host 非法');
}
if ($set_default_port && empty($urlset['port'])) {
$urlset['port'] = 'https' == $urlset['scheme'] ? '443' : '80';
}
return $urlset;
}
function ihttp_allow_host($host) {
global $_W;
if (strexists($host, '@')) {
return false;
}
$pattern = '/^(10|172|192|127)/';
if (preg_match($pattern, $host) && isset($_W['setting']['ip_white_list'])) {
$ip_white_list = $_W['setting']['ip_white_list'];
if ($ip_white_list && isset($ip_white_list[$host]) && !$ip_white_list[$host]['status']) {
return false;
}
}
return true;
}
function ihttp_build_curl($url, $post, $extra, $timeout) {
if (!function_exists('curl_init') || !function_exists('curl_exec')) {
return error(1, 'curl扩展未开启');
}
$urlset = ihttp_parse_url($url);
if (is_error($urlset)) {
return $urlset;
}
if (!empty($urlset['ip'])) {
$extra['ip'] = $urlset['ip'];
}
$ch = curl_init();
if (!empty($extra['ip'])) {
$extra['Host'] = $urlset['host'];
$urlset['host'] = $extra['ip'];
unset($extra['ip']);
}
curl_setopt($ch, CURLOPT_URL, $urlset['scheme'] . '://' . $urlset['host'] . (empty($urlset['port']) || '80' == $urlset['port'] ? '' : ':' . $urlset['port']) . $urlset['path'] . (!empty($urlset['query']) ? $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_1);
if ($post) {
if (is_array($post)) {
$filepost = false;
foreach ($post as $name => &$value) {
if (version_compare(phpversion(), '5.5') >= 0 && is_string($value) && '@' == substr($value, 0, 1)) {
$post[$name] = new CURLFile(ltrim($value, '@'));
}
if ((is_string($value) && '@' == substr($value, 0, 1)) || (class_exists('CURLFile') && $value instanceof CURLFile)) {
$filepost = true;
}
}
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);
}
}
return $ch;
}
function ihttp_build_httpbody($url, $post, $extra) {
$urlset = ihttp_parse_url($url, true);
if (is_error($urlset)) {
return $urlset;
}
if (!empty($urlset['ip'])) {
$extra['ip'] = $urlset['ip'];
}
$body = '';
if (!empty($post) && is_array($post)) {
$filepost = false;
$boundary = random(40);
foreach ($post as $name => &$value) {
if ((is_string($value) && '@' == substr($value, 0, 1)) && file_exists(ltrim($value, '@'))) {
$filepost = true;
$file = ltrim($value, '@');
$body .= "--$boundary\r\n";
$body .= 'Content-Disposition: form-data; name="' . $name . '"; filename="' . basename($file) . '"; Content-Type: application/octet-stream' . "\r\n\r\n";
$body .= file_get_contents($file) . "\r\n";
} else {
$body .= "--$boundary\r\n";
$body .= 'Content-Disposition: form-data; name="' . $name . '"' . "\r\n\r\n";
$body .= $value . "\r\n";
}
}
if (!$filepost) {
$body = http_build_query($post, '', '&');
} else {
$body .= "--$boundary\r\n";
}
}
$method = empty($post) ? 'GET' : 'POST';
$fdata = "{$method} {$urlset['path']}{$urlset['query']} HTTP/1.1\r\n";
$fdata .= "Accept: */*\r\n";
$fdata .= "Accept-Language: zh-cn\r\n";
if ('POST' == $method) {
$fdata .= empty($filepost) ? "Content-Type: application/x-www-form-urlencoded\r\n" : "Content-Type: multipart/form-data; boundary=$boundary\r\n";
}
$fdata .= "Host: {$urlset['host']}\r\n";
$fdata .= "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1\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";
}
}
}
if ($body) {
$fdata .= 'Content-Length: ' . strlen($body) . "\r\n\r\n{$body}";
} else {
$fdata .= "\r\n";
}
return $fdata;
}
function ihttp_email($to, $subject, $body, $global = false) {
static $mailer;
set_time_limit(0);
if (empty($mailer)) {
if (!class_exists('PHPMailer')) {
load()->library('phpmailer');
}
$mailer = new PHPMailer();
global $_W;
$config = $GLOBALS['_W']['setting']['mail'];
if (!$global) {
$row = pdo_get('uni_settings', array('uniacid' => $_W['uniacid']), array('notify'));
$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;
} elseif ($config['smtp']['type'] == 'qq') {
$config['smtp']['server'] = 'ssl://smtp.qq.com';
$config['smtp']['port'] = 465;
} 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 ($body) {
if (is_array($body)) {
$newbody = '';
foreach ($body as $value) {
if ('@' == substr($value, 0, 1)) {
if (!is_file($file = ltrim($value, '@'))) {
return error(1, $file . ' 附件不存在或非文件!');
}
$mailer->addAttachment($file);
} else {
$newbody .= $value . '\n';
}
}
$body = $newbody;
} else {
if ('@' == substr($body, 0, 1)) {
$mailer->addAttachment(ltrim($body, '@'));
$body = '';
}
}
}
if (!empty($mailer->signature)) {
$body .= htmlspecialchars_decode($mailer->signature);
}
$mailer->Subject = $subject;
$mailer->Body = $body;
$mailer->addAddress($to);
$result = $mailer->send();
$mailer->clearAddresses();
$mailer->clearReplyTos();
if ($result) {
return true;
} else {
return error(1, $mailer->ErrorInfo);
}
}

139
framework/function/compat.biz.func.php

@ -0,0 +1,139 @@
<?php
defined('IN_IA') or exit('Access Denied');
if (isset($_W['uniacid'])) {
$_W['weid'] = $_W['uniacid'];
}
if (isset($_W['openid'])) {
$_W['fans']['from_user'] = $_W['openid'];
}
if (isset($_W['member']['uid'])) {
if (empty($_W['fans']['from_user'])) {
$_W['fans']['from_user'] = $_W['member']['uid'];
}
}
if (!function_exists('fans_search')) {
function fans_search($user, $fields = array()) {
global $_W;
load()->model('mc');
$uid = intval($user);
if (empty($uid)) {
$uid = pdo_fetchcolumn('SELECT uid FROM ' . tablename('mc_mapping_fans') . ' WHERE openid = :openid AND uniacid = :uniacid', array(':openid' => $user, ':uniacid' => $_W['uniacid']));
if (empty($uid)) {
return array(); }
}
return mc_fetch($uid, $fields);
}
}
if (!function_exists('fans_fields')) {
function fans_fields() {
load()->model('mc');
return mc_fields();
}
}
if (!function_exists('fans_update')) {
function fans_update($user, $fields) {
global $_W;
load()->model('mc');
$uid = intval($user);
if (empty($uid)) {
$uid = pdo_fetchcolumn('SELECT uid FROM ' . tablename('mc_mapping_fans') . ' WHERE openid = :openid AND uniacid = :uniacid', array(':openid' => $user, ':uniacid' => $_W['uniacid']));
if (empty($uid)) {
return false; }
}
return mc_update($uid, $fields);
}
}
if (!function_exists('create_url')) {
function create_url($segment = '', $params = array(), $noredirect = false) {
return url($segment, $params, $noredirect);
}
}
if (!function_exists('toimage')) {
function toimage($src) {
return tomedia($src);
}
}
if (!function_exists('uni_setting')) {
function uni_setting($uniacid = 0, $fields = '*', $force_update = false) {
global $_W;
load()->model('account');
if ('*' == $fields) {
$fields = '';
}
return uni_setting_load($fields, $uniacid);
}
}
if (!function_exists('activity_token_owned')) {
function activity_token_owned($uid, $filter = array(), $pindex = 1, $psize = 10) {
return activity_coupon_owned();
}
}
if (!function_exists('activity_token_info')) {
function activity_token_info($couponid, $uniacid) {
return activity_coupon_info($couponid);
}
}
if (!function_exists('activity_token_grant')) {
function activity_token_grant($uid, $couponid, $module = '', $remark = '') {
return activity_coupon_grant($couponid, $uid);
}
}
if (!function_exists('activity_token_use')) {
function activity_token_use($uid, $couponid, $operator, $clerk_id = 0, $recid = '', $module = 'system', $clerk_type = 1, $store_id = 0) {
return activity_coupon_use($couponid, $recid, $module);
}
}
if (!function_exists('activity_token_available')) {
function activity_token_available($uid, $pindex = 1, $psize = 0) {
return activity_coupon_available();
}
}
if (!function_exists('uni_user_permission')) {
function uni_user_permission($type = 'system') {
return permission_account_user($type);
}
}
if (!function_exists('uni_permission')) {
function uni_permission($uid = 0, $uniacid = 0) {
return permission_account_user_role($uid, $uniacid);
}
}
if (!function_exists('uni_user_permission_exist')) {
function uni_user_permission_exist($uid = 0, $uniacid = 0) {
return permission_account_user_permission_exist($uid, $uniacid);
}
}
if (!function_exists('uni_user_permission_check')) {
function uni_user_permission_check($permission_name = '', $show_message = true, $action = '') {
return permission_check_account_user($permission_name, $show_message, $action);
}
}
if (!defined('CACHE_KEY_MODULE_SETTING')) {
define('CACHE_KEY_MODULE_SETTING', 'module_setting:%s:%s');
}
if (!function_exists('uni_accounts')) {
function uni_accounts($uniacid = 0) {
global $_W;
$uniacid = empty($uniacid) ? $_W['uniacid'] : intval($uniacid);
$account_info = pdo_get('account', array('uniacid' => $uniacid));
if (!empty($account_info)) {
$account_tablename = uni_account_type($account_info['type']);
$account_tablename = $account_tablename['table_name'];
$accounts = pdo_fetchall("SELECT w.*, a.type, a.isconnect FROM " . tablename('account') . " a INNER JOIN " . tablename($account_tablename) . " w USING(acid) WHERE a.uniacid = :uniacid AND a.isdeleted <> 1 ORDER BY a.acid ASC", array(':uniacid' => $uniacid), 'acid');
}
return !empty($accounts) ? $accounts : array();
}
}

173
framework/function/compat.func.php

@ -0,0 +1,173 @@
<?php
defined('IN_IA') or exit('Access Denied');
if (!function_exists('json_encode')) {
function json_encode($value) {
static $jsonobj;
if (!isset($jsonobj)) {
load()->library('json');
$jsonobj = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
}
return $jsonobj->encode($value);
}
}
if (!function_exists('json_decode')) {
function json_decode($jsonString) {
static $jsonobj;
if (!isset($jsonobj)) {
load()->library('json');
$jsonobj = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
}
return $jsonobj->decode($jsonString);
}
}
if (!function_exists('http_build_query')) {
function http_build_query($formdata, $numeric_prefix = null, $arg_separator = null) {
if (!is_array($formdata)) {
return false;
}
if (null == $arg_separator) {
$arg_separator = '&';
}
return http_build_recursive($formdata, $arg_separator);
}
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);
}
}
if (!defined('JSON_UNESCAPED_UNICODE')) {
define('JSON_UNESCAPED_UNICODE', 256);
}
if (!function_exists('hex2bin')) {
function hex2bin($str) {
$sbin = '';
$len = strlen($str);
for ($i = 0; $i < $len; $i += 2) {
$sbin .= pack('H*', substr($str, $i, 2));
}
return $sbin;
}
}
if (!function_exists('mb_strlen')) {
function mb_strlen($string, $charset = '') {
return istrlen($string, $charset);
}
}
if (!interface_exists('SessionHandlerInterface')) {
interface SessionHandlerInterface {
}
}
if (!function_exists('fastcgi_finish_request')) {
function fastcgi_finish_request() {
return error(-1, 'Not npm or fast cgi');
}
}
if (!function_exists('openssl_decrypt')) {
function openssl_decrypt($ciphertext_dec, $method, $key, $options, $iv) {
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
mcrypt_generic_init($module, $key, $iv);
$decrypted = mdecrypt_generic($module, $ciphertext_dec);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
return $decrypted;
}
}
if (!function_exists('openssl_encrypt')) {
function openssl_encrypt($text, $method, $key, $options, $iv) {
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
mcrypt_generic_init($module, $key, $iv);
$encrypted = mcrypt_generic($module, $text);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
return $encrypted;
}
}
if (!function_exists('array_column')) {
function array_column($input, $columnKey, $indexKey = null) {
$columnKeyIsNumber = (is_numeric($columnKey)) ? true : false;
$indexKeyIsNull = (is_null($indexKey)) ? true : false;
$indexKeyIsNumber = (is_numeric($indexKey)) ? true : false;
$result = array();
foreach ((array) $input as $key => $row) {
if ($columnKeyIsNumber) {
$tmp = array_slice($row, $columnKey, 1);
$tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : null;
} else {
$tmp = isset($row[$columnKey]) ? $row[$columnKey] : null;
}
if (!$indexKeyIsNull) {
if ($indexKeyIsNumber) {
$key = array_slice($row, $indexKey, 1);
$key = (is_array($key) && !empty($key)) ? current($key) : null;
$key = is_null($key) ? 0 : $key;
} else {
$key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
}
}
$result[$key] = $tmp;
}
return $result;
}
}
if (!function_exists('boolval')) {
function boolval($val) {
return (bool) $val;
}
}

320
framework/function/db.func.php

@ -0,0 +1,320 @@
<?php
defined('IN_IA') or exit('Access Denied');
$GLOBALS['_W']['config']['db']['tablepre'] = empty($GLOBALS['_W']['config']['db']['tablepre']) ? $GLOBALS['_W']['config']['db']['master']['tablepre'] : $GLOBALS['_W']['config']['db']['tablepre'];
function db_table_schema($db, $tablename = '') {
$result = $db->fetch("SHOW TABLE STATUS LIKE '" . trim($db->tablename($tablename), '`') . "'");
if (empty($result)) {
return array();
}
$ret['tablename'] = $result['Name'];
$ret['charset'] = $result['Collation'];
$ret['engine'] = $result['Engine'];
$ret['increment'] = $result['Auto_increment'];
$result = $db->fetchall('SHOW FULL COLUMNS FROM ' . $db->tablename($tablename));
foreach ($result as $value) {
$temp = array();
$type = explode(' ', $value['Type'], 2);
$temp['name'] = $value['Field'];
$pieces = explode('(', $type[0], 2);
$temp['type'] = $pieces[0];
$temp['length'] = rtrim($pieces[1], ')');
$temp['null'] = 'NO' != $value['Null'];
$temp['signed'] = empty($type[1]);
$temp['increment'] = 'auto_increment' == $value['Extra'];
$ret['fields'][$value['Field']] = $temp;
}
$result = $db->fetchall('SHOW INDEX FROM ' . $db->tablename($tablename));
foreach ($result as $value) {
$ret['indexes'][$value['Key_name']]['name'] = $value['Key_name'];
$ret['indexes'][$value['Key_name']]['type'] = ('PRIMARY' == $value['Key_name']) ? 'primary' : (0 == $value['Non_unique'] ? 'unique' : 'index');
$ret['indexes'][$value['Key_name']]['fields'][] = $value['Column_name'];
}
return $ret;
}
function db_table_serialize($db, $dbname) {
$tables = $db->fetchall('SHOW TABLES');
if (empty($tables)) {
return '';
}
$struct = array();
foreach ($tables as $value) {
$structs[] = db_table_schema($db, substr($value['Tables_in_' . $dbname], strpos($value['Tables_in_' . $dbname], '_') + 1));
}
return iserializer($structs);
}
function db_table_create_sql($schema) {
$pieces = explode('_', $schema['charset']);
$charset = $pieces[0];
$engine = $schema['engine'];
$schema['tablename'] = str_replace('ims_', $GLOBALS['_W']['config']['db']['tablepre'], $schema['tablename']);
$sql = "CREATE TABLE IF NOT EXISTS `{$schema['tablename']}` (\n";
foreach ($schema['fields'] as $value) {
$piece = _db_build_field_sql($value);
$sql .= "`{$value['name']}` {$piece},\n";
}
foreach ($schema['indexes'] as $value) {
$fields = implode('`,`', $value['fields']);
if ('index' == $value['type']) {
$sql .= "KEY `{$value['name']}` (`{$fields}`),\n";
}
if ('unique' == $value['type']) {
$sql .= "UNIQUE KEY `{$value['name']}` (`{$fields}`),\n";
}
if ('primary' == $value['type']) {
$sql .= "PRIMARY KEY (`{$fields}`),\n";
}
}
$sql = rtrim($sql);
$sql = rtrim($sql, ',');
$sql .= "\n) ENGINE=$engine DEFAULT CHARSET=$charset;\n\n";
return $sql;
}
function db_schema_compare($table1, $table2) {
$table1['charset'] == $table2['charset'] ? '' : $ret['diffs']['charset'] = true;
$fields1 = array_keys($table1['fields']);
$fields2 = array_keys($table2['fields']);
$diffs = array_diff($fields1, $fields2);
if (!empty($diffs)) {
$ret['fields']['greater'] = array_values($diffs);
}
$diffs = array_diff($fields2, $fields1);
if (!empty($diffs)) {
$ret['fields']['less'] = array_values($diffs);
}
$diffs = array();
$intersects = array_intersect($fields1, $fields2);
if (!empty($intersects)) {
foreach ($intersects as $field) {
if ($table1['fields'][$field] != $table2['fields'][$field]) {
$diffs[] = $field;
}
}
}
if (!empty($diffs)) {
$ret['fields']['diff'] = array_values($diffs);
}
$indexes1 = is_array($table1['indexes']) ? array_keys($table1['indexes']) : array();
$indexes2 = is_array($table2['indexes']) ? array_keys($table2['indexes']) : array();
$diffs = array_diff($indexes1, $indexes2);
if (!empty($diffs)) {
$ret['indexes']['greater'] = array_values($diffs);
}
$diffs = array_diff($indexes2, $indexes1);
if (!empty($diffs)) {
$ret['indexes']['less'] = array_values($diffs);
}
$diffs = array();
$intersects = array_intersect($indexes1, $indexes2);
if (!empty($intersects)) {
foreach ($intersects as $index) {
if ($table1['indexes'][$index] != $table2['indexes'][$index]) {
$diffs[] = $index;
}
}
}
if (!empty($diffs)) {
$ret['indexes']['diff'] = array_values($diffs);
}
return $ret;
}
function db_table_fix_sql($schema1, $schema2, $strict = false) {
if (empty($schema1)) {
return array(db_table_create_sql($schema2));
}
$diff = $result = db_schema_compare($schema1, $schema2);
if (!empty($diff['diffs']['tablename'])) {
return array(db_table_create_sql($schema2));
}
$sqls = array();
if (!empty($diff['diffs']['engine'])) {
$sqls[] = "ALTER TABLE `{$schema1['tablename']}` ENGINE = {$schema2['engine']}";
}
if (!empty($diff['diffs']['charset'])) {
$pieces = explode('_', $schema2['charset']);
$charset = $pieces[0];
$sqls[] = "ALTER TABLE `{$schema1['tablename']}` DEFAULT CHARSET = {$charset}";
}
if (!empty($diff['fields'])) {
if (!empty($diff['fields']['less'])) {
foreach ($diff['fields']['less'] as $fieldname) {
$field = $schema2['fields'][$fieldname];
$piece = _db_build_field_sql($field);
if (!empty($field['rename']) && !empty($schema1['fields'][$field['rename']])) {
$sql = "ALTER TABLE `{$schema1['tablename']}` CHANGE `{$field['rename']}` `{$field['name']}` {$piece}";
unset($schema1['fields'][$field['rename']]);
} else {
if ($field['position']) {
$pos = ' ' . $field['position'];
}
$sql = "ALTER TABLE `{$schema1['tablename']}` ADD `{$field['name']}` {$piece}{$pos}";
}
$primary = array();
$isincrement = array();
if (strexists($sql, 'AUTO_INCREMENT')) {
$isincrement = $field;
$sql = str_replace('AUTO_INCREMENT', '', $sql);
foreach ($schema1['fields'] as $field) {
if (1 == $field['increment']) {
$primary = $field;
break;
}
}
if (!empty($primary)) {
$piece = _db_build_field_sql($primary);
if (!empty($piece)) {
$piece = str_replace('AUTO_INCREMENT', '', $piece);
}
$sqls[] = "ALTER TABLE `{$schema1['tablename']}` CHANGE `{$primary['name']}` `{$primary['name']}` {$piece}";
}
}
$sqls[] = $sql;
}
}
if (!empty($diff['fields']['diff'])) {
foreach ($diff['fields']['diff'] as $fieldname) {
$field = $schema2['fields'][$fieldname];
$piece = _db_build_field_sql($field);
if (!empty($schema1['fields'][$fieldname])) {
$sqls[] = "ALTER TABLE `{$schema1['tablename']}` CHANGE `{$field['name']}` `{$field['name']}` {$piece}";
}
}
}
if ($strict && !empty($diff['fields']['greater'])) {
foreach ($diff['fields']['greater'] as $fieldname) {
if (!empty($schema1['fields'][$fieldname])) {
$sqls[] = "ALTER TABLE `{$schema1['tablename']}` DROP `{$fieldname}`";
}
}
}
}
if (!empty($diff['indexes'])) {
if (!empty($diff['indexes']['less'])) {
foreach ($diff['indexes']['less'] as $indexname) {
$index = $schema2['indexes'][$indexname];
$piece = _db_build_index_sql($index);
$sqls[] = "ALTER TABLE `{$schema1['tablename']}` ADD {$piece}";
}
}
if (!empty($diff['indexes']['diff'])) {
foreach ($diff['indexes']['diff'] as $indexname) {
$index = $schema2['indexes'][$indexname];
$piece = _db_build_index_sql($index);
$sqls[] = "ALTER TABLE `{$schema1['tablename']}` DROP " . ('PRIMARY' == $indexname ? ' PRIMARY KEY ' : "INDEX {$indexname}") . ", ADD {$piece}";
}
}
if ($strict && !empty($diff['indexes']['greater'])) {
foreach ($diff['indexes']['greater'] as $indexname) {
$sqls[] = "ALTER TABLE `{$schema1['tablename']}` DROP `{$indexname}`";
}
}
}
if (!empty($isincrement)) {
$piece = _db_build_field_sql($isincrement);
$sqls[] = "ALTER TABLE `{$schema1['tablename']}` CHANGE `{$isincrement['name']}` `{$isincrement['name']}` {$piece}";
}
return $sqls;
}
function _db_build_index_sql($index) {
$piece = '';
$fields = implode('`,`', $index['fields']);
if ('index' == $index['type']) {
$piece .= " INDEX `{$index['name']}` (`{$fields}`)";
}
if ('unique' == $index['type']) {
$piece .= "UNIQUE `{$index['name']}` (`{$fields}`)";
}
if ('primary' == $index['type']) {
$piece .= "PRIMARY KEY (`{$fields}`)";
}
return $piece;
}
function _db_build_field_sql($field) {
if (!empty($field['length'])) {
$length = "({$field['length']})";
} else {
$length = '';
}
if (false !== strpos(strtolower($field['type']), 'int') || in_array(strtolower($field['type']), array('decimal', 'float', 'dobule'))) {
$signed = empty($field['signed']) ? ' unsigned' : '';
} else {
$signed = '';
}
if (empty($field['null'])) {
$null = ' NOT NULL';
} else {
$null = '';
}
if (isset($field['default'])) {
$default = " DEFAULT '" . $field['default'] . "'";
} else {
$default = '';
}
if ($field['increment']) {
$increment = ' AUTO_INCREMENT';
} else {
$increment = '';
}
return "{$field['type']}{$length}{$signed}{$null}{$default}{$increment}";
}
function db_table_schemas($table) {
$dump = "DROP TABLE IF EXISTS {$table};\n";
$sql = "SHOW CREATE TABLE {$table}";
$row = pdo_fetch($sql);
$dump .= $row['Create Table'];
$dump .= ";\n\n";
return $dump;
}
function db_table_insert_sql($tablename, $start, $size) {
$data = '';
$tmp = '';
$sql = "SELECT * FROM {$tablename} LIMIT {$start}, {$size}";
$result = pdo_fetchall($sql);
if (!empty($result)) {
foreach ($result as $row) {
$tmp .= '(';
foreach ($row as $k => $v) {
$value = str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $v);
$tmp .= "'" . $value . "',";
}
$tmp = rtrim($tmp, ',');
$tmp .= "),\n";
}
$tmp = rtrim($tmp, ",\n");
$data .= "INSERT INTO {$tablename} VALUES \n{$tmp};\n";
$datas = array(
'data' => $data,
'result' => $result,
);
return $datas;
} else {
return false;
}
}

891
framework/function/file.func.php

@ -0,0 +1,891 @@
<?php
defined('IN_IA') or exit('Access Denied');
function file_write($filename, $data) {
global $_W;
$filename = ATTACHMENT_ROOT . '/' . $filename;
mkdirs(dirname($filename));
file_put_contents($filename, $data);
@chmod($filename, $_W['config']['setting']['filemode']);
return is_file($filename);
}
function file_read($filename) {
$filename = ATTACHMENT_ROOT . '/' . $filename;
if (!is_file($filename)) {
return false;
}
return file_get_contents($filename);
}
function file_move($filename, $dest) {
global $_W;
mkdirs(dirname($dest));
if (is_uploaded_file($filename)) {
move_uploaded_file($filename, $dest);
} else {
rename($filename, $dest);
}
@chmod($filename, $_W['config']['setting']['filemode']);
return is_file($dest);
}
function file_tree($path, $include = array()) {
$files = array();
if (!empty($include)) {
$ds = glob($path . '/{' . implode(',', $include) . '}', GLOB_BRACE);
} else {
$ds = glob($path . '/*');
}
if (is_array($ds)) {
foreach ($ds as $entry) {
if (is_file($entry)) {
$files[] = $entry;
}
if (is_dir($entry)) {
$rs = file_tree($entry);
foreach ($rs as $f) {
$files[] = $f;
}
}
}
}
return $files;
}
function file_tree_limit($path, $limit = 0, $acquired_files_count = 0) {
$files = array();
if (is_dir($path)) {
if ($dir = opendir($path)) {
while (false !== ($file = readdir($dir))) {
if (in_array($file, array('.', '..'))) {
continue;
}
if (is_file($path . '/' . $file)) {
$files[] = $path . '/' . $file;
++$acquired_files_count;
if ($limit > 0 && $acquired_files_count >= $limit) {
closedir($dir);
return $files;
}
}
if (is_dir($path . '/' . $file)) {
$rs = file_tree_limit($path . '/' . $file, $limit, $acquired_files_count);
foreach ($rs as $f) {
$files[] = $f;
++$acquired_files_count;
if ($limit > 0 && $acquired_files_count >= $limit) {
closedir($dir);
return $files;
}
}
}
}
closedir($dir);
}
}
return $files;
}
function file_dir_exist_image($path) {
if (is_dir($path)) {
if ($dir = opendir($path)) {
while (false !== ($file = readdir($dir))) {
if (in_array($file, array('.', '..'))) {
continue;
}
if (is_file($path . '/' . $file) && $path != (ATTACHMENT_ROOT . 'images') && file_is_image($path . '/' . $file)) {
if (0 === strpos($path, ATTACHMENT_ROOT)) {
$attachment = str_replace(ATTACHMENT_ROOT . 'images/', '', $path . '/' . $file);
list($file_account) = explode('/', $attachment);
if ('global' == $file_account) {
continue;
}
}
closedir($dir);
return true;
}
if (is_dir($path . '/' . $file) && file_dir_exist_image($path . '/' . $file)) {
closedir($dir);
return true;
}
}
closedir($dir);
}
}
return false;
}
function mkdirs($path) {
if (!is_dir($path)) {
mkdirs(dirname($path));
mkdir($path);
}
return is_dir($path);
}
function file_copy($src, $des, $filter) {
$dir = opendir($src);
@mkdir($des);
while (false !== ($file = readdir($dir))) {
if (('.' != $file) && ('..' != $file)) {
if (is_dir($src . '/' . $file)) {
file_copy($src . '/' . $file, $des . '/' . $file, $filter);
} elseif (!in_array(substr($file, strrpos($file, '.') + 1), $filter)) {
copy($src . '/' . $file, $des . '/' . $file);
}
}
}
closedir($dir);
}
function rmdirs($path, $clean = false) {
if (!is_dir($path)) {
return false;
}
$files = glob($path . '/*');
if ($files) {
foreach ($files as $file) {
is_dir($file) ? rmdirs($file) : @unlink($file);
}
}
return $clean ? true : @rmdir($path);
}
function file_upload($file, $type = 'image', $name = '', $compress = false) {
load()->model('system');
$harmtype = array('asp', 'php', 'jsp', 'js', 'css', 'php3', 'php4', 'php5', 'ashx', 'aspx', 'exe', 'cgi');
if (empty($file)) {
return error(-1, '没有上传内容');
}
if (!in_array($type, array('image', 'thumb', 'voice', 'video', 'audio'))) {
return error(-2, '未知的上传类型');
}
global $_W;
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$ext = strtolower($ext);
$setting = setting_load('upload');
switch ($type) {
case 'image':
case 'thumb':
$allowExt = array('gif', 'jpg', 'jpeg', 'bmp', 'png', 'ico');
$limit = $setting['upload']['image']['limit'];
break;
case 'voice':
case 'audio':
$allowExt = array('mp3', 'wma', 'wav', 'amr');
$limit = $setting['upload']['audio']['limit'];
break;
case 'video':
$allowExt = array('rm', 'rmvb', 'wmv', 'avi', 'mpg', 'mpeg', 'mp4');
$limit = $setting['upload']['audio']['limit'];
break;
}
$type_setting = in_array($type, array('image', 'thumb')) ? 'image' : 'audio';
// $setting = $_W['setting']['upload'][$type_setting];
// if (!empty($setting['extentions'])) {
// $allowExt = $setting['extentions'];
// }
if (!in_array(strtolower($ext), $allowExt) || in_array(strtolower($ext), $harmtype)) {
return error(-3, '不允许上传此类文件');
}
if (!empty($limit) && $limit * 1024 < filesize($file['tmp_name'])) {
return error(-4, "上传的文件超过大小限制,请上传小于 {$limit}k 的文件");
}
$result = array();
if (empty($name) || 'auto' == $name) {
$uniacid = intval($_W['uniacid']);
$path = "{$type}s/{$uniacid}/" . date('Y/m/');
mkdirs(ATTACHMENT_ROOT . '/' . $path);
$filename = file_random_name(ATTACHMENT_ROOT . '/' . $path, $ext);
$result['path'] = $path . $filename;
} else {
mkdirs(dirname(ATTACHMENT_ROOT . '/' . $name));
if (!strexists($name, $ext)) {
$name .= '.' . $ext;
}
$result['path'] = $name;
}
$save_path = ATTACHMENT_ROOT . '/' . $result['path'];
$image = '';
if (isset($setting['zip_percentage']) && $setting['zip_percentage'] == 100 && system_check_php_ext('exif')) {
$exif = exif_read_data($file['tmp_name']);
if (!empty($exif['THUMBNAIL']['Orientation'])) {
$image = imagecreatefromstring(file_get_contents($file['tmp_name']));
switch($exif['THUMBNAIL']['Orientation']) {
case 8:
$image = imagerotate($image,0,0);
break;
case 3:
$image = imagerotate($image,180,0);
break;
case 6:
$image = imagerotate($image,-90,0);
break;
default:
$image = imagerotate($image,0,0);
break;
}
}
}
if (empty($image)) {
$newimage = file_move($file['tmp_name'], $save_path);
} else {
$newimage = imagejpeg($image,$save_path);
imagedestroy($image);
}
if (empty($newimage)) {
return error(-1, '文件上传失败, 请将 attachment 目录权限先777 <br> (如果777上传失败,可尝试将目录设置为755)');
}
if ('image' == $type && $compress) {
file_image_quality($save_path, $save_path, $ext);
}
if (file_is_uni_attach($save_path)) {
$check_result = file_check_uni_space($save_path);
if (is_error($check_result)) {
@unlink($save_path);
return $check_result;
}
$uni_remote_setting = uni_setting_load('remote');
if (empty($uni_remote_setting['remote']) && empty($_W['setting']['remote']['type'])) {
file_change_uni_attchsize($save_path);
}
}
$result['success'] = true;
return $result;
}
function file_wechat_upload($file, $type = 'image', $name = '') {
$harmtype = array('asp', 'php', 'jsp', 'js', 'css', 'php3', 'php4', 'php5', 'ashx', 'aspx', 'exe', 'cgi');
if (empty($file)) {
return error(-1, '没有上传内容');
}
if (!in_array($type, array('image', 'thumb', 'voice', 'video', 'audio'))) {
return error(-2, '未知的上传类型');
}
global $_W;
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$ext = strtolower($ext);
if (in_array(strtolower($ext), $harmtype)) {
return error(-3, '不允许上传此类文件');
}
$result = array();
if (empty($name) || 'auto' == $name) {
$uniacid = intval($_W['uniacid']);
$path = "{$type}s/{$uniacid}/" . date('Y/m/');
mkdirs(ATTACHMENT_ROOT . '/' . $path);
$filename = file_random_name(ATTACHMENT_ROOT . '/' . $path, $ext);
$result['path'] = $path . $filename;
} else {
mkdirs(dirname(ATTACHMENT_ROOT . '/' . $name));
if (!strexists($name, $ext)) {
$name .= '.' . $ext;
}
$result['path'] = $name;
}
$save_path = ATTACHMENT_ROOT . '/' . $result['path'];
if (!file_move($file['tmp_name'], $save_path)) {
return error(-1, '保存上传文件失败');
}
if ('image' == $type) {
file_image_quality($save_path, $save_path, $ext);
}
$result['success'] = true;
return $result;
}
function file_remote_upload($filename, $auto_delete_local = true) {
global $_W;
if (empty($_W['setting']['remote']['type'])) {
return false;
}
if ($_W['setting']['remote']['type'] == ATTACH_FTP) {
load()->library('ftp');
$ftp_config = array(
'hostname' => $_W['setting']['remote']['ftp']['hostname'] ?: $_W['setting']['remote']['ftp']['host'],
'username' => $_W['setting']['remote']['ftp']['username'],
'password' => $_W['setting']['remote']['ftp']['password'],
'port' => $_W['setting']['remote']['ftp']['port'],
'ssl' => $_W['setting']['remote']['ftp']['ssl'],
'passive' => $_W['setting']['remote']['ftp']['passive'] ?: $_W['setting']['remote']['ftp']['pasv'],
'timeout' => $_W['setting']['remote']['ftp']['timeout'] ?: $_W['setting']['remote']['ftp']['overtime'],
'rootdir' => $_W['setting']['remote']['ftp']['rootdir'] ?: $_W['setting']['remote']['ftp']['dir'],
);
$ftp = new Ftp($ftp_config);
if (true === $ftp->connect()) {
$response = $ftp->upload(ATTACHMENT_ROOT . '/' . $filename, $filename);
if ($auto_delete_local) {
file_delete($filename);
}
if (!empty($response)) {
return true;
} else {
return error(1, '远程附件上传失败,请检查配置并重新上传');
}
} else {
return error(1, '远程附件上传失败,请检查配置并重新上传');
}
} elseif ($_W['setting']['remote']['type'] == ATTACH_OSS) {
load()->library('oss');
load()->model('attachment');
$buckets = attachment_alioss_buctkets($_W['setting']['remote']['alioss']['key'], $_W['setting']['remote']['alioss']['secret']);
$host_name = $_W['setting']['remote']['alioss']['internal'] ? '-internal.aliyuncs.com' : '.aliyuncs.com';
$endpoint = 'http://' . $buckets[$_W['setting']['remote']['alioss']['bucket']]['location'] . $host_name;
try {
$ossClient = new \OSS\OssClient($_W['setting']['remote']['alioss']['key'], $_W['setting']['remote']['alioss']['secret'], $endpoint);
$ossClient->uploadFile($_W['setting']['remote']['alioss']['bucket'], $filename, ATTACHMENT_ROOT . $filename);
} catch (\OSS\Core\OssException $e) {
return error(1, $e->getMessage());
}
if ($auto_delete_local) {
file_delete($filename);
}
} elseif ($_W['setting']['remote']['type'] == ATTACH_QINIU) {
load()->library('qiniu');
$auth = new Qiniu\Auth($_W['setting']['remote']['qiniu']['accesskey'], $_W['setting']['remote']['qiniu']['secretkey']);
$config = new Qiniu\Config();
$uploadmgr = new Qiniu\Storage\UploadManager($config);
$putpolicy = Qiniu\base64_urlSafeEncode(json_encode(array(
'scope' => $_W['setting']['remote']['qiniu']['bucket'] . ':' . $filename,
)));
$uploadtoken = $auth->uploadToken($_W['setting']['remote']['qiniu']['bucket'], $filename, 3600, $putpolicy);
list($ret, $err) = $uploadmgr->putFile($uploadtoken, $filename, ATTACHMENT_ROOT . '/' . $filename);
if ($auto_delete_local) {
file_delete($filename);
}
if (null !== $err) {
return error(1, '远程附件上传失败,请检查配置并重新上传');
} else {
return true;
}
} elseif ($_W['setting']['remote']['type'] == ATTACH_COS) {
load()->library('cosv5');
try {
$bucket = $_W['setting']['remote']['cos']['bucket'] . '-' . $_W['setting']['remote']['cos']['appid'];
$cosClient = new Qcloud\Cos\Client(
array(
'region' => $_W['setting']['remote']['cos']['local'],
'credentials'=> array(
'secretId' => $_W['setting']['remote']['cos']['secretid'],
'secretKey' => $_W['setting']['remote']['cos']['secretkey'])));
$cosClient->Upload($bucket, $filename, fopen(ATTACHMENT_ROOT . $filename, 'rb'));
if ($auto_delete_local) {
file_delete($filename);
}
} catch (\Exception $e) {
return error(1, $e->getMessage());
}
}
return true;
}
function file_dir_remote_upload($dir_path, $limit = 200) {
global $_W;
if (empty($_W['setting']['remote']['type'])) {
return error(1, '未开启远程附件');
}
$dir_path = safe_gpc_path($dir_path);
if (!empty($dir_path)) {
$local_attachment = file_tree_limit($dir_path, $limit);
} else {
$local_attachment = array();
}
if (is_array($local_attachment) && !empty($local_attachment)) {
foreach ($local_attachment as $attachment) {
$filename = str_replace(ATTACHMENT_ROOT, '', $attachment);
list($image_dir, $file_account) = explode('/', $filename);
if ('global' == $file_account || !file_is_image($attachment)) {
continue;
}
$result = file_remote_upload($filename);
if (is_error($result)) {
return $result;
}
}
}
return true;
}
function file_random_name($dir, $ext) {
do {
$filename = random(30) . '.' . $ext;
} while (file_exists($dir . $filename));
return $filename;
}
function file_delete($file) {
global $_W;
if (empty($file)) {
return false;
}
$file = safe_gpc_path($file);
$file_extension = pathinfo($file, PATHINFO_EXTENSION);
if (in_array($file_extension, array('php', 'html', 'js', 'css', 'ttf', 'otf', 'eot', 'svg', 'woff'))) {
return false;
}
$uni_remote_setting = uni_setting_load('remote');
if (empty($uni_remote_setting['remote']) && empty($_W['setting']['remote']['type'])) {
if (file_exists(ATTACHMENT_ROOT . '/' . $file) && file_is_uni_attach(ATTACHMENT_ROOT . '/' . $file)) {
file_change_uni_attchsize(ATTACHMENT_ROOT . '/' . $file, false);
}
}
if (file_exists($file)) {
@unlink($file);
}
if (file_exists(ATTACHMENT_ROOT . '/' . $file)) {
@unlink(ATTACHMENT_ROOT . '/' . $file);
}
return true;
}
function file_remote_delete($file) {
global $_W;
if (empty($file)) {
return true;
}
if ($_W['setting']['remote']['type'] == '1') {
load()->library('ftp');
$ftp_config = array(
'hostname' => $_W['setting']['remote']['ftp']['hostname'] ?: $_W['setting']['remote']['ftp']['host'],
'username' => $_W['setting']['remote']['ftp']['username'],
'password' => $_W['setting']['remote']['ftp']['password'],
'port' => $_W['setting']['remote']['ftp']['port'],
'ssl' => $_W['setting']['remote']['ftp']['ssl'],
'passive' => $_W['setting']['remote']['ftp']['passive'] ?: $_W['setting']['remote']['ftp']['pasv'],
'timeout' => $_W['setting']['remote']['ftp']['timeout'] ?: $_W['setting']['remote']['ftp']['overtime'],
'rootdir' => $_W['setting']['remote']['ftp']['rootdir'] ?: $_W['setting']['remote']['ftp']['dir'],
);
$ftp = new Ftp($ftp_config);
if (true === $ftp->connect()) {
if ($ftp->delete_file($file)) {
return true;
} else {
return error(1, '删除附件失败,请检查配置并重新删除');
}
} else {
return error(1, '删除附件失败,请检查配置并重新删除');
}
} elseif ($_W['setting']['remote']['type'] == '2') {
load()->model('attachment');
load()->library('oss');
$buckets = attachment_alioss_buctkets($_W['setting']['remote']['alioss']['key'], $_W['setting']['remote']['alioss']['secret']);
$endpoint = 'http://' . $buckets[$_W['setting']['remote']['alioss']['bucket']]['location'] . '.aliyuncs.com';
try {
$ossClient = new \OSS\OssClient($_W['setting']['remote']['alioss']['key'], $_W['setting']['remote']['alioss']['secret'], $endpoint);
$ossClient->deleteObject($_W['setting']['remote']['alioss']['bucket'], $file);
} catch (\OSS\Core\OssException $e) {
return error(1, '删除oss远程文件失败');
}
} elseif ($_W['setting']['remote']['type'] == '3') {
load()->library('qiniu');
$auth = new Qiniu\Auth($_W['setting']['remote']['qiniu']['accesskey'], $_W['setting']['remote']['qiniu']['secretkey']);
$bucketMgr = new Qiniu\Storage\BucketManager($auth);
$error = $bucketMgr->delete($_W['setting']['remote']['qiniu']['bucket'], $file);
if ($error instanceof Qiniu\Http\Error) {
if (612 == $error->code()) {
return true;
}
return error(1, '删除七牛远程文件失败');
} else {
return true;
}
} elseif ($_W['setting']['remote']['type'] == '4') {
load()->library('cosv5');
try {
$key = $file;
$bucket = $_W['setting']['remote']['cos']['bucket'] . '-' . $_W['setting']['remote']['cos']['appid'];
$cosClient = new Qcloud\Cos\Client(
array(
'region' => $_W['setting']['remote']['cos']['local'],
'credentials'=> array(
'secretId' => $_W['setting']['remote']['cos']['secretid'],
'secretKey' => $_W['setting']['remote']['cos']['secretkey'])));
$cosClient->deleteObjects(array(
'Bucket' => $bucket,
'Objects' => array(array('Key' => $key))
));
} catch (\Exception $e) {
return error(1, '删除cos远程文件失败');
}
}
return true;
}
function file_image_thumb($srcfile, $desfile = '', $width = 0) {
global $_W;
load()->classs('image');
if (0 == intval($width)) {
load()->model('setting');
$width = intval($_W['setting']['upload']['image']['width']);
}
if (empty($desfile)) {
$ext = pathinfo($srcfile, PATHINFO_EXTENSION);
$srcdir = dirname($srcfile);
do {
$desfile = $srcdir . '/' . random(30) . ".{$ext}";
} while (file_exists($desfile));
}
$des = dirname($desfile);
if (!file_exists($des)) {
if (!mkdirs($des)) {
return error('-1', '创建目录失败');
}
} elseif (!is_writable($des)) {
return error('-1', '目录无法写入');
}
$org_info = @getimagesize($srcfile);
if ($org_info) {
if (0 == $width || $width > $org_info[0]) {
copy($srcfile, $desfile);
return str_replace(ATTACHMENT_ROOT . '/', '', $desfile);
}
}
$scale_org = $org_info[0] / $org_info[1];
$height = $width / $scale_org;
$desfile = Image::create($srcfile)->resize($width, $height)->saveTo($desfile);
if (!$desfile) {
return false;
}
return str_replace(ATTACHMENT_ROOT . '/', '', $desfile);
}
function file_image_crop($src, $desfile, $width = 400, $height = 300, $position = 1) {
load()->classs('image');
$des = dirname($desfile);
if (!file_exists($des)) {
if (!mkdirs($des)) {
return error('-1', '创建目录失败');
}
} elseif (!is_writable($des)) {
return error('-1', '目录无法写入');
}
return Image::create($src)
->crop($width, $height, $position)
->saveTo($desfile);
}
function file_lists($filepath, $subdir = 1, $ex = '', $isdir = 0, $md5 = 0, $enforcement = 0) {
static $file_list = array();
if ($enforcement) {
$file_list = array();
}
$flags = $isdir ? GLOB_ONLYDIR : 0;
$list = glob($filepath . '*' . (!empty($ex) && empty($subdir) ? '.' . $ex : ''), $flags);
if (!empty($ex)) {
$ex_num = strlen($ex);
}
foreach ($list as $k => $v) {
$v = str_replace('\\', '/', $v);
$v1 = str_replace(IA_ROOT . '/', '', $v);
if ($subdir && is_dir($v)) {
file_lists($v . '/', $subdir, $ex, $isdir, $md5);
continue;
}
if (!empty($ex) && strtolower(substr($v, -$ex_num, $ex_num)) == $ex) {
if ($md5) {
$file_list[$v1] = md5_file($v);
} else {
$file_list[] = $v1;
}
continue;
} elseif (!empty($ex) && strtolower(substr($v, -$ex_num, $ex_num)) != $ex) {
unset($list[$k]);
continue;
}
}
return $file_list;
}
function file_remote_attach_fetch($url, $limit = 0, $path = '') {
global $_W;
$url = trim($url);
if (empty($url)) {
return error(-1, '文件地址不存在');
}
load()->func('communication');
$resp = ihttp_get($url);
if (is_error($resp)) {
return error(-1, '提取文件失败, 错误信息: ' . $resp['message']);
}
if (200 != intval($resp['code'])) {
return error(-1, '提取文件失败: 未找到该资源文件.');
}
$get_headers = file_media_content_type($url);
if (empty($get_headers)) {
return error(-1, '提取资源失败, 资源文件类型错误.');
} else {
$ext = $get_headers['ext'];
$type = $get_headers['type'];
}
if (empty($path)) {
$path = $type . "/{$_W['uniacid']}/" . date('Y/m/');
} else {
$path = parse_path($path);
}
if (!$path) {
return error(-1, '提取文件失败: 上传路径配置有误.');
}
if (!is_dir(ATTACHMENT_ROOT . $path)) {
if (!mkdirs(ATTACHMENT_ROOT . $path, 0700, true)) {
return error(-1, '提取文件失败: 权限不足.');
}
}
if (!$limit) {
if ('images' == $type) {
$limit = $_W['setting']['upload']['image']['limit'] * 1024;
} else {
$limit = $_W['setting']['upload']['audio']['limit'] * 1024;
}
} else {
$limit = $limit * 1024;
}
if (intval($resp['headers']['Content-Length']) > $limit) {
return error(-1, '上传的媒体文件过大(' . sizecount($resp['headers']['Content-Length']) . ' > ' . sizecount($limit));
}
$filename = file_random_name(ATTACHMENT_ROOT . $path, $ext);
$pathname = $path . $filename;
$fullname = ATTACHMENT_ROOT . $pathname;
if (false == file_put_contents($fullname, $resp['content'])) {
return error(-1, '提取失败.');
}
return $pathname;
}
function file_media_content_type($url) {
$file_header = iget_headers($url, 1);
if (empty($url) || !is_array($file_header)) {
return false;
}
switch ($file_header['Content-Type']) {
case 'application/x-jpg':
case 'image/jpg':
case 'image/jpeg':
$ext = 'jpg';
$type = 'images';
break;
case 'image/png':
$ext = 'png';
$type = 'images';
break;
case 'image/gif':
$ext = 'gif';
$type = 'images';
break;
case 'video/mp4':
case 'video/mpeg4':
$ext = 'mp4';
$type = 'videos';
break;
case 'video/x-ms-wmv':
$ext = 'wmv';
$type = 'videos';
break;
case 'audio/mpeg':
$ext = 'mp3';
$type = 'audios';
break;
case 'audio/mp4':
$ext = 'mp4';
$type = 'audios';
break;
case 'audio/x-ms-wma':
$ext = 'wma';
$type = 'audios';
break;
default:
return false;
break;
}
return array('ext' => $ext, 'type' => $type);
}
function file_allowed_media($type) {
global $_W;
if (!in_array($type, array('image', 'audio'))) {
return array();
}
if (empty($_W['setting']['upload'][$type]['extention']) || !is_array($_W['setting']['upload'][$type]['extention'])) {
return $_W['config']['upload'][$type]['extentions'];
}
return $_W['setting']['upload'][$type]['extention'];
}
function file_is_image($url) {
global $_W;
$allowed_media = file_allowed_media('image');
if ('//' == substr($url, 0, 2)) {
$url = 'http:' . $url;
}
if (0 == strpos($url, $_W['siteroot'] . 'attachment/')) {
$url = str_replace($_W['siteroot'] . 'attachment/', ATTACHMENT_ROOT, $url);
}
$lower_url = strtolower($url);
if (('http://' == substr($lower_url, 0, 7)) || ('https://' == substr($lower_url, 0, 8))) {
$analysis_url = parse_url($lower_url);
$preg_str = '/.*(\.' . implode('|\.', $allowed_media) . ')$/';
if (!empty($analysis_url['query']) || !preg_match($preg_str, $lower_url) || !preg_match($preg_str, $analysis_url['path'])) {
return false;
}
$img_headers = file_media_content_type($url);
if (empty($img_headers) || !in_array($img_headers['ext'], $allowed_media)) {
return false;
}
}
$info = igetimagesize($url);
if (!is_array($info)) {
return false;
}
return true;
}
function file_image_quality($src, $to_path, $ext) {
load()->classs('image');
global $_W;
if ('gif' == strtolower($ext)) {
return;
}
$quality = intval($_W['setting']['upload']['image']['zip_percentage']);
if ($quality <= 0 || $quality >= 100) {
return;
}
if (filesize($src) / 1024 > 5120) {
return;
}
$result = Image::create($src, $ext)->saveTo($to_path, $quality);
return $result;
}
function file_is_uni_attach($file) {
global $_W;
if (!is_file($file)) {
return error(-1, '未找到的文件。');
}
return strpos($file, "/{$_W['uniacid']}/") > 0;
}
function file_check_uni_space($file) {
global $_W;
if (!is_file($file)) {
return error(-1, '未找到上传的文件。');
}
$uni_remote_setting = uni_setting_load('remote');
if (empty($uni_remote_setting['remote']['type'])) {
$uni_setting = uni_setting_load(array('attachment_limit', 'attachment_size'));
$attachment_limit = intval($uni_setting['attachment_limit']);
if (0 == $attachment_limit) {
$upload = setting_load('upload');
$attachment_limit = empty($upload['upload']['attachment_limit']) ? 0 : intval($upload['upload']['attachment_limit']);
}
if ($attachment_limit > 0) {
$file_size = max(1, round(filesize($file) / 1024));
if (($file_size + $uni_setting['attachment_size']) > ($attachment_limit * 1024)) {
return error(-1, '上传失败,可使用的附件空间不足!');
}
}
}
return true;
}
function file_change_uni_attchsize($file, $is_add = true) {
global $_W;
if (!is_file($file)) {
return error(-1, '未找到的文件。');
}
$file_size = round(filesize($file) / 1024);
$file_size = max(1, $file_size);
$result = true;
$uni_remote_setting = uni_setting_load('remote');
if (empty($uni_remote_setting['remote']['type'])) {
$uniacid = pdo_getcolumn('uni_settings', array('uniacid' => $_W['uniacid']), 'uniacid');
if (empty($uniacid)) {
$result = pdo_insert('uni_settings', array('attachment_size' => $file_size, 'uniacid' => $_W['uniacid']));
} else {
if (!$is_add) {
$file_size = -$file_size;
}
$result = pdo_update('uni_settings', array('attachment_size +=' => $file_size), array('uniacid' => $_W['uniacid']));
}
$cachekey = cache_system_key('unisetting', array('uniacid' => $uniacid));
$unisetting = cache_load($cachekey);
$unisetting['attachment_size'] += $file_size;
$unisetting['attachment_size'] = max(0, $unisetting['attachment_size']);
cache_write($cachekey, $unisetting);
}
return $result;
}

1350
framework/function/global.func.php

File diff suppressed because it is too large

59
framework/function/logging.func.php

@ -0,0 +1,59 @@
<?php
defined('IN_IA') or exit('Access Denied');
define('LOGGING_ERROR', 'error');
define('LOGGING_TRACE', 'trace');
define('LOGGING_WARNING', 'warning');
define('LOGGING_INFO', 'info');
function logging_run($log, $type = 'trace', $filename = 'run') {
global $_W;
$filename = IA_ROOT . '/data/logs/' . $filename . '_' . date('Ymd') . '.php';
load()->func('file');
mkdirs(dirname($filename));
$logFormat = '%date %type %user %url %context';
if (!empty($GLOBALS['_POST'])) {
$context[] = logging_implode($GLOBALS['_POST']);
}
if (is_array($log)) {
$context[] = logging_implode($log);
} else {
$context[] = preg_replace('/[ \t\r\n]+/', ' ', $log);
}
$log = str_replace(explode(' ', $logFormat), array(
'[' . date('Y-m-d H:i:s', $_W['timestamp']) . ']',
$type,
$_W['username'],
$_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'],
implode("\n", $context),
), $logFormat);
if (file_exists($filename)) {
$log = $log . "\r\n";
} else {
$log = "<?php exit;?>\r\n" . $log . "\r\n";
}
file_put_contents($filename, $log, FILE_APPEND);
return true;
}
function logging_implode($array, $skip = array()) {
$return = '';
if (is_array($array) && !empty($array)) {
foreach ($array as $key => $value) {
if (empty($skip) || !in_array($key, $skip, true)) {
if (is_array($value)) {
$return .= $key . '={' . logging_implode($value, $skip) . '}; ';
} else {
$return .= "$key=$value; ";
}
}
}
}
return $return;
}

143
framework/function/pdo.func.php

@ -0,0 +1,143 @@
<?php
defined('IN_IA') or exit('Access Denied');
function pdo() {
global $_W;
static $db;
if (empty($db)) {
if ($_W['config']['db']['slave_status'] == true && !empty($_W['config']['db']['slave'])) {
load()->classs('slave.db');
$db = new SlaveDb('master');
} else {
load()->classs('db');
if (empty($_W['config']['db']['master'])) {
$_W['config']['db']['master'] = $GLOBALS['_W']['config']['db'];
}
$db = new DB('master');
}
}
return $db;
}
function pdos($table = '') {
return load()->singleton('Query');
}
function pdo_query($sql, $params = array()) {
return pdo()->query($sql, $params);
}
function pdo_fetchcolumn($sql, $params = array(), $column = 0) {
return pdo()->fetchcolumn($sql, $params, $column);
}
function pdo_fetch($sql, $params = array()) {
return pdo()->fetch($sql, $params);
}
function pdo_fetchall($sql, $params = array(), $keyfield = '') {
return pdo()->fetchall($sql, $params, $keyfield);
}
function pdo_get($tablename, $condition = array(), $fields = array()) {
return pdo()->get($tablename, $condition, $fields);
}
function pdo_getall($tablename, $condition = array(), $fields = array(), $keyfield = '', $orderby = array(), $limit = array()) {
return pdo()->getall($tablename, $condition, $fields, $keyfield, $orderby, $limit);
}
function pdo_getslice($tablename, $condition = array(), $limit = array(), &$total = null, $fields = array(), $keyfield = '', $orderby = array()) {
return pdo()->getslice($tablename, $condition, $limit, $total, $fields, $keyfield, $orderby);
}
function pdo_getcolumn($tablename, $condition = array(), $field) {
return pdo()->getcolumn($tablename, $condition, $field);
}
function pdo_exists($tablename, $condition = array()) {
return pdo()->exists($tablename, $condition);
}
function pdo_count($tablename, $condition = array(), $cachetime = 15) {
return pdo()->count($tablename, $condition, $cachetime);
}
function pdo_update($table, $data = array(), $params = array(), $glue = 'AND') {
return pdo()->update($table, $data, $params, $glue);
}
function pdo_insert($table, $data = array(), $replace = false) {
return pdo()->insert($table, $data, $replace);
}
function pdo_delete($table, $params = array(), $glue = 'AND') {
return pdo()->delete($table, $params, $glue);
}
function pdo_insertid() {
return pdo()->insertid();
}
function pdo_begin() {
pdo()->begin();
}
function pdo_commit() {
pdo()->commit();
}
function pdo_rollback() {
pdo()->rollBack();
}
function pdo_debug($output = true, $append = array()) {
return pdo()->debug($output, $append);
}
function pdo_run($sql) {
return pdo()->run($sql);
}
function pdo_fieldexists($tablename, $fieldname = '') {
return pdo()->fieldexists($tablename, $fieldname);
}
function pdo_fieldmatch($tablename, $fieldname, $datatype = '', $length = '') {
return pdo()->fieldmatch($tablename, $fieldname, $datatype, $length);
}
function pdo_indexexists($tablename, $indexname = '') {
return pdo()->indexexists($tablename, $indexname);
}
function pdo_fetchallfields($tablename) {
$fields = pdo_fetchall("DESCRIBE {$tablename}", array(), 'Field');
$fields = array_keys($fields);
return $fields;
}
function pdo_tableexists($tablename) {
return pdo()->tableexists($tablename);
}

245
framework/function/safe.func.php

@ -0,0 +1,245 @@
<?php
defined('IN_IA') or exit('Access Denied');
function safe_gpc_int($value, $default = 0)
{
if (false !== strpos($value, '.')) {
$value = floatval($value);
$default = floatval($default);
} else {
$value = intval($value);
$default = intval($default);
}
if (empty($value) && $default != $value) {
$value = $default;
}
return $value;
}
function safe_gpc_belong($value, $allow = array(), $default = '')
{
if (empty($allow)) {
return $default;
}
if (in_array($value, $allow, true)) {
return $value;
} else {
return $default;
}
}
function safe_gpc_string($value, $default = '')
{
$value = safe_bad_str_replace($value);
$value = preg_replace('/&((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $value);
if (empty($value) && $default != $value) {
$value = $default;
}
return $value;
}
function safe_gpc_path($value, $default = '')
{
$path = safe_gpc_string($value);
$path = str_replace(array('..', '..\\', '\\\\', '\\', '..\\\\'), '', $path);
if (empty($path) || $path != $value) {
$path = $default;
}
return $path;
}
function safe_gpc_array($value, $default = array())
{
if (empty($value) || !is_array($value)) {
return $default;
}
foreach ($value as &$row) {
if (is_numeric($row)) {
$row = safe_gpc_int($row);
} elseif (is_array($row)) {
$row = safe_gpc_array($row, $default);
} else {
$row = safe_gpc_string($row);
}
}
return $value;
}
function safe_gpc_boolean($value)
{
return boolval($value);
}
function safe_gpc_html($value, $default = '')
{
if (empty($value) || !is_string($value)) {
return $default;
}
$value = safe_bad_str_replace($value);
$value = safe_remove_xss($value);
if (empty($value) && $value != $default) {
$value = $default;
}
return $value;
}
function safe_gpc_sql($value, $operator = 'ENCODE', $default = '')
{
if (empty($value) || !is_string($value)) {
return $default;
}
$value = trim(strtolower($value));
$badstr = array(
'_', '%', "'", chr(39),
'select', 'join', 'union',
'where', 'insert', 'delete',
'update', 'like', 'drop',
'create', 'modify', 'rename',
'alter', 'cast',
);
$newstr = array(
'\_', '\%', "''", '&#39;',
'sel&#101;ct"', 'jo&#105;n', 'un&#105;on',
'wh&#101;re', 'ins&#101;rt', 'del&#101;te',
'up&#100;ate', 'lik&#101;', 'dro&#112',
'cr&#101;ate', 'mod&#105;fy', 'ren&#097;me"',
'alt&#101;r', 'ca&#115;',
);
if ('ENCODE' == $operator) {
$value = str_replace($badstr, $newstr, $value);
} else {
$value = str_replace($newstr, $badstr, $value);
}
return $value;
}
function safe_gpc_url($value, $strict_domain = true, $default = '')
{
global $_W;
if (empty($value) || !is_string($value)) {
return $default;
}
$value = urldecode($value);
if (starts_with($value, './')) {
return $value;
}
if ($strict_domain) {
if (starts_with($value, $_W['siteroot'])) {
return $value;
}
return $default;
}
if (starts_with($value, 'http') || starts_with($value, '//')) {
return $value;
}
return $default;
}
function safe_remove_xss($val)
{
$val = preg_replace('/([\x0e-\x19])/', '', $val);
$search = 'abcdefghijklmnopqrstuvwxyz';
$search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$search .= '1234567890!@#$%^&*()';
$search .= '~`";:?+/={}[]-_|\'\\';
for ($i = 0; $i < strlen($search); ++$i) {
$val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val);
$val = preg_replace('/(&#0{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val);
}
preg_match_all('/href=[\'|\"](.*?)[\'|\"]|src=[\'|\"](.*?)[\'|\"]/i', $val, $matches);
$url_list = array_merge($matches[1], $matches[2]);
$encode_url_list = array();
if (!empty($url_list)) {
foreach ($url_list as $key => $url) {
$val = str_replace($url, 'we7_' . $key . '_we7placeholder', $val);
$encode_url_list[] = $url;
}
}
$ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'frameset', 'ilayer', 'bgsound', 'base');
$ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload', '@import');
$ra = array_merge($ra1, $ra2);
$found = true;
while (true == $found) {
$val_before = $val;
for ($i = 0; $i < sizeof($ra); ++$i) {
$pattern = '/';
for ($j = 0; $j < strlen($ra[$i]); ++$j) {
if ($j > 0) {
$pattern .= '(';
$pattern .= '(&#[xX]0{0,8}([9ab]);)';
$pattern .= '|';
$pattern .= '|(&#0{0,8}([9|10|13]);)';
$pattern .= ')*';
}
$pattern .= $ra[$i][$j];
}
$pattern .= '/i';
$replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2);
$val = preg_replace($pattern, $replacement, $val);
if ($val_before == $val) {
$found = false;
}
}
}
if (!empty($encode_url_list) && is_array($encode_url_list)) {
foreach ($encode_url_list as $key => $url) {
$val = str_replace('we7_' . $key . '_we7placeholder', $url, $val);
}
}
return $val;
}
function safe_bad_str_replace($string)
{
if (empty($string)) {
return '';
}
$badstr = array("\0", '%00', '%3C', '%3E', '<?', '<%', '<?php', '{php', '{if', '{loop', '../');
$newstr = array('_', '_', '&lt;', '&gt;', '_', '_', '_', '_', '_', '_', '.._');
$string = str_replace($badstr, $newstr, $string);
return $string;
}
function safe_check_password($password)
{
$setting = setting_load('register');
if (!$setting['register']['safe']) {
return true;
}
preg_match('/(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,30}/', $password, $out);
if (empty($out)) {
return error(-1, '密码至少8-16个字符,至少1个大写字母,1个小写字母和1个数字,其他可以是任意字符');
} else {
return true;
}
}

44
framework/function/system.func.php

@ -0,0 +1,44 @@
<?php
if (!function_exists('getglobal')) {
function getglobal($key) {
global $_W;
$key = explode('/', $key);
$v = &$_W;
foreach ($key as $k) {
if (!isset($v[$k])) {
return null;
}
$v = &$v[$k];
}
return $v;
}
}
if (!function_exists('strip_gpc')) {
function strip_gpc($values, $type = 'g') {
$filter = array(
'g' => "'|(and|or)\\b.+?(>|<|=|in|like)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)",
'p' => '\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)',
'c' => '\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)',
);
if (!isset($values)) {
return '';
}
if (is_array($values)) {
foreach ($values as $key => $val) {
$values[addslashes($key)] = strip_gpc($val, $type);
}
} else {
if (1 == preg_match('/' . $filter[$type] . '/is', $values, $match)) {
$values = '';
}
}
return $values;
}
}

577
framework/function/tpl.func.php

@ -0,0 +1,577 @@
<?php
defined('IN_IA') or exit('Access Denied');
if (defined('IN_MOBILE')) {
load()->app('tpl');
} else {
load()->web('tpl');
}
function tpl_form_field_date($name, $value = '', $withtime = false) {
return _tpl_form_field_date($name, $value, $withtime);
}
function tpl_form_field_clock($name, $value = '') {
$s = '';
if (!defined('TPL_INIT_CLOCK_TIME')) {
$s .= '
<script type="text/javascript">
require(["clockpicker"], function($){
$(function(){
$(".clockpicker").clockpicker({
autoclose: true
});
});
});
</script>
';
define('TPL_INIT_CLOCK_TIME', 1);
}
$time = date('H:i');
if (!empty($value)) {
if (!strexists($value, ':')) {
$time = date('H:i', $value);
} else {
$time = $value;
}
}
$s .= ' <div class="input-group clockpicker">
<span class="input-group-addon"><i class="fa fa-clock-o"></i></span>
<input type="text" name="' . $name . '" value="' . $time . '" class="form-control">
</div>';
return $s;
}
function tpl_form_field_daterange($name, $value = array(), $time = false, $clear = true) {
$s = '';
if (empty($time) && !defined('TPL_INIT_DATERANGE_DATE')) {
$s = '
<script type="text/javascript">
require(["daterangepicker"], function(){
$(function(){
$(".daterange.daterange-date").each(function(){
var elm = this;
$(this).daterangepicker({
startDate: $(elm).prev().prev().val() || moment("不限", "Y"),
endDate: $(elm).prev().val() || moment("不限", "Y"),
format: "YYYY-MM-DD",
clear: '. $clear .'
}, function(start, end){
start = start.toDateStr().indexOf("0000-01-01") != -1 ? "" : start.toDateStr();
end = end.toDateStr().indexOf("0000-01-01") != -1 ? "" : end.toDateStr();
var html = (start == "" ? "不限时间" : start) + (start == "" && end === "" ? "" : (" 至" + end))
$(elm).find(".date-title").html(html);
$(elm).prev().prev().val(start);
$(elm).prev().val(end);
});
});
});
});
</script>
';
define('TPL_INIT_DATERANGE_DATE', true);
}
if (!empty($time) && !defined('TPL_INIT_DATERANGE_TIME')) {
$s = '
<script type="text/javascript">
require(["daterangepicker"], function(){
$(function(){
$(".daterange.daterange-time").each(function(){
var elm = this;
$(this).daterangepicker({
startDate: $(elm).prev().prev().val() || moment("不限", "Y"),
endDate: $(elm).prev().val() || moment("不限", "Y"),
format: "YYYY-MM-DD HH:mm",
timePicker: true,
timePicker12Hour : false,
timePickerIncrement: 1,
minuteStep: 1,
clear: '. $clear .'
}, function(start, end){
start = start.toDateStr().indexOf("0000-01-01") != -1 ? "" : start.toDateTimeStr();
end = end.toDateStr().indexOf("0000-01-01") != -1 ? "" : end.toDateTimeStr();
var html = (start == "" ? "不限时间" : start) + (start == "" && end === "" ? "" : (" 至" + end))
$(elm).find(".date-title").html(html);
$(elm).prev().prev().val(start);
$(elm).prev().val(end);
});
});
});
});
</script>
';
define('TPL_INIT_DATERANGE_TIME', true);
}
if (!empty($value['starttime']) || !empty($value['start'])) {
if ($value['start'] && strtotime($value['start'])) {
$value['starttime'] = empty($time) ? date('Y-m-d', strtotime($value['start'])) : date('Y-m-d H:i', strtotime($value['start']));
}
$value['starttime'] = empty($value['starttime']) ? '' : $value['starttime'];
} else {
$value['starttime'] = '';
}
if (!empty($value['endtime']) || !empty($value['end'])) {
if ($value['end'] && strtotime($value['end'])) {
$value['endtime'] = empty($time) ? date('Y-m-d', strtotime($value['end'])) : date('Y-m-d H:i', strtotime($value['end']));
}
$value['endtime'] = empty($value['endtime']) ? $value['starttime'] : $value['endtime'];
} else {
$value['endtime'] = '';
}
$s .= '
<input name="' . $name . '[start]' . '" type="hidden" value="' . $value['starttime'] . '" />
<input name="' . $name . '[end]' . '" type="hidden" value="' . $value['endtime'] . '" />
<button class="btn btn-default daterange ' . (!empty($time) ? 'daterange-time' : 'daterange-date') . '" type="button"><span class="date-title">' .
($value['starttime'] == "" ? "不限时间" : $value['starttime']) . ($value['starttime'] == "" && $value['endtime'] === "" ? "" : (" 至" . $value['endtime'])) . '</span> <i class="fa fa-calendar"></i></button>
';
return $s;
}
function tpl_form_field_calendar($name, $values = array()) {
$html = '';
if (!defined('TPL_INIT_CALENDAR')) {
$html .= '
<script type="text/javascript">
function handlerCalendar(elm) {
require(["moment"], function(moment){
var tpl = $(elm).parent().parent();
var year = tpl.find("select.tpl-year").val();
var month = tpl.find("select.tpl-month").val();
var day = tpl.find("select.tpl-day");
day[0].options.length = 1;
if(year && month) {
var date = moment(year + "-" + month, "YYYY-M");
var days = date.daysInMonth();
for(var i = 1; i <= days; i++) {
var opt = new Option(i, i);
day[0].options.add(opt);
}
if(day.attr("data-value")!=""){
day.val(day.attr("data-value"));
} else {
day[0].options[0].selected = "selected";
}
}
if($("select").niceSelect) {
$("select").niceSelect("update");
}
});
}
require([""], function(){
$(".tpl-calendar").each(function(){
handlerCalendar($(this).find("select.tpl-year")[0]);
});
});
</script>';
define('TPL_INIT_CALENDAR', true);
}
if (empty($values) || !is_array($values)) {
$values = array(0, 0, 0);
}
$values['year'] = intval($values['year']);
$values['month'] = intval($values['month']);
$values['day'] = intval($values['day']);
if (empty($values['year'])) {
$values['year'] = '1980';
}
$year = array(date('Y'), '1914');
$html .= '<div class="row row-fix tpl-calendar">
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
<select name="' . $name . '[year]" onchange="handlerCalendar(this)" class="form-control tpl-year">
<option value=""></option>';
for ($i = $year[1]; $i <= $year[0]; ++$i) {
$html .= '<option value="' . $i . '"' . ($i == $values['year'] ? ' selected="selected"' : '') . '>' . $i . '</option>';
}
$html .= ' </select>
</div>
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
<select name="' . $name . '[month]" onchange="handlerCalendar(this)" class="form-control tpl-month">
<option value=""></option>';
for ($i = 1; $i <= 12; ++$i) {
$html .= '<option value="' . $i . '"' . ($i == $values['month'] ? ' selected="selected"' : '') . '>' . $i . '</option>';
}
$html .= ' </select>
</div>
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
<select name="' . $name . '[day]" data-value="' . $values['day'] . '" class="form-control tpl-day">
<option value="0"></option>
</select>
</div>
</div>';
return $html;
}
function tpl_form_field_district($name, $values = array()) {
$html = '';
if (!defined('TPL_INIT_DISTRICT')) {
$html .= '
<script type="text/javascript">
require(["district"], function(dis){
$(".tpl-district-container").each(function(){
var elms = {};
elms.province = $(this).find(".tpl-province")[0];
elms.city = $(this).find(".tpl-city")[0];
elms.district = $(this).find(".tpl-district")[0];
var vals = {};
vals.province = $(elms.province).attr("data-value");
vals.city = $(elms.city).attr("data-value");
vals.district = $(elms.district).attr("data-value");
dis.render(elms, vals, {withTitle: true});
});
});
</script>';
define('TPL_INIT_DISTRICT', true);
}
if (empty($values) || !is_array($values)) {
$values = array('province' => '', 'city' => '', 'district' => '');
}
if (empty($values['province'])) {
$values['province'] = '';
}
if (empty($values['city'])) {
$values['city'] = '';
}
if (empty($values['district'])) {
$values['district'] = '';
}
$html .= '
<div class="row row-fix tpl-district-container">
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
<select name="' . $name . '[province]" data-value="' . $values['province'] . '" class="form-control tpl-province">
</select>
</div>
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
<select name="' . $name . '[city]" data-value="' . $values['city'] . '" class="form-control tpl-city">
</select>
</div>
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
<select name="' . $name . '[district]" data-value="' . $values['district'] . '" class="form-control tpl-district">
</select>
</div>
</div>';
return $html;
}
function tpl_form_field_category_2level($name, $parents, $children, $parentid, $childid) {
$html = '
<script type="text/javascript">
window._' . $name . ' = ' . json_encode($children) . ';
</script>';
if (!defined('TPL_INIT_CATEGORY')) {
$html .= '
<script type="text/javascript">
function renderCategory(obj, name){
var index = obj.options[obj.selectedIndex].value;
require([\'jquery\', \'util\'], function($, u){
$selectChild = $(\'#\'+name+\'_child\');
var html = \'<option value="0">请选择二级分类</option>\';
if (!window[\'_\'+name] || !window[\'_\'+name][index]) {
$selectChild.html(html);
return false;
}
for(var i=0; i< window[\'_\'+name][index].length; i++){
html += \'<option value="\'+window[\'_\'+name][index][i][\'id\']+\'">\'+window[\'_\'+name][index][i][\'name\']+\'</option>\';
}
$selectChild.html(html);
if($("select").niceSelect) {
$("select").niceSelect("update");
}
});
}
</script>
';
define('TPL_INIT_CATEGORY', true);
}
$html .=
'<div class="row row-fix tpl-category-container">
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">
<select class="form-control tpl-category-parent we7-select" id="' . $name . '_parent" name="' . $name . '[parentid]" onchange="renderCategory(this,\'' . $name . '\')">
<option value="0">请选择一级分类</option>';
$ops = '';
if (!empty($parents)) {
foreach ($parents as $row) {
$html .= '
<option value="' . $row['id'] . '" ' . (($row['id'] == $parentid) ? 'selected="selected"' : '') . '>' . $row['name'] . '</option>';
}
}
$html .= '
</select>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">
<select class="form-control tpl-category-child we7-select" id="' . $name . '_child" name="' . $name . '[childid]">
<option value="0">请选择二级分类</option>';
if (!empty($parentid) && !empty($children[$parentid])) {
foreach ($children[$parentid] as $row) {
$html .= '
<option value="' . $row['id'] . '"' . (($row['id'] == $childid) ? 'selected="selected"' : '') . '>' . $row['name'] . '</option>';
}
}
$html .= '
</select>
</div>
</div>
';
return $html;
}
function tpl_form_field_industry($name, $pvalue = '', $cvalue = '', $parentid = 'industry_1', $childid = 'industry_2') {
$html = '
<div class="row row-fix">
<div class="col-sm-4">
<select name="' . $name . '[parent]" id="' . $parentid . '" class="form-control" value="' . $pvalue . '"></select>
</div>
<div class="col-sm-4">
<select name="' . $name . '[child]" id="' . $childid . '" class="form-control" value="' . $cvalue . '"></select>
</div>
<script type="text/javascript">
require([\'industry\'], function(industry){
industry.init("' . $parentid . '","' . $childid . '");
});
</script>
</div>';
return $html;
}
function tpl_form_field_coordinate($field, $value = array()) {
$s = '';
if (!defined('TPL_INIT_COORDINATE')) {
$s .= '<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=F51571495f717ff1194de02366bb8da9&s=1"></script><script type="text/javascript">
function showCoordinate(elm) {
require(["util"], function(util){
var val = {};
val.lng = parseFloat($(elm).parent().prev().prev().find(":text").val());
val.lat = parseFloat($(elm).parent().prev().find(":text").val());
util.map(val, function(r){
$(elm).parent().prev().prev().find(":text").val(r.lng);
$(elm).parent().prev().find(":text").val(r.lat);
});
});
}
</script>';
define('TPL_INIT_COORDINATE', true);
}
$s .= '
<div class="row row-fix">
<div class="col-xs-4 col-sm-4">
<input type="text" name="' . $field . '[lng]" value="' . $value['lng'] . '" placeholder="地理经度" class="form-control" />
</div>
<div class="col-xs-4 col-sm-4">
<input type="text" name="' . $field . '[lat]" value="' . $value['lat'] . '" placeholder="地理纬度" class="form-control" />
</div>
<div class="col-xs-4 col-sm-4">
<button onclick="showCoordinate(this);" class="btn btn-default" type="button">选择坐标</button>
</div>
</div>';
return $s;
}
function tpl_fans_form($field, $value = '') {
switch ($field) {
case 'avatar':
$avatar_url = '../attachment/images/global/avatars/';
$html = '';
if (!defined('TPL_INIT_AVATAR')) {
$html .= '
<script type="text/javascript">
function showAvatarDialog(elm, opts) {
require(["util"], function(util){
var btn = $(elm);
var ipt = btn.parent().prev();
var img = ipt.parent().next().children();
var content = \'<div class="avatar-browser clearfix">\';
for(var i = 1; i <= 12; i++) {
content +=
\'<div title="头像\' + i + \'" class="thumbnail">\' +
\'<em><img src="' . $avatar_url . 'avatar_\' + i + \'.jpg" class="img-responsive"></em>\' +
\'</div>\';
}
content += "</div>";
var dialog = util.dialog("请选择头像", content);
dialog.modal("show");
dialog.find(".thumbnail").on("click", function(){
var url = $(this).find("img").attr("src");
img.get(0).src = url;
ipt.val(url.replace(/^\.\.\/attachment\//, ""));
dialog.modal("hide");
});
});
}
</script>';
define('TPL_INIT_AVATAR', true);
}
if (!defined('TPL_INIT_IMAGE')) {
global $_W;
if (defined('IN_MOBILE')) {
$html .= <<<EOF
<script type="text/javascript">
// in mobile
function showImageDialog(elm) {
require(["jquery", "util"], function($, util){
var btn = $(elm);
var ipt = btn.parent().prev();
var val = ipt.val();
var img = ipt.parent().next().children();
util.image(elm, function(url){
img.get(0).src = url.url;
ipt.val(url.attachment);
});
});
}
</script>
EOF;
} else {
$html .= <<<EOF
<script type="text/javascript">
// in web
function showImageDialog(elm, opts) {
require(["util"], function(util){
var btn = $(elm);
var ipt = btn.parent().prev();
var val = ipt.val();
var img = ipt.parent().next().find('img');
util.image(val, function(url){
img.get(0).src = url.url;
ipt.val(url.attachment);
}, {multiple:false,type:"image",direct:true}, opts);
});
}
</script>
EOF;
}
define('TPL_INIT_IMAGE', true);
}
$val = './resource/images/nopic.jpg';
if (!empty($value)) {
$val = tomedia($value);
}
$options = array();
$options['width'] = '200';
$options['height'] = '200';
if (defined('IN_MOBILE')) {
$html .= <<<EOF
<div class="input-group">
<input type="text" value="{$value}" name="{$field}" class="form-control" autocomplete="off">
<span class="input-group-btn">
<button class="btn btn-default" type="button" onclick="showImageDialog(this);">选择图片</button>
<button class="btn btn-default" type="button" onclick="showAvatarDialog(this);">系统头像</button>
</span>
</div>
<div class="input-group" style="margin-top:.5em;">
<img src="{$val}" class="img-responsive img-thumbnail" width="150" style="max-height: 150px;"/>
</div>
EOF;
} else {
$html .= '
<div class="input-group">
<input type="text" value="' . $value . '" name="' . $field . '" class="form-control" autocomplete="off">
<span class="input-group-btn">
<button class="btn btn-default" type="button" onclick="showImageDialog(this, \'' . base64_encode(iserializer($options)) . '\');">选择图片</button>
<button class="btn btn-default" type="button" onclick="showAvatarDialog(this);">系统头像</button>
</span>
</div>
<div class="input-group" style="margin-top:.5em;">
<img src="' . $val . '" class="img-responsive img-thumbnail" width="150" />
</div>';
}
break;
case 'birth':
case 'birthyear':
case 'birthmonth':
case 'birthday':
$html = tpl_form_field_calendar('birth', $value);
break;
case 'reside':
case 'resideprovince':
case 'residecity':
case 'residedist':
$html = tpl_form_field_district('reside', $value);
break;
case 'bio':
case 'interest':
$html = '<textarea name="' . $field . '" class="form-control">' . $value . '</textarea>';
break;
case 'gender':
$html = '
<select name="gender" class="form-control">
<option value="0" ' . (0 == $value ? 'selected ' : '') . '>保密</option>
<option value="1" ' . (1 == $value ? 'selected ' : '') . '></option>
<option value="2" ' . (2 == $value ? 'selected ' : '') . '></option>
</select>';
break;
case 'education':
case 'constellation':
case 'zodiac':
case 'bloodtype':
if ('bloodtype' == $field) {
$options = array('A', 'B', 'AB', 'O', '其它');
} elseif ('zodiac' == $field) {
$options = array('鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪');
} elseif ('constellation' == $field) {
$options = array('水瓶座', '双鱼座', '白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座', '天秤座', '天蝎座', '射手座', '摩羯座');
} elseif ('education' == $field) {
$options = array('博士', '硕士', '本科', '专科', '中学', '小学', '其它');
}
$html = '<select name="' . $field . '" class="form-control">';
foreach ($options as $item) {
$html .= '<option value="' . $item . '" ' . ($value == $item ? 'selected ' : '') . '>' . $item . '</option>';
}
$html .= '</select>';
break;
case 'nickname':
case 'realname':
case 'address':
case 'mobile':
case 'qq':
case 'msn':
case 'email':
case 'telephone':
case 'taobao':
case 'alipay':
case 'studentid':
case 'grade':
case 'graduateschool':
case 'idcard':
case 'zipcode':
case 'site':
case 'affectivestatus':
case 'lookingfor':
case 'nationality':
case 'height':
case 'weight':
case 'company':
case 'occupation':
case 'position':
case 'revenue':
default:
$html = '<input type="text" class="form-control" name="' . $field . '" value="' . $value . '" />';
break;
}
return $html;
}

193
framework/library/agent/agent.class.php

@ -0,0 +1,193 @@
<?php
// 接口输出类
class Agent
{
// 设备类型
const DEVICE_MOBILE = 1;
const DEVICE_DESKTOP = 2;
const DEVICE_UNKNOWN = -1;
// 浏览器类型
const BROWSER_TYPE_IPHONE = 1;
const BROWSER_TYPE_IPAD = 2;
const BROWSER_TYPE_IPOD = 3;
const BROWSER_TYPE_ANDROID = 4;
const BROWSER_TYPE_XZAPP = 5;
const BROWSER_TYPE_UNKNOWN = -1;
// 系统类型
const OS_TYPE_IOS = 1;
const OS_TYPE_ANDROID = 2;
const OS_TYPE_UNKNOWN = -1;
// 是否RETINA屏
const RETINA_TYPE_YES = 1;
const RETINA_TYPE_NOT = 0;
// 是否IOS6系统
const IOS6_YES = 1;
const IOS6_NOT = 0;
// 是否微信打开
const MICRO_MESSAGE_YES = 1;
const MICRO_MESSAGE_NOT = 0;
// APP已经安装
const APP_INSTALLED_YES = 1;
const APP_INSTALLED_NOT = 0;
// 得到agent完整类型信息
public static function getDeviceInfo()
{
return array(
'deviceType' => self::deviceType(),
'browserType' => self::browserType(),
'isRetina' => self::isRetina(),
'osType' => self::osType(),
'isIos6' => self::isIos6(),
);
}
// 浏览器类型
public static function browserType($agent = '')
{
$agent = self::getAgent($agent);
if (stripos($agent, 'baiduboxapp') !== false) {
return self::BROWSER_TYPE_XZAPP;
}
if (stripos($agent, 'iphone') !== false) {
return self::BROWSER_TYPE_IPHONE;
}
if (stripos($agent, 'ipad') !== false) {
return self::BROWSER_TYPE_IPAD;
}
if (stripos($agent, 'ipod') !== false) {
return self::BROWSER_TYPE_IPOD;
}
if (stripos($agent, 'android') !== false) {
return self::BROWSER_TYPE_ANDROID;
}
return self::BROWSER_TYPE_UNKNOWN;
}
// 系统类型
public static function osType($agent = '')
{
$agent = self::getAgent($agent);
$browserType = self::browserType($agent);
switch ($browserType) {
case self::BROWSER_TYPE_IPHONE:
case self::BROWSER_TYPE_IPAD:
case self::BROWSER_TYPE_IPOD:
$osType = self::OS_TYPE_IOS;
break;
case self::BROWSER_TYPE_ANDROID:
$osType = self::OS_TYPE_ANDROID;
break;
default:
$osType = self::OS_TYPE_UNKNOWN;
}
return $osType;
}
// 设备类型
public static function deviceType()
{
if (self::isMobile()) {
return self::DEVICE_MOBILE;
} else {
return self::DEVICE_DESKTOP;
}
}
// retina屏
public static function isRetina($agent = '')
{
$agent = self::getAgent($agent);
$osType = self::osType($agent);
if (($osType == self::OS_TYPE_IOS) && (self::isIos6($agent) != 1)) {
return self::RETINA_TYPE_YES;
} else {
return self::RETINA_TYPE_NOT;
}
}
// ios6系统的手机(iphone4, iphone4s)
public static function isIos6($agent = '')
{
$agent = self::getAgent($agent);
if (stripos($agent, 'iPhone OS 6')) {
return self::IOS6_YES;
} else {
return self::IOS6_NOT;
}
}
// 检查是否在微信中打开
public static function isMicroMessage($agent = '')
{
$agent = self::getAgent($agent);
if (stripos($agent, 'MicroMessenger') !== false) {
return self::MICRO_MESSAGE_YES;
} else {
return self::MICRO_MESSAGE_NOT;
}
}
// 已安装APP
public static function isAppInstalled()
{
if (isset($_GET['isappinstalled']) && ($_GET['isappinstalled'] == 1)) {
return self::APP_INSTALLED_YES;
} else {
return self::APP_INSTALLED_NOT;
}
}
// 是移动设备访问
public static function isMobile()
{
// 如果有HTTP_X_WAP_PROFILE则一定是移动设备
if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
return true;
}
// 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
if (isset($_SERVER['HTTP_VIA']) && stristr($_SERVER['HTTP_VIA'], "wap")) {
return true;
}
// 脑残法,判断手机发送的客户端标志,兼容性有待提高
if (isset ($_SERVER['HTTP_USER_AGENT'])) {
$clientkeywords = array('nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp',
'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu',
'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave',
'nexusone', 'cldc', 'midp', 'wap', 'mobile', 'WindowsWechat');
// 从HTTP_USER_AGENT中查找手机浏览器的关键字
if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
return true;
}
}
// 协议法,因为有可能不准确,放到最后判断
if (isset($_SERVER['HTTP_ACCEPT'])) {
// 如果只支持wml并且不支持html那一定是移动设备, 如果支持wml和html但是wml在html之前则是移动设备
if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
return true;
}
}
return false;
}
public static function getAgent($agent = '')
{
$agent = empty($agent) ? $_SERVER['HTTP_USER_AGENT'] : $agent;
return $agent;
}
}

57
framework/library/alioss/CHANGELOG.md

@ -0,0 +1,57 @@
# ChangeLog - Aliyun OSS SDK for PHP
## v2.0.7 / 2016-06-17
* Support append object
## v2.0.6
* Trim access key id/secret and endpoint
* Refine tests and setup travis CI
## v2.0.5
* 增加Add/Delete/Get BucketCname接口
## v2.0.4
* 增加Put/Get Object Acl接口
## v2.0.3
* 修复Util中的常量定义在低于5.6的PHP版本中报错的问题
## v2.0.2
* 修复multipart上传时无法指定Content-Type的问题
## v2.0.1
* 增加对ListObjects/ListMultipartUploads时特殊字符的处理
* 提供接口获取OssException中的详细信息
## 2015.11.25
* **大版本升级,不再兼容以前接口,新版本对易用性做了很大的改进,建议用户迁移到新版本。**
## 修改内容
* 不再支持PHP 5.2版本
### 新增内容
* 引入命名空间
* 接口命名修正,采用驼峰式命名
* 接口入参修改,把常用参数从Options参数中提出来
* 接口返回结果修改,对返回结果进行处理,用户可以直接得到容易处理的数据结构 
* OssClient的构造函数变更
* 支持CNAME和IP格式的Endpoint地址
* 重新整理sample文件组织结构,使用function组织功能点
* 增加设置连接超时,请求超时的接口
* 去掉Object Group相关的已经过时的接口
* OssException中的message改为英文
### 问题修复
* object名称校验不完备

21
framework/library/alioss/LICENSE.md

@ -0,0 +1,21 @@
#The MIT License (MIT)
Copyright (c) ali-sdk and other contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

152
framework/library/alioss/README.md

@ -0,0 +1,152 @@
# Aliyun OSS SDK for PHP
[![Latest Stable Version](https://poser.pugx.org/aliyuncs/oss-sdk-php/v/stable)](https://packagist.org/packages/aliyuncs/oss-sdk-php)
[![Build Status](https://travis-ci.org/aliyun/aliyun-oss-php-sdk.svg?branch=master)](https://travis-ci.org/aliyun/aliyun-oss-php-sdk)
[![Coverage Status](https://coveralls.io/repos/github/aliyun/aliyun-oss-php-sdk/badge.svg?branch=master)](https://coveralls.io/github/aliyun/aliyun-oss-php-sdk?branch=master)
## 概述
阿里云对象存储(Object Storage Service,简称OSS),是阿里云对外提供的海量、安全、低成本、高可靠的云存储服务。用户可以通过调用API,在任何应用、任何时间、任何地点上传和下载数据,也可以通过用户Web控制台对数据进行简单的管理。OSS适合存放任意文件类型,适合各种网站、开发企业及开发者使用。
## 运行环境
- PHP 5.3+
- cURL extension
提示:
- Ubuntu下可以使用apt-get包管理器安装php的cURL扩展 `sudo apt-get install php5-curl`
## 安装方法
1. 如果您通过composer管理您的项目依赖,可以在你的项目根目录运行:
$ composer require aliyuncs/oss-sdk-php
或者在你的`composer.json`中声明对Aliyun OSS SDK for PHP的依赖:
"require": {
"aliyuncs/oss-sdk-php": "~2.0"
}
然后通过`composer install`安装依赖。composer安装完成后,在您的PHP代码中引入依赖即可:
require_once __DIR__ . '/vendor/autoload.php';
2. 您也可以直接下载已经打包好的[phar文件][releases-page],然后在你
的代码中引入这个文件即可:
require_once '/path/to/oss-sdk-php.phar';
3. 下载SDK源码,在您的代码中引入SDK目录下的`autoload.php`文件:
require_once '/path/to/oss-sdk/autoload.php';
## 快速使用
### 常用类
| 类名 | 解释 |
|:------------------|:------------------------------------|
|OSS\OssClient | OSS客户端类,用户通过OssClient的实例调用接口 |
|OSS\Core\OssException | OSS异常类,用户在使用的过程中,只需要注意这个异常|
### OssClient初始化
SDK的OSS操作通过OssClient类完成的,下面代码创建一个OssClient对象:
```php
<?php
$accessKeyId = "<您从OSS获得的AccessKeyId>"; ;
$accessKeySecret = "<您从OSS获得的AccessKeySecret>";
$endpoint = "<您选定的OSS数据中心访问域名例如oss-cn-hangzhou.aliyuncs.com>";
try {
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
} catch (OssException $e) {
print $e->getMessage();
}
```
### 文件操作
文件(又称对象,Object)是OSS中最基本的数据单元,您可以把它简单地理解为文件,用下面代码可以实现一个Object的上传:
```php
<?php
$bucket = "<您使用的Bucket名字注意命名规范>";
$object = "<您使用的Object名字注意命名规范>";
$content = "Hello, OSS!"; // 上传的文件内容
try {
$ossClient->putObject($bucket, $object, $content);
} catch (OssException $e) {
print $e->getMessage();
}
```
### 存储空间操作
存储空间(又称Bucket)是一个用户用来管理所存储Object的存储空间,对于用户来说是一个管理Object的单元,所有的Object都必须隶属于某个Bucket。您可以按照下面的代码新建一个Bucket:
```php
<?php
$bucket = "<您使用的Bucket名字注意命名规范>";
try {
$ossClient->createBucket($bucket);
} catch (OssException $e) {
print $e->getMessage();
}
```
### 返回结果处理
OssClient提供的接口返回返回数据分为两种:
* Put,Delete类接口,接口返回null,如果没有OssException,即可认为操作成功
* Get,List类接口,接口返回对应的数据,如果没有OssException,即可认为操作成功,举个例子:
```php
<?php
$bucketListInfo = $ossClient->listBuckets();
$bucketList = $bucketListInfo->getBucketList();
foreach($bucketList as $bucket) {
print($bucket->getLocation() . "\t" . $bucket->getName() . "\t" . $bucket->getCreatedate() . "\n");
}
```
上面代码中的$bucketListInfo的数据类型是 `OSS\Model\BucketListInfo`
### 运行Sample程序
1. 修改 `samples/Config.php`, 补充配置信息
2. 执行 `cd samples/ && php RunAll.php`
### 运行单元测试
1. 执行`composer install`下载依赖的库
2. 设置环境变量
export OSS_ACCESS_KEY_ID=access-key-id
export OSS_ACCESS_KEY_SECRET=access-key-secret
export OSS_ENDPOINT=endpoint
export OSS_BUCKET=bucket-name
3. 执行 `php vendor/bin/phpunit`
## 贡献代码
0. 开发流程参考:https://github.com/rockuw/oss-sdk-status#development-oss-members-only
1. 提交代码后,确保travis CI是PASS的
2. 每发布一个新的版本:
- 运行`build-phar.sh`生成相应的phar包(需要安装[phar-composer][phar-composer])
- 在[Release页面][releases-page]发布一个版本
- 将生成的phar包上传到相应的Release下面
## 联系我们
- [阿里云OSS官方网站](http://oss.aliyun.com)
- [阿里云OSS官方论坛](http://bbs.aliyun.com)
- [阿里云OSS官方文档中心](http://www.aliyun.com/product/oss#Docs)
- 阿里云官方技术支持:[提交工单](https://workorder.console.aliyun.com/#/ticket/createIndex)
[releases-page]: https://github.com/aliyun/aliyun-oss-php-sdk/releases
[phar-composer]: https://github.com/clue/phar-composer

11
framework/library/alioss/autoload.php

@ -0,0 +1,11 @@
<?php
function classLoader($class)
{
$path = str_replace('\\', DIRECTORY_SEPARATOR, $class);
$file = __DIR__ . DIRECTORY_SEPARATOR .'src'. DIRECTORY_SEPARATOR . $path . '.php';
if (file_exists($file)) {
require_once $file;
}
}
spl_autoload_register('classLoader');

3
framework/library/alioss/index.php

@ -0,0 +1,3 @@
<?php
require_once __DIR__ . '/vendor/autoload.php';

262
framework/library/alioss/src/OSS/Core/MimeTypes.php

@ -0,0 +1,262 @@
<?php
namespace OSS\Core;
/**
* Class MimeTypes
*
* 在上传文件的时候,根据文件的缺省名,得到其对应的Content-type
*
* @package OSS\Core
*/
class MimeTypes
{
/**
* 根据文件名,获取http协议header中的content-type应该填写的数据
*
* @param string $name 缺省名
* @return string content-type
*/
public static function getMimetype($name)
{
$parts = explode('.', $name);
if (count($parts) > 1) {
$ext = strtolower(end($parts));
if (isset(self::$mime_types[$ext])) {
return self::$mime_types[$ext];
}
}
return null;
}
private static $mime_types = array(
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
'apk' => 'application/vnd.android.package-archive',
'hqx' => 'application/mac-binhex40',
'cpt' => 'application/mac-compactpro',
'doc' => 'application/msword',
'ogg' => 'audio/ogg',
'pdf' => 'application/pdf',
'rtf' => 'text/rtf',
'mif' => 'application/vnd.mif',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
'odc' => 'application/vnd.oasis.opendocument.chart',
'odb' => 'application/vnd.oasis.opendocument.database',
'odf' => 'application/vnd.oasis.opendocument.formula',
'odg' => 'application/vnd.oasis.opendocument.graphics',
'otg' => 'application/vnd.oasis.opendocument.graphics-template',
'odi' => 'application/vnd.oasis.opendocument.image',
'odp' => 'application/vnd.oasis.opendocument.presentation',
'otp' => 'application/vnd.oasis.opendocument.presentation-template',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template',
'odt' => 'application/vnd.oasis.opendocument.text',
'odm' => 'application/vnd.oasis.opendocument.text-master',
'ott' => 'application/vnd.oasis.opendocument.text-template',
'oth' => 'application/vnd.oasis.opendocument.text-web',
'sxw' => 'application/vnd.sun.xml.writer',
'stw' => 'application/vnd.sun.xml.writer.template',
'sxc' => 'application/vnd.sun.xml.calc',
'stc' => 'application/vnd.sun.xml.calc.template',
'sxd' => 'application/vnd.sun.xml.draw',
'std' => 'application/vnd.sun.xml.draw.template',
'sxi' => 'application/vnd.sun.xml.impress',
'sti' => 'application/vnd.sun.xml.impress.template',
'sxg' => 'application/vnd.sun.xml.writer.global',
'sxm' => 'application/vnd.sun.xml.math',
'sis' => 'application/vnd.symbian.install',
'wbxml' => 'application/vnd.wap.wbxml',
'wmlc' => 'application/vnd.wap.wmlc',
'wmlsc' => 'application/vnd.wap.wmlscriptc',
'bcpio' => 'application/x-bcpio',
'torrent' => 'application/x-bittorrent',
'bz2' => 'application/x-bzip2',
'vcd' => 'application/x-cdlink',
'pgn' => 'application/x-chess-pgn',
'cpio' => 'application/x-cpio',
'csh' => 'application/x-csh',
'dvi' => 'application/x-dvi',
'spl' => 'application/x-futuresplash',
'gtar' => 'application/x-gtar',
'hdf' => 'application/x-hdf',
'jar' => 'application/java-archive',
'jnlp' => 'application/x-java-jnlp-file',
'js' => 'application/javascript',
'json' => 'application/json',
'ksp' => 'application/x-kspread',
'chrt' => 'application/x-kchart',
'kil' => 'application/x-killustrator',
'latex' => 'application/x-latex',
'rpm' => 'application/x-rpm',
'sh' => 'application/x-sh',
'shar' => 'application/x-shar',
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'sv4cpio' => 'application/x-sv4cpio',
'sv4crc' => 'application/x-sv4crc',
'tar' => 'application/x-tar',
'tcl' => 'application/x-tcl',
'tex' => 'application/x-tex',
'man' => 'application/x-troff-man',
'me' => 'application/x-troff-me',
'ms' => 'application/x-troff-ms',
'ustar' => 'application/x-ustar',
'src' => 'application/x-wais-source',
'zip' => 'application/zip',
'm3u' => 'audio/x-mpegurl',
'ra' => 'audio/x-pn-realaudio',
'wav' => 'audio/x-wav',
'wma' => 'audio/x-ms-wma',
'wax' => 'audio/x-ms-wax',
'pdb' => 'chemical/x-pdb',
'xyz' => 'chemical/x-xyz',
'bmp' => 'image/bmp',
'gif' => 'image/gif',
'ief' => 'image/ief',
'png' => 'image/png',
'wbmp' => 'image/vnd.wap.wbmp',
'ras' => 'image/x-cmu-raster',
'pnm' => 'image/x-portable-anymap',
'pbm' => 'image/x-portable-bitmap',
'pgm' => 'image/x-portable-graymap',
'ppm' => 'image/x-portable-pixmap',
'rgb' => 'image/x-rgb',
'xbm' => 'image/x-xbitmap',
'xpm' => 'image/x-xpixmap',
'xwd' => 'image/x-xwindowdump',
'css' => 'text/css',
'rtx' => 'text/richtext',
'tsv' => 'text/tab-separated-values',
'jad' => 'text/vnd.sun.j2me.app-descriptor',
'wml' => 'text/vnd.wap.wml',
'wmls' => 'text/vnd.wap.wmlscript',
'etx' => 'text/x-setext',
'mxu' => 'video/vnd.mpegurl',
'flv' => 'video/x-flv',
'wm' => 'video/x-ms-wm',
'wmv' => 'video/x-ms-wmv',
'wmx' => 'video/x-ms-wmx',
'wvx' => 'video/x-ms-wvx',
'avi' => 'video/x-msvideo',
'movie' => 'video/x-sgi-movie',
'ice' => 'x-conference/x-cooltalk',
'3gp' => 'video/3gpp',
'ai' => 'application/postscript',
'aif' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'asc' => 'text/plain',
'atom' => 'application/atom+xml',
'au' => 'audio/basic',
'bin' => 'application/octet-stream',
'cdf' => 'application/x-netcdf',
'cgm' => 'image/cgm',
'class' => 'application/octet-stream',
'dcr' => 'application/x-director',
'dif' => 'video/x-dv',
'dir' => 'application/x-director',
'djv' => 'image/vnd.djvu',
'djvu' => 'image/vnd.djvu',
'dll' => 'application/octet-stream',
'dmg' => 'application/octet-stream',
'dms' => 'application/octet-stream',
'dtd' => 'application/xml-dtd',
'dv' => 'video/x-dv',
'dxr' => 'application/x-director',
'eps' => 'application/postscript',
'exe' => 'application/octet-stream',
'ez' => 'application/andrew-inset',
'gram' => 'application/srgs',
'grxml' => 'application/srgs+xml',
'gz' => 'application/x-gzip',
'htm' => 'text/html',
'html' => 'text/html',
'ico' => 'image/x-icon',
'ics' => 'text/calendar',
'ifb' => 'text/calendar',
'iges' => 'model/iges',
'igs' => 'model/iges',
'jp2' => 'image/jp2',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'kar' => 'audio/midi',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'm4a' => 'audio/mp4a-latm',
'm4p' => 'audio/mp4a-latm',
'm4u' => 'video/vnd.mpegurl',
'm4v' => 'video/x-m4v',
'mac' => 'image/x-macpaint',
'mathml' => 'application/mathml+xml',
'mesh' => 'model/mesh',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mov' => 'video/quicktime',
'mp2' => 'audio/mpeg',
'mp3' => 'audio/mpeg',
'mp4' => 'video/mp4',
'mpe' => 'video/mpeg',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpga' => 'audio/mpeg',
'msh' => 'model/mesh',
'nc' => 'application/x-netcdf',
'oda' => 'application/oda',
'ogv' => 'video/ogv',
'pct' => 'image/pict',
'pic' => 'image/pict',
'pict' => 'image/pict',
'pnt' => 'image/x-macpaint',
'pntg' => 'image/x-macpaint',
'ps' => 'application/postscript',
'qt' => 'video/quicktime',
'qti' => 'image/x-quicktime',
'qtif' => 'image/x-quicktime',
'ram' => 'audio/x-pn-realaudio',
'rdf' => 'application/rdf+xml',
'rm' => 'application/vnd.rn-realmedia',
'roff' => 'application/x-troff',
'sgm' => 'text/sgml',
'sgml' => 'text/sgml',
'silo' => 'model/mesh',
'skd' => 'application/x-koan',
'skm' => 'application/x-koan',
'skp' => 'application/x-koan',
'skt' => 'application/x-koan',
'smi' => 'application/smil',
'smil' => 'application/smil',
'snd' => 'audio/basic',
'so' => 'application/octet-stream',
'svg' => 'image/svg+xml',
't' => 'application/x-troff',
'texi' => 'application/x-texinfo',
'texinfo' => 'application/x-texinfo',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'tr' => 'application/x-troff',
'txt' => 'text/plain',
'vrml' => 'model/vrml',
'vxml' => 'application/voicexml+xml',
'webm' => 'video/webm',
'webp' => 'image/webp',
'wrl' => 'model/vrml',
'xht' => 'application/xhtml+xml',
'xhtml' => 'application/xhtml+xml',
'xml' => 'application/xml',
'xsl' => 'application/xml',
'xslt' => 'application/xslt+xml',
'xul' => 'application/vnd.mozilla.xul+xml',
);
}

54
framework/library/alioss/src/OSS/Core/OssException.php

@ -0,0 +1,54 @@
<?php
namespace OSS\Core;
/**
* Class OssException
*
* OssClient在使用的时候,所抛出的异常,用户在使用OssClient的时候,要Try住相关代码,
* try的Exception应该是OssException,其中会得到相关异常原因
*
* @package OSS\Core
*/
class OssException extends \Exception
{
private $details = array();
function __construct($details)
{
if (is_array($details)) {
$message = $details['code'] . ': ' . $details['message']
. ' RequestId: ' . $details['request-id'];
parent::__construct($message);
$this->details = $details;
} else {
$message = $details;
parent::__construct($message);
}
}
public function getHTTPStatus()
{
return isset($this->details['status']) ? $this->details['status'] : '';
}
public function getRequestId()
{
return isset($this->details['request-id']) ? $this->details['request-id'] : '';
}
public function getErrorCode()
{
return isset($this->details['code']) ? $this->details['code'] : '';
}
public function getErrorMessage()
{
return isset($this->details['message']) ? $this->details['message'] : '';
}
public function getDetails()
{
return isset($this->details['body']) ? $this->details['body'] : '';
}
}

448
framework/library/alioss/src/OSS/Core/OssUtil.php

@ -0,0 +1,448 @@
<?php
namespace OSS\Core;
/**
* Class OssUtil
*
* Oss工具类,主要供OssClient使用,用户也可以使用本类进行返回结果的格式化
*
* @package OSS
*/
class OssUtil
{
const OSS_CONTENT = 'content';
const OSS_LENGTH = 'length';
const OSS_HEADERS = 'headers';
const OSS_MAX_OBJECT_GROUP_VALUE = 1000;
const OSS_MAX_PART_SIZE = 5368709120; // 5GB
const OSS_MID_PART_SIZE = 10485760; // 10MB
const OSS_MIN_PART_SIZE = 102400; // 100KB
/**
* 生成query params
*
* @param array $options 关联数组
* @return string 返回诸如 key1=value1&key2=value2
*/
public static function toQueryString($options = array())
{
$temp = array();
uksort($options, 'strnatcasecmp');
foreach ($options as $key => $value) {
if (is_string($key) && !is_array($value)) {
$temp[] = rawurlencode($key) . '=' . rawurlencode($value);
}
}
return implode('&', $temp);
}
/**
* 转义字符替换
*
* @param string $subject
* @return string
*/
public static function sReplace($subject)
{
$search = array('<', '>', '&', '\'', '"');
$replace = array('&lt;', '&gt;', '&amp;', '&apos;', '&quot;');
return str_replace($search, $replace, $subject);
}
/**
* 检查是否是中文编码
*
* @param $str
* @return int
*/
public static function chkChinese($str)
{
return preg_match('/[\x80-\xff]./', $str);
}
/**
* 检测是否GB2312编码
*
* @param string $str
* @return boolean false UTF-8编码 TRUE GB2312编码
*/
public static function isGb2312($str)
{
for ($i = 0; $i < strlen($str); $i++) {
$v = ord($str[$i]);
if ($v > 127) {
if (($v >= 228) && ($v <= 233)) {
if (($i + 2) >= (strlen($str) - 1)) return true; // not enough characters
$v1 = ord($str[$i + 1]);
$v2 = ord($str[$i + 2]);
if (($v1 >= 128) && ($v1 <= 191) && ($v2 >= 128) && ($v2 <= 191))
return false;
else
return true;
}
}
}
return false;
}
/**
* 检测是否GBK编码
*
* @param string $str
* @param boolean $gbk
* @return boolean
*/
public static function checkChar($str, $gbk = true)
{
for ($i = 0; $i < strlen($str); $i++) {
$v = ord($str[$i]);
if ($v > 127) {
if (($v >= 228) && ($v <= 233)) {
if (($i + 2) >= (strlen($str) - 1)) return $gbk ? true : FALSE; // not enough characters
$v1 = ord($str[$i + 1]);
$v2 = ord($str[$i + 2]);
if ($gbk) {
return (($v1 >= 128) && ($v1 <= 191) && ($v2 >= 128) && ($v2 <= 191)) ? FALSE : TRUE;//GBK
} else {
return (($v1 >= 128) && ($v1 <= 191) && ($v2 >= 128) && ($v2 <= 191)) ? TRUE : FALSE;
}
}
}
}
return $gbk ? TRUE : FALSE;
}
/**
* 检验bucket名称是否合法
* bucket的命名规范:
* 1. 只能包括小写字母,数字
* 2. 必须以小写字母或者数字开头
* 3. 长度必须在3-63字节之间
*
* @param string $bucket Bucket名称
* @return boolean
*/
public static function validateBucket($bucket)
{
$pattern = '/^[a-z0-9][a-z0-9-]{2,62}$/';
if (!preg_match($pattern, $bucket)) {
return false;
}
return true;
}
/**
* 检验object名称是否合法
* object命名规范:
* 1. 规则长度必须在1-1023字节之间
* 2. 使用UTF-8编码
* 3. 不能以 "/" "\\"开头
*
* @param string $object Object名称
* @return boolean
*/
public static function validateObject($object)
{
$pattern = '/^.{1,1023}$/';
if (empty($object) || !preg_match($pattern, $object) ||
self::startsWith($object, '/') || self::startsWith($object, '\\')
) {
return false;
}
return true;
}
/**
* 判断字符串$str是不是以$findMe开始
*
* @param string $str
* @param string $findMe
* @return bool
*/
public static function startsWith($str, $findMe)
{
if (strpos($str, $findMe) === 0) {
return true;
} else {
return false;
}
}
/**
* 检验$options
*
* @param array $options
* @throws OssException
* @return boolean
*/
public static function validateOptions($options)
{
//$options
if ($options != NULL && !is_array($options)) {
throw new OssException ($options . ':' . 'option must be array');
}
}
/**
* 检查上传文件的内容是否合法
*
* @param $content string
* @throws OssException
*/
public static function validateContent($content)
{
if (empty($content)) {
throw new OssException("http body content is invalid");
}
}
/**
* 校验BUCKET/OBJECT/OBJECT GROUP是否为空
*
* @param string $name
* @param string $errMsg
* @throws OssException
* @return void
*/
public static function throwOssExceptionWithMessageIfEmpty($name, $errMsg)
{
if (empty($name)) {
throw new OssException($errMsg);
}
}
/**
* 仅供测试使用的接口,请勿使用
*
* @param $filename
* @param $size
*/
public static function generateFile($filename, $size)
{
if (file_exists($filename) && $size == filesize($filename)) {
echo $filename . " already exists, no need to create again. ";
return;
}
$part_size = 1 * 1024 * 1024;
$fp = fopen($filename, "w");
$characters = <<<BBB
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
BBB;
$charactersLength = strlen($characters);
if ($fp) {
while ($size > 0) {
if ($size < $part_size) {
$write_size = $size;
} else {
$write_size = $part_size;
}
$size -= $write_size;
$a = $characters[rand(0, $charactersLength - 1)];
$content = str_repeat($a, $write_size);
$flag = fwrite($fp, $content);
if (!$flag) {
echo "write to " . $filename . " failed. <br>";
break;
}
}
} else {
echo "open " . $filename . " failed. <br>";
}
fclose($fp);
}
/**
* 得到文件的md5编码
*
* @param $filename
* @param $from_pos
* @param $to_pos
* @return string
*/
public static function getMd5SumForFile($filename, $from_pos, $to_pos)
{
$content_md5 = "";
if (($to_pos - $from_pos) > self::OSS_MAX_PART_SIZE) {
return $content_md5;
}
$filesize = filesize($filename);
if ($from_pos >= $filesize || $to_pos >= $filesize || $from_pos < 0 || $to_pos < 0) {
return $content_md5;
}
$total_length = $to_pos - $from_pos + 1;
$buffer = 8192;
$left_length = $total_length;
if (!file_exists($filename)) {
return $content_md5;
}
if (false === $fh = fopen($filename, 'rb')) {
return $content_md5;
}
fseek($fh, $from_pos);
$data = '';
while (!feof($fh)) {
if ($left_length >= $buffer) {
$read_length = $buffer;
} else {
$read_length = $left_length;
}
if ($read_length <= 0) {
break;
} else {
$data .= fread($fh, $read_length);
$left_length = $left_length - $read_length;
}
}
fclose($fh);
$content_md5 = base64_encode(md5($data, true));
return $content_md5;
}
/**
* 检测是否windows系统,因为windows系统默认编码为GBK
*
* @return bool
*/
public static function isWin()
{
return strtoupper(substr(PHP_OS, 0, 3)) == "WIN";
}
/**
* 主要是由于windows系统编码是gbk,遇到中文时候,如果不进行转换处理会出现找不到文件的问题
*
* @param $file_path
* @return string
*/
public static function encodePath($file_path)
{
if (self::chkChinese($file_path) && self::isWin()) {
$file_path = iconv('utf-8', 'gbk', $file_path);
}
return $file_path;
}
/**
* 判断用户输入的endpoint是否是 xxx.xxx.xxx.xxx:port 或者 xxx.xxx.xxx.xxx的ip格式
*
* @param string $endpoint 需要做判断的endpoint
* @return boolean
*/
public static function isIPFormat($endpoint)
{
$ip_array = explode(":", $endpoint);
$hostname = $ip_array[0];
$ret = filter_var($hostname, FILTER_VALIDATE_IP);
if (!$ret) {
return false;
} else {
return true;
}
}
/**
* 生成DeleteMultiObjects接口的xml消息
*
* @param string[] $objects
* @param bool $quiet
* @return string
*/
public static function createDeleteObjectsXmlBody($objects, $quiet)
{
$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><Delete></Delete>');
$xml->addChild('Quiet', $quiet);
foreach ($objects as $object) {
$sub_object = $xml->addChild('Object');
$object = OssUtil::sReplace($object);
$sub_object->addChild('Key', $object);
}
return $xml->asXML();
}
/**
* 生成CompleteMultipartUpload接口的xml消息
*
* @param array[] $listParts
* @return string
*/
public static function createCompleteMultipartUploadXmlBody($listParts)
{
$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><CompleteMultipartUpload></CompleteMultipartUpload>');
foreach ($listParts as $node) {
$part = $xml->addChild('Part');
$part->addChild('PartNumber', $node['PartNumber']);
$part->addChild('ETag', $node['ETag']);
}
return $xml->asXML();
}
/**
* 读取目录
*
* @param string $dir
* @param string $exclude
* @param bool $recursive
* @return string[]
*/
public static function readDir($dir, $exclude = ".|..|.svn|.git", $recursive = false)
{
$file_list_array = array();
$base_path = $dir;
$exclude_array = explode("|", $exclude);
$exclude_array = array_unique(array_merge($exclude_array, array('.', '..')));
if ($recursive) {
foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir)) as $new_file) {
if ($new_file->isDir()) continue;
$object = str_replace($base_path, '', $new_file);
if (!in_array(strtolower($object), $exclude_array)) {
$object = ltrim($object, '/');
if (is_file($new_file)) {
$key = md5($new_file . $object, false);
$file_list_array[$key] = array('path' => $new_file, 'file' => $object,);
}
}
}
} else if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (!in_array(strtolower($file), $exclude_array)) {
$new_file = $dir . '/' . $file;
$object = $file;
$object = ltrim($object, '/');
if (is_file($new_file)) {
$key = md5($new_file . $object, false);
$file_list_array[$key] = array('path' => $new_file, 'file' => $object,);
}
}
}
closedir($handle);
}
return $file_list_array;
}
/**
* Decode key based on the encoding type
*
* @param string $key
* @param string $encoding
* @return string
*/
public static function decodeKey($key, $encoding)
{
if ($encoding == "") {
return $key;
}
if ($encoding == "url") {
return rawurldecode($key);
} else {
throw new OssException("Unrecognized encoding type: " . $encoding);
}
}
}

25
framework/library/alioss/src/OSS/Http/LICENSE

@ -0,0 +1,25 @@
Copyright (c) 2006-2010 Ryan Parman, Foleeo Inc., and contributors. All rights reserved.
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.
* Neither the name of Ryan Parman, Foleeo Inc. nor the names of its contributors may be used to
endorse or promote products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDERS
AND 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.

937
framework/library/alioss/src/OSS/Http/RequestCore.php

@ -0,0 +1,937 @@
<?php
namespace OSS\Http;
/**
* Handles all HTTP requests using cURL and manages the responses.
*
* @version 2011.06.07
* @copyright 2006-2011 Ryan Parman
* @copyright 2006-2010 Foleeo Inc.
* @copyright 2010-2011 Amazon.com, Inc. or its affiliates.
* @copyright 2008-2011 Contributors
* @license http://opensource.org/licenses/bsd-license.php Simplified BSD License
*/
class RequestCore
{
/**
* The URL being requested.
*/
public $request_url;
/**
* The headers being sent in the request.
*/
public $request_headers;
/**
* The body being sent in the request.
*/
public $request_body;
/**
* The response returned by the request.
*/
public $response;
/**
* The headers returned by the request.
*/
public $response_headers;
/**
* The body returned by the request.
*/
public $response_body;
/**
* The HTTP status code returned by the request.
*/
public $response_code;
/**
* Additional response data.
*/
public $response_info;
/**
* The handle for the cURL object.
*/
public $curl_handle;
/**
* The method by which the request is being made.
*/
public $method;
/**
* Stores the proxy settings to use for the request.
*/
public $proxy = null;
/**
* The username to use for the request.
*/
public $username = null;
/**
* The password to use for the request.
*/
public $password = null;
/**
* Custom CURLOPT settings.
*/
public $curlopts = null;
/**
* The state of debug mode.
*/
public $debug_mode = false;
/**
* The default class to use for HTTP Requests (defaults to <RequestCore>).
*/
public $request_class = 'OSS\Http\RequestCore';
/**
* The default class to use for HTTP Responses (defaults to <ResponseCore>).
*/
public $response_class = 'OSS\Http\ResponseCore';
/**
* Default useragent string to use.
*/
public $useragent = 'RequestCore/1.4.3';
/**
* File to read from while streaming up.
*/
public $read_file = null;
/**
* The resource to read from while streaming up.
*/
public $read_stream = null;
/**
* The size of the stream to read from.
*/
public $read_stream_size = null;
/**
* The length already read from the stream.
*/
public $read_stream_read = 0;
/**
* File to write to while streaming down.
*/
public $write_file = null;
/**
* The resource to write to while streaming down.
*/
public $write_stream = null;
/**
* Stores the intended starting seek position.
*/
public $seek_position = null;
/**
* The location of the cacert.pem file to use.
*/
public $cacert_location = false;
/**
* The state of SSL certificate verification.
*/
public $ssl_verification = true;
/**
* The user-defined callback function to call when a stream is read from.
*/
public $registered_streaming_read_callback = null;
/**
* The user-defined callback function to call when a stream is written to.
*/
public $registered_streaming_write_callback = null;
/**
* 请求超时时间, 默认是5184000秒,6天
*
* @var int
*/
public $timeout = 5184000;
/**
* 连接超时时间,默认是10秒
*
* @var int
*/
public $connect_timeout = 10;
/*%******************************************************************************************%*/
// CONSTANTS
/**
* GET HTTP Method
*/
const HTTP_GET = 'GET';
/**
* POST HTTP Method
*/
const HTTP_POST = 'POST';
/**
* PUT HTTP Method
*/
const HTTP_PUT = 'PUT';
/**
* DELETE HTTP Method
*/
const HTTP_DELETE = 'DELETE';
/**
* HEAD HTTP Method
*/
const HTTP_HEAD = 'HEAD';
/*%******************************************************************************************%*/
// CONSTRUCTOR/DESTRUCTOR
/**
* Constructs a new instance of this class.
*
* @param string $url (Optional) The URL to request or service endpoint to query.
* @param string $proxy (Optional) The faux-url to use for proxy settings. Takes the following format: `proxy://user:pass@hostname:port`
* @param array $helpers (Optional) An associative array of classnames to use for request, and response functionality. Gets passed in automatically by the calling class.
* @return $this A reference to the current instance.
*/
public function __construct($url = null, $proxy = null, $helpers = null)
{
// Set some default values.
$this->request_url = $url;
$this->method = self::HTTP_GET;
$this->request_headers = array();
$this->request_body = '';
// Set a new Request class if one was set.
if (isset($helpers['request']) && !empty($helpers['request'])) {
$this->request_class = $helpers['request'];
}
// Set a new Request class if one was set.
if (isset($helpers['response']) && !empty($helpers['response'])) {
$this->response_class = $helpers['response'];
}
if ($proxy) {
$this->set_proxy($proxy);
}
return $this;
}
/**
* Destructs the instance. Closes opened file handles.
*
* @return $this A reference to the current instance.
*/
public function __destruct()
{
if (isset($this->read_file) && isset($this->read_stream)) {
fclose($this->read_stream);
}
if (isset($this->write_file) && isset($this->write_stream)) {
fclose($this->write_stream);
}
return $this;
}
/*%******************************************************************************************%*/
// REQUEST METHODS
/**
* Sets the credentials to use for authentication.
*
* @param string $user (Required) The username to authenticate with.
* @param string $pass (Required) The password to authenticate with.
* @return $this A reference to the current instance.
*/
public function set_credentials($user, $pass)
{
$this->username = $user;
$this->password = $pass;
return $this;
}
/**
* Adds a custom HTTP header to the cURL request.
*
* @param string $key (Required) The custom HTTP header to set.
* @param mixed $value (Required) The value to assign to the custom HTTP header.
* @return $this A reference to the current instance.
*/
public function add_header($key, $value)
{
$this->request_headers[$key] = $value;
return $this;
}
/**
* Removes an HTTP header from the cURL request.
*
* @param string $key (Required) The custom HTTP header to set.
* @return $this A reference to the current instance.
*/
public function remove_header($key)
{
if (isset($this->request_headers[$key])) {
unset($this->request_headers[$key]);
}
return $this;
}
/**
* Set the method type for the request.
*
* @param string $method (Required) One of the following constants: <HTTP_GET>, <HTTP_POST>, <HTTP_PUT>, <HTTP_HEAD>, <HTTP_DELETE>.
* @return $this A reference to the current instance.
*/
public function set_method($method)
{
$this->method = strtoupper($method);
return $this;
}
/**
* Sets a custom useragent string for the class.
*
* @param string $ua (Required) The useragent string to use.
* @return $this A reference to the current instance.
*/
public function set_useragent($ua)
{
$this->useragent = $ua;
return $this;
}
/**
* Set the body to send in the request.
*
* @param string $body (Required) The textual content to send along in the body of the request.
* @return $this A reference to the current instance.
*/
public function set_body($body)
{
$this->request_body = $body;
return $this;
}
/**
* Set the URL to make the request to.
*
* @param string $url (Required) The URL to make the request to.
* @return $this A reference to the current instance.
*/
public function set_request_url($url)
{
$this->request_url = $url;
return $this;
}
/**
* Set additional CURLOPT settings. These will merge with the default settings, and override if
* there is a duplicate.
*
* @param array $curlopts (Optional) A set of key-value pairs that set `CURLOPT` options. These will merge with the existing CURLOPTs, and ones passed here will override the defaults. Keys should be the `CURLOPT_*` constants, not strings.
* @return $this A reference to the current instance.
*/
public function set_curlopts($curlopts)
{
$this->curlopts = $curlopts;
return $this;
}
/**
* Sets the length in bytes to read from the stream while streaming up.
*
* @param integer $size (Required) The length in bytes to read from the stream.
* @return $this A reference to the current instance.
*/
public function set_read_stream_size($size)
{
$this->read_stream_size = $size;
return $this;
}
/**
* Sets the resource to read from while streaming up. Reads the stream from its current position until
* EOF or `$size` bytes have been read. If `$size` is not given it will be determined by <php:fstat()> and
* <php:ftell()>.
*
* @param resource $resource (Required) The readable resource to read from.
* @param integer $size (Optional) The size of the stream to read.
* @return $this A reference to the current instance.
*/
public function set_read_stream($resource, $size = null)
{
if (!isset($size) || $size < 0) {
$stats = fstat($resource);
if ($stats && $stats['size'] >= 0) {
$position = ftell($resource);
if ($position !== false && $position >= 0) {
$size = $stats['size'] - $position;
}
}
}
$this->read_stream = $resource;
return $this->set_read_stream_size($size);
}
/**
* Sets the file to read from while streaming up.
*
* @param string $location (Required) The readable location to read from.
* @return $this A reference to the current instance.
*/
public function set_read_file($location)
{
$this->read_file = $location;
$read_file_handle = fopen($location, 'r');
return $this->set_read_stream($read_file_handle);
}
/**
* Sets the resource to write to while streaming down.
*
* @param resource $resource (Required) The writeable resource to write to.
* @return $this A reference to the current instance.
*/
public function set_write_stream($resource)
{
$this->write_stream = $resource;
return $this;
}
/**
* Sets the file to write to while streaming down.
*
* @param string $location (Required) The writeable location to write to.
* @return $this A reference to the current instance.
*/
public function set_write_file($location)
{
$this->write_file = $location;
$write_file_handle = fopen($location, 'w');
return $this->set_write_stream($write_file_handle);
}
/**
* Set the proxy to use for making requests.
*
* @param string $proxy (Required) The faux-url to use for proxy settings. Takes the following format: `proxy://user:pass@hostname:port`
* @return $this A reference to the current instance.
*/
public function set_proxy($proxy)
{
$proxy = parse_url($proxy);
$proxy['user'] = isset($proxy['user']) ? $proxy['user'] : null;
$proxy['pass'] = isset($proxy['pass']) ? $proxy['pass'] : null;
$proxy['port'] = isset($proxy['port']) ? $proxy['port'] : null;
$this->proxy = $proxy;
return $this;
}
/**
* Set the intended starting seek position.
*
* @param integer $position (Required) The byte-position of the stream to begin reading from.
* @return $this A reference to the current instance.
*/
public function set_seek_position($position)
{
$this->seek_position = isset($position) ? (integer)$position : null;
return $this;
}
/**
* Register a callback function to execute whenever a data stream is read from using
* <CFRequest::streaming_read_callback()>.
*
* The user-defined callback function should accept three arguments:
*
* <ul>
* <li><code>$curl_handle</code> - <code>resource</code> - Required - The cURL handle resource that represents the in-progress transfer.</li>
* <li><code>$file_handle</code> - <code>resource</code> - Required - The file handle resource that represents the file on the local file system.</li>
* <li><code>$length</code> - <code>integer</code> - Required - The length in kilobytes of the data chunk that was transferred.</li>
* </ul>
*
* @param string|array|function $callback (Required) The callback function is called by <php:call_user_func()>, so you can pass the following values: <ul>
* <li>The name of a global function to execute, passed as a string.</li>
* <li>A method to execute, passed as <code>array('ClassName', 'MethodName')</code>.</li>
* <li>An anonymous function (PHP 5.3+).</li></ul>
* @return $this A reference to the current instance.
*/
public function register_streaming_read_callback($callback)
{
$this->registered_streaming_read_callback = $callback;
return $this;
}
/**
* Register a callback function to execute whenever a data stream is written to using
* <CFRequest::streaming_write_callback()>.
*
* The user-defined callback function should accept two arguments:
*
* <ul>
* <li><code>$curl_handle</code> - <code>resource</code> - Required - The cURL handle resource that represents the in-progress transfer.</li>
* <li><code>$length</code> - <code>integer</code> - Required - The length in kilobytes of the data chunk that was transferred.</li>
* </ul>
*
* @param string|array|function $callback (Required) The callback function is called by <php:call_user_func()>, so you can pass the following values: <ul>
* <li>The name of a global function to execute, passed as a string.</li>
* <li>A method to execute, passed as <code>array('ClassName', 'MethodName')</code>.</li>
* <li>An anonymous function (PHP 5.3+).</li></ul>
* @return $this A reference to the current instance.
*/
public function register_streaming_write_callback($callback)
{
$this->registered_streaming_write_callback = $callback;
return $this;
}
/*%******************************************************************************************%*/
// PREPARE, SEND, AND PROCESS REQUEST
/**
* A callback function that is invoked by cURL for streaming up.
*
* @param resource $curl_handle (Required) The cURL handle for the request.
* @param resource $file_handle (Required) The open file handle resource.
* @param integer $length (Required) The maximum number of bytes to read.
* @return binary Binary data from a stream.
*/
public function streaming_read_callback($curl_handle, $file_handle, $length)
{
// Once we've sent as much as we're supposed to send...
if ($this->read_stream_read >= $this->read_stream_size) {
// Send EOF
return '';
}
// If we're at the beginning of an upload and need to seek...
if ($this->read_stream_read == 0 && isset($this->seek_position) && $this->seek_position !== ftell($this->read_stream)) {
if (fseek($this->read_stream, $this->seek_position) !== 0) {
throw new RequestCore_Exception('The stream does not support seeking and is either not at the requested position or the position is unknown.');
}
}
$read = fread($this->read_stream, min($this->read_stream_size - $this->read_stream_read, $length)); // Remaining upload data or cURL's requested chunk size
$this->read_stream_read += strlen($read);
$out = $read === false ? '' : $read;
// Execute callback function
if ($this->registered_streaming_read_callback) {
call_user_func($this->registered_streaming_read_callback, $curl_handle, $file_handle, $out);
}
return $out;
}
/**
* A callback function that is invoked by cURL for streaming down.
*
* @param resource $curl_handle (Required) The cURL handle for the request.
* @param binary $data (Required) The data to write.
* @return integer The number of bytes written.
*/
public function streaming_write_callback($curl_handle, $data)
{
$length = strlen($data);
$written_total = 0;
$written_last = 0;
while ($written_total < $length) {
$written_last = fwrite($this->write_stream, substr($data, $written_total));
if ($written_last === false) {
return $written_total;
}
$written_total += $written_last;
}
// Execute callback function
if ($this->registered_streaming_write_callback) {
call_user_func($this->registered_streaming_write_callback, $curl_handle, $written_total);
}
return $written_total;
}
/**
* Prepares and adds the details of the cURL request. This can be passed along to a <php:curl_multi_exec()>
* function.
*
* @return resource The handle for the cURL object.
*
*/
public function prep_request()
{
$curl_handle = curl_init();
// Set default options.
curl_setopt($curl_handle, CURLOPT_URL, $this->request_url);
curl_setopt($curl_handle, CURLOPT_FILETIME, true);
curl_setopt($curl_handle, CURLOPT_FRESH_CONNECT, false);
// curl_setopt($curl_handle, CURLOPT_CLOSEPOLICY, CURLCLOSEPOLICY_LEAST_RECENTLY_USED);
curl_setopt($curl_handle, CURLOPT_MAXREDIRS, 5);
curl_setopt($curl_handle, CURLOPT_HEADER, true);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_handle, CURLOPT_TIMEOUT, $this->timeout);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, $this->connect_timeout);
curl_setopt($curl_handle, CURLOPT_NOSIGNAL, true);
curl_setopt($curl_handle, CURLOPT_REFERER, $this->request_url);
curl_setopt($curl_handle, CURLOPT_USERAGENT, $this->useragent);
curl_setopt($curl_handle, CURLOPT_READFUNCTION, array($this, 'streaming_read_callback'));
// Verification of the SSL cert
if ($this->ssl_verification) {
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYHOST, 2);
} else {
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYHOST, false);
}
// chmod the file as 0755
if ($this->cacert_location === true) {
curl_setopt($curl_handle, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
} elseif (is_string($this->cacert_location)) {
curl_setopt($curl_handle, CURLOPT_CAINFO, $this->cacert_location);
}
// Debug mode
if ($this->debug_mode) {
curl_setopt($curl_handle, CURLOPT_VERBOSE, true);
}
// Handle open_basedir & safe mode
if (!ini_get('safe_mode') && !ini_get('open_basedir')) {
curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, true);
}
// Enable a proxy connection if requested.
if ($this->proxy) {
curl_setopt($curl_handle, CURLOPT_HTTPPROXYTUNNEL, true);
$host = $this->proxy['host'];
$host .= ($this->proxy['port']) ? ':' . $this->proxy['port'] : '';
curl_setopt($curl_handle, CURLOPT_PROXY, $host);
if (isset($this->proxy['user']) && isset($this->proxy['pass'])) {
curl_setopt($curl_handle, CURLOPT_PROXYUSERPWD, $this->proxy['user'] . ':' . $this->proxy['pass']);
}
}
// Set credentials for HTTP Basic/Digest Authentication.
if ($this->username && $this->password) {
curl_setopt($curl_handle, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl_handle, CURLOPT_USERPWD, $this->username . ':' . $this->password);
}
// Handle the encoding if we can.
if (extension_loaded('zlib')) {
curl_setopt($curl_handle, CURLOPT_ENCODING, '');
}
// Process custom headers
if (isset($this->request_headers) && count($this->request_headers)) {
$temp_headers = array();
foreach ($this->request_headers as $k => $v) {
$temp_headers[] = $k . ': ' . $v;
}
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $temp_headers);
}
switch ($this->method) {
case self::HTTP_PUT:
//unset($this->read_stream);
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'PUT');
if (isset($this->read_stream)) {
if (!isset($this->read_stream_size) || $this->read_stream_size < 0) {
throw new RequestCore_Exception('The stream size for the streaming upload cannot be determined.');
}
curl_setopt($curl_handle, CURLOPT_INFILESIZE, $this->read_stream_size);
curl_setopt($curl_handle, CURLOPT_UPLOAD, true);
} else {
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $this->request_body);
}
break;
case self::HTTP_POST:
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'POST');
if (isset($this->read_stream)) {
if (!isset($this->read_stream_size) || $this->read_stream_size < 0) {
throw new RequestCore_Exception('The stream size for the streaming upload cannot be determined.');
}
curl_setopt($curl_handle, CURLOPT_INFILESIZE, $this->read_stream_size);
curl_setopt($curl_handle, CURLOPT_UPLOAD, true);
} else {
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $this->request_body);
}
break;
case self::HTTP_HEAD:
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, self::HTTP_HEAD);
curl_setopt($curl_handle, CURLOPT_NOBODY, 1);
break;
default: // Assumed GET
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, $this->method);
if (isset($this->write_stream)) {
curl_setopt($curl_handle, CURLOPT_WRITEFUNCTION, array($this, 'streaming_write_callback'));
curl_setopt($curl_handle, CURLOPT_HEADER, false);
} else {
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $this->request_body);
}
break;
}
// Merge in the CURLOPTs
if (isset($this->curlopts) && sizeof($this->curlopts) > 0) {
foreach ($this->curlopts as $k => $v) {
curl_setopt($curl_handle, $k, $v);
}
}
return $curl_handle;
}
/**
* Take the post-processed cURL data and break it down into useful header/body/info chunks. Uses the
* data stored in the `curl_handle` and `response` properties unless replacement data is passed in via
* parameters.
*
* @param resource $curl_handle (Optional) The reference to the already executed cURL request.
* @param string $response (Optional) The actual response content itself that needs to be parsed.
* @return ResponseCore A <ResponseCore> object containing a parsed HTTP response.
*/
public function process_response($curl_handle = null, $response = null)
{
// Accept a custom one if it's passed.
if ($curl_handle && $response) {
$this->curl_handle = $curl_handle;
$this->response = $response;
}
// As long as this came back as a valid resource...
if (is_resource($this->curl_handle)) {
// Determine what's what.
$header_size = curl_getinfo($this->curl_handle, CURLINFO_HEADER_SIZE);
$this->response_headers = substr($this->response, 0, $header_size);
$this->response_body = substr($this->response, $header_size);
$this->response_code = curl_getinfo($this->curl_handle, CURLINFO_HTTP_CODE);
$this->response_info = curl_getinfo($this->curl_handle);
// Parse out the headers
$this->response_headers = explode("\r\n\r\n", trim($this->response_headers));
$this->response_headers = array_pop($this->response_headers);
$this->response_headers = explode("\r\n", $this->response_headers);
array_shift($this->response_headers);
// Loop through and split up the headers.
$header_assoc = array();
foreach ($this->response_headers as $header) {
$kv = explode(': ', $header);
$header_assoc[strtolower($kv[0])] = isset($kv[1]) ? $kv[1] : '';
}
// Reset the headers to the appropriate property.
$this->response_headers = $header_assoc;
$this->response_headers['_info'] = $this->response_info;
$this->response_headers['_info']['method'] = $this->method;
if ($curl_handle && $response) {
//return new $this->response_class($this->response_headers, $this->response_body, $this->response_code, $this->curl_handle);
return new ResponseCore($this->response_headers, $this->response_body, $this->response_code);
}
}
// Return false
return false;
}
/**
* Sends the request, calling necessary utility functions to update built-in properties.
*
* @param boolean $parse (Optional) Whether to parse the response with ResponseCore or not.
* @return string The resulting unparsed data from the request.
*/
public function send_request($parse = false)
{
set_time_limit(0);
$curl_handle = $this->prep_request();
$this->response = curl_exec($curl_handle);
if ($this->response === false) {
throw new RequestCore_Exception('cURL resource: ' . (string)$curl_handle . '; cURL error: ' . curl_error($curl_handle) . ' (' . curl_errno($curl_handle) . ')');
}
$parsed_response = $this->process_response($curl_handle, $this->response);
curl_close($curl_handle);
if ($parse) {
return $parsed_response;
}
return $this->response;
}
/**
* Sends the request using <php:curl_multi_exec()>, enabling parallel requests. Uses the "rolling" method.
*
* @param array $handles (Required) An indexed array of cURL handles to process simultaneously.
* @param array $opt (Optional) An associative array of parameters that can have the following keys: <ul>
* <li><code>callback</code> - <code>string|array</code> - Optional - The string name of a function to pass the response data to. If this is a method, pass an array where the <code>[0]</code> index is the class and the <code>[1]</code> index is the method name.</li>
* <li><code>limit</code> - <code>integer</code> - Optional - The number of simultaneous requests to make. This can be useful for scaling around slow server responses. Defaults to trusting cURLs judgement as to how many to use.</li></ul>
* @return array Post-processed cURL responses.
*/
public function send_multi_request($handles, $opt = null)
{
set_time_limit(0);
// Skip everything if there are no handles to process.
if (count($handles) === 0) return array();
if (!$opt) $opt = array();
// Initialize any missing options
$limit = isset($opt['limit']) ? $opt['limit'] : -1;
// Initialize
$handle_list = $handles;
$http = new $this->request_class();
$multi_handle = curl_multi_init();
$handles_post = array();
$added = count($handles);
$last_handle = null;
$count = 0;
$i = 0;
// Loop through the cURL handles and add as many as it set by the limit parameter.
while ($i < $added) {
if ($limit > 0 && $i >= $limit) break;
curl_multi_add_handle($multi_handle, array_shift($handles));
$i++;
}
do {
$active = false;
// Start executing and wait for a response.
while (($status = curl_multi_exec($multi_handle, $active)) === CURLM_CALL_MULTI_PERFORM) {
// Start looking for possible responses immediately when we have to add more handles
if (count($handles) > 0) break;
}
// Figure out which requests finished.
$to_process = array();
while ($done = curl_multi_info_read($multi_handle)) {
// Since curl_errno() isn't reliable for handles that were in multirequests, we check the 'result' of the info read, which contains the curl error number, (listed here http://curl.haxx.se/libcurl/c/libcurl-errors.html )
if ($done['result'] > 0) {
throw new RequestCore_Exception('cURL resource: ' . (string)$done['handle'] . '; cURL error: ' . curl_error($done['handle']) . ' (' . $done['result'] . ')');
} // Because curl_multi_info_read() might return more than one message about a request, we check to see if this request is already in our array of completed requests
elseif (!isset($to_process[(int)$done['handle']])) {
$to_process[(int)$done['handle']] = $done;
}
}
// Actually deal with the request
foreach ($to_process as $pkey => $done) {
$response = $http->process_response($done['handle'], curl_multi_getcontent($done['handle']));
$key = array_search($done['handle'], $handle_list, true);
$handles_post[$key] = $response;
if (count($handles) > 0) {
curl_multi_add_handle($multi_handle, array_shift($handles));
}
curl_multi_remove_handle($multi_handle, $done['handle']);
curl_close($done['handle']);
}
} while ($active || count($handles_post) < $added);
curl_multi_close($multi_handle);
ksort($handles_post, SORT_NUMERIC);
return $handles_post;
}
/*%******************************************************************************************%*/
// RESPONSE METHODS
/**
* Get the HTTP response headers from the request.
*
* @param string $header (Optional) A specific header value to return. Defaults to all headers.
* @return string|array All or selected header values.
*/
public function get_response_header($header = null)
{
if ($header) {
return $this->response_headers[strtolower($header)];
}
return $this->response_headers;
}
/**
* Get the HTTP response body from the request.
*
* @return string The response body.
*/
public function get_response_body()
{
return $this->response_body;
}
/**
* Get the HTTP response code from the request.
*
* @return string The HTTP response code.
*/
public function get_response_code()
{
return $this->response_code;
}
}

8
framework/library/alioss/src/OSS/Http/RequestCore_Exception.php

@ -0,0 +1,8 @@
<?php
namespace OSS\Http;
class RequestCore_Exception extends \Exception
{
}

56
framework/library/alioss/src/OSS/Http/ResponseCore.php

@ -0,0 +1,56 @@
<?php
namespace OSS\Http;
/**
* Container for all response-related methods.
*/
class ResponseCore
{
/**
* Stores the HTTP header information.
*/
public $header;
/**
* Stores the SimpleXML response.
*/
public $body;
/**
* Stores the HTTP response code.
*/
public $status;
/**
* Constructs a new instance of this class.
*
* @param array $header (Required) Associative array of HTTP headers (typically returned by <RequestCore::get_response_header()>).
* @param string $body (Required) XML-formatted response from AWS.
* @param integer $status (Optional) HTTP response status code from the request.
* @return Mixed Contains an <php:array> `header` property (HTTP headers as an associative array), a <php:SimpleXMLElement> or <php:string> `body` property, and an <php:integer> `status` code.
*/
public function __construct($header, $body, $status = null)
{
$this->header = $header;
$this->body = $body;
$this->status = $status;
return $this;
}
/**
* Did we receive the status code we expected?
*
* @param integer|array $codes (Optional) The status code(s) to expect. Pass an <php:integer> for a single acceptable value, or an <php:array> of integers for multiple acceptable values.
* @return boolean Whether we received the expected status code or not.
*/
public function isOK($codes = array(200, 201, 204, 206))
{
if (is_array($codes)) {
return in_array($this->status, $codes);
}
return $this->status === $codes;
}
}

78
framework/library/alioss/src/OSS/Model/BucketInfo.php

@ -0,0 +1,78 @@
<?php
namespace OSS\Model;
/**
* Bucket信息,ListBuckets接口返回数据
*
* Class BucketInfo
* @package OSS\Model
*/
class BucketInfo
{
/**
* BucketInfo constructor.
*
* @param string $location
* @param string $name
* @param string $createDate
*/
public function __construct($location, $name, $createDate)
{
$this->location = $location;
$this->name = $name;
$this->createDate = $createDate;
}
/**
* 得到bucket所在的region
*
* @return string
*/
public function getLocation()
{
return $this->location;
}
/**
* 得到bucket的名称
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* 得到bucket的创建时间
*
* @return string
*/
public function getCreateDate()
{
return $this->createDate;
}
/**
* bucket所在的region
*
* @var string
*/
private $location;
/**
* bucket的名称
*
* @var string
*/
private $name;
/**
* bucket的创建事件
*
* @var string
*/
private $createDate;
}

39
framework/library/alioss/src/OSS/Model/BucketListInfo.php

@ -0,0 +1,39 @@
<?php
namespace OSS\Model;
/**
* Class BucketListInfo
*
* ListBuckets接口返回的数据类型
*
* @package OSS\Model
*/
class BucketListInfo
{
/**
* BucketListInfo constructor.
* @param array $bucketList
*/
public function __construct(array $bucketList)
{
$this->bucketList = $bucketList;
}
/**
* 得到BucketInfo列表
*
* @return BucketInfo[]
*/
public function getBucketList()
{
return $this->bucketList;
}
/**
* BucketInfo信息列表
*
* @var array
*/
private $bucketList = array();
}

99
framework/library/alioss/src/OSS/Model/CnameConfig.php

@ -0,0 +1,99 @@
<?php
namespace OSS\Model;
use OSS\Core\OssException;
/**
* Class CnameConfig
* @package OSS\Model
*
* TODO: fix link
* @link http://help.aliyun.com/document_detail/oss/api-reference/cors/PutBucketcors.html
*/
class CnameConfig implements XmlConfig
{
public function __construct()
{
$this->cnameList = array();
}
/**
* @return array
* @example
* array(2) {
* [0]=>
* array(3) {
* ["Domain"]=>
* string(11) "www.foo.com"
* ["Status"]=>
* string(7) "enabled"
* ["LastModified"]=>
* string(8) "20150101"
* }
* [1]=>
* array(3) {
* ["Domain"]=>
* string(7) "bar.com"
* ["Status"]=>
* string(8) "disabled"
* ["LastModified"]=>
* string(8) "20160101"
* }
* }
*/
public function getCnames()
{
return $this->cnameList;
}
public function addCname($cname)
{
if (count($this->cnameList) >= self::OSS_MAX_RULES) {
throw new OssException(
"num of cname in the config exceeds self::OSS_MAX_RULES: " . strval(self::OSS_MAX_RULES));
}
$this->cnameList[] = array('Domain' => $cname);
}
public function parseFromXml($strXml)
{
$xml = simplexml_load_string($strXml);
if (!isset($xml->Cname)) return;
foreach ($xml->Cname as $entry) {
$cname = array();
foreach ($entry as $key => $value) {
$cname[strval($key)] = strval($value);
}
$this->cnameList[] = $cname;
}
}
public function serializeToXml()
{
$strXml = <<<EOF
<?xml version="1.0" encoding="utf-8"?>
<BucketCnameConfiguration>
</BucketCnameConfiguration>
EOF;
$xml = new \SimpleXMLElement($strXml);
foreach ($this->cnameList as $cname) {
$node = $xml->addChild('Cname');
foreach ($cname as $key => $value) {
$node->addChild($key, $value);
}
}
return $xml->asXML();
}
public function __toString()
{
return $this->serializeToXml();
}
const OSS_MAX_RULES = 10;
private $cnameList = array();
}

113
framework/library/alioss/src/OSS/Model/CorsConfig.php

@ -0,0 +1,113 @@
<?php
namespace OSS\Model;
use OSS\Core\OssException;
/**
* Class CorsConfig
* @package OSS\Model
*
* @link http://help.aliyun.com/document_detail/oss/api-reference/cors/PutBucketcors.html
*/
class CorsConfig implements XmlConfig
{
/**
* CorsConfig constructor.
*/
public function __construct()
{
$this->rules = array();
}
/**
* 得到CorsRule列表
*
* @return CorsRule[]
*/
public function getRules()
{
return $this->rules;
}
/**
* 添加一条CorsRule
*
* @param CorsRule $rule
* @throws OssException
*/
public function addRule($rule)
{
if (count($this->rules) >= self::OSS_MAX_RULES) {
throw new OssException("num of rules in the config exceeds self::OSS_MAX_RULES: " . strval(self::OSS_MAX_RULES));
}
$this->rules[] = $rule;
}
/**
* 从xml数据中解析出CorsConfig
*
* @param string $strXml
* @throws OssException
* @return null
*/
public function parseFromXml($strXml)
{
$xml = simplexml_load_string($strXml);
if (!isset($xml->CORSRule)) return;
foreach ($xml->CORSRule as $rule) {
$corsRule = new CorsRule();
foreach ($rule as $key => $value) {
if ($key === self::OSS_CORS_ALLOWED_HEADER) {
$corsRule->addAllowedHeader(strval($value));
} elseif ($key === self::OSS_CORS_ALLOWED_METHOD) {
$corsRule->addAllowedMethod(strval($value));
} elseif ($key === self::OSS_CORS_ALLOWED_ORIGIN) {
$corsRule->addAllowedOrigin(strval($value));
} elseif ($key === self::OSS_CORS_EXPOSE_HEADER) {
$corsRule->addExposeHeader(strval($value));
} elseif ($key === self::OSS_CORS_MAX_AGE_SECONDS) {
$corsRule->setMaxAgeSeconds(strval($value));
}
}
$this->addRule($corsRule);
}
return;
}
/**
* 生成xml字符串
*
* @return string
*/
public function serializeToXml()
{
$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><CORSConfiguration></CORSConfiguration>');
foreach ($this->rules as $rule) {
$xmlRule = $xml->addChild('CORSRule');
$rule->appendToXml($xmlRule);
}
return $xml->asXML();
}
public function __toString()
{
return $this->serializeToXml();
}
const OSS_CORS_ALLOWED_ORIGIN = 'AllowedOrigin';
const OSS_CORS_ALLOWED_METHOD = 'AllowedMethod';
const OSS_CORS_ALLOWED_HEADER = 'AllowedHeader';
const OSS_CORS_EXPOSE_HEADER = 'ExposeHeader';
const OSS_CORS_MAX_AGE_SECONDS = 'MaxAgeSeconds';
const OSS_MAX_RULES = 10;
/**
* orsRule列表
*
* @var CorsRule[]
*/
private $rules = array();
}

150
framework/library/alioss/src/OSS/Model/CorsRule.php

@ -0,0 +1,150 @@
<?php
namespace OSS\Model;
use OSS\Core\OssException;
/**
* Class CorsRule
* @package OSS\Model
* @link http://help.aliyun.com/document_detail/oss/api-reference/cors/PutBucketcors.html
*/
class CorsRule
{
/**
* Rule中增加一条allowedOrigin
*
* @param string $allowedOrigin
*/
public function addAllowedOrigin($allowedOrigin)
{
if (!empty($allowedOrigin)) {
$this->allowedOrigins[] = $allowedOrigin;
}
}
/**
* Rule中增加一条allowedMethod
*
* @param string $allowedMethod
*/
public function addAllowedMethod($allowedMethod)
{
if (!empty($allowedMethod)) {
$this->allowedMethods[] = $allowedMethod;
}
}
/**
* Rule中增加一条allowedHeader
*
* @param string $allowedHeader
*/
public function addAllowedHeader($allowedHeader)
{
if (!empty($allowedHeader)) {
$this->allowedHeaders[] = $allowedHeader;
}
}
/**
* Rule中增加一条exposeHeader
*
* @param string $exposeHeader
*/
public function addExposeHeader($exposeHeader)
{
if (!empty($exposeHeader)) {
$this->exposeHeaders[] = $exposeHeader;
}
}
/**
* @return int
*/
public function getMaxAgeSeconds()
{
return $this->maxAgeSeconds;
}
/**
* @param int $maxAgeSeconds
*/
public function setMaxAgeSeconds($maxAgeSeconds)
{
$this->maxAgeSeconds = $maxAgeSeconds;
}
/**
* 得到AllowedHeaders列表
*
* @return string[]
*/
public function getAllowedHeaders()
{
return $this->allowedHeaders;
}
/**
* 得到AllowedOrigins列表
*
* @return string[]
*/
public function getAllowedOrigins()
{
return $this->allowedOrigins;
}
/**
* 得到AllowedMethods列表
*
* @return string[]
*/
public function getAllowedMethods()
{
return $this->allowedMethods;
}
/**
* 得到ExposeHeaders列表
*
* @return string[]
*/
public function getExposeHeaders()
{
return $this->exposeHeaders;
}
/**
* 根据提供的xmlRule, 把this按照一定的规则插入到$xmlRule中
*
* @param \SimpleXMLElement $xmlRule
* @throws OssException
*/
public function appendToXml(&$xmlRule)
{
if (!isset($this->maxAgeSeconds)) {
throw new OssException("maxAgeSeconds is not set in the Rule");
}
foreach ($this->allowedOrigins as $allowedOrigin) {
$xmlRule->addChild(CorsConfig::OSS_CORS_ALLOWED_ORIGIN, $allowedOrigin);
}
foreach ($this->allowedMethods as $allowedMethod) {
$xmlRule->addChild(CorsConfig::OSS_CORS_ALLOWED_METHOD, $allowedMethod);
}
foreach ($this->allowedHeaders as $allowedHeader) {
$xmlRule->addChild(CorsConfig::OSS_CORS_ALLOWED_HEADER, $allowedHeader);
}
foreach ($this->exposeHeaders as $exposeHeader) {
$xmlRule->addChild(CorsConfig::OSS_CORS_EXPOSE_HEADER, $exposeHeader);
}
$xmlRule->addChild(CorsConfig::OSS_CORS_MAX_AGE_SECONDS, strval($this->maxAgeSeconds));
}
private $allowedHeaders = array();
private $allowedOrigins = array();
private $allowedMethods = array();
private $exposeHeaders = array();
private $maxAgeSeconds = null;
}

88
framework/library/alioss/src/OSS/Model/LifecycleAction.php

@ -0,0 +1,88 @@
<?php
namespace OSS\Model;
/**
* Class LifecycleAction
* @package OSS\Model
* @link http://help.aliyun.com/document_detail/oss/api-reference/bucket/PutBucketLifecycle.html
*/
class LifecycleAction
{
/**
* LifecycleAction constructor.
* @param string $action
* @param string $timeSpec
* @param string $timeValue
*/
public function __construct($action, $timeSpec, $timeValue)
{
$this->action = $action;
$this->timeSpec = $timeSpec;
$this->timeValue = $timeValue;
}
/**
* @return LifecycleAction
*/
public function getAction()
{
return $this->action;
}
/**
* @param string $action
*/
public function setAction($action)
{
$this->action = $action;
}
/**
* @return string
*/
public function getTimeSpec()
{
return $this->timeSpec;
}
/**
* @param string $timeSpec
*/
public function setTimeSpec($timeSpec)
{
$this->timeSpec = $timeSpec;
}
/**
* @return string
*/
public function getTimeValue()
{
return $this->timeValue;
}
/**
* @param string $timeValue
*/
public function setTimeValue($timeValue)
{
$this->timeValue = $timeValue;
}
/**
* appendToXml 把actions插入到xml中
*
* @param \SimpleXMLElement $xmlRule
*/
public function appendToXml(&$xmlRule)
{
$xmlAction = $xmlRule->addChild($this->action);
$xmlAction->addChild($this->timeSpec, $this->timeValue);
}
private $action;
private $timeSpec;
private $timeValue;
}

107
framework/library/alioss/src/OSS/Model/LifecycleConfig.php

@ -0,0 +1,107 @@
<?php
namespace OSS\Model;
use OSS\Core\OssException;
/**
* Class BucketLifecycleConfig
* @package OSS\Model
* @link http://help.aliyun.com/document_detail/oss/api-reference/bucket/PutBucketLifecycle.html
*/
class LifecycleConfig implements XmlConfig
{
/**
* 从xml数据中解析出LifecycleConfig
*
* @param string $strXml
* @throws OssException
* @return null
*/
public function parseFromXml($strXml)
{
$this->rules = array();
$xml = simplexml_load_string($strXml);
if (!isset($xml->Rule)) return;
$this->rules = array();
foreach ($xml->Rule as $rule) {
$id = strval($rule->ID);
$prefix = strval($rule->Prefix);
$status = strval($rule->Status);
$actions = array();
foreach ($rule as $key => $value) {
if ($key === 'ID' || $key === 'Prefix' || $key === 'Status') continue;
$action = $key;
$timeSpec = null;
$timeValue = null;
foreach ($value as $timeSpecKey => $timeValueValue) {
$timeSpec = $timeSpecKey;
$timeValue = strval($timeValueValue);
}
$actions[] = new LifecycleAction($action, $timeSpec, $timeValue);
}
$this->rules[] = new LifecycleRule($id, $prefix, $status, $actions);
}
return;
}
/**
* 生成xml字符串
*
* @return string
*/
public function serializeToXml()
{
$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><LifecycleConfiguration></LifecycleConfiguration>');
foreach ($this->rules as $rule) {
$xmlRule = $xml->addChild('Rule');
$rule->appendToXml($xmlRule);
}
return $xml->asXML();
}
/**
*
* 添加LifecycleRule
*
* @param LifecycleRule $lifecycleRule
* @throws OssException
*/
public function addRule($lifecycleRule)
{
if (!isset($lifecycleRule)) {
throw new OssException("lifecycleRule is null");
}
$this->rules[] = $lifecycleRule;
}
/**
* 将配置转换成字符串,便于用户查看
*
* @return string
*/
public function __toString()
{
return $this->serializeToXml();
}
/**
* 得到所有的生命周期规则
*
* @return LifecycleRule[]
*/
public function getRules()
{
return $this->rules;
}
/**
* @var LifecycleRule[]
*/
private $rules;
}

126
framework/library/alioss/src/OSS/Model/LifecycleRule.php

@ -0,0 +1,126 @@
<?php
namespace OSS\Model;
/**
* Class LifecycleRule
* @package OSS\Model
*
* @link http://help.aliyun.com/document_detail/oss/api-reference/bucket/PutBucketLifecycle.html
*/
class LifecycleRule
{
/**
* 得到规则ID
*
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* @param string $id 规则ID
*/
public function setId($id)
{
$this->id = $id;
}
/**
* 得到文件前缀
*
* @return string
*/
public function getPrefix()
{
return $this->prefix;
}
/**
* 设置文件前缀
*
* @param string $prefix 文件前缀
*/
public function setPrefix($prefix)
{
$this->prefix = $prefix;
}
/**
* Lifecycle规则的状态
*
* @return string
*/
public function getStatus()
{
return $this->status;
}
/**
* 设置Lifecycle规则状态
*
* @param string $status
*/
public function setStatus($status)
{
$this->status = $status;
}
/**
*
* @return LifecycleAction[]
*/
public function getActions()
{
return $this->actions;
}
/**
* @param LifecycleAction[] $actions
*/
public function setActions($actions)
{
$this->actions = $actions;
}
/**
* LifecycleRule constructor.
*
* @param string $id 规则ID
* @param string $prefix 文件前缀
* @param string $status 规则状态,可选[self::LIFECYCLE_STATUS_ENABLED, self::LIFECYCLE_STATUS_DISABLED]
* @param LifecycleAction[] $actions
*/
public function __construct($id, $prefix, $status, $actions)
{
$this->id = $id;
$this->prefix = $prefix;
$this->status = $status;
$this->actions = $actions;
}
/**
* @param \SimpleXMLElement $xmlRule
*/
public function appendToXml(&$xmlRule)
{
$xmlRule->addChild('ID', $this->id);
$xmlRule->addChild('Prefix', $this->prefix);
$xmlRule->addChild('Status', $this->status);
foreach ($this->actions as $action) {
$action->appendToXml($xmlRule);
}
}
private $id;
private $prefix;
private $status;
private $actions = array();
const LIFECYCLE_STATUS_ENABLED = 'Enabled';
const LIFECYCLE_STATUS_DISABLED = 'Disabled';
}

134
framework/library/alioss/src/OSS/Model/ListMultipartUploadInfo.php

@ -0,0 +1,134 @@
<?php
namespace OSS\Model;
/**
* Class ListMultipartUploadInfo
* @package OSS\Model
*
* @link http://help.aliyun.com/document_detail/oss/api-reference/multipart-upload/ListMultipartUploads.html
*/
class ListMultipartUploadInfo
{
/**
* ListMultipartUploadInfo constructor.
*
* @param string $bucket
* @param string $keyMarker
* @param string $uploadIdMarker
* @param string $nextKeyMarker
* @param string $nextUploadIdMarker
* @param string $delimiter
* @param string $prefix
* @param int $maxUploads
* @param string $isTruncated
* @param array $uploads
*/
public function __construct($bucket, $keyMarker, $uploadIdMarker, $nextKeyMarker, $nextUploadIdMarker, $delimiter, $prefix, $maxUploads, $isTruncated, array $uploads)
{
$this->bucket = $bucket;
$this->keyMarker = $keyMarker;
$this->uploadIdMarker = $uploadIdMarker;
$this->nextKeyMarker = $nextKeyMarker;
$this->nextUploadIdMarker = $nextUploadIdMarker;
$this->delimiter = $delimiter;
$this->prefix = $prefix;
$this->maxUploads = $maxUploads;
$this->isTruncated = $isTruncated;
$this->uploads = $uploads;
}
/**
* 得到bucket名称
*
* @return string
*/
public function getBucket()
{
return $this->bucket;
}
/**
* @return string
*/
public function getKeyMarker()
{
return $this->keyMarker;
}
/**
*
* @return string
*/
public function getUploadIdMarker()
{
return $this->uploadIdMarker;
}
/**
* @return string
*/
public function getNextKeyMarker()
{
return $this->nextKeyMarker;
}
/**
* @return string
*/
public function getNextUploadIdMarker()
{
return $this->nextUploadIdMarker;
}
/**
* @return string
*/
public function getDelimiter()
{
return $this->delimiter;
}
/**
* @return string
*/
public function getPrefix()
{
return $this->prefix;
}
/**
* @return int
*/
public function getMaxUploads()
{
return $this->maxUploads;
}
/**
* @return string
*/
public function getIsTruncated()
{
return $this->isTruncated;
}
/**
* @return UploadInfo[]
*/
public function getUploads()
{
return $this->uploads;
}
private $bucket = "";
private $keyMarker = "";
private $uploadIdMarker = "";
private $nextKeyMarker = "";
private $nextUploadIdMarker = "";
private $delimiter = "";
private $prefix = "";
private $maxUploads = 0;
private $isTruncated = "false";
private $uploads = array();
}

97
framework/library/alioss/src/OSS/Model/ListPartsInfo.php

@ -0,0 +1,97 @@
<?php
namespace OSS\Model;
/**
* Class ListPartsInfo
* @package OSS\Model
* @link http://help.aliyun.com/document_detail/oss/api-reference/multipart-upload/ListParts.html
*/
class ListPartsInfo
{
/**
* ListPartsInfo constructor.
* @param string $bucket
* @param string $key
* @param string $uploadId
* @param int $nextPartNumberMarker
* @param int $maxParts
* @param string $isTruncated
* @param array $listPart
*/
public function __construct($bucket, $key, $uploadId, $nextPartNumberMarker, $maxParts, $isTruncated, array $listPart)
{
$this->bucket = $bucket;
$this->key = $key;
$this->uploadId = $uploadId;
$this->nextPartNumberMarker = $nextPartNumberMarker;
$this->maxParts = $maxParts;
$this->isTruncated = $isTruncated;
$this->listPart = $listPart;
}
/**
* @return string
*/
public function getBucket()
{
return $this->bucket;
}
/**
* @return string
*/
public function getKey()
{
return $this->key;
}
/**
* @return string
*/
public function getUploadId()
{
return $this->uploadId;
}
/**
* @return int
*/
public function getNextPartNumberMarker()
{
return $this->nextPartNumberMarker;
}
/**
* @return int
*/
public function getMaxParts()
{
return $this->maxParts;
}
/**
* @return string
*/
public function getIsTruncated()
{
return $this->isTruncated;
}
/**
* @return array
*/
public function getListPart()
{
return $this->listPart;
}
private $bucket = "";
private $key = "";
private $uploadId = "";
private $nextPartNumberMarker = 0;
private $maxParts = 0;
private $isTruncated = "";
private $listPart = array();
}

86
framework/library/alioss/src/OSS/Model/LoggingConfig.php

@ -0,0 +1,86 @@
<?php
namespace OSS\Model;
/**
* Class LoggingConfig
* @package OSS\Model
* @link http://help.aliyun.com/document_detail/oss/api-reference/bucket/PutBucketLogging.html
*/
class LoggingConfig implements XmlConfig
{
/**
* LoggingConfig constructor.
* @param null $targetBucket
* @param null $targetPrefix
*/
public function __construct($targetBucket = null, $targetPrefix = null)
{
$this->targetBucket = $targetBucket;
$this->targetPrefix = $targetPrefix;
}
/**
* @param $strXml
* @return null
*/
public function parseFromXml($strXml)
{
$xml = simplexml_load_string($strXml);
if (!isset($xml->LoggingEnabled)) return;
foreach ($xml->LoggingEnabled as $status) {
foreach ($status as $key => $value) {
if ($key === 'TargetBucket') {
$this->targetBucket = strval($value);
} elseif ($key === 'TargetPrefix') {
$this->targetPrefix = strval($value);
}
}
break;
}
}
/**
* 序列化成xml字符串
*
*/
public function serializeToXml()
{
$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><BucketLoggingStatus></BucketLoggingStatus>');
if (isset($this->targetBucket) && isset($this->targetPrefix)) {
$loggingEnabled = $xml->addChild('LoggingEnabled');
$loggingEnabled->addChild('TargetBucket', $this->targetBucket);
$loggingEnabled->addChild('TargetPrefix', $this->targetPrefix);
}
return $xml->asXML();
}
/**
* @return string
*/
public function __toString()
{
return $this->serializeToXml();
}
/**
* @return string
*/
public function getTargetBucket()
{
return $this->targetBucket;
}
/**
* @return string
*/
public function getTargetPrefix()
{
return $this->targetPrefix;
}
private $targetBucket = "";
private $targetPrefix = "";
}

93
framework/library/alioss/src/OSS/Model/ObjectInfo.php

@ -0,0 +1,93 @@
<?php
namespace OSS\Model;
/**
*
* Class ObjectInfo
*
* listObjects接口中返回的Object列表中的类
*
* listObjects接口返回数据中包含两个Array
* 一个是拿到的Object列表【可以理解成对应文件系统中的文件列表】
* 一个是拿到的Prefix列表【可以理解成对应文件系统中的目录列表】
*
* @package OSS\Model
*/
class ObjectInfo
{
/**
* ObjectInfo constructor.
*
* @param string $key
* @param string $lastModified
* @param string $eTag
* @param string $type
* @param int $size
* @param string $storageClass
*/
public function __construct($key, $lastModified, $eTag, $type, $size, $storageClass)
{
$this->key = $key;
$this->lastModified = $lastModified;
$this->eTag = $eTag;
$this->type = $type;
$this->size = $size;
$this->storageClass = $storageClass;
}
/**
* @return string
*/
public function getKey()
{
return $this->key;
}
/**
* @return string
*/
public function getLastModified()
{
return $this->lastModified;
}
/**
* @return string
*/
public function getETag()
{
return $this->eTag;
}
/**
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* @return int
*/
public function getSize()
{
return $this->size;
}
/**
* @return string
*/
public function getStorageClass()
{
return $this->storageClass;
}
private $key = "";
private $lastModified = "";
private $eTag = "";
private $type = "";
private $size = 0;
private $storageClass = "";
}

126
framework/library/alioss/src/OSS/Model/ObjectListInfo.php

@ -0,0 +1,126 @@
<?php
namespace OSS\Model;
/**
* Class ObjectListInfo
*
* ListObjects接口返回数据
*
* @package OSS\Model
* @link http://help.aliyun.com/document_detail/oss/api-reference/bucket/GetBucket.html
*/
class ObjectListInfo
{
/**
* ObjectListInfo constructor.
*
* @param string $bucketName
* @param string $prefix
* @param string $marker
* @param string $nextMarker
* @param string $maxKeys
* @param string $delimiter
* @param null $isTruncated
* @param array $objectList
* @param array $prefixList
*/
public function __construct($bucketName, $prefix, $marker, $nextMarker, $maxKeys, $delimiter, $isTruncated, array $objectList, array $prefixList)
{
$this->bucketName = $bucketName;
$this->prefix = $prefix;
$this->marker = $marker;
$this->nextMarker = $nextMarker;
$this->maxKeys = $maxKeys;
$this->delimiter = $delimiter;
$this->isTruncated = $isTruncated;
$this->objectList = $objectList;
$this->prefixList = $prefixList;
}
/**
* @return string
*/
public function getBucketName()
{
return $this->bucketName;
}
/**
* @return string
*/
public function getPrefix()
{
return $this->prefix;
}
/**
* @return string
*/
public function getMarker()
{
return $this->marker;
}
/**
* @return int
*/
public function getMaxKeys()
{
return $this->maxKeys;
}
/**
* @return string
*/
public function getDelimiter()
{
return $this->delimiter;
}
/**
* @return mixed
*/
public function getIsTruncated()
{
return $this->isTruncated;
}
/**
* 返回ListObjects接口返回数据中的ObjectInfo列表
*
* @return ObjectInfo[]
*/
public function getObjectList()
{
return $this->objectList;
}
/**
* 返回ListObjects接口返回数据中的PrefixInfo列表
*
* @return PrefixInfo[]
*/
public function getPrefixList()
{
return $this->prefixList;
}
/**
* @return string
*/
public function getNextMarker()
{
return $this->nextMarker;
}
private $bucketName = "";
private $prefix = "";
private $marker = "";
private $nextMarker = "";
private $maxKeys = 0;
private $delimiter = "";
private $isTruncated = null;
private $objectList = array();
private $prefixList = array();
}

63
framework/library/alioss/src/OSS/Model/PartInfo.php

@ -0,0 +1,63 @@
<?php
namespace OSS\Model;
/**
* Class PartInfo
* @package OSS\Model
*/
class PartInfo
{
/**
* PartInfo constructor.
*
* @param int $partNumber
* @param string $lastModified
* @param string $eTag
* @param int $size
*/
public function __construct($partNumber, $lastModified, $eTag, $size)
{
$this->partNumber = $partNumber;
$this->lastModified = $lastModified;
$this->eTag = $eTag;
$this->size = $size;
}
/**
* @return int
*/
public function getPartNumber()
{
return $this->partNumber;
}
/**
* @return string
*/
public function getLastModified()
{
return $this->lastModified;
}
/**
* @return string
*/
public function getETag()
{
return $this->eTag;
}
/**
* @return int
*/
public function getSize()
{
return $this->size;
}
private $partNumber = 0;
private $lastModified = "";
private $eTag = "";
private $size = 0;
}

36
framework/library/alioss/src/OSS/Model/PrefixInfo.php

@ -0,0 +1,36 @@
<?php
namespace OSS\Model;
/**
* Class PrefixInfo
*
* listObjects接口中返回的Prefix列表中的类
* listObjects接口返回数据中包含两个Array:
* 一个是拿到的Object列表【可以理解成对应文件系统中的文件列表】
* 一个是拿到的Prefix列表【可以理解成对应文件系统中的目录列表】
*
* @package OSS\Model
* @link http://help.aliyun.com/document_detail/oss/api-reference/bucket/GetBucket.html
*/
class PrefixInfo
{
/**
* PrefixInfo constructor.
* @param string $prefix
*/
public function __construct($prefix)
{
$this->prefix = $prefix;
}
/**
* @return string
*/
public function getPrefix()
{
return $this->prefix;
}
private $prefix;
}

93
framework/library/alioss/src/OSS/Model/RefererConfig.php

@ -0,0 +1,93 @@
<?php
namespace OSS\Model;
/**
* Class RefererConfig
*
* @package OSS\Model
* @link http://help.aliyun.com/document_detail/oss/api-reference/bucket/PutBucketReferer.html
*/
class RefererConfig implements XmlConfig
{
/**
* @param string $strXml
* @return null
*/
public function parseFromXml($strXml)
{
$xml = simplexml_load_string($strXml);
if (!isset($xml->AllowEmptyReferer)) return;
if (!isset($xml->RefererList)) return;
$this->allowEmptyReferer =
(strval($xml->AllowEmptyReferer) === 'TRUE' || strval($xml->AllowEmptyReferer) === 'true') ? true : false;
foreach ($xml->RefererList->Referer as $key => $refer) {
$this->refererList[] = strval($refer);
}
}
/**
* 把RefererConfig序列化成xml
*
* @return string
*/
public function serializeToXml()
{
$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><RefererConfiguration></RefererConfiguration>');
if ($this->allowEmptyReferer) {
$xml->addChild('AllowEmptyReferer', 'true');
} else {
$xml->addChild('AllowEmptyReferer', 'false');
}
$refererList = $xml->addChild('RefererList');
foreach ($this->refererList as $referer) {
$refererList->addChild('Referer', $referer);
}
return $xml->asXML();
}
/**
* @return string
*/
function __toString()
{
return $this->serializeToXml();
}
/**
* @param boolean $allowEmptyReferer
*/
public function setAllowEmptyReferer($allowEmptyReferer)
{
$this->allowEmptyReferer = $allowEmptyReferer;
}
/**
* @param string $referer
*/
public function addReferer($referer)
{
$this->refererList[] = $referer;
}
/**
* @return boolean
*/
public function isAllowEmptyReferer()
{
return $this->allowEmptyReferer;
}
/**
* @return array
*/
public function getRefererList()
{
return $this->refererList;
}
private $allowEmptyReferer = true;
private $refererList = array();
}

55
framework/library/alioss/src/OSS/Model/UploadInfo.php

@ -0,0 +1,55 @@
<?php
namespace OSS\Model;
/**
* Class UploadInfo
*
* ListMultipartUpload接口得到的UploadInfo
*
* @package OSS\Model
*/
class UploadInfo
{
/**
* UploadInfo constructor.
*
* @param string $key
* @param string $uploadId
* @param string $initiated
*/
public function __construct($key, $uploadId, $initiated)
{
$this->key = $key;
$this->uploadId = $uploadId;
$this->initiated = $initiated;
}
/**
* @return string
*/
public function getKey()
{
return $this->key;
}
/**
* @return string
*/
public function getUploadId()
{
return $this->uploadId;
}
/**
* @return string
*/
public function getInitiated()
{
return $this->initiated;
}
private $key = "";
private $uploadId = "";
private $initiated = "";
}

76
framework/library/alioss/src/OSS/Model/WebsiteConfig.php

@ -0,0 +1,76 @@
<?php
namespace OSS\Model;
use OSS\Core\OssException;
/**
* Class WebsiteConfig
* @package OSS\Model
* @link http://help.aliyun.com/document_detail/oss/api-reference/bucket/PutBucketWebsite.html
*/
class WebsiteConfig implements XmlConfig
{
/**
* WebsiteConfig constructor.
* @param string $indexDocument
* @param string $errorDocument
*/
public function __construct($indexDocument = "", $errorDocument = "")
{
$this->indexDocument = $indexDocument;
$this->errorDocument = $errorDocument;
}
/**
* @param string $strXml
* @return null
*/
public function parseFromXml($strXml)
{
$xml = simplexml_load_string($strXml);
if (isset($xml->IndexDocument) && isset($xml->IndexDocument->Suffix)) {
$this->indexDocument = strval($xml->IndexDocument->Suffix);
}
if (isset($xml->ErrorDocument) && isset($xml->ErrorDocument->Key)) {
$this->errorDocument = strval($xml->ErrorDocument->Key);
}
}
/**
* 把WebsiteConfig序列化成xml
*
* @return string
* @throws OssException
*/
public function serializeToXml()
{
$xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><WebsiteConfiguration></WebsiteConfiguration>');
$index_document_part = $xml->addChild('IndexDocument');
$error_document_part = $xml->addChild('ErrorDocument');
$index_document_part->addChild('Suffix', $this->indexDocument);
$error_document_part->addChild('Key', $this->errorDocument);
return $xml->asXML();
}
/**
* @return string
*/
public function getIndexDocument()
{
return $this->indexDocument;
}
/**
* @return string
*/
public function getErrorDocument()
{
return $this->errorDocument;
}
private $indexDocument = "";
private $errorDocument = "";
}

27
framework/library/alioss/src/OSS/Model/XmlConfig.php

@ -0,0 +1,27 @@
<?php
namespace OSS\Model;
/**
* Interface XmlConfig
* @package OSS\Model
*/
interface XmlConfig
{
/**
* 接口定义,实现此接口的类都需要实现从xml数据解析的函数
*
* @param string $strXml
* @return null
*/
public function parseFromXml($strXml);
/**
* 接口定义,实现此接口的类,都需要实现把子类序列化成xml字符串的接口
*
* @return string
*/
public function serializeToXml();
}

2230
framework/library/alioss/src/OSS/OssClient.php

File diff suppressed because it is too large

33
framework/library/alioss/src/OSS/Result/AclResult.php

@ -0,0 +1,33 @@
<?php
namespace OSS\Result;
use OSS\Core\OssException;
use OSS\Tests\OssExceptionTest;
/**
* Class AclResult getBucketAcl接口返回结果类,封装了
* 返回的xml数据的解析
*
* @package OSS\Result
*/
class AclResult extends Result
{
/**
* @return string
* @throws OssException
*/
protected function parseDataFromResponse()
{
$content = $this->rawResponse->body;
if (empty($content)) {
throw new OssException("body is null");
}
$xml = simplexml_load_string($content);
if (isset($xml->AccessControlList->Grant)) {
return strval($xml->AccessControlList->Grant);
} else {
throw new OssException("xml format exception");
}
}
}

27
framework/library/alioss/src/OSS/Result/AppendResult.php

@ -0,0 +1,27 @@
<?php
namespace OSS\Result;
use OSS\Core\OssException;
/**
* Class AppendResult
* @package OSS\Result
*/
class AppendResult extends Result
{
/**
* 结果中part的next-append-position
*
* @return int
* @throws OssException
*/
protected function parseDataFromResponse()
{
$header = $this->rawResponse->header;
if (isset($header["x-oss-next-append-position"])) {
return intval($header["x-oss-next-append-position"]);
}
throw new OssException("cannot get next-append-position");
}
}

19
framework/library/alioss/src/OSS/Result/BodyResult.php

@ -0,0 +1,19 @@
<?php
namespace OSS\Result;
/**
* Class BodyResult
* @package OSS\Result
*/
class BodyResult extends Result
{
/**
* @return string
*/
protected function parseDataFromResponse()
{
return empty($this->rawResponse->body) ? "" : $this->rawResponse->body;
}
}

35
framework/library/alioss/src/OSS/Result/ExistResult.php

@ -0,0 +1,35 @@
<?php
namespace OSS\Result;
/**
* Class ExistResult 检查bucket和object是否存在的返回结果,
* 根据返回response的http status判断
* @package OSS\Result
*/
class ExistResult extends Result
{
/**
* @return bool
*/
protected function parseDataFromResponse()
{
return intval($this->rawResponse->status) === 200 ? true : false;
}
/**
* 根据返回http状态码判断,[200-299]即认为是OK, 判断是否存在的接口,404也认为是一种
* 有效响应
*
* @return bool
*/
protected function isResponseOk()
{
$status = $this->rawResponse->status;
if ((int)(intval($status) / 100) == 2 || (int)(intval($status)) === 404) {
return true;
}
return false;
}
}

34
framework/library/alioss/src/OSS/Result/GetCnameResult.php

@ -0,0 +1,34 @@
<?php
namespace OSS\Result;
use OSS\Model\CnameConfig;
class GetCnameResult extends Result
{
/**
* @return CnameConfig
*/
protected function parseDataFromResponse()
{
$content = $this->rawResponse->body;
$config = new CnameConfig();
$config->parseFromXml($content);
return $config;
}
/**
* 根据返回http状态码判断,[200-299]即认为是OK, 获取bucket相关配置的接口,404也认为是一种
* 有效响应
*
* @return bool
*/
protected function isResponseOk()
{
$status = $this->rawResponse->status;
if ((int)(intval($status) / 100) == 2 || (int)(intval($status)) === 404) {
return true;
}
return false;
}
}

35
framework/library/alioss/src/OSS/Result/GetCorsResult.php

@ -0,0 +1,35 @@
<?php
namespace OSS\Result;
use OSS\Model\CorsConfig;
class GetCorsResult extends Result
{
/**
* @return CorsConfig
*/
protected function parseDataFromResponse()
{
$content = $this->rawResponse->body;
$config = new CorsConfig();
$config->parseFromXml($content);
return $config;
}
/**
* 根据返回http状态码判断,[200-299]即认为是OK, 获取bucket相关配置的接口,404也认为是一种
* 有效响应
*
* @return bool
*/
protected function isResponseOk()
{
$status = $this->rawResponse->status;
if ((int)(intval($status) / 100) == 2 || (int)(intval($status)) === 404) {
return true;
}
return false;
}
}

41
framework/library/alioss/src/OSS/Result/GetLifecycleResult.php

@ -0,0 +1,41 @@
<?php
namespace OSS\Result;
use OSS\Model\LifecycleConfig;
/**
* Class GetLifecycleResult
* @package OSS\Result
*/
class GetLifecycleResult extends Result
{
/**
* 解析Lifestyle数据
*
* @return LifecycleConfig
*/
protected function parseDataFromResponse()
{
$content = $this->rawResponse->body;
$config = new LifecycleConfig();
$config->parseFromXml($content);
return $config;
}
/**
* 根据返回http状态码判断,[200-299]即认为是OK, 获取bucket相关配置的接口,404也认为是一种
* 有效响应
*
* @return bool
*/
protected function isResponseOk()
{
$status = $this->rawResponse->status;
if ((int)(intval($status) / 100) == 2 || (int)(intval($status)) === 404) {
return true;
}
return false;
}
}

41
framework/library/alioss/src/OSS/Result/GetLoggingResult.php

@ -0,0 +1,41 @@
<?php
namespace OSS\Result;
use OSS\Model\LoggingConfig;
/**
* Class GetLoggingResult
* @package OSS\Result
*/
class GetLoggingResult extends Result
{
/**
* 解析LoggingConfig数据
*
* @return LoggingConfig
*/
protected function parseDataFromResponse()
{
$content = $this->rawResponse->body;
$config = new LoggingConfig();
$config->parseFromXml($content);
return $config;
}
/**
* 根据返回http状态码判断,[200-299]即认为是OK, 获取bucket相关配置的接口,404也认为是一种
* 有效响应
*
* @return bool
*/
protected function isResponseOk()
{
$status = $this->rawResponse->status;
if ((int)(intval($status) / 100) == 2 || (int)(intval($status)) === 404) {
return true;
}
return false;
}
}

41
framework/library/alioss/src/OSS/Result/GetRefererResult.php

@ -0,0 +1,41 @@
<?php
namespace OSS\Result;
use OSS\Model\RefererConfig;
/**
* Class GetRefererResult
* @package OSS\Result
*/
class GetRefererResult extends Result
{
/**
* 解析RefererConfig数据
*
* @return RefererConfig
*/
protected function parseDataFromResponse()
{
$content = $this->rawResponse->body;
$config = new RefererConfig();
$config->parseFromXml($content);
return $config;
}
/**
* 根据返回http状态码判断,[200-299]即认为是OK, 获取bucket相关配置的接口,404也认为是一种
* 有效响应
*
* @return bool
*/
protected function isResponseOk()
{
$status = $this->rawResponse->status;
if ((int)(intval($status) / 100) == 2 || (int)(intval($status)) === 404) {
return true;
}
return false;
}
}

40
framework/library/alioss/src/OSS/Result/GetWebsiteResult.php

@ -0,0 +1,40 @@
<?php
namespace OSS\Result;
use OSS\Model\WebsiteConfig;
/**
* Class GetWebsiteResult
* @package OSS\Result
*/
class GetWebsiteResult extends Result
{
/**
* 解析WebsiteConfig数据
*
* @return WebsiteConfig
*/
protected function parseDataFromResponse()
{
$content = $this->rawResponse->body;
$config = new WebsiteConfig();
$config->parseFromXml($content);
return $config;
}
/**
* 根据返回http状态码判断,[200-299]即认为是OK, 获取bucket相关配置的接口,404也认为是一种
* 有效响应
*
* @return bool
*/
protected function isResponseOk()
{
$status = $this->rawResponse->status;
if ((int)(intval($status) / 100) == 2 || (int)(intval($status)) === 404) {
return true;
}
return false;
}
}

23
framework/library/alioss/src/OSS/Result/HeaderResult.php

@ -0,0 +1,23 @@
<?php
namespace OSS\Result;
/**
* Class HeaderResult
* @package OSS\Result
* @link https://docs.aliyun.com/?spm=5176.383663.13.7.HgUIqL#/pub/oss/api-reference/object&GetObjectMeta
*/
class HeaderResult extends Result
{
/**
* 把返回的ResponseCore中的header作为返回数据
*
* @return array
*/
protected function parseDataFromResponse()
{
return empty($this->rawResponse->header) ? array() : $this->rawResponse->header;
}
}

29
framework/library/alioss/src/OSS/Result/InitiateMultipartUploadResult.php

@ -0,0 +1,29 @@
<?php
namespace OSS\Result;
use OSS\Core\OssException;
/**
* Class initiateMultipartUploadResult
* @package OSS\Result
*/
class InitiateMultipartUploadResult extends Result
{
/**
* 结果中获取uploadId并返回
*
* @throws OssException
* @return string
*/
protected function parseDataFromResponse()
{
$content = $this->rawResponse->body;
$xml = simplexml_load_string($content);
if (isset($xml->UploadId)) {
return strval($xml->UploadId);
}
throw new OssException("cannot get UploadId");
}
}

33
framework/library/alioss/src/OSS/Result/ListBucketsResult.php

@ -0,0 +1,33 @@
<?php
namespace OSS\Result;
use OSS\Model\BucketInfo;
use OSS\Model\BucketListInfo;
/**
* Class ListBucketsResult
*
* @package OSS\Result
*/
class ListBucketsResult extends Result
{
/**
* @return BucketListInfo
*/
protected function parseDataFromResponse()
{
$bucketList = array();
$content = $this->rawResponse->body;
$xml = new \SimpleXMLElement($content);
if (isset($xml->Buckets) && isset($xml->Buckets->Bucket)) {
foreach ($xml->Buckets->Bucket as $bucket) {
$bucketInfo = new BucketInfo(strval($bucket->Location),
strval($bucket->Name),
strval($bucket->CreationDate));
$bucketList[] = $bucketInfo;
}
}
return new BucketListInfo($bucketList);
}
}

55
framework/library/alioss/src/OSS/Result/ListMultipartUploadResult.php

@ -0,0 +1,55 @@
<?php
namespace OSS\Result;
use OSS\Core\OssUtil;
use OSS\Model\ListMultipartUploadInfo;
use OSS\Model\UploadInfo;
/**
* Class ListMultipartUploadResult
* @package OSS\Result
*/
class ListMultipartUploadResult extends Result
{
/**
* 解析从ListMultipartUpload接口的返回数据
*
* @return ListMultipartUploadInfo
*/
protected function parseDataFromResponse()
{
$content = $this->rawResponse->body;
$xml = simplexml_load_string($content);
$encodingType = isset($xml->EncodingType) ? strval($xml->EncodingType) : "";
$bucket = isset($xml->Bucket) ? strval($xml->Bucket) : "";
$keyMarker = isset($xml->KeyMarker) ? strval($xml->KeyMarker) : "";
$keyMarker = OssUtil::decodeKey($keyMarker, $encodingType);
$uploadIdMarker = isset($xml->UploadIdMarker) ? strval($xml->UploadIdMarker) : "";
$nextKeyMarker = isset($xml->NextKeyMarker) ? strval($xml->NextKeyMarker) : "";
$nextKeyMarker = OssUtil::decodeKey($nextKeyMarker, $encodingType);
$nextUploadIdMarker = isset($xml->NextUploadIdMarker) ? strval($xml->NextUploadIdMarker) : "";
$delimiter = isset($xml->Delimiter) ? strval($xml->Delimiter) : "";
$delimiter = OssUtil::decodeKey($delimiter, $encodingType);
$prefix = isset($xml->Prefix) ? strval($xml->Prefix) : "";
$prefix = OssUtil::decodeKey($prefix, $encodingType);
$maxUploads = isset($xml->MaxUploads) ? intval($xml->MaxUploads) : 0;
$isTruncated = isset($xml->IsTruncated) ? strval($xml->IsTruncated) : "";
$listUpload = array();
if (isset($xml->Upload)) {
foreach ($xml->Upload as $upload) {
$key = isset($upload->Key) ? strval($upload->Key) : "";
$key = OssUtil::decodeKey($key, $encodingType);
$uploadId = isset($upload->UploadId) ? strval($upload->UploadId) : "";
$initiated = isset($upload->Initiated) ? strval($upload->Initiated) : "";
$listUpload[] = new UploadInfo($key, $uploadId, $initiated);
}
}
return new ListMultipartUploadInfo($bucket, $keyMarker, $uploadIdMarker,
$nextKeyMarker, $nextUploadIdMarker,
$delimiter, $prefix, $maxUploads, $isTruncated, $listUpload);
}
}

71
framework/library/alioss/src/OSS/Result/ListObjectsResult.php

@ -0,0 +1,71 @@
<?php
namespace OSS\Result;
use OSS\Core\OssUtil;
use OSS\Model\ObjectInfo;
use OSS\Model\ObjectListInfo;
use OSS\Model\PrefixInfo;
/**
* Class ListObjectsResult
* @package OSS\Result
*/
class ListObjectsResult extends Result
{
/**
* 解析ListObjects接口返回的xml数据
*
* return ObjectListInfo
*/
protected function parseDataFromResponse()
{
$xml = new \SimpleXMLElement($this->rawResponse->body);
$encodingType = isset($xml->EncodingType) ? strval($xml->EncodingType) : "";
$objectList = $this->parseObjectList($xml, $encodingType);
$prefixList = $this->parsePrefixList($xml, $encodingType);
$bucketName = isset($xml->Name) ? strval($xml->Name) : "";
$prefix = isset($xml->Prefix) ? strval($xml->Prefix) : "";
$prefix = OssUtil::decodeKey($prefix, $encodingType);
$marker = isset($xml->Marker) ? strval($xml->Marker) : "";
$marker = OssUtil::decodeKey($marker, $encodingType);
$maxKeys = isset($xml->MaxKeys) ? intval($xml->MaxKeys) : 0;
$delimiter = isset($xml->Delimiter) ? strval($xml->Delimiter) : "";
$delimiter = OssUtil::decodeKey($delimiter, $encodingType);
$isTruncated = isset($xml->IsTruncated) ? strval($xml->IsTruncated) : "";
$nextMarker = isset($xml->NextMarker) ? strval($xml->NextMarker) : "";
$nextMarker = OssUtil::decodeKey($nextMarker, $encodingType);
return new ObjectListInfo($bucketName, $prefix, $marker, $nextMarker, $maxKeys, $delimiter, $isTruncated, $objectList, $prefixList);
}
private function parseObjectList($xml, $encodingType)
{
$retList = array();
if (isset($xml->Contents)) {
foreach ($xml->Contents as $content) {
$key = isset($content->Key) ? strval($content->Key) : "";
$key = OssUtil::decodeKey($key, $encodingType);
$lastModified = isset($content->LastModified) ? strval($content->LastModified) : "";
$eTag = isset($content->ETag) ? strval($content->ETag) : "";
$type = isset($content->Type) ? strval($content->Type) : "";
$size = isset($content->Size) ? intval($content->Size) : 0;
$storageClass = isset($content->StorageClass) ? strval($content->StorageClass) : "";
$retList[] = new ObjectInfo($key, $lastModified, $eTag, $type, $size, $storageClass);
}
}
return $retList;
}
private function parsePrefixList($xml, $encodingType)
{
$retList = array();
if (isset($xml->CommonPrefixes)) {
foreach ($xml->CommonPrefixes as $commonPrefix) {
$prefix = isset($commonPrefix->Prefix) ? strval($commonPrefix->Prefix) : "";
$prefix = OssUtil::decodeKey($prefix, $encodingType);
$retList[] = new PrefixInfo($prefix);
}
}
return $retList;
}
}

42
framework/library/alioss/src/OSS/Result/ListPartsResult.php

@ -0,0 +1,42 @@
<?php
namespace OSS\Result;
use OSS\Model\ListPartsInfo;
use OSS\Model\PartInfo;
/**
* Class ListPartsResult
* @package OSS\Result
*/
class ListPartsResult extends Result
{
/**
* 解析ListParts接口返回的xml数据
*
* @return ListPartsInfo
*/
protected function parseDataFromResponse()
{
$content = $this->rawResponse->body;
$xml = simplexml_load_string($content);
$bucket = isset($xml->Bucket) ? strval($xml->Bucket) : "";
$key = isset($xml->Key) ? strval($xml->Key) : "";
$uploadId = isset($xml->UploadId) ? strval($xml->UploadId) : "";
$nextPartNumberMarker = isset($xml->NextPartNumberMarker) ? intval($xml->NextPartNumberMarker) : "";
$maxParts = isset($xml->MaxParts) ? intval($xml->MaxParts) : "";
$isTruncated = isset($xml->IsTruncated) ? strval($xml->IsTruncated) : "";
$partList = array();
if (isset($xml->Part)) {
foreach ($xml->Part as $part) {
$partNumber = isset($part->PartNumber) ? intval($part->PartNumber) : "";
$lastModified = isset($part->LastModified) ? strval($part->LastModified) : "";
$eTag = isset($part->ETag) ? strval($part->ETag) : "";
$size = isset($part->Size) ? intval($part->Size) : "";
$partList[] = new PartInfo($partNumber, $lastModified, $eTag, $size);
}
}
return new ListPartsInfo($bucket, $key, $uploadId, $nextPartNumberMarker, $maxParts, $isTruncated, $partList);
}
}

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save