Compare commits

...

443 Commits

Author SHA1 Message Date
StandWithYOU 8633e1cd2d
Add files via upload 6 years ago
StandWithYOU ba85e469ac
Add files via upload 6 years ago
StandWithYOU 5e6638547f
Add files via upload 6 years ago
StandWithYOU cfb13c8ef0
Update README.md 6 years ago
StandWithYOU b91b0c3e33
Update README.md 6 years ago
StandWithYOU 78d09700ea
Update README.md 6 years ago
Cadwalader 80cd95f334 更新canvasjs.js至3.2.6 GA 6 years ago
Cadwalader d14e8f8115
Update README.md 6 years ago
Cadwalader 025bbeb9d3 Add support for CFW exe file 6 years ago
Cadwalader bc49882353
Update README.md 6 years ago
Cadwalader e3eab497ae Update canvasjs.js version to 3.2 6 years ago
Cadwalader 5645bb1b1a
Update malio.js 6 years ago
Cadwalader 18ecb3723f Revert "Update README.md"
This reverts commit a822b502b2.
6 years ago
Cadwalader a822b502b2
Update README.md 6 years ago
Cadwalader af02fc0efb
Update README.md
更改 CREDIT 和 AFF
6 years ago
Cadwalader fdf582dcdf 更新CFW教程图片 6 years ago
Cadwalader 882aa266cb
Update README.md 6 years ago
Cadwalader d19cd32055
Update README.md 6 years ago
Cadwalader 62d8f8ead8
解密malio.js文件 6 years ago
Cadwalader 1f87696d86
Update README.md 6 years ago
Cadwalader e6a23af95f
Update README.md 6 years ago
Cadwalader 04d20e52f6
Update README.md 6 years ago
GeekQu 53e817431c chore(clash): update some fields 6 years ago
Malio 28213af6ba Merge branch 'malio' of https://gitlab.com/maxitio/malio-theme-for-sspanel into malio 7 years ago
Malio d7d536c79d 支持materialpay 7 years ago
Masivro 8043684bf6 Merge branch 'malio' into 'malio'
feat(js): 更正 JS 轮询逻辑问题

See merge request masivro/malio-theme-for-sspanel!48
7 years ago
孔雀 deeb5ecdac feat(js): 更正 JS 轮询逻辑问题 7 years ago
Masivro 4bb967085a Merge branch 'patch-2' into 'malio'
fix bug with af2a7d2a

See merge request masivro/malio-theme-for-sspanel!47
7 years ago
孔雀 f9fb905aa8
! fix bug 7 years ago
Masivro 8701e6ed2b Merge branch 'patch-1' into 'malio'
fix bug:修复index中迄今为止部分从i18n.php获取数据的名称错误

See merge request masivro/malio-theme-for-sspanel!36
7 years ago
Masivro 2c05cd08e3 Merge branch 'patch-3' into 'malio'
fix bug:修复Malio_Config['support_sub_type']在user/index.tpl中失效的问题,并调整了button顺序

See merge request masivro/malio-theme-for-sspanel!38
7 years ago
Masivro a05176d2b6 Merge branch 'patch-2' into 'malio'
add config custom_invite_price

See merge request masivro/malio-theme-for-sspanel!41
7 years ago
Masivro b4c7d13296 Merge branch 'patch-1' into 'malio'
修复最近72小时流量图表在单次流量记录超过1g的情况下无法正常显示的bug。

See merge request masivro/malio-theme-for-sspanel!44
7 years ago
Masivro 23014aad36 Merge branch 'patch-1' into 'malio'
修复重置周期最后一天的下次重置显示问题

See merge request masivro/malio-theme-for-sspanel!42
7 years ago
Masivro ed481f683d Merge branch 'patch-2' into 'malio'
fix quantumult

See merge request masivro/malio-theme-for-sspanel!43
7 years ago
Masivro b1aa5090f6 Merge branch 'patch-2' into 'malio'
删除 .config.example.php 中支付系统里重复的tomatopay设置

See merge request masivro/malio-theme-for-sspanel!37
7 years ago
Masivro 171c39bb87 Merge branch 'patch-1' into 'malio'
Support Trojan

See merge request masivro/malio-theme-for-sspanel!46
7 years ago
孔雀 af2a7d2a41
Support Trojan 7 years ago
Malio 493d0232aa 修改tg bot绑定方式为发送绑定码 7 years ago
Liu Yunsan 0ec4414b33 修复最近72小时流量图表在单次流量记录超过1g的情况下无法正常显示的bug。 7 years ago
MigSro df8a2b2190 fix quantumult 7 years ago
lithromantic 196a8bc151 修复重置周期最后一天的下次重置显示问题 7 years ago
matt 8a56a0ba90 add config custom_invite_price 7 years ago
Masivro 69fedbcbf3 Merge branch 'patch-1' into 'malio'
fix bug: V2RayN 格式修正

See merge request masivro/malio-theme-for-sspanel!39
7 years ago
孔雀 a3f0c7ece6 fix bug: V2RayN 格式修正 7 years ago
Sanqian ed9c1eb7bb fix bug:修复Malio_Config['support_sub_type']在user/index.tpl中失效的问题,并调整了button顺序 7 years ago
Sanqian 1ba142cd90 删除 .config.example.php 中支付系统里重复的tomatopay设置 7 years ago
Sanqian a902d4e60d fix bug:修复index中迄今为止部分从i18n.php获取数据的名称错误 7 years ago
Malio 69e4d22e4a fix bug: 任何Key均可获取用户信息 by Gtary 7 years ago
Malio e350d32b1a fix bugs 7 years ago
Malio f57ffdfb0a fix bugs 7 years ago
Malio c38ab82d42 Merge branch 'malio' of https://gitlab.com/maxitio/malio-theme-for-sspanel into malio
# Conflicts:
#	app/Controllers/LinkController.php
7 years ago
Malio 76517c9172 Merge remote-tracking branch 'origin/dev' into malio
# Conflicts:
#	README.md
#	app/Command/Update.php
#	app/Command/XCat.php
#	app/Controllers/AuthController.php
#	app/Controllers/HomeController.php
#	app/Controllers/Mod_Mu/UserController.php
#	app/Controllers/UserController.php
#	app/Models/User.php
#	app/Services/Gateway/TomatoPay.php
#	app/Services/Gateway/YftPayUtil.php
#	app/Services/Payment.php
#	composer.json
#	config/.config.example.php
#	config/routes.php
7 years ago
GeekQu 8924e5fd82 修复或导致 XSS 注入的问题 7 years ago
GeekQu facc66d78a
Merge pull request #66 from GeekQu/dev
修复一些问题
7 years ago
GeekQu 787e8f16be
修复或导致 XSS 注入的问题 7 years ago
GeekQu 0185572e5c
修复 ssr 节点无法订阅的问题 7 years ago
GeekQu 1c455e0b3c
Merge branch 'pr/50' into dev 7 years ago
GeekQu b547121472
Merge pull request #49 from du5/patch-1
优化判断逻辑
7 years ago
Malio 4b75975399 支持锁定只使用一种语言 7 years ago
Malio b516a11f87 着陆页支持更换语言 7 years ago
Malio d971fa429e 支持Wolfpay,修复一些bug 7 years ago
v2rayv3 aa0e40e893 1. 修复ss+ws中的path设定,一直为空的bug
2. 修复小火箭订阅ss+ws peer设定,目前逻辑如下
   1. 如果没有额外参数host=情况下,则用第一个地址,或者server=的值
   2. 如果需要中转则 且 tls,额外参数如下 relayserver=中转地址|outside_poert=中转端口|server=落地地址|host=落地地址
7 years ago
v2rayv3 79e8b40dfd 统一在tls的时候,host必须是tls的域名。 感恩 7 years ago
Gtary 516344fa7b
Update UserController.php 7 years ago
Gtary 7da5fae5eb
优化判断逻辑 7 years ago
v2rayv3 73cdeb69a9 修复php 7.3 下 undefined offset的问题 7 years ago
v2rayv3 7e0f4fc5ce Merge branch 'dev' of github.com:v2rayv3/ss-panel-v3-mod_Uim into dev
merge
7 years ago
v2rayv3 c49fe18b2f 增加小火箭peer v2plugin 设定 7 years ago
GeekQu 3de1210f39
管理页面节点列表显示节点出口地址 7 years ago
GeekQu 784c82a50d
修复 Quantumult 订阅 over-tls host 错误 7 years ago
GeekQu 360d09d94b
修复 sub=2 订阅中 ss-v2plugin 节点缺 path 7 years ago
v2rayv3 68e1a92672
Update README.md 7 years ago
Malio edbebf43fd update 7 years ago
v2rayv3 90a746a633 和quan 统一使用host 7 years ago
v2rayv3 0cb6c62614 修复quan 中转host tls请求的时候使用中转域名的问题,默认host(落地域名)的值 7 years ago
GeekQu 4dc562a41d
更改为 Regex 7 years ago
GeekQu 0c042b3aee
可配置任意未知的命令触发 /help 的回复 7 years ago
GeekQu 735cbc129b
fix (PaymentWall) 7 years ago
Malio 5c1112b3a6 据说能修复当面付 7 years ago
GeekQu 2717862e29
去除无用 (Config) 7 years ago
GeekQu fe546e5024
Merge pull request #65 from GeekQu/dev
fix  (sql)
7 years ago
GeekQu 47f3813ec2 fix (sql) 7 years ago
Malio 7abed27b75 update 7 years ago
GeekQu 27542ca725
Merge pull request #64 from GeekQu/dev
20200130
7 years ago
GeekQu 13abb867dd 修改版本 7 years ago
GeekQu 9ff825c294 清理无用 (GeekQu.md) 7 years ago
GeekQu bd4fc024b2
去除无用 (relay_port_migration) 7 years ago
Malio 533d1423ff update 7 years ago
GeekQu d47bd98773
V2RayN 客户端支持附带节点信息下载 7 years ago
GeekQu 7c817b6174
修复无法获取 VMess kcp 节点 7 years ago
GeekQu 733a11048d
修复管理后台用户编辑解封时间不正确 7 years ago
GeekQu c010a67300
调整审计封禁手动封禁流程 7 years ago
GeekQu f6a94fbdf3
审计封禁支持所有节点对接方式 7 years ago
Malio c259030c9a 修复bug 7 years ago
GeekQu 7814d7ec83
Tools 格式化 7 years ago
GeekQu 2244627804
Merge pull request #63 from GeekQu/dev
修复些许问题
7 years ago
GeekQu ac5c582b76
修复 Surge、Clash 配置可能出现 null 7 years ago
GeekQu 5838189366
优化静态文件中的判断 7 years ago
GeekQu c3daab80cb
修复私聊发送 /my 触发的回复会被自动删除的问题 7 years ago
GeekQu 5a8b03a106
修复私聊发送 /menu 找不到用户时无回复的问题 7 years ago
GeekQu b3dac73008
调整 telegram bot 绑定流程:支持手动发送绑定码绑定 7 years ago
GeekQu dd41e26a0d
修复 SS/SSR 订阅无协议无 group 7 years ago
GeekQu 01e10aeaf0
修复管理员触发的 Bot 回复和 /start & /ping 命令触发的回复不会自动删除的问题 7 years ago
GeekQu 04e4ec061b
Merge pull request #62 from GeekQu/dev
修复一些问题
7 years ago
GeekQu 6415da3819
staff 增加版本以及说明为 UIM 修改版 7 years ago
GeekQu 3f39e56b52
fix(LinkController) 7 years ago
GeekQu e28ede416b
修复群组内可从他人消息中签到 7 years ago
GeekQu 81fc72a9b5
修复 Bot 用户启用显示为数值 7 years ago
GeekQu b2d1f1d6fe
使用 $_ENV 7 years ago
GeekQu 1a99f59c6f
增加用户命令删除任务 7 years ago
GeekQu aacef2eaec
修复在群组中点击签到后出现私聊菜单 7 years ago
GeekQu e12fa43ef4
fix(job) 7 years ago
GeekQu 441a081724
fix(job) 7 years ago
GeekQu 781c41f2ae
修改 Config 默认配置,避免初始坑 7 years ago
GeekQu 38ccb7960e
修 bug 7 years ago
GeekQu 4326f52b8e
可配置将订阅中单端口的信息去除 7 years ago
GeekQu ef84384ecc
去除无用 7 years ago
GeekQu 41dab53a8c
Update index.tpl 7 years ago
GeekQu 251f4095d1
调整已生效套餐查询的位置 7 years ago
GeekQu 6d8559c78b
调整优化 7 years ago
GeekQu f59c424407
去除订阅 sub=4&5 7 years ago
GeekQu 3661829e80
Merge pull request #47 from v2rayv3/dev
增加按照后台中转配置自动增加中转配置订阅信息
7 years ago
GeekQu b2df72ef79
添加缺少的文本 7 years ago
GeekQu 6c863f745b
管理员、用户查询增加套餐信息 7 years ago
GeekQu eaea2b336e
修改群组内 /my 显示 7 years ago
GeekQu 96f7a23400
Update UserCallback.php 7 years ago
GeekQu ae330b454c
账户解绑增加提示 7 years ago
GeekQu ee4060f8ab
优化调整 7 years ago
GeekQu 56cfbfe67d
遗漏 7 years ago
GeekQu 9465a24947
更改文件结构 7 years ago
GeekQu 48100a0f98
调整用户中心获取 ssd 链接 7 years ago
GeekQu 2b97a04e8f
调整、增加 SS-Android订阅 7 years ago
GeekQu 40848af02f
调整 7 years ago
Malio d56edcf7e2 尝试修复用户余额多倍到账的问题 7 years ago
GeekQu 4313d1e428
修复合并订阅的问题、重写 SSD 订阅 7 years ago
GeekQu ae6eca628b
修复 Clash Provider 的部分问题、重新启用配置中的合并订阅选项 7 years ago
GeekQu 795bfe8af5
调整类型 7 years ago
GeekQu 66274de89c
... 7 years ago
GeekQu 4e6db25d6a
list 支持 extend 7 years ago
GeekQu 228158c84d
分离只获取节点而非整体配置的节点订阅 7 years ago
v2rayv3 134fe6cb29 增加按照后台中转配置自动增加中转配置订阅信息 7 years ago
GeekQu 7204c32e9e
订阅缓存数量限制 7 years ago
GeekQu 8e61ac1175
文档中心页面引入可获取支持的订阅链接关键词 7 years ago
GeekQu 2a6b4ba9d6
Update main.tpl 7 years ago
GeekQu 07a6120651
Bot 细节调整 7 years ago
GeekQu 9cbf3d88db
为长者续一秒 7 years ago
GeekQu 56099ff991
跟进 rico 7 years ago
GeekQu fe2fb3ae29
Merge branch 'pr/46' into dev 7 years ago
v2rayv3 05054f2910 localserver应该是add覆盖前的 7 years ago
v2rayv3 043ff80923 修复逻辑bug,应该是peer是落地的地址信息 7 years ago
v2rayv3 1514e36e44 漏了符号 7 years ago
v2rayv3 d1c0bf6d5d 小火箭添加peer设定,这里是默认是add,如果relayserver存在,方便中转,小伙伴测试可用 7 years ago
GeekQu 2ee42af5f5
api提供用户限制ip数量的配置信息 7 years ago
GeekQu 239e2fc6d2
继续替换each 7 years ago
GeekQu 157805d495
修复7.2 及其以上的bug 7 years ago
GeekQu 08eefe35e6
修复ip判断 7 years ago
GeekQu b4f7bf6e55
删除不需要的f 7 years ago
GeekQu 8fed9d184c
更新api url 7 years ago
GeekQu 1723af4419
update 7 years ago
GeekQu 7eaaf1addf
IDPAY 7 years ago
GeekQu 133918163b
修复tomataopay 7 years ago
GeekQu 3edc891722
先增加tomatopay 7 years ago
GeekQu 02fdf1e90d
Update glzjin_all.sql 7 years ago
GeekQu 049f71d913
Bot +1 7 years ago
GeekQu 478339ff4f
Update Node.php 7 years ago
GeekQu e95205d203
Update Node.php 7 years ago
GeekQu 0d2b25b4e2
修复 ssd 订阅, 7 years ago
GeekQu 4009d7d883
rico obfs 7 years ago
GeekQu 12ecd51269
Bot +1 7 years ago
GeekQu 758b4272ff
Update glzjin_all.sql 7 years ago
GeekQu f20a405c0c
Create telegram_tasks.sql 7 years ago
GeekQu 730a6e432a
定时任务增加判断 7 years ago
GeekQu 15d9462d3e
Bot +1 7 years ago
GeekQu 41a44f3c12
用户中心显示套餐已使用天数、下次流量重置时间、套餐过期时间 7 years ago
GeekQu d7d83c2b0d
单用户购买记录页 添加套餐 7 years ago
GeekQu 6b9d5800d3
单用户购买记录页 删除记录 7 years ago
GeekQu 6d6a01b3e9
Bot +1 7 years ago
Max f8b08a0bb6 修复繁体不显示文本的问题 7 years ago
GeekQu fa7933966f
单用户购买记录页 7 years ago
GeekQu 06483130dd
Bot +1 7 years ago
GeekQu efa11e17e3
Bot +1 7 years ago
GeekQu 9079c21340
Bot +1 7 years ago
GeekQu 691aef4578
修 7 years ago
GeekQu f6f1267e28
Bot +1 7 years ago
GeekQu f922d60e9d
Bot +1 7 years ago
GeekQu 5c5de895e8
Bot +1 7 years ago
GeekQu 5873a37fed
Bot +1 7 years ago
GeekQu 34569c5dc2
Bot +1 7 years ago
GeekQu df9f9009a5
Bot +1 7 years ago
GeekQu a04c1755d2
Bot +1 7 years ago
GeekQu e8be1d0a39
Bot 资料编辑菜单增加解绑账户 7 years ago
GeekQu a709cfae54
Telegram Bot +1 7 years ago
GeekQu 30b8239dd6
Bot 支持下载 Surge 2&3 配置 7 years ago
GeekQu cd20d8c37a
修改 Quantumult、支持 QuantumultX 7 years ago
GeekQu cc96e2e3b5
f 7 years ago
GeekQu 73afc143cd
分离 URI 生成 7 years ago
Max bc7e18e211 增加为不同等级给不同的签到流量的功能(定制功能) 7 years ago
Max b57e618ee3 2019 to 2020 7 years ago
Max c37c12d8a4 update 7 years ago
GeekQu 78b378b978
Telegram Bot 7 years ago
Max 5dff6c4ce1 修复首页在中文下缺失文本的bug 7 years ago
Max 4ac06220b9 修复一堆i18n造成的bug 7 years ago
Max 3cd4017f37 Merge branch 'malio' of https://gitlab.com/maxitio/malio-theme-for-sspanel into malio
# Conflicts:
#	config/.malio_config.example.php
#	config/routes.php
#	resources/views/malio/index.tpl
#	resources/views/malio/user/code.tpl
#	resources/views/malio/user/index.tpl
#	resources/views/malio/user/shop.tpl
7 years ago
Max 6bdc510cf2 增加多语言支持 7 years ago
Max 096228c6c7 修复试用套餐购买不了的问题 7 years ago
GeekQu 4fc6ae0db4
Telegram Bot 7 years ago
GeekQu 438b4fe3a4
Telegram Bot 7 years ago
GeekQu c0fb19dbf4
Telegram Bot 7 years ago
GeekQu b6fc28819e
Telegram Bot 7 years ago
Max 5eff0b6a01 修复可以重复试用的bug 7 years ago
GeekQu d1c3e9cf9c
Telegram Bot 7 years ago
GeekQu 7669cf7768
Telegram Bot 7 years ago
GeekQu cd529f5657
Telegram Bot 7 years ago
GeekQu 95a437f04b
Telegram Bot 7 years ago
GeekQu e76026a5d8
Telegram Bot 7 years ago
GeekQu 339dfaac21
Telegram Bot 7 years ago
GeekQu 006250ff76
Telegram Bot 7 years ago
GeekQu 487cefb418
Telegram Bot 7 years ago
GeekQu dbb3bd7751
Telegram Bot 7 years ago
GeekQu 33aeabf077
Telegram Bot 7 years ago
GeekQu fa6026c4c9 Telegram Bot 7 years ago
Max 952825b7d4 修复聚合支付的番茄云支付 7 years ago
Max e554b29711 Malio聚合支付支持Stripe 7 years ago
Max 5061561e71 admin面板增加收入情况和新用户统计功能 7 years ago
GeekQu 6ab5fcd17e
Telegram Bot 7 years ago
GeekQu 086f4c5b58 修手欠 7 years ago
GeekQu 7b78b7800c
Telegram Bot 7 years ago
GeekQu 1ad8d806ac Telegram Bot 7 years ago
GeekQu 5afc5e0ac9
Telegram Bot 7 years ago
GeekQu 609bc6ed1c
Telegram Bot 7 years ago
GeekQu 0dabf932f9
Telegram Bot 7 years ago
GeekQu 653e82f1c4
Telegram Bot 7 years ago
GeekQu ca36add3f9
修 bot setWebhook 错误提示 7 years ago
GeekQu b889f2b366
Telegram Bot 7 years ago
GeekQu 36f167c0dd
Update Message.php 7 years ago
GeekQu a797a8d2b3
Update Message.php 7 years ago
GeekQu 94d822a708
Telegram Bot 7 years ago
GeekQu 1ca33982b2
修手残 7 years ago
GeekQu b2d78c0d63
Telegram Bot 7 years ago
Max 3dc8e6001a 防止充值金额重复到账 7 years ago
GeekQu e775d9a329
Telegram Bot 7 years ago
Max 5eee24df84 修复刚写的支付回调bug 7 years ago
Max 5e7b07d256 Merge branch 'malio' of https://gitlab.com/maxitio/malio-theme-for-sspanel into malio 7 years ago
Max dd532ab945 支持Clash for Android一键导入配置 7 years ago
Max 4c19b026a9 Merge branch 'patch-1' into 'malio'
fix bug with Coupon code

See merge request maxitio/malio-theme-for-sspanel!24
7 years ago
Max 9c994800cc 修复聚合支付回调失败的问题 7 years ago
孔雀 e704107a5d Update UserController.php 7 years ago
limiyun d645c8659e fix bug with Coupon code 7 years ago
Max 98d9f04c68 Merge branch 'malio' of https://gitlab.com/maxitio/malio-theme-for-sspanel into malio 7 years ago
Max 1dc1d9e555 新增 Clash for Android 教程 7 years ago
Max 545c021013 Merge branch 'malio' into 'malio'
Malio 支持开启用户中心弹窗24小时只弹一次

