Compare commits

..

No commits in common. 'dev' and 'Anankke_dev' have entirely different histories.

@ -0,0 +1,22 @@
# https://editorconfig.org/
root = true
[*]
tab_width = 4
[*.php]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
charset = utf-8
end_of_line = lf
indent_style = space
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 80

2
.gitattributes vendored

@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto

@ -1,34 +0,0 @@
---
name: Bug report
about: Create a bug report
title: "[BUG]"
labels: bug
---
请将 [ ] 替换为 [x] 。Please relpace [ ] with [x] .
- [ ] 我已知晓并同意,如果我不遵循以下格式提交 issue,或者我使用的并非最新版本的 SSPanel UIM,或者我没有提供足够的信息,或者我没有选中这些框,则我的 issue 将会被无条件关闭和锁定。 I acknowledge if I don't follow the format below, or I'm on an old commit, or I fail to provide sufficient information, or I don't check these box, my issue could be closed without any notice.
- [ ] 我已确认我已经阅读过使用文档、Wiki,并在 issue 列表中查找相似的问题。I certify that I have read project Wiki and other issue may related to this one.
- [ ] 我已知晓并同意,如果我不同意上述条件却仍然提交 issue,或即使同意上述条件但在提交 issue 时不按照条件执行,我的 issue 可被 SSPanel UIM 维护团队视为 spam、并在必要时会被举报到 GitHub。 I acknowledge if I disagree with the conditions above but still submit a issue, or if I agree conditions above but do not follow them when submitting a issue, my issue could be considered as spam by the SSPanel UIM maintenance team, and might be reported to GitHub if necessary.
**Environment 环境**
Your OS info, PHP/MySQL version and so on... 你的操作系统信息、PHP/MySQL 版本、以及其它所有可能相关的信息。
**Commit**
The commit you on. 你当前的 SSPanel UIM 位于哪条 commit。
**Bug**
The bug information. 请描述你遇到的 Bug。
**Reproduce**
Steps to reproduce the bug. 请逐步描述如何复现 Bug。
**Expected behavior**
What you expected to happen. 请描述你预期的行为。
**Logs**
If applicable, add your PHP logs here. 如果需要,请在这里粘贴 PHP Log。
**Addition**
Additional context here. 如有可能,请提供更多相关资料。

@ -1,19 +0,0 @@
---
name: Feature request
about: Suggest an new idea for this project
title: "[Feature Request]"
labels: enhancement
---
- [ ] I acknowledge if I don't follow the format below or I don't check these box, my issue could be closed without any notice.
- [ ] I certify that I have read project Wiki and other issue may related to this one.
**Feature**
The feature you want.
**Solution**
If you have some solution about this issue, type it here.
**Addition**
Additional context here.