See merge request maxitio/malio-theme-for-sspanel!23
7 years ago
Leeze 64589d8e03 Malio 支持开启用户中心弹窗24小时只弹一次 7 years ago
Max 0567e05d80 聚合支付接口支持支付宝当面付 7 years ago
Max e2773f5a2d 添加聚合支付系统的功能 7 years ago
GeekQu ff4177668b
网站侧栏显示配置 7 years ago
GeekQu a984e01afb
修复显示问题 7 years ago
Max f6f88fc19a 现在爬虫再也看不到SSPANEL字样了,Staff也看不到,只有用访问浏览器才能看到 7 years ago
Max 1fd4b4a8e3 修tg bot 7 years ago
GeekQu 90958f2aa1
修改提示 7 years ago
GeekQu 78a7c0ff14
Xcat 增加清理订阅缓存,增删改节点、增删改中转规则时清理订阅缓存 7 years ago
GeekQu 3b85685260
Update .gitignore 7 years ago
Max e89a266572 修复crisp 7 years ago
GeekQu f02d933b8f
修复手贱 7 years ago
GeekQu 3150594b86
修复上一条commit遗漏 7 years ago
GeekQu 6997a7fb0c
telegram 推送使用数据库内的配置 7 years ago
GeekQu a116d92e00
后台清理用户订阅缓存增加成功提示 7 years ago
GeekQu 513697ea18
优化订阅 token 查询 7 years ago
GeekQu d4ce819dc5
美化一下 7 years ago
Max 14c4db9be5 更新config.php 7 years ago
Max edaad4aec6 Merge branch 'dev' of https://gitlab.com/maxitio/malio-theme-for-sspanel into malio
# Conflicts:
#	README.md
#	app/Command/Update.php
#	app/Controllers/UserController.php
#	app/Middleware/Mod_Mu.php
#	app/Models/User.php
#	app/Services/Gateway/TomatoPay.php
#	app/Services/Payment.php
#	app/Utils/TelegramProcess.php
#	app/Utils/URL.php
#	config/.config.example.php
7 years ago
Rico a8f2224484 先增加tomatopay 7 years ago
GeekQu 8f7c22a991
Merge branch 'dev' of https://github.com/GeekQu/ss-panel-v3-mod_Uim into dev 7 years ago
GeekQu 083826931a
后台用户编辑未开启订阅缓存时不显示清理选项 7 years ago
GeekQu 23390cd207
订阅缓存增加 header 可识别 7 years ago
GeekQu 2911b9e7a7
Merge branch 'pr/60' into dev 7 years ago
GeekQu 8b004688c9
修复端口偏移 7 years ago
GeekQu 457e4277ca
用户修改连接密码、重置端口、更改加密协议混淆、重置订阅链接、以及删除账户时自动清理订阅缓存 7 years ago
GeekQu 96db900a6b
增强判断 7 years ago
GeekQu b57f817475
Merge pull request #44 from Anankke/dev
merge 20191128
7 years ago
Rico 659bc38af8 逗比了,正常的 7 years ago
Rico c210019290 添加小火箭h2订阅,暂时不允许 跳过证书验证,应为测试连不上 7 years ago
Rico 894cec5373 修复 节点显示问题 7 years ago
Rico aa1fe9be44 1.删除用户页面v2ray中转设置
2.管理员中转配置,Port是指本地监听,只能中转V2ray相关节点配置
7 years ago
Rico c2a09434b9 增加kit对tls的支持,增加kit对h2的订阅支持,clash过滤h2协议,shadowrocket过滤h2,quan 过滤h2 7 years ago
Rico 95e96d2c99 测试增加小火箭 mkcp订阅支持 7 years ago
Rico e5e244d0b4 修复 V2rayNG 教程链接 7 years ago
Rico 4cabe238f9 修复 quan的完整订阅 tgbot 7 years ago
Rico 16f003a1bb 修复 clash tag的问题 傻逼bug 7 years ago
Rico ee6f8b86db Merge branch 'no_ymq_dev' into dev 7 years ago
Rico c9b3d22040 修复 流水统计的报错 7 years ago
SakuraSa233 57de09ea4a
fix(vue-controller): default return 7 years ago
SakuraSa233 ab60f5c7c8
fix(vue): return type, logic, bad code style(incompletely) 7 years ago
laurieryayoi d68337872e fix console.log warning 7 years ago
Sukka b6135efc88
github(issue_template): add zh-CN version 7 years ago
laurieryayoi e7ac0b9562 布尔值判断去引号 & 添加nodeinfo相关代码 7 years ago
laurieryayoi d809788106 Merge branch 'dev' of https://github.com/Anankke/SSPanel-Uim into dev 7 years ago
laurieryayoi c2bf1dc952 添加nodeinfo api 7 years ago
SakuraSa233 be32a13c9b
feat(github): multi issue template 7 years ago
GeekQu 777c409031
修改 ss-v2ray-plugin 节点默认 host 为 microsoft.com 7 years ago
GeekQu e7700ee755
修复漏写 getUri()... 7 years ago
GeekQu c7d2b5f614
订阅信息缓存 7 years ago
SakuraSa233 30654b7cd2
clean(trimepay): clean template file 7 years ago
SakuraSa233 a647590326
Revert "clean(payment): remove unused paymentwall"
This reverts commit 67af63b052.
7 years ago
SakuraSa233 931eb9d1d2
refactor(controller): base slim-http native json output 7 years ago
Rico d3c1ae3f20 改成布朗 7 years ago
Rico 3c84838193 明确问题 7 years ago
Rico aded91b730 增加开关是否验证node ip 7 years ago
SakuraSa233 e1127e863a
refactor(qrcode): local decode with better perf 7 years ago
SakuraSa233 9b0cd43a2e
clean(services): remove empty cache class 7 years ago
SakuraSa233 e9e59e4dcb
clean(service): remove unused "token" 7 years ago
SakuraSa233 6996425e9b
clean(auth): remove empty class 7 years ago
SakuraSa233 67af63b052
clean(payment): remove unused paymentwall 7 years ago
SakuraSa233 0449eed1fe
fix(ci): boolean config variable 7 years ago
GeekQu b8d383f8f3
可用 Xcat 执行配置新增检测 7 years ago
GeekQu f0cb4b710a
修复 7 years ago
GeekQu 4f312527ae
网站配置 7 years ago
Anankke d69fb6b1b8
Merge pull request #870 from regendsoh/patch-1
Fix: Remove preset value of $_ENV['reg_obfs_param']
7 years ago
Anankke 000abaa4d7
Merge pull request #872 from xcxnig/dev
clean(discord): remove invalid discord config
7 years ago
Miku 9dfd9e992a
Update UserController.php 7 years ago
Miku 90f11f9e50
Update config.php 7 years ago
Miku 8bfa574c7f
Update Config.php 7 years ago
Regend Soh ad160e46f7
Fix: Remove preset value of $_ENV['reg_obfs_param']
To avoid problem when setting up SSPanel for idiotic user.
防止傻逼不会弄单端口
7 years ago
TheCGDF 38283cf96d 调整:当余额高于auto_clean_min_money时,即使账户到期后也不会被删除。避免歧义 7 years ago
錢爸爸 67334f8abf
Change style 7 years ago
錢爸爸 56ebebf928
Change style 7 years ago
GeekQu 8546a43f9e
修复 7 years ago
GeekQu 895410e80f
术后修复 7 years ago
GeekQu 3c063f5b4b
Merge branch 'pr/43' into dev 7 years ago
Anankke ccac5960ff
Merge pull request #867 from xcxnig/dev
Optimize link alignment
7 years ago
Miku 9c905ff215
Optimize link alignment 7 years ago
SakuraSa233 051ffc57f9
clean(cloudxns): remove mostly unused cloudxns 7 years ago
SakuraSa233 74e5f87b84
feat(conf): un-string variable type 7 years ago
SakuraSa233 d01adce482
clean(discord): remove invalid discord bot 7 years ago
SakuraSa233 8d7e1f9293
refactor(middleware): refactor ModMu for better perf(?) 7 years ago
SakuraSa233 0fecd8600b
perf(auth): user identification cache 7 years ago
SakuraSa233 082f7c5a00
fix(middleware): correct comment 7 years ago
SakuraSa233 e40e820135
clean(utils): remove unused Helper class 7 years ago
SakuraSa233 d06ebb83c4
refactor(middleware): style refactor and optimize 7 years ago
SakuraSa233 2dbdf2a25c
clean(controller): remove prorietary ApiController 7 years ago
SakuraSa233 a98ff85079
clean(utils): remove unused utils classes 7 years ago
SakuraSa233 6be1abfaf1
fix(tmt-pay): response return 7 years ago
SakuraSa233 83db32626f
clean(services): remove unused Slim class 7 years ago
SakuraSa233 b56272fe07
clean(controller): remove prorietary client api controller 7 years ago
GeekQu 588696234e
更新说明 7 years ago
Rico cf12b34262 修改flag,看着不是很丑了 7 years ago
Rico dfa3e01157 中转tls,clash 增加skip-cert-verify=true 7 years ago
Anankke be379f66a9
Merge pull request #860 from zeva20/bugfix
fix(user) Fix missing obfs_param data
7 years ago
zeva20 accd82e754 fix(user) Fix missing obfs_param data 7 years ago
Rico ff2d944dbe 出去多余的一栏bitpay 7 years ago
錢爸爸 0a4f629226
random gravatar avatar 7 years ago
GeekQu eed442a52b
Update PortAutoChange.php 7 years ago
GeekQu 3aabb5c58a PortAutoChange 7 years ago
Rico 52b1e8ca1d 修改quan,在有relayserver和tls的前提下,允许非安全 7 years ago
GeekQu 245f584a9e 修复 IPv6 访问订阅出现的问题 7 years ago
Rico 273e6c39c2 修改小火箭,在有relayserver和tls的前提下,允许非安全 7 years ago
錢爸爸 da7ca38780
admin/user add obfs_param
就是喜歡在web直接水Commit
7 years ago
錢爸爸 30e24b24c3
admin/user add obfs_param 7 years ago
SakuraSa233 c0eee00f74
refactor(tmtpay): style refactor and code optimize 7 years ago
SakuraSa233 6d918b8c11
feat(payment): add comments for AbstractPayment function 7 years ago
SakuraSa233 1c6b49555d
fix(routes): remove Mu middleware and controller 7 years ago
SakuraSa233 04899474d3
fix(tree): remove unused files 7 years ago
SakuraSa233 c358c7ae45
fix(payment): remove invalid DoiAmPay 7 years ago
SakuraSa233 fd4aa61bb9
fix(payment): remove invalid TrimePay 7 years ago
Regend Soh 1279aea9cf Fix: MySQL 8.0 support for income calculation (#856)
* Fix: MySQL 8.0 support for income calculation

* Fix: MySQL 8.0 support for income calculation
7 years ago
Regend Soh 110229fe5a feat: 接入番茄支付平台 (#855)
这是好的
7 years ago
錢爸爸 6c2830c0db
Update README.md 7 years ago
GeekQu 30e7577b86 Create PortAutoChange.php 7 years ago
Anankke 9b0005b013
Merge pull request #850 from regendsoh/patch-3
Fix bug: display last month Income
7 years ago
Regend Soh e4329a7661
Fix bug: display last month Income
Ref: https://stackoverflow.com/questions/19727274/strtotime-bug-when-using-1-month-from-january
7 years ago
Anankke 9f24cffb73
Merge pull request #849 from GeekQu/Anankke_dev
包含订阅信息的客户端下载方式
7 years ago
GeekQu 2db61fb807 包含订阅信息的客户端下载方式 7 years ago
GeekQu cf4b62966c
Merge pull request #42 from Anankke/dev
merge 20191027
7 years ago
Anankke 1a8dd4d873
Merge pull request #846 from regendsoh/patch-2
Simplify if...else statement from previous commit
7 years ago
Regend Soh d217000ca2
Simplify if...else statement from previous commit
as mentioned.
7 years ago
SakuraSa233 a2e471d9f9
fix(composer): lost pagination
fix #844
7 years ago
Anankke 2782c532cc
Merge pull request #845 from regendsoh/patch-1
Fix bug for income calculation
7 years ago
Regend Soh 532f2f457f
Fix bug for income calculation
Fix bug as mentioned by @topjohncian
7 years ago
Anankke 9601dd3aa6
Merge pull request #835 from lifespy/dev
新增易付支付
7 years ago
GeekQu 7911c76057
Merge pull request #59 from GeekQu/dev
修复 Shadowrocket ss-v2ray-plugin 节点的编码错误
7 years ago
GeekQu 12ccc306d8 +1 7 years ago
GeekQu 60e82fc07f 修改客户端下载链接 7 years ago
GeekQu e9fa797b25 修复 Shadowrocket ss-v2ray-plugin 节点的编码错误 7 years ago
GeekQu b24f68098e ss && ssd 7 years ago
GeekQu 77c7f2e8c9 fix 7 years ago
TheCGDF c7140d35ad 修复签到后流量显示异常 7 years ago
GeekQu 42cf1b8749 Create README.md 7 years ago
GeekQu 31b53a0052 getPcClient 7 years ago
laurieryayoi 0e3e64b952 fix no-empty bug 7 years ago
laurieryayoi 2806ea97fa 节点列表v1 7 years ago
GeekQu f955323d3c getPcClient 7 years ago
GeekQu 0a4cda9047
Merge pull request #58 from GeekQu/dev
20191015
7 years ago
GeekQu 764b300582 修复 Surge 4 使用 Surge 2 规则的问题 7 years ago
GeekQu a8470bb0a3 修复缺失的判断 7 years ago
GeekQu 7a7ec8a192 分离 YAML2Array 7 years ago
GeekQu fea0fc9580 telegram 推送自定义设置 2 7 years ago
GeekQu 5bc4a557b7 修改 sendDiary_Msg 7 years ago
SakuraSa233 972bd1ede8
feat(git): update contribute guide 7 years ago
SakuraSa233 8082ea7bb2
feat(controller): refactor HomeController as standard 7 years ago
SakuraSa233 093dbc3d48
fix(composer): clean php dependencies 7 years ago
GeekQu 805e602d5a telegram 推送自定义设置 7 years ago
GeekQu a835ba415b Update ConfController.php 7 years ago
GeekQu ae58db22ee 术后修复 7 years ago
GeekQu 647efbecc7 Merge branch 'pr/41' into dev 7 years ago
Anankke 51a10a31b6
Merge pull request #838 from NS-Sp4ce/dev
修复安卓V2RayNG链接错误
7 years ago
Sp4ce 7fc7046290
修复安卓V2RayNG链接错误
修复安卓V2RayNG链接错误
7 years ago
GeekQu 44bcbbcb6f 修复 Base64_url_encode 带来的兼容问题 7 years ago
GeekQu 7a7a7d8044 2333 7 years ago
GeekQu 7516dfcf83 修复 Quantumult SS 订阅的兼容问题 7 years ago
GeekQu 87d178fd29 Update index.tpl 7 years ago
GeekQu 36799fc57b 为 Clash VMess 加入 udp 字段 7 years ago
GeekQu 9beb73c5a0 重写订阅中的用户账户到期及流量展示,现在可以在 Config 配置为订阅添加一些简短的公告了 7 years ago
GeekQu f4c1688f84 可移除 SS 节点名称中的站点名 7 years ago
lifespy c4e38e84d3 yft 7 years ago
GeekQu 53c9578796 解决 Quantumult SS 订阅提示无 group 的问题 7 years ago
GeekQu 6dab034a26 emoji 7 years ago
TheCGDF 275941191f V2rayU -> ssr-download 7 years ago
laurieryayoi ed70ab3ed8 替换update中的System_config为_ENV 7 years ago
Regend Soh d747eedadd config: update default params(#829)
避免小白继续祸害各大运营商IP
7 years ago
錢爸爸 576e9e5b98
Update README.md 7 years ago
錢爸爸 8d5b103234
fix:Gravatar url 7 years ago
Anankke e42e5ee3e0 refactor: 129137b773 (r35233741) 7 years ago
SukkaW e1907e3b7b refactor(gravatar): minor updates 7 years ago
Regend Soh 8916041998 feat: add copy button for node SSR and SS link (#816)
* Add copy button for node SSR and SS link

* Remove unnecessary script
7 years ago
Regend Soh c92a52df64 feat: add function to display disable reason for disabled accounts (#815)
* Add disableReason Function

* Added disable reason based on 审计规则
7 years ago
錢爸爸 a7503a8207
Restore Gravatar function & Add set Avatar 7 years ago
錢爸爸 129137b773
Restore Gravatar function 7 years ago
Regend Soh 84ad7f2bf3 feat: add paid user count feature (#814)
* Add paidUserCount function

* Add display of paidUserCount
7 years ago
Regend Soh 89ea1b75d8 feat: add display income feature (#813)
* Adding income calculation function

Below functions are added:
- yesterday_income()
- today_income()
- this_month_income()
- last_month_income()
- total_income()

* Add income display on /admin/code page

Display the following information at /admin/code
- Today's income
- Yesterday's income
- This month's income
- Last month's income
- Total income

* Reformatting code style

Reformat the code, attempting to follow the standard required.

* Refactor to camel case naming

* Refactor to camel case naming

* Reformat due to spacing and tabbing issue
7 years ago
Anankke 797bd35f1b revert: "fix(init): remove default http forward header handle"
This reverts commit 040e987a
7 years ago
SakuraSa233 189bbf9026
fix(ci): sync test config file 7 years ago
SakuraSa233 91b2bf2016
feat(config): store config to $_ENV 7 years ago
SakuraSa233 fb8bd622fb
clean(services\config): unused env set function 7 years ago
SakuraSa233 040e987aa6
fix(init): remove default http forward header handle 7 years ago
Regend Soh badc98f29e feat(admin): add aff id change function
* 添加修改用户邀请者

* 添加 chginvite 路由

* 添加chgInvite function
7 years ago
Anankke 76d7d586d9
Merge pull request #807 from wewall/patch-2
fix error(user/index): rm obsolete code
7 years ago
围墙 bc05bb18ff
fix error(user/index): rm obsolete code 7 years ago
NimaQu 66f8d8bc8f
Update README.md 7 years ago
Anankke 85306ae54d
Merge pull request #803 from pang-w/dev
#801 修复暴力获取mu参数引发的错误。
7 years ago
Pw 8d5122c7b4 * 修复暴力获取mu参数引发的错误。
* 简单优化没有mu参数的逻辑。
7 years ago
GeekQu bb805d65a4 Merge branch 'pr/40' into Anankke_dev 7 years ago
GeekQu 0a94ae0778 +1 8 years ago
GeekQu c9b0573f43 修正 Clash ss 节点异常输出 obfs-host 8 years ago

@ -1,22 +0,0 @@
# 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

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

@ -0,0 +1,34 @@
---
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. 如有可能,请提供更多相关资料。

@ -0,0 +1,19 @@
---
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.

@ -1,49 +0,0 @@
---
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 输出内容。
-->
<!--从这一行往下写--我是分割线-->

4
.gitignore vendored

@ -6,6 +6,7 @@
composer.lock
.php_cs.cache
.env
.editorconfig
vendor
php_errors.log
@ -41,4 +42,5 @@ malio-noobfs.js
malio-dev.js
malio-release.js
malio.js
resources/email/template
resources/email/template
.i18n.php

@ -1,28 +0,0 @@
<?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>

@ -16,14 +16,19 @@ pull request for each branch. This allows each feature or improvement to be revi
### Coding Style
All pull requests and commits **must** adhere to the [PSR-2 standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md) at least.
All pull requests and commits **must** adhere to the [PSR-2 standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md) at least.
And we **recommend** adhering to the [PSR-12 standard](https://github.com/php-fig/fig-standards/blob/master/proposed/extended-coding-style-guide.md).
### Commit message
The Commit message **must** containe all the changes you maked in sort.
The Commit message **must** containe all the changes you maked in sort.
Please **do not** use words like "fix", "improve" only.
### Rule
If you want to add a new function for router callback, please follow the structure of the HomeController.
Please use the function from PSR-7 like `$request->getParsedBodyParam()`, `getParsedBodyParam()` as possible.
## 简体中文
### Pull Request
@ -36,9 +41,14 @@ Please **do not** use words like "fix", "improve" only.
### 代码风格
所有的 Pull request 和 commit 都至少**必须**遵守 [PSR-2 标准](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)。
所有的 Pull request 和 commit 都至少**必须**遵守 [PSR-2 标准](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)。
我们建议**最好**遵守 [PSR-12 标准](https://github.com/php-fig/fig-standards/blob/master/proposed/extended-coding-style-guide.md)。
### Commit 消息
Commit 消息必须简洁地包含你所有的修改。请不要仅使用「修复」、「改进」等字样。
### 规范
若你需要新增/修改 Router callback,请依照类似 HomeController 的形式。
如无必要,请不要使用`$request->getParam()`并尽量使用 PSR-7 中的`$request->getParsedBodyParam()`、`getParsedBodyParam()`等一系列用于获取参数的方法。

@ -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 托管配置
……

@ -1,12 +1,171 @@
# 请勿泄露源码给他人,当你让他人为你debug或进行其他操作时,切勿让他访问你网站的全部代码,尤其是不认识的人。泄露源码对你我都没好处。
# 不能删改页面底部的 Powered by SSPANEL. Theme by editXY,不能删改staff页面的任何信息。
# 不能删改页面底部的 Powered by SSPANEL,不能删改staff页面的任何信息。
## 删除Powered by SSPANEL可能会导致你的网站被D,现在 Theme by editXY 可以随意去掉
本主题包含了SSPANEL的完整代码,需要删除原来的面板,然后全新安装(数据库通用),操作前请备份面板
## Wiki
[详细安装教程](https://gitlab.com/maxitio/malio-theme-for-sspanel/wikis/详细安装教程)
## 安装步骤
[授权说明](https://gitlab.com/maxitio/malio-theme-for-sspanel/wikis/授权说明)
# 安装宝塔面板
使用SSH登录你的VPS,根据你VPS的系统选择下面的安装命令
宝塔面板 Centos 一键安装脚本👇
```
yum install -y wget && wget -O install.sh http://download.bt.cn/install/install_6.0.sh && sh install.sh
```
宝塔面板 Ubuntu/Debian 一键安装脚本👇
```
wget -O install.sh http://download.bt.cn/install/install-ubuntu_6.0.sh && sudo bash install.sh
```
输入 `y` 回车安装
执行完毕后,会显示类似下面的宝塔面板的登录信息,请保存好此信息
```
Bt-Panel: http://xxx.xxx.xx.xx:8888/xxxxxxx
username: xxxxxxx
password: xxxxxxxx
```
# 安装LNMP
登录宝塔面板后,宝塔面板会提示你安装 PHP, MySQL, Nginx 等环境。
推荐使用 PHP 7.1、MySQL 5.6、Nginx任意版本。
需要一段时间才能安装完成,请等待完成。
# 配置PHP
打开 `宝塔面版 > 软件商店 > 你安装的PHP > 设置`,在禁用函数一栏删除 `system`、`proc_open`、`proc_get_status`、`putenv`、`pcntl_signal`。
# 安装Malio主题
打开 `宝塔面版 > 网站 > 添加站点`,输入你的域名,点击提交
------
在SSH里执行下面命令👇👇👇
下载SSPANEL+Malio的代码。如果你的这个网站文件夹包含原版的SSPANEL代码,请删除原版SSPANEL代码或者换个目录
```
cd /www/wwwroot/你的网站文件夹名
git clone -b malio https://gitlab.com/maxitio/malio-theme-for-sspanel.git tmp && mv tmp/.git . && rm -rf tmp && git reset --hard
```
然后Git会要求你输入Gitlab的账号密码
使用composer安装依赖
```
wget https://getcomposer.org/installer -O composer.phar
php composer.phar
php composer.phar install
```
用composer安装依赖时如果内存不够的话,可以使用 `宝塔面版 > 首页 > Linux工具箱 > Swap/虚拟内存` 增加虚拟内存
复制配置文件
```
cp config/.malio_config.example.php config/.malio_config.php
cp config/.config.example.php config/.config.php
cp config/.i18n.example.php config/.i18n.php
```
------
打开 `宝塔面版 > 网站 > 你的网站`
在 `网站目录` 里取消勾选 `防跨站攻击`,运行目录里面选择 `/public`,点击保存。
在 `伪静态` 中填入下面内容,然后保存
```
location / {
try_files $uri /index.php$is_args$args;
}
```
------
在SSH里的网站目录下执行,给网站文件755权限
```
cd ../
chmod -R 755 你的文件夹名/
chown -R www:www 你的文件夹名/
```
# 数据库操作
打开 `宝塔面版 > 数据库`,选择添加数据库,数据库名字和用户名任意写,密码建议使用随机生成的密码,点击提交即可添加数据库
点击数据库名字旁边的 `导入 > 本地上传`,即可上传并导入sql文件到数据库
如果你是全新安装面板,请上传并导入网站目录下的 `/sql/glzjin_all.sql`、`/sql/malio_all.sql`
如果你是从其他主题迁移到Malio主题,请上传并导入网站目录下的 `/sql/malio_all.sql`、`/sql/user_subscribe_log.sql`、`/sql/detect_ban_log.sql`
如果没有导入 `/sql/malio_all.sql` 的话会导致无法注册新用户
将数据库user表里的全部用户的theme列改为malio,使用phpmyadmin执行这条sql语句👉 `UPDATE user SET theme='malio'`
# 编辑 config.php
将你的数据库名字,用户名和密码填入.config.php里,类似下面这样
```
$_ENV['db_database'] = 'sspanel'; //数据库名
$_ENV['db_username'] = 'sspanel'; //数据库用户名
$_ENV['db_password'] = 'sspanel_password'; //用户名对应的密码
```
# 其他操作
在SSH里的网站目录下执行 `php xcat createAdmin`,即可创建管理员用户。(如果你已经有了管理员用户就不用创建了)
在SSH里的网站目录下执行 `php xcat initQQWry `,即可下载IP数据库(必须要执行这个)
下载通知频道里的 `GeoLite2-City.mmdb` 文件放入网站目录下的 `/storage/` 目录下
为Crisp和Chatra的跨设备恢复会话功能生成UUID,在SSH里网站目录下执行👉 `php xcat GenerateUUIDforAllUsers`
# 配置定时任务
执行 `crontab -e` 命令,添加以下:
```
0 0 * * * php -n /www/wwwroot/你的文件夹名/xcat dailyjob
*/1 * * * * php /www/wwwroot/你的文件夹名/xcat checkjob
*/1 * * * * php /www/wwwroot/你的文件夹名/xcat syncnode
```
# 客户端下载
客户端的安装包需要自行下载到 `/public/client-download/` 目录,安装包名字参考同目录下的 apps.txt 文件
另外在此目录下还提供了 [download.sh](https://github.com/sspanel-uim/ssr-download-updater) 脚本,可自动下载部分客户端。
# 请仔细阅读 .malio_config.php 和 .config.php 的全部注释,进一步了解SSPANEL
## 贡献
[提出新想法 & 提交 Bug](https://github.com/Cadwalader307/Malio-Theme-for-SSPANEL/issues/new) | [改善文档 & 投稿](https://github.com/Cadwalader307/Malio-Theme-for-SSPANEL/Wiki) | [Fork & Pull Request](https://github.com/Cadwalader307/Malio-Theme-for-SSPANEL/pulls)
由于原开发团队已经放弃Malio主题,因此此项目欢迎各种贡献,包括但不限于改进,新功能,文档和代码改进,问题和错误报告。
## 注意事项
.malio_config.php 文件里的商品id必须设置好,不然在商店plans模式下没办法购买。
@ -21,11 +180,8 @@
需要去.config.php打开订阅记录的开关才会记录订阅
## Telegram
[TG群组](https://t.me/joinchat/DM2_FxStXAbYZ2DzVfZjcw)
[TG频道](https://t.me/malio_for_sspanel) ,有新功能或优化都会在频道里发广播,所以请一定要关注频道
https://t.me/woaizyg)
## CREDIT
基于 [rico](https://github.com/rico93) 和 [GeekQu](https://github.com/GeekQu) 维护的 [ss-panel-v3-mod_Uim](https://github.com/rico93/ss-panel-v3-mod_Uim) 修改
基于 [Anankke](https://github.com/Anankke),[galaxyq](https://github.com/galaxychuck),[dumplin](https://github.com/dumplin233),[Rin SAMA](https://github.com/mxihan),[Miku](https://github.com/xcxnig),[Tony Zou](https://github.com/ZJY2003),[Nymph](https://github.com/laurieryayoi) 维护的 [SSPanel-Uim](https://github.com/Anankke/SSPanel-Uim) 修改

@ -52,11 +52,21 @@ class DailyMail
$sts = new Analytics();
Telegram::Send('各位老爷少奶奶,我来为大家报告一下系统今天的运行状况哈~' .
PHP_EOL .
'今日签到人数:' . $sts->getTodayCheckinUser() . PHP_EOL .
'今日使用总流量:' . Tools::flowAutoShow($lastday_total) . PHP_EOL .
'晚安~');
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')
)
);
}
}

@ -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 .

@ -19,6 +19,7 @@ use App\Models\TelegramSession;
use App\Models\EmailVerify;
use App\Models\UserSubscribeLog;
use App\Models\DetectBanLog;
use App\Models\TelegramTasks;
use App\Services\Config;
use App\Services\Password;
use App\Utils\DNSoverHTTPS;
@ -29,11 +30,13 @@ use App\Utils\QQWry;
use App\Utils\GA;
use App\Utils\Telegram;
use ArrayObject;
use CloudXNS\Api;
use App\Models\Disconnect;
use App\Models\GConfig;
use App\Models\Token;
use App\Models\UnblockIp;
use Exception;
use RuntimeException;
use Ramsey\Uuid\Uuid;
class Job
{
@ -75,7 +78,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',
@ -101,7 +104,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('备份完毕了喵~今天又是安全祥和的一天呢。');
}
}
@ -153,6 +156,8 @@ class Job
// 清理订阅记录
UserSubscribeLog::where('request_time', '<', date('Y-m-d H:i:s', time() - 86400 * (int) Config::get('subscribeLog_keep_days')))->delete();
Token::where('expire_time', '<', time())->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();
@ -160,7 +165,10 @@ class Job
Speedtest::where('datetime', '<', time() - 86400 * 3)->delete();
EmailVerify::where('expire_in', '<', time() - 86400 * 3)->delete();
system('rm ' . BASE_PATH . '/storage/*.png', $ret);
Telegram::Send('姐姐姐姐,数据库被清理了,感觉身体被掏空了呢~');
if (Config::getdb('Telegram.enable.DailyJob') !== '0') {
Telegram::Send(Config::getdb('Telegram.msg.DailyJob'));
}
//auto reset
$boughts = Bought::all();
@ -300,7 +308,7 @@ class Job
$ips[$alive_ip->ip] = 1;
if ($user->node_connector < count($ips)) {
//暂时封禁
$isDisconnect = Disconnect::where('id', '=', $alive_ip->ip)->where(
$isDisconnect = Disconnect::where('ip', '=', $alive_ip->ip)->where(
'userid',
'=',
$user->id
@ -443,12 +451,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(
@ -478,63 +486,20 @@ class Job
Mail::send($to, $subject, 'news/warn.tpl', [
'user' => $user,
'text' => $text
], [
]);
} catch (Exception $e) {
echo $e->getMessage();
}
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 . ' 节点掉线了喵~';
}
$notice_text = str_replace(
'%node_name%',
$node->name,
Config::getdb('Telegram.msg.NodeOffline')
);
}
Telegram::Send($notice_text);
if (Config::getdb('Telegram.enable.NodeOffline') !== '0') {
Telegram::Send($notice_text);
}
$myfile = fopen(
BASE_PATH . '/storage/' . $node->id . '.offline',
@ -544,7 +509,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(
@ -574,53 +539,20 @@ class Job
Mail::send($to, $subject, 'news/warn.tpl', [
'user' => $user,
'text' => $text
], [
]);
} catch (Exception $e) {
echo $e->getMessage();
}
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 . ' 节点恢复了喵~';
}
$notice_text = str_replace(
'%node_name%',
$node->name,
Config::getdb('Telegram.msg.NodeOnline')
);
}
Telegram::Send($notice_text);
if (Config::getdb('Telegram.enable.NodeOnline') !== '0') {
Telegram::Send($notice_text);
}
unlink(BASE_PATH . '/storage/' . $node->id . '.offline');
}
@ -629,7 +561,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) {
@ -679,6 +611,11 @@ class Job
$users = User::all();
foreach ($users as $user) {
$user->uuid = Uuid::uuid3(
Uuid::NAMESPACE_DNS,
strval($user->id) . '|' . $user->passwd
)->toString();
$user->save();
if (($user->transfer_enable <= $user->u + $user->d || $user->enable == 0 || (strtotime($user->expire_in) < time() && strtotime($user->expire_in) > 644447105)) && RadiusBan::where(
'userid',
$user->id
@ -723,7 +660,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';
@ -765,7 +702,9 @@ class Job
}
if (Config::get('account_expire_delete_days') >= 0 &&
strtotime($user->expire_in) + Config::get('account_expire_delete_days') * 86400 < time()
strtotime($user->expire_in) + Config::get('account_expire_delete_days') * 86400 < time() &&
$user->money <= Config::get('auto_clean_min_money')
) {
$subject = Config::get('appName') . '-您的用户账户已经被删除了';
$to = $user->email;
@ -859,10 +798,12 @@ class Job
}
// 审计封禁解封
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;
if ($user->enable == 0) {
$logs = DetectBanLog::where('user_id', $user->id)->orderBy('id', 'desc')->first();
if ($logs != null) {
if (($logs->end_time + $logs->ban_time * 60) <= time()) {
$user->enable = 1;
}
}
}
@ -883,6 +824,21 @@ class Job
Radius::Add($user, $user->passwd);
}
}
if (Config::get('enable_telegram') === true) {
# 删除 tg 消息
$TelegramTasks = TelegramTasks::where('type', 1)->where('executetime', '<', time())->get();
foreach ($TelegramTasks as $Task) {
\App\Utils\Telegram\TelegramTools::SendPost('deleteMessage', ['chat_id' => $Task->chatid, 'message_id' => $Task->messageid]);
TelegramTasks::where('chatid', $Task->chatid)->where('type', '<>', 1)->where('messageid', $Task->messageid)->delete();
$Task->delete();
}
}
if ($_ENV['enable_auto_detect_ban'] === true) {
self::DetectBan();
}
}
public static function detectGFW()
@ -939,50 +895,15 @@ class Job
} catch (Exception $e) {
echo $e->getMessage();
}
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 . ' 节点被墙了喵~';
}
$notice_text = str_replace(
'%node_name%',
$node->name,
Config::getdb('Telegram.msg.NodeGFW')
);
}
if (Config::getdb('Telegram.enable.NodeGFW') !== '0') {
Telegram::Send($notice_text);
}
Telegram::Send($notice_text);
$file_node = fopen(BASE_PATH . '/storage/' . $node->id . '.gfw', 'wb+');
fclose($file_node);
} else {
@ -1005,42 +926,15 @@ class Job
} catch (Exception $e) {
echo $e->getMessage();
}
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 . ' 节点恢复了喵~';
}
$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);
}
Telegram::Send($notice_text);
unlink(BASE_PATH . '/storage/' . $node->id . '.gfw');
}
}
@ -1051,4 +945,88 @@ class Job
sleep(3);
}
}
public static function DetectBan()
{
echo '审计封禁检查开始.';
$last_id = (int) Config::getdb('get.Detect.Log');
$new_logs = DetectLog::where('id', '>', $last_id)->orderBy('id', 'desc')->get();
if (count($new_logs) != 0) {
$Config = GConfig::find('get.Detect.Log');
$Config->value = $new_logs[0]->id;
$Config->save();
$user_logs = [];
foreach ($new_logs as $log) {
if (!in_array($log->user_id, array_keys($user_logs))) {
$user_logs[$log->user_id] = 0;
}
$user_logs[$log->user_id]++;
}
foreach ($user_logs as $userid => $value) {
$user = User::find($userid);
if ($user == null) {
continue;
}
$user->all_detect_number += $value;
$user->save();
if ($user->enable == 0 || ($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', $userid)->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->enable = 0;
$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->enable = 0;
$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();
}
}
}
}
}
echo '审计封禁检查结束.';
}
}

@ -0,0 +1,239 @@
<?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,12 +3,13 @@
namespace App\Command;
use App\Services\Config;
use App\Services\DefaultConfig;
class Update
{
public static function update($xcat)
{
global $System_Config;
global $_ENV;
$copy_result = copy(BASE_PATH . '/config/.config.php', BASE_PATH . '/config/.config.php.bak');
if ($copy_result == true) {
echo ('备份成功' . PHP_EOL);
@ -17,7 +18,11 @@ class Update
return false;
}
echo (PHP_EOL);
echo(PHP_EOL);
// 检查并创建新增的配置项
echo DefaultConfig::detectConfigs();
echo(PHP_EOL);
echo('开始升级客户端...' . PHP_EOL);
Job::updatedownload();
@ -33,17 +38,17 @@ class Update
$config_new = file_get_contents(BASE_PATH . '/config/.config.example.php');
//执行版本升级
$version_old = $System_Config['version'] ?? 0;
$version_old = $_ENV['version'] ?? 0;
self::old_to_new($version_old);
//将旧config迁移到新config上
$migrated = array();
foreach ($System_Config as $key => $value_reserve) {
foreach ($_ENV as $key => $value_reserve) {
if ($key == 'config_migrate_notice' || $key == 'version') {
continue;
}
$regex = '/System_Config\[\'' . $key . '\'\].*?;/s';
$regex = '/_ENV\[\'' . $key . '\'\].*?;/s';
$matches_new = array();
preg_match($regex, $config_new, $matches_new);
if (isset($matches_new[0]) == false) {
@ -55,20 +60,18 @@ class Update
preg_match($regex, $config_old, $matches_old);
$config_new = str_replace($matches_new[0], $matches_old[0], $config_new);
$migrated[] = 'System_Config[\'' . $key . '\']';
$migrated[] = '_ENV[\'' . $key . '\']';
}
echo (PHP_EOL);
//检查新增了哪些config
$regex_new = '/System_Config\[\'.*?\'\]/s';
$regex_new = '/_ENV\[\'.*?\'\]/s';
$matches_new_all = array();
preg_match_all($regex_new, $config_new, $matches_new_all);
$differences = array_diff($matches_new_all[0], $migrated);
foreach ($differences as $difference) {
if (
$difference == 'System_Config[\'config_migrate_notice\']' ||
$difference == 'System_Config[\'version\']'
) {
if ($difference == '_ENV[\'config_migrate_notice\']' ||
$difference == '_ENV[\'version\']') {
continue;
}
//匹配注释
@ -97,7 +100,7 @@ class Update
echo ('新增配置项通常带有默认值,因此通常即使不作任何改动网站也可以正常运行' . PHP_EOL);
//输出notice
$regex_notice = '/System_Config\[\'config_migrate_notice\'\].*?(?=\';)/s';
$regex_notice = '/_ENV\[\'config_migrate_notice\'\].*?(?=\';)/s';
$matches_notice = array();
preg_match($regex_notice, $config_new, $matches_notice);
$notice_new = $matches_notice[0];
@ -109,10 +112,10 @@ class Update
strpos($notice_new, '=') //查找'='之后的第一个'\'',然后substr其后面的notice
) + 1
);
echo ('以下是迁移附注:');
if (isset($System_Config['config_migrate_notice'])) {
if ($System_Config['config_migrate_notice'] != $notice_new) {
echo ($notice_new);
echo('以下是迁移附注:');
if (isset($_ENV['config_migrate_notice'])) {
if ($_ENV['config_migrate_notice'] != $notice_new) {
echo($notice_new);
}
} else {
echo ($notice_new);
@ -136,11 +139,6 @@ 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');
}
}
public static function update_malio_config($xcat)

@ -12,9 +12,8 @@ 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;
@ -33,6 +32,10 @@ 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'):
@ -41,8 +44,6 @@ class XCat
return $this->createAdmin();
case ('resetTraffic'):
return $this->resetTraffic();
case ('setDiscord'):
return Discord::set();
case ('setTelegram'):
return $this->setTelegram();
case ('initQQWry'):
@ -97,11 +98,11 @@ class XCat
return $this->resetPort();
case ('resetAllPort'):
return $this->resetAllPort();
case ('update'):
return Update::update($this);
case ('update'):
return Update::update($this);
case ('sendDailyUsageByTG'):
return $this->sendDailyUsageByTG();
case ('npmbuild'):
case ('npmbuild'):
return $this->npmbuild();
case ('getCookie'):
return $this->getCookie();
@ -109,26 +110,27 @@ class XCat
return $this->iptest();
case ('GenerateUUIDforAllUsers'):
return Malio::GenerateUUIDforAllUsers();
default:
case ('delSubCache'):
return $this->delSubCache();
default:
return $this->defaultAction();
}
}
public function defaultAction()
{
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(' 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 (' 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);
}
public function resetPort()
@ -165,9 +167,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;
}
@ -175,7 +177,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();
}
}
@ -208,7 +210,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';
}
@ -272,33 +274,42 @@ 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);
$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);
if (Config::get('use_new_telegram_bot') === true) {
$WebhookUrl = (Config::get('baseUrl') . '/TelegramCallback?token=' . Config::get('telegram_request_token'));
$telegram = new \Telegram\Bot\Api(Config::get('telegram_token'));
$telegram->removeWebhook();
if ($telegram->setWebhook(['url' => $WebhookUrl])) {
echo('New Bot @' . $telegram->getMe()->getUsername() . ' 设置成功!');
}
} else {
$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);
$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 ('Old Bot 设置成功!' . 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 反馈!');
}
}
@ -337,11 +348,12 @@ class XCat
}
}
public function npmbuild(){
chdir(BASE_PATH . '/uim-index-dev');
system('npm install');
system('npm run build');
system('cp -u ../public/vuedist/index.html ../resources/views/material/index.tpl');
public function npmbuild()
{
chdir(BASE_PATH . '/uim-index-dev');
system('npm install');
system('npm run build');
system('cp -u ../public/vuedist/index.html ../resources/views/material/index.tpl');
}
public function iptest()
@ -357,8 +369,8 @@ class XCat
$ip = DNSoverHTTPS::gethostbyName($server); // returns a collection of DNS A Records
}
}
if ($server!="" and $ip !="") {
echo "Server: ".$server." ip address: ".$ip."\n";
if ($server != "" and $ip != "") {
echo "Server: " . $server . " ip address: " . $ip . "\n";
}
}
}
@ -371,4 +383,22 @@ 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);
}
}
}

@ -0,0 +1,108 @@
<?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);
}
}

@ -19,7 +19,7 @@ class NodeController extends AdminController
{
$table_config['total_column'] = array('op' => '操作', 'id' => 'ID', 'name' => '节点名称',
'type' => '显示与隐藏', 'sort' => '类型',
'server' => '节点地址', 'node_ip' => '节点IP',
'server' => '节点地址', 'outaddress' => '出口地址', 'node_ip' => '节点IP',
'info' => '节点信息',
'status' => '状态', 'traffic_rate' => '流量比率', 'node_group' => '节点群组',
'node_class' => '节点等级', 'node_speedlimit' => '节点限速/Mbps',
@ -93,11 +93,21 @@ class NodeController extends AdminController
$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);
}
Telegram::Send('新节点添加~' . $request->getParam('name'));
if (Config::getdb('Telegram.enable.AddNode') !== '0') {
Telegram::Send(
str_replace(
'%node_name%',
$request->getParam('name'),
Config::getdb('Telegram.msg.AddNode')
)
);
}
Tools::delSubCache();
$rs['ret'] = 1;
$rs['msg'] = '节点添加成功';
@ -186,7 +196,17 @@ class NodeController extends AdminController
$node->save();
Telegram::Send('节点信息被修改~' . $request->getParam('name'));
if (Config::getdb('Telegram.enable.UpdateNode') !== '0') {
Telegram::Send(
str_replace(
'%node_name%',
$request->getParam('name'),
Config::getdb('Telegram.msg.UpdateNode')
)
);
}
Tools::delSubCache();
$rs['ret'] = 1;
$rs['msg'] = '修改成功';
@ -202,15 +222,23 @@ 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));
}
Telegram::Send('节点被删除~' . $name);
if (Config::getdb('Telegram.enable.DeleteNode') !== '0') {
Telegram::Send(
str_replace(
'%node_name%',
$node->name,
Config::getdb('Telegram.msg.DeleteNode')
)
);
}
Tools::delSubCache();
$rs['ret'] = 1;
$rs['msg'] = '删除成功';
@ -224,7 +252,7 @@ class NodeController extends AdminController
$total_column = array('op' => '操作', 'id' => 'ID', 'name' => '节点名称',
'type' => '显示与隐藏', 'sort' => '类型',
'server' => '节点地址', 'node_ip' => '节点IP',
'server' => '节点地址', 'outaddress' => '出口地址', 'node_ip' => '节点IP',
'info' => '节点信息',
'status' => '状态', 'traffic_rate' => '流量比率', 'node_group' => '节点群组',
'node_class' => '节点等级', 'node_speedlimit' => '节点限速/Mbps',
@ -238,6 +266,10 @@ class NodeController extends AdminController
$key_str .= 'id as op';
continue;
}
if ($single_key == 'outaddress') {
$key_str .= ',server as ' . $single_key;
continue;
}
$key_str .= ',' . $single_key;
}
@ -248,6 +280,10 @@ class NodeController extends AdminController
<a class="btn btn-brand-accent" ' . ($data['sort'] == 999 ? 'disabled' : 'id="delete" value="' . $data['id'] . '" href="javascript:void(0);" onClick="delete_modal_show(\'' . $data['id'] . '\')"') . '>删除</a>';
});
$datatables->edit('outaddress', static function ($data) {
return (in_array($data['sort'], [0, 10, 11, 12, 13, 14]) ? explode(';', $data['server'])[0] : '');
});
$datatables->edit('node_bandwidth', static function ($data) {
return Tools::flowToGB($data['node_bandwidth']);
});
@ -286,6 +322,9 @@ class NodeController extends AdminController
case 13:
$sort = 'Shadowsocks - V2Ray-Plugin';
break;
case 14:
$sort = 'Trojan';
break;
default:
$sort = '系统保留';
}

@ -38,7 +38,7 @@ class RelayController extends AdminController
)->orderBy('name')->get();
foreach ($source_nodes as $node) {
if ($node->sort == 12) {
$node->name .= ' 正在使用V2ray后端 ';
$node->name .= 'V2ray中转,Port代表中转监听端口';
}
}
$dist_nodes = Node::where(
@ -53,9 +53,9 @@ class RelayController extends AdminController
foreach ($dist_nodes as $node) {
if ($node->sort == 11 || $node->sort == 12) {
$node_explode = Tools::v2Array($node->server);
$node->name = $node->name . ' 如果是V2ray后端 请设置成 ' . $node_explode['port'];
$node->name = $node->name;
} else {
$node->name .= ' 如果是V2ray后端 请不要设置,用户页面设置 ';
$node->name .= ' 如果是V2ray中转,无法食用';
}
}
@ -79,9 +79,9 @@ class RelayController extends AdminController
if ($source_node->sort == 12) {
$rules = Relay::Where('source_node_id', $source_node_id)->get();
if (count($rules) > 0) {
if (!Tools::relayRulePortCheck($rules)) {
$rs['ret'] = 0;
$rs['msg'] = 'v2ray中转一个起点一个rule';
$rs['msg'] = '端口冲突请,请更换一个';
return $response->getBody()->write(json_encode($rs));
}
}
@ -124,6 +124,8 @@ 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));
@ -164,9 +166,9 @@ class RelayController extends AdminController
foreach ($dist_nodes as $node) {
if ($node->sort == 11 || $node->sort == 12) {
$node_explode = Tools::v2Array($node->server);
$node->name = $node->name . ' 如果是V2ray后端 请设置成' . $node_explode['port'];
$node->name = $node->name . 'V2ray中转,Port代表中转监听端口';
} else {
$node->name .= ' 如果是V2ray后端 请不要设置,用户页面设置 ';
$node->name .= ' 如果是V2ray中转,无法食用';
}
}
@ -234,6 +236,8 @@ 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));
@ -255,6 +259,9 @@ 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));

@ -2,22 +2,22 @@
namespace App\Controllers\Admin;
use App\Models\User;
use App\Models\Ip;
use App\Controllers\AdminController;
use App\Models\Bought;
use App\Models\Ip;
use App\Models\Relay;
use App\Models\User;
use App\Models\DetectBanLog;
use App\Controllers\AdminController;
use App\Services\Config;
use App\Models\Shop;
use App\Services\Auth;
use App\Services\Config;
use App\Services\Mail;
use App\Utils;
use App\Utils\GA;
use App\Utils\Hash;
use App\Utils\Radius;
use App\Utils\QQWry;
use App\Utils\Check;
use App\Utils\Radius;
use App\Utils\Tools;
use App\Utils\GA;
use Exception;
@ -25,19 +25,38 @@ 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' => '连接混淆方式',
'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' => '混淆方式',
'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' => '邀请人用户名',
'top_up' => '累计充值');
$table_config['default_show_column'] = array('op', 'id', 'user_name', 'remark', 'email');
$table_config['ajax_url'] = 'user/ajax';
@ -116,7 +135,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) {
@ -177,7 +196,6 @@ class UserController extends AdminController
return $response->getBody()->write(json_encode($result));
}
public function search($request, $response, $args)
{
$pageNum = 1;
@ -189,11 +207,9 @@ 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();
@ -207,7 +223,6 @@ 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];
@ -216,7 +231,6 @@ class UserController extends AdminController
}
}
return $this->view()->assign('users', $users)->assign('regloc', $regloc)->assign('useripcount', $useripcount)->assign('userip', $userip)->display('admin/user/index.tpl');
}
@ -229,14 +243,11 @@ 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();
@ -250,7 +261,6 @@ 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];
@ -259,11 +269,9 @@ 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'];
@ -286,7 +294,6 @@ class UserController extends AdminController
Radius::ChangeUserName($email1, $email2, $passwd);
if ($request->getParam('pass') != '') {
$user->pass = Hash::passwordHash($request->getParam('pass'));
$user->clean_link();
@ -328,30 +335,21 @@ 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;
$ban_time = (int) $request->getParam('ban_time');
if ($ban_time > 0) {
$user->enable = 0;
$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 = $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();
}
@ -407,7 +405,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'] = '切换成功';
@ -510,6 +508,7 @@ class UserController extends AdminController
//model里是casts所以没法直接 $tempdata=(array)$user
$tempdata['op'] = '<a class="btn btn-brand" href="/admin/user/' . $user->id . '/edit">编辑</a>
<a class="btn btn-brand-accent" id="delete" href="javascript:void(0);" onClick="delete_modal_show(\'' . $user->id . '\')">删除</a>
<a class="btn btn-brand" href="/admin/user/' . $user->id . '/bought">查套餐</a>
<a class="btn btn-brand" id="changetouser" href="javascript:void(0);" onClick="changetouser_modal_show(\'' . $user->id . '\')">切换为该用户</a>';
$tempdata['id'] = $user->id;
$tempdata['user_name'] = $user->user_name;
@ -540,6 +539,7 @@ 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);
@ -575,4 +575,136 @@ 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);
}
public function bought($request, $response, $args)
{
$id = $args['id'];
$user = User::find($id);
$table_config['total_column'] = array(
'op' => '操作',
'id' => 'ID',
'name' => '商品名称',
'valid' => '是否有效期内',
'auto_renew' => '自动续费时间',
'reset_time' => '流量重置时间',
'buy_time' => '套餐购买时间',
'exp_time' => '套餐过期时间',
'content' => '商品详细内容',
);
$table_config['default_show_column'] = array('op', 'name', 'valid', 'reset_time');
$table_config['ajax_url'] = 'bought/ajax';
$shops = Shop::where('status', 1)->orderBy('name')->get();
return $this->view()->assign('table_config', $table_config)->assign('shops', $shops)->assign('user', $user)->display('admin/user/bought.tpl');
}
public function bought_ajax($request, $response, $args)
{
$start = $request->getParam("start");
$limit_length = $request->getParam('length');
$id = $args['id'];
$user = User::find($id);
$boughts = Bought::where('userid', $user->id)->skip($start)->limit($limit_length)->orderBy('id', 'desc')->get();
$total_conut = Bought::where('userid', $user->id)->count();
$data = [];
foreach ($boughts as $bought) {
$shop = $bought->shop();
if ($shop == null) {
$bought->delete();
continue;
}
$tempdata = [];
$tempdata['op'] = '<a class="btn btn-brand-accent" id="delete" href="javascript:void(0);" onClick="delete_modal_show(\'' . $bought->id . '\')">删除</a>';
$tempdata['id'] = $bought->id;
$tempdata['name'] = $shop->name;
$tempdata['content'] = $shop->content();
$tempdata['auto_renew'] = ($bought->renew == 0 ? '不自动续费' : $bought->renew_date());
$tempdata['buy_time'] = $bought->datetime();
if ($bought->use_loop()) {
$tempdata['valid'] = ($bought->valid() ? '有效' : '已过期');
} else {
$tempdata['valid'] = '-';
}
$tempdata['reset_time'] = $bought->reset_time();
$tempdata['exp_time'] = $bought->exp_time();
$data[] = $tempdata;
}
$info = [
'draw' => $request->getParam('draw'),
'recordsTotal' => $total_conut,
'recordsFiltered' => $total_conut,
'data' => $data
];
return json_encode($info, true);
}
public function bought_delete($request, $response, $args)
{
$id = $request->getParam('id');
$Bought = Bought::find($id);
if (!$Bought->delete()) {
$rs['ret'] = 0;
$rs['msg'] = '删除失败';
return $response->getBody()->write(json_encode($rs));
}
$rs['ret'] = 1;
$rs['msg'] = '删除成功';
return $response->getBody()->write(json_encode($rs));
}
public function bought_add($request, $response, $args)
{
$id = $args['id'];
$user = User::find($id);
$shop_id = (int) $request->getParam('buy_shop');
$buy_type = (int) $request->getParam('buy_type');
if ($shop_id == '') {
$rs['ret'] = 0;
$rs['msg'] = '请选择套餐';
return $response->getBody()->write(json_encode($rs));
}
$shop = Shop::find($shop_id);
if ($shop == null) {
$rs['ret'] = 0;
$rs['msg'] = '套餐不存在';
return $response->getBody()->write(json_encode($rs));
}
if ($buy_type != 0) {
if (bccomp($user->money, $shop->price, 2) == -1) {
$res['ret'] = 0;
$res['msg'] = '喵喵喵~ 该用户余额不足。';
return $response->getBody()->write(json_encode($res));
}
$user->money = bcsub($user->money, $shop->price, 2);
$user->save();
}
$boughts = Bought::where('userid', $user->id)->get();
foreach ($boughts as $disable_bought) {
$disable_bought->renew = 0;
$disable_bought->save();
}
$bought = new Bought();
$bought->userid = $user->id;
$bought->shopid = $shop->id;
$bought->datetime = time();
$bought->renew = 0;
$bought->coupon = '';
$bought->price = $shop->price;
$bought->save();
$shop->buy($user);
$rs['msg'] = ($buy_type != 0 ? '套餐购买成功' : '套餐添加成功');
$rs['ret'] = 1;
return $response->getBody()->write(json_encode($rs));
}
}

@ -21,7 +21,16 @@ class AdminController extends UserController
public function index($request, $response, $args)
{
$sts = new Analytics();
return $this->view()->assign('sts', $sts)->display('admin/index.tpl');
$days = [];
for ($i = 1; $i <= 7; $i++) {
$date_expression = '-'.$i.' days';
$day = strtotime($date_expression);
$days[] = date("Y-m-d", $day);
}
return $this->view()->assign('sts', $sts)->assign('days', $days)->display('admin/index.tpl');
}
public function node($request, $response, $args)
@ -60,6 +69,33 @@ class AdminController extends UserController
return $this->view()->assign('table_config', $table_config)->display('admin/invite.tpl');
}
public function chgInvite($request, $response, $args)
{
$prefix = $request->getParam('prefix');
if ($request->getParam('userid')!=NULL && $request->getParam('refid')!=NULL) {
if (strpos($request->getParam('userid'), "@")!=false) {
$user=User::where("email", "=", $request->getParam('userid'))->first();
} else {
$user=User::Where("id", "=", $request->getParam('userid'))->first();
}
if ($user==null) {
$res['ret'] = 0;
$res['msg'] = "邀请者更改失败,检查用户id是否输入正确";
return $response->getBody()->write(json_encode($res));
}
$uid = $user->id;
} else {
$uid=0;
}
$user->ref_by = $request->getParam('refid');
$user->save();
$res['ret'] = 1;
$res['msg'] = "邀请者更改成功";
return $response->getBody()->write(json_encode($res));
}
public function addInvite($request, $response, $args)
{
$num = $request->getParam('num');
@ -211,4 +247,79 @@ class AdminController extends UserController
$body = $response->getBody();
$body->write($datatables->generate());
}
public function getIncome($request, $response, $args)
{
$date = $request->getParam('date');
$date_in_timestamp = strtotime($date);
//$date_in_timestamp = strtotime('2019-12-12');
$stats = new Analytics();
$today_income = $stats->getIncome($date_in_timestamp, $date_in_timestamp+86400);
$yesterday_income = $stats->getIncome($date_in_timestamp-86400, $date_in_timestamp);
$first_day_of_this_week_timestamp = strtotime("last monday midnight",$date_in_timestamp);
$first_day_of_next_week_timestamp = strtotime("next monday midnight",$date_in_timestamp);
$this_week_income = $stats->getIncome($first_day_of_this_week_timestamp, $first_day_of_next_week_timestamp);
$first_day_of_last_week_timestamp = strtotime("last monday midnight",$date_in_timestamp-604800);
$last_week_income = $stats->getIncome($first_day_of_last_week_timestamp, $first_day_of_this_week_timestamp);
$first_day_of_this_month_timestamp = strtotime("first day of this month",$date_in_timestamp);
$first_day_of_next_month_timestamp = strtotime("first day of next month",$date_in_timestamp);
$this_month_income = $stats->getIncome($first_day_of_this_month_timestamp, $first_day_of_next_month_timestamp);
$first_day_of_last_month_timestamp = strtotime("first day of last month",$date_in_timestamp);
$last_moneth_income = $stats->getIncome($first_day_of_last_month_timestamp, $first_day_of_this_month_timestamp);
$res['success'] = true;
$res['error'] = '';
$res['message'] = '';
$res['data'] = array(
"date" => $date,
"todayIncome" => $today_income,
"yesterdayIncome" => $yesterday_income,
"thisWeekIncome" => $this_week_income,
"lastWeekIncome" => $last_week_income,
"thisMonthIncome" => $this_month_income,
"lastMonthIncome" => $last_moneth_income
);
return $response->getBody()->write(json_encode($res));
}
public function newUsers($request, $response, $args)
{
$date = $request->getParam('date');
$date_in_timestamp = strtotime($date);
$stats = new Analytics();
$today_users = $stats->getNewUsers($date_in_timestamp, $date_in_timestamp+86400);
$yesterday_users = $stats->getNewUsers($date_in_timestamp-86400, $date_in_timestamp);
$first_day_of_this_week_timestamp = strtotime("last monday midnight",$date_in_timestamp);
$first_day_of_next_week_timestamp = strtotime("next monday midnight",$date_in_timestamp);
$this_week_users = $stats->getNewUsers($first_day_of_this_week_timestamp, $first_day_of_next_week_timestamp);
$first_day_of_last_week_timestamp = strtotime("last monday midnight",$date_in_timestamp-604800);
$last_week_users = $stats->getNewUsers($first_day_of_last_week_timestamp, $first_day_of_this_week_timestamp);
$first_day_of_this_month_timestamp = strtotime("first day of this month",$date_in_timestamp);
$first_day_of_next_month_timestamp = strtotime("first day of next month",$date_in_timestamp);
$this_month_users = $stats->getNewUsers($first_day_of_this_month_timestamp, $first_day_of_next_month_timestamp);
$first_day_of_last_month_timestamp = strtotime("first day of last month",$date_in_timestamp);
$last_moneth_users = $stats->getNewUsers($first_day_of_last_month_timestamp, $first_day_of_this_month_timestamp);
$res['success'] = true;
$res['error'] = '';
$res['message'] = '';
$res['data'] = array(
"date" => $date,
"today" => $today_users,
"yesterday" => $yesterday_users,
"thisWeek" => $this_week_users,
"lastWeek" => $last_week_users,
"thisMonth" => $this_month_users,
"lastMonth" => $last_moneth_users
);
return $response->getBody()->write(json_encode($res));
}
}

@ -1,162 +0,0 @@
<?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);
}
}