@ -0,0 +1,49 @@
---
name: issue
about: temlpate
---
<!--
如果你不仔细填写下面的内容,我们可能会直接关闭你的 issue。
如果你没有仔细阅读 Wiki ,或者无关问题,我们可能会直接关闭你的 issue。
注意:Wiki 可能随时都会更新。在提交一个 issue 前,请重新查看相关内容。
如果你还有什么别的小问题请加入群组 https://t.me/SSUnion
不要用你的 issue 污染几百个 watchers 的邮箱
-->
**我确认我已经阅读了** (使用 "x" 选择)
- [ ] [项目 Wiki ](https://github.com/Anankke/SSPanel-Uim/wiki)
- [ ] [项目其他 issue](https://github.com/Anankke/SSPanel-Uim/issues?utf8=%E2%9C%93&q=is%3Aissue)
**我确认我做到了** (使用 "x" 选择)
- [ ] [将项目升级到当前分支最新版本](https://github.com/Anankke/SSPanel-Uim/wiki/%E5%8D%87%E7%B4%9A%E7%89%88%E6%9C%AC)
- [ ] 在[项目演示站](https://demo.nimaqu.com)成功复现问题
**我正在申请** (使用 "x" 选择)
- [ ] 反馈一个 bug
- [ ] 申请添加新的特性或功能或者好的想法
<!--
**反馈BUG**
1. 反馈之前先升级到分支的最新版本。
2.如果是页面问题(500 或 Slim Application Error ),请在 config 开启 debug 模式后截图或贴出输出内容,如果是某个按钮点击没反应,请打开浏览器开发者控制台(通常为 F12 ) ,贴出 console 输出内容。
-->
<!--从这一行往下写--我是分割线-->

1
.gitignore vendored

@ -6,7 +6,6 @@
composer.lock
.php_cs.cache
.env
.editorconfig
vendor
php_errors.log

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ss-panel-v3-mod_UIChanges</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.aptana.ide.core.unifiedBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.aptana.projects.webnature</nature>
</natures>
<filteredResources>
<filter>
<id>1522297588605</id>
<name></name>
<type>26</type>
<matcher>
<id>org.eclipse.ui.ide.multiFilter</id>
<arguments>1.0-name-matches-false-false-node_modules</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>

@ -1,19 +0,0 @@
根据时间从 2018 年 12 月始...
- 支持 Quantumult 格式的 V2Ray 订阅以及策略组配置导出
- 支持 Surge 2 & 3 的托管配置以及 policy group
- 支持 SurfBoard 的托管配置
- 支持 Shadowrocket 支持的 Shadowsocks(R) & VMess 合并订阅
- 提供用户使用文档
- 完全合并普通端口和单端口的订阅及托管
- ShadowsocksR 订阅中的账户及流量信息改为可选
- ~~一键切换 SS/SSR 加密、协议、混淆~~ (已废弃)
- 订阅链接兼容 Anankke
- ~~支持 ss-v2ray-plugin 类型节点~~ (已合并到 Anankke)
- V2Ray 订阅可选支持显示账户及流量信息
- 可选使用预定义的加密、协议、混淆配置方案
- 支持用户自定义 Surge 托管配置
- 支持用户自定义 Clash 托管配置
……

@ -18,10 +18,6 @@
SSPanel UIM 是一款专为 Shadowsocks / ShadowsocksR / V2Ray 设计的多用户管理面板,基于 ss-panel-v3-mod 开发。
## AD
**特别优惠 Malio SSPANEL 主题 + Rico V2Ray 后端,原价 1000 CNY,现在只需 899 CNY,👉[查看详情](https://malio.fxxkmy.life/)**
## 特性
- 集成超过 8 种支付系统
@ -167,7 +163,6 @@ SSPanel UIM 离不开所有 [贡献代码](https://github.com/Anankke/SSPanel-Ui
#### galaxychuck
- [hkserversolution-推荐UIM面板服务器放置](https://www.hkserversolution.com/aff.php?aff=60)
- [moecloud-美國VPS](https://moecloud.asia/aff.php?aff=56)
#### laurieryayoi

@ -52,21 +52,11 @@ class DailyMail
$sts = new Analytics();
if (Config::getdb('Telegram.enable.Diary') !== '0') {
Telegram::Send(
str_replace(
array(
'%getTodayCheckinUser%',
'%lastday_total%'
),
array(
$sts->getTodayCheckinUser(),
Tools::flowAutoShow($lastday_total)
),
Config::getdb('Telegram.msg.Diary')
)
);
}
Telegram::Send('各位老爷少奶奶,我来为大家报告一下系统今天的运行状况哈~' .
PHP_EOL .
'今日签到人数:' . $sts->getTodayCheckinUser() . PHP_EOL .
'今日使用总流量:' . Tools::flowAutoShow($lastday_total) . PHP_EOL .
'晚安~');
}

@ -83,7 +83,7 @@ class FinanceMail
}
}
if (Config::get('finance_public') == true) {
if (Config::get('finance_public') == 'true') {
$sts = new Analytics();
Telegram::Send(
'新鲜出炉的财务日报~' . PHP_EOL .
@ -150,7 +150,7 @@ class FinanceMail
}
}
if (Config::get('finance_public') == true) {
if (Config::get('finance_public') == 'true') {
$sts = new Analytics();
Telegram::Send(
'新鲜出炉的财务周报~' . PHP_EOL .
@ -197,7 +197,7 @@ class FinanceMail
}
}
if (Config::get('finance_public') == true) {
if (Config::get('finance_public') == 'true') {
$sts = new Analytics();
Telegram::Send(
'新鲜出炉的财务月报~' . PHP_EOL .

@ -17,11 +17,7 @@ use App\Models\DetectLog;
use App\Models\BlockIp;
use App\Models\TelegramSession;
use App\Models\EmailVerify;
use App\Models\UserSubscribeLog;
use App\Models\DetectBanLog;
use App\Services\Config;
use App\Services\Password;
use App\Utils\DNSoverHTTPS;
use App\Utils\Radius;
use App\Utils\Tools;
use App\Services\Mail;
@ -29,6 +25,7 @@ use App\Utils\QQWry;
use App\Utils\GA;
use App\Utils\Telegram;
use ArrayObject;
use CloudXNS\Api;
use App\Models\Disconnect;
use App\Models\UnblockIp;
use Exception;
@ -74,7 +71,7 @@ class Job
'mysqldump --opt --user=' . Config::get('db_username') . ' --password=' . Config::get('db_password') . ' --host=' . $db_address_array[0] . ' ' . (isset($db_address_array[1]) ? '-P ' . $db_address_array[1] : '') . ' -d ' . Config::get('db_database') . ' alive_ip ss_node_info ss_node_online_log user_traffic_log detect_log telegram_session >> /tmp/ssmodbackup/mod.sql',
$ret
);
if (Config::get('enable_radius') == true) {
if (Config::get('enable_radius') == 'true') {
$db_address_array = explode(':', Config::get('radius_db_host'));
system(
'mysqldump --user=' . Config::get('radius_db_user') . ' --password=' . Config::get('radius_db_password') . ' --host=' . $db_address_array[0] . ' ' . (isset($db_address_array[1]) ? '-P ' . $db_address_array[1] : '') . '' . Config::get('radius_db_database') . '> /tmp/ssmodbackup/radius.sql',
@ -100,7 +97,7 @@ class Job
system('rm -rf /tmp/ssmodbackup', $ret);
system('rm /tmp/ssmodbackup.zip', $ret);
if (Config::get('backup_notify') == true) {
if (Config::get('backup_notify') == 'true') {
Telegram::Send('备份完毕了喵~今天又是安全祥和的一天呢。');
}
}
@ -125,9 +122,6 @@ class Job
$rule = preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/", $node->server);
if (!$rule && (!$node->sort || $node->sort == 10 || $node->sort == 12 || $node->sort == 13)) {
$ip = gethostbyname($node->server);
if ($ip == "127.0.0.1"){
$ip = DNSoverHTTPS::gethostbyName($node->server);
}
$node->node_ip = $ip;
$node->save();
@ -149,9 +143,6 @@ class Job
}
}
// 清理订阅记录
UserSubscribeLog::where('request_time', '<', date('Y-m-d H:i:s', time() - 86400 * (int) Config::get('subscribeLog_keep_days')))->delete();
NodeInfoLog::where('log_time', '<', time() - 86400 * 3)->delete();
NodeOnlineLog::where('log_time', '<', time() - 86400 * 3)->delete();
TrafficLog::where('log_time', '<', time() - 86400 * 3)->delete();
@ -159,10 +150,7 @@ class Job
Speedtest::where('datetime', '<', time() - 86400 * 3)->delete();
EmailVerify::where('expire_in', '<', time() - 86400 * 3)->delete();
system('rm ' . BASE_PATH . '/storage/*.png', $ret);
if (Config::getdb('Telegram.enable.DailyJob') !== '0') {
Telegram::Send(Config::getdb('Telegram.msg.DailyJob'));
}
Telegram::Send('姐姐姐姐,数据库被清理了,感觉身体被掏空了呢~');
//auto reset
$boughts = Bought::all();
@ -445,12 +433,12 @@ class Job
$adminUser = User::where('is_admin', '=', '1')->get();
//节点掉线检测
if (Config::get('enable_detect_offline') == true) {
if (Config::get('enable_detect_offline') == 'true') {
$nodes = Node::all();
foreach ($nodes as $node) {
if ($node->isNodeOnline() === false && !file_exists(BASE_PATH . '/storage/' . $node->id . '.offline')) {
if (Config::get('useScFtqq') == true && Config::get('enable_detect_offline_useScFtqq') == true) {
if (Config::get('useScFtqq') == 'true' && Config::get('enable_detect_offline_useScFtqq') == 'true') {
$ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY');
$text = '管理员您好,系统发现节点 ' . $node->name . ' 掉线了,请您及时处理。';
$postdata = http_build_query(
@ -480,21 +468,64 @@ class Job
Mail::send($to, $subject, 'news/warn.tpl', [
'user' => $user,
'text' => $text
], [
]);
} catch (Exception $e) {
echo $e->getMessage();
}
$notice_text = str_replace(
'%node_name%',
$node->name,
Config::getdb('Telegram.msg.NodeOffline')
);
}
if (Config::getdb('Telegram.enable.NodeOffline') !== '0') {
Telegram::Send($notice_text);
if (Config::get('enable_cloudxns') == 'true' && ($node->sort == 0 || $node->sort == 10 || $node->sort == 12 || $node->sort == 13)) {
$api = new Api();
$api->setApiKey(Config::get('cloudxns_apikey'));//修改成自己API KEY
$api->setSecretKey(Config::get('cloudxns_apisecret'));//修改成自己的SECERET KEY
$api->setProtocol(true);
$domain_json = json_decode($api->domain->domainList());
foreach ($domain_json->data as $domain) {
if (strpos($domain->domain, Config::get('cloudxns_domain')) !== false) {
$domain_id = $domain->id;
}
}
$record_json = json_decode($api->record->recordList($domain_id, 0, 0, 2000));
foreach ($record_json->data as $record) {
if (($record->host . '.' . Config::get('cloudxns_domain')) == $node->server) {
$record_id = $record->record_id;
$Temp_node = Node::where('node_class', '<=', $node->node_class)->where(
static function ($query) use ($node) {
$query->where('node_group', '=', $node->node_group)
->orWhere('node_group', '=', 0);
}
)->whereRaw('UNIX_TIMESTAMP()-`node_heartbeat`<300')->first();
if ($Temp_node != null) {
$api->record->recordUpdate(
$domain_id,
$record->host,
$Temp_node->server,
'CNAME',
55,
60,
1,
'',
$record_id
);
}
$notice_text = '喵喵喵~ ' . $node->name . ' 节点掉线了喵~域名解析被切换到了 ' . $Temp_node->name . ' 上了喵~';
}
}
} else {
$notice_text = '喵喵喵~ ' . $node->name . ' 节点掉线了喵~';
}
}
Telegram::Send($notice_text);
$myfile = fopen(
BASE_PATH . '/storage/' . $node->id . '.offline',
'wb+'
@ -503,7 +534,7 @@ class Job
fwrite($myfile, $txt);
fclose($myfile);
} elseif ($node->isNodeOnline() === true && file_exists(BASE_PATH . '/storage/' . $node->id . '.offline')) {
if (Config::get('useScFtqq') == true && Config::get('enable_detect_offline_useScFtqq') == true) {
if (Config::get('useScFtqq') == 'true' && Config::get('enable_detect_offline_useScFtqq') == 'true') {
$ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY');
$text = '管理员您好,系统发现节点 ' . $node->name . ' 恢复上线了。';
$postdata = http_build_query(
@ -533,21 +564,54 @@ class Job
Mail::send($to, $subject, 'news/warn.tpl', [
'user' => $user,
'text' => $text
], [
]);
} catch (Exception $e) {
echo $e->getMessage();
}
$notice_text = str_replace(
'%node_name%',
$node->name,
Config::getdb('Telegram.msg.NodeOnline')
);
}
if (Config::getdb('Telegram.enable.NodeOnline') !== '0') {
Telegram::Send($notice_text);
if (Config::get('enable_cloudxns') == 'true' && ($node->sort == 0 || $node->sort == 10 || $node->sort == 12 || $node->sort == 13)) {
$api = new Api();
$api->setApiKey(Config::get('cloudxns_apikey'));//修改成自己API KEY
$api->setSecretKey(Config::get('cloudxns_apisecret'));//修改成自己的SECERET KEY
$api->setProtocol(true);
$domain_json = json_decode($api->domain->domainList());
foreach ($domain_json->data as $domain) {
if (strpos($domain->domain, Config::get('cloudxns_domain')) !== false) {
$domain_id = $domain->id;
}
}
$record_json = json_decode($api->record->recordList($domain_id, 0, 0, 2000));
foreach ($record_json->data as $record) {
if (($record->host . '.' . Config::get('cloudxns_domain')) == $node->server) {
$record_id = $record->record_id;
$api->record->recordUpdate(
$domain_id,
$record->host,
$node->getNodeIp(),
'A',
55,
600,
1,
'',
$record_id
);
}
}
$notice_text = '喵喵喵~ ' . $node->name . ' 节点恢复了喵~域名解析被切换回来了喵~';
} else {
$notice_text = '喵喵喵~ ' . $node->name . ' 节点恢复了喵~';
}
}
Telegram::Send($notice_text);
unlink(BASE_PATH . '/storage/' . $node->id . '.offline');
}
}
@ -555,7 +619,7 @@ class Job
//登录地检测
if (Config::get('login_warn') == true) {
if (Config::get('login_warn') == 'true') {
$iplocation = new QQWry();
$Logs = LoginIp::where('datetime', '>', time() - 60)->get();
foreach ($Logs as $log) {
@ -649,7 +713,7 @@ class Job
if (!file_exists(BASE_PATH . '/storage/traffic_notified/') && !mkdir($concurrentDirectory = BASE_PATH . '/storage/traffic_notified/') && !is_dir($concurrentDirectory)) {
throw new RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
}
if (Config::get('notify_limit_mode') != false) {
if (Config::get('notify_limit_mode') != 'false') {
$user_traffic_left = $user->transfer_enable - $user->u - $user->d;
$under_limit = 'false';
@ -691,9 +755,7 @@ class Job
}
if (Config::get('account_expire_delete_days') >= 0 &&
strtotime($user->expire_in) + Config::get('account_expire_delete_days') * 86400 < time() &&
$user->money <= Config::get('auto_clean_min_money')
strtotime($user->expire_in) + Config::get('account_expire_delete_days') * 86400 < time()
) {
$subject = Config::get('appName') . '-您的用户账户已经被删除了';
$to = $user->email;
@ -786,14 +848,6 @@ class Job
$user->class = 0;
}
// 审计封禁解封
if ($user->detect_ban == 1) {
$logs = DetectBanLog::where('user_id', $user->id)->orderBy("id", "desc")->first();
if (($logs->end_time + $logs->ban_time * 60) <= time() || $logs == null) {
$user->detect_ban = 0;
}
}
$user->save();
}
@ -867,15 +921,50 @@ class Job
} catch (Exception $e) {
echo $e->getMessage();
}
$notice_text = str_replace(
'%node_name%',
$node->name,
Config::getdb('Telegram.msg.NodeGFW')
);
}
if (Config::getdb('Telegram.enable.NodeGFW') !== '0') {
Telegram::Send($notice_text);
if (Config::get('enable_cloudxns') == 'true' && ($node->sort == 0 || $node->sort == 10 || $node->sort == 12 || $node->sort == 13)) {
$api = new Api();
$api->setApiKey(Config::get('cloudxns_apikey'));
//修改成自己API KEY
$api->setSecretKey(Config::get('cloudxns_apisecret'));
//修改成自己的SECERET KEY
$api->setProtocol(true);
$domain_json = json_decode($api->domain->domainList());
foreach ($domain_json->data as $domain) {
if (strpos($domain->domain, Config::get('cloudxns_domain')) !== false) {
$domain_id = $domain->id;
}
}
$record_json = json_decode($api->record->recordList($domain_id, 0, 0, 2000));
foreach ($record_json->data as $record) {
if (($record->host . '.' . Config::get('cloudxns_domain')) == $node->server) {
$record_id = $record->record_id;
$Temp_node = Node::where('node_class', '<=', $node->node_class)->where(
static function ($query) use ($node) {
$query->where('node_group', '=', $node->node_group)
->orWhere('node_group', '=', 0);
}
)->whereRaw('UNIX_TIMESTAMP()-`node_heartbeat`<300')->first();
if ($Temp_node != null) {
$api->record->recordUpdate(
$domain_id,
$record->host,
$Temp_node->server,
'CNAME',
55,
60,
1,
'',
$record_id
);
}
$notice_text = '喵喵喵~ ' . $node->name . ' 节点被墙了喵~域名解析被切换到了 ' . $Temp_node->name . ' 上了喵~';
}
}
} else {
$notice_text = '喵喵喵~ ' . $node->name . ' 节点被墙了喵~';
}
}
Telegram::Send($notice_text);
$file_node = fopen(BASE_PATH . '/storage/' . $node->id . '.gfw', 'wb+');
fclose($file_node);
} else {
@ -898,15 +987,42 @@ class Job
} catch (Exception $e) {
echo $e->getMessage();
}
$notice_text = str_replace(
'%node_name%',
$node->name,
Config::getdb('Telegram.msg.NodeGFW_recover')
);
}
if (Config::getdb('Telegram.enable.NodeGFW_recover') !== '0') {
Telegram::Send($notice_text);
if (Config::get('enable_cloudxns') == 'true' && ($node->sort == 0 || $node->sort == 10 || $node->sort == 12 || $node->sort == 13)) {
$api = new Api();
$api->setApiKey(Config::get('cloudxns_apikey'));
//修改成自己API KEY
$api->setSecretKey(Config::get('cloudxns_apisecret'));
//修改成自己的SECERET KEY
$api->setProtocol(true);
$domain_json = json_decode($api->domain->domainList());
foreach ($domain_json->data as $domain) {
if (strpos($domain->domain, Config::get('cloudxns_domain')) !== false) {
$domain_id = $domain->id;
}
}
$record_json = json_decode($api->record->recordList($domain_id, 0, 0, 2000));
foreach ($record_json->data as $record) {
if (($record->host . '.' . Config::get('cloudxns_domain')) == $node->server) {
$record_id = $record->record_id;
$api->record->recordUpdate(
$domain_id,
$record->host,
$node->getNodeIp(),
'A',
55,
600,
1,
'',
$record_id
);
}
}
$notice_text = '喵喵喵~ ' . $node->name . ' 节点恢复了喵~域名解析被切换回来了喵~';
} else {
$notice_text = '喵喵喵~ ' . $node->name . ' 节点恢复了喵~';
}
}
Telegram::Send($notice_text);
unlink(BASE_PATH . '/storage/' . $node->id . '.gfw');
}
}

@ -1,239 +0,0 @@
<?php
/**
* [实验性] 检测到端口被墙则自动更换端口
*
* // 实验性,可能会有惊喜,请确保拥有承受能力
* // 请通过 Crontab 启动,间隔建议 60 分钟以上
*
* PHP version 7.2+
*
* @category GeekQu
* @package App\Command
* @author GeekQu <iloves@live.com>
* @license MIT https://github.com/GeekQu/ss-panel-v3-mod_Uim/blob/dev/LICENSE
* @link https://github.com/GeekQu
*/
namespace App\Command;
use App\Models\Node;
use App\Models\User;
use App\Services\Config;
use App\Utils\URL;
class PortAutoChange
{
/**
* 配置
*/
private const Config = [
// 取端口范围最小值,新的端口将是之间的随机数
'port_min' => 23333,
// 取端口范围最大值,新的端口将是之间的随机数
'port_max' => 65535,
// 当某个使用的端口的被墙节点数量超过该端口使用总数量的百分比
// 超过该百分比时,直接更换单端口多用户节点(sort=9)和承载用户的端口
// 未超过时,对已被墙该端口的节点进行端口偏移
'mu_node_port_change_percent' => 60,
// 例外的节点,填写节点 ID,英文逗号分隔
// 此处提供的节点将不会进行端口更换
// 即使当原先的承载端口被更换时,也会将例外节点的端口偏移回去
'exception_node_id' => array(),
];
public static function index()
{
$gfw_port_nodes = [];
$nodes = Node::where(
static function ($query) {
$query->where('sort', 0)
->orwhere('sort', 10);
}
)
->where('mu_only', '>=', '0')
->where('type', '1')
->get();
foreach ($nodes as $node) {
$mu_nodes = Node::where('sort', 9)->where('type', '1')
->where(
static function ($query) use ($node) {
$query->Where('node_group', '=', $node->node_group)
->orWhere('node_group', '=', 0);
}
)
->where('node_class', '<=', $node->node_class)
->get();
foreach ($mu_nodes as $mu_node) {
$mu_user = User::where('enable', 1)->where('is_multi_user', '<>', 0)->where('port', '=', $mu_node->server)->first();
if ($mu_user == null) continue;
$port = self::OutPort($node->server, $mu_node->server);
$api_url = Config::get('detect_gfw_url');
$api_url = str_replace(
array('{ip}', '{port}'),
array($node->node_ip, $port),
$api_url
);
$result_tcping = self::DetectPort($api_url);
if ($result_tcping) continue;
$gfw_port_nodes[$mu_node->server][] = $node->id;
echo ('#' . $node->id . ' --- ' . $node->name . ' --- ' . $port . ' 端口不通' . PHP_EOL);
}
}
foreach ($gfw_port_nodes as $port => $array) {
$mu_node = Node::where('sort', 9)->where('server', '=', $port)->where('type', '1')->first();
$mu_user = User::where('enable', 1)->where('is_multi_user', '<>', 0)->where('port', '=', $port)->first();
if ($mu_node == null || $mu_user == null) continue;
$mu_port_nodes = Node::where(
static function ($query) {
$query->where('sort', 0)
->orwhere('sort', 10);
}
)
->where(
static function ($query) use ($mu_node) {
if ($mu_node->node_group == 0) {
$query->where('node_group', '>=', 0);
} else {
$query->where('node_group', '=', $mu_node->node_group);
}
}
)
->where('node_class', '>=', $mu_node->node_class)
->where('mu_only', '>=', '0')
->where('type', '1')
->get();
for ($i = 0; $i <= 10; $i++) {
$new_port = rand((int) self::Config['port_min'], (int) self::Config['port_max']);
if (Node::where('sort', 9)->where('server', '=', $new_port)->first() == null && User::where('port', '=', $new_port)->first() == null) {
break;
}
}
$number = (count($array) / count($mu_port_nodes)) * 100;
if ($number >= self::Config['mu_node_port_change_percent']) {
echo ('超过百分比:' . $number . '%'. PHP_EOL);
echo ('#' . $mu_node->id . ' - 单端口承载节点 - ' . $mu_node->name . ' - 更换了新的端口 ' . $new_port . PHP_EOL);
$mu_node->server = $new_port;
$mu_node->save();
echo ('#' . $mu_user->id . ' - 单端口承载用户 - ' . $mu_user->user_name . ' - 更换了新的端口 ' . $new_port . PHP_EOL);
$mu_user->port = $new_port;
$mu_user->save();
foreach ($mu_port_nodes as $mu_port_node) {
$node_port = self::OutPort($mu_port_node->server, $port);
if (in_array($mu_port_node->id, $array) && !in_array($mu_port_node->id, self::Config['exception_node_id'])) {
if ($node_port != $port) {
if ($node_port == $new_port) {
if (strpos($mu_port_node->server, ($port . '#')) !== false) {
for ($i = 0; $i <= 10; $i++) {
$new_mu_node_port = rand((int) self::Config['port_min'], (int) self::Config['port_max']);
if ($new_mu_node_port != $new_port && Node::where('port', '=', $new_mu_node_port)->first() == null && User::where('port', '=', $new_mu_node_port)->first() == null) {
break;
}
}
$mu_port_node->server = str_replace(($port . '#' . $node_port), ($new_port . '#' . $new_mu_node_port), $mu_port_node->server);
echo ('#' . $mu_port_node->id . ' - 节点 - ' . $mu_port_node->name . ' - 端口从 ' . $node_port . ' 偏移到了新的端口 ' . $new_mu_node_port . PHP_EOL);
}
} else {
if (strpos($mu_port_node->server, ($port . '#')) !== false) {
$mu_port_node->server = str_replace(('+' . $port . '#' . $node_port), '', $mu_port_node->server);
$mu_port_node->server = str_replace(($port . '#' . $node_port . '+'), '', $mu_port_node->server);
$mu_port_node->server = str_replace(($port . '#' . $node_port), '', $mu_port_node->server);
echo ('#' . $mu_port_node->id . ' - 节点 - ' . $mu_port_node->name . ' - 端口从 ' . $node_port . ' 偏移到了新的端口 ' . $new_port . PHP_EOL);
}
}
}
} else {
if ($node_port == $port) {
if (strpos($mu_port_node->server, ';') !== false) {
if (strpos($mu_port_node->server, 'port=') !== false) {
$mu_port_node->server = str_replace('port=', ('port=' . $new_port . '#' . $port . '+'), $mu_port_node->server);
} else {
$mu_port_node->server = ($mu_port_node->server . ';port=' . $new_port . '#' . $port);
}
} else {
$mu_port_node->server = ($mu_port_node->server . ';port=' . $new_port . '#' . $port);
}
} else {
if (strpos($mu_port_node->server, ($port . '#')) !== false) {
$mu_port_node->server = str_replace(($port . '#'), ($new_port . '#'), $mu_port_node->server);
}
}
echo ('#' . $mu_port_node->id . ' - 节点 - ' . $mu_port_node->name . ' - 由于端口未被墙或例外设置,已将端口偏移回原端口 ' . $node_port . PHP_EOL);
}
$mu_port_node->save();
}
} else {
foreach ($array as $node_id) {
if (in_array($node_id, self::Config['exception_node_id'])) continue;
$node = Node::find($node_id);
$node_port = self::OutPort($node->server, $port);
if ($node_port != $port) {
if (strpos($node->server, ('#' . $node_port)) !== false) {
echo ('#' . $node->id . ' - 节点 - ' . $node->name . ' - 端口从' . $node_port . '偏移到了新的端口 ' . $new_port . PHP_EOL);
$node->server = str_replace(('#' . $node_port), ('#' . $new_port), $node->server);
}
} else {
if (strpos($node->server, ';') !== false) {
if (strpos($node->server, 'port=') !== false) {
$node->server = str_replace('port=', ('port=' . $port . '#' . $new_port . '+'), $node->server);
} else {
$node->server = ($node->server . ';port=' . $port . '#' . $new_port);
}
} else {
$node->server = ($node->server . ';port=' . $port . '#' . $new_port);
}
echo ('#' . $node->id . ' - 节点 - ' . $node->name . ' - 端口从' . $node_port . '偏移到了新的端口 ' . $new_port . PHP_EOL);
}
$node->save();
}
}
}
}
public static function OutPort($server, $mu_port)
{
$node_port = $mu_port;
if (strpos($server, ';') !== false) {
$node_server = explode(';', $server);
if (strpos($node_server[1], 'port') !== false) {
$item = URL::parse_args($node_server[1]);
if (strpos($item['port'], '#') !== false) {
if (strpos($item['port'], '+') !== false) {
$args_explode = explode('+', $item['port']);
foreach ($args_explode as $arg) {
if ((int) substr($arg, 0, strpos($arg, '#')) == $mu_port) {
$node_port = (int) substr($arg, strpos($arg, '#') + 1);
}
}
} else {
if ((int) substr($item['port'], 0, strpos($item['port'], '#')) == $mu_port) {
$node_port = (int) substr($item['port'], strpos($item['port'], '#') + 1);
}
}
} else {
$node_port = ($mu_port + (int) $item['port']);
}
}
}
return $node_port;
}
public static function DetectPort($api_url)
{
$result_tcping = false;
$detect_time = Config::get('detect_gfw_count');
for ($i = 1; $i <= $detect_time; $i++) {
$json_tcping = json_decode(file_get_contents($api_url), true);
if (eval('return ' . Config::get('detect_gfw_judge') . ';')) {
$result_tcping = true;
break;
}
}
return $result_tcping;
}
}

@ -20,7 +20,7 @@ class SyncRadius
{
public static function synclogin()
{
if (Config::get('enable_radius') == false) {
if (Config::get('enable_radius') == 'false') {
return;
}
$tempuserbox = array();

@ -3,7 +3,6 @@
namespace App\Command;
use App\Services\Config;
use App\Services\DefaultConfig;
class Update
{
@ -18,10 +17,6 @@ class Update
return false;
}
echo(PHP_EOL);
// 检查并创建新增的配置项
echo DefaultConfig::detectConfigs();
echo(PHP_EOL);
echo('开始升级客户端...' . PHP_EOL);
@ -137,5 +132,10 @@ class Update
public static function old_to_new($version_old)
{
if ($version_old <= 0) {
echo('执行升级:0 -> 1');
$conn = mysqli_connect(Config::get('db_host'), Config::get('db_username'), Config::get('db_password'), Config::get('db_database'));
mysqli_query($conn, 'ALTER TABLE user ADD discord BIGINT NULL AFTER telegram_id');
}
}
}

@ -12,11 +12,10 @@ use App\Models\Relay;
use App\Services\Gateway\ChenPay;
use App\Utils\Hash;
use App\Utils\Tools;
use App\Utils\Discord;
use App\Services\Config;
use App\Services\DefaultConfig;
use App\Utils\GA;
use App\Models\Node;
use App\Utils\DNSoverHTTPS;
use Exception;
use TelegramBot\Api\BotApi;
@ -32,10 +31,6 @@ class XCat
public function boot()
{
switch ($this->argv[1]) {
case ('detectConfigs'):
return $this->detectConfigs();
case ('portAutoChange'):
return PortAutoChange::index();
case ('alipay'):
return (new ChenPay())->AliPayListen();
case ('wxpay'):
@ -44,6 +39,8 @@ class XCat
return $this->createAdmin();
case ('resetTraffic'):
return $this->resetTraffic();
case ('setDiscord'):
return Discord::set();
case ('setTelegram'):
return $this->setTelegram();
case ('initQQWry'):
@ -88,8 +85,6 @@ class XCat
return Job::backup(true);
case ('initdownload'):
return $this->initdownload();
case ('initdocuments'):
return $this->initdocuments();
case ('updatedownload'):
return Job::updatedownload();
case ('cleanRelayRule'):
@ -106,12 +101,6 @@ class XCat
return $this->npmbuild();
case ('getCookie'):
return $this->getCookie();
case ('iptest'):
return $this->iptest();
case ('delSubCache'):
return $this->delSubCache();
case ('setNewTelegram'):
return $this->setNewTelegram();
default:
return $this->defaultAction();
}
@ -119,18 +108,18 @@ class XCat
public function defaultAction()
{
echo (PHP_EOL . '用法: php xcat [选项]' . PHP_EOL);
echo ('常用选项:' . PHP_EOL);
echo (' createAdmin - 创建管理员帐号' . PHP_EOL);
echo (' setTelegram - 设置 Telegram 机器人' . PHP_EOL);
echo (' cleanRelayRule - 清除所有中转规则' . PHP_EOL);
echo (' resetPort - 重置单个用户端口' . PHP_EOL);
echo (' resetAllPort - 重置所有用户端口' . PHP_EOL);
echo (' initdownload - 下载 SSR 程序至服务器' . PHP_EOL);
echo (' initdocuments - 下载用户使用文档至服务器' . PHP_EOL);
echo (' initQQWry - 下载 IP 解析库' . PHP_EOL);
echo (' resetTraffic - 重置所有用户流量' . PHP_EOL);
echo (' update - 更新并迁移配置' . PHP_EOL);
echo(PHP_EOL . '用法: php xcat [选项]' . PHP_EOL);
echo('常用选项:' . PHP_EOL);
echo(' createAdmin - 创建管理员帐号' . PHP_EOL);
echo(' setDiscord - 设置 Discord 机器人' . PHP_EOL);
echo(' setTelegram - 设置 Telegram 机器人' . PHP_EOL);
echo(' cleanRelayRule - 清除所有中转规则' . PHP_EOL);
echo(' resetPort - 重置单个用户端口' . PHP_EOL);
echo(' resetAllPort - 重置所有用户端口' . PHP_EOL);
echo(' initdownload - 下载 SSR 程序至服务器' . PHP_EOL);
echo(' initQQWry - 下载 IP 解析库' . PHP_EOL);
echo(' resetTraffic - 重置所有用户流量' . PHP_EOL);
echo(' update - 更新并迁移配置' . PHP_EOL);
}
public function resetPort()
@ -167,9 +156,9 @@ class XCat
{
$rules = Relay::all();
foreach ($rules as $rule) {
echo ($rule->id . "\n");
echo($rule->id . "\n");
if ($rule->source_node_id == 0) {
echo ($rule->id . "被删除!\n");
echo($rule->id . "被删除!\n");
$rule->delete();
continue;
}
@ -177,7 +166,7 @@ class XCat
$ruleset = Relay::where('user_id', $rule->user_id)->orwhere('user_id', 0)->get();
$maybe_rule_id = Tools::has_conflict_rule($rule, $ruleset, $rule->id);
if ($maybe_rule_id != 0) {
echo ($rule->id . "被删除!\n");
echo($rule->id . "被删除!\n");
$rule->delete();
}
}
@ -189,12 +178,6 @@ class XCat
echo $ret;
}
public function initdocuments()
{
system('git clone https://github.com/GeekQu/PANEL_DOC.git ' . BASE_PATH . "/public/docs/", $ret);
echo $ret;
}
public function createAdmin()
{
if (count($this->argv) === 2) {
@ -210,7 +193,7 @@ class XCat
fwrite(STDOUT, "Press [y] to create admin..... 按下[Y]确认来确认创建管理员账户..... \n");
$y = trim(fgets(STDIN));
} elseif (count($this->argv) === 4) {
[,, $email, $passwd] = $this->argv;
[, , $email, $passwd] = $this->argv;
$y = 'y';
}
@ -275,42 +258,32 @@ class XCat
public function setTelegram()
{
$bot = new BotApi(Config::get('telegram_token'));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, sprintf('https://api.telegram.org/bot%s/deleteWebhook', Config::get('telegram_token')));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$ch= curl_init();
curl_setopt ($ch, CURLOPT_URL, sprintf('https://api.telegram.org/bot%s/deleteWebhook', Config::get('telegram_token')));
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
$deleteWebhookReturn = json_decode(curl_exec($ch));
curl_close($ch);
if ($deleteWebhookReturn->ok && $deleteWebhookReturn->result && $bot->setWebhook(Config::get('baseUrl') . '/telegram_callback?token=' . Config::get('telegram_request_token')) == 1) {
echo ('设置成功!' . PHP_EOL);
}
}
public function setNewTelegram()
{
$WebhookUrl = (Config::get('baseUrl') . '/TelegramCallback?token=' . Config::get('new_telegram_request_token'));
$telegram = new \Telegram\Bot\Api(Config::get('new_telegram_token'));
$telegram->removeWebhook();
if ($telegram->setWebhook(['url' => $WebhookUrl])) {
echo('Bot @' . $telegram->getMe()->getUsername() . ' 设置成功!');
echo('设置成功!' . PHP_EOL);
}
}
public function initQQWry()
{
echo ('开始下载纯真 IP 数据库....');
echo('开始下载纯真 IP 数据库....');
$qqwry = file_get_contents('https://qqwry.mirror.noc.one/QQWry.Dat?from=sspanel_uim');
if ($qqwry != '') {
$fp = fopen(BASE_PATH . '/storage/qqwry.dat', 'wb');
if ($fp) {
fwrite($fp, $qqwry);
fclose($fp);
echo ('纯真 IP 数据库下载成功!');
echo('纯真 IP 数据库下载成功!');
} else {
echo ('纯真 IP 数据库保存失败!');
echo('纯真 IP 数据库保存失败!');
}
} else {
echo ('下载失败!请重试,或在 https://github.com/SukkaW/qqwry-mirror/issues/new 反馈!');
echo('下载失败!请重试,或在 https://github.com/SukkaW/qqwry-mirror/issues/new 反馈!');
}
}
@ -357,25 +330,6 @@ class XCat
system('cp -u ../public/vuedist/index.html ../resources/views/material/index.tpl');
}
public function iptest()
{
$nodes = Node::all();
foreach ($nodes as $node) {
$ip = "";
$server = "";
if (in_array($node->sort, array(0, 1, 10, 11, 12, 13))) {
$server_list = explode(";", $node->server);
$server = $server_list[0];
if (!Tools::is_ip($server)) {
$ip = DNSoverHTTPS::gethostbyName($server); // returns a collection of DNS A Records
}
}
if ($server != "" and $ip != "") {
echo "Server: " . $server . " ip address: " . $ip . "\n";
}
}
}
public function getCookie()
{
if (count($this->argv) === 3) {
@ -384,22 +338,4 @@ class XCat
echo Hash::cookieHash($user->pass, $expire_in) . ' ' . $expire_in;
}
}
public function detectConfigs()
{
echo DefaultConfig::detectConfigs();
}
public function delSubCache()
{
if (Config::get('enable_sub_cache') === true) {
if (Tools::delSubCache() === true) {
echo (PHP_EOL . '订阅缓存清理成功.' . PHP_EOL);
} else {
echo (PHP_EOL . '订阅缓存清理失败.' . PHP_EOL);
}
} else {
echo (PHP_EOL . '订阅缓存未开启.' . PHP_EOL);
}
}
}

@ -1,43 +0,0 @@
<?php
namespace App\Controllers\Admin;
use App\Controllers\AdminController;
use Ozdemir\Datatables\Datatables;
use App\Utils\DatatablesHelper;
class DetectBanLogController extends AdminController
{
public function index($request, $response, $args)
{
$table_config['total_column'] = array("id" => "ID", "user_id" => "用户ID",
"user_name" => "用户名", "email" => "用户邮箱",
"detect_number" => "违规次数", "ban_time" => "封禁时长(分钟)",
"start_time" => "统计开始时间", "end_time" => "统计结束以及封禁开始时间",
"ban_end_time" => "封禁结束时间", "all_detect_number" => "累计违规次数");
$table_config['default_show_column'] = array();
foreach ($table_config['total_column'] as $column => $value) {
array_push($table_config['default_show_column'], $column);
}
$table_config['ajax_url'] = 'ban/ajax';
return $this->view()->assign('table_config', $table_config)->display('admin/detect/ban.tpl');
}
public function ajax_log($request, $response, $args)
{
$datatables = new Datatables(new DatatablesHelper());
$datatables->query('Select detect_ban_log.id,detect_ban_log.user_id,detect_ban_log.user_name,detect_ban_log.email,detect_ban_log.detect_number,detect_ban_log.ban_time,detect_ban_log.start_time,detect_ban_log.end_time,detect_ban_log.all_detect_number,detect_ban_log.end_time as ban_end_time from detect_ban_log');
$datatables->edit('start_time', function ($data) {
return date('Y-m-d H:i:s', $data['start_time']);
});
$datatables->edit('end_time', function ($data) {
return date('Y-m-d H:i:s', $data['end_time']);
});
$datatables->edit('ban_end_time', function ($data) {
return date('Y-m-d H:i:s', $data['ban_end_time']+$data['ban_time']*60);
});
$body = $response->getBody();
$body->write($datatables->generate());
}
}

@ -1,108 +0,0 @@
<?php
namespace App\Controllers\Admin;
use App\Controllers\AdminController;
use App\Services\Auth;
use App\Models\GConfig;
class GConfigController extends AdminController
{
public function update($request, $response, $args)
{
$key = trim($args['key']);
$user = Auth::getUser();
$config = GConfig::find($key);
$config->oldvalue = $config->value;
$config->value = $request->getParam('value');
$config->operator_id = $user->id;
$config->operator_name = $user->user_name;
$config->operator_email = $user->email;
$config->last_update = time();
if (!$config->save()) {
$rs['ret'] = 0;
$rs['msg'] = '修改失败';
return $response->write(json_encode($rs));
}
$rs['ret'] = 1;
$rs['msg'] = '修改成功';
return $response->write(json_encode($rs));
}
public function telegram($request, $response, $args)
{
$table_config['total_column'] = array(
'op' => '操作',
'name' => '配置名称',
'key' => '配置名',
'value' => '配置值',
'operator_id' => '操作员 ID',
'operator_name' => '操作员名称',
'operator_email' => '操作员邮箱',
'last_update' => '修改时间'
);
$table_config['default_show_column'] = array();
foreach ($table_config['total_column'] as $column => $value) {
$table_config['default_show_column'][] = $column;
}
$table_config['ajax_url'] = 'telegram/ajax';
return $this->view()->assign('table_config', $table_config)->fetch('admin/config/telegram/index.tpl');
}
public function telegram_edit($request, $response, $args)
{
$key = trim($args['key']);
$config = GConfig::find($key);
return $this->view()->assign('edit_config', $config)->fetch('admin/config/telegram/edit.tpl');
}
public function telegram_update($request, $response, $args)
{
return self::update($request, $response, $args);
}
public function telegram_ajax($request, $response, $args)
{
$start = $request->getParam("start");
$limit_length = $request->getParam('length');
$configs = GConfig::skip($start)->where('key', 'LIKE', "%Telegram%")->limit($limit_length)->get();
$total_conut = GConfig::where('key', 'LIKE', "%Telegram%")->count();
$data = [];
foreach ($configs as $config) {
$tempdata = [];
$tempdata['op'] = '<a class="btn btn-brand" href="/admin/config/telegram/' . $config->key . '/edit">编辑</a>';
$tempdata['name'] = $config->name;
$tempdata['key'] = $config->key;
$tempdata['value'] = $config->value;
$tempdata['operator_id'] = $config->operator_id;
$tempdata['operator_name'] = $config->operator_name;
$tempdata['operator_email'] = $config->operator_email;
$tempdata['last_update'] = date('Y-m-d H:i:s', $config->last_update);
if (strpos($config->key, '.enable.')) {
switch ((int) $config->value) {
case 0:
$tempdata['value'] = '关闭';
break;
case 1:
$tempdata['value'] = '开启';
break;
default:
$tempdata['value'] = '未知';
break;
}
} else {
$tempdata['value'] = '(请在编辑页面查看)';
}
$data[] = $tempdata;
}
$info = [
'draw' => $request->getParam('draw'),
'recordsTotal' => $total_conut,
'recordsFiltered' => $total_conut,
'data' => $data
];
return json_encode($info, true);
}
}

@ -11,7 +11,6 @@ use App\Utils\CloudflareDriver;
use App\Services\Config;
use Ozdemir\Datatables\Datatables;
use App\Utils\DatatablesHelper;
use App\Utils\DNSoverHTTPS;
class NodeController extends AdminController
{
@ -64,9 +63,6 @@ class NodeController extends AdminController
$server_list = explode(';', $node->server);
if (!Tools::is_ip($server_list[0])) {
$node->node_ip = gethostbyname($server_list[0]);
if ($node->node_ip == "127.0.0.1") {
$node->node_ip = DNSoverHTTPS::gethostbyName($server_list[0]);
}
} else {
$node->node_ip = $req_node_ip;
}
@ -86,28 +82,14 @@ class NodeController extends AdminController
$node->node_bandwidth_limit = $request->getParam('node_bandwidth_limit') * 1024 * 1024 * 1024;
$node->bandwidthlimit_resetday = $request->getParam('bandwidthlimit_resetday');
if (in_array($node->sort, array(11, 12, 13))) {
$node->mu_only = 1;
}
$node->save();
$domain_name = explode('.' . Config::get('cloudflare_name'), $node->server);
if (Config::get('cloudflare_enable') == true) {
if (Config::get('cloudflare_enable') == 'true') {
CloudflareDriver::updateRecord($domain_name[0], $node->node_ip);
}
if (Config::getdb('Telegram.enable.AddNode') !== '0') {
Telegram::Send(
str_replace(
'%node_name%',
$request->getParam('name'),
Config::getdb('Telegram.msg.AddNode')
)
);
}
Tools::delSubCache();
Telegram::Send('新节点添加~' . $request->getParam('name'));
$rs['ret'] = 1;
$rs['msg'] = '节点添加成功';
@ -170,18 +152,10 @@ class NodeController extends AdminController
$SS_Node = Node::where('sort', '=', 0)->where('server', '=', $request->getParam('server'))->first();
if ($SS_Node != null) {
if ($SS_Node->node_heartbeat == 0 || time() - $SS_Node->node_heartbeat < 300) {
$ip = gethostbyname($request->getParam('server'));
if ($ip == '127.0.0.1') {
$ip = DNSoverHTTPS::gethostbyName($request->getParam('server'));
}
Radius::AddNas($ip, $request->getParam('server'));
Radius::AddNas(gethostbyname($request->getParam('server')), $request->getParam('server'));
}
} else {
$ip = gethostbyname($request->getParam('server'));
if ($ip == "127.0.0.1") {
$ip = DNSoverHTTPS::gethostbyName($request->getParam('server'));
}
Radius::AddNas($ip, $request->getParam('server'));
Radius::AddNas(gethostbyname($request->getParam('server')), $request->getParam('server'));
}
}
@ -190,23 +164,9 @@ class NodeController extends AdminController
$node->node_bandwidth_limit = $request->getParam('node_bandwidth_limit') * 1024 * 1024 * 1024;
$node->bandwidthlimit_resetday = $request->getParam('bandwidthlimit_resetday');
if (in_array($node->sort, array(11, 12, 13))) {
$node->mu_only = 1;
}
$node->save();
if (Config::getdb('Telegram.enable.UpdateNode') !== '0') {
Telegram::Send(
str_replace(
'%node_name%',
$request->getParam('name'),
Config::getdb('Telegram.msg.UpdateNode')
)
);
}
Tools::delSubCache();
Telegram::Send('节点信息被修改~' . $request->getParam('name'));
$rs['ret'] = 1;
$rs['msg'] = '修改成功';
@ -222,23 +182,15 @@ class NodeController extends AdminController
Radius::DelNas($node->node_ip);
}
$name = $node->name;
if (!$node->delete()) {
$rs['ret'] = 0;
$rs['msg'] = '删除失败';
return $response->getBody()->write(json_encode($rs));
}
if (Config::getdb('Telegram.enable.DeleteNode') !== '0') {
Telegram::Send(
str_replace(
'%node_name%',
$node->name,
Config::getdb('Telegram.msg.DeleteNode')
)
);
}
Tools::delSubCache();
Telegram::Send('节点被删除~' . $name);
$rs['ret'] = 1;
$rs['msg'] = '删除成功';

@ -52,7 +52,7 @@ class RelayController extends AdminController
foreach ($dist_nodes as $node) {
if ($node->sort == 11 || $node->sort == 12) {
$node_explode = Tools::v2Array($node->server);
$node_explode = Tools::ssv2Array($node->server);
$node->name = $node->name . ' 如果是V2ray后端 请设置成 ' . $node_explode['port'];
} else {
$node->name .= ' 如果是V2ray后端 请不要设置,用户页面设置 ';
@ -124,8 +124,6 @@ class RelayController extends AdminController
return $response->getBody()->write(json_encode($rs));
}
Tools::delSubCache();
$rs['ret'] = 1;
$rs['msg'] = '添加成功';
return $response->getBody()->write(json_encode($rs));
@ -165,7 +163,7 @@ class RelayController extends AdminController
foreach ($dist_nodes as $node) {
if ($node->sort == 11 || $node->sort == 12) {
$node_explode = Tools::v2Array($node->server);
$node_explode = Tools::ssv2Array($node->server);
$node->name = $node->name . ' 如果是V2ray后端 请设置成' . $node_explode['port'];
} else {
$node->name .= ' 如果是V2ray后端 请不要设置,用户页面设置 ';
@ -236,8 +234,6 @@ class RelayController extends AdminController
return $response->getBody()->write(json_encode($rs));
}
Tools::delSubCache();
$rs['ret'] = 1;
$rs['msg'] = '修改成功';
return $response->getBody()->write(json_encode($rs));
@ -259,9 +255,6 @@ class RelayController extends AdminController
$rs['msg'] = '删除失败';
return $response->getBody()->write(json_encode($rs));
}
Tools::delSubCache();
$rs['ret'] = 1;
$rs['msg'] = '删除成功';
return $response->getBody()->write(json_encode($rs));

@ -1,41 +0,0 @@
<?php
namespace App\Controllers\Admin;
use App\Controllers\AdminController;
use App\Utils\QQWry;
use Ozdemir\Datatables\Datatables;
use App\Utils\DatatablesHelper;
class SubscribeLogController extends AdminController
{
public function index($request, $response, $args)
{
$table_config['total_column'] = array('id' => 'ID', 'user_name' => '用户名',
'user_id' => '用户ID', 'email' => '用户邮箱', 'subscribe_type' => '类型',
'request_ip' => 'IP', 'location' => '归属地', 'request_time' => '时间',
'request_user_agent' => 'User-Agent');
$table_config['default_show_column'] = array();
foreach ($table_config['total_column'] as $column => $value) {
$table_config['default_show_column'][] = $column;
}
$table_config['ajax_url'] = 'subscribe/ajax';
return $this->view()->assign('table_config', $table_config)->display('admin/subscribe.tpl');
}
public function ajax_subscribe_log($request, $response, $args)
{
$datatables = new Datatables(new DatatablesHelper());
$datatables->query('Select user_subscribe_log.id,user_subscribe_log.user_name,user_subscribe_log.user_id,user_subscribe_log.email,user_subscribe_log.subscribe_type,user_subscribe_log.request_ip,user_subscribe_log.request_ip as location,user_subscribe_log.request_time,user_subscribe_log.request_user_agent from user_subscribe_log');
$iplocation = new QQWry();
$datatables->edit('location', static function ($data) use ($iplocation) {
$location = $iplocation->getlocation($data['location']);
return iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']);
});
$body = $response->getBody();
$body->write($datatables->generate());
}
}

@ -2,60 +2,40 @@
namespace App\Controllers\Admin;
use App\Controllers\AdminController;
use App\Models\Bought;
use App\Models\User;
use App\Models\Ip;
use App\Models\Bought;
use App\Models\Relay;
use App\Models\User;
use App\Models\DetectBanLog;
use App\Services\Auth;
use App\Controllers\AdminController;
use App\Services\Config;
use App\Services\Auth;
use App\Services\Mail;
use App\Utils;
use App\Utils\GA;
use App\Utils\Hash;
use App\Utils\QQWry;
use App\Utils\Radius;
use App\Utils\QQWry;
use App\Utils\Check;
use App\Utils\Tools;
use App\Utils\GA;
use Exception;
class UserController extends AdminController
{
public function index($request, $response, $args)
{
$table_config['total_column'] = array(
'op' => '操作',
'id' => 'ID',
'user_name' => '用户名',
'remark' => '备注',
'email' => '邮箱',
'money' => '金钱',
'im_type' => '联络方式类型',
'im_value' => '联络方式详情',
'node_group' => '群组',
'expire_in' => '账户过期时间',
'class' => '等级',
'class_expire' => '等级过期时间',
'passwd' => '连接密码',
'port' => '连接端口',
'method' => '加密方式',
'protocol' => '连接协议',
'obfs' => '混淆方式',
'obfs_param' => '混淆参数',
'online_ip_count' => '在线IP数',
'last_ss_time' => '上次使用时间',
'used_traffic' => '已用流量/GB',
'enable_traffic' => '总流量/GB',
'last_checkin_time' => '上次签到时间',
'today_traffic' => '今日流量/MB',
'enable' => '是否启用',
'reg_date' => '注册时间',
'reg_ip' => '注册IP',
'auto_reset_day' => '自动重置流量日',
'auto_reset_bandwidth' => '自动重置流量/GB',
'ref_by' => '邀请人ID',
'ref_by_user_name' => '邀请人用户名',
$table_config['total_column'] = array('op' => '操作', 'id' => 'ID', 'user_name' => '用户名',
'remark' => '备注', 'email' => '邮箱', 'money' => '金钱',
'im_type' => '联络方式类型', 'im_value' => '联络方式详情',
'node_group' => '群组', 'expire_in' => '账户过期时间',
'class' => '等级', 'class_expire' => '等级过期时间',
'passwd' => '连接密码', 'port' => '连接端口', 'method' => '加密方式',
'protocol' => '连接协议', 'obfs' => '连接混淆方式',
'online_ip_count' => '在线IP数', 'last_ss_time' => '上次使用时间',
'used_traffic' => '已用流量/GB', 'enable_traffic' => '总流量/GB',
'last_checkin_time' => '上次签到时间', 'today_traffic' => '今日流量/MB',
'enable' => '是否启用', 'reg_date' => '注册时间',
'reg_ip' => '注册IP', 'auto_reset_day' => '自动重置流量日',
'auto_reset_bandwidth' => '自动重置流量/GB', 'ref_by' => '邀请人ID', 'ref_by_user_name' => '邀请人用户名',
'top_up' => '累计充值');
$table_config['default_show_column'] = array('op', 'id', 'user_name', 'remark', 'email');
$table_config['ajax_url'] = 'user/ajax';
@ -134,7 +114,7 @@ class UserController extends AdminController
$text = '您好,管理员已经为您生成账户,用户名: ' . $email . ',登录密码为:' . $pass . ',感谢您的支持。 ';
try {
Mail::send($to, $subject, 'newuser.tpl', [
'user' => $user, 'text' => $text,
'user' => $user, 'text' => $text
], [
]);
} catch (Exception $e) {
@ -195,6 +175,7 @@ class UserController extends AdminController
return $response->getBody()->write(json_encode($result));
}
public function search($request, $response, $args)
{
$pageNum = 1;
@ -206,9 +187,11 @@ class UserController extends AdminController
$users = User::where('email', 'LIKE', '%' . $text . '%')->orWhere('user_name', 'LIKE', '%' . $text . '%')->orWhere('im_value', 'LIKE', '%' . $text . '%')->orWhere('port', 'LIKE', '%' . $text . '%')->orWhere('remark', 'LIKE', '%' . $text . '%')->paginate(20, ['*'], 'page', $pageNum);
$users->setPath('/admin/user/search/' . $text);
//Ip::where("datetime","<",time()-90)->get()->delete();
$total = Ip::where('datetime', '>=', time() - 90)->orderBy('userid', 'desc')->get();
$userip = array();
$useripcount = array();
$regloc = array();
@ -222,6 +205,7 @@ class UserController extends AdminController
$regloc[$user->id] = iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']);
}
foreach ($total as $single) {
if (isset($useripcount[$single->userid]) && !isset($userip[$single->userid][$single->ip])) {
++$useripcount[$single->userid];
@ -230,6 +214,7 @@ class UserController extends AdminController
}
}
return $this->view()->assign('users', $users)->assign('regloc', $regloc)->assign('useripcount', $useripcount)->assign('userip', $userip)->display('admin/user/index.tpl');
}
@ -242,11 +227,14 @@ class UserController extends AdminController
$pageNum = $request->getQueryParams()['page'];
}
$users->setPath('/admin/user/sort/' . $text . '/' . $asc);
//Ip::where("datetime","<",time()-90)->get()->delete();
$total = Ip::where('datetime', '>=', time() - 90)->orderBy('userid', 'desc')->get();
$userip = array();
$useripcount = array();
$regloc = array();
@ -260,6 +248,7 @@ class UserController extends AdminController
$regloc[$user->id] = iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']);
}
foreach ($total as $single) {
if (isset($useripcount[$single->userid]) && !isset($userip[$single->userid][$single->ip])) {
++$useripcount[$single->userid];
@ -268,9 +257,11 @@ class UserController extends AdminController
}
}
return $this->view()->assign('users', $users)->assign('regloc', $regloc)->assign('useripcount', $useripcount)->assign('userip', $userip)->display('admin/user/index.tpl');
}
public function edit($request, $response, $args)
{
$id = $args['id'];
@ -293,6 +284,7 @@ class UserController extends AdminController
Radius::ChangeUserName($email1, $email2, $passwd);
if ($request->getParam('pass') != '') {
$user->pass = Hash::passwordHash($request->getParam('pass'));
$user->clean_link();
@ -334,33 +326,6 @@ class UserController extends AdminController
$user->forbidden_ip = str_replace(PHP_EOL, ',', $request->getParam('forbidden_ip'));
$user->forbidden_port = str_replace(PHP_EOL, ',', $request->getParam('forbidden_port'));
$detect_ban = (int)$request->getParam('detect_ban');
// 手动解封
if ($user->detect_ban == 1 && $detect_ban == 0) {
$user->detect_ban = 0;
}
// 手动封禁
if ($user->detect_ban == 0 && $detect_ban == 1) {
if ((int)$request->getParam('ban_time') == 0) {
$rs['ret'] = 0;
$rs['msg'] = "修改失败,封禁时长不能为 0";
return $response->getBody()->write(json_encode($rs));
}
$user->detect_ban = 1;
$end_time = date('Y-m-d H:i:s');
$user->last_detect_ban_time = $end_time;
$DetectBanLog = new DetectBanLog();
$DetectBanLog->user_name = $user->user_name;
$DetectBanLog->user_id = $user->id;
$DetectBanLog->email = $user->email;
$DetectBanLog->detect_number = '0';
$DetectBanLog->ban_time = (int)$request->getParam('ban_time');
$DetectBanLog->start_time = strtotime('1989-06-04 00:05:00');
$DetectBanLog->end_time = strtotime($end_time);
$DetectBanLog->all_detect_number = $user->all_detect_number;
$DetectBanLog->save();
}
if (!$user->save()) {
$rs['ret'] = 0;
$rs['msg'] = '修改失败';
@ -413,7 +378,7 @@ class UserController extends AdminController
'old_key' => Utils\Cookie::get('key'),
'old_ip' => Utils\Cookie::get('ip'),
'old_expire_in' => Utils\Cookie::get('expire_in'),
'old_local' => $request->getParam('local'),
'old_local' => $request->getParam('local')
], $expire_in);
$rs['ret'] = 1;
$rs['msg'] = '切换成功';
@ -546,7 +511,6 @@ class UserController extends AdminController
$tempdata['method'] = $user->method;
$tempdata['protocol'] = $user->protocol;
$tempdata['obfs'] = $user->obfs;
$tempdata['obfs_param'] = $user->obfs_param;
$tempdata['online_ip_count'] = $user->online_ip_count();
$tempdata['last_ss_time'] = $user->lastSsTime();
$tempdata['used_traffic'] = Tools::flowToGB($user->u + $user->d);
@ -582,16 +546,4 @@ class UserController extends AdminController
];
return json_encode($info, true);
}
public function cleanSubCache($request, $response, $args)
{
$id = $args['id'];
$user_path = (BASE_PATH . '/storage/SubscribeCache/' . $id . '/');
Tools::delDirAndFile($user_path);
$res['ret'] = 1;
$res['msg'] = '清理成功';
return $this->echoJson($response, $res);
}
}

@ -30,6 +30,7 @@ class AdminController extends UserController
return $this->view()->assign('nodes', $nodes)->display('admin/node.tpl');
}
public function editConfig($request, $response, $args)
{
return (new ChenPay())->editConfig();

@ -0,0 +1,162 @@
<?php
namespace App\Controllers;
use App\Models\Node;
use App\Models\User;
use App\Services\Factory;
use App\Services\Config;
use App\Utils\Tools;
use App\Utils\Hash;
use App\Utils\Helper;
/**
* ApiController
*/
class ApiController extends BaseController
{
public function index()
{
}
public function token($request, $response, $args)
{
$accessToken = $id = $args['token'];
$storage = Factory::createTokenStorage();
$token = $storage->get($accessToken);
if ($token == null) {
$res['ret'] = 0;
$res['msg'] = 'token is null';
return $this->echoJson($response, $res);
}
$res['ret'] = 1;
$res['msg'] = 'ok';
$res['data'] = $token;
return $this->echoJson($response, $res);
}
public function newToken($request, $response, $args)
{
// $data = $request->post('sdf');
$email = $request->getParam('email');
$email = strtolower($email);
$passwd = $request->getParam('passwd');
// Handle Login
$user = User::where('email', '=', $email)->first();
if ($user == null) {
$res['ret'] = 0;
$res['msg'] = '401 邮箱或者密码错误';
return $this->echoJson($response, $res);
}
if (!Hash::checkPassword($user->pass, $passwd)) {
$res['ret'] = 0;
$res['msg'] = '402 邮箱或者密码错误';
return $this->echoJson($response, $res);
}
$tokenStr = Tools::genToken();
$storage = Factory::createTokenStorage();
$expireTime = time() + 3600 * 24 * 7;
if ($storage->store($tokenStr, $user, $expireTime)) {
$res['ret'] = 1;
$res['msg'] = 'ok';
$res['data']['token'] = $tokenStr;
$res['data']['user_id'] = $user->id;
return $this->echoJson($response, $res);
}
$res['ret'] = 0;
$res['msg'] = 'system error';
return $this->echoJson($response, $res);
}
public function node($request, $response, $args)
{
$accessToken = Helper::getParam($request, 'access_token');
$storage = Factory::createTokenStorage();
$token = $storage->get($accessToken);
$user = User::find($token->userId);
$nodes = Node::where('sort', 0)->where('type', '1')->where(
static function ($query) use ($user) {
$query->where('node_group', '=', $user->node_group)
->orWhere('node_group', '=', 0);
}
)->orderBy('name')->get();
$mu_nodes = Node::where('sort', 9)->where('node_class', '<=', $user->class)->where('type', '1')->where(
static function ($query) use ($user) {
$query->where('node_group', '=', $user->node_group)
->orWhere('node_group', '=', 0);
}
)->orderBy('name')->get();
$temparray = array();
foreach ($nodes as $node) {
if ($node->mu_only == 0) {
$temparray[] = array('remarks' => $node->name,
'server' => $node->server,
'server_port' => $user->port,
'method' => $node->custom_method == 1 ? $user->method : $node->method,
'obfs' => str_replace('_compatible', '', (($node->custom_rss == 1 && !($user->obfs == 'plain' && $user->protocol == 'origin')) ? $user->obfs : 'plain')),
'obfsparam' => ($node->custom_rss == 1 && !($user->obfs == 'plain' && $user->protocol == 'origin')) ? $user->obfs_param : '',
'remarks_base64' => base64_encode($node->name),
'password' => $user->passwd,
'tcp_over_udp' => false,
'udp_over_tcp' => false,
'group' => Config::get('appName'),
'protocol' => str_replace('_compatible', '', (($node->custom_rss == 1 && !($user->obfs == 'plain' && $user->protocol == 'origin')) ? $user->protocol : 'origin')),
'obfs_udp' => false,
'enable' => true);
}
if ($node->custom_rss == 1) {
foreach ($mu_nodes as $mu_node) {
$mu_user = User::where('port', '=', $mu_node->server)->first();
$mu_user->obfs_param = $user->getMuMd5();
$temparray[] = array('remarks' => $node->name . '- ' . $mu_node->server . ' 单端口',
'server' => $node->server,
'server_port' => $mu_user->port,
'method' => $mu_user->method,
'group' => Config::get('appName'),
'obfs' => str_replace('_compatible', '', (($node->custom_rss == 1 && !($mu_user->obfs == 'plain' && $mu_user->protocol == 'origin')) ? $mu_user->obfs : 'plain')),
'obfsparam' => ($node->custom_rss == 1 && !($mu_user->obfs == 'plain' && $mu_user->protocol == 'origin')) ? $mu_user->obfs_param : '',
'remarks_base64' => base64_encode($node->name . '- ' . $mu_node->server . ' 单端口'),
'password' => $mu_user->passwd,
'tcp_over_udp' => false,
'udp_over_tcp' => false,
'protocol' => str_replace('_compatible', '', (($node->custom_rss == 1 && !($mu_user->obfs == 'plain' && $mu_user->protocol == 'origin')) ? $mu_user->protocol : 'origin')),
'obfs_udp' => false,
'enable' => true);
}
}
}
$res['ret'] = 1;
$res['msg'] = 'ok';
$res['data'] = $temparray;
return $this->echoJson($response, $res);
}
public function userInfo($request, $response, $args)
{
$id = $args['id'];
$accessToken = Helper::getParam($request, 'access_token');
$storage = Factory::createTokenStorage();
$token = $storage->get($accessToken);
if ($id != $token->userId) {
$res['ret'] = 0;
$res['msg'] = 'access denied';
return $this->echoJson($response, $res);
}
$user = User::find($token->userId);
$user->pass = null;
$data = $user;
$res['ret'] = 1;
$res['msg'] = 'ok';
$res['data'] = $data;
return $this->echoJson($response, $res);
}
}

@ -29,7 +29,7 @@ class AuthController extends BaseController
{
$GtSdk = null;
$recaptcha_sitekey = null;
if (Config::get('enable_login_captcha') === true) {
if (Config::get('enable_login_captcha') === 'true') {
switch (Config::get('captcha_provider')) {
case 'recaptcha':
$recaptcha_sitekey = Config::get('recaptcha_sitekey');
@ -41,7 +41,7 @@ class AuthController extends BaseController
}
}
if (Config::get('new_telegram_enable') === true) {
if (Config::get('enable_telegram') === 'true') {
$login_text = TelegramSessionManager::add_login_session();
$login = explode('|', $login_text);
$login_token = $login[0];
@ -55,7 +55,7 @@ class AuthController extends BaseController
->assign('geetest_html', $GtSdk)
->assign('login_token', $login_token)
->assign('login_number', $login_number)
->assign('telegram_bot', Config::get('new_telegram_username'))
->assign('telegram_bot', Config::get('telegram_bot'))
->assign('base_url', Config::get('baseUrl'))
->assign('recaptcha_sitekey', $recaptcha_sitekey)
->display('auth/login.tpl');
@ -93,7 +93,7 @@ class AuthController extends BaseController
$code = $request->getParam('code');
$rememberMe = $request->getParam('remember_me');
if (Config::get('enable_login_captcha') === true) {
if (Config::get('enable_login_captcha') === 'true') {
switch (Config::get('captcha_provider')) {
case 'recaptcha':
$recaptcha = $request->getParam('recaptcha');
@ -218,7 +218,7 @@ class AuthController extends BaseController
$GtSdk = null;
$recaptcha_sitekey = null;
if (Config::get('enable_reg_captcha') === true) {
if (Config::get('enable_reg_captcha') === 'true') {
switch (Config::get('captcha_provider')) {
case 'recaptcha':
$recaptcha_sitekey = Config::get('recaptcha_sitekey');
@ -242,7 +242,7 @@ class AuthController extends BaseController
public function sendVerify($request, $response, $next)
{
if (Config::get('enable_email_verify') == true) {
if (Config::get('enable_email_verify') === 'true') {
$email = $request->getParam('email');
$email = trim($email);
@ -335,7 +335,7 @@ class AuthController extends BaseController
// check code
if (Config::get('enable_reg_captcha') === true) {
if (Config::get('enable_reg_captcha') === 'true') {
switch (Config::get('captcha_provider')) {
case 'recaptcha':
$recaptcha = $request->getParam('recaptcha');
@ -402,7 +402,7 @@ class AuthController extends BaseController
return $response->getBody()->write(json_encode($res));
}
if (Config::get('enable_email_verify') == true) {
if (Config::get('enable_email_verify') === 'true') {
$mailcount = EmailVerify::where('email', '=', $email)->where('code', '=', $emailcode)->where('expire_in', '>', time())->first();
if ($mailcount == null) {
$res['ret'] = 0;
@ -437,7 +437,7 @@ class AuthController extends BaseController
$res['msg'] = '此联络方式已注册';
return $response->getBody()->write(json_encode($res));
}
if (Config::get('enable_email_verify') == true) {
if (Config::get('enable_email_verify') === 'true') {
EmailVerify::where('email', '=', $email)->delete();
}
// do reg user
@ -530,7 +530,7 @@ class AuthController extends BaseController
return $response->getBody()->write(json_encode($res));
}
if (Config::get('new_telegram_enable') === true) {
if (Config::get('enable_telegram') === 'true') {
$ret = TelegramSessionManager::check_login_session($token, $number);
$res['ret'] = $ret;
return $response->getBody()->write(json_encode($res));
@ -542,7 +542,7 @@ class AuthController extends BaseController
public function telegram_oauth($request, $response, $args)
{
if (Config::get('new_telegram_enable') === true) {
if (Config::get('enable_telegram') === 'true') {
$auth_data = $request->getQueryParams();
if ($this->telegram_oauth_check($auth_data) === true) { // Looks good, proceed.
$telegram_id = $auth_data['id'];
@ -565,7 +565,7 @@ class AuthController extends BaseController
private function telegram_oauth_check($auth_data)
{
$check_hash = $auth_data['hash'];
$bot_token = Config::get('new_telegram_token');
$bot_token = Config::get('telegram_token');
unset($auth_data['hash']);
$data_check_arr = [];
foreach ($auth_data as $key => $value) {

@ -5,8 +5,6 @@ namespace App\Controllers;
use App\Models\User;
use App\Services\View;
use App\Services\Auth;
use Slim\Http\Response;
use Psr\Http\Message\ResponseInterface;
use Smarty;
/**
@ -42,18 +40,13 @@ class BaseController
{
return $this->view;
}
// TODO: remove
/**
* Output JSON
*
* @param Response $response
* @param array|object $resource
*
* @return ResponseInterface
* @param $response
* @param $res
* @return mixed
*/
public function echoJson(Response $response, $resource)
public function echoJson($response, $res)
{
return $response->withJson($resource);
return $response->getBody()->write(json_encode($res));
}
}

@ -0,0 +1,70 @@
<?php
/**
* Created by PhpStorm.
* User: kaguya
* Date: 2018/06/30
* Time: 21:40
*/
namespace App\Controllers\Client;
use App\Controllers\BaseController;
use App\Controllers\LinkController;
use App\Models\Ann;
use App\Models\User;
use App\Services\Auth;
use App\Services\Config;
use App\Services\Factory;
use App\Utils\Helper;
class ClientApiController extends BaseController
{
public function GetAnnouncement($request, $response, $args)
{
$accessToken = Helper::getParam($request, 'access_token');
$storage = Factory::createTokenStorage();
$token = $storage->get($accessToken);
$user = User::find($token->userId);
$Anns = Ann::orderBy('date', 'desc')->first();
$res['ret'] = 1;
$res['msg'] = 'ok';
$res['data'] = $Anns;
return $this->echoJson($response, $res);
}
public function Redirect($request, $response, $args)
{
$user = Auth::getUser();
$url = $request->getQueryParams()['target'];
if (!$user->isLogin) {
$accessToken = Helper::getParam($request, 'access_token');
$storage = Factory::createTokenStorage();
$token = $storage->get($accessToken);
if ($token == null) {
$res['ret'] = 0;
$res['msg'] = 'token is null';
return $this->echoJson($response, $res);
}
$user = User::find($token->userId);
$time = 3600 * 24;
Auth::login($user->id, $time);
}
return $response->withRedirect($url);
}
public function GetSubLink($request, $response, $args)
{
$accessToken = Helper::getParam($request, 'access_token');
$mu = Helper::getParam($request, 'mu');
$storage = Factory::createTokenStorage();
$token = $storage->get($accessToken);
$user = User::find($token->userId);
$ssr_sub_token = LinkController::GenerateSSRSubCode($user->id, 0);
$res['ret'] = 1;
$res['msg'] = 'ok';
$res['data'] = Config::get('subUrl') . $ssr_sub_token;
if ($mu != '') $res['data'] = $res['data'].'?mu=' . $mu;
return $this->echoJson($response, $res);
}
}

@ -1,575 +0,0 @@
<?php
/**
* 部分应用自定义配置
*
* PHP version 7.2+
*
* @category GeekQu
* @package App/Controllers/ConfController
* @author GeekQu <iloves@live.com>
* @license MIT https://github.com/GeekQu/ss-panel-v3-mod_Uim/blob/dev/LICENSE
* @link https://github.com/GeekQu
*/
namespace App\Controllers;
use App\Models\User;
use App\Services\Config;
use App\Utils\ConfRender;
use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Yaml\Exception\ParseException;
/**
* ConfController
*
* @category GeekQu
* @package App/Controllers/ConfController
* @author GeekQu <iloves@live.com>
* @license MIT https://github.com/GeekQu/ss-panel-v3-mod_Uim/blob/dev/LICENSE
* @link https://github.com/GeekQu
*/
class ConfController extends BaseController
{
/**
* YAML 转数组
*
* @param string $Content YAML 字符串
*
* @return string
*/
public static function YAML2Array($Content)
{
try {
return Yaml::parse($Content);
} catch (ParseException $exception) {
return printf('无法解析 YAML 字符串: %s', $exception->getMessage());
}
}
/**
* 从远端自定义配置文件生成 Surge 托管配置
*
* @param object $User 用户
* @param string $AllProxys Surge 格式的全部节点
* @param array $Nodes 全部节点数组
* @param string $SourceContent 远程配置内容
*
* @return string
*/
public static function getSurgeConfs($User, $AllProxys, $Nodes, $Configs, $local = false)
{
$General = self::getSurgeConfGeneral($Configs['General']);
$Proxys = (isset($Configs['Proxy'])
? self::getSurgeConfProxy($Configs['Proxy'])
: '');
if (isset($Configs['Proxy Group'])) {
$Configs['ProxyGroup'] = $Configs['Proxy Group'];
}
$ProxyGroups = self::getSurgeConfProxyGroup(
$Nodes,
$Configs['ProxyGroup']
);
$ProxyGroup = self::getSurgeProxyGroup2String($ProxyGroups);
$Rule = self::getSurgeConfRule($Configs['Rule'], $local);
$Conf = '#!MANAGED-CONFIG '
. Config::get('baseUrl') . $_SERVER['REQUEST_URI'] .
"\n\n#---------------------------------------------------#" .
"\n## 上次更新于:" . date("Y-m-d h:i:s") .
"\n#---------------------------------------------------#" .
"\n\n[General]"
. $General .
"\n\n[Proxy]\n"
. $AllProxys . $Proxys .
"\n\n[Proxy Group]"
. $ProxyGroup .
"\n\n[Rule]\n"
. $Rule;
return $Conf;
}
/**
* Surge 配置中的 General
*
* @param array $General Surge General 定义
*
* @return string
*/
public static function getSurgeConfGeneral($General)
{
$return = '';
if (count($General) != 0) {
foreach ($General as $key => $value) {
$return .= "\n$key = $value";
}
}
return $return;
}
/**
* Surge 配置中的 Proxy
*
* @param array $Proxys 自定义配置中的额外 Proxy
*
* @return string
*/
public static function getSurgeConfProxy($Proxys)
{
$return = '';
if (count($Proxys) != 0) {
foreach ($Proxys as $value) {
if (!preg_match('/(\[General|Replica|Proxy|Proxy\sGroup|Rule|Host|URL\sRewrite|Header\sRewrite|MITM|Script\])/', $value)) {
$return .= "\n$value";
}
}
}
return $return;
}
/**
* Surge 配置中的 ProxyGroup
*
* @param array $Nodes 全部节点数组
* @param array $ProxyGroups Surge 策略组定义
*
* @return array
*/
public static function getSurgeConfProxyGroup($Nodes, $ProxyGroups)
{
$return = [];
foreach ($ProxyGroups as $ProxyGroup) {
if (in_array($ProxyGroup['type'], ['select', 'url-test', 'fallback'])) {
$proxies = [];
if (
isset($ProxyGroup['content']['left-proxies'])
&& count($ProxyGroup['content']['left-proxies']) != 0
) {
$proxies = $ProxyGroup['content']['left-proxies'];
}
foreach ($Nodes as $item) {
$item = self::getMatchProxy($item, $ProxyGroup);
if ($item !== null && !in_array($item['remark'], $proxies)) {
$proxies[] = $item['remark'];
}
}
if (isset($ProxyGroup['content']['right-proxies'])) {
$proxies = array_merge($proxies, $ProxyGroup['content']['right-proxies']);
}
$ProxyGroup['proxies'] = $proxies;
}
$return[] = $ProxyGroup;
}
return $return;
}
/**
* 获取匹配的节点
*
* @param array $Proxy 节点
* @param array $Rule 匹配规则
*
* @return array
*/
public static function getMatchProxy($Proxy, $Rule)
{
$return = null;
switch (true) {
case (isset($Rule['content']['class'])):
if ($Proxy['class'] == $Rule['content']['class']) {
if (isset($Rule['content']['regex'])) {
if (preg_match('/' . $Rule['content']['regex'] . '/i', $Proxy['remark'])) {
$return = $Proxy;
}
} else {
$return = $Proxy;
}
}
break;
case (isset($Rule['content']['noclass'])):
if ($Proxy['class'] != $Rule['content']['noclass']) {
if (isset($Rule['content']['regex'])) {
if (preg_match('/' . $Rule['content']['regex'] . '/i', $Proxy['remark'])) {
$return = $Proxy;
}
} else {
$return = $Proxy;
}
}
break;
case (!isset($Rule['content']['class'])
&& !isset($Rule['content']['noclass'])
&& isset($Rule['content']['regex'])
&& preg_match('/' . $Rule['content']['regex'] . '/i', $Proxy['remark'])
):
$return = $Proxy;
break;
}
return $return;
}
/**
* Surge ProxyGroup 去除无用策略组
*
* @param array $ProxyGroups 策略组
* @param array $checks 要检查的策略组名
*
* @return array
*/
public static function fixSurgeProxyGroup($ProxyGroups, $checks)
{
if (count($checks) == 0) {
return $ProxyGroups;
}
$clean_names = [];
$newProxyGroups = [];
foreach ($ProxyGroups as $ProxyGroup) {
if (in_array($ProxyGroup['name'], $checks) && count($ProxyGroup['proxies']) == 0) {
$clean_names[] = $ProxyGroup['name'];
continue;
}
$newProxyGroups[] = $ProxyGroup;
}
if (count($clean_names) >= 1) {
$ProxyGroups = $newProxyGroups;
$newProxyGroups = [];
foreach ($ProxyGroups as $ProxyGroup) {
if (!in_array($ProxyGroup['name'], $checks) && $ProxyGroup['type'] != 'ssid') {
$newProxies = [];
foreach ($ProxyGroup['proxies'] as $proxie) {
if (!in_array($proxie, $clean_names)) {
$newProxies[] = $proxie;
}
}
$ProxyGroup['proxies'] = $newProxies;
}
$newProxyGroups[] = $ProxyGroup;
}
}
return $newProxyGroups;
}
/**
* Surge ProxyGroup 转字符串
*
* @param array $ProxyGroups Surge 策略组定义
*
* @return string
*/
public static function getSurgeProxyGroup2String($ProxyGroups)
{
$return = '';
foreach ($ProxyGroups as $ProxyGroup) {
$str = '';
if (in_array($ProxyGroup['type'], ['select', 'url-test', 'fallback'])) {
$proxies = implode(', ', $ProxyGroup['proxies']);
if (in_array($ProxyGroup['type'], ['url-test', 'fallback'])) {
$str .= ($ProxyGroup['name']
. ' = '
. $ProxyGroup['type']
. ', '
. $proxies
. ', url = ' . $ProxyGroup['url']
. ', interval = ' . $ProxyGroup['interval']);
} else {
$str .= ($ProxyGroup['name']
. ' = '
. $ProxyGroup['type']
. ', '
. $proxies);
}
} elseif ($ProxyGroup['type'] == 'ssid') {
$wifi = '';
foreach ($ProxyGroup['content'] as $key => $value) {
$wifi .= ', "' . $key . '" = ' . $value;
}
$cellular = (isset($ProxyGroup['cellular'])
? ', cellular = ' . $ProxyGroup['cellular']
: '');
$str .= ($ProxyGroup['name']
. ' = '
. $ProxyGroup['type']
. ', default = '
. $ProxyGroup['default']
. $cellular
. $wifi);
} else {
$str .= '';
}
$return .= "\n$str";
}
return $return;
}
/**
* Surge 配置中的 Rule
*
* @param array $Rules Surge 规则加载地址
*
* @return string
*/
public static function getSurgeConfRule($Rules, $local)
{
// 加载本地规则文件
if ($local) {
$render = ConfRender::getTemplateRender();
return $render->fetch(trim($Rules['source']));
}
// 加载远程规则文件
$return = '';
if (isset($Rules['source']) && $Rules['source'] != '') {
$sourceURL = trim($Rules['source']);
// 远程规则仅支持 github 以及 gitlab
if (preg_match('/^https:\/\/((gist\.)?github\.com|raw\.githubusercontent\.com|gitlab\.com)/i', $sourceURL)) {
$return = @file_get_contents($sourceURL);
if (!$return) {
$return = ('// 远程规则加载失败'
. PHP_EOL
. 'GEOIP,CN,DIRECT'
. PHP_EOL
. 'FINAL,DIRECT,dns-failed');
}
} else {
$return = ('// 远程规则仅支持 github 以及 gitlab'
. PHP_EOL
. 'GEOIP,CN,DIRECT'
. PHP_EOL
. 'FINAL,DIRECT,dns-failed');
}
}
return $return;
}
/**
* 从远端自定义配置文件生成 Clash 配置
*
* @param object $User 用户
* @param array $AllProxys 全部节点数组
* @param string $SourceContent 远程配置内容
*
* @return string
*/
public static function getClashConfs($User, $AllProxys, $Configs, $local = false)
{
if (isset($Configs['Proxy']) || count($Configs['Proxy']) != 0) {
$tmpProxys = array_merge($AllProxys, $Configs['Proxy']);
} else {
$tmpProxys = $AllProxys;
}
$Proxys = [];
foreach ($tmpProxys as $Proxy) {
unset($Proxy['class']);
$Proxys[] = $Proxy;
}
$tmp = self::getClashConfGeneral($Configs['General']);
$tmp['Proxy'] = $Proxys;
if (isset($Configs['ProxyGroup'])) {
$tmp['Proxy Group'] = self::getClashConfProxyGroup(
$AllProxys,
$Configs['ProxyGroup']
);
} else {
$tmp['Proxy Group'] = self::getClashConfProxyGroup(
$AllProxys,
$Configs['Proxy Group']
);
}
$Conf = '#!MANAGED-CONFIG '
. Config::get('baseUrl') . $_SERVER['REQUEST_URI'] .
"\n\n#---------------------------------------------------#" .
"\n## 上次更新于:" . date("Y-m-d h:i:s") .
"\n#---------------------------------------------------#" .
"\n\n"
. Yaml::dump($tmp, 4, 2) .
"\n\n"
. self::getClashConfRule($Configs['Rule'], $local);
return $Conf;
}
/**
* Clash 配置中的 General
*
* @param array $General Clash General 定义
*
* @return array
*/
public static function getClashConfGeneral($General)
{
if (count($General) != 0) {
foreach ($General as $key) {
if (in_array(
$key,
[
'Proxy',
'Proxy Group',
'Rule'
]
)) {
unset($key);
}
}
}
return $General;
}
/**
* Clash 配置中的 ProxyGroup
*
* @param array $Nodes 全部节点数组
* @param array $ProxyGroups Clash 策略组定义
*
* @return array
*/
public static function getClashConfProxyGroup($Nodes, $ProxyGroups)
{
$return = [];
foreach ($ProxyGroups as $ProxyGroup) {
$tmp = [];
if (in_array($ProxyGroup['type'], ['select', 'url-test', 'fallback', 'load-balance'])) {
$proxies = [];
if (
isset($ProxyGroup['content']['left-proxies'])
&& count($ProxyGroup['content']['left-proxies']) != 0
) {
$proxies = $ProxyGroup['content']['left-proxies'];
}
foreach ($Nodes as $item) {
$item['remark'] = $item['name'];
$item = self::getMatchProxy($item, $ProxyGroup);
if ($item !== null && !in_array($item['name'], $proxies)) {
$proxies[] = $item['name'];
}
}
if (isset($ProxyGroup['content']['right-proxies'])) {
$proxies = array_merge($proxies, $ProxyGroup['content']['right-proxies']);
}
$tmp = [
'name' => $ProxyGroup['name'],
'type' => $ProxyGroup['type'],
'proxies' => $proxies
];
if ($ProxyGroup['type'] != 'select') {
$tmp['url'] = $ProxyGroup['url'];
$tmp['interval'] = $ProxyGroup['interval'];
}
$return[] = $tmp;
}
}
return $return;
}
/**
* Clash 配置中的 Rule
*
* @param array $Rules Clash 规则加载地址
*
* @return string
*/
public static function getClashConfRule($Rules, $local)
{
// 加载本地规则文件
if ($local) {
$render = ConfRender::getTemplateRender();
return $render->fetch(trim($Rules['source']));
}
// 加载远程规则文件
$return = ('Rule:' . PHP_EOL);
if (isset($Rules['source']) && $Rules['source'] != '') {
$sourceURL = trim($Rules['source']);
// 远程规则仅支持 github 以及 gitlab
if (preg_match('/^https:\/\/((gist\.)?github\.com|raw\.githubusercontent\.com|gitlab\.com)/i', $sourceURL)) {
$sourceContent = @file_get_contents($sourceURL);
if (!$sourceContent) {
$return .= ('// 远程规则加载失败'
. PHP_EOL
. 'GEOIP,CN,DIRECT'
. PHP_EOL
. 'MATCH,DIRECT');
} else {
try {
$sourceRule = Yaml::parse($sourceContent);
} catch (ParseException $exception) {
$sourceRule['error'] = printf('无法解析 YAML 字符串: %s', $exception->getMessage());
}
if (isset($sourceRule['error']) || !isset($sourceRule['Rule'])) {
$return .= $sourceContent;
} else {
$return .= Yaml::dump($sourceRule['Rule'], 4, 2);
}
}
} else {
$return .= ('// 远程规则仅支持 github 以及 gitlab'
. PHP_EOL
. 'GEOIP,CN,DIRECT'
. PHP_EOL
. 'MATCH,DIRECT');
}
}
return $return;
}
/**
* Clash ProxyGroup 去除无用策略组
*
* @param array $ProxyGroups 策略组
* @param array $checks 要检查的策略组名
*
* @return array
*/
public static function fixClashProxyGroup($ProxyGroups, $checks)
{
if (count($checks) == 0) {
return $ProxyGroups;
}
$clean_names = [];
$newProxyGroups = [];
foreach ($ProxyGroups as $ProxyGroup) {
if (in_array($ProxyGroup['name'], $checks) && count($ProxyGroup['proxies']) == 0) {
$clean_names[] = $ProxyGroup['name'];
continue;
}
$newProxyGroups[] = $ProxyGroup;
}
if (count($clean_names) >= 1) {
$ProxyGroups = $newProxyGroups;
$newProxyGroups = [];
foreach ($ProxyGroups as $ProxyGroup) {
if (!in_array($ProxyGroup['name'], $checks)) {
$newProxies = [];
foreach ($ProxyGroup['proxies'] as $proxie) {
if (!in_array($proxie, $clean_names)) {
$newProxies[] = $proxie;
}
}
$ProxyGroup['proxies'] = $newProxies;
}
$newProxyGroups[] = $ProxyGroup;
}
}
return $newProxyGroups;
}
/**
* Clash ProxyGroup 转字符串
*
* @param array $ProxyGroups ProxyGroup
*
* @return string
*/
public static function getClashProxyGroup2String($ProxyGroups)
{
return Yaml::dump($ProxyGroups, 4, 2);
}
// 待续 Quantumult...
}

@ -3,14 +3,11 @@
namespace App\Controllers;
use App\Models\InviteCode;
use App\Services\Auth;
use App\Services\Config;
use App\Utils\AliPay;
use App\Utils\TelegramSessionManager;
use App\Utils\TelegramProcess;
use App\Utils\Geetest;
use App\Utils\Tools;
use App\Utils\Telegram\Process;
use Slim\Http\{Request, Response};
use Psr\Http\Message\ResponseInterface;
@ -40,7 +37,7 @@ class HomeController extends BaseController
}
}
if (Config::get('new_telegram_enable') == true) {
if (Config::get('enable_telegram') == 'true') {
$login_text = TelegramSessionManager::add_login_session();
$login = explode('|', $login_text);
$login_token = $login[0];
@ -50,20 +47,16 @@ class HomeController extends BaseController
$login_number = '';
}
if (Config::get('newIndex') === false && Config::get('theme') == 'material') {
return $response->write($this->view()->fetch('indexold.tpl'));
} else {
return $response->write($this->view()
->assign('geetest_html', $GtSdk)
->assign('login_token', $login_token)
->assign('login_number', $login_number)
->assign('telegram_bot', Config::get('new_telegram_username'))
->assign('enable_logincaptcha', Config::get('enable_login_captcha'))
->assign('enable_regcaptcha', Config::get('enable_reg_captcha'))
->assign('base_url', Config::get('baseUrl'))
->assign('recaptcha_sitekey', $recaptcha_sitekey)
->fetch('index.tpl'));
}
return $response->write($this->view()
->assign('geetest_html', $GtSdk)
->assign('login_token', $login_token)
->assign('login_number', $login_number)
->assign('telegram_bot', Config::get('telegram_bot'))
->assign('enable_logincaptcha', Config::get('enable_login_captcha'))
->assign('enable_regcaptcha', Config::get('enable_reg_captcha'))
->assign('base_url', Config::get('baseUrl'))
->assign('recaptcha_sitekey', $recaptcha_sitekey)
->fetch('index.tpl'));
}
/**
@ -124,23 +117,6 @@ class HomeController extends BaseController
return $response->write($result);
}
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function NewTelegram($request, $response, $args): ResponseInterface
{
$token = $request->getQueryParam('token');
if ($token == Config::get('new_telegram_request_token')) {
Process::index();
$result = '1';
} else {
$result = '0';
}
return $response->write($result);
}
/**
* @param Request $request
* @param Response $response
@ -204,128 +180,4 @@ class HomeController extends BaseController
}
return $response->write(json_encode(['res' => AliPay::setOrder($sn, $url)]));
}
public function getDocCenter($request, $response, $args)
{
$user = Auth::getUser();
if (!$user->isLogin && Config::get('enable_documents') === false) {
$newResponse = $response->withStatus(302)->withHeader('Location', '/');
return $newResponse;
}
$basePath = Config::get('remote_documents') === true ? Config::get('documents_source') : '/docs/GeekQu';
return $this->view()
->assign('appName', Config::get('documents_name'))
->assign('basePath', $basePath)
->fetch('doc/index.tpl');
}
public function getSubLink($request, $response, $args)
{
$user = Auth::getUser();
if (!$user->isLogin) {
return $msg = '!> ₍₍ ◝(・ω・)◟ ⁾⁾ 您没有登录噢,[点击此处登录](/auth/login \':ignore target=_blank\') 之后再刷新就阔以了啦';
} else {
$subInfo = LinkController::getSubinfo($user, 0);
switch ($request->getParam('type')) {
case 'ssr':
$msg = [
'**订阅链接:**',
'```',
$subInfo['ssr'] . '&extend=1',
'```'
];
break;
case 'v2ray':
$msg = [
'**订阅链接:**',
'```',
$subInfo['v2ray'] . '&extend=1',
'```'
];
break;
case 'ssd':
$msg = [
'**订阅链接:**',
'```',
$subInfo['ssd'],
'```'
];
break;
case 'clash':
$msg = [
'**订阅链接:**[[点击下载配置]](' . $subInfo['clash'] . ')',
'```',
$subInfo['clash'],
'```'
];
break;
case 'surge':
$msg = [
'**Surge Version 2.x 托管配置链接:**[[iOS 点击此处一键添加]](surge:///install-config?url=' . urlencode($subInfo['surge2']) . ')',
'```',
$subInfo['surge2'],
'```',
'**Surge Version 3.x 托管配置链接:**[[iOS 点击此处一键添加]](surge3:///install-config?url=' . urlencode($subInfo['surge3']) . ')',
'```',
$subInfo['surge3'],
'```'
];
break;
case 'kitsunebi':
$msg = [
'**包含 ss、v2ray 的合并订阅链接:**',
'```',
$subInfo['kitsunebi'] . '&extend=1',
'```'
];
break;
case 'surfboard':
$msg = [
'**托管配置链接:**',
'```',
$subInfo['surfboard'],
'```'
];
break;
case 'quantumult_sub':
$msg = [
'**ssr 订阅链接:**[[iOS 点击此处一键添加]](quantumult://configuration?server=' . Tools::base64_url_encode($subInfo['ssr']) . ')',
'```',
$subInfo['ssr'],
'```',
'**V2ray 订阅链接:**[[iOS 点击此处一键添加]](quantumult://configuration?server=' . Tools::base64_url_encode($subInfo['quantumult_v2']) . ')',
'```',
$subInfo['quantumult_v2'],
'```'
];
break;
case 'quantumult_conf':
$msg = [
'**导入 ss、ssr、v2ray 以及分流规则的配置链接:**',
'```',
$subInfo['quantumult_sub'],
'```',
'**导入类似 Surge、Clash 使用自定义策略组的配置链接:**',
'```',
$subInfo['quantumult_conf'],
'```'
];
break;
case 'shadowrocket':
$msg = [
'**包含 ss、ssr、v2ray 的合并订阅链接:**[[iOS 点击此处一键添加]](sub://' . base64_encode($subInfo['shadowrocket']) . ')',
'```',
$subInfo['shadowrocket'],
'```'
];
break;
default:
$msg = [
'获取失败了呢...,请联系管理员。'
];
break;
}
}
return implode(PHP_EOL, $msg);
}
}

File diff suppressed because it is too large Load Diff

@ -9,10 +9,7 @@ use App\Models\UnblockIp;
use App\Models\Speedtest;
use App\Models\Node;
use App\Models\Auto;
use App\Models\User;
use App\Controllers\BaseController;
use App\Utils\Tools;
use App\Services\Config;
class FuncController extends BaseController
{
@ -61,57 +58,18 @@ class FuncController extends BaseController
if ($rules[0]['dist_node_id'] == -1) {
$server = null;
}
if (Config::get('relay_port_migration') === true) {
foreach ($rules as $rule) {
$dis = $this->get_dis_node_info($rule['dist_node_id']);
if ($dis != null) {
$rule['source_node_sort'] = $node->sort;
$rule['dist_node_sort'] = $dis->sort;
if (in_array($dis->sort, [0, 10])) {
$dis_server = explode(';', $dis->server);
$rule['dist_node_server'] = $dis_server[0];
} else {
$rule['dist_node_server'] = $dis->server;
}
if (in_array($dis->sort, [0, 10]) && strpos($dis->server, ';') !== false && $dis->mu_only != -1) {
$muPort = Tools::get_MuOutPortArray($dis->server);
$user = User::where('port', '=', $rule['port'])->first();
if ($user != null) {
if ($user->is_multi_user != 0) {
if ($muPort['type'] == 0) {
if (in_array($rule['port'], array_keys($muPort['port']))) {
$rule['port'] = $muPort['port'][$rule['port']];
}
} else {
$rule['port'] = ($rule['port'] + $muPort['type']);
}
}
}
}
} else {
$rule['source_node_sort'] = $node->sort;
$rule['dist_node_sort'] = null;
$rule['dist_node_server'] = null;
}
}
} else {
foreach ($rules as $rule) {
$dis = $this->get_dis_node_info($rule['dist_node_id']);
if ($dis != null) {
$rule['source_node_sort'] = $node->sort;
$rule['dist_node_sort'] = $dis->sort;
$rule['dist_node_server'] = $dis->server;
} else {
$rule['source_node_sort'] = $node->sort;
$rule['dist_node_sort'] = null;
$rule['dist_node_server'] = null;
}
foreach ($rules as $rule) {
$dis = $this->get_dis_node_info($rule['dist_node_id']);
if ($dis != null) {
$rule['source_node_sort'] = $node->sort;
$rule['dist_node_sort'] = $dis->sort;
$rule['dist_node_server'] = $dis->server;
} else {
$rule['source_node_sort'] = $node->sort;
$rule['dist_node_sort'] = null;
$rule['dist_node_server'] = null;
}
}
$res = [
'ret' => 1,
'data' => $rules,

@ -52,12 +52,6 @@ class NodeController extends BaseController
];
return $this->echoJson($response, $res);
}
if (in_array($node->sort, [0, 10])) {
$node_explode = explode(';', $node->server);
$node_server = $node_explode[0];
} else {
$node_server = $node->server;
}
$res = [
'ret' => 1,
'data' => [
@ -67,7 +61,7 @@ class NodeController extends BaseController
'traffic_rate' => $node->traffic_rate,
'mu_only' => $node->mu_only,
'sort' => $node->sort,
'server' => $node_server,
'server' => $node->server,
'type' => 'ss-panel-v3-mod_Uim'
],
];
@ -80,8 +74,7 @@ class NodeController extends BaseController
static function ($query) {
$query->where('sort', '=', 0)
->orWhere('sort', '=', 10)
->orWhere('sort', '=', 12)
->orWhere('sort', '=', 13);
->orWhere('sort', '=', 12);
}
)->get();
$res = [

@ -8,11 +8,8 @@ use App\Models\User;
use App\Models\NodeOnlineLog;
use App\Models\Ip;
use App\Models\DetectLog;
use App\Models\DetectBanLog;
use App\Controllers\BaseController;
use App\Services\Config;
use App\Utils\Tools;
use App\Utils\URL;
class UserController extends BaseController
{
@ -38,123 +35,50 @@ class UserController extends BaseController
$node->node_heartbeat = time();
$node->save();
// 节点流量耗尽则返回 null
if (($node->node_bandwidth_limit != 0) && $node->node_bandwidth_limit < $node->node_bandwidth) {
$users = null;
$res = [
'ret' => 1,
'data' => $users
];
return $this->echoJson($response, $res);
}
if (in_array($node->sort, [0, 10]) && $node->mu_only != -1) {
$mu_port_migration = Config::get('mu_port_migration');
} else {
$mu_port_migration = false;
}
/*
* 1. 请不要把管理员作为单端口承载用户
* 2. 请不要把真实用户作为单端口承载用户
*/
$users_raw = User::where(
static function ($query) use ($node, $mu_port_migration) {
if ($mu_port_migration === true) {
$query->where(
static function ($query1) use ($node) {
if ($node->node_group != 0) {
$query1->where('class', '>=', $node->node_class)
->where('node_group', '=', $node->node_group)
->where('is_multi_user', '=', 0)
->where('is_admin', 0);
} else {
$query1->where('class', '>=', $node->node_class)
->where('is_multi_user', '=', 0)
->where('is_admin', 0);
}
}
);
} else {
if ($node->node_group != 0) {
$users_raw = User::where(
static function ($query) use ($node) {
$query->where(
static function ($query1) use ($node) {
if ($node->node_group != 0) {
$query1->where('class', '>=', $node->node_class)
->where('node_group', '=', $node->node_group);
} else {
$query1->where('class', '>=', $node->node_class);
}
$query1->where('class', '>=', $node->node_class)
->where('node_group', '=', $node->node_group);
}
)->orwhere('is_admin', 1);
}
}
)->where('enable', 1)->where("detect_ban", 0)->where('expire_in', '>', date('Y-m-d H:i:s'))->get();
// 单端口承载用户
if ($mu_port_migration === true) {
$mu_users_raw = User::where(
)
->where('enable', 1)->where('expire_in', '>', date('Y-m-d H:i:s'))->get();
} else {
$users_raw = User::where(
static function ($query) use ($node) {
$query->where(
static function ($query1) use ($node) {
if ($node->node_group != 0) {
$query1->where('class', '>=', $node->node_class)
->where('node_group', '=', $node->node_group)
->where('is_multi_user', '>', 0);
} else {
$query1->where('class', '>=', $node->node_class)
->where('is_multi_user', '>', 0);
}
$query1->where('class', '>=', $node->node_class);
}
)->orwhere('is_admin', 1);
}
)->where('enable', 1)->where("detect_ban", 0)->where('expire_in', '>', date('Y-m-d H:i:s'))->get();
$muPort = Tools::get_MuOutPortArray($node->server);
if ($muPort['type'] == 0) {
foreach ($mu_users_raw as $user_raw) {
if ($user_raw->is_multi_user != 0 && in_array($user_raw->port, array_keys($muPort['port']))) {
$user_raw->port = $muPort['port'][$user_raw->port];
}
$users_raw[] = $user_raw;
}
} else {
foreach ($mu_users_raw as $user_raw) {
if ($user_raw->is_multi_user != 0) {
$user_raw->port = ($user_raw->port + $muPort['type']);
}
$users_raw[] = $user_raw;
}
}
)->where('enable', 1)->where('expire_in', '>', date('Y-m-d H:i:s'))->get();
}
if (($node->node_bandwidth_limit != 0) && $node->node_bandwidth_limit < $node->node_bandwidth) {
$users = null;
$res = [
'ret' => 1,
'data' => $users
];
return $this->echoJson($response, $res);
}
$users = array();
$key_list = array('email', 'method', 'obfs', 'obfs_param', 'protocol', 'protocol_param',
'forbidden_ip', 'forbidden_port', 'node_speedlimit', 'disconnect_ip',
'is_multi_user', 'id', 'port', 'passwd', 'u', 'd');
$users = array();
if (Config::get('keep_connect') === true) {
foreach ($users_raw as $user_raw) {
if ($user_raw->transfer_enable > $user_raw->u + $user_raw->d) {
$user_raw = Tools::keyFilter($user_raw, $key_list);
$user_raw->uuid = $user_raw->getUuid();
$users[] = $user_raw;
} else {
// 流量耗尽用户限速至 1Mbps
$user_raw = Tools::keyFilter($user_raw, $key_list);
$user_raw->uuid = $user_raw->getUuid();
$user_raw->node_speedlimit = 1;
$users[] = $user_raw;
}
}
} else {
foreach ($users_raw as $user_raw) {
if ($user_raw->transfer_enable > $user_raw->u + $user_raw->d) {
$user_raw = Tools::keyFilter($user_raw, $key_list);
$user_raw->uuid = $user_raw->getUuid();
$users[] = $user_raw;
}
foreach ($users_raw as $user_raw) {
if ($user_raw->transfer_enable > $user_raw->u + $user_raw->d) {
$user_raw = Tools::keyFilter($user_raw, $key_list);
$user_raw->uuid = $user_raw->getUuid();
$users[] = $user_raw;
}
}
@ -298,49 +222,18 @@ class UserController extends BaseController
return $this->echoJson($response, $res);
}
if (Config::get('enable_auto_detect_ban') === true) {
$detect_Users = array();
if (count($data) > 0) {
foreach ($data as $log) {
$list_id = $log['list_id'];
$user_id = $log['user_id'];
// log
$detect_log = new DetectLog();
$detect_log->user_id = $user_id;
$detect_log->list_id = $list_id;
$detect_log->node_id = $node_id;
$detect_log->datetime = time();
$detect_log->save();
$User = User::find($user_id);
if ($User == null) {
continue;
}
if (!in_array($user_id, $detect_Users)) {
$detect_Users[] = $user_id;
}
$User->all_detect_number++;
$User->save();
}
}
if (count($detect_Users) > 0) {
self::DetectBan($detect_Users);
}
} else {
if (count($data) > 0) {
foreach ($data as $log) {
$list_id = $log['list_id'];
$user_id = $log['user_id'];
// log
$detect_log = new DetectLog();
$detect_log->user_id = $user_id;
$detect_log->list_id = $list_id;
$detect_log->node_id = $node_id;
$detect_log->datetime = time();
$detect_log->save();
}
if (count($data) > 0) {
foreach ($data as $log) {
$list_id = $log['list_id'];
$user_id = $log['user_id'];
// log
$detect_log = new DetectLog();
$detect_log->user_id = $user_id;
$detect_log->list_id = $list_id;
$detect_log->node_id = $node_id;
$detect_log->datetime = time();
$detect_log->save();
}
}
@ -350,74 +243,4 @@ class UserController extends BaseController
];
return $this->echoJson($response, $res);
}
public function DetectBan($detect_Users)
{
foreach ($detect_Users as $user_id) {
$User = User::find($user_id);
if ($User == null) {
continue;
}
if ($User->detect_ban == 1 || ($User->is_admin && Config::get('auto_detect_ban_allow_admin') === true) || in_array($User->id, Config::get('auto_detect_ban_allow_users'))) {
continue;
}
if (Config::get('auto_detect_ban_type') == 1) {
$last_DetectBanLog = DetectBanLog::where('user_id', $user_id)->orderBy("id", "desc")->first();
$last_all_detect_number = (
$last_DetectBanLog == null
? 0
: (int) $last_DetectBanLog->all_detect_number
);
$detect_number = ($User->all_detect_number - $last_all_detect_number);
if ($detect_number >= Config::get('auto_detect_ban_number')) {
$last_detect_ban_time = $User->last_detect_ban_time;
$end_time = date('Y-m-d H:i:s');
$User->detect_ban = 1;
$User->last_detect_ban_time = $end_time;
$User->save();
$DetectBanLog = new DetectBanLog();
$DetectBanLog->user_name = $User->user_name;
$DetectBanLog->user_id = $User->id;
$DetectBanLog->email = $User->email;
$DetectBanLog->detect_number = $detect_number;
$DetectBanLog->ban_time = Config::get('auto_detect_ban_time');
$DetectBanLog->start_time = strtotime($last_detect_ban_time);
$DetectBanLog->end_time = strtotime($end_time);
$DetectBanLog->all_detect_number = $User->all_detect_number;
$DetectBanLog->save();
}
} else {
$number = $User->all_detect_number;
$tmp = 0;
foreach (Config::get('auto_detect_ban') as $key => $value) {
if ($number >= $key) {
if ($key >= $tmp) {
$tmp = $key;
}
}
}
if ($tmp != 0) {
if (Config::get('auto_detect_ban')[$tmp]['type'] == 'kill') {
$User->kill_user();
} else {
$last_detect_ban_time = $User->last_detect_ban_time;
$end_time = date('Y-m-d H:i:s');
$User->detect_ban = 1;
$User->last_detect_ban_time = $end_time;
$User->save();
$DetectBanLog = new DetectBanLog();
$DetectBanLog->user_name = $User->user_name;
$DetectBanLog->user_id = $User->id;
$DetectBanLog->email = $User->email;
$DetectBanLog->detect_number = $number;
$DetectBanLog->ban_time = Config::get('auto_detect_ban')[$tmp]['time'];
$DetectBanLog->start_time = strtotime('1989-06-04 00:05:00');
$DetectBanLog->end_time = strtotime($end_time);
$DetectBanLog->all_detect_number = $number;
$DetectBanLog->save();
}
}
}
}
}
}

@ -0,0 +1,57 @@
<?php
namespace App\Controllers\Mu;
use App\Controllers\BaseController;
use App\Models\NodeOnlineLog;
use App\Models\NodeInfoLog;
class NodeController extends BaseController
{
public function onlineUserLog($request, $response, $args)
{
$node_id = $args['id'];
$count = $request->getParam('count');
$log = new NodeOnlineLog();
$log->node_id = $node_id;
$log->online_user = $count;
$log->log_time = time();
if (!$log->save()) {
$res = [
'ret' => 0,
'msg' => 'update failed',
];
return $this->echoJson($response, $res);
}
$res = [
'ret' => 1,
'msg' => 'ok',
];
return $this->echoJson($response, $res);
}
public function info($request, $response, $args)
{
$node_id = $args['id'];
$load = $request->getParam('load');
$uptime = $request->getParam('uptime');
$log = new NodeInfoLog();
$log->node_id = $node_id;
$log->load = $load;
$log->uptime = $uptime;
$log->log_time = time();
if (!$log->save()) {
$res = [
'ret' => 0,
'msg' => 'update failed',
];
return $this->echoJson($response, $res);
}
$res = [
'ret' => 1,
'msg' => 'ok',
];
return $this->echoJson($response, $res);
}
}

@ -0,0 +1,122 @@
<?php
namespace App\Controllers\Mu;
use App\Models\Node;
use App\Models\TrafficLog;
use App\Models\User;
use App\Controllers\BaseController;
use App\Utils\Tools;
class UserController extends BaseController
{
// User List
public function index($request, $response, $args)
{
$node = Node::where('node_ip', '=', $_SERVER['REMOTE_ADDR'])->where(
static function ($query) {
$query->where('sort', '=', 0)
->orWhere('sort', '=', 10)->orWhere('sort', '=', 12);
}
)->first();
$node->node_heartbeat = time();
$node->save();
if ($node->node_group != 0) {
$users_raw = User::where(
static function ($query) use ($node) {
$query->where(
static function ($query1) use ($node) {
$query1->where('class', '>=', $node->node_class)
->where('node_group', '=', $node->node_group);
}
)->orwhere('is_admin', 1);
}
)
->where('enable', 1)->where('expire_in', '>', date('Y-m-d H:i:s'))->get();
} else {
$users_raw = User::where(
static function ($query) use ($node) {
$query->where(
static function ($query1) use ($node) {
$query1->where('class', '>=', $node->node_class);
}
)->orwhere('is_admin', 1);
}
)->where('enable', 1)->where('expire_in', '>', date('Y-m-d H:i:s'))->get();
}
if (($node->node_bandwidth_limit != 0) && $node->node_bandwidth_limit < $node->node_bandwidth) {
$users = null;
$res = [
'ret' => 1,
'data' => $users
];
return $this->echoJson($response, $res);
}
$key_list = array('method', 'id', 'port', 'passwd', 'u', 'd', 'enable',
't', 'transfer_enable', 'switch', 'email');
$users_output = array();
foreach ($users_raw as $user_raw) {
if ($user_raw->transfer_enable > $user_raw->u + $user_raw->d) {
$user_raw = Tools::keyFilter($user_raw, $key_list);
$users_output[] = $user_raw;
}
}
$res = [
'ret' => 1,
'msg' => 'ok',
'data' => $users_output
];
return $this->echoJson($response, $res);
}
// Update Traffic
public function addTraffic($request, $response, $args)
{
$id = $args['id'];
$u = $request->getParam('u');
$d = $request->getParam('d');
$nodeId = $request->getParam('node_id');
$node = Node::find($nodeId);
$node->node_bandwidth = $node->node_bandwidth + $d + $u;
$node->save();
$rate = $node->traffic_rate;
$user = User::find($id);
$user->t = time();
$user->u += ($u * $rate);
$user->d += ($d * $rate);
if (!$user->save()) {
$res = [
'ret' => 0,
'msg' => 'update failed',
];
//return $this->echoJson($response, $res);
}
// log
$traffic = new TrafficLog();
$traffic->user_id = $id;
$traffic->u = $u;
$traffic->d = $d;
$traffic->node_id = $nodeId;
$traffic->rate = $rate;
$traffic->traffic = Tools::flowAutoShow(($u + $d) * $rate);
$traffic->log_time = time();
$traffic->save();
$res = [
'ret' => 1,
'msg' => 'ok',
];
return $this->echoJson($response, $res);
}
}

@ -166,7 +166,7 @@ class RelayController extends UserController
foreach ($dist_nodes as $node) {
if ($node->sort == 11 || $node->sort == 12) {
$node_explode = Tools::v2Array($node->server);
$node_explode = Tools::ssv2Array($node->server);
$ports[] = $node_explode['port'];
$node->name = $node->name . ' 如果是V2ray后端 请设置成 ' . $node_explode['port'];
} else {
@ -249,7 +249,7 @@ class RelayController extends UserController
)->where('type', 1)->where('sort', 9)->where('node_class', '<=', $user->class)->first();
$v2ray_port_raw = '';
if ($dist_node->sort == 12 || $dist_node->sort == 11) {
$node_explode = Tools::v2Array($dist_node->server);
$node_explode = Tools::ssv2Array($dist_node->server);
$v2ray_port_raw = $node_explode['port'];
}
if (($port_raw == null && $port != $user->port && $v2ray_port_raw == '') || ($v2ray_port_raw != '' && ($port != $user->port && $port != $v2ray_port_raw))) {
@ -292,8 +292,6 @@ class RelayController extends UserController
return $response->getBody()->write(json_encode($rs));
}
Tools::delSubCache();
$rs['ret'] = 1;
$rs['msg'] = '添加成功';
return $response->getBody()->write(json_encode($rs));
@ -357,7 +355,7 @@ class RelayController extends UserController
}
foreach ($dist_nodes as $node) {
if ($node->sort == 11 || $node->sort == 12) {
$node_explode = Tools::v2Array($node->server);
$node_explode = Tools::ssv2Array($node->server);
$ports[] = $node_explode['port'];
$node->name = $node->name . ' 如果是V2ray后端 请设置成: ' . $node_explode['port'];
} else {
@ -437,7 +435,7 @@ class RelayController extends UserController
)->where('type', 1)->where('sort', 9)->where('node_class', '<=', $user->class)->first();
$v2ray_port_raw = '';
if ($dist_node->sort == 12 || $dist_node->sort == 11) {
$node_explode = Tools::v2Array($dist_node->server);
$node_explode = Tools::ssv2Array($dist_node->server);
$v2ray_port_raw = $node_explode['port'];
}
if (($port_raw == null && $port != $user->port && $v2ray_port_raw == '') || ($v2ray_port_raw != '' && ($port != $user->port && $port != $v2ray_port_raw))) {
@ -479,8 +477,6 @@ class RelayController extends UserController
return $response->getBody()->write(json_encode($rs));
}
Tools::delSubCache();
$rs['ret'] = 1;
$rs['msg'] = '修改成功';
return $response->getBody()->write(json_encode($rs));
@ -502,9 +498,6 @@ class RelayController extends UserController
$rs['msg'] = '删除失败';
return $response->getBody()->write(json_encode($rs));
}
Tools::delSubCache();
$rs['ret'] = 1;
$rs['msg'] = '删除成功';
return $response->getBody()->write(json_encode($rs));

@ -37,7 +37,6 @@ use App\Models\BlockIp;
use App\Models\UnblockIp;
use App\Models\Payback;
use App\Models\Relay;
use App\Models\UserSubscribeLog;
use App\Utils\QQWry;
use App\Utils\GA;
use App\Utils\Geetest;
@ -59,7 +58,7 @@ class UserController extends BaseController
$GtSdk = null;
$recaptcha_sitekey = null;
if (Config::get('enable_checkin_captcha') == true) {
if (Config::get('enable_checkin_captcha') == 'true') {
switch (Config::get('captcha_provider')) {
case 'recaptcha':
$recaptcha_sitekey = Config::get('recaptcha_sitekey');
@ -73,8 +72,8 @@ class UserController extends BaseController
$Ann = Ann::orderBy('date', 'desc')->first();
return $this->view()
->assign('subInfo', LinkController::getSubinfo($this->user, 0))
->assign('ssr_sub_token', $ssr_sub_token)
->assign('display_ios_class', Config::get('display_ios_class'))
->assign('display_ios_topup', Config::get('display_ios_topup'))
@ -113,7 +112,7 @@ class UserController extends BaseController
public function donate($request, $response, $args)
{
if (Config::get('enable_donate') != true) {
if (Config::get('enable_donate') != 'true') {
exit(0);
}
@ -269,7 +268,7 @@ class UserController extends BaseController
$res['ret'] = 1;
$res['msg'] = '充值成功,充值的金额为' . $codeq->number . '元。';
if (Config::get('enable_donate') == true) {
if (Config::get('enable_donate') == 'true') {
if ($this->user->is_hide == 1) {
Telegram::Send('姐姐姐姐,一位不愿透露姓名的大老爷给我们捐了 ' . $codeq->number . ' 元呢~');
} else {
@ -378,8 +377,6 @@ class UserController extends BaseController
$user->money -= $price;
$user->save();
$user->cleanSubCache();
$res['ret'] = 1;
$res['msg'] = $user->port;
return $response->getBody()->write(json_encode($res));
@ -426,8 +423,6 @@ class UserController extends BaseController
$user->money -= $price;
$user->save();
$user->cleanSubCache();
$res['ret'] = 1;
$res['msg'] = '钦定成功';
return $response->getBody()->write(json_encode($res));
@ -506,7 +501,7 @@ class UserController extends BaseController
$sort = $array_node['sort'];
$array_node['online_user'] = 0;
foreach ($onlineLogs as $log) {
if ($log['node_id'] != $node->id) {
continue;
@ -518,12 +513,12 @@ class UserController extends BaseController
}
break;
}
// check node status
// check node status
// 0: new node; -1: offline; 1: online
$node_heartbeat = $node->node_heartbeat + 300;
$array_node['online'] = -1;
if (!in_array($sort, array(0, 7, 8, 10, 11, 12, 13)) || $node_heartbeat == 300) {
if (!in_array($sort, array(0, 7, 8, 10, 11, 12, 13)) || $node_heartbeat == 300 ) {
$array_node['online'] = 0;
} elseif ($node_heartbeat > time()) {
$array_node['online'] = 1;
@ -537,8 +532,8 @@ class UserController extends BaseController
}
}
$array_node['traffic_used'] = (int) Tools::flowToGB($node->node_bandwidth);
$array_node['traffic_limit'] = (int) Tools::flowToGB($node->node_bandwidth_limit);
$array_node['traffic_used'] = (int)Tools::flowToGB($node->node_bandwidth);
$array_node['traffic_limit'] = (int)Tools::flowToGB($node->node_bandwidth_limit);
if ($node->node_speedlimit == 0.0) {
$array_node['bandwidth'] = 0;
} elseif ($node->node_speedlimit >= 1024.00) {
@ -552,14 +547,7 @@ class UserController extends BaseController
$array_nodes[] = $array_node;
}
return $this->view()
->assign('nodes', $array_nodes)
->assign('nodes_muport', $nodes_muport)
->assign('relay_rules', $relay_rules)
->assign('tools', new Tools())
->assign('user', $user)
->registerClass('URL', URL::class)
->display('user/node.tpl');
return $this->view()->assign('nodes', $array_nodes)->assign('nodes_muport', $nodes_muport)->assign('relay_rules', $relay_rules)->assign('tools', new Tools())->assign('user', $user)->registerClass('URL', URL::class)->display('user/node.tpl');
}
@ -576,7 +564,7 @@ class UserController extends BaseController
$node_prefix = array();
$node_flag_file = array();
$node_method = array();
$a = 0; //命名的什么JB变量
$a = 0;//命名的什么JB变量
$node_order = array();
$node_alive = array();
$node_prealive = array();
@ -632,9 +620,9 @@ class UserController extends BaseController
}
if ($node->node_bandwidth_limit == 0) {
$node_bandwidth[$name_cheif] = (int) ($node->node_bandwidth / 1024 / 1024 / 1024) . ' GB 已用';
$node_bandwidth[$name_cheif] = (int)($node->node_bandwidth / 1024 / 1024 / 1024) . ' GB 已用';
} else {
$node_bandwidth[$name_cheif] = (int) ($node->node_bandwidth / 1024 / 1024 / 1024) . ' GB / ' . (int) ($node->node_bandwidth_limit / 1024 / 1024 / 1024) . ' GB - ' . $node->bandwidthlimit_resetday . ' 日重置';
$node_bandwidth[$name_cheif] = (int)($node->node_bandwidth / 1024 / 1024 / 1024) . ' GB / ' . (int)($node->node_bandwidth_limit / 1024 / 1024 / 1024) . ' GB - ' . $node->bandwidthlimit_resetday . ' 日重置';
}
if ($node_tempalive != '暂无数据') {
@ -653,14 +641,14 @@ class UserController extends BaseController
$nodeLoad = $node->getNodeLoad();
if (isset($nodeLoad[0]['load'])) {
$node_latestload[$name_cheif] = ((float) (explode(' ', $nodeLoad[0]['load']))[0]) * 100;
$node_latestload[$name_cheif] = ((float)(explode(' ', $nodeLoad[0]['load']))[0]) * 100;
} else {
$node_latestload[$name_cheif] = null;
}
$node_prefix[$name_cheif][] = $node;
if (Config::get('enable_flag') == true) {
if (Config::get('enable_flag') == 'true') {
$regex = Config::get('flag_regex');
$matches = array();
preg_match($regex, $name_cheif, $matches);
@ -668,8 +656,8 @@ class UserController extends BaseController
}
}
}
$node_prefix = (object) $node_prefix;
$node_order = (object) $node_order;
$node_prefix = (object)$node_prefix;
$node_order = (object)$node_order;
$tools = new Tools();
return $this->view()->assign('relay_rules', $relay_rules)->assign('node_class', $node_class)->assign('node_isv6', $node_isv6)->assign('tools', $tools)->assign('node_method', $node_method)->assign('node_muport', $node_muport)->assign('node_bandwidth', $node_bandwidth)->assign('node_heartbeat', $node_heartbeat)->assign('node_prefix', $node_prefix)->assign('node_flag_file', $node_flag_file)->assign('node_prealive', $node_prealive)->assign('node_order', $node_order)->assign('user', $user)->assign('node_alive', $node_alive)->assign('node_latestload', $node_latestload)->registerClass('URL', URL::class)->display('user/node.tpl');
}
@ -756,11 +744,11 @@ class UserController extends BaseController
foreach ($totallogin as $single) {
//if(isset($useripcount[$single->userid]))
{
if (!isset($userloginip[$single->ip])) {
//$useripcount[$single->userid]=$useripcount[$single->userid]+1;
$location = $iplocation->getlocation($single->ip);
$userloginip[$single->ip] = iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']);
}
if (!isset($userloginip[$single->ip])) {
//$useripcount[$single->userid]=$useripcount[$single->userid]+1;
$location = $iplocation->getlocation($single->ip);
$userloginip[$single->ip] = iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']);
}
}
}
@ -769,16 +757,16 @@ class UserController extends BaseController
{
$single->ip = Tools::getRealIp($single->ip);
$is_node = Node::where('node_ip', $single->ip)->first();
if ($is_node) {
continue;
}
if ($is_node) {
continue;
}
if (!isset($userip[$single->ip])) {
//$useripcount[$single->userid]=$useripcount[$single->userid]+1;
$location = $iplocation->getlocation($single->ip);
$userip[$single->ip] = iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']);
}
if (!isset($userip[$single->ip])) {
//$useripcount[$single->userid]=$useripcount[$single->userid]+1;
$location = $iplocation->getlocation($single->ip);
$userip[$single->ip] = iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']);
}
}
}
@ -818,17 +806,8 @@ class UserController extends BaseController
$config_service = new Config();
return $this->view()
->assign('user', $this->user)
->assign('schemes', Config::get('user_agreement_scheme'))
->assign('themes', $themes)
->assign('isBlock', $isBlock)
->assign('Block', $Block)
->assign('bind_token', $bind_token)
->assign('telegram_bot', Config::get('new_telegram_username'))
->assign('config_service', $config_service)
->registerClass('URL', URL::class)
->display('user/edit.tpl');
return $this->view()->assign('user', $this->user)->assign('themes', $themes)->assign('isBlock', $isBlock)->assign('Block', $Block)->assign('bind_token', $bind_token)->assign('telegram_bot', Config::get('telegram_bot'))->assign('config_service', $config_service)
->registerClass('URL', URL::class)->display('user/edit.tpl');
}
@ -1197,7 +1176,7 @@ class UserController extends BaseController
public function ticket($request, $response, $args)
{
if (Config::get('enable_ticket') != true) {
if (Config::get('enable_ticket') != 'true') {
exit(0);
}
$pageNum = $request->getQueryParams()['page'] ?? 1;
@ -1240,7 +1219,7 @@ class UserController extends BaseController
$ticket->datetime = time();
$ticket->save();
if (Config::get('mail_ticket') == true && $markdown != '') {
if (Config::get('mail_ticket') == 'true' && $markdown != '') {
$adminUser = User::where('is_admin', '=', '1')->get();
foreach ($adminUser as $user) {
$subject = Config::get('appName') . '-新工单被开启';
@ -1249,14 +1228,15 @@ class UserController extends BaseController
try {
Mail::send($to, $subject, 'news/warn.tpl', [
'user' => $user, 'text' => $text
], []);
], [
]);
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
if (Config::get('useScFtqq') == true && $markdown != '') {
if (Config::get('useScFtqq') == 'true' && $markdown != '') {
$ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY');
$postdata = http_build_query(
array(
@ -1265,11 +1245,11 @@ class UserController extends BaseController
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
));
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
));
$context = stream_context_create($opts);
file_get_contents('https://sc.ftqq.com/' . $ScFtqq_SCKEY . '.send', false, $context);
}
@ -1306,7 +1286,7 @@ class UserController extends BaseController
}
if ($status == 1 && $ticket_main->status != $status) {
if (Config::get('mail_ticket') == true && $markdown != '') {
if (Config::get('mail_ticket') == 'true' && $markdown != '') {
$adminUser = User::where('is_admin', '=', '1')->get();
foreach ($adminUser as $user) {
$subject = Config::get('appName') . '-工单被重新开启';
@ -1315,13 +1295,14 @@ class UserController extends BaseController
try {
Mail::send($to, $subject, 'news/warn.tpl', [
'user' => $user, 'text' => $text
], []);
], [
]);
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
if (Config::get('useScFtqq') == true && $markdown != '') {
if (Config::get('useScFtqq') == 'true' && $markdown != '') {
$ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY');
$postdata = http_build_query(
array(
@ -1330,17 +1311,17 @@ class UserController extends BaseController
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
));
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
));
$context = stream_context_create($opts);
file_get_contents('https://sc.ftqq.com/' . $ScFtqq_SCKEY . '.send', false, $context);
$useScFtqq = Config::get('ScFtqq_SCKEY');
}
} else {
if (Config::get('mail_ticket') == true && $markdown != '') {
if (Config::get('mail_ticket') == 'true' && $markdown != '') {
$adminUser = User::where('is_admin', '=', '1')->get();
foreach ($adminUser as $user) {
$subject = Config::get('appName') . '-工单被回复';
@ -1349,13 +1330,14 @@ class UserController extends BaseController
try {
Mail::send($to, $subject, 'news/warn.tpl', [
'user' => $user, 'text' => $text
], []);
], [
]);
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
if (Config::get('useScFtqq') == true && $markdown != '') {
if (Config::get('useScFtqq') == 'true' && $markdown != '') {
$ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY');
$postdata = http_build_query(
array(
@ -1364,11 +1346,11 @@ class UserController extends BaseController
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
));
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
));
$context = stream_context_create($opts);
file_get_contents('https://sc.ftqq.com/' . $ScFtqq_SCKEY . '.send', false, $context);
}
@ -1427,6 +1409,12 @@ class UserController extends BaseController
return $response->getBody()->write(json_encode($res));
}
if ($user->discord != 0) {
$res['ret'] = 0;
$res['msg'] = '您绑定了 Discord ,所以此项并不能被修改。';
return $response->getBody()->write(json_encode($res));
}
if ($wechat == '' || $type == '') {
$res['ret'] = 0;
$res['msg'] = '非法输入';
@ -1450,6 +1438,7 @@ class UserController extends BaseController
return $this->echoJson($response, $res);
}
public function updateSSR($request, $response, $args)
{
$protocol = $request->getParam('protocol');
@ -1497,8 +1486,6 @@ class UserController extends BaseController
$user->save();
$user->cleanSubCache();
if (!URL::SSCanConnect($user)) {
$res['ret'] = 1;
$res['msg'] = '设置成功,但您目前的协议,混淆,加密方式设置会导致 Shadowsocks原版客户端无法连接,请您自行更换到 ShadowsocksR 客户端。';
@ -1605,7 +1592,6 @@ class UserController extends BaseController
Radius::Add($user, $pwd);
$user->cleanSubCache();
return $this->echoJson($response, $res);
}
@ -1669,7 +1655,7 @@ class UserController extends BaseController
public function doCheckIn($request, $response, $args)
{
if (Config::get('enable_checkin_captcha') == true) {
if (Config::get('enable_checkin_captcha') == 'true') {
switch (Config::get('captcha_provider')) {
case 'recaptcha':
$recaptcha = $request->getParam('recaptcha');
@ -1697,14 +1683,16 @@ class UserController extends BaseController
return $response->getBody()->write(json_encode($res));
}
$checkin = $this->user->checkin();
if ($checkin['ok'] === false) {
if (!$this->user->isAbleToCheckin()) {
$res['ret'] = 0;
$res['msg'] = $checkin['msg'];
return $this->echoJson($response, $res);
$res['msg'] = '您似乎已经签到过了...';
return $response->getBody()->write(json_encode($res));
}
$res['msg'] = $checkin['msg'];
$traffic = random_int(Config::get('checkinMin'), Config::get('checkinMax'));
$this->user->transfer_enable += Tools::toMB($traffic);
$this->user->last_check_in_time = time();
$this->user->save();
$res['msg'] = sprintf('获得了 %d MB流量.', $traffic);
$res['unflowtraffic'] = $this->user->transfer_enable;
$res['traffic'] = Tools::flowAutoShow($this->user->transfer_enable);
$res['trafficInfo'] = array(
@ -1736,9 +1724,8 @@ class UserController extends BaseController
return $this->echoJson($response, $res);
}
if (Config::get('enable_kill') == true) {
if (Config::get('enable_kill') == 'true') {
Auth::logout();
$user->cleanSubCache();
$user->kill_user();
$res['ret'] = 1;
$res['msg'] = '您的帐号已经从我们的系统中删除。欢迎下次光临!';
@ -1777,6 +1764,14 @@ class UserController extends BaseController
return $this->view()->display('user/disable.tpl');
}
public function discord_reset($request, $response, $args)
{
$user = $this->user;
$user->discord = 0;
$user->save();
return $response->withStatus(302)->withHeader('Location', '/user/edit');
}
public function telegram_reset($request, $response, $args)
{
$user = $this->user;
@ -1789,7 +1784,6 @@ class UserController extends BaseController
{
$user = $this->user;
$user->clean_link();
$user->cleanSubCache();
return $response->withStatus(302)->withHeader('Location', '/user');
}
@ -1840,83 +1834,11 @@ class UserController extends BaseController
return $response->withStatus(302)->withHeader('Location', $local);
}
public function switchType($request, $response, $args)
{
$user = $this->user;
$type = $request->getParam('id');
$type = trim($type);
$scheme = [];
$items = Config::get('user_agreement_scheme');
foreach ($items as $item) {
if ($type == $item['id']) {
$scheme = $item;
}
}
if (!isset($scheme['id'])) {
$res['ret'] = 0;
$res['msg'] = '非法输入';
return $response->getBody()->write(json_encode($res));
}
$user->method = $scheme['method'];
$user->protocol = $scheme['protocol'];
$user->obfs = $scheme['obfs'];
$user->save();
$user->cleanSubCache();
$res['ret'] = 1;
$res['msg'] = '切换' . $scheme['name'] . '成功';
return $this->echoJson($response, $res);
}
public function getUserAllURL($request, $response, $args)
{
$user = $this->user;
$type = $request->getQueryParams()["type"];
$return = '';
switch ($type) {
case 'ss':
$return .= URL::getAllUrl($user, 0, 1) . PHP_EOL;
break;
case 'ssr':
$return .= URL::getAllUrl($user, 0, 0) . PHP_EOL;
break;
case 'ssd':
$return .= URL::getAllSSDUrl($user) . PHP_EOL;
break;
case 'v2ray':
$return .= URL::getAllVMessUrl($user) . PHP_EOL;
break;
default:
$return .= '悟空别闹!';
break;
}
$newResponse = $response->withHeader('Content-type', ' application/octet-stream; charset=utf-8')->withHeader('Cache-Control', 'no-store, no-cache, must-revalidate')->withHeader('Content-Disposition', ' attachment; filename=node.txt');
$newResponse->write($return);
return $newResponse;
}
public function subscribe_log($request, $response, $args)
{
$pageNum = $request->getQueryParams()['page'] ?? 1;
$logs = UserSubscribeLog::orderBy('id', 'desc')->where('user_id', $this->user->id)->paginate(15, ['*'], 'page', $pageNum);
$logs->setPath('/user/subscribe_log');
$iplocation = new QQWry();
return $this->view()->assign('logs', $logs)->assign('iplocation', $iplocation)->display('user/subscribe_log.tpl');
}
/**
/**
* 获取包含订阅信息的客户端压缩档
*
* @param Request $request
* @param Response $response
*
* @param Request $request
* @param Response $response
* @param array $args
*/
public function getPcClient($request, $response, $args)
@ -1969,21 +1891,4 @@ class UserController extends BaseController
return $newResponse;
}
/**
* 清理订阅缓存
*
* @param Request $request
* @param Response $response
* @param array $args
*/
public function cleanSubCache($request, $response, $args)
{
$this->user->cleanSubCache();
$res['ret'] = 1;
$res['msg'] = '清理成功';
return $this->echoJson($response, $res);
}
}

@ -10,15 +10,15 @@ use App\Models\Ann;
use App\Models\Shop;
use App\Services\Auth;
use App\Services\Config;
use App\Utils\AliPay;
use App\Utils\Tools;
use App\Utils\TelegramSessionManager;
use App\Utils\Spay_tool;
use App\Utils\Geetest;
use App\Utils\URL;
use App\Models\Node;
use App\Models\Relay;
use Slim\Http\{Request, Response};
use Psr\Http\Message\ResponseInterface;
class VueController extends BaseController
{
@ -39,7 +39,7 @@ class VueController extends BaseController
}
}
if (Config::get('new_telegram_enable') == true) {
if (Config::get('enable_telegram') == 'true') {
$login_text = TelegramSessionManager::add_login_session();
$login = explode('|', $login_text);
$login_token = $login[0];
@ -53,7 +53,7 @@ class VueController extends BaseController
'geetest_html' => $GtSdk,
'login_token' => $login_token,
'login_number' => $login_number,
'telegram_bot' => Config::get('new_telegram_username'),
'telegram_bot' => Config::get('telegram_bot'),
'enable_logincaptcha' => Config::get('enable_login_captcha'),
'enable_regcaptcha' => Config::get('enable_reg_captcha'),
'enable_checkin_captcha' => Config::get('enable_checkin_captcha'),
@ -66,7 +66,7 @@ class VueController extends BaseController
'appName' => Config::get('appName'),
'dateY' => date('Y'),
'isLogin' => $user->isLogin,
'enable_telegram' => Config::get('new_telegram_enable'),
'enable_telegram' => Config::get('enable_telegram'),
'enable_mylivechat' => Config::get('enable_mylivechat'),
'enable_flag' => Config::get('enable_flag'),
'payment_type' => Config::get('payment_system'),
@ -438,126 +438,4 @@ class VueController extends BaseController
return $response->getBody()->write(json_encode($res));
}
/**
* @param Request $requesr
* @param Response $response
* @param array $args
*/
public function getNodeInfo($request, $response, $args): ResponseInterface
{
$user = $this->user;
$id = $args['id'];
$mu = $request->getQueryParam('ismu');
$relay_rule_id = $request->getQueryParam('relay_rule');
$node = Node::find($id);
if ($node == null) {
return $response->withJson([null]);
}
switch ($node->sort) {
case 0:
if ((($user->class >= $node->node_class
&& ($user->node_group == $node->node_group || $node->node_group == 0)) || $user->is_admin)
&& ($node->node_bandwidth_limit == 0 || $node->node_bandwidth < $node->node_bandwidth_limit)
) {
return $response->withJson([
'ret' => 1,
'nodeInfo' => [
'node' => $node,
'user' => $user,
'mu' => $mu,
'relay_rule_id' => $relay_rule_id,
'URL' => URL::class,
],
]);
}
break;
case 1:
if ($user->class >= $node->node_class
&& ($user->node_group == $node->node_group || $node->node_group == 0)
) {
$email = $user->email;
$email = Radius::GetUserName($email);
$json_show = 'VPN 信息<br>地址:' . $node->server
. '<br>用户名:' . $email . '<br>密码:' . $this->user->passwd
. '<br>支持方式:' . $node->method . '<br>备注:' . $node->info;
return $response->write(
$this->view()->assign('json_show', $json_show)->fetch('user/nodeinfovpn.tpl')
);
}
break;
case 2:
if ($user->class >= $node->node_class
&& ($user->node_group == $node->node_group || $node->node_group == 0)) {
$email = $user->email;
$email = Radius::GetUserName($email);
$json_show = 'SSH 信息<br>地址:' . $node->server
. '<br>用户名:' . $email . '<br>密码:' . $this->user->passwd
. '<br>支持方式:' . $node->method . '<br>备注:' . $node->info;
return $response->write(
$this->view()->assign('json_show', $json_show)->fetch('user/nodeinfossh.tpl')
);
}
break;
case 5:
if ($user->class >= $node->node_class
&& ($user->node_group == $node->node_group || $node->node_group == 0)) {
$email = $user->email;
$email = Radius::GetUserName($email);
$json_show = 'Anyconnect 信息<br>地址:' . $node->server
. '<br>用户名:' . $email . '<br>密码:' . $this->user->passwd
. '<br>支持方式:' . $node->method . '<br>备注:' . $node->info;
return $response->write(
$this->view()->assign('json_show', $json_show)->fetch('user/nodeinfoanyconnect.tpl')
);
}
break;
case 10:
if ((($user->class >= $node->node_class
&& ($user->node_group == $node->node_group || $node->node_group == 0)) || $user->is_admin)
&& ($node->node_bandwidth_limit == 0 || $node->node_bandwidth < $node->node_bandwidth_limit)) {
return $response->withJson([
'ret' => 1,
'nodeInfo' => [
'node' => $node,
'user' => $user,
'mu' => $mu,
'relay_rule_id' => $relay_rule_id,
'URL' => URL::class,
],
]);
}
break;
case 13:
if ((($user->class >= $node->node_class
&& ($user->node_group == $node->node_group || $node->node_group == 0)) || $user->is_admin)
&& ($node->node_bandwidth_limit == 0 || $node->node_bandwidth < $node->node_bandwidth_limit)) {
return $response->withJson([
'ret' => 1,
'nodeInfo' => [
'node' => $node,
'user' => $user,
'mu' => $mu,
'relay_rule_id' => $relay_rule_id,
'URL' => URL::class,
],
]);
}
break;
}
// Default and judgement fail return
return $response->withJson([
'ret' => 0,
'nodeInfo' => [
'message' => ':)',
],
]);
}
}

@ -2,26 +2,27 @@
namespace App\Middleware;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use App\Services\Auth as AuthService;
class Admin
{
/**
* @param \Slim\Http\Request $request
* @param \Slim\Http\Response $response
* @param callable $next
*
* @return \Slim\Http\Response
*/
public function __invoke($request, $response, $next)
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
{
//$response->getBody()->write('BEFORE');
$user = AuthService::getUser();
if (!$user->isLogin) {
return $response->withStatus(302)->withHeader('Location', '/auth/login');
$newResponse = $response->withStatus(302)->withHeader('Location', '/auth/login');
return $newResponse;
}
if (!$user->isAdmin()) {
return $response->withStatus(302)->withHeader('Location', '/user');
$newResponse = $response->withStatus(302)->withHeader('Location', '/user');
return $newResponse;
}
return $next($request, $response);
$response = $next($request, $response);
return $response;
}
}

@ -0,0 +1,38 @@
<?php
namespace App\Middleware;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use App\Services\Factory;
use App\Utils\Helper;
class Api
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
{
$accessToken = Helper::getParam($request, 'access_token');
if ($accessToken == null) {
$res['ret'] = 0;
$res['msg'] = 'token is null';
$response->getBody()->write(json_encode($res));
return $response;
}
$storage = Factory::createTokenStorage();
$token = $storage->get($accessToken);
if ($token == null) {
$res['ret'] = 0;
$res['msg'] = 'token is null';
$response->getBody()->write(json_encode($res));
return $response;
}
if ($token->expireTime < time()) {
$res['ret'] = 0;
$res['msg'] = 'token is expire';
$response->getBody()->write(json_encode($res));
return $response;
}
$response = $next($request, $response);
return $response;
}
}

@ -2,27 +2,25 @@
namespace App\Middleware;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use App\Services\Auth as AuthService;
class Auth
{
/**
* @param \Slim\Http\Request $request
* @param \Slim\Http\Response $response
* @param callable $next
*
* @return \Slim\Http\Response
*/
public function __invoke($request, $response, $next)
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
{
$user = AuthService::getUser();
if (!$user->isLogin) {
return $response->withStatus(302)->withHeader('Location', '/auth/login');
$newResponse = $response->withStatus(302)->withHeader('Location', '/auth/login');
return $newResponse;
}
$enablePages = array('/user/disable', '/user/backtoadmin', '/user/logout');
if ($user->enable == 0 && !in_array($_SERVER['REQUEST_URI'], $enablePages)) {
return $response->withStatus(302)->withHeader('Location', '/user/disable');
$newResponse = $response->withStatus(302)->withHeader('Location', '/user/disable');
return $newResponse;
}
return $next($request, $response);
$response = $next($request, $response);
return $response;
}
}

@ -2,23 +2,19 @@
namespace App\Middleware;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use App\Services\Auth as AuthService;
class Guest
{
/**
* @param \Slim\Http\Request $request
* @param \Slim\Http\Response $response
* @param callable $next
*
* @return \Slim\Http\Response
*/
public function __invoke($request, $response, $next)
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
{
$user = AuthService::getUser();
if ($user->isLogin) {
return $response->withStatus(302)->withHeader('Location', '/user');
}
return $next($request, $response);
$response = $next($request, $response);
return $response;
}
}

@ -1,42 +1,51 @@
<?php
namespace App\Middleware;
use App\Services\Config;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use App\Utils\Helper;
use App\Models\Node;
class Mod_Mu
{
/**
* @param \Slim\Http\Request $request
* @param \Slim\Http\Response $response
* @param callable $next
*
* @return \Slim\Http\Response
*/
public function __invoke($request, $response, $next)
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
{
$key = $request->getQueryParam('key');
$key = Helper::getParam($request, 'key');
if ($key === null) {
return $response->withjson([
'ret' => 0,
'data' => 'Your key is null.'
]);
$res['ret'] = 0;
$res['data'] = 'null';
$response->getBody()->write(json_encode($res));
return $response;
}
$auth = false;
$keys = Config::getMuKey();
$auth = in_array($key, $keys);
foreach ($keys as $k) {
if ($key == $k) {
$auth = true;
break;
}
}
$node = Node::where('node_ip', 'LIKE', $_SERVER['REMOTE_ADDR'] . '%')->first();
if ($auth === false
|| ($node === null && $_SERVER['REMOTE_ADDR'] != '127.0.0.1')
) {
return $response->withJson([
'ret' => 0,
'data' => 'Token or IP is invalid. Now, your IP address is ' . $_SERVER['REMOTE_ADDR']
]);
if ($node == null && $_SERVER['REMOTE_ADDR'] != '127.0.0.1') {
$res['ret'] = 0;
$res['data'] = 'token or source is invalid, Your ip address is ' . $_SERVER['REMOTE_ADDR'];
$response->getBody()->write(json_encode($res));
return $response;
}
if ($auth == false) {
$res['ret'] = 0;
$res['data'] = 'token or source is invalid';
$response->getBody()->write(json_encode($res));
return $response;
}
return $next($request, $response);
$response = $next($request, $response);
return $response;
}
}

@ -0,0 +1,51 @@
<?php
namespace App\Middleware;
use App\Services\Config;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use App\Utils\Helper;
use App\Models\Node;
class Mu
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
{
$key = Helper::getParam($request, 'key');
if ($key === null) {
$res['ret'] = 0;
$res['msg'] = 'key is null';
$response->getBody()->write(json_encode($res));
return $response;
}
$auth = false;
$keyset = explode(',', Config::get('muKey'));
foreach ($keyset as $sinkey) {
if ($key == $sinkey) {
$auth = true;
break;
}
}
if ($auth == false) {
$res['ret'] = 0;
$res['msg'] = 'token or source is invalid';
$response->getBody()->write(json_encode($res));
return $response;
}
$node = Node::where('node_ip', 'LIKE', $_SERVER['REMOTE_ADDR'] . '%')->first();
if ($node == null && $_SERVER['REMOTE_ADDR'] != '127.0.0.1') {
$res['ret'] = 0;
$res['msg'] = 'token or source is invalid';
$response->getBody()->write(json_encode($res));
return $response;
}
$response = $next($request, $response);
return $response;
}
}

@ -1,9 +0,0 @@
<?php
namespace App\Models;
class DetectBanLog extends Model
{
protected $connection = "default";
protected $table = "detect_ban_log";
}

@ -1,55 +0,0 @@
<?php
namespace App\Models;
use App\Services\DefaultConfig;
class GConfig extends Model
{
/**
* The connection name for the model.
*
* @var string
*/
protected $connection = 'default';
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'gconfig';
/**
* The primary key associated with the table.
*
* @var string
*/
protected $primaryKey = 'key';
/**
* Indicates if the IDs are auto-incrementing.
*
* @var bool
*/
public $incrementing = false;
/**
* The "type" of the auto-incrementing ID.
*
* @var string
*/
protected $keyType = 'string';
public static function recover($user)
{
$this->oldvalue = $this->value;
$this->value = DefaultConfig::default_value($this->key)['value'];
$this->operator_id = $user->id;
$this->operator_name = ('[恢复默认] - ' . $user->user_name);
$this->operator_email = $user->email;
$this->last_update = time();
$this->save();
}
}

@ -7,7 +7,7 @@ namespace App\Models;
*/
use App\Utils\Tools;
use App\Utils\DNSoverHTTPS;
class Node extends Model
{
protected $connection = 'default';
@ -153,9 +153,6 @@ class Node extends Model
public function changeNodeIp($server_name)
{
$ip = gethostbyname($server_name);
if ($ip=="127.0.0.1"){
$ip = DNSoverHTTPS::gethostbyName($server_name);
}
$node_id = $this->attributes['id'];
if ($ip == '') {

@ -135,7 +135,7 @@ class Shop extends Model
switch ($key) {
case 'bandwidth':
if ($is_renew == 0) {
if (Config::get('enable_bought_reset') == true) {
if (Config::get('enable_bought_reset') == 'true') {
$user->transfer_enable = $value * 1024 * 1024 * 1024;
$user->u = 0;
$user->d = 0;
@ -160,7 +160,7 @@ class Shop extends Model
}
break;
case 'class':
if (Config::get('enable_bought_extend') == true) {
if (Config::get('enable_bought_extend') == 'true') {
if ($user->class == $value) {
$user->class_expire = date('Y-m-d H:i:s', strtotime($user->class_expire) + $content['class_expire'] * 86400);
} else {

@ -13,8 +13,6 @@ use App\Utils\GA;
use App\Utils\QQWry;
use App\Utils\Radius;
use Ramsey\Uuid\Uuid;
use App\Models\DetectLog;
use App\Models\DetectBanLog;
class User extends Model
{
@ -40,7 +38,7 @@ class User extends Model
public function getGravatarAttribute()
{
$hash = md5(strtolower(trim($this->attributes['email'])));
return 'https://gravatar.loli.net/avatar/' . $hash."?&d=identicon";
return 'https://gravatar.loli.net/avatar/' . $hash;
}
public function isAdmin()
@ -140,52 +138,37 @@ class User extends Model
)->toString();
}
/*
* 总流量
*/
public function trafficUsagePercent()
{
$total = $this->attributes['u'] + $this->attributes['d'];
$transferEnable = $this->attributes['transfer_enable'];
if ($transferEnable == 0) {
return 0;
}
$percent = $total / $transferEnable;
$percent = round($percent, 2);
$percent *= 100;
return $percent;
}
public function enableTraffic()
{
$transfer_enable = $this->attributes['transfer_enable'];
return Tools::flowAutoShow($transfer_enable);
}
/*
* 总流量[GB]
*/
public function enableTrafficInGB()
{
$transfer_enable = $this->attributes['transfer_enable'];
return Tools::flowToGB($transfer_enable);
}
/*
* 已用流量
*/
public function usedTraffic()
{
$total = $this->attributes['u'] + $this->attributes['d'];
return Tools::flowAutoShow($total);
}
/*
* 已用流量占总流量的百分比
*/
public function trafficUsagePercent()
{
$total = $this->attributes['u'] + $this->attributes['d'];
$transferEnable = $this->attributes['transfer_enable'];
if ($transferEnable == 0) {
return 0;
}
$percent = $total / $transferEnable;
$percent = round($percent, 2);
$percent *= 100;
return $percent;
}
/*
* 剩余流量
*/
public function unusedTraffic()
{
$total = $this->attributes['u'] + $this->attributes['d'];
@ -193,75 +176,18 @@ class User extends Model
return Tools::flowAutoShow($transfer_enable - $total);
}
/*
* 剩余流量占总流量的百分比
*/
public function unusedTrafficPercent()
{
$transferEnable = $this->attributes['transfer_enable'];
if ($transferEnable == 0) {
return 0;
}
$unusedTraffic = $transferEnable - ($this->attributes['u'] + $this->attributes['d']);
$percent = $unusedTraffic / $transferEnable;
$percent = round($percent, 2);
$percent *= 100;
return $percent;
}
/*
* 今天使用的流量
*/
public function TodayusedTraffic()
{
$total = $this->attributes['u'] + $this->attributes['d'] - $this->attributes['last_day_t'];
return Tools::flowAutoShow($total);
}
/*
* 今天使用的流量占总流量的百分比
*/
public function TodayusedTrafficPercent()
{
$transferEnable = $this->attributes['transfer_enable'];
if ($transferEnable == 0) {
return 0;
}
$TodayusedTraffic = $this->attributes['u'] + $this->attributes['d'] - $this->attributes['last_day_t'];
$percent = $TodayusedTraffic / $transferEnable;
$percent = round($percent, 2);
$percent *= 100;
return $percent;
}
/*
* 今天之前已使用的流量
*/
public function LastusedTraffic()
{
$total = $this->attributes['last_day_t'];
return Tools::flowAutoShow($total);
}
/*
* 今天之前已使用的流量占总流量的百分比
*/
public function LastusedTrafficPercent()
{
$transferEnable = $this->attributes['transfer_enable'];
if ($transferEnable == 0) {
return 0;
}
$LastusedTraffic = $this->attributes['last_day_t'];
$percent = $LastusedTraffic / $transferEnable;
$percent = round($percent, 2);
$percent *= 100;
return $percent;
}
/*
* 是否可以签到
*/
public function isAbleToCheckin()
{
$last = $this->attributes['last_check_in_time'];
@ -423,7 +349,6 @@ class User extends Model
$this->attributes['method'],
$this->attributes['protocol'],
$this->attributes['obfs'],
$this->attributes['obfs_param'],
$this->online_ip_count(),
$this->lastSsTime(),
$used_traffic,
@ -456,62 +381,34 @@ class User extends Model
return round($top_up, 2);
}
// 最后一次被封禁的时间
public function last_detect_ban_time()
public function yesterdayIncome()
{
return ($this->attributes['last_detect_ban_time'] == '1989-06-04 00:05:00'
? '未被封禁过'
: $this->attributes['last_detect_ban_time']
);
$number = Code::where('usedatetime', 'like', date('Y-m-d%', strtotime('-1 days')))->sum('number');
return is_null($number)?0:$number;
}
// 当前解封时间
public function relieve_time()
public function todayIncome()
{
if ($this->attributes['detect_ban'] == 1) {
$logs = DetectBanLog::where('user_id', $this->attributes['id'])->orderBy("id", "desc")->first();
$time = ($logs->end_time + $logs->ban_time * 60);
return date('Y-m-d H:i:s', $time);
} else {
return '当前未被封禁';
}
$number = Code::where('usedatetime', 'like', date('Y-m-d%'))->sum('number');
return is_null($number)?0:$number;
}
// 累计被封禁的次数
public function detect_ban_number()
public function thisMonthIncome()
{
$logs = DetectBanLog::where('user_id', $this->attributes['id'])->get();
return count($logs);
$number = Code::where('usedatetime', 'like', date('Y-m%'))->sum('number');
return is_null($number)?0:$number;
}
// 最后一次封禁的违规次数
public function user_detect_ban_number()
public function lastMonthIncome()
{
$logs = DetectBanLog::where('user_id', $this->attributes['id'])->orderBy("id", "desc")->first();
return $logs->detect_number;
$number = Code::where('usedatetime', 'like', date('Y-m%', strtotime('-1 months')))->sum('number');
return is_null($number)?0:$number;
}
public function calIncome($req)
public function totalIncome()
{
switch($req)
{
case "yesterday":
$number = Code::whereDate('usedatetime', '=', date('Y-m-d',strtotime('-1 days')))->sum('number');
break;
case "today":
$number = Code::whereDate('usedatetime', '=', date('Y-m-d'))->sum('number');
break;
case "this month":
$number = Code::whereMonth('usedatetime', '=', date('m'))->sum('number');
break;
case "last month":
$number = Code::whereMonth('usedatetime', '=', date('m',strtotime('last month')))->sum('number');
break;
default:
$number = Code::sum('number');
break;
}
return is_null($number)?0:$number;
$number = Code::where('usedatetime', 'like', date('%'))->sum('number');
return is_null($number)?0:$number;
}
public function paidUserCount()
@ -525,39 +422,4 @@ class User extends Model
$reason = DetectRule::where('id', '=', $reason_id->list_id)->get();
return $reason[0]->text;
}
/**
* 清理订阅缓存
*/
public function cleanSubCache()
{
$id = $this->attributes['id'];
$user_path = (BASE_PATH . '/storage/SubscribeCache/' . $id . '/');
if (is_dir($user_path)) {
Tools::delDirAndFile($user_path);
}
}
/**
* 签到
*/
public function checkin()
{
$return = [
'ok' => true,
'msg' => ''
];
if (!$this->isAbleToCheckin()) {
$return['ok'] = false;
$return['msg'] = '您似乎已经签到过了...';
} else {
$traffic = random_int((int) Config::get('checkinMin'), (int) Config::get('checkinMax'));
$this->transfer_enable += Tools::toMB($traffic);
$this->last_check_in_time = time();
$this->save();
$return['msg'] = '获得了 ' . $traffic . 'MB 流量.';
}
return $return;
}
}

@ -1,9 +0,0 @@
<?php
namespace App\Models;
class UserSubscribeLog extends Model
{
protected $connection = 'default';
protected $table = 'user_subscribe_log';
}

@ -1,554 +0,0 @@
<?php
namespace App\Services;
class AppsProfiles
{
/**
* Surge 策略组配置
*
* @return array
*/
public static function Surge()
{
$Apps_Profiles = [
'lhie1' => [
'Checks' => ['🇭🇰 香港', '🇯🇵 日本', '🇸🇬 坡坡', '🇨🇳 台湾', '🇺🇸 美国', '🇰🇷 韩国', '🇨🇳 中继'],
'ProxyGroup' => [
[
'name' => '🍃 Proxy',
'type' => 'select',
'content' => [
'left-proxies' => ['🇭🇰 香港', '🇯🇵 日本', '🇸🇬 坡坡', '🇨🇳 台湾', '🇺🇸 美国', '🇰🇷 韩国', '🇨🇳 中继', '🚀 Direct']
]
],
[
'name' => '🍂 Domestic',
'type' => 'select',
'content' => [
'left-proxies' => ['🚀 Direct', '🍃 Proxy', '🇨🇳 中继']
]
],
[
'name' => '🍎 Only',
'type' => 'select',
'content' => [
'left-proxies' => ['🚀 Direct', '🇭🇰 香港', '🇯🇵 日本', '🇸🇬 坡坡', '🇨🇳 台湾', '🇺🇸 美国', '🇰🇷 韩国', '🇨🇳 中继']
]
],
[
'name' => '☁️ Others',
'type' => 'select',
'content' => [
'left-proxies' => ['🍃 Proxy', '🍂 Domestic']
]
],
[
'name' => '🇭🇰 香港',
'type' => 'select',
'content' => [
'regex' => '(香港|HK)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '🇯🇵 日本',
'type' => 'select',
'content' => [
'regex' => '(日本|JP)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '🇸🇬 坡坡',
'type' => 'select',
'content' => [
'regex' => '(新加坡|SG)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '🇨🇳 台湾',
'type' => 'select',
'content' => [
'regex' => '(台湾|TW)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '🇺🇸 美国',
'type' => 'select',
'content' => [
'regex' => '(美国|US)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '🇰🇷 韩国',
'type' => 'select',
'content' => [
'regex' => '(韩国|KR)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '🇨🇳 中继',
'type' => 'select',
'content' => [
'regex' => '(中继|中转|中国|回国|China)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
]
]
],
'123456' => [
'Checks' => [],
'ProxyGroup' => [
[
'name' => '🍃 Proxy',
'type' => 'select',
'content' => [
'regex' => '(.*)'
]
],
[
'name' => '🍂 Domestic',
'type' => 'select',
'content' => [
'left-proxies' => ['🚀 Direct', '🍃 Proxy']
]
],
[
'name' => '🍎 Only',
'type' => 'select',
'content' => [
'left-proxies' => ['🚀 Direct', '🍃 Proxy']
]
],
[
'name' => '☁️ Others',
'type' => 'select',
'content' => [
'left-proxies' => ['🍃 Proxy', '🍂 Domestic']
]
]
]
]
];
return $Apps_Profiles;
}
/**
* Surfboard 策略组配置
*
* @return array
*/
public static function Surfboard()
{
$Apps_Profiles = [
'lhie1' => [
'Checks' => ['🇭🇰 香港', '🇯🇵 日本', '🇸🇬 坡坡', '🇨🇳 台湾', '🇺🇸 美国', '🇰🇷 韩国', '🇨🇳 中继'],
'ProxyGroup' => [
[
'name' => '🍃 Proxy',
'type' => 'select',
'content' => [
'left-proxies' => ['🇭🇰 香港', '🇯🇵 日本', '🇸🇬 坡坡', '🇨🇳 台湾', '🇺🇸 美国', '🇰🇷 韩国', '🇨🇳 中继', '🚀 Direct']
]
],
[
'name' => '🍂 Domestic',
'type' => 'select',
'content' => [
'left-proxies' => ['🚀 Direct', '🍃 Proxy', '🇨🇳 中继']
]
],
[
'name' => '☁️ Others',
'type' => 'select',
'content' => [
'left-proxies' => ['🍃 Proxy', '🍂 Domestic']
]
],
[
'name' => '🇭🇰 香港',
'type' => 'select',
'content' => [
'regex' => '(香港|HK)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '🇯🇵 日本',
'type' => 'select',
'content' => [
'regex' => '(日本|JP)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '🇸🇬 坡坡',
'type' => 'select',
'content' => [
'regex' => '(新加坡|SG)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '🇨🇳 台湾',
'type' => 'select',
'content' => [
'regex' => '(台湾|TW)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '🇺🇸 美国',
'type' => 'select',
'content' => [
'regex' => '(美国|US)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '🇰🇷 韩国',
'type' => 'select',
'content' => [
'regex' => '(韩国|KR)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '🇨🇳 中继',
'type' => 'select',
'content' => [
'regex' => '(中继|中转|中国|回国|China)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
]
]
],
'123456' => [
'Checks' => [],
'ProxyGroup' => [
[
'name' => '🍃 Proxy',
'type' => 'select',
'content' => [
'regex' => '(.*)'
]
],
[
'name' => '🍂 Domestic',
'type' => 'select',
'content' => [
'left-proxies' => ['🚀 Direct', '🍃 Proxy']
]
],
[
'name' => '☁️ Others',
'type' => 'select',
'content' => [
'left-proxies' => ['🍃 Proxy', '🍂 Domestic']
]
]
]
]
];
return $Apps_Profiles;
}
/**
* Clash 策略组配置
*
* @return array
*/
public static function Clash()
{
$Apps_Profiles = [
'lhie1' => [
'Checks' => ['香港', '日本', '坡坡', '台湾', '美国', '韩国', '中继'],
'ProxyGroup' => [
[
'name' => '香港',
'type' => 'url-test',
'content' => [
'regex' => '(香港|HK)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '日本',
'type' => 'url-test',
'content' => [
'regex' => '(日本|JP)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '坡坡',
'type' => 'url-test',
'content' => [
'regex' => '(新加坡|SG)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '美国',
'type' => 'url-test',
'content' => [
'regex' => '(美国|US)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '台湾',
'type' => 'url-test',
'content' => [
'regex' => '(台湾|TW)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '韩国',
'type' => 'url-test',
'content' => [
'regex' => '(韩国|KR)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '中继',
'type' => 'url-test',
'content' => [
'regex' => '(中继|中转|中国|回国|China)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => 'Proxy',
'type' => 'select',
'content' => [
'left-proxies' => ['香港', '日本', '坡坡', '台湾', '美国', '韩国', '中继']
]
],
[
'name' => 'Domestic',
'type' => 'select',
'content' => [
'left-proxies' => ['DIRECT', 'Proxy', '中继']
]
],
[
'name' => 'AsianTV',
'type' => 'select',
'content' => [
'left-proxies' => ['Domestic', 'Proxy', '中继']
]
],
[
'name' => 'GlobalTV',
'type' => 'select',
'content' => [
'left-proxies' => ['Proxy', '香港', '日本', '坡坡', '台湾', '美国', '韩国', '中继']
]
],
[
'name' => 'Others',
'type' => 'select',
'content' => [
'left-proxies' => ['Proxy', 'Domestic']
]
]
]
],
'ConnersHua_Pro' => [
'Checks' => ['香港', '日本', '坡坡', '台湾', '美国', '韩国', '中继'],
'ProxyGroup' => [
[
'name' => '香港',
'type' => 'url-test',
'content' => [
'regex' => '(香港|HK)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '日本',
'type' => 'url-test',
'content' => [
'regex' => '(日本|JP)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '坡坡',
'type' => 'url-test',
'content' => [
'regex' => '(新加坡|SG)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '美国',
'type' => 'url-test',
'content' => [
'regex' => '(美国|US)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '台湾',
'type' => 'url-test',
'content' => [
'regex' => '(台湾|TW)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '韩国',
'type' => 'url-test',
'content' => [
'regex' => '(韩国|KR)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => '中继',
'type' => 'url-test',
'content' => [
'regex' => '(中继|中转|中国|回国|China|CN)'
],
'url' => 'http://www.qualcomm.cn/generate_204',
'interval' => 3600
],
[
'name' => 'PROXY',
'type' => 'select',
'content' => [
'left-proxies' => ['香港', '日本', '坡坡', '台湾', '美国', '韩国', '中继']
]
],
[
'name' => 'Final',
'type' => 'select',
'content' => [
'left-proxies' => ['PROXY', 'DIRECT']
]
],
[
'name' => 'ForeignMedia',
'type' => 'select',
'content' => [
'left-proxies' => ['PROXY', '香港', '日本', '坡坡', '台湾', '美国', '韩国', '中继']
]
],
[
'name' => 'DomesticMedia',
'type' => 'select',
'content' => [
'left-proxies' => ['DIRECT', 'PROXY', '中继']
]
],
[
'name' => 'Apple',
'type' => 'select',
'content' => [
'left-proxies' => ['DIRECT', 'PROXY']
]
],
[
'name' => 'Hijacking',
'type' => 'select',
'content' => [
'left-proxies' => ['DIRECT', 'REJECT']
]
]
]
],
'ConnersHua_BacktoCN' => [
'Checks' => [],
'ProxyGroup' => [
[
'name' => 'PROXY',
'type' => 'select',
'content' => [
'regex' => '(中继|中转|中国|回国|China)'
]
]
]
],
'123456' => [
'Checks' => [],
'ProxyGroup' => [
[
'name' => 'Proxy',
'type' => 'select',
'content' => [
'regex' => '(.*)'
]
],
[
'name' => 'Domestic',
'type' => 'select',
'content' => [
'left-proxies' => ['DIRECT', 'Proxy']
]
],
[
'name' => 'AsianTV',
'type' => 'select',
'content' => [
'left-proxies' => ['Domestic', 'Proxy']
]
],
[
'name' => 'GlobalTV',
'type' => 'select',
'content' => [
'left-proxies' => ['Proxy']
]
],
[
'name' => 'Others',
'type' => 'select',
'content' => [
'left-proxies' => ['Proxy', 'Domestic']
]
]
]
]
];
return $Apps_Profiles;
}
}

@ -4,8 +4,11 @@ namespace App\Services;
class Auth
{
protected $driver;
protected $user;
public function __construct()
{
}
private static function getDriver()
{
@ -17,18 +20,9 @@ class Auth
self::getDriver()->login($uid, $time);
}
/**
* Get current user(cached)
*
* @return \App\Models\User
*/
public static function getUser()
{
global $user;
if ($user === null) {
$user = self::getDriver()->getUser();
}
return $user;
return self::getDriver()->getUser();
}
public static function logout()

@ -43,7 +43,7 @@ class Cookie extends Base
return $user;
}
if (Config::get('enable_login_bind_ip') == true) {
if (Config::get('enable_login_bind_ip') == 'true') {
$nodes = Node::where('node_ip', '=', $_SERVER['REMOTE_ADDR'])->first();
if (($nodes == null) && $ipHash != md5($_SERVER['REMOTE_ADDR'] . Config::get('key') . $uid . $expire_in)) {
return $user;

@ -0,0 +1,7 @@
<?php
namespace App\Services\Auth;
class File
{
}

@ -48,7 +48,7 @@ class Redis extends Base
$ip = $this->client->get($sid . 'ip');
$nodes = Node::where('node_ip', '=', $_SERVER['REMOTE_ADDR'])->first();
if ($ip != $_SERVER['REMOTE_ADDR'] && $nodes == null && Config::get('enable_login_bind_ip') == true) {
if ($ip != $_SERVER['REMOTE_ADDR'] && $nodes == null && Config::get('enable_login_bind_ip') == 'true') {
$user = new User();
$user->isLogin = false;
return $user;

@ -0,0 +1,31 @@
<?php
namespace App\Services\Auth;
use App\Services\Factory;
class Token extends Base
{
protected $storage;
public function __construct()
{
$this->storage = Factory::createTokenStorage();
}
public function login($uid, $time)
{
// TODO: Implement getUser() method.
}
public function logout()
{
// TODO: Implement logout() method.
}
public function getUser()
{
$token = Cookie::get('token');
}
}

@ -28,7 +28,7 @@ class Boot
// Init Eloquent ORM Connection
$capsule = new Capsule();
$capsule->addConnection(Config::getDbConfig());
if (Config::get('enable_radius') == true) {
if (Config::get('enable_radius') == 'true') {
$capsule->addConnection(Config::getRadiusDbConfig(), 'radius');
}
$capsule->bootEloquent();

@ -0,0 +1,7 @@
<?php
namespace App\Services;
class Cache
{
}

@ -2,8 +2,6 @@
namespace App\Services;
use App\Models\GConfig;
class Config
{
// TODO: remove
@ -12,15 +10,6 @@ class Config
return $_ENV[$key];
}
public static function getdb($key)
{
$value = GConfig::find($key);
if ($value === null) {
$value = DefaultConfig::firstOrCreate($key);
}
return $value->value;
}
public static function getPublicConfig()
{
return [
@ -41,7 +30,8 @@ class Config
'enable_analytics_code' => self::get('enable_analytics_code'),
'sspanelAnalysis' => self::get('sspanelAnalysis'),
'enable_donate' => self::get('enable_donate'),
'enable_telegram' => self::get('new_telegram_enable'),
'enable_telegram' => self::get('enable_telegram'),
'enable_discord' => self::get('enable_discord'),
'payment_system' => self::get('payment_system'),
'enable_mylivechat' => self::get('enable_mylivechat'),
'mylivechat_id' => self::get('mylivechat_id'),
@ -56,16 +46,7 @@ class Config
'custom_invite_price' => self::get('custom_invite_price'),
'captcha_provider' => self::get('captcha_provider'),
'enable_email_verify' => self::get('enable_email_verify'),
'protocol_specify' => self::get('protocol_specify'),
'subscribeLog' => self::get('subscribeLog'),
'subscribeLog_keep_days' => self::get('subscribeLog_keep_days'),
'enable_auto_detect_ban' => self::get('enable_auto_detect_ban'),
'auto_detect_ban_type' => self::get('auto_detect_ban_type'),
'auto_detect_ban_number' => self::get('auto_detect_ban_number'),
'auto_detect_ban_time' => self::get('auto_detect_ban_time'),
'auto_detect_ban' => self::get('auto_detect_ban'),
'subscribe_client' => self::get('subscribe_client'),
'enable_sub_cache' => self::get('enable_sub_cache')
'subscribe_client' => self::get('subscribe_client')
];
}

@ -1,227 +0,0 @@
<?php
namespace App\Services;
use App\Models\GConfig;
class DefaultConfig
{
public static function create($key)
{
$value = self::default_value($key);
if ($value != null) {
$new = new GConfig();
$new->key = $value['key'];
$new->value = $value['value'];
$new->name = $value['name'];
$new->comment = $value['comment'];
$new->operator_id = $value['operator_id'];
$new->operator_name = $value['operator_name'];
$new->oldvalue = '';
$new->operator_email = '';
$new->last_update = time();
if ($new->save()) {
return true;
}
}
return false;
}
public static function firstOrCreate($key)
{
return (self::create($key)
? GConfig::find($key)
: null
);
}
public static function detectConfigs()
{
$return = '开始检查新增的配置项...' . PHP_EOL;
$configs = self::configs();
foreach ($configs as $key => $value) {
$config = GConfig::find($key);
if ($config == null) {
if (self::create($key)) {
$return .= '新增的配置项:' . $key . ':' . $value['name'] . PHP_EOL;
} else {
$return .= $key . ':配置项创建失败,请检查错误' . PHP_EOL;
}
}
}
$return .= '以上是新增的配置项...' . PHP_EOL;
return $return;
}
public static function configs($key = null)
{
$configs = [
'Telegram.enable.Diary' => [
'key' => $key,
'value' => 1,
'name' => '开启 Telegram 群组推送系统今天的运行状况',
'comment' => '',
'operator_id' => 0,
'operator_name' => '系统默认',
],
'Telegram.msg.Diary' => [
'key' => $key,
'value' => ('各位老爷少奶奶,我来为大家报告一下系统今天的运行状况哈~' . PHP_EOL . '今日签到人数:%getTodayCheckinUser%' . PHP_EOL . '今日使用总流量:%lastday_total%' . PHP_EOL . '晚安~'),
'name' => '自定义向 Telegram 群组推送系统今天的运行状况的信息',
'comment' => '可用变量:' . PHP_EOL . '[今日签到人数] %getTodayCheckinUser%' . PHP_EOL . '[今日使用总流量] %lastday_total%',
'operator_id' => 0,
'operator_name' => '系统默认',
],
'Telegram.enable.DailyJob' => [
'key' => $key,
'value' => 1,
'name' => '开启 Telegram 群组推送数据库清理的通知',
'comment' => '',
'operator_id' => 0,
'operator_name' => '系统默认',
],
'Telegram.msg.DailyJob' => [
'key' => $key,
'value' => '姐姐姐姐,数据库被清理了,感觉身体被掏空了呢~',
'name' => '自定义向 Telegram 群组推送数据库清理通知的信息',
'comment' => '',
'operator_id' => 0,
'operator_name' => '系统默认',
],
'Telegram.enable.NodeOffline' => [
'key' => $key,
'value' => 1,
'name' => '开启 Telegram 群组推送节点掉线的通知',
'comment' => '',
'operator_id' => 0,
'operator_name' => '系统默认',
],
'Telegram.msg.NodeOffline' => [
'key' => $key,
'value' => '喵喵喵~ %node_name% 节点掉线了喵~',
'name' => '自定义向 Telegram 群组推送节点掉线通知的信息',
'comment' => '可用变量:' . PHP_EOL . '[节点名称] %node_name%',
'operator_id' => 0,
'operator_name' => '系统默认',
],
'Telegram.enable.NodeOnline' => [
'key' => $key,
'value' => 1,
'name' => '开启 Telegram 群组推送节点上线的通知',
'comment' => '',
'operator_id' => 0,
'operator_name' => '系统默认',
],
'Telegram.msg.NodeOnline' => [
'key' => $key,
'value' => '喵喵喵~ %node_name% 节点恢复了喵~',
'name' => '自定义向 Telegram 群组推送节点上线通知的信息',
'comment' => '可用变量:' . PHP_EOL . '[节点名称] %node_name%',
'operator_id' => 0,
'operator_name' => '系统默认',
],
'Telegram.enable.NodeGFW' => [
'key' => $key,
'value' => 1,
'name' => '开启 Telegram 群组推送节点被墙的通知',
'comment' => '',
'operator_id' => 0,
'operator_name' => '系统默认',
],
'Telegram.msg.NodeGFW' => [
'key' => $key,
'value' => '喵喵喵~ %node_name% 节点被墙了喵~',
'name' => '自定义向 Telegram 群组推送节点被墙通知的信息',
'comment' => '可用变量:' . PHP_EOL . '[节点名称] %node_name%',
'operator_id' => 0,
'operator_name' => '系统默认',
],
'Telegram.enable.NodeGFW_recover' => [
'key' => $key,
'value' => 1,
'name' => '开启 Telegram 群组推送节点被墙恢复的通知',
'comment' => '',
'operator_id' => 0,
'operator_name' => '系统默认',
],
'Telegram.msg.NodeGFW_recover' => [
'key' => $key,
'value' => '喵喵喵~ %node_name% 节点恢复了喵~',
'name' => '自定义向 Telegram 群组推送节点被墙恢复通知的信息',
'comment' => '可用变量:' . PHP_EOL . '[节点名称] %node_name%',
'operator_id' => 0,
'operator_name' => '系统默认',
],
'Telegram.enable.AddNode' => [
'key' => $key,
'value' => 1,
'name' => '开启 Telegram 群组推送节点新增的通知',
'comment' => '',
'operator_id' => 0,
'operator_name' => '系统默认',
],
'Telegram.msg.AddNode' => [
'key' => $key,
'value' => '新节点添加~ %node_name%',
'name' => '自定义向 Telegram 群组推送节点新增通知的信息',
'comment' => '可用变量:' . PHP_EOL . '[节点名称] %node_name%',
'operator_id' => 0,
'operator_name' => '系统默认',
],
'Telegram.enable.UpdateNode' => [
'key' => $key,
'value' => 1,
'name' => '开启 Telegram 群组推送节点修改的通知',
'comment' => '',
'operator_id' => 0,
'operator_name' => '系统默认',
],
'Telegram.msg.UpdateNode' => [
'key' => $key,
'value' => '节点信息被修改~ %node_name%',
'name' => '自定义向 Telegram 群组推送节点修改通知的信息',
'comment' => '可用变量:' . PHP_EOL . '[节点名称] %node_name%',
'operator_id' => 0,
'operator_name' => '系统默认',
],
'Telegram.enable.DeleteNode' => [
'key' => $key,
'value' => 1,
'name' => '开启 Telegram 群组推送节点删除的通知',
'comment' => '',
'operator_id' => 0,
'operator_name' => '系统默认',
],
'Telegram.msg.DeleteNode' => [
'key' => $key,
'value' => '节点被删除~ %node_name%',
'name' => '自定义向 Telegram 群组推送节点删除通知的信息',
'comment' => '可用变量:' . PHP_EOL . '[节点名称] %node_name%',
'operator_id' => 0,
'operator_name' => '系统默认',
],
];
return ($key === null
? $configs
: $configs[$key]
);
}
public static function default_value($key)
{
return (in_array($key, array_keys(self::configs()))
? self::configs($key)
: null
);
}
}

@ -5,6 +5,8 @@ namespace App\Services;
use App\Services\Auth\Cookie;
use App\Services\Auth\Redis;
use App\Services\Auth\JwtToken;
use App\Services\Token\DB;
use App\Services\Token\Dynamodb;
class Factory
{
@ -21,4 +23,24 @@ class Factory
}
return new Redis();
}
public static function createCache()
{
}
public static function createMail()
{
}
public static function createTokenStorage()
{
switch (Config::get('tokenDriver')) {
case 'db':
return new DB();
case 'dynamodb':
return new Dynamodb();
default:
return new DB();
}
}
}

@ -14,40 +14,19 @@ use App\Models\User;
use App\Models\Code;
use App\Services\Config;
use App\Utils\Telegram;
use Slim\Http\{Request, Response};
abstract class AbstractPayment
{
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
abstract public function purchase($request, $response, $args);
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
abstract public function notify($request, $response, $args);
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
abstract public function getPurchaseHTML();
abstract public function getReturnHTML($request, $response, $args);
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
abstract public function getStatus($request, $response, $args);
abstract public function getPurchaseHTML();
public function postPayment($pid, $method)
{
$p = Paylist::where('tradeno', $pid)->first();
@ -83,7 +62,7 @@ abstract class AbstractPayment
$Payback->save();
}
if (Config::get('enable_donate') == true) {
if (Config::get('enable_donate') == 'true') {
if ($user->is_hide == 1) {
Telegram::Send('一位不愿透露姓名的大老爷给我们捐了 ' . $codeq->number . ' 元!');
} else {

@ -1,201 +0,0 @@
<?php
/**
* BitPayX - Yet Another Payment for FIAT
* Make Payment Safer, Faster, Cheaper.
*
* Date: 2019/6/15
* Time: 10:08 AM PST
*/
namespace App\Services\Gateway;
use App\Models\Paylist;
use App\Services\Auth;
use App\Services\Config;
use App\Services\View;
class BitPayX extends AbstractPayment
{
private $bitpayAppSecret;
private $bitpayGatewayUri;
/*****************************************************************
* BitPay Helper Function
******************************************************************/
public function __construct($bitpayAppSecret)
{
$this->bitpayAppSecret = $bitpayAppSecret;
$this->bitpayGatewayUri = 'https://api.mugglepay.com/v1/';
}
public function prepareSignId($tradeno)
{
$data_sign = array();
$data_sign['merchant_order_id'] = $tradeno;
$data_sign['secret'] = $this->bitpayAppSecret;
$data_sign['type'] = 'FIAT';
ksort($data_sign);
return http_build_query($data_sign);
}
public function sign($data)
{
return strtolower(md5(md5($data) . $this->bitpayAppSecret));
}
public function verify($data, $signature)
{
$mySign = $this->sign($data);
return $mySign === $signature;
}
public function mprequest($data, $type = 'pay')
{
$headers = array('content-type: application/json', 'token: ' . $this->bitpayAppSecret);
$curl = curl_init();
if ($type === 'pay') {
$this->bitpayGatewayUri .= 'orders';
curl_setopt($curl, CURLOPT_URL, $this->bitpayGatewayUri);
curl_setopt($curl, CURLOPT_POST, 1);
$data_string = json_encode($data);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
} elseif ($type === 'query') {
$this->bitpayGatewayUri .= 'orders/merchant_order_id/status?id=' . $data['merchant_order_id'];
curl_setopt($curl, CURLOPT_URL, $this->bitpayGatewayUri);
curl_setopt($curl, CURLOPT_HTTPGET, 1);
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($curl);
curl_close($curl);
return $data;
}
public function query($tradeNo)
{
$data['merchant_order_id'] = $tradeNo;
return json_decode($this->mprequest($data, 'query'), true);
}
/*****************************************************************
* Abstract Payment Implentation
******************************************************************/
public function purchase($request, $response, $args)
{
$price = $request->getParam('price');
$type = $request->getParam('type');
// file_put_contents(BASE_PATH.'/bitpay_purchase.log', $price . " " . $type . "\r\n", FILE_APPEND);
if ($price <= 0) {
return json_encode(['errcode' => -1, 'errmsg' => '请输入合理的金额。']);
}
$user = Auth::getUser();
$pl = new Paylist();
$pl->userid = $user->id;
$pl->total = $price;
$pl->tradeno = self::generateGuid();
$pl->save();
$data['merchant_order_id'] = $pl->tradeno;
$data['price_amount'] = (float)$price;
$data['price_currency'] = 'CNY';
if ($type === 'WECHAT' || $type === 'ALIPAY') {
$data['pay_currency'] = $type;
}
$data['title'] = '支付单号:' . $pl->tradeno;
$data['description'] = '充值:' . $price . ' 元';
$data['callback_url'] = Config::get('baseUrl') . '/payment/notify';
$data['success_url'] = Config::get('baseUrl') . '/user/payment/return?merchantTradeNo=';
$data['success_url'] .= $pl->tradeno;
$data['cancel_url'] = $data['success_url'];
$str_to_sign = $this->prepareSignId($pl->tradeno);
$data['token'] = $this->sign($str_to_sign);
$result = json_decode($this->mprequest($data), true);
$result['pid'] = $pl->tradeno;
// file_put_contents(BASE_PATH.'/bitpay_purchase.log', json_encode($data)."\r\n", FILE_APPEND);
// file_put_contents(BASE_PATH.'/bitpay_purchase.log', json_encode($result)."\r\n", FILE_APPEND);
if ($result['status'] === 200 || $result['status'] === 201) {
$result['payment_url'] .= '&lang=zh';
return json_encode(array('url' => $result['payment_url'], 'errcode' => 0, 'pid' => $pl->id));
}
return json_encode(['errcode' => -1, 'errmsg' => $result . error]);
}
public function notify($request, $response, $args)
{
if (!$this->bitpayAppSecret || $this->bitpayAppSecret === '') {
$return = [];
$return['status'] = 400;
echo json_encode($return);
return;
}
$inputString = file_get_contents('php://input', 'r');
$inputStripped = str_replace(array("\r", "\n", "\t", "\v"), '', $inputString);
$inputJSON = json_decode($inputStripped, true); //convert JSON into array
$data = array();
if ($inputJSON !== null) {
$data['status'] = $inputJSON['status'];
$data['order_id'] = $inputJSON['order_id'];
$data['merchant_order_id'] = $inputJSON['merchant_order_id'];
$data['price_amount'] = $inputJSON['price_amount'];
$data['price_currency'] = $inputJSON['price_currency'];
$data['created_at_t'] = $inputJSON['created_at_t'];
}
// file_put_contents(BASE_PATH.'/bitpay_notify.log', json_encode($data)."\r\n", FILE_APPEND);
// 准备待签名数据
$str_to_sign = $this->prepareSignId($inputJSON['merchant_order_id']);
$resultVerify = $this->verify($str_to_sign, $inputJSON['token']);
$isPaid = $data !== null && $data['status'] !== null && $data['status'] === 'PAID';
// file_put_contents(BASE_PATH.'/bitpay_notify.log', $resultVerify."\r\n".$isPaid."\r\n", FILE_APPEND);
if ($resultVerify && $isPaid) {
$this->postPayment($data['merchant_order_id'], 'BitPayX');
// echo 'SUCCESS';
$return = [];
$return['status'] = 200;
echo json_encode($return);
} else {
// echo 'FAIL';
$return = [];
$return['status'] = 400;
echo json_encode($return);
}
}
public function getPurchaseHTML()
{
return View::getSmarty()->fetch('user/bitpayx.tpl');
}
public function getReturnHTML($request, $response, $args)
{
$pid = $_GET['merchantTradeNo'];
$p = Paylist::where('tradeno', '=', $pid)->first();
$money = $p->total;
if ($p->status === 1) {
$success = 1;
} else {
$data = $this->query($pid);
$isPaid = $data !== null && $data['order'] !== null && $data['order']['status'] !== null && $data['order']['status'] === 'PAID';
// file_put_contents(BASE_PATH.'/bitpay_return.log', $pid . " " . $data ."\r\n". $isPaid . "\r\n", FILE_APPEND);
if ($isPaid) {
$this->postPayment($pid, 'BitPayX');
$success = 1;
} else {
$success = 0;
}
}
return View::getSmarty()->assign('money', $money)->assign('success', $success)->fetch('user/pay_success.tpl');
}
public function getStatus($request, $response, $args)
{
$return = [];
$p = Paylist::where('tradeno', $_POST['pid'])->first();
$return['ret'] = 1;
$return['result'] = $p->status;
// file_put_contents(BASE_PATH.'/bitpay_status_success.log', json_encode($return)."\r\n", FILE_APPEND);
return json_encode($return);
}
}

@ -0,0 +1,161 @@
<?php
/**
* Created by PhpStorm.
* User: tonyzou
* Author:
* Date: 2018/9/24
* Time: 下午4:01
*/
/**
* Made By Leo
* 黛米付接口
* 2.1.4版本
* 适用于 V1 API 黛米付面板V1
* copyright all rights reserved
*/
namespace App\Services\Gateway;
use App\Services\View;
use App\Services\Auth;
use App\Services\Config;
use App\Models\Paylist;
class DoiAMPay extends AbstractPayment
{
public function getPurchaseHTML()
{
return View::getSmarty()->assign('enabled', Config::get('doiampay')['enabled'])->fetch('user/doiam.tpl');
}
public function notify($request, $response, $args)
{
$order_data = $_POST;
$status = $order_data['status']; //获取传递过来的交易状态
$invoiceid = $order_data['out_trade_no']; //订单号
$transid = $order_data['trade_no']; //转账交易号
$amount = $order_data['money']; //获取递过来的总价格
if (!DoiAM::checksign($_POST, Config::get('doiampay')['mchdata'][$args['type']]['token'])) {
return json_encode(array('errcode' => 2333));
}
if ($status == 'success') {
$this->postPayment($invoiceid, '黛米付' . ['wepay' => '(微信)', 'qqpay' => '(QQ支付)', 'alipay' => '(支付宝)'][$args['type']]);
return json_encode(['errcode' => 0]);
}
return 1;
}
public function purchase($request, $response, $args)
{
$type = $request->getParam('type');
$price = $request->getParam('price');
if (Config::get('doiampay')['enabled'][$type] == 0) {
return json_encode(['errcode' => -1, 'errmsg' => '非法的支付方式.']);
}
if ($price <= 0) {
return json_encode(['errcode' => -1, 'errmsg' => '非法的金额.']);
}
$user = Auth::getUser();
$settings = Config::get('doiampay')['mchdata'][$type];
$pl = new Paylist();
$pl->userid = $user->id;
$pl->total = $price;
$pl->tradeno = self::generateGuid();
$pl->save();
$data = [
'trade' => $pl->tradeno,
'price' => $price,
'phone' => $settings['phone'],
'mchid' => $settings['mchid'],
'subject' => Config::get('appName') . '充值' . $price . '元',
'body' => Config::get('appName') . '充值' . $price . '元',
'type' => 'Mod',
];
$data = DoiAM::sign($data, $settings['token']);
$ret = DoiAM::post('https://api.daimiyun.cn/v2/' . $type . '/create', $data);
$result = json_decode($ret, true);
if ($result && $result['errcode'] == 0) {
$result['pid'] = $pl->tradeno;
return json_encode($result);
}
return json_encode([
'errcode' => -1,
'errmsg' => '接口调用失败!' . $ret,
]);
}
public function getReturnHTML($request, $response, $args)
{
$money = $_GET['money'];
echo "您已经成功支付 $money 元,正在跳转..";
echo <<<HTML
<script>
location.href="/user/code";
</script>
HTML;
}
public function getStatus($request, $response, $args)
{
$p = Paylist::where('tradeno', $_POST['pid'])->first();
$return['ret'] = 1;
$return['result'] = $p->status;
return json_encode($return);
}
}
class DoiAM
{
public static function sort(&$array)
{
ksort($array);
}
public static function getsign($array, $key)
{
unset($array['sign']);
self::sort($array);
$sss = http_build_query($array);
$sign = hash('sha256', $sss . $key);
$sign = sha1($sign . hash('sha256', $key));
return $sign;
}
public static function sign($array, $key)
{
$array['sign'] = self::getSign($array, $key);
return $array;
}
public static function checksign($array, $key)
{
$new = $array;
$new = self::sign($new, $key);
if (!isset($array['sign'])) {
return false;
}
return $array['sign'] == $new['sign'];
}
public static function post($url, $data = null)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
if (!empty($data)) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
}

@ -64,7 +64,7 @@ class PaymentWall extends AbstractPayment
$Payback->save();
}
echo 'OK'; // Paymentwall expects response to be OK, otherwise the pingback will be resent
if (Config::get('enable_donate') == true) {
if (Config::get('enable_donate') == 'true') {
if ($user->is_hide == 1) {
Telegram::Send('姐姐姐姐,一位不愿透露姓名的大老爷给我们捐了 ' . $codeq->number . ' 元呢~');
} else {

@ -1,139 +0,0 @@
<?php
namespace App\Services\Gateway;
use App\Services\Auth;
use App\Models\Paylist;
class TomatoPay extends AbstractPayment
{
public function purchase($request, $response, $args)
{
$type = $request->getParsedBodyParam('type');
$price = $request->getParsedBodyParam('price');
if ($price <= 0) {
return $response->write(json_encode(['errcode' => -1, 'errmsg' => "非法的金额."]));
}
$user = Auth::getUser();
$settings = $_ENV['tomatopay'][$type];
$pl = new Paylist();
$pl->userid = $user->id;
$pl->total = $price;
$pl->tradeno = self::generateGuid();
$pl->save();
$fqaccount = $settings['account'];
$fqkey = $settings['token'];
$fqmchid = $settings['mchid'];
$fqtrade = $pl->tradeno;
$fqcny = $price;
$signs = md5(
'mchid=' . $fqmchid . '&account=' . $fqaccount . '&cny=' . $fqcny . '&type=1&trade=' . $fqtrade . $fqkey
);
$url = 'https://b.fanqieui.com/gateways/' . $type . '.php?account='
. $fqaccount . '&mchid=' . $fqmchid . '&type=1'
. '&trade=' . $fqtrade . '&cny=' . $fqcny . '&signs=' . $signs;
$result = "<script language='javascript' type='text/javascript'>window.location.href='" . $url . "';</script>";
return $response->write(json_encode(['code' => $result, 'errcode' => 0, 'pid' => $pl->id]));
}
public function notify($request, $response, $args)
{
$type = $args['type'];
$settings = $_ENV['tomatopay'][$type];
$order_data = $request->getParsedBody();
$signs = $order_data['sign'];
unset($order_data['sign']);
$security = $order_data;
$o = '';
foreach ($security as $k => $v) {
$o .= "$k=" . urlencode($v) . "&";
}
$sign = md5(substr($o, 0, -1) . $settings['token']);
if ($sign == $signs) {
$this->postPayment($order_data['out_trade_no'], "在线支付");
return $response->write('success');
} else {
return $response->write('failed');
}
}
public function getPurchaseHTML()
{
return '
<div class="card-inner">
<p class="card-heading">充值</p>
<h5>支付方式:</h5>
<h5 style="color:red">推荐使用支付宝支付,更快到账!</h5>
<br/>
<nav class="tab-nav margin-top-no">
<ul class="nav nav-list">
<li>
<a class="waves-attach waves-effect type active" data-toggle="tab" data-pay="alipay"><img src="/images/alipay.jpg" height="50px"></img></a>
</li>
<li>
<a class="waves-attach waves-effect type" data-toggle="tab" data-pay="wxpay"><img src="/images/weixin.jpg" height="50px"></img></a>
</li>
</ul>
<div class="tab-nav-indicator"></div>
</nav>
<div class="form-group form-group-label">
<label class="floating-label" for="amount">金额</label>
<input class="form-control" id="amount" type="text">
</div>
</div>
<div class="card-action">
<div class="card-action-btn pull-left">
<button class="btn btn-flat waves-attach" id="tomato_pay" ><span class="icon">check</span>&nbsp;充值</NOtton>
</div>
</div>
<script>
var type = "wxpay";
var type = "alipay";
var pid = 0;
$(".type").click(function(){
type = $(this).data("pay");
});
$("#tomato_pay").click(function(){
var price = parseFloat($("#amount").val());
console.log("将要使用"+type+"方法充值"+price+"元")
if(isNaN(price)){
$("#result").modal();
$("#msg").html("非法的金额!");
}
$.ajax({
\'url\':"/user/payment/purchase",
\'data\':{
\'price\':price,
\'type\':type,
},
\'dataType\':\'json\',
\'type\':"POST",
success:function(data){
console.log(data);
if(data.errcode==-1){
$("#result").modal();
$("#msg").html(data.errmsg);
}
if(data.errcode==0){
pid = data.pid;
if(type=="wxpay"){
$("#result").modal();
$("#msg").html("正在跳转到微信..."+data.code);
}else if(type=="alipay"){
$("#result").modal();
$("#msg").html("正在跳转到支付宝..."+data.code);
}
}
}
});
setTimeout(f, 1000);
});
</script>
';
}
}

@ -0,0 +1,211 @@
<?php
/**
* Created by PhpStorm.
* User: tonyzou
* Date: 2018/9/28
* Time: 9:08 PM
*/
namespace App\Services\Gateway;
use App\Services\View;
use App\Services\Auth;
use App\Services\Config;
use App\Models\Paylist;
class TrimePay extends AbstractPayment
{
private $appSecret;
private $gatewayUri;
/**
* 签名初始化
* @param merKey 签名密钥
*/
public function __construct($appSecret)
{
$this->appSecret = $appSecret;
$this->gatewayUri = 'https://api.Trimepay.com/gateway/';
}
/**
* @name 准备签名/验签字符串
*/
public function prepareSign($data)
{
ksort($data);
return http_build_query($data);
}
/**
* @name 生成签名
* @param sourceData
* @return 签名数据
*/
public function sign($data)
{
return strtolower(md5(md5($data) . $this->appSecret));
}
/*
* @name 验证签名
* @param signData 签名数据
* @param sourceData 原数据
* @return
*/
public function verify($data, $signature)
{
$mySign = $this->sign($data);
return $mySign === $signature;
}
public function post($data, $type = 'pay')
{
if ($type == 'pay') {
$this->gatewayUri .= 'pay/go';
} elseif ($type == 'refund') {
$this->gatewayUri .= 'refund/go';
} elseif ($type == 'pre') {
$this->gatewayUri .= 'pay/pre';
} else {
$this->gatewayUri .= 'query/go';
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $this->gatewayUri);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$data = curl_exec($curl);
curl_close($curl);
return $data;
}
public function purchase($request, $response, $args)
{
$price = $request->getParam('price');
$type = $request->getParam('type');
if ($price <= 0) {
return json_encode(['code' => -1, 'errmsg' => '非法的金额.']);
}
$user = Auth::getUser();
$pl = new Paylist();
$pl->userid = $user->id;
$pl->total = $price;
$pl->tradeno = self::generateGuid();
$pl->save();
$data['appId'] = Config::get('trimepay_appid');
$data['payType'] = $type;
$data['merchantTradeNo'] = $pl->tradeno;
$data['totalFee'] = (float)$price * 100;
$data['notifyUrl'] = Config::get('baseUrl') . '/payment/notify';
$data['returnUrl'] = Config::get('baseUrl') . '/user/payment/return';
$params = $this->prepareSign($data);
$data['sign'] = $this->sign($params);
switch ($type) {
case ('WEPAY_JSAPI'):
$result = json_decode($this->post($data, $type = 'pre'), true);
break;
default:
$result = json_decode($this->post($data), true);
}
$result['pid'] = $pl->tradeno;
return json_encode($result);
}
public function query($tradeNo)
{
$data['appId'] = Config::get('trimepay_appid');
$data['merchantTradeNo'] = $tradeNo;
$params = $this->prepareSign($data);
$data['sign'] = $this->sign($params);
return json_decode($this->post($data, $type = 'query'), true);
}
public function notify($request, $response, $args)
{
$data = array();
$data['payStatus'] = $request->getParam('payStatus');
$data['payFee'] = $request->getParam('payFee');
$data['callbackTradeNo'] = $request->getParam('callbackTradeNo');
$data['payType'] = $request->getParam('payType');
$data['merchantTradeNo'] = $request->getParam('merchantTradeNo');
//file_put_contents(BASE_PATH.'/storage/trimepay_notify.log', json_encode($data)."\r\n", FILE_APPEND);
// 准备待签名数据
$str_to_sign = $this->prepareSign($data);
// 验证签名
$resultVerify = $this->verify($str_to_sign, $request->getParam('sign'));
if ($resultVerify) {
//file_put_contents('./trimepay_notify_success.log', json_encode($data)."\r\n", FILE_APPEND);
$this->postPayment($data['merchantTradeNo'], 'TrimePay');
echo 'SUCCESS';
} else {
echo 'FAIL';
}
}
public function refund($merchantTradeNo)
{
$data['appId'] = Config::get('trimepay_appid');
$data['merchantTradeNo'] = $merchantTradeNo;
$params = $this->prepareSign($data);
$data['sign'] = $this->sign($params);
return $this->post($data, 'refund');
}
public function getPurchaseHTML()
{
return View::getSmarty()->fetch('user/trimepay.tpl');
}
public function getReturnHTML($request, $response, $args)
{
$pid = $_GET['merchantTradeNo'];
$p = Paylist::where('tradeno', '=', $pid)->first();
$money = $p->total;
if ($p->status == 1) {
$success = 1;
} else {
$data = array();
$data['payStatus'] = $request->getParam('payStatus');
$data['payFee'] = $request->getParam('payFee');
$data['callbackTradeNo'] = $request->getParam('callbackTradeNo');
$data['payType'] = $request->getParam('payType');
$data['merchantTradeNo'] = $request->getParam('merchantTradeNo');
// 准备待签名数据
$str_to_sign = $this->prepareSign($data);
// 验证签名
$resultVerify = $this->verify($str_to_sign, $request->getParam('sign'));
if ($resultVerify) {
$this->postPayment($data['merchantTradeNo'], 'TrimePay');
$success = 1;
} else {
$success = 0;
}
}
return View::getSmarty()->assign('money', $money)->assign('success', $success)->fetch('user/pay_success.tpl');
}
public function getStatus($request, $response, $args)
{
$return = [];
$p = Paylist::where('tradeno', $_POST['pid'])->first();
$return['ret'] = 1;
$return['result'] = $p->status;
return json_encode($return);
}
}

@ -21,7 +21,7 @@ class Smtp extends Base
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = $this->config['username']; // SMTP username
$mail->Password = $this->config['passsword']; // SMTP password
if ($_ENV['smtp_ssl'] == true) {
if (Config::get('smtp_ssl') == 'true') {
$mail->SMTPSecure = (Config::get('smtp_port') == '587' ? 'tls' : 'ssl'); // Enable TLS encryption, `ssl` also accepted
}
$mail->Port = $this->config['port']; // TCP port to connect to

@ -9,7 +9,7 @@
namespace App\Services;
use App\Services\Gateway\{
AopF2F, Codepay, PaymentWall, ChenPay, SPay, PAYJS, YftPay, BitPayX
AopF2F, Codepay, DoiAMPay, PaymentWall, ChenPay, SPay, TrimePay, PAYJS, YftPay
};
class Payment
@ -20,6 +20,8 @@ class Payment
switch ($method) {
case ('codepay'):
return new Codepay();
case ('doiampay'):
return new DoiAMPay();
case ('paymentwall'):
return new PaymentWall();
case ('spay'):
@ -28,8 +30,8 @@ class Payment
return new AopF2F();
case ('chenAlipay'):
return new ChenPay();
case ('bitpayx'):
return new BitPayX(Config::get('bitpay_secret'));
case ('trimepay'):
return new TrimePay(Config::get('trimepay_secret'));
case ('payjs'):
return new PAYJS(Config::get('payjs_key'));
case ('yftpay'):

@ -0,0 +1,39 @@
<?php
namespace App\Services;
use Slim\App;
use Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware;
/***
* The slim documents: http://www.slimframework.com/docs/objects/router.html
*/
class Slim
{
public $app;
public function newApp()
{
// config
$debug = false;
if (defined('DEBUG')) {
$debug = true;
}
// Make a Slim App
$app = new App([
'settings' => [
'debug' => $debug,
'whoops.editor' => 'sublime',
'displayErrorDetails' => $debug
]
]);
$app->add(new WhoopsMiddleware());
$this->app = $app;
}
public function run()
{
$this->app->run();
}
}

@ -0,0 +1,14 @@
<?php
namespace App\Services\Token;
use App\Models\User;
abstract class Base
{
abstract public function store($token, User $user, $expireTime);
abstract public function delete($token);
abstract public function get($token);
}

@ -0,0 +1,49 @@
<?php
namespace App\Services\Token;
use App\Models\User;
use App\Models\Token as TokenModel;
use Illuminate\Database\Eloquent\ModelNotFoundException;
class DB extends Base
{
public function store($tokenStr, User $user, $expireTime)
{
$token = new TokenModel();
$token->token = $tokenStr;
$token->user_id = $user->id;
$token->create_time = time();
$token->expire_time = $expireTime;
if ($token->save()) {
return true;
}
return false;
}
public function delete($token)
{
$token = TokenModel::where('token', $token)->first();
if ($token == null) {
return false;
}
$token->delete();
return true;
}
public function get($token)
{
try {
$tokenModel = TokenModel::where('token', $token)->firstOrFail();
} catch (ModelNotFoundException $e) {
return null;
}
$token = new Token();
$token->token = $tokenModel->token;
$token->userId = $tokenModel->user_id;
$token->createTime = $tokenModel->create_time;
$token->expireTime = $tokenModel->expire_time;
return $token;
}
}

@ -0,0 +1,60 @@
<?php
namespace App\Services\Token;
use App\Models\User;
use App\Services\Aws\Factory;
class Dynamodb extends Base
{
protected $client;
protected $tableName = 'token';
public function __construct()
{
$this->client = Factory::createDynamodb();
$this->tableName = 'token';
}
public function store($token, User $user, $expireTime)
{
$result = $this->client->putItem(array(
'TableName' => $this->tableName,
'Item' => array(
'token' => array('S' => $token),
'user_id' => array('N' => (string)$user->id),
'create_time' => array('N' => (string)time()),
'expire_time' => array('N' => (string)$expireTime)
)
));
return true;
}
public function delete($token)
{
$this->client->deleteItem(array(
'TableName' => $this->tableName,
'Key' => array(
'token' => array('S' => $token),
)
));
}
public function get($token)
{
$result = $this->client->getItem(array(
'ConsistentRead' => true,
'TableName' => $this->tableName,
'Key' => array(
'token' => array('S' => $token),
)
));
$token = new Token();
$token->token = $result['Item']['token']['S'];
$token->userId = $result['Item']['user_id']['N'];
$token->createTime = $result['Item']['create_time']['N'];
$token->expireTime = $result['Item']['expire_time']['N'];
return $token;
}
}

@ -0,0 +1,12 @@
<?php
namespace App\Services\Token;
class Token
{
public $token;
public $userId;
public $createTime;
public $expireTime;
}

@ -1,18 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: rico93
* Date: 2019/1/26
* Time: 12:22
*/
namespace App\Utils;
use RemotelyLiving\PHPDNS\Resolvers\GoogleDNS;
class DNSoverHTTPS
{
public static function gethostbyName($hostname){
$resolver = new GoogleDNS();
return $resolver->getARecords($hostname)->pickFirst()->toArray()["IPAddress"];
}
}

@ -0,0 +1,73 @@
<?php
namespace App\Utils;
use App\Models\User;
use App\Services\Config;
class Discord
{
public static function set()
{
$loop = \React\EventLoop\Factory::create();
$client = new \CharlotteDunois\Yasmin\Client(array(), $loop);
$client->on('error', static function ($error) {
echo $error . PHP_EOL;
});
$client->on('ready', static function () use ($client) {
echo 'Logged in as ' . $client->user->tag . ' created on ' . $client->user->createdAt->format('d.m.Y H:i:s') . PHP_EOL;
});
$client->on('message', static function ($message) {
//echo 'Received Message from '.$message->author->tag.' in '.($message->channel->type === 'text' ? 'channel #'.$message->channel->name : 'DM').' with '.$message->attachments->count().' attachment(s) and '.\count($message->embeds).' embed(s)'.PHP_EOL;
if (strpos($message->content, '!bind') === 0) {
bindQR($client, $message);
} elseif (strpos($message->content, '!checkin') === 0) {
checkin($client, $message);
} elseif (strpos($message->content, '!traffic') === 0) {
traffic($client, $message);
}
});
$client->login(Config::get('discord_token'))->done();
$loop->run();
echo('<27><><EFBFBD>óɹ<C3B3><C9B9><EFBFBD>' . PHP_EOL);
}
public static function bindQR($client, $message)
{
$message->channel->send('<27><><EFBFBD>ڽ<EFBFBD><DABD>룬<EFBFBD><EBA3AC><EFBFBD>Ժ󡣡<D4BA><F3A1A3A1><EFBFBD>');
$attachments = $message->attachments->toArray();
reset($attachments);
$qrcode_text = QRcode::decod(current($attachments)->url);
if ($qrcode_text == null) {
$message->channel->send('<27><><EFBFBD><EFBFBD>ʧ<EFBFBD><CAA7>');
return;
}
if (strpos($qrcode_text, 'mod://bind/') === 0 && strlen($qrcode_text) == 27) {
$uid = TelegramSessionManager::verify_bind_session(substr($qrcode_text, 11));
if ($uid == 0) {
$message->channel->send('<27><>ʧ<EFBFBD>ܣ<EFBFBD><DCA3><EFBFBD>ά<EFBFBD><CEAC><EFBFBD><EFBFBD>Ч<EFBFBD><D0A7>' . substr($qrcode_text, 11) . '<27><>ά<EFBFBD><CEAC><EFBFBD><EFBFBD><EFBFBD>Ч<EFBFBD><D0A7>Ϊ10<31><30><EFBFBD>ӣ<EFBFBD><D3A3>볢<EFBFBD><EBB3A2>ˢ<EFBFBD><CBA2><EFBFBD><EFBFBD>վ<EFBFBD>ġ<EFBFBD><C4A1><EFBFBD><EFBFBD>ϱ༭<CFB1><E0BCAD>ҳ<EFBFBD><D2B3><EFBFBD>Ը<EFBFBD><D4B8><EFBFBD>ά<EFBFBD><CEAC>');
return;
}
$user = User::where('id', $uid)->first();
$user->discord = $message->author->id;
$user->im_type = 5;
$user->im_value = $message->author->username;
$user->save();
$reply['message'] = '<27>󶨳ɹ<F3B6A8B3><C9B9><EFBFBD><EFBFBD><EFBFBD><EFBFBD>䣺' . $user->email;
}
$message->channel->send('δ֪<CEB4><D6AA><EFBFBD>ݶ<EFBFBD>ά<EFBFBD><CEAC>');
}
public static function checkin($client, $message)
{
}
public static function traffic($client, $message)
{
}
}

@ -0,0 +1,179 @@
<?php
namespace App\Utils;
/**
* Made By Leo
* 黛米付接口
* 2.1.4版本
* 适用于 V1 API 黛米付面板V1
* copyright all rights reserved
*/
use App\Services\View;
use App\Services\Auth;
use App\Services\Config;
use App\Models\User;
use App\Models\Code;
use App\Models\Paylist;
use App\Models\Payback;
class DoiAMPay
{
public static function render()
{
return View::getSmarty()->assign('enabled', Config::get('doiampay')['enabled'])->fetch('user/doiam.tpl');
}
public function handle($request, $response, $args)
{
$type = $request->getParam('type');
$price = $request->getParam('price');
if (Config::get('doiampay')['enabled'][$type] == 0) {
return json_encode(['errcode' => -1, 'errmsg' => '非法的支付方式.']);
}
if ($price <= 0) {
return json_encode(['errcode' => -1, 'errmsg' => '非法的金额.']);
}
$user = Auth::getUser();
$settings = Config::get('doiampay')['mchdata'][$type];
$pl = new Paylist();
$pl->userid = $user->id;
$pl->total = $price;
$pl->save();
$data = [
'trade' => $pl->id,
'price' => $price,
'phone' => $settings['phone'],
'mchid' => $settings['mchid'],
'subject' => Config::get('appName') . '充值' . $price . '元',
'body' => Config::get('appName') . '充值' . $price . '元',
'type' => 'Mod',
];
$data = DoiAM::sign($data, $settings['token']);
$ret = DoiAM::post('https://api.daimiyun.cn/v2/' . $type . '/create', $data);
$result = json_decode($ret, true);
if ($result and $result['errcode'] == 0) {
$result['pid'] = $pl->id;
return json_Encode($result);
}
return json_encode([
'errcode' => -1,
'errmsg' => '接口调用失败!' . $ret,
]);
}
public function status($request, $response, $args)
{
return json_encode(Paylist::find($_POST['pid']));
}
public function handle_return($request, $response, $args)
{
$money = $_GET['money'];
echo "您已经成功支付 $money 元,正在跳转..";
echo <<<HTML
<script>
location.href="/user/code";
</script>
HTML;
}
public function handle_callback($request, $response, $args)
{
$order_data = $_POST;
$status = $order_data['status']; //获取传递过来的交易状态
$invoiceid = $order_data['out_trade_no']; //订单号
$transid = $order_data['trade_no']; //转账交易号
$amount = $order_data['money']; //获取递过来的总价格
if (!DoiAM::checksign($_POST, Config::get('doiampay')['mchdata'][$args['type']]['token'])) {
return json_encode(array('errcode' => 2333));
}
if ($status == 'success') {
$p = Paylist::find($invoiceid);
if ($p->status == 1) {
return json_encode(['errcode' => 0]);
}
$p->status = 1;
$p->save();
$user = User::find($p->userid);
$user->money += $p->total;
$user->save();
$codeq = new Code();
$codeq->code = ['wepay' => '微信', 'qqpay' => 'QQ支付', 'alipay' => '支付宝'][$args['type']] . '充值';
$codeq->isused = 1;
$codeq->type = -1;
$codeq->number = $p->total;
$codeq->usedatetime = date('Y-m-d H:i:s');
$codeq->userid = $user->id;
$codeq->save();
if ($user->ref_by != '' && $user->ref_by != 0 && $user->ref_by != null) {
$gift_user = User::where('id', '=', $user->ref_by)->first();
$gift_user->money += ($codeq->number * (Config::get('code_payback') / 100));
$gift_user->save();
$Payback = new Payback();
$Payback->total = $codeq->number;
$Payback->userid = $user->id;
$Payback->ref_by = $user->ref_by;
$Payback->ref_get = $codeq->number * (Config::get('code_payback') / 100);
$Payback->datetime = time();
$Payback->save();
}
return json_encode(['errcode' => 0]);
}
return '';
}
}
class DoiAM
{
public static function sort(&$array)
{
ksort($array);
}
public static function getsign($array, $key)
{
unset($array['sign']);
self::sort($array);
$sss = http_build_query($array);
$sign = hash('sha256', $sss . $key);
$sign = sha1($sign . hash('sha256', $key));
return $sign;
}
public static function sign($array, $key)
{
$array['sign'] = self::getSign($array, $key);
return $array;
}
public static function checksign($array, $key)
{
$new = $array;
$new = self::sign($new, $key);
if (!isset($array['sign'])) {
return false;
}
return $array['sign'] == $new['sign'];
}
public static function post($url, $data = null)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
if (!empty($data)) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
}

@ -0,0 +1,420 @@
<?php
namespace App\Utils;
/**
* Socket communication class.
*
* Originally designed for use with DirectAdmin's API, this class will fill any HTTP socket need.
*
* Very, very basic usage:
* $Socket = new HTTPSocket;
* echo $Socket->get('http://user:pass@somesite.com/somedir/some.file?query=string&this=that');
*
* @author Phi1 'l0rdphi1' Stier <l0rdphi1@liquenox.net>
* @package HTTPSocket
* @version 2.7.2
* 2.7.2
* added x-use-https header check
* added max number of location redirects
* added custom settable message if x-use-https is found, so users can be told where to set their scripts
* if a redirect host is https, add ssl:// to remote_host
* 2.7.1
* added isset to headers['location'], line 306
*/
class HTTPSocket
{
public $version = '2.7.2';
/* all vars are private except $error, $query_cache, and $doFollowLocationHeader */
public $method = 'GET';
public $remote_host;
public $remote_port;
public $remote_uname;
public $remote_passwd;
public $result;
public $result_header;
public $result_body;
public $result_status_code;
public $lastTransferSpeed;
public $bind_host;
public $error = array();
public $warn = array();
public $query_cache = array();
public $doFollowLocationHeader = true;
public $redirectURL;
public $max_redirects = 5;
public $ssl_setting_message = 'DirectAdmin appears to be using SSL. Change your script to connect to ssl://';
public $extra_headers = array();
/**
* Create server "connection".
*
*/
public function connect($host, $port = '')
{
if (!is_numeric($port)) {
$port = 80;
}
$this->remote_host = $host;
$this->remote_port = $port;
}
public function bind($ip = '')
{
if ($ip == '') {
$ip = $_SERVER['SERVER_ADDR'];
}
$this->bind_host = $ip;
}
/**
* Change the method being used to communicate.
*
* @param string|null request method. supports GET, POST, and HEAD. default is GET
*/
public function set_method($method = 'GET')
{
$this->method = strtoupper($method);
}
/**
* Specify a username and password.
*
* @param string|null username. defualt is null
* @param string|null password. defualt is null
*/
public function set_login($uname = '', $passwd = '')
{
if ($uname !== '') {
$this->remote_uname = $uname;
}
if ($passwd !== '') {
$this->remote_passwd = $passwd;
}
}
/**
* Query the server
*
* @param string containing properly formatted server API. See DA API docs and examples. Http:// URLs O.K. too.
* @param string|array query to pass to url
* @param int if connection KB/s drops below value here, will drop connection
*/
public function query($request, $content = '', $doSpeedCheck = 0)
{
$this->error = $this->warn = array();
$this->result_status_code = null;
// is our request a http:// ... ?
if (preg_match('!^http://!i', $request) || preg_match('!^https://!i', $request)) {
$location = parse_url($request);
if (preg_match('!^https://!i', $request)) {
$this->connect('ssl://' . $location['host'], $location['port']);
} else {
$this->connect($location['host'], $location['port']);
}
$this->set_login($location['user'], $location['pass']);
$request = $location['path'];
$content = $location['query'];
if ($request == '') {
$request = '/';
}
}
$array_headers = array(
'User-Agent' => "HTTPSocket/$this->version",
'Host' => $this->remote_port == 80 ? $this->remote_host : "$this->remote_host:$this->remote_port",
'Accept' => '*/*',
'Connection' => 'Close');
foreach ($this->extra_headers as $key => $value) {
$array_headers[$key] = $value;
}
$this->result = $this->result_header = $this->result_body = '';
// was content sent as an array? if so, turn it into a string
if (is_array($content)) {
$pairs = array();
foreach ($content as $key => $value) {
$pairs[] = "$key=" . urlencode($value);
}
$content = implode('&', $pairs);
unset($pairs);
}
$OK = true;
// instance connection
if ($this->bind_host) {
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($socket, $this->bind_host);
if (!@socket_connect($socket, $this->remote_host, $this->remote_port)) {
$OK = false;
}
} else {
$socket = @fsockopen($this->remote_host, $this->remote_port, $sock_errno, $sock_errstr, 10);
}
if (!$socket || !$OK) {
$this->error[] = "Can't create socket connection to $this->remote_host:$this->remote_port.";
return 0;
}
// if we have a username and password, add the header
if (isset($this->remote_uname, $this->remote_passwd)) {
$array_headers['Authorization'] = 'Basic ' . base64_encode("$this->remote_uname:$this->remote_passwd");
}
// for DA skins: if $this->remote_passwd is NULL, try to use the login key system
if (isset($this->remote_uname) && $this->remote_passwd == null) {
$array_headers['Cookie'] = "session={$_SERVER['SESSION_ID']}; key={$_SERVER['SESSION_KEY']}";
}
// if method is POST, add content length & type headers
if ($this->method == 'POST') {
$array_headers['Content-type'] = 'application/x-www-form-urlencoded';
$array_headers['Content-length'] = strlen($content);
} // else method is GET or HEAD. we don't support anything else right now.
elseif ($content) {
$request .= "?$content";
}
// prepare query
$query = "$this->method $request HTTP/1.0\r\n";
foreach ($array_headers as $key => $value) {
$query .= "$key: $value\r\n";
}
$query .= "\r\n";
// if POST we need to append our content
if ($this->method == 'POST' && $content) {
$query .= "$content\r\n\r\n";
}
// query connection
if ($this->bind_host) {
socket_write($socket, $query);
// now load results
while ($out = socket_read($socket, 2048)) {
$this->result .= $out;
}
} else {
fwrite($socket, $query, strlen($query));
// now load results
$this->lastTransferSpeed = 0;
$status = stream_get_meta_data($socket);
$startTime = time();
$length = 0;
$prevSecond = 0;
while (!feof($socket) && !$status['timed_out']) {
$chunk = fgets($socket, 1024);
$length += strlen($chunk);
$this->result .= $chunk;
$elapsedTime = time() - $startTime;
if ($elapsedTime > 0) {
$this->lastTransferSpeed = ($length / 1024) / $elapsedTime;
}
if ($doSpeedCheck > 0 && $elapsedTime > 5 && $this->lastTransferSpeed < $doSpeedCheck) {
$this->warn[] = 'kB/s for last 5 seconds is below 50 kB/s (~' . (($length / 1024) / $elapsedTime) . '), dropping connection...';
$this->result_status_code = 503;
break;
}
}
if ($this->lastTransferSpeed == 0) {
$this->lastTransferSpeed = $length / 1024;
}
}
[$this->result_header, $this->result_body] = preg_split("/\r\n\r\n/", $this->result, 2);
if ($this->bind_host) {
socket_close($socket);
} else {
fclose($socket);
}
$this->query_cache[] = $query;
$headers = $this->fetch_header();
// what return status did we get?
if (!$this->result_status_code) {
preg_match("#HTTP/1\.. (\d+)#", $headers[0], $matches);
$this->result_status_code = $matches[1];
}
// did we get the full file?
if (!empty($headers['content-length']) && $headers['content-length'] != strlen($this->result_body)) {
$this->result_status_code = 206;
}
// now, if we're being passed a location header, should we follow it?
if ($this->doFollowLocationHeader) {
//dont bother if we didn't even setup the script correctly
if (isset($headers['x-use-https']) && $headers['x-use-https'] == 'yes') {
die($this->ssl_setting_message);
}
if (isset($headers['location'])) {
if ($this->max_redirects <= 0) {
die('Too many redirects on: ' . $headers['location']);
}
$this->max_redirects--;
$this->redirectURL = $headers['location'];
$this->query($headers['location']);
}
}
}
public function getTransferSpeed()
{
return $this->lastTransferSpeed;
}
/**
* The quick way to get a URL's content :)
*
* @param string URL
* @param boolean return as array? (like PHP's file() command)
* @return string result body
*/
public function get($location, $asArray = false)
{
$this->query($location);
if ($this->get_status_code() == 200) {
if ($asArray) {
return explode("\n", $this->fetch_body());
}
return $this->fetch_body();
}
return false;
}
/**
* Returns the last status code.
* 200 = OK;
* 403 = FORBIDDEN;
* etc.
*
* @return int status code
*/
public function get_status_code()
{
return $this->result_status_code;
}
/**
* Adds a header, sent with the next query.
*
* @param string header name
* @param string header value
*/
public function add_header($key, $value)
{
$this->extra_headers[$key] = $value;
}
/**
* Clears any extra headers.
*
*/
public function clear_headers()
{
$this->extra_headers = array();
}
/**
* Return the result of a query.
*
* @return string result
*/
public function fetch_result()
{
return $this->result;
}
/**
* Return the header of result (stuff before body).
*
* @param string (optional) header to return
* @return array result header
*/
public function fetch_header($header = '')
{
$array_headers = preg_split("/\r\n/", $this->result_header);
$array_return = array(0 => $array_headers[0]);
unset($array_headers[0]);
foreach ($array_headers as $pair) {
[$key, $value] = explode(': ', $pair, 2);
$array_return[strtolower($key)] = $value;
}
if ($header != '') {
return $array_return[strtolower($header)];
}
return $array_return;
}
/**
* Return the body of result (stuff after header).
*
* @return string result body
*/
public function fetch_body()
{
return $this->result_body;
}
/**
* Return parsed body in array format.
*
* @return array result parsed
*/
public function fetch_parsed_body()
{
parse_str($this->result_body, $x);
return $x;
}
/**
* Set a specifc message on how to change the SSL setting, in the event that it's not set correctly.
*/
public function set_ssl_setting_message($str)
{
$this->ssl_setting_message = $str;
}
}

@ -0,0 +1,18 @@
<?php
namespace App\Utils;
class Helper
{
public static function getParam($request, $queryString): ?string
{
return $request->getQueryParams()[$queryString] ?? null;
}
public static function getData($request, $name)
{
return $request->getParsedBody()[$name];
}
}

@ -0,0 +1,9 @@
<?php
namespace App\Utils;
class Pay
{
}

@ -1,27 +1,88 @@
<?php
declare(strict_types=1);
namespace App\Utils;
use App\Services\Config;
use Zxing\QrReader;
use ZBarCodeImage;
use ZBarCodeScanner;
class QRcode
{
/**
* Decode QR code
*
* @param string $source QR code source url/path
*
* @return string|null Decoded string, null for empty
*/
public static function decode(string $source)
public static function decode($url)
{
$img = file_get_contents($source);
$qrcode = new QrReader($img, QrReader::SOURCE_TYPE_BLOB);
$text = $qrcode->text();
if ($text == false || $text == '') {
switch (Config::get('qrcode')) {
case 'phpzbar':
return self::phpzbar_decode($url);
case 'online':
return self::online_decode($url);
case 'zxing_local':
return self::zxing_local_decode($url);
default:
return self::zxing_decode($url);
}
}
public static function online_decode($url)
{
$data = array();
$data['fileurl'] = $url;
$param = http_build_query($data, '', '&');
$sock = new HTTPSocket();
$sock->connect('api.qrserver.com', 80);
$sock->set_method('GET');
$sock->query('/v1/read-qr-code/', $param);
$raw_text = $sock->fetch_body();
$result_array = json_decode($raw_text, true);
if (isset($result_array[0])) {
return $result_array[0]['symbol'][0]['data'];
}
return null;
}
public static function phpzbar_decode($url)
{
$filepath = BASE_PATH . '/storage/' . time() . random_int(1, 100) . '.png';
$img = file_get_contents($url);
file_put_contents($filepath, $img);
/* Create new image object */
$image = new ZBarCodeImage($filepath);
/* Create a barcode scanner */
$scanner = new ZBarCodeScanner();
/* Scan the image */
$barcode = $scanner->scan($image);
unlink($filepath);
return ($barcode[0]['data'] ?? null);
}
public static function zxing_local_decode($url)
{
$filepath = BASE_PATH . '/storage/' . time() . random_int(1, 100) . '.png';
$img = file_get_contents($url);
file_put_contents($filepath, $img);
$qrcode = new QrReader($filepath);
$text = $qrcode->text(); //return decoded text from QR Code
unlink($filepath);
if ($text == null || $text == '') {
return null;
}
return $text;
}
public static function zxing_decode($url)
{
$raw_text = file_get_contents('https://zxing.org/w/decode?u=' . urlencode($url));
return Tools::get_middle_text($raw_text, '<tr><td>Raw text</td><td><pre>', '</pre></td></tr><tr><td>Raw bytes</td><td><pre>');
}
}

@ -17,7 +17,7 @@ class Radius
*/
public static function Add($user, $pwd)
{
if (Config::get('enable_radius') == true) {
if (Config::get('enable_radius') == 'true') {
$email = $user->email;
$email = str_replace(array('@', '.'), '', $email);
@ -51,7 +51,7 @@ class Radius
public static function Delete($email)
{
if (Config::get('enable_radius') == true) {
if (Config::get('enable_radius') == 'true') {
$email = str_replace(array('@', '.'), '', $email);
@ -66,7 +66,7 @@ class Radius
public static function ChangeUserName($origin_email, $new_email, $passwd)
{
if (Config::get('enable_radius') == true) {
if (Config::get('enable_radius') == 'true') {
$email1 = str_replace(array('@', '.'), '', $origin_email);
$email2 = str_replace(array('@', '.'), '', $new_email);
@ -105,7 +105,7 @@ class Radius
public static function AddNas($ip, $name)
{
if (Config::get('enable_radius') == true) {
if (Config::get('enable_radius') == 'true') {
$exists = RadiusNas::where('shortname', $ip)->first();
if ($exists == null) {
$exists = new RadiusNas();
@ -121,7 +121,7 @@ class Radius
public static function DelNas($ip)
{
if (Config::get('enable_radius') == true) {
if (Config::get('enable_radius') == 'true') {
RadiusNas::where('shortname', $ip)->delete();
}
}

@ -0,0 +1,11 @@
<?php
namespace App\Utils;
class Response
{
public static function redirect($response, $to)
{
return $response->withStatus(302)->withHeader('Location', $to);
}
}

@ -14,7 +14,7 @@ class Telegram
*/
public static function Send($messageText)
{
if (Config::get('enable_telegram') == true) {
if (Config::get('enable_telegram') == 'true') {
$bot = new BotApi(Config::get('telegram_token'));
try {
$bot->sendMessage(Config::get('telegram_chatid'), $messageText);
@ -27,7 +27,7 @@ class Telegram
public static function SendMarkdown($messageText)
{
if (Config::get('enable_telegram') == true) {
if (Config::get('enable_telegram') == 'true') {
$bot = new BotApi(Config::get('telegram_token'));
try {
$bot->sendMessage(Config::get('telegram_chatid'), $messageText, 'Markdown');

@ -1,471 +0,0 @@
<?php
namespace App\Utils\Telegram;
use App\Models\{LoginIp, Node, Ip, Payback, UserSubscribeLog};
use App\Services\Config;
use App\Utils\{Tools, QQWry};
class Callback
{
public static function CallbackQueryMethod($user, $bot, $Callback)
{
// 触发用户
$SendUser = [
'id' => $Callback->getFrom()->getId(),
'name' => $Callback->getFrom()->getFirstName() . ' ' . $Callback->getFrom()->getLastName(),
'username' => $Callback->getFrom()->getUsername(),
];
// 触发源消息发送时间
$MessageSendTime = $Callback->getMessage()->getDate();
// 消息是否可编辑
$AllowEditMessage = (time() < $MessageSendTime + 172800
? true
: false);
$Data = [
'CallbackData' => $Callback->getData(), // 回调数据
'ChatID' => $Callback->getMessage()->getChat()->getId(), // 消息会话 ID
'MessageID' => $Callback->getMessage()->getMessageId(), // 触发源信息 ID
'AllowEditMessage' => $AllowEditMessage, // 消息是否可编辑
];
if ($Data['ChatID'] < 0) {
// 群组
if (Config::get('new_telegram_group_quiet') === true) {
// 群组中不回应
return;
}
}
switch (true) {
case (strpos($Data['CallbackData'], 'user.') === 0 && $user != null):
// 用户相关
self::UserHandler($user, $bot, $Callback, $Data, $SendUser);
break;
default:
// 回调数据处理
self::CallbackDataHandler($user, $bot, $Callback, $Data, $SendUser);
break;
}
}
/**
*
* 回调数据处理
*
*/
public static function CallbackDataHandler($user, $bot, $Callback, $Data, $SendUser)
{
switch ($Data['CallbackData']) {
case 'index':
// 主菜单
$temp = Reply::getInlinekeyboard($user, 'index');
$sendMessage = [
'chat_id' => $Data['ChatID'],
'message_id' => $Data['MessageID'],
'text' => $temp['text'],
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => json_encode(
[
'inline_keyboard' => $temp['keyboard']
]
),
];
break;
case 'general.pricing':
// 产品介绍
$sendMessage = [
'chat_id' => $Data['ChatID'],
'message_id' => $Data['MessageID'],
'text' => '产品介绍',
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => json_encode(
[
'inline_keyboard' => [
Reply::getInlinekeyboard()
]
]
),
];
break;
case 'general.terms':
// 服务条款
$sendMessage = [
'chat_id' => $Data['ChatID'],
'message_id' => $Data['MessageID'],
'text' => '服务条款',
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => json_encode(
[
'inline_keyboard' => [
Reply::getInlinekeyboard()
]
]
),
];
break;
default:
$sendMessage = [
'chat_id' => $Data['ChatID'],
'text' => '发生错误.',
'parse_mode' => 'Markdown',
];
$Data['AllowEditMessage'] = false;
break;
}
if ($Data['AllowEditMessage']) {
// 消息可编辑
Process::SendPost('editMessageText', $sendMessage);
return;
}
$bot->sendMessage($sendMessage);
}
/**
*
* 用户相关回调数据处理
*
*/
public static function UserHandler($user, $bot, $Callback, $Data, $SendUser)
{
$CallbackDataExplode = explode('.', $Data['CallbackData']);
$op_1 = $CallbackDataExplode[1];
switch ($op_1) {
case 'edit':
// 资料编辑
$op_2 = $CallbackDataExplode[2];
switch ($op_2) {
case 'update_link':
// 重置订阅链接
$temp = Reply::getInlinekeyboard($user, 'index');
$user->clean_link();
$sendMessage = [
'chat_id' => $Data['ChatID'],
'message_id' => $Data['MessageID'],
'text' => '订阅链接重置成功.',
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => json_encode(
[
'inline_keyboard' => $temp['keyboard']
]
),
];
break;
case 'update_passwd':
// 重置链接密码
$temp = Reply::getInlinekeyboard($user, 'index');
$user->passwd = Tools::genRandomChar(8);
if ($user->save()) {
$sendMessage = [
'chat_id' => $Data['ChatID'],
'message_id' => $Data['MessageID'],
'text' => '连接密码更新成功.' . PHP_EOL . '新密码为:' . $user->passwd,
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => json_encode(
[
'inline_keyboard' => $temp['keyboard']
]
),
];
} else {
$sendMessage = [
'chat_id' => $Data['ChatID'],
'message_id' => $Data['MessageID'],
'text' => '出现错误,连接密码更新失败,请联系管理员.',
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => json_encode(
[
'inline_keyboard' => $temp['keyboard']
]
),
];
}
break;
case 'encrypt':
// 加密方式更改
$sendMessage = [
'chat_id' => $Data['ChatID'],
'message_id' => $Data['MessageID'],
'text' => 'ing.',
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => null
];
break;
case 'protocol':
// 协议更改
$sendMessage = [
'chat_id' => $Data['ChatID'],
'message_id' => $Data['MessageID'],
'text' => 'ing.',
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => null
];
break;
case 'obfs':
// 混淆更改
$sendMessage = [
'chat_id' => $Data['ChatID'],
'message_id' => $Data['MessageID'],
'text' => 'ing.',
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => null
];
break;
case 'sendemail':
// 每日邮件设置更改
$keyboard = [
[
[
'text' => '更改开启/关闭',
'callback_data' => 'user.edit.sendemail.update'
]
],
Reply::getInlinekeyboard()
];
$op_3 = $CallbackDataExplode[3];
switch ($op_3) {
case 'update':
$user->sendDailyMail = ($user->sendDailyMail == 0 ? 1 : 0);
if ($user->save()) {
$text = '设置更改成功.';
} else {
$text = '发生错误.';
}
break;
default:
$text = '每日邮件接收当前设置为:';
$text .= ($user->sendDailyMail == 0 ? '不发送' : '发送');
break;
}
$sendMessage = [
'chat_id' => $Data['ChatID'],
'message_id' => $Data['MessageID'],
'text' => $text,
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => json_encode(
[
'inline_keyboard' => $keyboard
]
),
];
break;
default:
$temp = Reply::getInlinekeyboard($user, 'user.edit');
$sendMessage = [
'chat_id' => $Data['ChatID'],
'message_id' => $Data['MessageID'],
'text' => '您可在此编辑您的资料或连接信息:',
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => json_encode(
[
'inline_keyboard' => $temp['keyboard']
]
),
];
break;
}
break;
case 'subscribe':
// 订阅中心
$sendMessage = [
'chat_id' => $Data['ChatID'],
'message_id' => $Data['MessageID'],
'text' => 'ing.',
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => null
];
break;
case 'invite':
// 分享计划
$sendMessage = [
'chat_id' => $Data['ChatID'],
'message_id' => $Data['MessageID'],
'text' => 'ing.',
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => null
];
break;
default:
// 用户中心
$op_2 = $CallbackDataExplode[2];
switch ($op_2) {
case 'login_log':
// 登录记录
$iplocation = new QQWry();
$totallogin = LoginIp::where('userid', '=', $user->id)->where('type', '=', 0)->orderBy('datetime', 'desc')->take(10)->get();
$userloginip = [];
foreach ($totallogin as $single) {
$location = $iplocation->getlocation($single->ip);
$loginiplocation = iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']);
if (!in_array($loginiplocation, $userloginip)) {
$userloginip[] = $loginiplocation;
}
}
$text = ('以下是您最近 10 次的登录位置:' .
PHP_EOL .
PHP_EOL .
implode('、', $userloginip));
$sendMessage = [
'chat_id' => $Data['ChatID'],
'message_id' => $Data['MessageID'],
'text' => $text,
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => json_encode(
[
'inline_keyboard' => [
Reply::getInlinekeyboard()
]
]
),
];
break;
case 'usage_log':
// 使用记录
$iplocation = new QQWry();
$total = Ip::where('datetime', '>=', time() - 300)->where('userid', '=', $user->id)->get();
$userip = [];
foreach ($total as $single) {
$single->ip = Tools::getRealIp($single->ip);
$is_node = Node::where('node_ip', $single->ip)->first();
if ($is_node) {
continue;
}
$location = $iplocation->getlocation($single->ip);
$userip[$single->ip] = '「' . $single->ip . '」 ' . iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']);
}
$text = ('以下是您最近 5 分钟的使用 IP:' .
PHP_EOL .
PHP_EOL .
implode(PHP_EOL, $userip));
$sendMessage = [
'chat_id' => $Data['ChatID'],
'message_id' => $Data['MessageID'],
'text' => $text,
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => json_encode(
[
'inline_keyboard' => [
Reply::getInlinekeyboard()
]
]
),
];
break;
case 'rebate_log':
// 返利记录
$paybacks = Payback::where('ref_by', $user->id)->orderBy('datetime', 'desc')->take(10)->get();
$temp = [];
foreach ($paybacks as $payback) {
$temp[] = '`#' . $payback->id . ':' . ($payback->user() != null ? $payback->user()->user_name : '已注销') . ':' . $payback->ref_get . ' 元`';
}
$text = ('以下是您最近 10 条返利记录:' .
PHP_EOL .
PHP_EOL .
implode(PHP_EOL, $temp));
$sendMessage = [
'chat_id' => $Data['ChatID'],
'message_id' => $Data['MessageID'],
'text' => $text,
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => json_encode(
[
'inline_keyboard' => [
Reply::getInlinekeyboard()
]
]
),
];
break;
case 'subscribe_log':
// 订阅记录
$iplocation = new QQWry();
$logs = UserSubscribeLog::orderBy('id', 'desc')->where('user_id', $user->id)->take(10)->get();
$temp = [];
foreach ($logs as $log) {
$location = $iplocation->getlocation($log->request_ip);
$temp[] = '`' . $log->request_time . ' 在 <' . $log->request_ip . '> ' . iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']) . '访问了 ' . $log->subscribe_type . ' 订阅`';
}
$text = ('以下是您最近 10 条订阅记录:' .
PHP_EOL .
PHP_EOL .
implode(PHP_EOL . PHP_EOL, $temp));
$sendMessage = [
'chat_id' => $Data['ChatID'],
'message_id' => $Data['MessageID'],
'text' => $text,
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => json_encode(
[
'inline_keyboard' => [
Reply::getInlinekeyboard()
]
]
),
];
break;
default:
$temp = Reply::getInlinekeyboard($user, 'user.index');
$sendMessage = [
'chat_id' => $Data['ChatID'],
'message_id' => $Data['MessageID'],
'text' => $temp['text'],
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => json_encode(
[
'inline_keyboard' => $temp['keyboard']
]
),
];
break;
}
break;
}
if ($Data['AllowEditMessage']) {
// 消息可编辑
Process::SendPost('editMessageText', $sendMessage);
return;
}
$bot->sendMessage($sendMessage);
}
}

@ -1,84 +0,0 @@
<?php
namespace App\Utils\Telegram\Commands;
use App\Models\User;
use App\Services\Config;
use Telegram\Bot\Actions;
use Telegram\Bot\Commands\Command;
/**
* Class CheckinCommand.
*/
class CheckinCommand extends Command
{
/**
* @var string Command Name
*/
protected $name = 'checkin';
/**
* @var string Command Description
*/
protected $description = '';
/**
* {@inheritdoc}
*/
public function handle($arguments)
{
$Update = $this->getUpdate();
$Message = $Update->getMessage();
// 消息会话 ID
$ChatID = $Message->getChat()->getId();
if ($ChatID < 0) {
// 群组
if (Config::get('new_telegram_group_quiet') === true) {
// 群组中不回应
return;
}
if ($ChatID != Config::get('new_telegram_group_chatid')) {
// 非我方群组
return;
}
}
// 发送 '输入中' 会话状态
$this->replyWithChatAction(['action' => Actions::TYPING]);
// 触发用户
$SendUser = [
'id' => $Message->getFrom()->getId(),
'name' => $Message->getFrom()->getFirstName() . ' ' . $Message->getFrom()->getLastName(),
'username' => $Message->getFrom()->getUsername(),
];
$User = User::where('telegram_id', $SendUser['id'])->first();
if ($User == null) {
// 回送信息
$this->replyWithMessage(
[
'text' => '您未绑定本站账号,您可以进入网站的 **资料编辑**,在右下方绑定您的账号.',
'parse_mode' => 'Markdown',
]
);
return;
}
$checkin = $User->checkin();
$text = [
$checkin['msg']
];
// 回送信息
$this->replyWithMessage(
[
'text' => implode(PHP_EOL, $text),
'parse_mode' => 'Markdown',
]
);
}
}

@ -1,87 +0,0 @@
<?php
namespace App\Utils\Telegram\Commands;
use App\Models\User;
use App\Services\Config;
use App\Utils\Telegram\{Process, Reply};
use Telegram\Bot\Actions;
use Telegram\Bot\Commands\Command;
/**
* Class HelpCommand.
*/
class HelpCommand extends Command
{
/**
* @var string Command Name
*/
protected $name = 'help';
/**
* @var string Command Description
*/
protected $description = '菜单';
/**
* {@inheritdoc}
*/
public function handle($arguments)
{
$Update = $this->getUpdate();
$Message = $Update->getMessage();
// 消息会话 ID
$ChatID = $Message->getChat()->getId();
if ($ChatID > 0) {
// 私人会话
// 发送 '输入中' 会话状态
$this->replyWithChatAction(['action' => Actions::TYPING]);
// 触发用户
$SendUser = [
'id' => $Message->getFrom()->getId(),
'name' => $Message->getFrom()->getFirstName() . ' ' . $Message->getFrom()->getLastName(),
'username' => $Message->getFrom()->getUsername(),
];
$user = Process::getUser($SendUser['id']);
$reply = Reply::getInlinekeyboard($user, 'index');
// 回送信息
$this->replyWithMessage(
[
'text' => $reply['text'],
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => json_encode(
[
'inline_keyboard' => $reply['keyboard']
]
),
]
);
} else {
// 群组
if (Config::get('new_telegram_group_quiet') === true || strpos($Message->getText(), '/' . $this->name) !== 0) {
// 群组中不回应
return;
}
// 发送 '输入中' 会话状态
$this->replyWithChatAction(['action' => Actions::TYPING]);
// 回送信息
$this->replyWithMessage(
[
'text' => '喵?',
]
);
}
}
}

@ -1,120 +0,0 @@
<?php
namespace App\Utils\Telegram\Commands;
use App\Models\User;
use App\Services\Config;
use Telegram\Bot\Actions;
use Telegram\Bot\Commands\Command;
/**
* Class MyCommand.
*/
class MyCommand extends Command
{
/**
* @var string Command Name
*/
protected $name = 'my';
/**
* @var string Command Description
*/
protected $description = '';
/**
* {@inheritdoc}
*/
public function handle($arguments)
{
$Update = $this->getUpdate();
$Message = $Update->getMessage();
// 消息 ID
$MessageID = $Message->getMessageId();
// 消息会话 ID
$ChatID = $Message->getChat()->getId();
if ($ChatID < 0) {
// 群组
if (Config::get('new_telegram_group_quiet') === true) {
// 群组中不回应
return;
}
if ($ChatID != Config::get('new_telegram_group_chatid')) {
// 非我方群组
return;
}
}
// 发送 '输入中' 会话状态
$this->replyWithChatAction(['action' => Actions::TYPING]);
// 触发用户
$SendUser = [
'id' => $Message->getFrom()->getId(),
'name' => $Message->getFrom()->getFirstName() . ' ' . $Message->getFrom()->getLastName(),
'username' => $Message->getFrom()->getUsername(),
];
$User = User::where('telegram_id', $SendUser['id'])->first();
if ($User == null) {
// 回送信息
$this->replyWithMessage(
[
'text' => '您未绑定本站账号,您可以进入网站的 **资料编辑**,在右下方绑定您的账号.',
'parse_mode' => 'Markdown',
]
);
return;
}
if ($ChatID > 0) {
// 私人
self::Privacy($User, $SendUser, $ChatID, $Message, $MessageID);
} else {
// 群组
self::Group($User, $SendUser, $ChatID, $Message, $MessageID);
}
}
public function Group($User, $SendUser, $ChatID, $Message, $MessageID)
{
$text = [
'您当前的流量状况:',
'',
'今日已使用[' . $User->TodayusedTrafficPercent(). '%]:' . $User->TodayusedTraffic(),
'之前已使用[' . $User->LastusedTrafficPercent(). '%]:' . $User->LastusedTraffic(),
'流量约剩余[' . $User->unusedTrafficPercent(). '%]:' . $User->unusedTraffic(),
];
// 回送信息
$this->replyWithMessage(
[
'text' => implode(PHP_EOL, $text),
'parse_mode' => 'Markdown',
'reply_to_message_id' => $MessageID,
]
);
}
public function Privacy($User, $SendUser, $ChatID, $Message, $MessageID)
{
$text = [
'您当前的流量状况:',
'',
'今日已使用[' . $User->TodayusedTrafficPercent(). '%]:' . $User->TodayusedTraffic(),
'之前已使用[' . $User->LastusedTrafficPercent(). '%]:' . $User->LastusedTraffic(),
'流量约剩余[' . $User->unusedTrafficPercent(). '%]:' . $User->unusedTraffic(),
];
// 回送信息
$this->replyWithMessage(
[
'text' => implode(PHP_EOL, $text),
'parse_mode' => 'Markdown',
]
);
}
}

@ -1,84 +0,0 @@
<?php
namespace App\Utils\Telegram\Commands;
use App\Services\Config;
use Telegram\Bot\Actions;
use Telegram\Bot\Commands\Command;
/**
* Class PingCommand.
*/
class PingCommand extends Command
{
/**
* @var string Command Name
*/
protected $name = 'ping';
/**
* @var string Command Description
*/
protected $description = '';
/**
* {@inheritdoc}
*/
public function handle($arguments)
{
$Update = $this->getUpdate();
$Message = $Update->getMessage();
// 消息会话 ID
$ChatID = $Message->getChat()->getId();
if ($ChatID > 0) {
// 私人会话
// 发送 '输入中' 会话状态
$this->replyWithChatAction(['action' => Actions::TYPING]);
// 触发用户
$SendUser = [
'id' => $Message->getFrom()->getId(),
'name' => $Message->getFrom()->getFirstName() . ' ' . $Message->getFrom()->getLastName(),
'username' => $Message->getFrom()->getUsername(),
];
$text = [
'Pong!',
'这个群组的 ID 是 ' . $ChatID . '.',
];
// 回送信息
$this->replyWithMessage(
[
'text' => implode(PHP_EOL ,$text),
'parse_mode' => 'Markdown',
]
);
} else {
// 群组
if (Config::get('new_telegram_group_quiet') === true) {
// 群组中不回应
return;
}
// 发送 '输入中' 会话状态
$this->replyWithChatAction(['action' => Actions::TYPING]);
$text = [
'Pong!',
'这个群组的 ID 是 ' . $ChatID . '.',
];
// 回送信息
$this->replyWithMessage(
[
'text' => implode(PHP_EOL ,$text),
]
);
}
}
}

@ -1,102 +0,0 @@
<?php
namespace App\Utils\Telegram\Commands;
use App\Models\User;
use App\Services\Config;
use App\Utils\TelegramSessionManager;
use Telegram\Bot\Actions;
use Telegram\Bot\Commands\Command;
/**
* Class StratCommand.
*/
class StartCommand extends Command
{
/**
* @var string Command Name
*/
protected $name = 'start';
/**
* @var string Command Description
*/
protected $description = 'Start Command to get you started';
/**
* {@inheritdoc}
*/
public function handle($arguments)
{
$Update = $this->getUpdate();
$Message = $Update->getMessage();
// 消息会话 ID
$ChatID = $Message->getChat()->getId();
if ($ChatID > 0) {
// 私人会话
// 发送 '输入中' 会话状态
$this->replyWithChatAction(['action' => Actions::TYPING]);
// 触发用户
$SendUser = [
'id' => $Message->getFrom()->getId(),
'name' => $Message->getFrom()->getFirstName() . ' ' . $Message->getFrom()->getLastName(),
'username' => $Message->getFrom()->getUsername(),
];
// 消息内容
$MessageText = trim($arguments);
if ($MessageText != '') {
$BindCode = $MessageText;
if (strlen($BindCode) == 16) {
$Uid = TelegramSessionManager::verify_bind_session($BindCode);
if ($Uid == 0) {
$text = '绑定失败了呢,经检查发现:【' . $BindCode . '】的有效期为 10 分钟,您可以在我们网站上的 **资料编辑** 页面刷新后重试.';
} else {
$BinsUser = User::where('id', $Uid)->first();
$BinsUser->telegram_id = $SendUser['id'];
$BinsUser->im_type = 4;
$BinsUser->im_value = $SendUser['username'];
$BinsUser->save();
if ($BinsUser->is_admin >= 1) {
$text = '尊敬的**管理员**您好,恭喜绑定成功。' . PHP_EOL .'当前绑定邮箱为:' . $BinsUser->email;
} else {
if ($BinsUser->class >= 1) {
$text = '尊敬的 **VIP ' . $BinsUser->class . '** 用户您好.' . PHP_EOL . '恭喜您绑定成功,当前绑定邮箱为:' . $BinsUser->email;
} else {
$text = '绑定成功了,您的邮箱为:' . $BinsUser->email;
}
}
}
}
// 回送信息
$this->replyWithMessage(
[
'text' => $text,
'parse_mode' => 'Markdown',
]
);
}
// 触发 /help
$this->triggerCommand('help');
} else {
// 群组
if (Config::get('new_telegram_group_quiet') === true) {
// 群组中不回应
return;
}
// 发送 '输入中' 会话状态
$this->replyWithChatAction(['action' => Actions::TYPING]);
// 回送信息
$this->replyWithMessage(
[
'text' => '喵喵喵.',
]
);
}
}
}

@ -1,99 +0,0 @@
<?php
namespace App\Utils\Telegram\Commands;
use App\Models\User;
use App\Services\Config;
use Telegram\Bot\Actions;
use Telegram\Bot\Commands\Command;
/**
* Class UnbindCommand.
*/
class UnbindCommand extends Command
{
/**
* @var string Command Name
*/
protected $name = 'unbind';
/**
* @var string Command Description
*/
protected $description = '';
/**
* {@inheritdoc}
*/
public function handle($arguments)
{
$Update = $this->getUpdate();
$Message = $Update->getMessage();
// 消息 ID
$MessageID = $Message->getMessageId();
// 消息会话 ID
$ChatID = $Message->getChat()->getId();
// 触发用户
$SendUser = [
'id' => $Message->getFrom()->getId(),
'name' => $Message->getFrom()->getFirstName() . ' ' . $Message->getFrom()->getLastName(),
'username' => $Message->getFrom()->getUsername(),
];
$User = User::where('telegram_id', $SendUser['id'])->first();
if ($ChatID > 0) {
// 私人
// 发送 '输入中' 会话状态
$this->replyWithChatAction(['action' => Actions::TYPING]);
if ($User == null) {
// 回送信息
$this->replyWithMessage(
[
'text' => '您未绑定本站账号,您可以进入网站的 **资料编辑**,在右下方绑定您的账号.',
'parse_mode' => 'Markdown',
]
);
return;
}
// 消息内容
$MessageText = trim($arguments);
if ($MessageText == $User->email) {
$User->telegram_id = 0;
if ($User->save()) {
$text = '解绑成功.';
} else {
$text = '解绑失败.';
}
// 回送信息
$this->replyWithMessage(
[
'text' => $text,
'parse_mode' => 'Markdown',
]
);
return;
}
$text = '发送 **/unbind 账户邮箱** 进行解绑.';
if ($MessageText != '') {
$text = '键入的 Email 地址与您的账户不匹配.';
}
// 回送信息
$this->replyWithMessage(
[
'text' => $text,
'parse_mode' => 'Markdown',
]
);
}
}
}

@ -1,53 +0,0 @@
<?php
namespace App\Utils\Telegram;
use App\Utils\TelegramSessionManager;
class Message
{
public static function MessageMethod($user, $bot, $Message)
{
// 触发用户
$SendUser = [
'id' => $Message->getFrom()->getId(),
'name' => $Message->getFrom()->getFirstName() . ' ' . $Message->getFrom()->getLastName(),
'username' => $Message->getFrom()->getUsername(),
];
// 消息会话 ID
$ChatID = $Message->getChat()->getId();
// 消息内容
$MessageData = $Message->getText();
if ($MessageData != null) {
$MessageData = trim($MessageData);
if (is_numeric($MessageData) && strlen($MessageData) == 6) {
if ($user != null) {
$uid = TelegramSessionManager::verify_login_number($MessageData, $user->id);
if ($uid != 0) {
$bot->sendMessage(
[
'chat_id' => $ChatID,
'text' => '登录验证成功,邮箱:' . $user->email,
]
);
} else {
$bot->sendMessage(
[
'chat_id' => $ChatID,
'text' => '登录验证失败,数字无效',
]
);
}
}
}
return;
}
// // 图片内容
// $PhotoData = $Message->getPhoto();
// if ($PhotoData != null) {
// }
}
}

@ -1,68 +0,0 @@
<?php
namespace App\Utils\Telegram;
use App\Models\User;
use App\Services\Config;
use Telegram\Bot\Api;
use Exception;
class Process
{
public static function index()
{
try {
$bot = new Api(Config::get('new_telegram_token'));
$bot->addCommands(
[
Commands\HelpCommand::class,
Commands\StartCommand::class,
Commands\PingCommand::class,
Commands\CheckinCommand::class,
Commands\MyCommand::class,
Commands\UnbindCommand::class,
]
);
$update = $bot->commandsHandler(true);
if ($update->getCallbackQuery() !== null) {
$id = $update->getCallbackQuery()->getFrom()->getId();
$user = self::getUser($id);
Callback::CallbackQueryMethod($user, $bot, $update->getCallbackQuery());
}
if ($update->getMessage() !== null) {
$id = $update->getMessage()->getFrom()->getId();
$user = self::getUser($id);
Message::MessageMethod($user, $bot, $update->getMessage());
}
} catch (Exception $e) {
$e->getMessage();
}
}
public static function getUser($telegram_id)
{
return User::where('telegram_id', $telegram_id)->first();
}
/**
* Sends a POST request to Telegram Bot API.
* 伪异步,无结果返回.
*
* @param array $params
*
* @return string
*/
public static function SendPost($Method, $Params)
{
$URL = 'https://api.telegram.org/bot' . Config::get('new_telegram_token') . '/' . $Method;
$POSTData = json_encode($Params);
$C = curl_init();
curl_setopt($C, CURLOPT_URL, $URL);
curl_setopt($C, CURLOPT_POST, 1);
curl_setopt($C, CURLOPT_HTTPHEADER, ['Content-Type:application/json; charset=utf-8']);
curl_setopt($C, CURLOPT_POSTFIELDS, $POSTData);
curl_setopt($C, CURLOPT_TIMEOUT, 1);
curl_exec($C);
curl_close($C);
}
}

@ -1,172 +0,0 @@
<?php
namespace App\Utils\Telegram;
class Reply
{
public static function getInlinekeyboard($user = null, $type = null)
{
$back = [
[
'text' => '回主菜单',
'callback_data' => 'index'
]
];
if ($type === null) return $back;
switch ($type) {
case 'index':
// 主菜单
$notLogin = [
[
'text' => '产品介绍',
'callback_data' => 'general.pricing'
],
[
'text' => '服务条款',
'callback_data' => 'general.terms'
]
];
$isLogin = [
[
[
'text' => '用户中心',
'callback_data' => 'user.index'
],
[
'text' => '资料编辑',
'callback_data' => 'user.edit'
],
],
[
[
'text' => '订阅中心',
'callback_data' => 'user.subscribe'
],
[
'text' => '分享计划',
'callback_data' => 'user.invite'
],
],
];
if ($user != null) {
if ($user->isAdmin()) {
$text = '尊敬的管理员您好:';
} else {
if ($user->class > 0) {
$text = '尊敬的 VIP ' . $user->class . '您好:';
} else {
$text = '尊敬的用户您好:';
}
}
$return = [
'text' => $text,
'keyboard' => $isLogin,
];
} else {
$text = '游客您好,以下是 BOT 菜单:' . PHP_EOL . PHP_EOL . '本站用户请前往用户中心进行 Telegram 绑定操作.';
$return = [
'text' => $text,
'keyboard' => [
$notLogin,
],
];
}
break;
case 'user.index':
// 用户中心
if ($user->class > 0) {
$text = '尊敬的 VIP ' . $user->class . ' 您好:';
} else {
$text = '尊敬的用户您好:';
}
$keyboard = [
[
[
'text' => '登录记录',
'callback_data' => 'user.index.login_log'
],
[
'text' => '使用记录',
'callback_data' => 'user.index.usage_log'
],
],
[
[
'text' => '返利记录',
'callback_data' => 'user.index.rebate_log'
],
[
'text' => '订阅记录',
'callback_data' => 'user.index.subscribe_log'
],
],
$back
];
$text .= (PHP_EOL . PHP_EOL .
'当前余额:' . $user->money .
PHP_EOL .
'在线设备:' . ($user->node_connector != 0 ? $user->online_ip_count() . ' / ' . $user->node_connector : $user->online_ip_count() . ' / 不限制') .
PHP_EOL .
'端口速率:' . ($user->node_speedlimit != 0 ? $user->node_speedlimit . 'Mbps' : '无限制') .
PHP_EOL .
'上次使用:' . $user->lastSsTime() .
PHP_EOL .
'过期时间:' . $user->class_expire);
$return = [
'text' => $text,
'keyboard' => $keyboard,
];
break;
case 'user.edit':
// 资料编辑
if ($user->class > 0) {
$text = '尊敬的 VIP ' . $user->class . '您好:';
} else {
$text = '尊敬的用户您好:';
}
$keyboard = [
[
[
'text' => '重置订阅链接',
'callback_data' => 'user.edit.update_link'
],
[
'text' => '重置链接密码',
'callback_data' => 'user.edit.update_passwd'
]
],
[
[
'text' => '更改加密方式',
'callback_data' => 'user.edit.encrypt'
],
[
'text' => '更改协议类型',
'callback_data' => 'user.edit.protocol'
]
],
[
[
'text' => '更改混淆类型',
'callback_data' => 'user.edit.obfs'
],
],
[
[
'text' => '每日邮件接收',
'callback_data' => 'user.edit.sendemail'
],
],
$back
];
$return = [
'text' => $text,
'keyboard' => $keyboard,
];
break;
}
return $return;
}
}

@ -13,17 +13,11 @@ class TelegramProcess
{
private static $all_rss = [
'clean_link' => '重置订阅',
'?sub=1' => 'SSR订阅',
'?sub=3' => 'V2ray订阅',
'?sub=5' => 'Shadowrocket',
'?sub=4' => 'Kitsunebi or V2rayNG or BifrostV',
'?surge=2' => 'Surge 2.x',
'?surge=3' => 'Surge 3.x',
'?ssd=1' => 'SSD',
'?clash=1' => 'Clash',
'?surfboard=1' => 'Surfboard',
'?quantumult=3' => 'Quantumult(完整配置)'
];
'?mu=0' => 'SSR普通订阅',
'?mu=1' => 'SSR单端口订阅',
'?mu=3' => 'SS/SSD订阅',
'?mu=2' => 'V2ray订阅',
'?mu=4' => 'Clash订阅'];
private static function callback_bind_method($bot, $callback)
{
@ -34,26 +28,7 @@ class TelegramProcess
$reply_message = '???';
if ($user != null) {
switch (true) {
case $callback_data == '?quantumult=3':
$ssr_sub_token = LinkController::GenerateSSRSubCode($user->id, 0);
$baseUrl = Config::get('baseUrl');
$keyboard = new \TelegramBot\Api\Types\Inline\InlineKeyboardMarkup(
[
[
['text' => '点击跳转', 'url' => $baseUrl . '/jump.html?url=quantumult://settings?configuration=clipboard']
]
]
);
$bot->sendMessage($user->get_user_attributes('telegram_id'), "两种方法:\n 方法一:\n 1.点击打开以下配置文件\n 2. 选择分享->拷贝到\"Quantumult\"\n 3.选择更新配置\n 方法二:\n 1.长按配置文件\n 2. 选择更多->分享->拷贝\n 3.点击跳转APP,到Quan中保存", $parseMode = null, $disablePreview = false, $replyToMessageId = null, $replyMarkup = $keyboard);
$filepath = '/tmp/tg_' . $ssr_sub_token . '.txt';
$fh = fopen($filepath, 'w+');
$string = LinkController::GetQuantumult($user, 3);
fwrite($fh, $string);
fclose($fh);
$bot->sendDocument($user->get_user_attributes('telegram_id'), new \CURLFile($filepath, '', 'quantumult_' . $ssr_sub_token . '.conf'));
unlink($filepath);
break;
case (strpos($callback_data, 'sub') or strpos($callback_data, 'surge') or strpos($callback_data, 'clash') or strpos($callback_data, 'surfboard')):
case (strpos($callback_data, 'mu')):
$ssr_sub_token = LinkController::GenerateSSRSubCode($user->id, 0);
$subUrl = Config::get('subUrl');
$reply_message = self::$all_rss[$callback_data] . ': ' . $subUrl . $ssr_sub_token . $callback_data . PHP_EOL;
@ -145,7 +120,7 @@ class TelegramProcess
/help 获取帮助信息
/rss 获取节点订阅';
if ($user == null) {
$reply['message'] .= PHP_EOL . '您未绑定本站账号,您可以进入网站的“资料编辑”,在右下方绑定您的账号';
$help_list .= PHP_EOL . '您未绑定本站账号,您可以进入网站的“资料编辑”,在右下方绑定您的账号';
}
break;
default:
@ -246,7 +221,7 @@ class TelegramProcess
}
} else {
//群组
if (Config::get('telegram_group_quiet') == true) {
if (Config::get('telegram_group_quiet') == 'true') {
return;
}
$bot->sendChatAction($message->getChat()->getId(), 'typing');
@ -282,7 +257,7 @@ class TelegramProcess
$reply['message'] = '不约,叔叔我们不约';
}
}
if ($message->getNewChatMember() != null && Config::get('enable_welcome_message') == true) {
if ($message->getNewChatMember() != null && Config::get('enable_welcome_message') == 'true') {
$reply['message'] = '欢迎 ' . $message->getNewChatMember()->getFirstName() . ' ' . $message->getNewChatMember()->getLastName();
} else {
$reply['message'] = null;

@ -280,7 +280,7 @@ class Tools
$relay_able_list = Config::getSupportParam('relay_able_protocol');
return in_array($user->protocol, $relay_able_list) || Config::get('relay_insecure_mode') == true;
return in_array($user->protocol, $relay_able_list) || Config::get('relay_insecure_mode') == 'true';
}
public static function has_conflict_rule($input_rule, $ruleset, $edit_rule_id = 0, $origin_node_id = 0, $user_id = 0)
@ -450,9 +450,9 @@ class Tools
if ($server[1] == '0' || $server[1] == '') {
$item['port'] = 443;
} else {
$item['port'] = (int) $server[1];
$item['port'] = (int)$server[1];
}
$item['aid'] = (int) $server[2];
$item['aid'] = (int)$server[2];
$item['net'] = 'tcp';
$item['type'] = 'none';
if (count($server) >= 4) {
@ -468,23 +468,18 @@ class Tools
$item['type'] = $server[4];
} elseif ($server[4] == 'ws') {
$item['net'] = 'ws';
} elseif ($server[4] == 'tls') {
$item['tls'] = 'tls';
}
}
if (count($server) >= 6 && $server[5] != '') {
if (count($server) >= 6) {
$item = array_merge($item, URL::parse_args($server[5]));
if (array_key_exists('server', $item)) {
$item['add'] = $item['server'];
unset($item['server']);
}
if (array_key_exists('outside_port', $item)) {
$item['port'] = (int) $item['outside_port'];
$item['port'] = (int)$item['outside_port'];
unset($item['outside_port']);
}
if (isset($item['inside_port'])) {
unset($item['inside_port']);
}
}
return $item;
}
@ -499,7 +494,7 @@ class Tools
{
$server = explode(';', $node);
$item = [
'host' => 'microsoft.com',
'host' => '',
'path' => '',
'net' => 'ws',
'tls' => ''
@ -508,7 +503,7 @@ class Tools
if ($server[1] == '0' || $server[1] == '') {
$item['port'] = 443;
} else {
$item['port'] = (int) $server[1];
$item['port'] = (int)$server[1];
}
if (count($server) >= 4) {
$item['net'] = $server[3];
@ -530,249 +525,19 @@ class Tools
unset($item['server']);
}
if (array_key_exists('outside_port', $item)) {
$item['port'] = (int) $item['outside_port'];
$item['port'] = (int)$item['outside_port'];
unset($item['outside_port']);
}
}
return $item;
}
public static function OutPort($server, $node_name, $mu_port)
{
$node_server = explode(';', $server);
$node_port = $mu_port;
if (strpos($node_server[1], 'port') !== false) {
$item = URL::parse_args($node_server[1]);
if (strpos($item['port'], '#') !== false) { // 端口偏移,指定端口,格式:8.8.8.8;port=80#1080
if (strpos($item['port'], '+') !== false) { // 多个单端口节点,格式:8.8.8.8;port=80#1080+443#8443
$args_explode = explode('+', $item['port']);
foreach ($args_explode as $arg) {
if ((int) substr($arg, 0, strpos($arg, '#')) == $mu_port) {
$node_port = (int) substr($arg, strpos($arg, '#') + 1);
}
}
} else {
if ((int) substr($item['port'], 0, strpos($item['port'], '#')) == $mu_port) {
$node_port = (int) substr($item['port'], strpos($item['port'], '#') + 1);
}
}
} else { // 端口偏移,偏移端口,格式:8.8.8.8;port=1000 or 8.8.8.8;port=-1000
$node_port = ($mu_port + (int) $item['port']);
}
}
return [
'name' => ($node_name . ' - ' . $node_port . ' 单端口'),
'address' => $node_server[0],
'port' => $node_port
];
}
public static function get_MuOutPortArray($server)
{
$type = 0; //偏移
$port = []; //指定
$node_server = explode(';', $server);
if (strpos($node_server[1], 'port') !== false) {
$item = URL::parse_args($node_server[1]);
if (strpos($item['port'], '#') !== false) {
if (strpos($item['port'], '+') !== false) {
$args_explode = explode('+', $item['port']);
foreach ($args_explode as $arg) {
$port[substr($arg, 0, strpos($arg, '#'))] = (int) substr($arg, strpos($arg, '#') + 1);
}
} else {
$port[substr($item['port'], 0, strpos($item['port'], '#'))] = (int) substr($item['port'], strpos($item['port'], '#') + 1);
}
} else {
$type = (int) $item['port'];
}
}
return [
'type' => $type,
'port' => $port
];
}
// 请将冷门的国家或地区放置在上方,热门的中继起源放置在下方
// 以便于兼容如:【上海 -> 美国】等节点名称
private static $emoji = [
"🇦🇷" => [
"阿根廷"
],
"🇦🇹" => [
"奥地利",
"维也纳"
],
"🇦🇺" => [
"澳大利亚",
"悉尼"
],
"🇧🇷" => [
"巴西",
"圣保罗"
],
"🇨🇦" => [
"加拿大",
"蒙特利尔",
"温哥华"
],
"🇨🇭" => [
"瑞士",
"苏黎世"
],
"🇩🇪" => [
"德国",
"法兰克福"
],
"🇫🇮" => [
"芬兰",
"赫尔辛基"
],
"🇫🇷" => [
"法国",
"巴黎"
],
"🇬🇧" => [
"英国",
"伦敦"
],
"🇮🇩" => [
"印尼",
"印度尼西亚",
"雅加达"
],
"🇮🇪" => [
"爱尔兰",
"都柏林"
],
"🇮🇳" => [
"印度",
"孟买"
],
"🇮🇹" => [
"意大利",
"米兰"
],
"🇰🇵" => [
"朝鲜"
],
"🇲🇾" => [
"马来西亚"
],
"🇳🇱" => [
"荷兰",
"阿姆斯特丹"
],
"🇵🇭" => [
"菲律宾"
],
"🇷🇴" => [
"罗马尼亚"
],
"🇷🇺" => [
"俄罗斯",
"伯力",
"莫斯科",
"圣彼得堡",
"西伯利亚",
"新西伯利亚"
],
"🇸🇬" => [
"新加坡"
],
"🇹🇭" => [
"泰国",
"曼谷"
],
"🇹🇷" => [
"土耳其",
"伊斯坦布尔"
],
"🇺🇲" => [
"美国",
"波特兰",
"俄勒冈",
"凤凰城",
"费利蒙",
"硅谷",
"拉斯维加斯",
"洛杉矶",
"圣克拉拉",
"西雅图",
"芝加哥",
"沪美"
],
"🇻🇳" => [
"越南"
],
"🇿🇦" => [
"南非"
],
"🇰🇷" => [
"韩国",
"首尔"
],
"🇲🇴" => [
"澳门"
],
"🇯🇵" => [
"日本",
"东京",
"大阪",
"埼玉",
"沪日"
],
"🇹🇼" => [
"台湾",
"台北",
"台中"
],
"🇭🇰" => [
"香港",
"深港"
],
"🇨🇳" => [
"中国",
"江苏",
"北京",
"上海",
"深圳",
"杭州",
"徐州",
"宁波",
"镇江"
]
];
public static function addEmoji($Name)
{
$done = [
'index' => -1,
'emoji' => ''
];
foreach (self::$emoji as $key => $value) {
foreach ($value as $item) {
$index = strpos($Name, $item);
if ($index !== false) {
$done['index'] = $index;
$done['emoji'] = $key;
continue 2;
}
}
}
return ($done['index'] == -1
? $Name
: ($done['emoji'] . ' ' . $Name));
}
/**
* Add files and sub-directories in a folder to zip file.
*
* @param string $folder
* @param ZipArchive $zipFile
* @param int $exclusiveLength Number of text to be exclusived from the file path.
/**
* Add files and sub-directories in a folder to zip file.
*
* @param string $folder
* @param ZipArchive $zipFile
* @param int $exclusiveLength Number of text to be exclusived from the file path.
*/
public static function folderToZip($folder, &$zipFile, $exclusiveLength)
{
@ -780,12 +545,12 @@ class Tools
while (false !== $f = readdir($handle)) {
if ($f != '.' && $f != '..') {
$filePath = "$folder/$f";
// Remove prefix from file path before add to zip.
// Remove prefix from file path before add to zip.
$localPath = substr($filePath, $exclusiveLength);
if (is_file($filePath)) {
$zipFile->addFile($filePath, $localPath);
} elseif (is_dir($filePath)) {
// Add sub-directory.
// Add sub-directory.
$zipFile->addEmptyDir($localPath);
self::folderToZip($filePath, $zipFile, $exclusiveLength);
}
@ -793,39 +558,4 @@ class Tools
}
closedir($handle);
}
/**
* 清空文件夹
*
* @param string $dirName
*/
public static function delDirAndFile($dirPath)
{
if ($handle = opendir($dirPath)){
while (false !== ($item = readdir($handle))){
if ($item != '.' && $item != '..'){
if (is_dir($dirPath . '/' . $item)){
self::delDirAndFile($dirPath . '/' . $item);
} else {
unlink($dirPath . '/' . $item);
}
}
}
closedir($handle);
}
}
/**
* 清空订阅缓存
*/
public static function delSubCache()
{
if (Config::get('enable_sub_cache') === true) {
$path = (BASE_PATH . '/storage/SubscribeCache/');
//rm -rf /home/happy/baidu/*
$a = system('rm -rf ' . $path . '*');
return ($a === false ?: true);
}
return true;
}
}

@ -8,7 +8,7 @@ class Tuling
{
public static function chat($user, $text)
{
if (Config::get('enable_tuling') == true) {
if (Config::get('enable_tuling') == 'true') {
$data = array();
$data['key'] = Config::get('tuling_apikey');
$data['userid'] = $user;

@ -7,7 +7,6 @@ use App\Models\Node;
use App\Models\Relay;
use App\Services\Config;
use App\Controllers\LinkController;
use App\Controllers\ConfController;
class URL
{
@ -59,14 +58,14 @@ class URL
return 2;
}
return 4; //SSR need origin plain
return 4;//SSR need origin plain
}
if (strpos($obfs, '_compatible') === false) {
return 1;
}
return 5; //SS need plain
return 5;//SS need plain
}
return 3;
@ -139,34 +138,30 @@ class URL
return $new_user;
}
public static function getAllItems($user, $is_mu = 0, $is_ss = 0, $emoji = 0)
public static function getAllItems($user, $is_mu = 0, $is_ss = 0)
{
$return_array = array();
if ($user->is_admin) {
$nodes = Node::where(
static function ($query) {
$query->where('sort', 0)->orwhere('sort', 10);
$query->where('sort', 0)
->orwhere('sort', 10)
->orwhere('sort', 13);
}
)
->where('type', '1')
->orderBy('name')
->get();
)->where('type', '1')->orderBy('name')->get();
} else {
$nodes = Node::where(
static function ($query) {
$query->where('sort', 0)->orwhere('sort', 10);
$query->where('sort', 0)
->orwhere('sort', 10)
->orwhere('sort', 13);
}
)
->where(
static function ($query) use ($user) {
$query->where('node_group', '=', $user->node_group)
->orWhere('node_group', '=', 0);
}
)
->where('type', '1')
->where('node_class', '<=', $user->class)
->orderBy('name')
->get();
)->where(
static function ($query) use ($user) {
$query->where('node_group', '=', $user->node_group)
->orWhere('node_group', '=', 0);
}
)->where('type', '1')->where('node_class', '<=', $user->class)->orderBy('name')->get();
}
if ($is_mu) {
if ($user->is_admin) {
@ -203,12 +198,12 @@ class URL
if (($relay_rule != null) && $relay_rule->dist_node() != null) {
$relay_rule_id = $relay_rule->id;
}
$item = self::getItem($user, $node, 0, $relay_rule_id, $is_ss, $emoji);
$item = self::getItem($user, $node, 0, $relay_rule_id, $is_ss);
if ($item != null) {
$return_array[] = $item;
}
} else {
$item = self::getItem($user, $node, 0, 0, $is_ss, $emoji);
$item = self::getItem($user, $node, 0, 0, $is_ss);
if ($item != null) {
$return_array[] = $item;
}
@ -216,18 +211,18 @@ class URL
}
if ($node->custom_rss == 1 && $node->mu_only != -1 && $is_mu != 0) {
foreach ($mu_nodes as $mu_node) {
if ($node->sort == 10) { // ss 中转
if ($node->sort == 10) {
$relay_rule_id = 0;
$relay_rule = Tools::pick_out_relay_rule($node->id, $mu_node->server, $relay_rules);
if (($relay_rule != null) && $relay_rule->dist_node() != null) {
$relay_rule_id = $relay_rule->id;
}
$item = self::getItem($user, $node, $mu_node->server, $relay_rule_id, $is_ss, $emoji);
$item = self::getItem($user, $node, $mu_node->server, $relay_rule_id, $is_ss);
if ($item != null) {
$return_array[] = $item;
}
} else {
$item = self::getItem($user, $node, $mu_node->server, 0, $is_ss, $emoji);
$item = self::getItem($user, $node, $mu_node->server, 0, $is_ss);
if ($item != null) {
$return_array[] = $item;
}
@ -235,71 +230,28 @@ class URL
}
}
}
return $return_array;
}
public static function getAllUrl($user, $is_mu, $is_ss = 0, $getV2rayPlugin = 1)
public static function getAllUrl($user, $is_mu, $is_ss = 0)
{
$return_url = '';
if (strtotime($user->expire_in) < time()) {
return $return_url;
}
$items = self::getAllItems($user, $is_mu, $is_ss);
foreach ($items as $item) {
$return_url .= self::getItemUrl($item, $is_ss) . PHP_EOL;
}
$is_mu = $is_mu == 0 ? 1 : 0;
$items = self::getAllItems($user, $is_mu, $is_ss);
foreach ($items as $item) {
$return_url .= self::getItemUrl($item, $is_ss) . PHP_EOL;
if (!$is_ss) {
$return_url .= self::getUserTraffic($user, $is_mu) . PHP_EOL;
$return_url .= self::getUserClassExpiration($user, $is_mu) . PHP_EOL;
}
return $return_url;
}
/**
* 获取全部节点 Url
*
* @param object $user 用户
* @param int $is_ss 是否 ss
* @param int $getV2rayPlugin 是否获取 V2rayPlugin 节点
* @param array $Rule 节点筛选规则
* @param bool $find 是否筛选节点
*
* @return string
*/
public static function get_NewAllUrl($user, $is_ss, $getV2rayPlugin, $Rule, $find, $emoji = 0)
{
$return_url = '';
if (strtotime($user->expire_in) < time()) {
return $return_url;
}
if ($getV2rayPlugin === 0) {
$items = array_merge(
self::getAllItems($user, 0, $is_ss, $emoji),
self::getAllItems($user, 1, $is_ss, $emoji)
);
if (Config::get('mergeSub') == 'true') {
$items = array_merge(self::getAllItems($user, 1, $is_ss), self::getAllItems($user, 0, $is_ss));
} else {
$items = array_merge(
self::getAllItems($user, 0, $is_ss, $emoji),
self::getAllItems($user, 1, $is_ss, $emoji),
self::getAllV2RayPluginItems($user, $emoji)
);
}
if ($find) {
foreach ($items as $item) {
$item = ConfController::getMatchProxy($item, $Rule);
if ($item !== null) {
$return_url .= self::getItemUrl($item, $is_ss) . PHP_EOL;
}
}
} else {
foreach ($items as $item) {
$return_url .= self::getItemUrl($item, $is_ss) . PHP_EOL;
}
$items = self::getAllItems($user, $is_mu, $is_ss);
}
foreach ($items as $item) {
$return_url .= self::getItemUrl($item, $is_ss) . PHP_EOL;
}
return $return_url;
}
@ -307,28 +259,14 @@ class URL
{
$ss_obfs_list = Config::getSupportParam('ss_obfs');
if (!$is_ss) {
$ssurl = $item['address'] . ':' . $item['port'] . ':' . $item['protocol'] .
':' . $item['method'] . ':' . $item['obfs'] . ':' .
Tools::base64_url_encode(
$item['passwd']
) . '/?obfsparam=' . Tools::base64_url_encode(
$item['obfs_param']
) . '&protoparam=' . Tools::base64_url_encode(
$item['protocol_param']
) . '&remarks=' . Tools::base64_url_encode(
$item['remark']
) . '&group=' . Tools::base64_url_encode(
$item['group']
);
$ssurl = $item['address'] . ':' . $item['port'] . ':' . $item['protocol'] . ':' . $item['method'] . ':' . $item['obfs'] . ':' . Tools::base64_url_encode($item['passwd']) . '/?obfsparam=' . Tools::base64_url_encode($item['obfs_param']) . '&protoparam=' . Tools::base64_url_encode($item['protocol_param']) . '&remarks=' . Tools::base64_url_encode($item['remark']) . '&group=' . Tools::base64_url_encode($item['group']);
return 'ssr://' . Tools::base64_url_encode($ssurl);
}
if ($is_ss == 2) {
$personal_info = $item['method'] . ':' . $item['passwd'] . '@' . $item['address'] . ':' . $item['port'];
$ssurl = 'ss://' . Tools::base64_url_encode($personal_info);
$ssurl .= (Config::get('add_appName_to_ss_uri') === true
? '#' . rawurlencode(Config::get('appName') . ' - ' . $item['remark'])
: '#' . rawurlencode($item['remark']));
$ssurl .= '#' . rawurlencode(Config::get('appName') . ' - ' . $item['remark']);
} else {
$personal_info = $item['method'] . ':' . $item['passwd'];
$ssurl = 'ss://' . Tools::base64_url_encode($personal_info) . '@' . $item['address'] . ':' . $item['port'];
@ -344,149 +282,50 @@ class URL
if ($item['obfs_param'] != '' && $item['obfs'] != 'v2ray') {
$plugin .= ';obfs-host=' . $item['obfs_param'];
}
$ssurl .= '/?plugin=' . rawurlencode($plugin) . '&group=' . Tools::base64_url_encode(Config::get('appName'));
} else {
$ssurl .= '/?group=' . Tools::base64_url_encode(Config::get('appName'));
$ssurl .= '?plugin=' . rawurlencode($plugin);
}
$ssurl .= (Config::get('add_appName_to_ss_uri') === true
? '#' . rawurlencode(Config::get('appName') . ' - ' . $item['remark'])
: '#' . rawurlencode($item['remark']));
$ssurl .= '#' . rawurlencode(Config::get('appName') . ' - ' . $item['remark']);
}
return $ssurl;
}
/**
* 获取 V2RayPlugin 全部节点
*
* @param object $user 用户
*
* @return array
*/
public static function getAllV2RayPluginItems($user, $emoji = 0)
{
$return_array = array();
if ($user->is_admin) {
$nodes = Node::where('sort', 13)
->where('type', '1')
->orderBy('name')
->get();
} else {
$nodes = Node::where('sort', 13)
->where(
static function ($query) use ($user) {
$query->where('node_group', '=', $user->node_group)
->orWhere('node_group', '=', 0);
}
)
->where('type', '1')
->where('node_class', '<=', $user->class)
->orderBy('name')
->get();
}
foreach ($nodes as $node) {
$item = self::getV2RayPluginItem($user, $node, $emoji);
if ($item != null) {
$return_array[] = $item;
}
}
return $return_array;
}
/**
* 获取 V2RayPlugin 节点
*
* @param object $user 用户
* @param object $node 节点
*
* @return array
*/
public static function getV2RayPluginItem($user, $node, $emoji = 0)
{
// 非 AEAD 加密无法使用
if (!in_array($user->method, Config::getSupportParam('ss_aead_method'))) {
return null;
}
$return_array = Tools::ssv2Array($node->server);
$return_array['remark'] = ($emoji == 1
? Tools::addEmoji($node->name)
: $node->name);
$return_array['address'] = $return_array['add'];
$return_array['method'] = $user->method;
$return_array['passwd'] = $user->passwd;
$return_array['protocol'] = 'origin';
$return_array['protocol_param'] = '';
$return_array['obfs'] = 'v2ray';
if ($return_array['tls'] == 'tls' && $return_array['net'] == 'ws') {
$return_array['obfs_param'] = ('mode=ws;security=tls;path=' . $return_array['path'] .
';host=' . $return_array['host']);
} else {
$return_array['obfs_param'] = ('mode=ws;security=none;path=' . $return_array['path'] .
';host=' . $return_array['host']);
}
$return_array['path'] = ($return_array['path'] . '?redirect=' . $user->getMuMd5());
$return_array['class'] = $node->node_class;
$return_array['group'] = Config::get('appName');
return $return_array;
}
public static function getV2Url($user, $node, $arrout = 0, $emoji = 0)
public static function getV2Url($user, $node, $arrout = 0)
{
$item = Tools::v2Array($node->server);
$item['v'] = '2';
$item['ps'] = ($emoji == 1
? Tools::addEmoji($node->name)
: $node->name);
$item['ps'] = $node->name;
$item['id'] = $user->getUuid();
$item['class'] = $node->node_class;
if ($arrout == 0) {
return 'vmess://' . base64_encode(
json_encode($item, 320)
);
return 'vmess://' . base64_encode(json_encode($item, JSON_UNESCAPED_UNICODE));
}
return $item;
}
public static function getAllVMessUrl($user, $arrout = 0, $emoji = 0)
public static function getAllVMessUrl($user, $arrout = 0)
{
if ($user->is_admin) {
$nodes = Node::where(
static function ($query) {
$query->where('sort', 11)
->orwhere('sort', 12);
}
)
->where('type', '1')
->orderBy('name')
->get();
} else {
$nodes = Node::where(
static function ($query) {
$query->where('sort', 11)
->orwhere('sort', 12);
}
)->where(
static function ($query) use ($user) {
$query->where('node_group', '=', $user->node_group)
->orWhere('node_group', '=', 0);
}
)
->where('type', '1')
->where('node_class', '<=', $user->class)
->orderBy('name')
->get();
}
$nodes = Node::where(
static function ($query) {
$query->where('sort', 11)
->orwhere('sort', 12);
}
)->where(
static function ($query) use ($user) {
$query->where('node_group', '=', $user->node_group)
->orWhere('node_group', '=', 0);
}
)->where('type', '1')->where('node_class', '<=', $user->class)->orderBy('name')->get();
if ($arrout == 0) {
$result = '';
foreach ($nodes as $node) {
$result .= (self::getV2Url($user, $node, $arrout, $emoji) . "\n");
$result .= (self::getV2Url($user, $node, $arrout) . "\n");
}
} else {
$result = [];
foreach ($nodes as $node) {
$result[] = self::getV2Url($user, $node, $arrout, $emoji);
$result[] = self::getV2Url($user, $node, $arrout);
}
}
return $result;
@ -505,7 +344,7 @@ class URL
$array_all['traffic_used'] = Tools::flowToGB($user->u + $user->d);
$array_all['traffic_total'] = Tools::flowToGB($user->transfer_enable);
$array_all['expiry'] = $user->class_expire;
$array_all['url'] = Config::get('subUrl') . LinkController::GenerateSSRSubCode($user->id, 0) . '?ssd=1';
$array_all['url'] = Config::get('subUrl') . LinkController::GenerateSSRSubCode($user->id, 0) . '?mu=3';
$plugin_options = '';
if (strpos($user->obfs, 'http') != false) {
$plugin_options = 'obfs=http';
@ -514,35 +353,25 @@ class URL
$plugin_options = 'obfs=tls';
}
if ($plugin_options != '') {
$array_all['plugin'] = 'simple-obfs'; //目前只支持这个
$array_all['plugin'] = 'simple-obfs';//目前只支持这个
$array_all['plugin_options'] = $plugin_options;
if ($user->obfs_param != '') {
$array_all['plugin_options'] .= ';obfs-host=' . $user->obfs_param;
}
}
$nodes_muport = Node::where('type', 1)
->where('sort', '=', 9)
->orderBy('name')
->get();
$nodes_muport = Node::where('type', 1)->where('sort', '=', 9)->orderBy('name')->get();
$array_server = array();
$nodes = Node::where('type', 1)
->where('node_class', '<=', $user->class)
->where(
static function ($func) {
$func->where('sort', '=', 0)
->orwhere('sort', '=', 10)
->orwhere('sort', '=', 13);
}
)
->where(
static function ($func) use ($user) {
$func->where('node_group', '=', $user->node_group)
->orwhere('node_group', '=', 0);
}
)
->orderBy('name')
->get();
$nodes = Node::where('type', 1)->where('node_class', '<=', $user->class)
->where(static function ($func) {
$func->where('sort', '=', 0)
->orwhere('sort', '=', 10)
->orwhere('sort', '=', 13);
})
->where(static function ($func) use ($user) {
$func->where('node_group', '=', $user->node_group)
->orwhere('node_group', '=', 0);
})->orderBy('name')->get();
$server_index = 1;
foreach ($nodes as $node) {
$server = array();
@ -550,29 +379,25 @@ class URL
if (self::CanMethodConnect($user->method) != 2) {
continue;
}
$server = Tools::ssv2Array($node->server);
$server['server'] = $server['add'];
$ssv2Array = Tools::ssv2Array($node->server);
$server['server'] = $ssv2Array['add'];
$server['id'] = $server_index;
$server['remarks'] = $node->name . ' - 单多' . $server['port'] . '端口';
$server['remarks'] = $node->name . ' - 单多' . $ssv2Array['port'] . '端口';
$server['port'] = $ssv2Array['port'];
$server['encryption'] = $user->method;
$server['password'] = $user->passwd;
$server['plugin'] = 'v2ray';
$server['path'] = ($server['path'] . '?redirect=' . $user->getMuMd5());
if ($server['tls'] == 'tls' && $server['net'] == 'ws') {
$server['obfs_param'] = ('mode=ws;security=tls;path=' . $server['path'] .
';host=' . $server['host']);
if ($ssv2Array['tls'] == 'tls' && $ssv2Array['net'] == 'ws') {
$server['plugin_options'] = 'mode=ws;security=tls;path=' . $ssv2Array['path'] . ';host=' . $user->getMuMd5();
} else {
$server['obfs_param'] = ('mode=ws;security=none;path=' . $server['path'] .
';host=' . $server['host']);
$server['plugin_options'] = 'mode=ws;security=none;path=' . $ssv2Array['path'] . ';host=' . $user->getMuMd5();
}
$array_server[] = $server;
$server_index++;
continue;
} else {
$node_server = explode(';', $node->server);
$server['server'] = $node_server[0];
}
$server['id'] = $server_index;
$server['server'] = $node->server;
//判断是否是中转起源节点
$relay_rule = Relay::where('source_node_id', $node->id)->where(
static function ($query) use ($user) {
@ -593,13 +418,13 @@ class URL
$server['ratio'] = $node->traffic_rate;
//包含普通
if (($node->mu_only == 0 || $node->mu_only == -1) && $node->sort != 13) {
if ($node->mu_only == 0 || $node->mu_only == -1) {
$server['remarks'] = $node->name;
$array_server[] = $server;
$server_index++;
}
//包含单多
if (($node->mu_only == 0 || $node->mu_only == 1) && $node->sort != 13) {
if ($node->mu_only == 0 || $node->mu_only == 1) {
$nodes_muport = Node::where('type', '1')->where('sort', '=', 9)
->where(static function ($query) use ($user) {
$query->Where('node_group', '=', $user->group)
@ -615,15 +440,9 @@ class URL
$server['id'] = $server_index;
$server['remarks'] = $node->name . ' - 单多' . $node_muport->server . '端口';
$server['port'] = $node_muport->server;
// 端口偏移
if (strpos($node->server, ';') !== false) {
$node_tmp = Tools::OutPort($node->server, $node->name, $node_muport->server);
$server['port'] = $node_tmp['port'];
$server['remarks'] = $node->name . ' - 单多' . $node_tmp['port'] . '端口';
}
$server['encryption'] = $muport_user->method;
$server['password'] = $muport_user->passwd;
$server['plugin'] = 'simple-obfs'; //目前只支持这个
$server['plugin'] = 'simple-obfs';//目前只支持这个
$plugin_options = '';
if (strpos($muport_user->obfs, 'http') != false) {
$plugin_options = 'obfs=http';
@ -667,14 +486,14 @@ class URL
$plugin = '';
if (in_array($item['obfs'], $ss_obfs_list)) {
if (strpos($item['obfs'], 'http') !== false) {
$plugin .= ', obfs=http';
$plugin .= ',obfs=http';
} else {
$plugin .= ', obfs=tls';
$plugin .= ',obfs=tls';
}
if ($item['obfs_param'] != '') {
$plugin .= ', obfs-host=' . $item['obfs_param'];
$plugin .= ',obfs-host=' . $item['obfs_param'];
} else {
$plugin .= ', obfs-host=wns.windows.com';
$plugin .= ',obfs-host=wns.windows.com';
}
}
return $plugin;
@ -692,7 +511,7 @@ class URL
* obfs
* obfs_param
*/
public static function getItem($user, $node, $mu_port = 0, $relay_rule_id = 0, $is_ss = 0, $emoji = 0)
public static function getItem($user, $node, $mu_port = 0, $relay_rule_id = 0, $is_ss = 0)
{
$relay_rule = Relay::where('id', $relay_rule_id)->where(
static function ($query) use ($user) {
@ -712,7 +531,9 @@ class URL
$mu_user->obfs_param = $user->getMuMd5();
$mu_user->protocol_param = $user->id . ':' . $user->passwd;
$user = $mu_user;
$node_name .= ' - ' . $mu_port . ' 单端口';
if (Config::get('mergeSub') != 'true') {
$node_name .= ' - ' . $mu_port . ' 单端口';
}
}
if ($is_ss) {
if (!self::SSCanConnect($user)) {
@ -725,31 +546,37 @@ class URL
}
$user = self::getSSRConnectInfo($user);
}
$return_array['address'] = $node->server;
$return_array['port'] = $user->port;
$return_array['protocol'] = $user->protocol;
$return_array['protocol_param'] = $user->protocol_param;
$return_array['obfs'] = $user->obfs;
$return_array['obfs_param'] = $user->obfs_param;
if (strpos($node->server, ';') !== false) {
$node_tmp = Tools::OutPort($node->server, $node->name, $mu_port);
if ($mu_port != 0) {
$return_array['port'] = $node_tmp['port'];
$node_name = $node_tmp['name'];
if ($node->sort == 13) {
$server = Tools::ssv2Array($node->server);
$return_array['address'] = $server['add'];
$return_array['port'] = $server['port'];
$return_array['protocol'] = 'origin';
$return_array['protocol_param'] = '';
$return_array['path'] = $server['path'];
$return_array['obfs'] = 'v2ray';
if ($server['tls'] == 'tls' && $server['net'] == 'ws') {
$return_array['obfs_param'] = 'mode=ws;security=tls;path=' . $server['path'] . ';host=' . $user->getMuMd5();
} else {
$return_array['obfs_param'] = 'mode=ws;security=none;path=' . $server['path'] . ';host=' . $user->getMuMd5();
}
$return_array['address'] = $node_tmp['address'];
} else {
$return_array['address'] = $node->server;
$return_array['port'] = $user->port;
$return_array['protocol'] = $user->protocol;
$return_array['protocol_param'] = $user->protocol_param;
$return_array['obfs'] = $user->obfs;
$return_array['obfs_param'] = $user->obfs_param;
}
$return_array['passwd'] = $user->passwd;
$return_array['method'] = $user->method;
$return_array['remark'] = ($emoji == 1
? Tools::addEmoji($node_name)
: $node_name);
$return_array['class'] = $node->node_class;
$return_array['remark'] = $node_name;
$return_array['group'] = Config::get('appName');
if ($mu_port != 0 && Config::get('mergeSub') != 'true') {
$return_array['group'] .= ' - 单端口';
}
$return_array['ratio'] = ($relay_rule != null
? $node->traffic_rate + $relay_rule->dist_node()->traffic_rate
: $node->traffic_rate);
return $return_array;
}
@ -758,49 +585,36 @@ class URL
return clone $user;
}
public static function getUserInfo($user, $type, $traffic_class_expire)
public static function getUserTraffic($user, $is_mu = 0)
{
$return = '';
// 订阅信息
$info_array = (count(Config::get('sub_message')) != 0
? (array) Config::get('sub_message')
: []);
if ($traffic_class_expire !== 0) {
// 用户账户及流量信息
if (strtotime($user->expire_in) > time()) {
if ($user->transfer_enable == 0) {
$info_array[] = '剩余流量:0.00%';
} else {
$info_array[] = '剩余流量:' . number_format(($user->transfer_enable - $user->u - $user->d) / $user->transfer_enable * 100, 2) . '% ' . $user->unusedTraffic();
}
$info_array[] = '过期时间:' . $user->class_expire;
$group_name = Config::get('appName');
if ($is_mu == 1 && Config::get('mergeSub') != 'true') {
$group_name .= ' - 单端口';
}
if (strtotime($user->expire_in) > time()) {
if ($user->transfer_enable == 0) {
$percent = '0.00%';
} else {
$info_array[] = '账户已过期,请续费后使用';
$percent = number_format(($user->transfer_enable - $user->u - $user->d) / $user->transfer_enable * 100, 2) . '%';
}
$ssurl = 'www.google.com:1:auth_chain_a:chacha20:tls1.2_ticket_auth:YnJlYWt3YWxs/?obfsparam=&protoparam=&remarks=' . Tools::base64_url_encode('剩余流量:' . $percent . ' ' . $user->unusedTraffic()) . '&group=' . Tools::base64_url_encode($group_name);
} else {
$ssurl = 'www.google.com:1:auth_chain_a:chacha20:tls1.2_ticket_auth:YnJlYWt3YWxs/?obfsparam=&protoparam=&remarks=' . Tools::base64_url_encode('账户已过期,请续费后使用') . '&group=' . Tools::base64_url_encode($group_name);
}
return 'ssr://' . Tools::base64_url_encode($ssurl);
}
public static function getUserClassExpiration($user, $is_mu = 0)
{
$group_name = Config::get('appName');
foreach ($info_array as $item) {
switch ($type) {
case 'ss':
$return .= 'ss://' . Tools::base64_url_encode('chacha20:breakwall') . '@www.google.com:10086' . '/?group=' . Tools::base64_url_encode($group_name) . '#' . rawurlencode($item) . PHP_EOL;
break;
case 'ssr':
$return .= 'ssr://' . Tools::base64_url_encode('www.google.com:10086:auth_chain_a:chacha20:tls1.2_ticket_auth:YnJlYWt3YWxs/?obfsparam=&protoparam=&remarks=' . Tools::base64_url_encode($item) . '&group=' . Tools::base64_url_encode($group_name)) . PHP_EOL;
break;
case 'v2ray':
$v2ray = ['v' => '2', 'ps' => $item, 'add' => 'www.google.com', 'port' => '10086', 'id' => '2661b5f8-8062-34a5-9371-a44313a75b6b', 'aid' => '2', 'net' => 'tcp', 'type' => 'none', 'host' => '', 'tls' => ''];
$return .= 'vmess://' . base64_encode(json_encode($v2ray, JSON_UNESCAPED_UNICODE)) . PHP_EOL;
break;
case 'quantumult_v2':
$quantumult_v2 = base64_encode($item . ' = vmess, ' . 'www.google.com' . ', ' . '10086' . ', chacha20-ietf-poly1305, "2661b5f8-8062-34a5-9371-a44313a75b6b", group=' . $group_name . '_v2') . PHP_EOL;
$return .= 'vmess://' . base64_encode($quantumult_v2) . PHP_EOL;
break;
}
if ($is_mu == 1 && Config::get('mergeSub') != 'true') {
$group_name .= ' - 单端口';
}
return $return;
if (strtotime($user->expire_in) > time()) {
$ssurl = 'www.google.com:2:auth_chain_a:chacha20:tls1.2_ticket_auth:YnJlYWt3YWxs/?obfsparam=&protoparam=&remarks=' . Tools::base64_url_encode('过期时间:' . $user->class_expire) . '&group=' . Tools::base64_url_encode($group_name);
} else {
$ssurl = 'www.google.com:2:auth_chain_a:chacha20:tls1.2_ticket_auth:YnJlYWt3YWxs/?obfsparam=&protoparam=&remarks=' . Tools::base64_url_encode('账户已过期,请续费后使用') . '&group=' . Tools::base64_url_encode($group_name);
}
return 'ssr://' . Tools::base64_url_encode($ssurl);
}
}

@ -9,6 +9,7 @@
"firebase/php-jwt": "~3.0",
"aws/aws-sdk-php": "3.*",
"gregwar/captcha": "1.*",
"cloudxns/cloud-xns-api-sdk-php": "*",
"voku/anti-xss": "^1.2",
"paymentwall/paymentwall-php": "^2.1",
"telegram-bot/api": "^2.2",
@ -21,10 +22,8 @@
"chen-see/chen-pay": "^1.0@dev",
"league/omnipay": "^3",
"lokielse/omnipay-alipay": "*",
"khanamiryan/qrcode-detector-decoder": "*",
"remotelyliving/php-dns": "3.0.6",
"symfony/yaml": "^4.4@dev",
"irazasyed/telegram-bot-sdk": "^2.0"
"charlottedunois/yasmin": "*",
"khanamiryan/qrcode-detector-decoder": "*"
},
"autoload": {
"psr-4": {

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

Loading…
Cancel
Save