@ -23,16 +23,19 @@ use App\Utils\Geetest;
use App\Utils\TelegramSessionManager;
use Ramsey\Uuid\Uuid;
use App\Services\Internationalization;
/**
* AuthController
*/
class AuthController extends BaseController
{
public function login()
public function login($request, $response, $args)
{
$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');
@ -44,7 +47,7 @@ class AuthController extends BaseController
}
}
if (Config::get('enable_telegram') === 'true') {
if (Config::get('enable_telegram') === true) {
$login_text = TelegramSessionManager::add_login_session();
$login = explode('|', $login_text);
$login_token = $login[0];
@ -66,6 +69,13 @@ class AuthController extends BaseController
$welcome = 'Good Evening';
}
$i18n = new Internationalization();
if (MalioConfig::get('only_one_lang') != 'none') {
$i18n->lang = MalioConfig::get('only_one_lang');
} else {
$i18n->detectLang($request, $response, $args);
}
return $this->view()
->assign('geetest_html', $GtSdk)
->assign('login_token', $login_token)
@ -74,6 +84,7 @@ class AuthController extends BaseController
->assign('telegram_bot', Config::get('telegram_bot'))
->assign('base_url', Config::get('baseUrl'))
->assign('recaptcha_sitekey', $recaptcha_sitekey)
->assign('i18n', $i18n)
->display('auth/login.tpl');
}
@ -109,7 +120,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');
@ -234,7 +245,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');
@ -246,7 +257,15 @@ class AuthController extends BaseController
}
}
$i18n = new Internationalization();
if (MalioConfig::get('only_one_lang') != 'none') {
$i18n->lang = MalioConfig::get('only_one_lang');
} else {
$i18n->detectLang($request, $response, $args);
}
return $this->view()
->assign('i18n', $i18n)
->assign('geetest_html', $GtSdk)
->assign('enable_email_verify', Config::get('enable_email_verify'))
->assign('code', $code)
@ -257,7 +276,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);
@ -437,7 +456,7 @@ class AuthController extends BaseController
$full_phone = $area_code.$phone;
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');
@ -517,7 +536,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;
@ -563,7 +582,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) {
EmailVerify::where('email', '=', $email)->delete();
}
@ -609,7 +628,7 @@ class AuthController extends BaseController
$user->ref_by = 0;
if (($c != null) && $c->user_id != 0) {
$gift_user = User::where('id', '=', $c->user_id)->first();
if ($gift_user->invite_num > 0) {
if ($gift_user->invite_num != 0) {
$user->ref_by = $c->user_id;
$user->money = Config::get('invite_get_money');
$gift_user->transfer_enable += Config::get('invite_gift') * 1024 * 1024 * 1024;
@ -673,7 +692,7 @@ class AuthController extends BaseController
return $response->getBody()->write(json_encode($res));
}
if (Config::get('enable_telegram') === 'true') {
if (Config::get('enable_telegram') === true) {
$ret = TelegramSessionManager::check_login_session($token, $number);
$res['ret'] = $ret;
return $response->getBody()->write(json_encode($res));
@ -685,7 +704,7 @@ class AuthController extends BaseController
public function telegram_oauth($request, $response, $args)
{
if (Config::get('enable_telegram') === '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'];

@ -5,7 +5,10 @@ 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;
use App\Services\Internationalization;
/**
* BaseController
@ -29,6 +32,7 @@ class BaseController
{
$this->view = View::getSmarty();
$this->user = Auth::getUser();
$this->i18n = new Internationalization();
}
/**
@ -40,13 +44,18 @@ class BaseController
{
return $this->view;
}
// TODO: remove
/**
* @param $response
* @param $res
* @return mixed
* Output JSON
*
* @param Response $response
* @param array|object $resource
*
* @return ResponseInterface
*/
public function echoJson($response, $res)
public function echoJson(Response $response, $resource)
{
return $response->getBody()->write(json_encode($res));
return $response->withJson($resource);
}
}

@ -1,68 +0,0 @@
<?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');
$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 . '?sub=1';
return $this->echoJson($response, $res);
}
}

@ -16,6 +16,7 @@ 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;
@ -31,6 +32,22 @@ use Symfony\Component\Yaml\Exception\ParseException;
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 托管配置
*
@ -41,13 +58,8 @@ class ConfController extends BaseController
*
* @return string
*/
public static function getSurgeConfs($User, $AllProxys, $Nodes, $SourceContent)
public static function getSurgeConfs($User, $AllProxys, $Nodes, $Configs, $local = false)
{
try {
$Configs = Yaml::parse($SourceContent);
} catch (ParseException $exception) {
return printf('无法解析 YAML 字符串: %s', $exception->getMessage());
}
$General = self::getSurgeConfGeneral($Configs['General']);
$Proxys = (isset($Configs['Proxy'])
? self::getSurgeConfProxy($Configs['Proxy'])
@ -62,7 +74,7 @@ class ConfController extends BaseController
);
$ProxyGroup = self::getSurgeProxyGroup2String($ProxyGroups);
$Rule = self::getSurgeConfRule($Configs['Rule']);
$Rule = self::getSurgeConfRule($Configs['Rule'], $local);
$Conf = '#!MANAGED-CONFIG '
. Config::get('baseUrl') . $_SERVER['REQUEST_URI'] .
"\n\n#---------------------------------------------------#" .
@ -168,7 +180,7 @@ class ConfController extends BaseController
$return = null;
switch (true) {
case (isset($Rule['content']['class'])):
if ($Proxy['class'] == $Rule['content']['class']) {
if (in_array($Proxy['class'], $Rule['content']['class'])) {
if (isset($Rule['content']['regex'])) {
if (preg_match('/' . $Rule['content']['regex'] . '/i', $Proxy['remark'])) {
$return = $Proxy;
@ -179,7 +191,7 @@ class ConfController extends BaseController
}
break;
case (isset($Rule['content']['noclass'])):
if ($Proxy['class'] != $Rule['content']['noclass']) {
if (!in_array($Proxy['class'], $Rule['content']['noclass'])) {
if (isset($Rule['content']['regex'])) {
if (preg_match('/' . $Rule['content']['regex'] . '/i', $Proxy['remark'])) {
$return = $Proxy;
@ -302,8 +314,15 @@ class ConfController extends BaseController
*
* @return string
*/
public static function getSurgeConfRule($Rules)
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']);
@ -337,13 +356,19 @@ class ConfController extends BaseController
*
* @return string
*/
public static function getClashConfs($User, $AllProxys, $SourceContent)
public static function getClashConfs($User, $AllProxys, $Configs, $local = false)
{
try {
$Configs = Yaml::parse($SourceContent);
} catch (ParseException $exception) {
return printf('无法解析 YAML 字符串: %s', $exception->getMessage());
$confStr = [
'Proxy' => 'proxies',
'ProxyGroup' => 'proxy-groups',
];
if (isset($_GET['newconf']) && (int) $_GET['newconf'] == 0) {
$confStr = [
'Proxy' => 'Proxy',
'ProxyGroup' => 'Proxy Group',
];
}
if (isset($Configs['Proxy']) || count($Configs['Proxy']) != 0) {
$tmpProxys = array_merge($AllProxys, $Configs['Proxy']);
} else {
@ -355,14 +380,14 @@ class ConfController extends BaseController
$Proxys[] = $Proxy;
}
$tmp = self::getClashConfGeneral($Configs['General']);
$tmp['Proxy'] = $Proxys;
$tmp[$confStr['Proxy']] = $Proxys;
if (isset($Configs['ProxyGroup'])) {
$tmp['Proxy Group'] = self::getClashConfProxyGroup(
$tmp[$confStr['ProxyGroup']] = self::getClashConfProxyGroup(
$AllProxys,
$Configs['ProxyGroup']
);
} else {
$tmp['Proxy Group'] = self::getClashConfProxyGroup(
$tmp[$confStr['ProxyGroup']] = self::getClashConfProxyGroup(
$AllProxys,
$Configs['Proxy Group']
);
@ -375,7 +400,7 @@ class ConfController extends BaseController
"\n\n"
. Yaml::dump($tmp, 4, 2) .
"\n\n"
. self::getClashConfRule($Configs['Rule']);
. self::getClashConfRule($Configs['Rule'], $local);
return $Conf;
}
@ -459,9 +484,21 @@ class ConfController extends BaseController
*
* @return string
*/
public static function getClashConfRule($Rules)
public static function getClashConfRule($Rules, $local)
{
$return = ('Rule:' . PHP_EOL);
$confStr = 'rules';
if (isset($_GET['newconf']) && (int) $_GET['newconf'] == 0) {
$confStr = 'Rule';
}
$return = ($confStr . ':' . PHP_EOL);
// 加载本地规则文件
if ($local) {
$render = ConfRender::getTemplateRender();
return $return . $render->fetch(trim($Rules['source']));
}
// 加载远程规则文件
if (isset($Rules['source']) && $Rules['source'] != '') {
$sourceURL = trim($Rules['source']);
// 远程规则仅支持 github 以及 gitlab
@ -479,10 +516,10 @@ class ConfController extends BaseController
} catch (ParseException $exception) {
$sourceRule['error'] = printf('无法解析 YAML 字符串: %s', $exception->getMessage());
}
if (isset($sourceRule['error']) || !isset($sourceRule['Rule'])) {
if (isset($sourceRule['error']) || !isset($sourceRule[$confStr])) {
$return .= $sourceContent;
} else {
$return .= Yaml::dump($sourceRule['Rule'], 4, 2);
$return .= Yaml::dump($sourceRule[$confStr], 4, 2);
}
}
} else {

@ -5,19 +5,28 @@ namespace App\Controllers;
use App\Models\InviteCode;
use App\Services\Auth;
use App\Services\Config;
use App\Services\MalioConfig;
use App\Utils\AliPay;
use App\Utils\TelegramSessionManager;
use App\Utils\TelegramProcess;
use App\Utils\Spay_tool;
use App\Utils\Geetest;
use App\Utils\Tools;
use App\Services\Internationalization;
use App\Utils\Telegram\Process;
use Slim\Http\{Request, Response};
use Psr\Http\Message\ResponseInterface;
/**
* HomeController
*/
class HomeController extends BaseController
{
public function index()
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function index($request, $response, $args): ResponseInterface
{
$GtSdk = null;
$recaptcha_sitekey = null;
@ -33,7 +42,7 @@ class HomeController extends BaseController
}
}
if (Config::get('enable_telegram') == 'true') {
if (Config::get('enable_telegram') == true) {
$login_text = TelegramSessionManager::add_login_session();
$login = explode('|', $login_text);
$login_token = $login[0];
@ -43,84 +52,170 @@ class HomeController extends BaseController
$login_number = '';
}
if (Config::get('newIndex') != 'true' && Config::get('theme') == 'material') {
return $this->view()->display('indexold.tpl');
if (Config::get('newIndex') === false && Config::get('theme') == 'material') {
return $response->write($this->view()->fetch('indexold.tpl'));
} else {
return $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)
->display('index.tpl');
if (!Auth::getUser()->isLogin) {
$i18n = new Internationalization();
if (MalioConfig::get('only_one_lang') != 'none') {
$i18n->lang = MalioConfig::get('only_one_lang');
} else {
$i18n->detectLang($request, $response, $args);
}
return $response->write($this->view()
->assign('i18n', $i18n)
->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)
->display('index.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('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)
->display('index.tpl')
);
}
}
}
public function indexold()
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function indexold($request, $response, $args): ResponseInterface
{
return $this->view()->display('indexold.tpl');
return $response->write($this->view()->fetch('indexold.tpl'));
}
public function code()
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function code($request, $response, $args): ResponseInterface
{
$codes = InviteCode::where('user_id', '=', '0')->take(10)->get();
return $this->view()->assign('codes', $codes)->display('code.tpl');
return $response->write($this->view()->assign('codes', $codes)->fetch('code.tpl'));
}
public function down()
{ }
public function tos()
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function tos($request, $response, $args): ResponseInterface
{
return $this->view()->display('tos.tpl');
return $response->write($this->view()->fetch('tos.tpl'));
}
public function staff()
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function staff($request, $response, $args): ResponseInterface
{
return $this->view()->display('staff.tpl');
return $response->write($this->view()->fetch('staff.tpl'));
}
public function telegram($request, $response, $args)
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function telegram($request, $response, $args): ResponseInterface
{
$token = $request->getQueryParams()['token'] ?? '';
$token = $request->getQueryParam('token');
if ($token == Config::get('telegram_request_token')) {
TelegramProcess::process();
$result = '1';
} else {
$result = '0';
}
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('telegram_request_token')) {
Process::index();
$result = '1';
} else {
echo ('不正确请求!');
$result = '0';
}
return $response->write($result);
}
public function page404($request, $response, $args)
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function page404($request, $response, $args): ResponseInterface
{
return $this->view()->display('404.tpl');
return $response->write($this->view()->fetch('404.tpl'));
}
public function page405($request, $response, $args)
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function page405($request, $response, $args): ResponseInterface
{
return $this->view()->display('405.tpl');
return $response->write($this->view()->fetch('405.tpl'));
}
public function page500($request, $response, $args)
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function page500($request, $response, $args): ResponseInterface
{
return $this->view()->display('500.tpl');
return $response->write($this->view()->fetch('500.tpl'));
}
public function getOrderList($request, $response, $args)
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function getOrderList($request, $response, $args): ResponseInterface
{
$key = $request->getParam('key');
if (!$key || $key != Config::get('key')) {
$res['ret'] = 0;
$res['msg'] = '错误';
return $response->getBody()->write(json_encode($res));
return $response->write(json_encode($res));
}
return $response->getBody()->write(json_encode(['data' => AliPay::getList()]));
return $response->write(json_encode(['data' => AliPay::getList()]));
}
public function setOrder($request, $response, $args)
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function setOrder($request, $response, $args): ResponseInterface
{
$key = $request->getParam('key');
$sn = $request->getParam('sn');
@ -128,38 +223,39 @@ class HomeController extends BaseController
if (!$key || $key != Config::get('key')) {
$res['ret'] = 0;
$res['msg'] = '错误';
return $response->getBody()->write(json_encode($res));
return $response->write(json_encode($res));
}
return $response->getBody()->write(json_encode(['res' => AliPay::setOrder($sn, $url)]));
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') != 'true') {
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';
$basePath = Config::get('remote_documents') === true ? Config::get('documents_source') : '/docs/GeekQu';
return $this->view()
->assign('appName', Config::get('documents_name'))
->assign('basePath', $basePath)
->display('doc/index.tpl');
->fetch('doc/index.tpl');
}
public function getSubLink($request, $response, $args)
{
$type = trim($request->getParam('type'));
$user = Auth::getUser();
if (!$user->isLogin) {
return $msg = '!> ₍₍ ◝(・ω・)◟ ⁾⁾ 您没有登录噢,[点击此处登录](/auth/login \':ignore target=_blank\') 之后再刷新就阔以了啦';
} else {
$subInfo = LinkController::getSubinfo($user, 0);
switch ($request->getParam('type')) {
switch ($type) {
case 'ssr':
$msg = [
'**订阅链接:**',
'```',
$subInfo['ssr'] . '&extend=1',
$subInfo['ssr'],
'```'
];
break;
@ -167,7 +263,7 @@ class HomeController extends BaseController
$msg = [
'**订阅链接:**',
'```',
$subInfo['v2ray'] . '&extend=1',
$subInfo['v2ray'],
'```'
];
break;
@ -203,7 +299,7 @@ class HomeController extends BaseController
$msg = [
'**包含 ss、v2ray 的合并订阅链接:**',
'```',
$subInfo['kitsunebi'] . '&extend=1',
$subInfo['kitsunebi'],
'```'
];
break;
@ -248,9 +344,17 @@ class HomeController extends BaseController
];
break;
default:
$msg = [
'获取失败了呢...,请联系管理员。'
];
if (in_array($type, $subInfo)) {
$msg = [
'```',
$subInfo[$type],
'```'
];
} else {
$msg = [
'获取失败了呢...,请联系管理员。'
];
}
break;
}
}

File diff suppressed because it is too large Load Diff

@ -62,53 +62,16 @@ class FuncController extends BaseController
$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;
}
}

@ -58,6 +58,16 @@ class NodeController extends BaseController
} else {
$node_server = $node->server;
}
// 0: new node; -1: offline; 1: online
$node_heartbeat = $node->node_heartbeat + 300;
$node_online = -1;
if ($node_heartbeat == 300) {
$node_online = 0;
} elseif ($node_heartbeat > time()) {
$node_online = 1;
}
$res = [
'ret' => 1,
'data' => [
@ -68,7 +78,8 @@ class NodeController extends BaseController
'mu_only' => $node->mu_only,
'sort' => $node->sort,
'server' => $node_server,
'type' => 'ss-panel-v3-mod_Uim'
'type' => 'ss-panel-v3-mod_Uim',
'online' => $node_online
],
];
return $this->echoJson($response, $res);

@ -53,7 +53,7 @@ class UserController extends BaseController
if (in_array($node->sort, [0, 10]) && $node->mu_only != -1) {
$mu_port_migration = Config::get('mu_port_migration');
} else {
$mu_port_migration = 'false';
$mu_port_migration = false;
}
/*
@ -62,7 +62,7 @@ class UserController extends BaseController
*/
$users_raw = User::where(
static function ($query) use ($node, $mu_port_migration) {
if ($mu_port_migration == 'true') {
if ($mu_port_migration === true) {
$query->where(
static function ($query1) use ($node) {
if ($node->node_group != 0) {
@ -90,10 +90,10 @@ class UserController extends BaseController
)->orwhere('is_admin', 1);
}
}
)->where('enable', 1)->where("detect_ban", 0)->where('expire_in', '>', date('Y-m-d H:i:s'))->get();
)->where('enable', 1)->where('expire_in', '>', date('Y-m-d H:i:s'))->get();
// 单端口承载用户
if ($mu_port_migration == 'true') {
if ($mu_port_migration === true) {
$mu_users_raw = User::where(
static function ($query) use ($node) {
$query->where(
@ -109,7 +109,7 @@ class UserController extends BaseController
}
)->orwhere('is_admin', 1);
}
)->where('enable', 1)->where("detect_ban", 0)->where('expire_in', '>', date('Y-m-d H:i:s'))->get();
)->where('enable', 1)->where('expire_in', '>', date('Y-m-d H:i:s'))->get();
$muPort = Tools::get_MuOutPortArray($node->server);
if ($muPort['type'] == 0) {
@ -131,42 +131,26 @@ class UserController extends BaseController
$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');
'is_multi_user', 'id', 'port', 'passwd', 'u', 'd', 'node_connector',
'sort', 'uuid', 'sha224uuid');
$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();
if (MalioConfig::get('enable_webapi_email_hash') == true) {
$user_raw->email = md5($user_raw->email);
}
$users[] = $user_raw;
} else {
// 流量耗尽用户限速至 1Mbps
$user_raw = Tools::keyFilter($user_raw, $key_list);
$user_raw->uuid = $user_raw->getUuid();
$user_raw->node_speedlimit = 1;
if (MalioConfig::get('enable_webapi_email_hash') == true) {
$user_raw->email = md5($user_raw->email);
}
$users[] = $user_raw;
}
foreach ($users_raw as $user_raw) {
if ($node->sort == 14) {
$user_raw->sha224uuid = hash('sha224', $user_raw->uuid);
}
} 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();
if (MalioConfig::get('enable_webapi_email_hash') == true) {
$user_raw->email = md5($user_raw->email);
}
$users[] = $user_raw;
}
if ($user_raw->transfer_enable > $user_raw->u + $user_raw->d) {
$user_raw = Tools::keyFilter($user_raw, $key_list);
$users[] = $user_raw;
} else if (Config::get('keep_connect') === true) {
$user_raw = Tools::keyFilter($user_raw, $key_list);
// 流量耗尽用户限速至 1Mbps
$user_raw->node_speedlimit = 1;
$users[] = $user_raw;
}
}
$res = [
'ret' => 1,
@ -308,49 +292,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();
}
}
@ -360,74 +313,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();
}
}
}
}
}
}

@ -1,57 +0,0 @@
<?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);
}
}

@ -1,122 +0,0 @@
<?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);
}
}

@ -126,15 +126,10 @@ class RelayController extends UserController
}
)->where('type', 1)->where(
static function ($query) {
$query->Where('sort', 10)
->orWhere('sort', 12);
$query->Where('sort', 10);
}
)->where('node_class', '<=', $user->class)->orderBy('name')->get();
foreach ($source_nodes as $node) {
if ($node->sort == 12) {
$node->name .= ' 正在使用V2ray后端 ';
}
}
$dist_nodes = Node::where(
static function ($query) use ($user) {
$query->Where('node_group', '=', $user->node_group)
@ -143,9 +138,7 @@ class RelayController extends UserController
)->where('type', 1)->where(
static function ($query) {
$query->Where('sort', 0)
->orWhere('sort', 10)
->orWhere('sort', 11)
->orWhere('sort', 12);
->orWhere('sort', 10);
}
)->where('node_class', '<=', $user->class)->orderBy('name')->get();
@ -164,16 +157,6 @@ class RelayController extends UserController
}
}
foreach ($dist_nodes as $node) {
if ($node->sort == 11 || $node->sort == 12) {
$node_explode = Tools::v2Array($node->server);
$ports[] = $node_explode['port'];
$node->name = $node->name . ' 如果是V2ray后端 请设置成 ' . $node_explode['port'];
} else {
$node->name = $node->name . ' 如果是V2ray后端 请设置成 ' . $user->port;
}
}
$ports[] = $user->port;
$ports = array_unique($ports);
return $this->view()->assign('source_nodes', $source_nodes)->assign('dist_nodes', $dist_nodes)->assign('ports', $ports)->display('user/relay/add.tpl');
@ -195,8 +178,7 @@ class RelayController extends UserController
}
)->where('type', 1)->where(
static function ($query) {
$query->Where('sort', 10)
->orWhere('sort', 12);
$query->Where('sort', 10);
}
)->where('node_class', '<=', $user->class)->first();
if ($source_node == null) {
@ -223,8 +205,7 @@ class RelayController extends UserController
static function ($query) {
$query->Where('sort', 0)
->orWhere('sort', 10)
->orWhere('sort', 11)
->orWhere('sort', 12);
->orWhere('sort', 11);
}
)->where('node_class', '<=', $user->class)->first();
@ -247,12 +228,7 @@ class RelayController extends UserController
->orWhere('node_group', '=', 0);
}
)->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);
$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))) {
if (($port_raw == null && $port != $user->port)) {
$rs['ret'] = 0;
$rs['msg'] = '端口错误';
return $response->getBody()->write(json_encode($rs));
@ -292,6 +268,8 @@ 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));
@ -316,15 +294,10 @@ class RelayController extends UserController
}
)->where('type', 1)->where(
static function ($query) {
$query->Where('sort', 10)
->orWhere('sort', 12);
$query->Where('sort', 10);
}
)->where('node_class', '<=', $user->class)->orderBy('name')->get();
foreach ($source_nodes as $node) {
if ($node->sort == 12) {
$node->name .= ' 正在使用V2ray后端 ';
}
}
$dist_nodes = Node::where(
static function ($query) use ($user) {
$query->Where('node_group', '=', $user->node_group)
@ -334,8 +307,7 @@ class RelayController extends UserController
static function ($query) {
$query->Where('sort', 0)
->orWhere('sort', 10)
->orWhere('sort', 11)
->orWhere('sort', 12);
->orWhere('sort', 11);
}
)->where('node_class', '<=', $user->class)->orderBy('name')->get();
@ -353,15 +325,7 @@ class RelayController extends UserController
$ports[] = $port_raw->server;
}
}
foreach ($dist_nodes as $node) {
if ($node->sort == 11 || $node->sort == 12) {
$node_explode = Tools::v2Array($node->server);
$ports[] = $node_explode['port'];
$node->name = $node->name . ' 如果是V2ray后端 请设置成: ' . $node_explode['port'];
} else {
$node->name = $node->name . ' 如果是V2ray后端 请设置成 ' . $user->port;
}
}
$ports[] = $user->port;
$ports = array_unique($ports);
@ -390,8 +354,7 @@ class RelayController extends UserController
}
)->where('type', 1)->where(
static function ($query) {
$query->Where('sort', 10)
->orWhere('sort', 12);
$query->Where('sort', 10);
}
)->where('node_class', '<=', $user->class)->first();
if ($source_node == null) {
@ -409,8 +372,7 @@ class RelayController extends UserController
static function ($query) {
$query->Where('sort', 0)
->orWhere('sort', 10)
->orWhere('sort', 11)
->orWhere('sort', 12);
->orWhere('sort', 11);
}
)->where('node_class', '<=', $user->class)->first();
@ -433,12 +395,7 @@ class RelayController extends UserController
->orWhere('node_group', '=', 0);
}
)->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);
$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))) {
if (($port_raw == null && $port != $user->port)) {
$rs['ret'] = 0;
$rs['msg'] = '端口错误';
return $response->getBody()->write(json_encode($rs));
@ -477,6 +434,8 @@ 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));
@ -498,6 +457,9 @@ 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));

@ -38,8 +38,10 @@ use App\Models\BlockIp;
use App\Models\UnblockIp;
use App\Models\Payback;
use App\Models\Relay;
use App\Models\Token;
use App\Models\UserSubscribeLog;
use App\Utils\QQWry;
use App\Utils\GeoIP2;
use App\Utils\GA;
use App\Utils\Geetest;
use App\Utils\Telegram;
@ -62,7 +64,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');
@ -82,11 +84,30 @@ class UserController extends BaseController
$class_left_days = floor((strtotime($this->user->class_expire)-time())/86400)+1;
if ($_ENV['subscribe_client_url'] != '') {
$getClient = new Token();
for ($i = 0; $i < 10; $i++) {
$token = $this->user->id . Tools::genRandomChar(16);
$Elink = Token::where('token', '=', $token)->first();
if ($Elink == null) {
$getClient->token = $token;
break;
}
}
$getClient->user_id = $this->user->id;
$getClient->create_time = time();
$getClient->expire_time = time() + 10 * 60;
$getClient->save();
} else {
$token = '';
}
return $this->view()
->assign('class_left_days', $class_left_days)
->assign('paybacks_sum', $paybacks_sum)
->assign('subInfo', LinkController::getSubinfo($this->user, 0))
->assign('ssr_sub_token', $ssr_sub_token)
->assign('getClient', $token)
->assign('display_ios_class', Config::get('display_ios_class'))
->assign('display_ios_topup', Config::get('display_ios_topup'))
->assign('ios_account', Config::get('ios_account'))
@ -132,7 +153,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);
}
@ -288,7 +309,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 {
@ -376,77 +397,20 @@ class UserController extends BaseController
public function ResetPort($request, $response, $args)
{
$price = Config::get('port_price');
$user = $this->user;
if ($user->money < $price) {
$res['ret'] = 0;
$res['msg'] = '余额不足';
return $response->getBody()->write(json_encode($res));
}
$origin_port = $user->port;
$user->port = Tools::getAvPort();
$relay_rules = Relay::where('user_id', $user->id)->where('port', $origin_port)->get();
foreach ($relay_rules as $rule) {
$rule->port = $user->port;
$rule->save();
}
$user->money -= $price;
$user->save();
$res['ret'] = 1;
$res['msg'] = $user->port;
$temp = $user->ResetPort();
$res['msg'] = $temp['msg'];
$res['ret'] = ($temp['ok'] === true ? 1 : 0);
return $response->getBody()->write(json_encode($res));
}
public function SpecifyPort($request, $response, $args)
{
$price = Config::get('port_price_specify');
$user = $this->user;
if ($user->money < $price) {
$res['ret'] = 0;
$res['msg'] = '余额不足';
return $response->getBody()->write(json_encode($res));
}
$port = $request->getParam('port');
if ($port < Config::get('min_port') || $port > Config::get('max_port') || Tools::isInt($port) == false) {
$res['ret'] = 0;
$res['msg'] = '端口不在要求范围内';
return $response->getBody()->write(json_encode($res));
}
$port_occupied = User::pluck('port')->toArray();
if (in_array($port, $port_occupied) == true) {
$res['ret'] = 0;
$res['msg'] = '端口已被占用';
return $response->getBody()->write(json_encode($res));
}
$origin_port = $user->port;
$user->port = $port;
$relay_rules = Relay::where('user_id', $user->id)->where('port', $origin_port)->get();
foreach ($relay_rules as $rule) {
$rule->port = $user->port;
$rule->save();
}
$user->money -= $price;
$user->save();
$res['ret'] = 1;
$res['msg'] = '钦定成功';
$temp = $user->SpecifyPort($port);
$res['msg'] = $temp['msg'];
$res['ret'] = ($temp['ok'] === true ? 1 : 0);
return $response->getBody()->write(json_encode($res));
}
@ -497,19 +461,19 @@ class UserController extends BaseController
}
$array_node = array();
$array_node['id']=$node->id;
$array_node['class']=$node->node_class;
$array_node['name']=$node->name;
$array_node['id'] = $node->id;
$array_node['class'] = $node->node_class;
$array_node['name'] = $node->name;
if ($node->sort == 13) {
$server = Tools::ssv2Array($node->server);
$array_node['server'] = $server['add'];
} else {
$array_node['server'] = $node->server;
$array_node['server'] = $node->getServer();
}
$array_node['sort']=$node->sort;
$array_node['info']=$node->info;
$array_node['mu_only']=$node->mu_only;
$array_node['group']=$node->node_group;
$array_node['sort'] = $node->sort;
$array_node['info'] = $node->info;
$array_node['mu_only'] = $node->mu_only;
$array_node['group'] = $node->node_group;
$array_node['raw_node'] = $node;
$regex = Config::get('flag_regex');
@ -528,7 +492,7 @@ class UserController extends BaseController
if ($log['node_id'] != $node->id) {
continue;
}
if (in_array($sort, array(0, 7, 8, 10, 11, 12, 13))) {
if (in_array($sort, array(0, 7, 8, 10, 11, 12, 13, 14))) {
$array_node['online_user'] = $log['online_user'];
} else {
$array_node['online_user'] = -1;
@ -540,7 +504,7 @@ class UserController extends BaseController
// 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, 14)) || $node_heartbeat == 300) {
$array_node['online'] = 0;
} elseif ($node_heartbeat > time()) {
$array_node['online'] = 1;
@ -554,8 +518,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) {
@ -577,7 +541,7 @@ class UserController extends BaseController
->assign('user', $user)
->registerClass('URL', URL::class)
->display('user/node.tpl');
}
}
public function node_old($request, $response, $args)
@ -593,7 +557,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();
@ -649,9 +613,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 != '暂无数据') {
@ -670,14 +634,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);
@ -685,8 +649,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');
}
@ -767,6 +731,11 @@ class UserController extends BaseController
return $this->view()->assign('node', $node)->assign('user', $user)->assign('mu', $mu)->assign('relay_rule_id', $relay_rule_id)->registerClass('URL', URL::class)->display('user/nodeinfo.tpl');
}
break;
case 14:
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 $this->view()->assign('node', $node)->assign('user', $user)->registerClass('URL', URL::class)->display('user/nodeinfo.tpl');
}
break;
default:
echo '微笑';
}
@ -774,12 +743,11 @@ class UserController extends BaseController
public function profile($request, $response, $args)
{
$user = Auth::getUser();
$pageNum = $request->getQueryParams()['page'] ?? 1;
$paybacks = Payback::where('ref_by', $this->user->id)->orderBy('datetime', 'desc')->paginate(15, ['*'], 'page', $pageNum);
$paybacks->setPath('/user/profile');
$iplocation = new QQWry();
$userip = array();
$total = Ip::where('datetime', '>=', time() - 300)->where('userid', '=', $this->user->id)->get();
@ -788,32 +756,61 @@ class UserController extends BaseController
$userloginip = array();
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 (MalioConfig::get('ip_database') == 'QQWry') {
$iplocation = new QQWry();
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']);
}
}
}
foreach ($total as $single) {
//if(isset($useripcount[$single->userid]))
{
$single->ip = Tools::getRealIp($single->ip);
$is_node = Node::where('node_ip', $single->ip)->first();
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']);
}
}
}
}
foreach ($total as $single) {
//if(isset($useripcount[$single->userid]))
{
$single->ip = Tools::getRealIp($single->ip);
$is_node = Node::where('node_ip', $single->ip)->first();
if ($is_node) {
continue;
if (MalioConfig::get('ip_database') == 'GeoIP2') {
$ip_location_geoip2 = new GeoIP2();
foreach ($totallogin as $single) {
{
if (!isset($userloginip[$single->ip])) {
$userloginip[$single->ip] = $ip_location_geoip2->getLocation($single->ip, $user->lang);
}
}
}
foreach ($total as $single) {
{
$single->ip = Tools::getRealIp($single->ip);
$is_node = Node::where('node_ip', $single->ip)->first();
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])) {
$userip[$single->ip] = $ip_location_geoip2->getLocation($single->ip, $user->lang);
}
}
}
}
@ -1100,7 +1097,11 @@ class UserController extends BaseController
$res['msg'] = '此优惠码无效';
return $response->getBody()->write(json_encode($res));
}
if ($coupon->expire < time()) {
$res['ret'] = 0;
$res['msg'] = '优惠码已过期';
return $response->getBody()->write(json_encode($res));
}
if ($coupon->order($shop->id) == false) {
$res['ret'] = 0;
$res['msg'] = '此优惠码不可用于此商品';
@ -1136,6 +1137,10 @@ class UserController extends BaseController
$disableothers = $request->getParam('disableothers');
$autorenew = $request->getParam('autorenew');
if (MalioConfig::get('shop_enable_trail_plan') == true && MalioConfig::get('shop_trail_plan_shopid') == $shop && $this->user->class >= 0) {
return 0;
};
$shop = Shop::where('id', $shop)->where('status', 1)->first();
if ($shop == null) {
@ -1258,7 +1263,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;
@ -1304,7 +1309,7 @@ class UserController extends BaseController
$new_ticket = Ticket::where('userid', $this->user->id)->where('title', $ticket->title)->orderBy('id','desc')->first();
$ticket_url = Config::get('baseUrl').'/admin/ticket/'.$new_ticket->id.'/view';
if (Config::get('mail_ticket') == 'true') {
if (Config::get('mail_ticket') == true && $markdown != '') {
$adminUser = User::where('is_admin', '=', '1')->get();
foreach ($adminUser as $user) {
$subject = '新工单被开启';
@ -1321,7 +1326,7 @@ class UserController extends BaseController
}
/* notify admins on telegram */
if (Config::get('enable_telegram') == 'true') {
if (Config::get('enable_telegram') == true) {
$messageText = 'Hi,管理员'.PHP_EOL.'有新工单需要您处理'.PHP_EOL.PHP_EOL.$this->user->user_name.': '.$title.PHP_EOL.$content;
$keyboard = new \TelegramBot\Api\Types\Inline\InlineKeyboardMarkup(
[
@ -1343,7 +1348,7 @@ class UserController extends BaseController
}
}
if (Config::get('useScFtqq') == 'true') {
if (Config::get('useScFtqq') == true && $markdown != '') {
$ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY');
$postdata = http_build_query(
array(
@ -1352,11 +1357,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);
}
@ -1392,96 +1397,93 @@ class UserController extends BaseController
return $newResponse;
}
if ($content != '这条工单已被关闭') {
if ($status == 1 && $ticket_main->status != $status) {
if (Config::get('mail_ticket') == 'true') {
$adminUser = User::where('is_admin', '=', '1')->get();
foreach ($adminUser as $user) {
$subject = Config::get('appName') . '-工单被重新开启';
$to = $user->email;
$text = '管理员,有人重新开启了<a href="' . Config::get('baseUrl') . '/admin/ticket/' . $ticket_main->id . '/view">工单</a>,请您及时处理。';
try {
Mail::send($to, $subject, 'news/warn.tpl', [
'user' => $user, 'text' => $text
], [
]);
} catch (Exception $e) {
}
if ($status == 1 && $ticket_main->status != $status) {
if (Config::get('mail_ticket') == true && $markdown != '') {
$adminUser = User::where('is_admin', '=', '1')->get();
foreach ($adminUser as $user) {
$subject = Config::get('appName') . '-工单被重新开启';
$to = $user->email;
$text = '管理员,有人重新开启了<a href="' . Config::get('baseUrl') . '/admin/ticket/' . $ticket_main->id . '/view">工单</a>,请您及时处理。';
try {
Mail::send($to, $subject, 'news/warn.tpl', [
'user' => $user, 'text' => $text
], []);
} catch (Exception $e) {
echo $e->getMessage();
}
}
if (Config::get('useScFtqq') == 'true') {
$ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY');
$postdata = http_build_query(
array(
'text' => Config::get('appName') . '-工单被重新开启',
'desp' => $markdown
)
);
$opts = array('http' =>
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') {
$adminUser = User::where('is_admin', '=', '1')->get();
$ticket_url = Config::get('baseUrl') . '/admin/ticket/' . $ticket_main->id . '/view';
foreach ($adminUser as $user) {
$subject = '工单被回复';
$to = $user->email;
$text = '有人回复了工单,请您及时处理';
try {
Mail::send($to, $subject, 'ticket/ticket_replay_admin.tpl', [
'user' => $this->user, 'text' => $text, 'ticket_url' => $ticket_url, 'content' => $content, 'title' => $ticket_main->title
], [
]);
} catch (Exception $e) {
}
}
if (Config::get('useScFtqq') == true && $markdown != '') {
$ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY');
$postdata = http_build_query(
array(
'text' => Config::get('appName') . '-工单被重新开启',
'desp' => $markdown
)
);
$opts = array('http' =>
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 != '') {
$adminUser = User::where('is_admin', '=', '1')->get();
foreach ($adminUser as $user) {
$subject = Config::get('appName') . '-工单被回复';
$to = $user->email;
$text = '管理员,有人回复了<a href="' . Config::get('baseUrl') . '/admin/ticket/' . $ticket_main->id . '/view">工单</a>,请您及时处理。';
try {
Mail::send($to, $subject, 'news/warn.tpl', [
'user' => $user, 'text' => $text
], []);
} catch (Exception $e) {
echo $e->getMessage();
}
}
if (Config::get('enable_telegram') == 'true') {
$messageText = 'Hi,管理员'.PHP_EOL.'有人回复了工单,请您及时处理'.PHP_EOL.PHP_EOL.$this->user->user_name.': '.$ticket_main->title.PHP_EOL.$content;
$ticket_url = Config::get('baseUrl') . '/admin/ticket/' . $ticket_main->id . '/view';
$keyboard = new \TelegramBot\Api\Types\Inline\InlineKeyboardMarkup(
}
if (Config::get('enable_telegram') == 'true') {
$messageText = 'Hi,管理员'.PHP_EOL.'有人回复了工单,请您及时处理'.PHP_EOL.PHP_EOL.$this->user->user_name.': '.$ticket_main->title.PHP_EOL.$content;
$ticket_url = Config::get('baseUrl') . '/admin/ticket/' . $ticket_main->id . '/view';
$keyboard = new \TelegramBot\Api\Types\Inline\InlineKeyboardMarkup(
[
[
[
['text' => '回复工单', 'url' => $ticket_url]
]
['text' => '回复工单', 'url' => $ticket_url]
]
);
$bot = new BotApi(Config::get('telegram_token'));
$adminUser = User::where('is_admin', '=', '1')->get();
foreach ($adminUser as $user) {
if ($user->telegram_id != null) {
try {
$bot->sendMessage($user->telegram_id, $messageText, null, null, null, $keyboard);
} catch (Exception $e) {
}
]
);
$bot = new BotApi(Config::get('telegram_token'));
$adminUser = User::where('is_admin', '=', '1')->get();
foreach ($adminUser as $user) {
if ($user->telegram_id != null) {
try {
$bot->sendMessage($user->telegram_id, $messageText, null, null, null, $keyboard);
} catch (Exception $e) {
}
}
}
if (Config::get('useScFtqq') == 'true') {
$ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY');
$postdata = http_build_query(
array(
'text' => Config::get('appName') . '-工单被回复',
'desp' => $markdown
)
);
$opts = array('http' =>
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);
}
}
if (Config::get('useScFtqq') == true && $markdown != '') {
$ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY');
$postdata = http_build_query(
array(
'text' => Config::get('appName') . '-工单被回复',
'desp' => $markdown
)
);
$opts = array('http' =>
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);
}
}
@ -1539,12 +1541,6 @@ 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'] = '非法输入';
@ -1615,6 +1611,8 @@ class UserController extends BaseController
$user->save();
$user->cleanSubCache();
if (!URL::SSCanConnect($user)) {
$res['ret'] = 1;
$res['msg'] = '设置成功,但您目前的协议,混淆,加密方式设置会导致 Shadowsocks原版客户端无法连接,请您自行更换到 ShadowsocksR 客户端。';
@ -1721,6 +1719,7 @@ class UserController extends BaseController
Radius::Add($user, $pwd);
$user->cleanSubCache();
return $this->echoJson($response, $res);
}
@ -1760,7 +1759,7 @@ class UserController extends BaseController
$user->updateMethod($method);
if (!URL::SSCanConnect($user)) {
$res['ret'] = 0;
$res['ret'] = 1;
$res['msg'] = '设置成功,但您目前的协议,混淆,加密方式设置会导致 Shadowsocks原版客户端无法连接,请您自行更换到 ShadowsocksR 客户端。';
return $this->echoJson($response, $res);
}
@ -1784,7 +1783,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');
@ -1812,23 +1811,21 @@ class UserController extends BaseController
return $response->getBody()->write(json_encode($res));
}
if (!$this->user->isAbleToCheckin()) {
$checkin = $this->user->checkin();
if ($checkin['ok'] === false) {
$res['ret'] = 0;
$res['msg'] = '您似乎已经签到过了...';
return $response->getBody()->write(json_encode($res));
$res['msg'] = $checkin['msg'];
return $this->echoJson($response, $res);
}
if (MalioConfig::get('daily_bonus_mode') == 'malio') {
$traffic = random_int(MalioConfig::get('daily_bonus_settings')[$this->user->class]['min'], MalioConfig::get('daily_bonus_settings')[$this->user->class]['max']);
} else {
$traffic = random_int(Config::get('checkinMin'), Config::get('checkinMax'));
}
$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(
'todayUsedTraffic' => $this->user->TodayusedTraffic(),
'lastUsedTraffic' => $this->user->LastusedTraffic(),
'unUsedTraffic' => $this->user->unusedTraffic(),
);
$res['msg'] = $this->i18n->get('got-daily-bonus',[$traffic]);
$res['ret'] = 1;
return $this->echoJson($response, $res);
}
@ -1853,8 +1850,9 @@ 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'] = '您的帐号已经从我们的系统中删除。欢迎下次光临!';
@ -1893,19 +1891,10 @@ 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;
$user->telegram_id = 0;
$user->save();
$user->TelegramReset();
return $response->withStatus(302)->withHeader('Location', '/user/edit');
}
@ -1913,6 +1902,7 @@ class UserController extends BaseController
{
$user = $this->user;
$user->clean_link();
$user->cleanSubCache();
return $response->withStatus(302)->withHeader('Location', '/user');
}
@ -1988,8 +1978,11 @@ class UserController extends BaseController
$user->obfs = $scheme['obfs'];
$user->save();
$user->cleanSubCache();
$res['ret'] = 1;
$res['msg'] = '切换' . $scheme['name'] . '成功';
return $this->echoJson($response, $res);
}
@ -2000,23 +1993,24 @@ class UserController extends BaseController
$return = '';
switch ($type) {
case 'ss':
$return .= URL::getAllUrl($user, 0, 1).PHP_EOL;
break;
$return .= URL::getAllUrl($user, 0, 1) . PHP_EOL;
break;
case 'ssr':
$return .= URL::getAllUrl($user, 0, 0).PHP_EOL;
break;
$return .= URL::getAllUrl($user, 0, 0) . PHP_EOL;
break;
case 'ssd':
$return .= URL::getAllSSDUrl($user).PHP_EOL;
break;
$return .= LinkController::getSSD($user, 1, [], ['type' => 'ss', 'is_mu' => 1], false) . PHP_EOL;
break;
case 'v2ray':
$return .= URL::getAllVMessUrl($user).PHP_EOL;
break;
$return .= URL::getAllVMessUrl($user) . PHP_EOL;
break;
default:
$return .= '悟空别闹!';
break;
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->getBody()->write($return);
$newResponse->write($return);
return $newResponse;
}
@ -2056,6 +2050,24 @@ class UserController extends BaseController
return $this->echoJson($response, $res);
}
public function getPlanTime($request, $response, $args)
{
$plan_num = $request->getQueryParams()['num'];
if (empty($plan_num)) {
$res['ret'] = 0;
return $this->echoJson($response, $res);
}
$plan_time = [];
foreach ((MalioConfig::get('plan_shop_id'))[$plan_num] as $key => $value) {
if ($value != 0) {
$plan_time[] = $key;
}
}
$res['plan_time'] = $plan_time;
$res['ret'] = 1;
return $this->echoJson($response, $res);
}
public function buyTrafficPackage($request, $response, $args)
{
$shopId = $request->getParam('shopid');
@ -2102,5 +2114,124 @@ class UserController extends BaseController
public function share_account($request, $response, $args)
{
return $this->view()->display('user/share_account.tpl');
}
public function qrcode($request, $response, $args)
{
return $this->view()->display('user/qrcode.tpl');
}
public function changeLang($request, $response, $args)
{
$lang = $request->getParam('lang');
$supported_lang = ['zh-cn','en'];
if (!in_array($lang, $supported_lang)) {
$res['ret'] = 0;
$res['msg'] = 'unsupport lang';
}
$this->user->lang = $lang;
$this->user->save();
$res['msg'] = 'yes';
$res['ret'] = 1;
return $this->echoJson($response, $res);
}
/**
* 获取包含订阅信息的客户端压缩档
*
* @param Request $request
* @param Response $response
* @param array $args
*/
public function getPcClient($request, $response, $args)
{
$zipArc = new \ZipArchive();
$user_token = LinkController::GenerateSSRSubCode($this->user->id, 0);
$type = trim($request->getQueryParams()['type']);
// 临时文件存放路径
$temp_file_path = '../storage/';
// 客户端文件存放路径
$client_path = '../resources/clients/';
switch ($type) {
case 'ss-win':
$temp_file_path .= $type . '_' . $user_token . '.zip';
$user_config_file_name = 'gui-config.json';
$content = LinkController::getSSPcConf($this->user);
$client_path .= $type . '/';
break;
case 'ssd-win':
$temp_file_path .= $type . '_' . $user_token . '.zip';
$user_config_file_name = 'gui-config.json';
$content = LinkController::getSSDPcConf($this->user);
$client_path .= $type . '/';
break;
case 'ssr-win':
$temp_file_path .= $type . '_' . $user_token . '.zip';
$user_config_file_name = 'gui-config.json';
$content = LinkController::getSSRPcConf($this->user);
$client_path .= $type . '/';
break;
case 'v2rayn-win':
$temp_file_path .= $type . '_' . $user_token . '.zip';
$user_config_file_name = 'guiNConfig.json';
$content = LinkController::getV2RayPcNConf($this->user);
$client_path .= $type . '/';
break;
default:
return 'gg';
}
// 文件存在则先删除
if (is_file($temp_file_path)) {
unlink($temp_file_path);
}
// 超链接文件内容
$site_url_content = '[InternetShortcut]' . PHP_EOL . 'URL=' . Config::get('baseUrl');
// 创建 zip 并添加内容
$zipArc->open($temp_file_path, \ZipArchive::CREATE);
$zipArc->addFromString($user_config_file_name, $content);
$zipArc->addFromString('点击访问_' . Config::get('appName') . '.url', $site_url_content);
Tools::folderToZip($client_path, $zipArc, strlen($client_path));
$zipArc->close();
$newResponse = $response->withHeader('Content-type', ' application/octet-stream')->withHeader('Content-Disposition', ' attachment; filename=' . $type . '.zip');
$newResponse->write(file_get_contents($temp_file_path));
unlink($temp_file_path);
return $newResponse;
}
public function getClientfromToken($request, $response, $args)
{
$token = $args['token'];
$Etoken = Token::where('token', '=', $token)->where('create_time', '>', time() - 60 * 10)->first();
if ($Etoken == null) {
return '下载链接已失效,请刷新页面后重新点击.';
}
$user = User::find($Etoken->user_id);
if ($user == null) {
return null;
}
$this->user = $user;
return self::getPcClient($request, $response, $args);
}
/**
* 清理订阅缓存
*
* @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('enable_telegram') == 'true') {
if (Config::get('enable_telegram') == true) {
$login_text = TelegramSessionManager::add_login_session();
$login = explode('|', $login_text);
$login_token = $login[0];
@ -68,6 +68,7 @@ class VueController extends BaseController
'isLogin' => $user->isLogin,
'enable_telegram' => Config::get('enable_telegram'),
'enable_mylivechat' => Config::get('enable_mylivechat'),
'enable_flag' => Config::get('enable_flag'),
'payment_type' => Config::get('payment_system'),
);
@ -437,4 +438,126 @@ 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,27 +2,26 @@
namespace App\Middleware;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use App\Services\Auth as AuthService;
class Admin
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
/**
* @param \Slim\Http\Request $request
* @param \Slim\Http\Response $response
* @param callable $next
*
* @return \Slim\Http\Response
*/
public function __invoke($request, $response, $next)
{
//$response->getBody()->write('BEFORE');
$user = AuthService::getUser();
if (!$user->isLogin) {
$newResponse = $response->withStatus(302)->withHeader('Location', '/auth/login');
return $newResponse;
return $response->withStatus(302)->withHeader('Location', '/auth/login');
}
if (!$user->isAdmin()) {
$newResponse = $response->withStatus(302)->withHeader('Location', '/user');
return $newResponse;
return $response->withStatus(302)->withHeader('Location', '/user');
}
$response = $next($request, $response);
return $response;
return $next($request, $response);
}
}

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

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

@ -1,55 +1,50 @@
<?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;
use App\Services\MalioConfig;
class Mod_Mu
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
/**
* @param \Slim\Http\Request $request
* @param \Slim\Http\Response $response
* @param callable $next
*
* @return \Slim\Http\Response
*/
public function __invoke($request, $response, $next)
{
$key = Helper::getParam($request, 'key');
$key = $request->getQueryParam('key');
if ($key === null) {
$res['ret'] = 0;
$res['data'] = 'null';
$response->getBody()->write(json_encode($res));
return $response;
return $response->withjson([
'ret' => 0,
'data' => 'Your key is null.'
]);
}
$auth = false;
$keys = Config::getMuKey();
foreach ($keys as $k) {
if ($key == $k) {
$auth = true;
break;
}
}
$auth = in_array($key, $keys);
if (MalioConfig::get('enable_webapi_ip_verification') == true) {
$node = Node::where('node_ip', 'LIKE', $_SERVER['REMOTE_ADDR'] . '%')->first();
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 is invalid';
$response->getBody()->write(json_encode($res));
return $response;
}
if (Config::get('checkNodeIp') === true){
$node = Node::where('node_ip', 'LIKE', $_SERVER['REMOTE_ADDR'] . '%')->first();
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 || ($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']
]);
}
}
$response = $next($request, $response);
return $response;
return $next($request, $response);
}
}

@ -1,51 +0,0 @@
<?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;
}
}

@ -32,4 +32,65 @@ class Bought extends Model
{
return Shop::where('id', $this->attributes['shopid'])->first();
}
/*
* 套餐已使用的天数
*
*/
public function used_days()
{
return (int) ((strtotime(date('Y-m-d')) - $this->datetime) / 86400);
}
/*
* 是否有效期内
*
*/
public function valid()
{
$shop = $this->shop();
if ($this->use_loop()) {
return (time() - $shop->reset_exp() * 86400 < $this->datetime);
}
return false;
}
/*
* 是否周期性商品
*
*/
public function use_loop()
{
$shop = $this->shop();
return ($shop->reset() != 0 && $shop->reset_value() != 0 && $shop->reset_exp() != 0);
}
/*
* 下一次流量重置时间
*
*/
public function reset_time($unix = false)
{
$shop = $this->shop();
if ($this->use_loop()) {
$day = $shop->reset() - ($this->used_days() % $shop->reset());
$time = time() + ($day * 86400);
return ($unix == false ? date('Y-m-d', $time) : $time);
}
return ($unix == false ? '-' : 0);
}
/*
* 过期时间
*
*/
public function exp_time($unix = false)
{
$shop = $this->shop();
if ($this->use_loop()) {
$time = $this->datetime + ($shop->reset_exp() * 86400);
return ($unix == false ? date('Y-m-d H:i:s', $time) : $time);
}
return ($unix == false ? '-' : 0);
}
}

@ -0,0 +1,55 @@
<?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();
}
}

@ -6,8 +6,9 @@ namespace App\Models;
* Node Model
*/
use App\Utils\Tools;
use App\Utils\{Tools, URL};
use App\Utils\DNSoverHTTPS;
class Node extends Model
{
protected $connection = 'default';
@ -172,4 +173,21 @@ class Node extends Model
$node_ip_array = explode(',', $node_ip_str);
return $node_ip_array[0];
}
public function getServer()
{
$out = '';
$explode = explode(';', $this->attributes['server']);
if (in_array($this->attributes['sort'], [0, 10])) {
if (isset($explode[1]) && stripos($explode[1], 'server=') !== false) {
$out = URL::parse_args($explode[1])['server'];
}
}
return ($out != '' ? $out : $explode[0]);
}
public function getOffsetPort($port)
{
return Tools::OutPort($this->attributes['server'], $this->attributes['name'], $port)['port'];
}
}

@ -136,7 +136,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;
@ -166,7 +166,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 {

@ -0,0 +1,36 @@
<?php
namespace App\Models;
/**
* TelegramTasks Model
*
* 请勿重复使用 type
*
* type:
* = 1 删除消息
* = 2 储存 /setuser 操作产生的 messageid
*
*/
class TelegramTasks extends Model
{
protected $connection = 'default';
protected $table = 'telegram_tasks';
protected $casts = [
'type' => 'int',
'status' => 'int',
'chatid' => 'int',
'messageid' => 'int',
'userid' => 'int',
'tguserid' => 'int',
'executetime' => 'int',
'datetime' => 'int',
];
public function datetime()
{
return date('Y-m-d H:i:s', $this->attributes['datetime']);
}
}

@ -12,7 +12,7 @@ use App\Services\Config;
use App\Utils\GA;
use App\Utils\QQWry;
use App\Utils\Radius;
use Ramsey\Uuid\Uuid;
use App\Utils\URL;
use App\Models\DetectLog;
use App\Models\DetectBanLog;
@ -63,7 +63,11 @@ class User extends Model
public function getMuMd5()
{
$str = str_replace(array('%id', '%suffix'), array($this->attributes['id'], Config::get('mu_suffix')), Config::get('mu_regex'));
$str = str_replace(
array('%id', '%suffix'),
array($this->attributes['id'], Config::get('mu_suffix')),
Config::get('mu_regex')
);
preg_match_all("|%-?[1-9]\d*m|U", $str, $matches, PREG_PATTERN_ORDER);
foreach ($matches[0] as $key) {
$key_match = str_replace(array('%', 'm'), '', $key);
@ -135,40 +139,59 @@ class User extends Model
public function getUuid()
{
return Uuid::uuid3(Uuid::NAMESPACE_DNS, $this->attributes['id'] . '|' . $this->attributes['passwd'])->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;
// return Uuid::uuid3(
// Uuid::NAMESPACE_DNS,
// $this->attributes['id'] . '|' . $this->attributes['passwd']
// )->toString();
return $this->attributes['uuid'];
}
/*
* 总流量
*/
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'];
@ -176,18 +199,75 @@ 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'];
@ -206,7 +286,10 @@ class User extends Model
public function getGAurl()
{
$ga = new GA();
$url = $ga->getUrl(urlencode(Config::get('appName') . '-' . $this->attributes['user_name'] . '-两步验证码'), $this->attributes['ga_token']);
$url = $ga->getUrl(
urlencode(Config::get('appName') . '-' . $this->attributes['user_name'] . '-两步验证码'),
$this->attributes['ga_token']
);
return $url;
}
@ -327,22 +410,40 @@ class User extends Model
$location = $iplocation->getlocation($reg_location);
$reg_location .= "\n" . iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']);
$return_array = array('DT_RowId' => 'row_1_' . $id, $id, $id,
$this->attributes['user_name'], $this->attributes['remark'],
$this->attributes['email'], $this->attributes['money'],
$im_type, $im_value,
$this->attributes['node_group'], $account_expire_in,
$this->attributes['class'], $class_expire_in,
$this->attributes['passwd'], $this->attributes['port'],
$return_array = array(
'DT_RowId' => 'row_1_' . $id,
$id,
$id,
$this->attributes['user_name'],
$this->attributes['remark'],
$this->attributes['email'],
$this->attributes['money'],
$im_type,
$im_value,
$this->attributes['node_group'],
$account_expire_in,
$this->attributes['class'],
$class_expire_in,
$this->attributes['passwd'],
$this->attributes['port'],
$this->attributes['method'],
$this->attributes['protocol'], $this->attributes['obfs'],
$this->online_ip_count(), $this->lastSsTime(),
$used_traffic, $enable_traffic,
$this->lastCheckInTime(), $today_traffic,
$is_enable, $this->attributes['reg_date'],
$this->attributes['protocol'],
$this->attributes['obfs'],
$this->attributes['obfs_param'],
$this->online_ip_count(),
$this->lastSsTime(),
$used_traffic,
$enable_traffic,
$this->lastCheckInTime(),
$today_traffic,
$is_enable,
$this->attributes['reg_date'],
$reg_location,
$this->attributes['auto_reset_day'], $this->attributes['auto_reset_bandwidth'],
$ref_user_id, $ref_user_name);
$this->attributes['auto_reset_day'],
$this->attributes['auto_reset_bandwidth'],
$ref_user_id,
$ref_user_name
);
return $return_array;
}
@ -373,8 +474,8 @@ class User extends Model
// 当前解封时间
public function relieve_time()
{
if ($this->attributes['detect_ban'] == 1) {
$logs = DetectBanLog::where('user_id', $this->attributes['id'])->orderBy("id", "desc")->first();
$logs = DetectBanLog::where('user_id', $this->attributes['id'])->orderBy('id', 'desc')->first();
if ($this->attributes['enable'] == 0 && $logs != null) {
$time = ($logs->end_time + $logs->ban_time * 60);
return date('Y-m-d H:i:s', $time);
} else {
@ -395,4 +496,336 @@ class User extends Model
$logs = DetectBanLog::where('user_id', $this->attributes['id'])->orderBy("id", "desc")->first();
return $logs->detect_number;
}
public function calIncome($req)
{
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;
}
public function paidUserCount()
{
return self::where('class', '!=', '0')->count();
}
public function disableReason()
{
$reason_id = DetectLog::where('user_id', '=', $this->attributes['id'])->orderBy('id', 'DESC')->first();
$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;
}
/**
* 更新加密方式
*/
public function setMethod($method)
{
$return = [
'ok' => true,
'msg' => '设置成功,您可自由选用两种客户端来进行连接。'
];
if ($method == '') {
$return['ok'] = false;
$return['msg'] = '非法输入';
return $return;
}
if (!Tools::is_param_validate('method', $method)) {
$return['ok'] = false;
$return['msg'] = '加密无效';
return $return;
}
$this->method = $method;
if (!Tools::checkNoneProtocol($this)) {
$return['ok'] = false;
$return['msg'] = '系统检测到您将要设置的加密方式为 none ,但您的协议并不在以下协议【' . implode(',', Config::getSupportParam('allow_none_protocol')) . '】之内,请您先修改您的协议,再来修改此处设置。';
return $return;
}
if (!URL::SSCanConnect($this) && !URL::SSRCanConnect($this)) {
$return['ok'] = false;
$return['msg'] = '您这样设置之后,就没有客户端能连接上了,所以系统拒绝了您的设置,请您检查您的设置之后再进行操作。';
return $return;
}
$this->updateMethod($method);
if (!URL::SSCanConnect($this)) {
$return['ok'] = true;
$return['msg'] = '设置成功,但您目前的协议,混淆,加密方式设置会导致 Shadowsocks 原版客户端无法连接,请您自行更换到 ShadowsocksR 客户端。';
}
if (!URL::SSRCanConnect($this)) {
$return['ok'] = true;
$return['msg'] = '设置成功,但您目前的协议,混淆,加密方式设置会导致 ShadowsocksR 客户端无法连接,请您自行更换到 Shadowsocks 客户端。';
}
return $return;
}
/**
* 更新协议
*/
public function setProtocol($Protocol)
{
$return = [
'ok' => true,
'msg' => '设置成功,您可自由选用客户端来连接。'
];
if ($Protocol == '') {
$return['ok'] = false;
$return['msg'] = '非法输入';
return $return;
}
if (!Tools::is_param_validate('protocol', $Protocol)) {
$return['ok'] = false;
$return['msg'] = '协议无效';
return $return;
}
$this->protocol = $Protocol;
if (!Tools::checkNoneProtocol($this)) {
$return['ok'] = false;
$return['msg'] = '系统检测到您目前的加密方式为 none ,但您将要设置为的协议并不在以下协议【' . implode(',', Config::getSupportParam('allow_none_protocol')) . '】之内,请您先修改您的加密方式,再来修改此处设置。';
return $return;
}
if (!URL::SSCanConnect($this) && !URL::SSRCanConnect($this)) {
$return['ok'] = false;
$return['msg'] = '您这样设置之后,就没有客户端能连接上了,所以系统拒绝了您的设置,请您检查您的设置之后再进行操作。';
return $return;
}
$this->save();
$this->cleanSubCache();
if (!URL::SSCanConnect($this)) {
$return['ok'] = true;
$return['msg'] = '设置成功,但您目前的协议,混淆,加密方式设置会导致 Shadowsocks 原版客户端无法连接,请您自行更换到 ShadowsocksR 客户端。';
}
if (!URL::SSRCanConnect($this)) {
$return['ok'] = true;
$return['msg'] = '设置成功,但您目前的协议,混淆,加密方式设置会导致 ShadowsocksR 客户端无法连接,请您自行更换到 Shadowsocks 客户端。';
}
return $return;
}
/**
* 更新混淆
*/
public function setObfs($Obfs)
{
$return = [
'ok' => true,
'msg' => '设置成功,您可自由选用客户端来连接。'
];
if ($Obfs == '') {
$return['ok'] = false;
$return['msg'] = '非法输入';
return $return;
}
if (!Tools::is_param_validate('obfs', $Obfs)) {
$return['ok'] = false;
$return['msg'] = '混淆无效';
return $return;
}
$this->obfs = $Obfs;
if (!URL::SSCanConnect($this) && !URL::SSRCanConnect($this)) {
$return['ok'] = false;
$return['msg'] = '您这样设置之后,就没有客户端能连接上了,所以系统拒绝了您的设置,请您检查您的设置之后再进行操作。';
return $return;
}
$this->save();
$this->cleanSubCache();
if (!URL::SSCanConnect($this)) {
$return['ok'] = true;
$return['msg'] = '设置成功,但您目前的协议,混淆,加密方式设置会导致 Shadowsocks 原版客户端无法连接,请您自行更换到 ShadowsocksR 客户端。';
}
if (!URL::SSRCanConnect($this)) {
$return['ok'] = true;
$return['msg'] = '设置成功,但您目前的协议,混淆,加密方式设置会导致 ShadowsocksR 客户端无法连接,请您自行更换到 Shadowsocks 客户端。';
}
return $return;
}
/**
* 解绑 Telegram
*/
public function TelegramReset()
{
$return = [
'ok' => true,
'msg' => '解绑成功.'
];
$telegram_id = $this->telegram_id;
$this->telegram_id = 0;
if ($this->save()) {
if (
Config::get('enable_telegram') === true
&&
Config::get('group_bound_user') === true
&&
Config::get('unbind_kick_member') === true
) {
\App\Utils\Telegram\TelegramTools::SendPost(
'kickChatMember',
[
'chat_id' => Config::get('telegram_chatid'),
'user_id' => $telegram_id,
]
);
}
} else {
$return = [
'ok' => false,
'msg' => '解绑失败.'
];
}
return $return;
}
/**
* 更新端口
*/
public function setPort($Port)
{
$PortOccupied = User::pluck('port')->toArray();
if (in_array($Port, $PortOccupied) == true) {
return [
'ok' => false,
'msg' => '端口已被占用'
];
}
$origin_port = $this->port;
$this->port = $Port;
$relay_rules = Relay::where('user_id', $this->id)->where('port', $origin_port)->get();
foreach ($relay_rules as $rule) {
$rule->port = $this->port;
$rule->save();
}
$this->save();
$this->cleanSubCache();
return [
'ok' => true,
'msg' => $this->port
];
}
/**
* 重置端口
*/
public function ResetPort()
{
$price = Config::get('port_price');
if ($this->money < $price) {
return [
'ok' => false,
'msg' => '余额不足'
];
}
$this->money -= $price;
$Port = Tools::getAvPort();
$this->setPort($Port);
$this->save();
return [
'ok' => true,
'msg' => $this->port
];
}
/**
* 指定端口
*/
public function SpecifyPort($Port)
{
$price = Config::get('port_price_specify');
if ($this->money < $price) {
return [
'ok' => false,
'msg' => '余额不足'
];
}
if ($Port < Config::get('min_port') || $Port > Config::get('max_port') || Tools::isInt($Port) == false) {
return [
'ok' => false,
'msg' => '端口不在要求范围内'
];
}
$PortOccupied = User::pluck('port')->toArray();
if (in_array($Port, $PortOccupied) == true) {
return [
'ok' => false,
'msg' => '端口已被占用'
];
}
$this->money -= $price;
$this->setPort($Port);
$this->save();
return [
'ok' => true,
'msg' => '钦定成功'
];
}
public function valid_use_loop()
{
$boughts = Bought::where('userid', $this->id)->orderBy('id', 'desc')->get();
$data = [];
foreach ($boughts as $bought) {
$shop = $bought->shop();
if ($shop != null && $bought->valid()) {
$data[] = $bought->reset_time();
}
}
if (count($data) == 0) {
return '未购买套餐.';
}
if (count($data) == 1) {
return $data[0];
}
return '多个有效套餐无法显示.';
}
}

@ -5,6 +5,7 @@ namespace App\Services;
use App\Models\User;
use App\Models\Node;
use App\Utils\Tools;
use App\Models\Code;
class Analytics
{
@ -117,4 +118,26 @@ class Analytics
}
)->where('node_heartbeat', '>', time() - 90)->count();
}
public function getIncome($start, $end)
{
$sum = Code::where('usedatetime', '>=', date("Y-m-d H:i:s", $start))
->where('usedatetime', '<', date("Y-m-d H:i:s", $end))
->sum('number');
if ($sum == null) {
$sum = 0;
}
return $sum;
}
public function getNewUsers($start, $end)
{
$users = User::where('reg_date', '>=', date("Y-m-d H:i:s", $start))
->where('reg_date', '<', date("Y-m-d H:i:s", $end))
->count();
if ($users == null) {
$users = 0;
}
return $users;
}
}

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

@ -1,7 +0,0 @@
<?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;

@ -1,31 +0,0 @@
<?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();

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

@ -2,18 +2,23 @@
namespace App\Services;
use App\Models\GConfig;
class Config
{
// TODO: remove
public static function get($key)
{
global $System_Config;
return $System_Config[$key];
return $_ENV[$key];
}
public static function set($key, $value)
public static function getdb($key)
{
global $System_Config;
$System_Config[$key] = $value;
$value = GConfig::find($key);
if ($value === null) {
$value = DefaultConfig::firstOrCreate($key);
}
return $value->value;
}
public static function getPublicConfig()
@ -38,7 +43,6 @@ class Config
'sspanelAnalysis' => self::get('sspanelAnalysis'),
'enable_donate' => self::get('enable_donate'),
'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'),
@ -60,7 +64,11 @@ class Config
'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')
'auto_detect_ban' => self::get('auto_detect_ban'),
'subscribe_client' => self::get('subscribe_client'),
'enable_sub_cache' => self::get('enable_sub_cache'),
'use_new_telegram_bot' => self::get('use_new_telegram_bot'),
'subscribe_client_url' => self::get('subscribe_client_url'),
];
}
@ -93,9 +101,8 @@ class Config
public static function getMuKey()
{
global $System_Config;
$muKeyList = array_key_exists('muKeyList', $System_Config) ? $System_Config['muKeyList'] : [' '];
return array_merge(explode(',', $System_Config['muKey']), $muKeyList);
$muKeyList = array_key_exists('muKeyList', $_ENV) ? $_ENV['muKeyList'] : [' '];
return array_merge(explode(',', $_ENV['muKey']), $muKeyList);
}
public static function getSupportParam($type)

@ -0,0 +1,236 @@
<?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' => '系统默认',
],
'get.Detect.Log' => [
'key' => $key,
'value' => '0',
'name' => '审计记录的处理记录',
'comment' => '',
'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,8 +5,6 @@ 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
{
@ -23,24 +21,4 @@ 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,19 +14,40 @@ 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);
abstract public function getPurchaseHTML();
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
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();
@ -62,6 +83,58 @@ abstract class AbstractPayment
$Payback->save();
}
if (Config::get('enable_donate') == true) {
if ($user->is_hide == 1) {
Telegram::Send('一位不愿透露姓名的大老爷给我们捐了 ' . $codeq->number . ' 元!');
} else {
Telegram::Send($user->user_name . ' 大老爷给我们捐了 ' . $codeq->number . ' 元!');
}
}
return 0;
}
public function postPaymentMaliopay($pid, $method)
{
$p = Paylist::where('tradeno', $pid)->first();
if ($p->status == 1) {
return json_encode(['errcode' => 0]);
}
$p->status = 1;
$p->save();
$user = User::find($p->userid);
// 先保存code,防止用户账号余额重复到账
$codeq = new Code();
$codeq->code = $method;
$codeq->isused = 1;
$codeq->type = -1;
$codeq->number = $p->total;
$codeq->usedatetime = date('Y-m-d H:i:s');
$codeq->userid = $user->id;
$codeq->tradeno = $pid;
$user->money += $p->total;
$user->save();
if (!$codeq->save()) {
return 0; // failed
}
if ($user->ref_by >= 1) {
$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();
}
if (Config::get('enable_donate') == 'true') {
if ($user->is_hide == 1) {
Telegram::Send('一位不愿透露姓名的大老爷给我们捐了 ' . $codeq->number . ' 元!');

@ -69,6 +69,46 @@ class AopF2F extends AbstractPayment
return json_encode($return);
}
public function purchase_maliopay($type, $price)
{
$amount = $price;
$user = Auth::getUser();
$pl = new Paylist();
$pl->userid = $user->id;
$pl->tradeno = self::generateGuid();
$pl->total = $amount;
$pl->save();
$gateway = Omnipay::create('Alipay_AopF2F');
$gateway->setSignType('RSA2'); //RSA/RSA2
$gateway->setAppId(Config::get('f2fpay_app_id'));
$gateway->setPrivateKey(Config::get('merchant_private_key')); // 可以是路径,也可以是密钥内容
$gateway->setAlipayPublicKey(Config::get('alipay_public_key')); // 可以是路径,也可以是密钥内容
$notifyUrl = Config::get('f2fNotifyUrl') ?? (Config::get('baseUrl') . '/payment/notify/f2fpay');
$gateway->setNotifyUrl($notifyUrl);
$request = $gateway->purchase();
$request->setBizContent([
'subject' => $pl->tradeno,
'out_trade_no' => $pl->tradeno,
'total_amount' => $pl->total
]);
/** @var \Omnipay\Alipay\Responses\AopTradePreCreateResponse $response */
$aliResponse = $request->send();
// 获取收款二维码内容
$qrCodeContent = $aliResponse->getQrCode();
$return['errcode'] = 0;
$return['url'] = $qrCodeContent;
$return['amount'] = $pl->total;
$return['tradeno'] = $pl->tradeno;
return $return;
}
public function notify($request, $response, $args)
{
$gateway = $this->createGateway();

@ -151,6 +151,64 @@ class BitPayX extends AbstractPayment
return json_encode(['errcode' => -1, 'errmsg' => $result . error]);
}
public function purchase_maliopay($type, $price)
{
$user = Auth::getUser();
$pl = new Paylist();
$pl->userid = $user->id;
$pl->total = $price;
$pl->tradeno = self::generateGuid();
$pl->datetime = time(); // date("Y-m-d H:i:s");
$pl->save();
$data['merchant_order_id'] = $pl->tradeno;
$data['price_amount'] = (float)$price;
$data['price_currency'] = 'CNY';
$type = strtoupper($type);
if ($type === 'WECHAT') {
$data['pay_currency'] = $type;
}
if ($type === 'ALIGLOBAL' || $type === 'ALIPAY') {
$data['pay_currency'] = $type;
}
$data['mobile'] = false;
$data['title'] = '支付单号:' . $pl->tradeno;
$data['description'] = '充值:' . $price . ' 元';
$data['callback_url'] = Config::get('baseUrl') . '/payment/notify/bitpayx';
$data['success_url'] = Config::get('baseUrl') . '/user/payment/return?merchantTradeNo='.$pl->tradeno.'&tradeno='.$pl->tradeno;
$data['cancel_url'] = Config::get('baseUrl') . '/user/code';
$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;
$qrcode_url = '';
$click_url = '';
if ($result['status'] === 200 || $result['status'] === 201) {
$result['payment_url'] .= '&lang=zh';
if ($result['invoice'] && $result['invoice']['pay_currency']) {
$pay_currency = $result['invoice']['pay_currency'];
$order_id = $result['invoice']['order_id'];
$base_url = 'https://www.zhihu.com/qrcode?url=';
if ($pay_currency === 'ALIPAY') {
$click_url = 'https://qrcode.icedropper.com/invoices/?id=' . $order_id . '&type=ALIPAY';
$qrcode_url = $base_url . $click_url;
} else if ($pay_currency === 'ALIGLOBAL') {
$click_url = 'https://qrcode.oceanlunettes.com/invoices/?id=' . $order_id . '&type=ALIGLOBAL';
$qrcode_url = $base_url . $click_url;
} else if ($pay_currency === 'WECHAT') {
$qrcode_url = $result['invoice']['qrcode'];
$click_url = "#";
}
}
return array('url' => $result['payment_url'], 'qrcode_url' => $qrcode_url, 'click_url' => $click_url, 'errcode' => 0, 'tradeno' => $pl->tradeno);
}
return ['errcode' => -1, 'errmsg' => $result];
}
public function notify($request, $response, $args)
{
if (!$this->bitpayAppSecret || $this->bitpayAppSecret === '') {

@ -1,161 +0,0 @@
<?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;
}
}

@ -0,0 +1,176 @@
<?php
/* *
* 支付宝接口公用函数
* 详细:该类是请求、通知返回两个文件所调用的公用函数核心处理文件
* 版本:3.3
* 日期:2012-07-19
* 说明:
* 以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
* 该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
*/
/**
* 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
* @param $para 需要拼接的数组
* return 拼接完成以后的字符串
*/
function createLinkstring($para) {
$arg = "";
foreach ($para as $key=>$val){
$arg.=$key."=".$val."&";
}
//去掉最后一个&字符
$arg = rtrim($arg,'&');
//如果存在转义字符,那么去掉转义
if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}
return $arg;
}
/**
* 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串,并对字符串做urlencode编码
* @param $para 需要拼接的数组
* return 拼接完成以后的字符串
*/
function createLinkstringUrlencode($para) {
$arg = "";
foreach ($para as $key=>$val){
$arg.=$key."=".$val."&";
}
//去掉最后一个&字符
$arg = rtrim($arg,'&');
//如果存在转义字符,那么去掉转义
if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}
return $arg;
}
/**
* 除去数组中的空值和签名参数
* @param $para 签名参数组
* return 去掉空值与签名参数后的新签名参数组
*/
function paraFilter($para) {
$para_filter = array();
foreach ($para as $key=>$val){
if($key == "sign" || $key == "sign_type" || $val == "")continue;
else $para_filter[$key] = $para[$key];
}
return $para_filter;
}
/**
* 对数组排序
* @param $para 排序前的数组
* return 排序后的数组
*/
function argSort($para) {
ksort($para);
reset($para);
return $para;
}
/**
* 写日志,方便测试(看网站需求,也可以改成把记录存入数据库)
* 注意:服务器需要开通fopen配置
* @param $word 要写入日志里的文本内容 默认值:空值
*/
function logResult($word='') {
$fp = fopen("log.txt","a");
flock($fp, LOCK_EX) ;
fwrite($fp,"执行日期:".strftime("%Y%m%d%H%M%S",time())."\n".$word."\n");
flock($fp, LOCK_UN);
fclose($fp);
}
/**
* 远程获取数据,POST模式
* 注意:
* 1.使用Crul需要修改服务器中php.ini文件的设置,找到php_curl.dll去掉前面的";"就行了
* 2.文件夹中cacert.pem是SSL证书请保证其路径有效,目前默认路径是:getcwd().'\\cacert.pem'
* @param $url 指定URL完整路径地址
* @param $cacert_url 指定当前工作目录绝对路径
* @param $para 请求的数据
* @param $input_charset 编码格式。默认值:空值
* return 远程输出的数据
*/
function getHttpResponsePOST($url, $cacert_url, $para, $input_charset = '') {
if (trim($input_charset) != '') {
$url = $url."_input_charset=".$input_charset;
}
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
curl_setopt($curl, CURLOPT_CAINFO,$cacert_url);//证书地址
curl_setopt($curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
curl_setopt($curl,CURLOPT_POST,true); // post传输数据
curl_setopt($curl,CURLOPT_POSTFIELDS,$para);// post传输数据
$responseText = curl_exec($curl);
//var_dump( curl_error($curl) );//如果执行curl过程中出现异常,可打开此开关,以便查看异常内容
curl_close($curl);
return $responseText;
}
/**
* 远程获取数据,GET模式
* 注意:
* 1.使用Crul需要修改服务器中php.ini文件的设置,找到php_curl.dll去掉前面的";"就行了
* 2.文件夹中cacert.pem是SSL证书请保证其路径有效,目前默认路径是:getcwd().'\\cacert.pem'
* @param $url 指定URL完整路径地址
* @param $cacert_url 指定当前工作目录绝对路径
* return 远程输出的数据
*/
function getHttpResponseGET($url,$cacert_url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
curl_setopt($curl, CURLOPT_CAINFO,$cacert_url);//证书地址
$responseText = curl_exec($curl);
//var_dump( curl_error($curl) );//如果执行curl过程中出现异常,可打开此开关,以便查看异常内容
curl_close($curl);
return $responseText;
}
/**
* 实现多种字符编码方式
* @param $input 需要编码的字符串
* @param $_output_charset 输出的编码格式
* @param $_input_charset 输入的编码格式
* return 编码后的字符串
*/
function charsetEncode($input,$_output_charset ,$_input_charset) {
$output = "";
if(!isset($_output_charset) )$_output_charset = $_input_charset;
if($_input_charset == $_output_charset || $input ==null ) {
$output = $input;
} elseif (function_exists("mb_convert_encoding")) {
$output = mb_convert_encoding($input,$_output_charset,$_input_charset);
} elseif(function_exists("iconv")) {
$output = iconv($_input_charset,$_output_charset,$input);
} else die("sorry, you have no libs support for charset change.");
return $output;
}
/**
* 实现多种字符解码方式
* @param $input 需要解码的字符串
* @param $_output_charset 输出的解码格式
* @param $_input_charset 输入的解码格式
* return 解码后的字符串
*/
function charsetDecode($input,$_input_charset ,$_output_charset) {
$output = "";
if(!isset($_input_charset) )$_input_charset = $_input_charset ;
if($_input_charset == $_output_charset || $input ==null ) {
$output = $input;
} elseif (function_exists("mb_convert_encoding")) {
$output = mb_convert_encoding($input,$_output_charset,$_input_charset);
} elseif(function_exists("iconv")) {
$output = iconv($_input_charset,$_output_charset,$input);
} else die("sorry, you have no libs support for charset changes.");
return $output;
}
?>

@ -0,0 +1,41 @@
<?php
/* *
* MD5
* 详细:MD5加密
* 版本:3.3
* 日期:2012-07-19
* 说明:
* 以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
* 该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
*/
/**
* 签名字符串
* @param $prestr 需要签名的字符串
* @param $key 私钥
* return 签名结果
*/
function md5Sign($prestr, $key) {
$prestr = $prestr . $key;
return md5($prestr);
}
/**
* 验证签名
* @param $prestr 需要签名的字符串
* @param $sign 签名结果
* @param $key 私钥
* return 签名结果
*/
function md5Verify($prestr, $sign, $key) {
$prestr = $prestr . $key;
$mysgin = md5($prestr);
if($mysgin == $sign) {
return true;
}
else {
return false;
}
}
?>

@ -0,0 +1,121 @@
<?php
/* *
* 类名:EpayNotify
* 功能:SAF易支付通知处理类
* 详细:处理易支付接口通知返回
*/
namespace App\Services\Gateway;
require_once("epay_core.function.php");
require_once("epay_md5.function.php");
class AlipayNotify {
var $alipay_config;
function __construct($alipay_config){
$this->alipay_config = $alipay_config;
$this->http_verify_url = $this->alipay_config['apiurl'].'api.php?';
}
function AlipayNotify($alipay_config) {
$this->__construct($alipay_config);
}
/**
* 针对notify_url验证消息是否是支付宝发出的合法消息
* @return 验证结果
*/
function verifyNotify(){
if(empty($_GET)) {//判断POST来的数组是否为空
return false;
}
else {
//生成签名结果
$isSign = $this->getSignVeryfy($_GET, $_GET["sign"]);
//获取支付宝远程服务器ATN结果(验证是否是支付宝发来的消息)
$responseTxt = 'true';
//if (! empty($_POST["notify_id"])) {$responseTxt = $this->getResponse($_POST["notify_id"]);}
//验证
//$responsetTxt的结果不是true,与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
//isSign的结果不是true,与安全校验码、请求时的参数格式(如:带自定义参数等)、编码格式有关
if (preg_match("/true$/i",$responseTxt) && $isSign) {
return true;
} else {
return false;
}
}
}
/**
* 针对return_url验证消息是否是支付宝发出的合法消息
* @return 验证结果
*/
function verifyReturn(){
if(empty($_GET)) {//判断POST来的数组是否为空
return false;
}
else {
//生成签名结果
$isSign = $this->getSignVeryfy($_GET, $_GET["sign"]);
//获取支付宝远程服务器ATN结果(验证是否是支付宝发来的消息)
$responseTxt = 'true';
//if (! empty($_GET["notify_id"])) {$responseTxt = $this->getResponse($_GET["notify_id"]);}
//验证
//$responsetTxt的结果不是true,与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
//isSign的结果不是true,与安全校验码、请求时的参数格式(如:带自定义参数等)、编码格式有关
if (preg_match("/true$/i",$responseTxt) && $isSign) {
return true;
} else {
return false;
}
}
}
/**
* 获取返回时的签名验证结果
* @param $para_temp 通知返回来的参数数组
* @param $sign 返回的签名结果
* @return 签名验证结果
*/
function getSignVeryfy($para_temp, $sign) {
//除去待签名参数数组中的空值和签名参数
$para_filter = paraFilter($para_temp);
//对待签名参数数组排序
$para_sort = argSort($para_filter);
//把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
$prestr = createLinkstring($para_sort);
$isSgin = false;
$isSgin = md5Verify($prestr, $sign, $this->alipay_config['key']);
return $isSgin;
}
/**
* 获取远程服务器ATN结果,验证返回URL
* @param $notify_id 通知校验ID
* @return 服务器ATN结果
* 验证结果集:
* invalid命令参数不对 出现这个错误,请检测返回处理中partner和key是否为空
* true 返回正确信息
* false 请检查防火墙或者是服务器阻止端口问题以及验证时间是否超过一分钟
*/
function getResponse($notify_id) {
$transport = strtolower(trim($this->alipay_config['transport']));
$partner = trim($this->alipay_config['partner']);
$veryfy_url = '';
if($transport == 'https') {
$veryfy_url = $this->https_verify_url;
}
else {
$veryfy_url = $this->http_verify_url;
}
$veryfy_url = $veryfy_url."partner=" . $partner . "&notify_id=" . $notify_id;
$responseTxt = getHttpResponseGET($veryfy_url, $this->alipay_config['cacert']);
return $responseTxt;
}
}
?>

@ -0,0 +1,98 @@
<?php
/* *
* 类名:EpaySubmit
* 功能:SAF易支付接口请求提交类
* 详细:构造易支付接口表单HTML文本,获取远程HTTP数据
*/
namespace App\Services\Gateway;
require_once("epay_core.function.php");
require_once("epay_md5.function.php");
class AlipaySubmit {
var $alipay_config;
function __construct($alipay_config){
$this->alipay_config = $alipay_config;
$this->alipay_gateway_new = $this->alipay_config['apiurl'].'submit.php?';
}
function AlipaySubmit($alipay_config) {
$this->__construct($alipay_config);
}
/**
* 生成签名结果
* @param $para_sort 已排序要签名的数组
* return 签名结果字符串
*/
function buildRequestMysign($para_sort) {
//把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
$prestr = createLinkstring($para_sort);
$mysign = md5Sign($prestr, $this->alipay_config['key']);
return $mysign;
}
/**
* 生成要请求给支付宝的参数数组
* @param $para_temp 请求前的参数数组
* @return 要请求的参数数组
*/
function buildRequestPara($para_temp) {
//除去待签名参数数组中的空值和签名参数
$para_filter = paraFilter($para_temp);
//对待签名参数数组排序
$para_sort = argSort($para_filter);
//生成签名结果
$mysign = $this->buildRequestMysign($para_sort);
//签名结果与签名方式加入请求提交参数组中
$para_sort['sign'] = $mysign;
$para_sort['sign_type'] = strtoupper(trim($this->alipay_config['sign_type']));
return $para_sort;
}
/**
* 生成要请求给支付宝的参数数组
* @param $para_temp 请求前的参数数组
* @return 要请求的参数数组字符串
*/
function buildRequestParaToString($para_temp) {
//待请求参数数组
$para = $this->buildRequestPara($para_temp);
//把参数组中所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串,并对字符串做urlencode编码
$request_data = createLinkstringUrlencode($para);
return $request_data;
}
/**
* 建立请求,以表单HTML形式构造(默认)
* @param $para_temp 请求参数数组
* @param $method 提交方式。两个值可选:post、get
* @param $button_name 确认按钮显示文字
* @return 提交表单HTML文本
*/
function buildRequestForm($para_temp, $method='POST', $button_name='正在跳转') {
//待请求参数数组
$para = $this->buildRequestPara($para_temp);
$sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='".$this->alipay_gateway_new."_input_charset=".trim(strtolower($this->alipay_config['input_charset']))."' method='".$method."'>";
foreach ($para as $key=>$val){
$sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
}
//submit按钮控件请不要含有name属性
$sHtml = $sHtml."<input type='submit' value='".$button_name."'></form>";
$sHtml = $sHtml."<script>document.forms['alipaysubmit'].submit();</script>";
return $sHtml;
}
}
?>

@ -0,0 +1,253 @@
<?php
namespace App\Services\Gateway;
use App\Services\Auth;
use App\Models\Paylist;
use App\Services\Config;
use App\Services\View;
require_once("IDt/epay_submit.class.php");
require_once("IDt/epay_notify.class.php");
class IDtPay 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();
$pl = new Paylist();
$pl->userid = $user->id;
$pl->total = $price;
$pl->tradeno = self::generateGuid();
$pl->save();
$settings = Config::get("idtpay");
$alipay_config = array(
'partner' => $settings['partner'],
'key' => $settings['key'],
'sign_type' => $settings['sign_type'],
'input_charset' => $settings['input_charset'],
'transport' => $settings['transport'],
'apiurl' => $settings['apiurl']
);
/**************************请求参数**************************/
$notify_url = Config::get("baseUrl")."/payment/notify";
//需http://格式的完整路径,不能加?id=123这类自定义参数
//页面跳转同步通知页面路径
$return_url = Config::get("baseUrl")."/user/payment/return";
//需http://格式的完整路径,不能加?id=123这类自定义参数,不能写成http://localhost/
//商户订单号
$out_trade_no = $pl->tradeno;
//商户网站订单系统中唯一订单号,必填
//商品名称
$name =$settings["subjects"][array_rand($settings["subjects"])];
//付款金额
$money =$price;
//站点名称
$sitename = $settings['appname'];
//必填
//订单描述
/************************************************************/
//构造要请求的参数数组,无需改动
$parameter = array(
"pid" => trim($alipay_config['partner']),
"type" => $type,
"notify_url" => $notify_url,
"return_url" => $return_url,
"out_trade_no" => $out_trade_no,
"name" => $name,
"money" => $money,
"sitename" => $sitename
);
//建立请求
$alipaySubmit = new AlipaySubmit($alipay_config);
$html_text = $alipaySubmit->buildRequestForm($parameter);
return $response->write(json_encode(['code' => $html_text, 'errcode' => 0, 'pid' => $pl->id]));
}
public function notify($request, $response, $args)
{
$pid = $_GET['out_trade_no'];
$p = Paylist::where('tradeno', '=', $pid)->first();
if ($p->status == 1) {
$success = 1;
} else {
$settings = Config::get("idtpay");
$alipay_config = array(
'partner' => $settings['partner'],
'key' => $settings['key'],
'sign_type' => $settings['sign_type'],
'input_charset' => $settings['input_charset'],
'transport' => $settings['transport'],
'apiurl' => $settings['apiurl']
);
//计算得出通知验证结果
$alipayNotify = new AlipayNotify($alipay_config);
$verify_result = $alipayNotify->verifyNotify();
if($verify_result) {
if ($_GET['trade_status'] == 'TRADE_SUCCESS') {
$this->postPayment($_GET['out_trade_no'], "IDtPay");
$success = 1;
}
else {
$success = 0;
}
}
else {
$success = 0;
}
}
if ($success==1){
echo "success";
}else{
echo "fail";
}
}
public function getReturnHTML($request, $response, $args)
{
$pid = $_GET['out_trade_no'];
$p = Paylist::where('tradeno', '=', $pid)->first();
$money = $p->total;
if ($p->status == 1) {
$success = 1;
} else {
$settings = Config::get("idtpay");
$alipay_config = array(
'partner' => $settings['partner'],
'key' => $settings['key'],
'sign_type' => $settings['sign_type'],
'input_charset' => $settings['input_charset'],
'transport' => $settings['transport'],
'apiurl' => $settings['apiurl']
);
//计算得出通知验证结果
$alipayNotify = new AlipayNotify($alipay_config);
$verify_result = $alipayNotify->verifyNotify();
if($verify_result) {
if ($_GET['trade_status'] == 'TRADE_SUCCESS') {
$this->postPayment($_GET['out_trade_no'], "IDtPay");
$success = 1;
}
else {
$success = 0;
}
}
else {
$success = 0;
}
}
return View::getSmarty()->assign('money', $money)->assign('success', $success)->fetch('user/pay_success.tpl');
}
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="idt_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");
});
$("#idt_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);
}
}
}
});
});
</script>
';
}
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,458 @@
<?php
namespace App\Services\Gateway;
use App\Services\View;
use App\Services\Auth;
use App\Services\Config;
use App\Models\Paylist;
use App\Services\MalioConfig;
use Omnipay\Omnipay;
use Stripe\Stripe;
use Stripe\Charge;
class MalioPay extends AbstractPayment
{
public function purchase($request, $response, $args)
{
$price = $request->getParam('price');
$type = $request->getParam('type');
$user = Auth::getUser();
if ($type != 'alipay' and $type != 'wechat') {
return json_encode(['ret' => 0, 'msg' => 'wrong type']);
}
if ($price < MalioConfig::get('mups_minimum_amount')) {
return json_encode(['ret' => 0, 'errmsg' => '充值最低金额为' . MalioConfig::get('mups_minimum_amount') . '元']);
}
if ($price <= 0) {
return json_encode(['ret' => 0, 'msg' => "金额必须大于0元"]);
}
if ($type == 'alipay') {
$payment_system = MalioConfig::get('mups_alipay');
switch ($payment_system) {
case ('bitpayx'):
$bitpayx = new BitPayX(Config::get('bitpay_secret'));
$result = $bitpayx->purchase_maliopay($type, $price);
if ($result['errcode'] == 0) {
$return = array(
'ret' => 1,
'type' => 'url',
'tradeno' => $result['tradeno'],
'url' => $result['url']
);
} else {
$return = array(
'ret' => 0,
'msg' => $result['errmsg']
);
}
return json_encode($return);
case ('tomatopay'):
$tomatopay = new TomatoPay();
$result = $tomatopay->purchase_maliopay($type, $price);
if ($result['errcode'] == 0) {
$return = array(
'ret' => 1,
'type' => 'url',
'tradeno' => $result['tradeno'],
'url' => $result['code']
);
} else {
$return = array(
'ret' => 0,
'msg' => $result['errmsg']
);
}
return json_encode($return);
case ('f2fpay'):
$f2fpay = new AopF2F();
$result = $f2fpay->purchase_maliopay($type, $price);
if ($result['errcode'] == 0) {
$return = array(
'ret' => 1,
'type' => 'qrcode',
'tradeno' => $result['tradeno'],
'url' => $result['url']
);
} else {
$return = array(
'ret' => 0,
'msg' => $result['errmsg']
);
}
return json_encode($return);
case ('stripe'):
$stripe = new StripePay();
$result = $stripe->purchase_maliopay($type, $price);
if ($result['errcode'] == 0) {
$return = array(
'ret' => 1,
'type' => 'url',
'tradeno' => $result['tradeno'],
'url' => $result['url']
);
} else {
$return = array(
'ret' => 0,
'msg' => $result['errmsg']
);
}
return json_encode($return);
case ('wolfpay'):
$wolfpay = new Wolfpay();
$result = $wolfpay->purchase_maliopay($type, $price);
if ($result['errcode'] == 0) {
$return = array(
'ret' => 1,
'type' => 'url',
'tradeno' => $result['tradeno'],
'url' => $result['url']
);
} else {
$return = array(
'ret' => 0,
'msg' => $result['errmsg']
);
}
return json_encode($return);
case ('materialpay'):
$materialpay = new MaterialPay(Config::get('materialpay_secret'));
$result = $materialpay->purchase_maliopay($type, $price);
if ($result['errcode'] == 0) {
$return = array(
'ret' => 1,
'type' => 'url',
'tradeno' => $result['tradeno'],
'url' => $result['url']
);
} else {
$return = array(
'ret' => 0,
'msg' => $result['errmsg']
);
}
return json_encode($return);
}
} else if ($type == 'wechat') {
$payment_system = MalioConfig::get('mups_wechat');
switch ($payment_system) {
case ('bitpayx'):
$bitpayx = new BitPayX(Config::get('bitpay_secret'));
$result = $bitpayx->purchase_maliopay($type, $price);
if ($result['errcode'] == 0) {
$return = array(
'ret' => 1,
'type' => 'qrcode',
'tradeno' => $result['tradeno'],
'url' => $result['qrcode_url']
);
} else {
$return = array(
'ret' => 0,
'msg' => $result['errmsg']
);
}
return json_encode($return);
case ('tomatopay'):
$tomatopay = new TomatoPay();
$result = $tomatopay->purchase_maliopay($type, $price);
if ($result['errcode'] == 0) {
$return = array(
'ret' => 1,
'type' => 'url',
'tradeno' => $result['tradeno'],
'url' => $result['code']
);
} else {
$return = array(
'ret' => 0,
'msg' => $result['errmsg']
);
}
return json_encode($return);
case ('stripe'):
$stripe = new StripePay();
$result = $stripe->purchase_maliopay($type, $price);
if ($result['errcode'] == 0) {
$return = array(
'ret' => 1,
'type' => 'qrcode',
'tradeno' => $result['tradeno'],
'url' => $result['url']
);
} else {
$return = array(
'ret' => 0,
'msg' => $result['errmsg']
);
}
return json_encode($return);
case ('materialpay'):
$materialpay = new MaterialPay(Config::get('materialpay_secret'));
$result = $materialpay->purchase_maliopay($type, $price);
if ($result['errcode'] == 0) {
$return = array(
'ret' => 1,
'type' => 'qrcode',
'tradeno' => $result['tradeno'],
'url' => $result['url']
);
} else {
$return = array(
'ret' => 0,
'msg' => $result['errmsg']
);
}
return json_encode($return);
}
}
}
public function notify($request, $response, $args)
{
$path = $request->getUri()->getPath();
$path_exploded = explode('/', $path);
$payment_system = $path_exploded[3];
switch ($payment_system) {
case ('bitpayx'):
$bitpayx = new BitPayX(Config::get('bitpay_secret'));
if (!Config::get('bitpay_secret') || Config::get('bitpay_secret') === '') {
$return = [];
$return['status'] = 400;
echo json_encode($return);
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'];
}
$str_to_sign = $bitpayx->prepareSignId($inputJSON['merchant_order_id']);
$resultVerify = $bitpayx->verify($str_to_sign, $inputJSON['token']);
$isPaid = $data !== null && $data['status'] !== null && $data['status'] === 'PAID';
if ($resultVerify && $isPaid) {
$bitpayx->postPaymentMaliopay($data['merchant_order_id'], '在线支付 ' . $data['merchant_order_id']);
// echo 'SUCCESS';
$return = [];
$return['status'] = 200;
echo json_encode($return);
} else {
// echo 'FAIL';
$return = [];
$return['status'] = 400;
echo json_encode($return);
}
return $return;
case ('tomatopay'):
$type = 'alipay';
$settings = Config::get("tomatopay")[$type];
$order_data = $_REQUEST;
$transid = $order_data['trade_no']; //转账交易号
$invoiceid = $order_data['out_trade_no']; //订单号
$amount = $order_data['total_fee']; //获取递过来的总价格
$status = $order_data['trade_status']; //获取传递过来的交易状态
$signs = $order_data['sign'];
if ($request->isGet()) {
header("Location: /user/payment/return?tradeno=".$order_data['out_trade_no']);
return 0;
}
$security = array();
$security['out_trade_no'] = $invoiceid;
$security['total_fee'] = $amount;
$security['trade_no'] = $transid;
$security['trade_status'] = $status;
foreach ($security as $k => $v) {
$o .= "$k=" . urlencode($v) . "&";
}
$sign = md5(substr($o, 0, -1) . $settings['token']);
if ($sign == $signs) {
//验重
$p = Paylist::where('tradeno', '=', $order_data['out_trade_no'])->first();
$money = $p->total;
if ($p->status != 1) {
$this->postPaymentMaliopay($order_data['out_trade_no'], "在线支付");
echo 'SUCCESS';
} else {
echo 'ERROR';
}
echo 'success';
} else {
echo '验证失败';
}
return 'tomatopay';
case ('f2fpay'):
$f2fpay = new AopF2F();
$gateway = Omnipay::create('Alipay_AopF2F');
$gateway->setSignType('RSA2'); //RSA/RSA2
$gateway->setAppId(Config::get('f2fpay_app_id'));
$gateway->setPrivateKey(Config::get('merchant_private_key')); // 可以是路径,也可以是密钥内容
$gateway->setAlipayPublicKey(Config::get('alipay_public_key')); // 可以是路径,也可以是密钥内容
$aliRequest = $gateway->completePurchase();
$aliRequest->setParams($_POST);
$aliResponse = $aliRequest->send();
$pid = $aliResponse->data('out_trade_no');
if ($aliResponse->isPaid()) {
$this->postPaymentMaliopay($pid, '支付宝');
die('success'); //The response should be 'success' only
}
return 'f2fpay';
case ('stripe'):
Stripe::setApiKey(Config::get('stripe_key'));
$endpoint_secret = Config::get('stripe_webhook_endpoint_secret');
$payload = @file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
$event = null;
try {
$event = \Stripe\Webhook::constructEvent(
$payload,
$sig_header,
$endpoint_secret
);
} catch (\UnexpectedValueException $e) {
http_response_code(400);
exit();
} catch (\Stripe\Error\SignatureVerification $e) {
http_response_code(400);
exit();
}
switch ($event->type) {
case 'source.chargeable':
$source = $event->data->object;
$charge = Charge::create([
'amount' => $source['amount'],
'currency' => $source['currency'],
'source' => $source['id'],
]);
if ($charge['status'] == 'succeeded') {
$type = null;
if ($source['type'] == 'alipay') {
$type = '支付宝支付';
} else if ($source['type'] == 'wechat') {
$type = '微信支付';
}
$order = Paylist::where('tradeno', '=', $source['id'])->first();
if ($order->status != 1) {
$this->postPaymentMaliopay($source['id'], 'Stripe '.$type);
echo 'SUCCESS';
} else {
echo 'ERROR';
}
}
break;
default:
http_response_code(400);
exit();
}
http_response_code(200);
case ('wolfpay'):
$type = $args['method'];
$settings = Config::get("wolfpay") ['config'];
$security['orderid'] = $_REQUEST['out_trade_no'];
if ($security['orderid'] == '' OR $security['orderid'] == null) {
header("Location: /user/code");
} else {
//实例化支付类
//$pay = new Pays($settings['hid'], $settings['key']);
$wolfpay = new Wolfpay();
//接收异步通知数据
$data = $_GET;
//商户订单号
$out_trade_no = $data['out_trade_no'];
//验证签名
if ($wolfpay->verify($data)) {
//验证支付状态
if ($data['trade_status'] == 'TRADE_SUCCESS') {
$wolfpay->postPaymentMaliopay($data['out_trade_no'], "在线支付");
echo "success";
header("Location: /user/code");
}
} else {
echo '錯誤';
}
}
case ('materialpay'):
$data = array();
$data['tradeStatus'] = $request->getParam('tradeStatus');
$data['payAmount'] = number_format($request->getParam('payAmount'),2);
$data['tradeNo'] = $request->getParam('tradeNo');
$data['payType'] = $request->getParam('payType');
$data['outTradeNo'] = $request->getParam('outTradeNo');
$pl = Paylist::where('tradeno',$data['outTradeNo'])->first();
if ($pl->status == 1) {
echo 'success';
return;
}
$materialpay = new MaterialPay(Config::get('materialpay_secret'));
// 准备待签名数据
$str_to_sign = $materialpay->prepareSign($data);
// 验证签名
$resultVerify = $materialpay->verify($str_to_sign, $request->getParam('sign'));
if ($resultVerify) {
$materialpay->postPaymentMaliopay($data['outTradeNo'], 'MaterialPay - ' . $data['outTradeNo']);
echo 'success';
return;
} else {
echo 'fail';
return;
}
default:
return 'failed';
}
}
public function getPurchaseHTML()
{
return 1;
}
public function getReturnHTML($request, $response, $args)
{
$tradeno = $_GET['tradeno'];
if ($tradeno == '' || $tradeno == null) {
$tradeno = $_GET['source'];
}
if ($tradeno == '' || $tradeno == null) {
$tradeno = $_GET['out_trade_no'];
}
$p = Paylist::where('tradeno', '=', $tradeno)->first();
$money = $p->total;
if ($p->status === 1) {
$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)
{
$p = Paylist::where('tradeno', $_POST['tradeno'])->first();
$return['ret'] = 1;
$return['result'] = $p->status;
return json_encode($return);
}
}

@ -1,11 +1,4 @@
<?php
/**
* Created by PhpStorm.
* User: tonyzou
* Date: 2018/9/28
* Time: 9:08 PM
*/
namespace App\Services\Gateway;
use App\Services\View;
@ -13,87 +6,64 @@ use App\Services\Auth;
use App\Services\Config;
use App\Models\Paylist;
class TrimePay extends AbstractPayment
class MaterialPay extends AbstractPayment
{
private $appSecret;
private $gatewayUri;
/**
* 签名初始化
* @param merKey 签名密钥
*/
public function __construct($appSecret)
{
$this->appSecret = $appSecret;
$this->gatewayUri = 'https://api.payease.io/gateway/';
$this->gatewayUri = 'https://www.materialpay.com/api/payment/';
}
/**
* @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')
public function post($data, $type = 'create')
{
if ($type == 'pay') {
$this->gatewayUri .= 'pay/go';
} elseif ($type == 'refund') {
$this->gatewayUri .= 'refund/go';
} elseif ($type == 'pre') {
$this->gatewayUri .= 'pay/pre';
if ($type == 'create') {
$this->gatewayUri .= 'create';
} else {
$this->gatewayUri .= 'query/go';
$this->gatewayUri .= 'query';
}
$headerArray = array("Content-type:application/json;charset='utf-8'","Accept:application/json");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $this->gatewayUri);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_HTTPHEADER,$headerArray);
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);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($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' => '非法的金额.']);
}
@ -104,18 +74,16 @@ class TrimePay extends AbstractPayment
$pl->tradeno = self::generateGuid();
$pl->save();
$data['appId'] = Config::get('trimepay_appid');
$data['appId'] = Config::get('materialpay_appid');
$data['outTradeNo'] = $pl->tradeno;
$data['payAmount'] = (float)$price;
$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);
$data['returnUrl'] = Config::get('baseUrl') . '/user/code';
switch ($type) {
case ('WEPAY_JSAPI'):
$result = json_decode($this->post($data, $type = 'pre'), true);
case ('WXPAY'):
$result = json_decode($this->post($data), true);
break;
default:
$result = json_decode($this->post($data), true);
@ -124,10 +92,46 @@ class TrimePay extends AbstractPayment
return json_encode($result);
}
public function purchase_maliopay($type, $price)
{
if ($price <= 0) {
return json_encode(['code' => -1, 'errmsg' => '非法的金额.']);
}
if ($type == 'wechat') {
$type = 'WXPAY';
}
if ($type == 'alipay') {
$type = 'ALIPAY_WEB';
}
$user = Auth::getUser();
$pl = new Paylist();
$pl->userid = $user->id;
$pl->total = $price;
$pl->tradeno = self::generateGuid();
$pl->save();
$data['appId'] = Config::get('materialpay_appid');
$data['outTradeNo'] = $pl->tradeno;
$data['payAmount'] = (float)$price;
$data['payType'] = $type;
$params = $this->prepareSign($data);
$data['sign'] = $this->sign($params);
$data['returnUrl'] = Config::get('baseUrl') . '/user/code';
switch ($type) {
case ('WXPAY'):
$result = json_decode($this->post($data), true);
break;
default:
$result = json_decode($this->post($data), true);
}
$result['pid'] = $pl->tradeno;
return array('url' => $result['result']['url'], 'errcode' => 0, 'tradeno' => $pl->tradeno);
}
public function query($tradeNo)
{
$data['appId'] = Config::get('trimepay_appid');
$data['merchantTradeNo'] = $tradeNo;
$data['appId'] = Config::get('materialpay_appid');
$data['outTradeNo'] = $tradeNo;
$params = $this->prepareSign($data);
$data['sign'] = $this->sign($params);
return json_decode($this->post($data, $type = 'query'), true);
@ -136,62 +140,49 @@ class TrimePay extends AbstractPayment
public function notify($request, $response, $args)
{
$data = array();
$data['payStatus'] = $request->getParam('payStatus');
$data['payFee'] = $request->getParam('payFee');
$data['callbackTradeNo'] = $request->getParam('callbackTradeNo');
$data['tradeStatus'] = $request->getParam('tradeStatus');
$data['payAmount'] = number_format($request->getParam('payAmount'),2);
$data['tradeNo'] = $request->getParam('tradeNo');
$data['payType'] = $request->getParam('payType');
$data['merchantTradeNo'] = $request->getParam('merchantTradeNo');
$data['outTradeNo'] = $request->getParam('outTradeNo');
//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';
$this->postPayment($data['outTradeNo'], 'MaterialPay - ' . $data['outTradeNo']);
echo 'success';
} else {
echo 'FAIL';
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');
return View::getSmarty()->fetch('user/materialpay.tpl');
}
public function getReturnHTML($request, $response, $args)
{
$pid = $_GET['merchantTradeNo'];
$pid = $_GET['outTradeNo'];
$p = Paylist::where('tradeno', '=', $pid)->first();
$money = $p->total;
$money = $p->total/1000;
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['tradeStatus'] = $request->getParam('tradeStatus');
$data['payAmount'] = number_format($request->getParam('payAmount'),2);
$data['tradeNo'] = $request->getParam('tradeNo');
$data['payType'] = $request->getParam('payType');
$data['merchantTradeNo'] = $request->getParam('merchantTradeNo');
$data['outTradeNo'] = $request->getParam('outTradeNo');
// 准备待签名数据
$str_to_sign = $this->prepareSign($data);
// 验证签名
$resultVerify = $this->verify($str_to_sign, $request->getParam('sign'));
if ($resultVerify) {
$this->postPayment($data['merchantTradeNo'], 'TrimePay');
$this->postPayment($data['outTradeNo'], 'MaterialPay');
$success = 1;
} else {
$success = 0;

@ -13,6 +13,7 @@ use App\Models\Code;
use App\Services\Auth;
use App\Models\Payback;
use App\Services\Config;
use App\Utils\Telegram;
use Paymentwall_Config;
use Paymentwall_Pingback;
use Paymentwall_Widget;
@ -64,7 +65,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 {

@ -62,9 +62,57 @@ class StripePay extends AbstractPayment
} else {
return json_encode(array('url' => $source['wechat']['qr_code_url'], 'errcode' => 0, 'pid' => $pl->id));
}
}
public function purchase_maliopay($type, $price)
{
$user = Auth::getUser();
if ($type != 'alipay' and $type != 'wechat') {
return json_encode(['errcode' => -1, 'errmsg' => 'wrong payment.']);
}
$stripe_minimum_amount = MalioConfig::get('stripe_minimum_amount');
if ($price < $stripe_minimum_amount) {
return json_encode(['errcode' => -1, 'errmsg' => '充值最低金额为'.$stripe_minimum_amount.'元']);
}
$ch = curl_init();
$url = 'https://api.exchangeratesapi.io/latest?symbols=CNY&base='.strtoupper(MalioConfig::get('stripe_currency'));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$currency = json_decode(curl_exec($ch));
curl_close($ch);
$price_exchanged = ((double)$price) / ($currency->rates->CNY);
return json_encode($source);
return json_encode(array('url' => $source['redirect']['url'], 'errcode' => 0, 'pid' => $pl->id));
$source = Source::create([
'amount' => floor($price_exchanged * 100),
'currency' => MalioConfig::get('stripe_currency'),
'type' => $type,
'redirect' => [
'return_url' => Config::get('baseUrl') . '/user/payment/return',
],
]);
$pl = new Paylist();
$pl->userid = $user->id;
$pl->total = $price;
$pl->tradeno = $source['id'];
$pl->save();
if ($type == 'alipay') {
return array(
'url' => $source['redirect']['url'],
'errcode' => 0,
'tradeno' => $pl->tradeno
);
} else {
return array(
'url' => $source['wechat']['qr_code_url'],
'errcode' => 0,
'tradeno' => $pl->tradeno
);
}
}
public function notify($request, $response, $args)

@ -20,7 +20,8 @@ class TomatoPay extends AbstractPayment
$pl->userid = $user->id;
$pl->total = $price;
$pl->tradeno = self::generateGuid();
$pl->save();
$pl->save();
$fqaccount=$settings['account'];
$fqkey=$settings['token'];
$fqmchid = $settings['mchid'];
@ -39,7 +40,39 @@ class TomatoPay extends AbstractPayment
$result = "<script language='javascript' type='text/javascript'>window.location.href='".$url."';</script>";
$result = json_encode(array('code'=>$url,'errcode'=>0,'pid' =>$pl->id));
return $result;
}
}
public function purchase_maliopay($type, $price)
{
if($price <= 0){
return json_encode(['errcode'=>-1,'errmsg'=>"非法的金额."]);
}
$user = Auth::getUser();
$settings = Config::get("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'];
$fqtype = 1;
$fqtrade = $pl->tradeno;
$fqcny = $price;
$data = [
'account' => $settings['account'],
'mchid' => $settings['mchid'],
'type' => 1,
'trade' => $pl->tradeno,
'cny' => $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=".$fqtype."&trade=".$fqtrade."&cny=".$fqcny."&signs=".$signs;
$result = array('code'=>$url,'errcode'=>0,'tradeno' => $pl->tradeno );
return $result;
}
public function notify($request, $response, $args)
{
@ -154,7 +187,6 @@ $sign = md5(substr($o,0,-1).$settings['token']);
}
}
});
setTimeout(f, 1000);
});
</script>
';

@ -0,0 +1,131 @@
<?php
namespace App\Services\Gateway;
use App\Services\View;
use App\Services\Auth;
use App\Services\Config;
use App\Models\Paylist;
class Wolfpay extends AbstractPayment {
private $pid;
private $key;
private $url;
public function __construct() {
$config = Config::get("wolfpay") ['config'];
$this->pid = $config['hid'];
$this->key = $config['key'];
$this->url = $config['url'];
}
public function purchase($request, $response, $args) {
return '';
}
public function purchase_maliopay($type, $price) {
$user = Auth::getUser();
$settings = Config::get("wolfpay")['config'];
$pl = new Paylist();
$pl->userid = $user->id;
$pl->total = $price;
$pl->tradeno = self::generateGuid();
$pl->save();
//支付方式
$type = 'all'; //$type;
//订单号
$out_trade_no = $pl->tradeno;
//异步通知地址
$notify_url = 'https://' . $_SERVER['HTTP_HOST'] . '/payment/notify/wolfpay/' . $type;
//回调通知地址
$return_url = 'https://' . $_SERVER['HTTP_HOST'] . '/user/payment/return';
//商品名称
$name = 'SS商品-' . $_SERVER['HTTP_HOST'];
//支付金额(保留小数点后两位)
$money = round($price, 2);
//站点名称
$sitename = $_SERVER['HTTP_HOST'];
//发起支付
$url = $this->submit($type, $out_trade_no, $notify_url, $return_url, $name, $money, $sitename);
return array(
'url' => $url,
'errcode' => 0,
'tradeno' => $pl->tradeno
);
}
public function notify($request, $response, $args) {
return '';
}
public function getPurchaseHTML() {
return '';
}
public function getReturnHTML($request, $response, $args) {
}
public function getStatus($request, $response, $args) {
// TODO: Implement getStatus() method.
}
public function verify($data) {
if (!isset($data['sign']) || !$data['sign']) {
return false;
}
$sign = $data['sign'];
unset($data['sign']);
unset($data['sign_type']);
$sign2 = $this->getSign($data, $this->key);
if ($sign != $sign2) {
return false;
}
return true;
}
public function submit($type, $out_trade_no, $notify_url, $return_url, $name, $money, $sitename) {
$data = ['pid' => $this->pid, 'type' => $type, 'out_trade_no' => $out_trade_no, 'notify_url' => $notify_url, 'return_url' => $return_url, 'name' => $name, 'money' => $money, 'sitename' => $sitename];
$string = http_build_query($data);
$keys = $this->ensy($string, $this->pid);
$keyss = $this->base64url_encode($this->pid . '-' . $keys);
$sign = substr($this->ensy($keyss, $this->key) , 0, 15);
return 'https://' . $this->url . '/submit?skey=' . $keyss . '&sign=' . $sign . '&sign_type=MD5';
}
private function getSign($data) {
$data = array_filter($data);
ksort($data);
$str1 = '';
foreach ($data as $k => $v) {
$str1.= '&' . $k . "=" . $v;
}
$str = $str1 . $this->key;
$str = trim($str, '&');
$sign = md5($str);
return $sign;
}
public function ensy($data, $key) {
$key = md5($key);
$len = strlen($data);
$code = '';
for ($i = 0; $i < ceil($len / 32); $i++) {
for ($j = 0; $j < 32; $j++) {
$p = $i * 32 + $j;
if ($p < $len) {
$code.= $data{$p} ^ $key{$j};
}
}
}
$code = str_replace(array(
'+',
'/',
'='
) , array(
'_',
'$',
''
) , base64_encode($code));
return $code;
}
public function base64url_encode($data) {
return rtrim(strtr(base64_encode($data) , '+/', '-_') , '=');
}
}

@ -33,11 +33,8 @@ class YftPayUtil
//待请求参数数组
$para = YftPayUtil::buildRequestPara($para_temp);
$sHtml = "<form id='paysubmit' name='paysubmit' action='https://payment.pi.do/pay/subOrder/zfb' accept-charset='utf-8' method='POST'>";
$params = '';
foreach ($para as $key => $val) {
$sHtml .= "<input type='hidden' name='" . $key . "' value='" . $val . "'/>";
$params = $params.'&'.$key.'='.$val;
}
if ($pay_config->pay_config["type"] == "aliPay") {
$sHtml .= "<input type='hidden' name='subject' value='余额充值'/>";
@ -47,9 +44,7 @@ class YftPayUtil
//submit按钮控件请不要含有name属性
$sHtml = $sHtml . "</form>";
$sHtml = $sHtml . "<script>document.forms['paysubmit'].submit();</script>";
//return $sHtml;
$url = 'https://payment.pi.do/pay/subOrder/zfb?trade_no='.$ss_order_no.'&subject=topup'.$params;
return json_encode(array('url' => $url, 'errcode' => 0));
return $sHtml;
}
/**

@ -224,7 +224,6 @@ if ($pay->verify($data)) {
}
}
});
setTimeout(f, 1000);
});
</script>
';

@ -0,0 +1,74 @@
<?php
namespace App\Services;
use App\Utils\Cookie;
class Internationalization
{
public function __construct()
{
$this->lang = MalioConfig::get('default_lang');
}
public function detectLang($request, $response, $args)
{
$user = Auth::getUser();
if ($user->isLogin == true && $user->lang != null) {
$lang = $user->lang;
} else {
$cookie = Cookie::get('lang');
if ($cookie != null || $cookie != '') {
$lang = $cookie;
} else {
$accept_language = $request->getHeader('Accept-Language');
$accept_language = strtolower($accept_language[0]);
$accept_language = explode(";",$accept_language)[0];
$accept_language = explode(",",$accept_language)[0];
if (strpos($accept_language, 'zh') !== false) {
if (strpos($accept_language, 'cn') !== false || strpos($accept_language, 'sg') !== false) {
$lang = 'zh-cn';
} elseif (strpos($accept_language, 'tw') !== false || strpos($accept_language, 'hk') !== false) {
$lang = 'zh-cn';
} else {
$lang = 'zh-cn';
}
} else if (strpos($accept_language, 'en') !== false) {
$lang = 'en';
}
if ($lang == null) {
$lang = MalioConfig::get('default_lang');
}
Cookie::set([
'lang' => $lang
],'1775445251');
}
}
$this->lang = $lang;
return $lang;
}
public function get($name, $args=null) {
global $I18N;
if ($args == null){
return $I18N[$name][$this->lang];
} else {
$counter = 1;
$text = $I18N[$name][$this->lang];
foreach ($args as $arg) {
$text = str_replace("$".$counter, $arg, $text);
$counter += 1;
}
return $text;
}
}
public static function getPublicConfig()
{
global $I18N;
return $I18N;
}
}

@ -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 (Config::get('smtp_ssl') == 'true') {
if ($_ENV['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, DoiAMPay, PaymentWall, ChenPay, SPay, TrimePay, BitPayX, TomatoPay, flyfoxpay, PAYJS, F2Fpay_PAYJS, StripePay, Payssion, YftPay
AopF2F, Codepay, DoiAMPay, PaymentWall, ChenPay, SPay, TrimePay, BitPayX, TomatoPay, flyfoxpay, PAYJS, F2Fpay_PAYJS, StripePay, Payssion, YftPay, MalioPay, IDtPay
};
class Payment
@ -20,8 +20,6 @@ class Payment
switch ($method) {
case ('codepay'):
return new Codepay();
case ('doiampay'):
return new DoiAMPay();
case ('paymentwall'):
return new PaymentWall();
case ('spay'):
@ -30,8 +28,6 @@ class Payment
return new AopF2F();
case ('chenAlipay'):
return new ChenPay();
case ('trimepay'):
return new TrimePay(Config::get('trimepay_secret'));
case ('bitpayx'):
return new BitPayX(Config::get('bitpay_secret'));
case("tomatopay"):
@ -48,6 +44,10 @@ class Payment
return new Payssion();
case ('yftpay'):
return new YftPay();
case ('malio'):
return new MalioPay();
case ("idtpay"):
return new IDtPay();
default:
return null;
}

@ -1,39 +0,0 @@
<?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();
}
}

@ -1,14 +0,0 @@
<?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);
}

@ -1,49 +0,0 @@
<?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;
}
}

@ -1,60 +0,0 @@
<?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;
}
}

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

@ -4,6 +4,7 @@ namespace App\Services;
use Smarty;
use App\Utils;
use App\Services\Internationalization;
class View
{
@ -18,6 +19,15 @@ class View
if ($user->isLogin) {
$theme = $user->theme;
$theme = $user->theme;
$i18n = new Internationalization();
if (MalioConfig::get('only_one_lang') != 'none') {
$i18n->lang = MalioConfig::get('only_one_lang');
} else {
$i18n->lang = $user->lang;
}
$smarty->assign('i18n', $i18n);
} else {
$theme = Config::get('theme');
}
@ -32,6 +42,7 @@ class View
// add config
$smarty->assign('config', Config::getPublicConfig());
$smarty->assign('malio_config', MalioConfig::getPublicConfig());
$smarty->assign('I18N', Internationalization::getPublicConfig());
$smarty->assign('user', $user);
$smarty->assign('can_backtoadmin', $can_backtoadmin);

@ -0,0 +1,519 @@
<?php
namespace App\Utils;
use App\Services\Config;
class AppURI
{
public static function getSurgeURI($item, $version)
{
$return = null;
switch ($version) {
case 2:
if ($item['obfs'] == 'v2ray') {
break;
}
if ($item['type'] == 'ss') {
$return = ($item['remark'] . ' = custom, ' . $item['address'] . ', ' . $item['port'] . ', ' . $item['method'] . ', ' . $item['passwd'] . ', https://raw.githubusercontent.com/lhie1/Rules/master/SSEncrypt.module' . URL::getSurgeObfs($item));
}
break;
default:
switch ($item['type']) {
case 'ss':
if ($item['obfs'] == 'v2ray') {
break;
}
$return = ($item['remark'] . ' = ss, ' . $item['address'] . ', ' . $item['port'] . ', encrypt-method=' . $item['method'] . ', password=' . $item['passwd'] . URL::getSurgeObfs($item) . ', udp-relay=true');
break;
case 'vmess':
if (!in_array($item['net'], ['ws', 'tcp'])) {
break;
}
$tls = ($item['tls'] == 'tls'
? ', tls=true'
: '');
$ws = ($item['net'] == 'ws'
? ', ws=true, ws-path=' . $item['path'] . ', ws-headers=host:' . $item['host']
: '');
$return = $item['remark'] . ' = vmess, ' . $item['add'] . ', ' . $item['port'] . ', username = ' . $item['id'] . $ws . $tls;
break;
case 'trojan':
$return = ($item['remark'] . ' = trojan, ' . $item['address'] . ', ' . $item['port'] . ', password=' . $item['passwd']) . ", sni=" . $item['host'];
break;
}
break;
}
return $return;
}
public static function getQuantumultURI($item, $base64_encode = false)
{
$return = null;
switch ($item['type']) {
case 'ss':
if ($item['obfs'] == 'v2ray') {
break;
}
$return = ($item['remark'] . ' = shadowsocks, ' . $item['address'] . ', ' . $item['port'] . ', ' . $item['method'] . ', "' . $item['passwd'] . '", upstream-proxy=false, upstream-proxy-auth=false' . URL::getSurgeObfs($item) . ', group=' . Config::get('appName') . '_ss');
break;
case 'ssr':
$return = ($item['remark'] . ' = shadowsocksr, ' . $item['address'] . ', ' . $item['port'] . ', ' . $item['method'] . ', "' . $item['passwd'] . '", protocol=' . $item['protocol'] . ', protocol_param=' . $item['protocol_param'] . ', obfs=' . $item['obfs'] . ', obfs_param="' . $item['obfs_param'] . '", group=' . Config::get('appName'));
break;
case 'vmess':
if (!in_array($item['net'], ['ws', 'tcp', 'http'])) {
break;
}
$tls = ', over-tls=false, certificate=1';
if ($item['tls'] == 'tls') {
$tls = ', over-tls=true';
if ($item['verify_cert']) {
$tls .=', tls-host=' . $item['host'];
$tls .= ', certificate=1';
} else {
$tls .=', tls-host=' . $item['host'];
$tls .= ', certificate=0';
}
}
$obfs = '';
if (in_array($item['net'], ['ws', 'http'])) {
$obfs = ', obfs=' . $item['net'] . ', obfs-path="' . $item['path'] . '", obfs-header="Host: ' . $item['host'] . '[Rr][Nn]User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 18_0_0 like Mac OS X) AppleWebKit/888.8.88 (KHTML, like Gecko) Mobile/6666666"';
}
$return = ($item['remark'] . ' = vmess, ' . $item['add'] . ', ' . $item['port'] . ', chacha20-ietf-poly1305, "' . $item['id'] . '", group=' . Config::get('appName') . '_VMess' . $tls . $obfs);
if ($base64_encode === true) {
$return = 'vmess://' . base64_encode($return);
}
break;
}
return $return;
}
public static function getQuantumultXURI($item)
{
$return = null;
switch ($item['type']) {
case 'ss':
// ;shadowsocks=example.com:80, method=chacha20, password=pwd, obfs=http, obfs-host=bing.com, obfs-uri=/resource/file, fast-open=false, udp-relay=false, server_check_url=http://www.apple.com/generate_204, tag=ss-01
// ;shadowsocks=example.com:80, method=chacha20, password=pwd, obfs=http, obfs-host=bing.com, obfs-uri=/resource/file, fast-open=false, udp-relay=false, tag=ss-02
// ;shadowsocks=example.com:443, method=chacha20, password=pwd, obfs=tls, obfs-host=bing.com, fast-open=false, udp-relay=false, tag=ss-03
// ;shadowsocks=example.com:80, method=aes-128-gcm, password=pwd, obfs=ws, fast-open=false, udp-relay=false, tag=ss-ws-01
// ;shadowsocks=example.com:80, method=aes-128-gcm, password=pwd, obfs=ws, obfs-uri=/ws, fast-open=false, udp-relay=false, tag=ss-ws-02
// ;shadowsocks=example.com:443, method=aes-128-gcm, password=pwd, obfs=wss, obfs-uri=/ws, fast-open=false, udp-relay=false, tag=ss-ws-tls
$return = ('shadowsocks=' . $item['address'] . ':' . $item['port'] . ', method=' . $item['method'] . ', password=' . $item['passwd']);
switch ($item['obfs']) {
case 'simple_obfs_http':
$return .= ', obfs=http';
$return .= ($item['obfs_param'] != '' ? ', obfs-host=' . $item['obfs_param'] : ', obfs-host=wns.windows.com');
$return .= ', obfs-uri=/';
break;
case 'simple_obfs_tls':
$return .= ', obfs=tls';
$return .= ($item['obfs_param'] != '' ? ', obfs-host=' . $item['obfs_param'] : ', obfs-host=wns.windows.com');
$return .= ', obfs-uri=/';
break;
case 'v2ray';
$return .= ($item['tls'] == 'tls' ? ', obfs=wss' : ', obfs=ws');
$return .= ', obfs-uri=' . $item['path'];
break;
}
$return .= (', tag=' . $item['remark']);
break;
case 'ssr':
// ;shadowsocks=example.com:443, method=chacha20, password=pwd, ssr-protocol=auth_chain_b, ssr-protocol-param=def, obfs=tls1.2_ticket_fastauth, obfs-host=bing.com, tag=ssr
$return = ('shadowsocks=' . $item['address'] . ':' . $item['port'] . ', method=' . $item['method'] . ', password=' . $item['passwd']);
$return .= (', ssr-protocol=' . $item['protocol']);
$return .= (', ssr-protocol-param=' . $item['protocol_param']);
$return .= (', obfs=' . $item['obfs']);
$return .= (', obfs-host="' . $item['obfs_param']);
$return .= (', tag=' . $item['remark']);
break;
case 'vmess':
// ;vmess=example.com:80, method=none, password=23ad6b10-8d1a-40f7-8ad0-e3e35cd32291, fast-open=false, udp-relay=false, tag=vmess-01
// ;vmess=example.com:80, method=aes-128-gcm, password=23ad6b10-8d1a-40f7-8ad0-e3e35cd32291, fast-open=false, udp-relay=false, tag=vmess-02
// ;vmess=example.com:443, method=none, password=23ad6b10-8d1a-40f7-8ad0-e3e35cd32291, obfs=over-tls, fast-open=false, udp-relay=false, tag=vmess-tls
// ;vmess=example.com:80, method=chacha20-poly1305, password=23ad6b10-8d1a-40f7-8ad0-e3e35cd32291, obfs=ws, obfs-uri=/ws, fast-open=false, udp-relay=false, tag=vmess-ws
// ;vmess=example.com:443, method=chacha20-poly1305, password=23ad6b10-8d1a-40f7-8ad0-e3e35cd32291, obfs=wss, obfs-uri=/ws, fast-open=false, udp-relay=false, tag=vmess-ws-tls
if (!in_array($item['net'], ['ws', 'tcp'])) {
break;
}
$return = ('vmess=' . $item['add'] . ':' . $item['port'] . ', method=chacha20-poly1305' . ', password=' . $item['id']);
switch ($item['net']) {
case 'ws':
$return .= ($item['tls'] == 'tls' ? ', obfs=wss' : ', obfs=ws');
$return .= ', obfs-uri=' . $item['path'];
break;
case 'tcp':
$return .= ($item['tls'] == 'tls' ? ', obfs=over-tls' : '');
break;
}
$return .= (', tag=' . $item['remark']);
break;
case 'trojan':
// ;trojan=example.com:443, password=pwd, over-tls=true, tls-verification=true, fast-open=false, udp-relay=false, tag=trojan-tls-01
$return = ('trojan=' . $item['address'] . ':' . $item['port'] . ', password=' . $item['passwd'] . ', tls-host=' . $item['host']);
$return .= ', over-tls=true, tls-verification=true';
$return .= (', tag=' . $item['remark']);
break;
}
return $return;
}
public static function getSurfboardURI($item)
{
$return = null;
switch ($item['type']) {
case 'ss':
if ($item['obfs'] == 'v2ray') {
break;
}
$return = ($item['remark'] . ' = custom, ' . $item['address'] . ', ' . $item['port'] . ', ' . $item['method'] . ', ' . $item['passwd'] . ', https://raw.githubusercontent.com/lhie1/Rules/master/SSEncrypt.module' . URL::getSurgeObfs($item));
break;
}
return $return;
}
public static function getClashURI($item, $ssr_support = false)
{
$return = null;
if ($item['type'] == 'ssr' && $ssr_support === false) {
return $return;
}
switch ($item['type']) {
case 'ss':
$method = ['rc4-md5-6', 'camellia-128-cfb', 'camellia-192-cfb', 'camellia-256-cfb', 'bf-cfb', 'cast5-cfb', 'des-cfb', 'des-ede3-cfb', 'idea-cfb', 'rc2-cfb', 'seed-cfb', 'salsa20', 'chacha20', 'xsalsa20', 'none'];
if (in_array($item['method'], $method)) {
// 不支持的
break;
}
$return = [
'name' => $item['remark'],
'type' => 'ss',
'server' => $item['address'],
'port' => $item['port'],
'cipher' => $item['method'],
'password' => $item['passwd'],
'udp' => true
];
if ($item['obfs'] != 'plain') {
switch ($item['obfs']) {
case 'simple_obfs_http':
$return['plugin'] = 'obfs';
$return['plugin-opts']['mode'] = 'http';
break;
case 'simple_obfs_tls':
$return['plugin'] = 'obfs';
$return['plugin-opts']['mode'] = 'tls';
break;
case 'v2ray':
$return['plugin'] = 'v2ray-plugin';
$return['plugin-opts']['mode'] = 'websocket';
if ($item['tls'] == 'tls') {
$return['plugin-opts']['tls'] = true;
if ($item['verify_cert'] == false) {
$return['plugin-opts']['skip-cert-verify'] = true;
}
}
$return['plugin-opts']['host'] = $item['host'];
$return['plugin-opts']['path'] = $item['path'];
break;
}
if ($item['obfs'] != 'v2ray') {
if ($item['obfs_param'] != '') {
$return['plugin-opts']['host'] = $item['obfs_param'];
} else {
$return['plugin-opts']['host'] = 'windowsupdate.windows.com';
}
}
}
break;
case 'ssr':
if (
in_array($item['method'], ['rc4-md5-6', 'des-ede3-cfb', 'xsalsa20', 'none'])
||
in_array($item['protocol'], array_merge(Config::getSupportParam('allow_none_protocol'), ['verify_deflate']))
||
in_array($item['obfs'], ['tls1.2_ticket_fastauth'])
) {
// 不支持的
break;
}
$return = [
'name' => $item['remark'],
'type' => 'ssr',
'server' => $item['address'],
'port' => $item['port'],
'cipher' => $item['method'],
'password' => $item['passwd'],
'protocol' => $item['protocol'],
'protocolparam' => $item['protocol_param'],
'obfs' => $item['obfs'],
'obfsparam' => $item['obfs_param']
];
break;
case 'vmess':
if (!in_array($item['net'], array('ws', 'tcp'))) {
break;
}
$return = [
'name' => $item['remark'],
'type' => 'vmess',
'server' => $item['add'],
'port' => $item['port'],
'uuid' => $item['id'],
'alterId' => $item['aid'],
'cipher' => 'auto',
'udp' => true
];
if ($item['net'] == 'ws') {
$return['network'] = 'ws';
$return['ws-path'] = $item['path'];
$return['ws-headers']['Host'] = ($item['host'] != '' ? $item['host'] : $item['add']);
}
if ($item['tls'] == 'tls') {
$return['tls'] = true;
if ($item['verify_cert'] == false) {
$return['skip-cert-verify'] = true;
}
}
break;
case 'trojan':
$return = [
'name' => $item['remark'],
'type' => 'trojan',
'server' => $item['address'],
'port' => $item['port'],
'password' => $item['passwd'],
'sni' => $item['host']
];
break;
}
return $return;
}
public static function getShadowrocketURI($item)
{
$return = null;
switch ($item['type']) {
case 'ss':
if (in_array($item['obfs'], Config::getSupportParam('ss_obfs'))) {
$return = (URL::getItemUrl($item, 1));
} else {
if ($item['obfs'] == 'v2ray') {
$v2rayplugin = [
'address' => $item['address'],
'port' => (string) $item['port'],
'path' => $item['path'],
'host' => $item['host'],
'mode' => 'websocket',
];
$v2rayplugin['tls'] = $item['tls'] == 'tls' ? true : false;
if ($v2rayplugin['tls']) {
if ($v2rayplugin['host'] != '' && $v2rayplugin['host'] != 'microsoft.com'){
$v2rayplugin['peer'] = $v2rayplugin['host'];
}else {
$v2rayplugin['peer'] = $v2rayplugin['address'];
}
}else {
$v2rayplugin['peer'] = '';
}
$return = ('ss://' . Tools::base64_url_encode($item['method'] . ':' . $item['passwd'] . '@' . $item['address'] . ':' . $item['port']) . '?v2ray-plugin=' . base64_encode(json_encode($v2rayplugin)) . '#' . rawurlencode($item['remark']));
}
if ($item['obfs'] == 'plain') {
$return = (URL::getItemUrl($item, 2));
}
}
break;
case 'ssr':
$return = (URL::getItemUrl($item, 0));
break;
case 'vmess':
if (!in_array($item['net'], ['tcp', 'ws', 'http', 'h2'])) {
break;
}
$obfs = '';
switch ($item['net']) {
case 'ws':
$obfs .= ($item['host'] != ''
? ('&obfsParam=' . $item['host'] . '&path=' . $item['path'] . '&obfs=websocket')
: ('&obfsParam=' . $item['add'] . '&path=' . $item['path'] . '&obfs=websocket'));
break;
case 'kcp':
$obfs .= 'obfsParam={"header":' . '"' . ($item['headerType'] == '' || $item['headerType'] == 'noop' ? 'none' : $item['headerType']) . '"' . '}&obfs=mkcp';
break;
case 'mkcp':
$obfs .= 'obfsParam={"header":' . '"' . ($item['headerType'] == '' || $item['headerType'] == 'noop' ? 'none' : $item['headerType']) . '"' . '}&obfs=mkcp';
break;
case 'h2':
$obfs .= ($item['host'] != ''
? ('&obfsParam=' . $item['host'] . '&path=' . $item['path'] . '&obfs=h2')
: ('&obfsParam=' . $item['add'] . '&path=' . $item['path'] . '&obfs=h2'));
break;
default:
$obfs .= '&obfs=none';
break;
}
$tls = '';
if ($item['tls'] == 'tls') {
$tls = '&tls=1';
if ($item['verify_cert'] == false){
$tls .= '&allowInsecure=1';
}
$tls .= '&peer=' . $item['host'];
}
$return = ('vmess://' . Tools::base64_url_encode('chacha20-poly1305:' . $item['id'] . '@' . $item['add'] . ':' . $item['port']) . '?remarks=' . rawurlencode($item['remark']) . $obfs . $tls);
break;
case 'trojan':
$return = ('trojan://' . $item['passwd'] . '@' . $item['address'] . ':' . $item['port']);
$return .= ('?peer=' . $item['host'] . '#' . rawurlencode($item['remark']));
break;
}
return $return;
}
public static function getKitsunebiURI($item)
{
$return = null;
switch ($item['type']) {
case 'ss':
if (in_array($item['obfs'], ['v2ray', 'simple_obfs_http', 'simple_obfs_tls'])) {
break;
}
$return = (URL::getItemUrl($item, 2));
break;
case 'vmess':
$network = ($item['net'] == 'tls'
? '&network=tcp'
: ('&network=' . $item['net']));
$protocol = '';
switch ($item['net']) {
case 'kcp':
$protocol .= ('&kcpheader=' . $item['headerType']);
break;
case 'ws':
$protocol .= ('&wspath=' . $item['path'] . '&wsHost=' . $item['host']);
break;
case 'h2':
$protocol .= ('&h2Path=' . $item['path'] . '&h2Host=' . $item['host']);
break;
}
$tls = '';
if ($item['tls'] == 'tls') {
$tls = '&tls=1';
if ($item['verify_cert'] == false) {
$tls .= '&allowInsecure=1';
}
}
$return .= ('vmess://' . base64_encode('auto:' . $item['id'] . '@' . $item['add'] . ':' . $item['port']) . '?remark=' . rawurlencode($item['remark']) . $network . $protocol . '&aid=' . $item['aid'] . $tls);
break;
}
return $return;
}
public static function getSSDURI($item)
{
$return = null;
switch ($item['type']) {
case 'ss':
# 666
$return['remarks'] = $item['remark'];
$return['server'] = $item['address'];
$return['port'] = $item['port'];
$return['encryption'] = $item['method'];
$return['password'] = $item['passwd'];
$plugin_options = '';
if ($item['obfs'] != 'plain') {
switch ($item['obfs']) {
case 'simple_obfs_http':
$return['plugin'] = 'simple-obfs';
$plugin_options .= 'obfs=http;obfs-host=' . $item['obfs_param'];
break;
case 'simple_obfs_tls':
$return['plugin'] = 'simple-obfs';
$plugin_options .= 'obfs=tls;obfs-host=' . $item['obfs_param'];
break;
case 'v2ray':
$return['plugin'] = 'v2ray';
if ($item['net'] == 'ws') {
$plugin_options .= 'mode=ws';
}
if ($item['tls'] == 'tls') {
$plugin_options .= ';security=tls';
} else {
$plugin_options .= ';security=none';
}
$plugin_options .= ';path=' . $item['path'];
if ($item['host'] != '') {
$plugin_options .= ';host=' . $item['host'];
} else {
$plugin_options .= ';host=' . $item['address'];
}
break;
}
}
$return['plugin_options'] = $plugin_options;
$return['ratio'] = $item['ratio'];
break;
}
return $return;
}
public static function getSSJSON($item)
{
$return = null;
switch ($item['type']) {
case 'ss':
# 666
$return['remarks'] = $item['remark'];
$return['server'] = $item['address'];
$return['server_port'] = $item['port'];
$return['method'] = $item['method'];
$return['password'] = $item['passwd'];
if ($item['obfs'] != 'plain') {
$plugin_options = '';
switch ($item['obfs']) {
case 'simple_obfs_http':
$return['plugin'] = 'simple-obfs';
$plugin_options .= 'obfs=http;obfs-host=' . $item['obfs_param'];
break;
case 'simple_obfs_tls':
$return['plugin'] = 'simple-obfs';
$plugin_options .= 'obfs=tls;obfs-host=' . $item['obfs_param'];
break;
case 'v2ray':
$return['plugin'] = 'v2ray';
if ($item['net'] == 'ws') {
$plugin_options .= 'mode=ws';
}
if ($item['tls'] == 'tls') {
$plugin_options .= ';security=tls';
} else {
$plugin_options .= ';security=none';
}
$plugin_options .= ';path=' . $item['path'];
if ($item['host'] != '') {
$plugin_options .= ';host=' . $item['host'];
} else {
$plugin_options .= ';host=' . $item['address'];
}
break;
}
$return['plugin_opts'] = $plugin_options;
}
break;
}
return $return;
}
public static function getTrojanURI(array $item)
{
$return = null;
switch ($item['type']) {
case 'trojan':
$return = ('trojan://' . $item['passwd'] . '@' . $item['address'] . ':' . $item['port']);
$return .= ('?peer=' . $item['host'] . '#' . rawurlencode($item['remark']));
break;
}
return $return;
}
}

@ -1,73 +0,0 @@
<?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)
{
}
}

@ -1,179 +0,0 @@
<?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,38 @@
<?php
namespace App\Utils;
use GeoIp2\Database\Reader;
use GeoIp2\Exception\AddressNotFoundException;
class GeoIP2
{
public function __construct()
{
$this->reader = new Reader(BASE_PATH . '/storage/GeoLite2-City.mmdb');
}
public function getLocation($ip, $lang)
{
try {
$record = $this->reader->city($ip);
} catch (AddressNotFoundException $e) {
if ($lang == 'zh-cn') {
return "未知";
} else {
return "Unknow";
}
}
if ($lang == 'zh-cn') {
$lang = 'zh-CN';
}
if ($lang == 'en') {
return $record->city->name. ', '.$record->country->name;
} else if ($lang == 'zh-CN') {
return $record->country->names[$lang]. ' '.$record->city->names[$lang];
}
}
}

@ -1,420 +0,0 @@
<?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;
}
}

@ -1,18 +0,0 @@
<?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];
}
}

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

@ -1,88 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Utils;
use App\Services\Config;
use Zxing\QrReader;
use ZBarCodeImage;
use ZBarCodeScanner;
class QRcode
{
public static function decode($url)
/**
* 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)
{
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 == '') {
$img = file_get_contents($source);
$qrcode = new QrReader($img, QrReader::SOURCE_TYPE_BLOB);
$text = $qrcode->text();
if ($text == false || $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();
}
}

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

@ -5,32 +5,62 @@ namespace App\Utils;
use App\Services\Config;
use Exception;
use TelegramBot\Api\BotApi;
use Telegram\Bot\Api;
class Telegram
{
/**
* <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϣ
* 发送消息
*/
public static function Send($messageText)
{
if (Config::get('enable_telegram') == 'true') {
$bot = new BotApi(Config::get('telegram_token'));
if (Config::get('enable_telegram') == true) {
// $bot = new BotApi(Config::get('telegram_token'));
// try {
// $bot->sendMessage(Config::get('telegram_chatid'), $messageText);
// } catch (Exception $e) {
// echo $e->getMessage();
// }
$bot = new Api(Config::get('telegram_token'));
$sendMessage = [
'chat_id' => Config::get('telegram_chatid'),
'text' => $messageText,
'parse_mode' => '',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => null
];
try {
$bot->sendMessage(Config::get('telegram_chatid'), $messageText);
$bot->sendMessage($sendMessage);
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
public static function SendMarkdown($messageText)
{
if (Config::get('enable_telegram') == 'true') {
$bot = new BotApi(Config::get('telegram_token'));
if (Config::get('enable_telegram') == true) {
// $bot = new BotApi(Config::get('telegram_token'));
// try {
// $bot->sendMessage(Config::get('telegram_chatid'), $messageText, 'Markdown');
// } catch (Exception $e) {
// echo $e->getMessage();
// }
$bot = new Api(Config::get('telegram_token'));
$sendMessage = [
'chat_id' => Config::get('telegram_chatid'),
'text' => $messageText,
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => null
];
try {
$bot->sendMessage(Config::get('telegram_chatid'), $messageText, 'Markdown');
$bot->sendMessage($sendMessage);
} catch (Exception $e) {
echo $e->getMessage();
}

@ -0,0 +1,136 @@
<?php
namespace App\Utils\Telegram\Callbacks;
use App\Utils\Telegram\TelegramTools;
class Callback
{
public static function CallbackQueryMethod($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 && $_ENV['telegram_group_quiet'] === true) {
// 群组中不回应
return;
}
switch (true) {
case (strpos($Data['CallbackData'], 'user.') === 0):
// 用户相关
UserCallback::handler($bot, $Callback, $Data, $SendUser);
break;
// case (strpos($Data['CallbackData'], 'admin.') === 0):
// // 管理员
// break;
default:
// 回调数据处理
self::CallbackDataHandler($bot, $Callback, $Data, $SendUser);
break;
}
}
public static function getGuestIndexKeyboard()
{
$Keyboard = [
[
[
'text' => '产品介绍',
'callback_data' => 'general.pricing'
],
[
'text' => '服务条款',
'callback_data' => 'general.terms'
]
]
];
$text = '游客您好,以下是 BOT 菜单:' . PHP_EOL . PHP_EOL . '本站用户请前往用户中心进行 Telegram 绑定操作.';
return [
'text' => $text,
'keyboard' => $Keyboard,
];
}
/**
*
* 回调数据处理
*
*/
public static function CallbackDataHandler($bot, $Callback, $Data, $SendUser)
{
$CallbackDataExplode = explode('|', $Data['CallbackData']);
switch ($CallbackDataExplode[0]) {
case 'general.pricing':
// 产品介绍
$sendMessage = [
'text' => $_ENV['telegram_general_pricing'],
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => json_encode(
[
'inline_keyboard' => self::getGuestIndexKeyboard()['keyboard']
]
),
];
break;
case 'general.terms':
// 服务条款
$sendMessage = [
'text' => $_ENV['telegram_general_terms'],
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => json_encode(
[
'inline_keyboard' => self::getGuestIndexKeyboard()['keyboard']
]
),
];
break;
default:
// 主菜单
$temp = self::getGuestIndexKeyboard();
$sendMessage = [
'text' => $temp['text'],
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => json_encode(
[
'inline_keyboard' => $temp['keyboard']
]
),
];
break;
}
$sendMessage = array_merge(
$sendMessage,
[
'chat_id' => $Data['ChatID'],
'message_id' => $Data['MessageID'],
'parse_mode' => 'HTML',
]
);
return ($Data['AllowEditMessage']
? TelegramTools::SendPost('editMessageText', $sendMessage)
: $bot->sendMessage($sendMessage));
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,93 @@
<?php
namespace App\Utils\Telegram\Commands;
use App\Models\User;
use App\Utils\Telegram\TelegramTools;
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 ($_ENV['enable_delete_user_cmd'] === true) {
TelegramTools::DeleteMessage([
'chatid' => $ChatID,
'messageid' => $Message->getMessageId(),
]);
}
if ($_ENV['telegram_group_quiet'] === true) {
// 群组中不回应
return;
}
if ($ChatID != $_ENV['telegram_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) {
// 回送信息
$response = $this->replyWithMessage(
[
'text' => $_ENV['user_not_bind_reply'],
'parse_mode' => 'Markdown',
]
);
} else {
$checkin = $User->checkin();
// 回送信息
$response = $this->replyWithMessage(
[
'text' => $checkin['msg'],
'reply_to_message_id' => $Message->getMessageId(),
'parse_mode' => 'Markdown',
]
);
}
if ($ChatID < 0) {
// 消息删除任务
TelegramTools::DeleteMessage([
'chatid' => $ChatID,
'messageid' => $response->getMessageId(),
]);
}
return $response;
}
}

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

Loading…
Cancel
Save