Compare commits

..

14 Commits

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

2
.gitattributes vendored

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

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

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

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

10
.gitignore vendored

@ -6,7 +6,6 @@
composer.lock
.php_cs.cache
.env
.editorconfig
vendor
php_errors.log
@ -36,11 +35,4 @@ public/.user.ini
resources/views/material/analytics.tpl
.vscode
config/.malio_config.php
malio-noobfs.js
malio-dev.js
malio-release.js
malio.js
resources/email/template
.i18n.php
test/tpl_files.txt

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

@ -16,19 +16,14 @@ 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
@ -41,14 +36,9 @@ Please use the function from PSR-7 like `$request->getParsedBodyParam()`, `getPa
### 代码风格
所有的 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()`等一系列用于获取参数的方法。

@ -0,0 +1,19 @@
根据时间从 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,6 +1,6 @@
MIT License
Copyright (c) 2017 Javi Aguilar
Copyright (c) 2019 Anankke
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

@ -1,121 +0,0 @@
# 欢迎使用 SSPanel V3 魔改再次修改版
**ss-panel-v3-mod**是一款专为 Shadowsocks/ShadowsocksR 设计的管理面板,再次感谢 ss-panel-v3-mod 的制作者,修改后的功能简介:
此仓库由 GeekQu 维护,修改记录 **[在此查看](https://github.com/GeekQu/ss-panel-v3-mod_Uim/blob/dev/GeekQu.md)**。
- **支付系统集成**:集成 支付宝当面付 易付通 码支付 TrimePay 等多种支付系统,使用方法见项目[wiki](https://github.com/Anankke/SSPanel-Uim/wiki/)
- **UI** :修改为 ~~援交~~ 圆角、并自定义了几个图标的显示,节点列表等級 0 可见等級 1 节点但无法看见节点详情,增加了国家图标显示
- **商店**:商品增加同时连接设备数,用户限速属性
- 从肥羊那里**抄**来的:新用户注册现金奖励|高等级节点体验|设备数量限制
- **优化**:css 和 js 等置入本地提升加载速度
- 增加 **v2Ray** 功能,详情请看 wiki: [Indexyz 版](https://github.com/Anankke/SSPanel-Uim/wiki/v2ray---indexyz-%E7%89%88%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B) | [Rico 版](https://github.com/Anankke/SSPanel-Uim/wiki/v2ray---Rico-%E7%89%88%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B)
- 巨量性能优化
- 更多新功能写不下了。(确信)
Telegram 频道 :https://t.me/sspanel_Uim
Telegram ~~可能是个官方~~水群 :https://t.me/SSUnion
记得点小星星!
演示站: [sspanel.host](https://sspanel.host) 账号和密码都是 admin 对接节点的 mukey=NimaQu
**原作者** [galaxychuck](https://github.com/galaxychuck)
[支持开发者请点我](https://github.com/Anankke/SSPanel-Uim#%E5%85%B3%E4%BA%8E%E6%8D%90%E8%B5%A0)
## 搭建教程
GitHub Wiki : https://github.com/Anankke/SSPanel-Uim/wiki/%E5%89%8D%E7%AB%AF%E5%AE%89%E8%A3%85
Wiki 已经启用,欢迎为此面板维护 wiki
#### 鸣谢
##### [Anankke](https://github.com/galaxychuck)
- 面板现**维护者**
##### [galaxychuck](https://github.com/galaxychuck)
- 面板**原作者**
##### [hkserversolution](https://www.hkserversolution.com/cart.php)
- Demo 演示站服务器赞助
##### [dumplin](https://github.com/dumplin233)
- 码支付对接 + 码支付当面付二合一
- 为面板加入 AFF 链接功能
- 商品增加限速和限制 ip 属性
- 多端口订阅
- 解决用户列表加载缓慢历史遗留问题
##### [RinSAMA](https://github.com/mxihan)
- 整理分类 config.php
- 美观性调整
- 客服系统优化
##### [miku](https://github.com/xcxnig)
- 美观和性能优化
##### [Tony Zou](https://github.com/ZJY2003)
- 为公告增加群发邮件功能
- 节点负载情况显示&用户账户过期在首页弹窗提醒
- 增加返利列表
[**Indexyz**](https://github.com/Indexyz)
- 为面板增加 v2Ray 功能
[**NeverBehave**](https://github.com/NeverBehave)
- 添加 Telegram OAuth
[**CGDF**](https://github.com/CGDF-GitHub)
- xcat一键update
- 适配SSD
- 用户列表分页加载
[**CHEN**](https://github.com/ChenSee)
- 免签约支付宝与微信,自带监听,不需第三方软件,直接到个人账户
[**laurieryayoi**](https://github.com/laurieryayoi)
- 重做美化UI(~~援交~~圆角化)
- 重写节点列表,支持分级显示所有级别节点
#### 还有所有被引用过代码的同学,以及所有提交过 pr/issue 的同学。
#### 关于捐赠
您对我们的帮助将是支持我们做下去的动力,只需您在购买部分产品或向他人推荐产品时从我们的返利链接购买,这就是对我们很大的支持了。~~没有钱了,肯定要做啊,不做没有钱用啊,打工是不可能打工的,这辈子不可能打工的~~
##### Anankke
- [Anankke 很可爱请给 Anankke 钱](https://t.me/anankke/5)
##### dumplin
- [码支付-微信收款功能开通](https://codepay.fateqq.com/i/39756)
##### galaxychuck
- [黛米付-支付接入](https://www.daimiyun.cn/register.php?aff=624)
- [冲上云霄云主机](http://console.soar-clouds.com/aff.php?aff=94)
- [Vultr](https://www.vultr.com/?ref=7205737)
[laurieryayoi 的前端课程报名](https://t.me/kinokonominoco)
## 免责声明
本程序由 MIT License 授权。**不提供任何担保**。使用本程序即表明,您知情并同意:程序开发者不对此程序导致的任何服务中断、数据损失或任何少见未列出的事故负责。

@ -1,187 +1,174 @@
# 不能删改页面底部的 Powered by SSPANEL,不能删改staff页面的任何信息。
## 删除Powered by SSPANEL可能会导致你的网站被D,现在 Theme by editXY 可以随意去掉
<img src="https://cdn.jsdelivr.net/npm/skx@0.1.3/img/uim-logo-round.png" alt="logo" width="130" height="130" align="left" />
本主题包含了SSPANEL的完整代码,需要删除原来的面板,然后全新安装(数据库通用),操作前请备份面板
<h1>SSPanel UIM</h1>
## 安装步骤
> Across the Great Wall we can reach every corner in the world
<br/>
[![License](https://img.shields.io/github/license/Anankke/SSPanel-Uim?style=flat-square)](https://github.com/Anankke/SSPanel-Uim/blob/dev/LICENSE)
[![Travis Build Status](https://img.shields.io/travis/Anankke/SSPanel-UIM/master.svg?style=flat-square)](https://travis-ci.org/Anankke/SSPanel-Uim)
![GitHub repo size](https://img.shields.io/github/repo-size/anankke/sspanel-uim?style=flat-square&color=328657)
[![Telegram Channel](https://img.shields.io/badge/news-t.me%2Fsspanel_uim-0d86d7?style=flat-square)](https://t.me/sspanel_uim)
[![Telegram Chat](https://img.shields.io/badge/chat-t.me%2Fssunion-0d86d7?style=flat-square)](https://t.me/ssunion)
# 安装宝塔面板
[演示站点](https://sspanel.host) | [使用文档](https://wiki.sspanel.host) | [更新日志](https://github.com/Anankke/SSPanel-Uim/releases) | [Telegram 频道](https://t.me/sspanel_uim) | [Telegram 水群](https://t.me/ssunion)
使用SSH登录你的VPS,根据你VPS的系统选择下面的安装命令
## 简介
宝塔面板 Centos 一键安装脚本👇
SSPanel UIM 是一款专为 Shadowsocks / ShadowsocksR / V2Ray 设计的多用户管理面板,基于 ss-panel-v3-mod 开发。
```
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` 回车安装
## AD
执行完毕后,会显示类似下面的宝塔面板的登录信息,请保存好此信息
**特别优惠 Malio SSPANEL 主题 + Rico V2Ray 后端,原价 1000 CNY,现在只需 899 CNY,👉[查看详情](https://malio.fxxkmy.life/)**
```
Bt-Panel: http://xxx.xxx.xx.xx:8888/xxxxxxx
username: xxxxxxx
password: xxxxxxxx
```
# 安装LNMP
登录宝塔面板后,宝塔面板会提示你安装 PHP, MySQL, Nginx 等环境。
## 特性
推荐使用 PHP 7.1、MySQL 5.6、Nginx任意版本。
- 集成超过 8 种支付系统
- 重构面板首页、节点列表、商品列表;新增 SPA(Single Page Apps)版 UI
- 商品增加同时连接设备数,用户限速属性
- 新用户注册现金奖励、用户常规端口切换与指定
- 公共库文件加载使用 jsDelivr
- 支持 V2Ray
- 巨量性能优化
- 更多新功能写不下了
需要一段时间才能安装完成,请等待完成。
## 安装
# 配置PHP
SSPanel UIM 的需要以下程序才能正常的安装和运行:
打开 `宝塔面版 > 软件商店 > 你安装的PHP > 设置`,在禁用函数一栏删除 `system`、`proc_open`、`proc_get_status`、`putenv`、`pcntl_signal`。
- Git
- MySQL
- PHP 7.2+
- Composer
# 安装Malio主题
SSPanel UIM 支持安装在 LNMP、宝塔面板、Plesk 面板、oneinstack 等集成环境中。安装教程请参阅 [文档](https://wiki.sspanel.host)。
打开 `宝塔面版 > 网站 > 添加站点`,输入你的域名,点击提交
## 演示
------
在SSH里执行下面命令👇👇👇
下载SSPANEL+Malio的代码。如果你的这个网站文件夹包含原版的SSPANEL代码,请删除原版SSPANEL代码或者换个目录
[演示站](https://sspanel.host) 每天更新 `dev` 分支最新源码。
```
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
账号:admin
密码:admin
mukey ShirakamiFubuki
```
然后Git会要求你输入Gitlab的账号密码
使用composer安装依赖
## 文档
```
wget https://getcomposer.org/installer -O composer.phar
php composer.phar
php composer.phar install
```
> 我们安装,我们更新,我们开发
用composer安装依赖时如果内存不够的话,可以使用 `宝塔面版 > 首页 > Linux工具箱 > Swap/虚拟内存` 增加虚拟内存
[SSPanel UIM 的文档](https://wiki.sspanel.host),在这里你可以找到大部分问题的解答。
复制配置文件
## 贡献
```
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
```
[提出新想法 & 提交 Bug](https://github.com/Anankke/SSPanel-Uim/issues/new) | [改善文档 & 投稿](https://github.com/sspanel-uim/Wiki) | [Fork & Pull Request](https://github.com/Anankke/SSPanel-Uim/fork)
------
SSPanel UIM 欢迎各种贡献,包括但不限于改进,新功能,文档和代码改进,问题和错误报告。
打开 `宝塔面版 > 网站 > 你的网站`
## 协议
在 `网站目录` 里取消勾选 `防跨站攻击`,运行目录里面选择 `/public`,点击保存。
SSPanel UIM 使用 MIT License 开源、不提供任何担保。使用 SSPanel UIM 即表明,您知情并同意:
在 `伪静态` 中填入下面内容,然后保存
- 您在使用 SSPanel UIM 时,必须保留 Staff 页面(该页面包含了 MIT License)和页脚的 Staff 入口
- SSPanel UIM 不会对您的任何损失负责,包括但不限于服务中断、Kernel Panic、机器无法开机或正常使用、数据丢失或硬件损坏、原子弹爆炸、第三次世界大战、SCP 基金会无法阻止 SCP-3125 引发的全球 MK 级现实重构等
```
location / {
try_files $uri /index.php$is_args$args;
}
```
------
## 鸣谢
在SSH里的网站目录下执行,给网站文件755权限
### [HKServerSolution](https://www.hkserversolution.com/cart.php)
```
cd ../
chmod -R 755 你的文件夹名/
chown -R www:www 你的文件夹名/
```
Demo 演示站服务器赞助。
# 数据库操作
### [贡献者](https://github.com/Anankke/SSPanel-Uim/graphs/contributors)
打开 `宝塔面版 > 数据库`,选择添加数据库,数据库名字和用户名任意写,密码建议使用随机生成的密码,点击提交即可添加数据库
SSPanel UIM 离不开所有 [贡献代码](https://github.com/Anankke/SSPanel-Uim/graphs/contributors) 和提交 Issue 的人。
点击数据库名字旁边的 `导入 > 本地上传`,即可上传并导入sql文件到数据库
<details>
<summary>查看贡献者</summary>
如果你是全新安装面板,请上传并导入网站目录下的 `/sql/glzjin_all.sql`、`/sql/malio_all.sql`
#### [Anankke](https://github.com/Anankke)
如果你是从其他主题迁移到Malio主题,请上传并导入网站目录下的 `/sql/malio_all.sql`、`/sql/user_subscribe_log.sql`、`/sql/detect_ban_log.sql`
- 面板现 **维护者**
如果没有导入 `/sql/malio_all.sql` 的话会导致无法注册新用户
#### [galaxychuck](https://github.com/galaxychuck)
将数据库user表里的全部用户的theme列改为malio,使用phpmyadmin执行这条sql语句👉 `UPDATE user SET theme='malio'`
- 面板 **原作者**
# 编辑 config.php
##### [dumplin](https://github.com/dumplin233)
将你的数据库名字,用户名和密码填入.config.php里,类似下面这样
- 码支付对接 + 码支付当面付二合一
- 为面板加入 AFF 链接功能
- 商品增加限速和限制 ip 属性
- 多端口订阅
- 解决用户列表加载缓慢历史遗留问题
```
$_ENV['db_database'] = 'sspanel'; //数据库名
$_ENV['db_username'] = 'sspanel'; //数据库用户名
$_ENV['db_password'] = 'sspanel_password'; //用户名对应的密码
```
##### [RinSAMA](https://github.com/mxihan)
# 其他操作
- 整理分类 config.php
- 美观性调整
- 客服系统优化
在SSH里的网站目录下执行 `php xcat createAdmin`,即可创建管理员用户。(如果你已经有了管理员用户就不用创建了)
##### [miku](https://github.com/xcxnig)
在SSH里的网站目录下执行 `php xcat initQQWry `,即可下载IP数据库(必须要执行这个)
- 美观和性能优化
下载通知频道里的 `GeoLite2-City.mmdb` 文件放入网站目录下的 `/storage/` 目录下
##### [Tony Zou](https://github.com/ZJY2003)
为Crisp和Chatra的跨设备恢复会话功能生成UUID,在SSH里网站目录下执行👉 `php xcat GenerateUUIDforAllUsers`
- 为公告增加群发邮件功能
- 节点负载情况显示&用户账户过期在首页弹窗提醒
- 增加返利列表
# 配置定时任务
[**Indexyz**](https://github.com/Indexyz)
执行 `crontab -e` 命令,添加以下:
- 为面板增加 v2Ray 功能
```
0 0 * * * php -n /www/wwwroot/你的文件夹名/xcat dailyjob
*/1 * * * * php /www/wwwroot/你的文件夹名/xcat checkjob
*/1 * * * * php /www/wwwroot/你的文件夹名/xcat syncnode
```
[**NeverBehave**](https://github.com/NeverBehave)
# 客户端下载
- 添加 Telegram OAuth
客户端的安装包需要自行下载到 `/public/client-download/` 目录,安装包名字参考同目录下的 apps.txt 文件
[**CGDF**](https://github.com/CGDF-GitHub)
另外在此目录下还提供了 [download.sh](https://github.com/sspanel-uim/ssr-download-updater) 脚本,可自动下载部分客户端。
- xcat 一键 update
- 适配 SSD
- 用户列表分页加载
# 请仔细阅读 .malio_config.php 和 .config.php 的全部注释,进一步了解SSPANEL
[**CHEN**](https://github.com/ChenSee)
- 免签约支付宝与微信,自带监听,不需第三方软件,直接到个人账户
[**laurieryayoi**](https://github.com/laurieryayoi)
- 重做美化UI(~~援交~~圆角化)
- 新版 Vue(SPA) 版界面
- 重写节点列表,支持分级显示所有级别节点
[**Sukka**](https://github.com/SukkaW)
- Travis CI 持续集成
- 单元测试
- 全站 JavaScript 重写
- 新版 Wiki 的搭建和维护
## 贡献
</details>
[提出新想法 & 提交 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模式下没办法购买。
#### Anankke
在.config.php里设置新用户注册等级为-1,如果不设置为-1的话,就没有新手引导教程,同时需要在.config.php里设置用户等级过期时间,建议设置为超过一个月的时间(720小时)。
- [Anankke 很可爱请给 Anankke 钱](https://t.me/anankke/5)
安装完成后如果旧用户无法登录的话,检查下 .config.php 里面的 salt 和 pwdMethod 的值是否跟原来的 .config.php 一致。
#### dumplin
端口偏移的说明查看 [端口偏移的食用方法](https://678765.xyz/2019/2.html),根据群友说支持普通端口和单端口,格式跟uim原版的偏移不一样
- [码支付-微信收款功能开通](https://codepay.fateqq.com/i/39756)
如果需要配置Stripe支付接口的话,请看本仓库的wiki
#### galaxychuck
需要去.config.php打开订阅记录的开关才会记录订阅
- [hkserversolution-推荐UIM面板服务器放置](https://www.hkserversolution.com/aff.php?aff=60)
https://t.me/woaizyg)
#### laurieryayoi
## CREDIT
基于 [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) 修改
[laurieryayoi 的前端课程报名](https://t.me/kinokonominoco)

@ -52,7 +52,7 @@ class DailyMail
$sts = new Analytics();
if (Config::getdb('Telegram.enable.Diary') !== '0') {
if (Config::get('sendDiary_Telegram') == 'true') {
Telegram::Send(
str_replace(
array(
@ -63,7 +63,7 @@ class DailyMail
$sts->getTodayCheckinUser(),
Tools::flowAutoShow($lastday_total)
),
Config::getdb('Telegram.msg.Diary')
Config::get('sendDiary_Msg')
)
);
}

@ -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,7 +19,6 @@ 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;
@ -30,13 +29,11 @@ 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
{
@ -78,7 +75,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',
@ -104,7 +101,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('备份完毕了喵~今天又是安全祥和的一天呢。');
}
}
@ -156,8 +153,6 @@ 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();
@ -166,8 +161,8 @@ class Job
EmailVerify::where('expire_in', '<', time() - 86400 * 3)->delete();
system('rm ' . BASE_PATH . '/storage/*.png', $ret);
if (Config::getdb('Telegram.enable.DailyJob') !== '0') {
Telegram::Send(Config::getdb('Telegram.msg.DailyJob'));
if (Config::get('sendDailyJob_Telegram') == 'true') {
Telegram::Send(Config::get('sendDailyJob_Msg'));
}
//auto reset
@ -451,12 +446,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(
@ -486,18 +481,71 @@ class Job
Mail::send($to, $subject, 'news/warn.tpl', [
'user' => $user,
'text' => $text
], [
]);
} catch (Exception $e) {
echo $e->getMessage();
}
$notice_text = str_replace(
'%node_name%',
$node->name,
Config::getdb('Telegram.msg.NodeOffline')
);
if (Config::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 = str_replace(
array('%node_name%', '%Temp_node_name%'),
array($node->name, $Temp_node->name),
Config::get('sendNodeOffline_Update_Msg')
);
}
}
} else {
$notice_text = str_replace(
'%node_name%',
$node->name,
Config::get('sendNodeOffline_Msg')
);
}
}
if (Config::getdb('Telegram.enable.NodeOffline') !== '0') {
if (Config::get('sendNodeOffline_Telegram') == 'true') {
Telegram::Send($notice_text);
}
@ -509,7 +557,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(
@ -539,18 +587,61 @@ class Job
Mail::send($to, $subject, 'news/warn.tpl', [
'user' => $user,
'text' => $text
], [
]);
} catch (Exception $e) {
echo $e->getMessage();
}
$notice_text = str_replace(
'%node_name%',
$node->name,
Config::getdb('Telegram.msg.NodeOnline')
);
if (Config::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 = str_replace(
'%node_name%',
$node->name,
Config::get('sendNodeOnline_Update_Msg')
);
} else {
$notice_text = str_replace(
'%node_name%',
$node->name,
Config::get('sendNodeOnline_Msg')
);
}
}
if (Config::getdb('Telegram.enable.NodeOnline') !== '0') {
if (Config::get('sendNodeOnline_Telegram') == 'true') {
Telegram::Send($notice_text);
}
@ -561,7 +652,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) {
@ -611,11 +702,6 @@ 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
@ -660,7 +746,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';
@ -702,9 +788,7 @@ class Job
}
if (Config::get('account_expire_delete_days') >= 0 &&
strtotime($user->expire_in) + Config::get('account_expire_delete_days') * 86400 < time() &&
$user->money <= Config::get('auto_clean_min_money')
strtotime($user->expire_in) + Config::get('account_expire_delete_days') * 86400 < time()
) {
$subject = Config::get('appName') . '-您的用户账户已经被删除了';
$to = $user->email;
@ -798,12 +882,10 @@ class Job
}
// 审计封禁解封
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;
}
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;
}
}
@ -824,21 +906,6 @@ 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()
@ -895,13 +962,58 @@ class Job
} catch (Exception $e) {
echo $e->getMessage();
}
$notice_text = str_replace(
'%node_name%',
$node->name,
Config::getdb('Telegram.msg.NodeGFW')
);
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 = str_replace(
array('%node_name%', '%Temp_node_name%'),
array($node->name, $Temp_node->name),
Config::get('sendNodeGFW_Update_Msg')
);
}
}
} else {
$notice_text = str_replace(
'%node_name%',
$node->name,
Config::get('sendNodeGFW_Msg')
);
}
}
if (Config::getdb('Telegram.enable.NodeGFW') !== '0') {
if (Config::get('sendNodeGFW_Telegram') == 'true') {
Telegram::Send($notice_text);
}
$file_node = fopen(BASE_PATH . '/storage/' . $node->id . '.gfw', 'wb+');
@ -926,13 +1038,50 @@ class Job
} catch (Exception $e) {
echo $e->getMessage();
}
$notice_text = str_replace(
'%node_name%',
$node->name,
Config::getdb('Telegram.msg.NodeGFW_recover')
);
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 = str_replace(
'%node_name%',
$node->name,
Config::get('sendNodeGFW_recover_Update_Msg')
);
} else {
$notice_text = str_replace(
'%node_name%',
$node->name,
Config::get('sendNodeGFW_recover_Msg')
);
}
}
if (Config::getdb('Telegram.enable.NodeGFW_recover') !== '0') {
if (Config::get('sendNodeGFW_recover_Telegram') == 'true') {
Telegram::Send($notice_text);
}
unlink(BASE_PATH . '/storage/' . $node->id . '.gfw');
@ -945,88 +1094,4 @@ 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 '审计封禁检查结束.';
}
}

@ -1,25 +0,0 @@
<?php
namespace App\Command;
use App\Models\User;
use App\Services\Config;
use Ramsey\Uuid\Uuid;
class Malio
{
public static function GenerateUUIDforAllUsers()
{
$users = User::all();
foreach ($users as $user) {
if ($user->uuid == null) {
$user->uuid = Uuid::uuid3(Uuid::NAMESPACE_DNS, ($user->passwd) . Config::get('key') . $user->id)->toString();
if ($user->save()) {
echo ($user->id . " 生成UUID成功 " . $user->uuid . PHP_EOL);
} else {
echo ($user->id . " 失败 " . $user->uuid . PHP_EOL);
};
}
}
}
}

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

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

@ -3,7 +3,6 @@
namespace App\Command;
use App\Services\Config;
use App\Services\DefaultConfig;
class Update
{
@ -12,16 +11,12 @@ class Update
global $_ENV;
$copy_result = copy(BASE_PATH . '/config/.config.php', BASE_PATH . '/config/.config.php.bak');
if ($copy_result == true) {
echo ('备份成功' . PHP_EOL);
echo('备份成功' . PHP_EOL);
} else {
echo ('备份失败,迁移终止' . PHP_EOL);
echo('备份失败,迁移终止' . PHP_EOL);
return false;
}
echo(PHP_EOL);
// 检查并创建新增的配置项
echo DefaultConfig::detectConfigs();
echo(PHP_EOL);
echo('开始升级客户端...' . PHP_EOL);
@ -32,7 +27,7 @@ class Update
$xcat->initQQWry();
echo('升级 QQWry结束' . PHP_EOL);
echo (PHP_EOL);
echo(PHP_EOL);
$config_old = file_get_contents(BASE_PATH . '/config/.config.php');
$config_new = file_get_contents(BASE_PATH . '/config/.config.example.php');
@ -52,7 +47,7 @@ class Update
$matches_new = array();
preg_match($regex, $config_new, $matches_new);
if (isset($matches_new[0]) == false) {
echo ('未找到配置项:' . $key . ' 未能在新config文件中找到,可能已被更名或废弃' . PHP_EOL);
echo('未找到配置项:' . $key . ' 未能在新config文件中找到,可能已被更名或废弃' . PHP_EOL);
continue;
}
@ -62,7 +57,7 @@ class Update
$config_new = str_replace($matches_new[0], $matches_old[0], $config_new);
$migrated[] = '_ENV[\'' . $key . '\']';
}
echo (PHP_EOL);
echo(PHP_EOL);
//检查新增了哪些config
$regex_new = '/_ENV\[\'.*?\'\]/s';
@ -95,9 +90,9 @@ class Update
$difference = substr($difference, 15);
$difference = substr($difference, 0, -2);
echo ('新增配置项:' . $difference . ':' . $comment . PHP_EOL);
echo('新增配置项:' . $difference . ':' . $comment . PHP_EOL);
}
echo ('新增配置项通常带有默认值,因此通常即使不作任何改动网站也可以正常运行' . PHP_EOL);
echo('新增配置项通常带有默认值,因此通常即使不作任何改动网站也可以正常运行' . PHP_EOL);
//输出notice
$regex_notice = '/_ENV\[\'config_migrate_notice\'\].*?(?=\';)/s';
@ -118,128 +113,29 @@ class Update
echo($notice_new);
}
} else {
echo ($notice_new);
echo($notice_new);
}
echo (PHP_EOL);
echo(PHP_EOL);
file_put_contents(BASE_PATH . '/config/.config.php', $config_new);
echo (PHP_EOL . '迁移完成' . PHP_EOL);
echo(PHP_EOL . '迁移完成' . PHP_EOL);
echo (PHP_EOL);
self::update_malio_config($xcat);
echo(PHP_EOL);
echo ('开始升级composer依赖...' . PHP_EOL);
echo('开始升级composer依赖...' . PHP_EOL);
system('php ' . BASE_PATH . '/composer.phar selfupdate');
system('php ' . BASE_PATH . '/composer.phar install -d ' . BASE_PATH);
echo ('升级composer依赖结束,请自行根据上方输出确认是否升级成功' . PHP_EOL);
echo('升级composer依赖结束,请自行根据上方输出确认是否升级成功' . PHP_EOL);
system('rm -rf ' . BASE_PATH . '/storage/framework/smarty/compile/*');
system('chown -R www:www ' . BASE_PATH . '/storage');
}
public static function old_to_new($version_old)
{
}
public static function update_malio_config($xcat)
{
echo ('----------开始.malio_config.php迁移工作-----------');
global $Malio_Config;
$copy_result = copy(BASE_PATH . '/config/.malio_config.php', BASE_PATH . '/config/.malio_config.php.bak');
if ($copy_result == true) {
echo ('备份成功' . PHP_EOL);
} else {
echo ('备份失败,迁移终止' . PHP_EOL);
return false;
}
$config_old = file_get_contents(BASE_PATH . '/config/.malio_config.php');
$config_new = file_get_contents(BASE_PATH . '/config/.malio_config.example.php');
$migrated = array();
foreach ($Malio_Config as $key => $value_reserve) {
if ($key == 'config_migrate_notice' || $key == 'version') {
continue;
}
$regex = '/Malio_Config\[\'' . $key . '\'\].*?;/s';
$matches_new = array();
preg_match($regex, $config_new, $matches_new);
if (isset($matches_new[0]) == false) {
echo ('未找到配置项:' . $key . ' 未能在新malio_config文件中找到,可能已被更名或废弃' . PHP_EOL);
continue;
}
$matches_old = array();
preg_match($regex, $config_old, $matches_old);
$config_new = str_replace($matches_new[0], $matches_old[0], $config_new);
$migrated[] = 'Malio_Config[\'' . $key . '\']';
}
echo (PHP_EOL);
//检查新增了哪些config
$regex_new = '/Malio_Config\[\'.*?\'\]/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 == 'Malio_Config[\'config_migrate_notice\']' ||
$difference == 'Malio_Config[\'version\']'
) {
continue;
}
//匹配注释
$regex_comment = '/' . $difference . '.*?;.*?(?=\n)/s';
$regex_comment = str_replace(array('[', ']'), array('\[', '\]'), $regex_comment);
$matches_comment = array();
preg_match($regex_comment, $config_new, $matches_comment);
$comment = '';
if (isset($matches_comment[0])) {
$comment = $matches_comment[0];
$comment = substr(
$comment,
strpos(
$comment,
'//',
strpos($comment, ';') //查找';'之后的第一个'//',然后substr其后面的comment
) + 2
);
}
//裁去首尾
$difference = substr($difference, 15);
$difference = substr($difference, 0, -2);
echo ('新增配置项:' . $difference . ':' . $comment . PHP_EOL);
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');
}
echo ('新增配置项通常带有默认值,因此通常即使不作任何改动网站也可以正常运行' . PHP_EOL);
//输出notice
$regex_notice = '/System_Config\[\'config_migrate_notice\'\].*?(?=\';)/s';
$matches_notice = array();
preg_match($regex_notice, $config_new, $matches_notice);
$notice_new = $matches_notice[0];
$notice_new = substr(
$notice_new,
strpos(
$notice_new,
'\'',
strpos($notice_new, '=') //查找'='之后的第一个'\'',然后substr其后面的notice
) + 1
);
echo ('以下是迁移附注:');
if (isset($Malio_Config['config_migrate_notice'])) {
if ($Malio_Config['config_migrate_notice'] != $notice_new) {
echo ($notice_new);
}
} else {
echo ($notice_new);
}
echo (PHP_EOL);
file_put_contents(BASE_PATH . '/config/.malio_config.php', $config_new);
echo (PHP_EOL . '.malio_config.php迁移完成' . PHP_EOL);
echo (PHP_EOL);
}
}

@ -12,8 +12,9 @@ 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;
@ -32,10 +33,6 @@ class XCat
public function boot()
{
switch ($this->argv[1]) {
case ('detectConfigs'):
return $this->detectConfigs();
case ('portAutoChange'):
return PortAutoChange::index();
case ('alipay'):
return (new ChenPay())->AliPayListen();
case ('wxpay'):
@ -44,6 +41,8 @@ class XCat
return $this->createAdmin();
case ('resetTraffic'):
return $this->resetTraffic();
case ('setDiscord'):
return Discord::set();
case ('setTelegram'):
return $this->setTelegram();
case ('initQQWry'):
@ -98,39 +97,36 @@ 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();
case ('iptest'):
return $this->iptest();
case ('GenerateUUIDforAllUsers'):
return Malio::GenerateUUIDforAllUsers();
case ('delSubCache'):
return $this->delSubCache();
default:
default:
return $this->defaultAction();
}
}
public function defaultAction()
{
echo (PHP_EOL . '用法: php xcat [选项]' . PHP_EOL);
echo ('常用选项:' . PHP_EOL);
echo (' createAdmin - 创建管理员帐号' . PHP_EOL);
echo (' setTelegram - 设置 Telegram 机器人' . PHP_EOL);
echo (' cleanRelayRule - 清除所有中转规则' . PHP_EOL);
echo (' resetPort - 重置单个用户端口' . PHP_EOL);
echo (' resetAllPort - 重置所有用户端口' . PHP_EOL);
echo (' initdownload - 下载 SSR 程序至服务器' . PHP_EOL);
echo (' initdocuments - 下载用户使用文档至服务器' . PHP_EOL);
echo (' initQQWry - 下载 IP 解析库' . PHP_EOL);
echo (' resetTraffic - 重置所有用户流量' . PHP_EOL);
echo (' update - 更新并迁移配置' . PHP_EOL);
echo(PHP_EOL . '用法: php xcat [选项]' . PHP_EOL);
echo('常用选项:' . PHP_EOL);
echo(' createAdmin - 创建管理员帐号' . PHP_EOL);
echo(' setDiscord - 设置 Discord 机器人' . PHP_EOL);
echo(' setTelegram - 设置 Telegram 机器人' . PHP_EOL);
echo(' cleanRelayRule - 清除所有中转规则' . PHP_EOL);
echo(' resetPort - 重置单个用户端口' . PHP_EOL);
echo(' resetAllPort - 重置所有用户端口' . PHP_EOL);
echo(' initdownload - 下载 SSR 程序至服务器' . PHP_EOL);
echo(' initdocuments - 下载用户使用文档至服务器' . PHP_EOL);
echo(' initQQWry - 下载 IP 解析库' . PHP_EOL);
echo(' resetTraffic - 重置所有用户流量' . PHP_EOL);
echo(' update - 更新并迁移配置' . PHP_EOL);
}
public function resetPort()
@ -167,9 +163,9 @@ class XCat
{
$rules = Relay::all();
foreach ($rules as $rule) {
echo ($rule->id . "\n");
echo($rule->id . "\n");
if ($rule->source_node_id == 0) {
echo ($rule->id . "被删除!\n");
echo($rule->id . "被删除!\n");
$rule->delete();
continue;
}
@ -177,7 +173,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();
}
}
@ -210,7 +206,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';
}
@ -274,42 +270,33 @@ class XCat
public function setTelegram()
{
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);
}
$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);
}
}
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 反馈!');
}
}
@ -348,12 +335,11 @@ 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()
@ -369,8 +355,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";
}
}
}
@ -383,22 +369,4 @@ class XCat
echo Hash::cookieHash($user->pass, $expire_in) . ' ' . $expire_in;
}
}
public function detectConfigs()
{
echo DefaultConfig::detectConfigs();
}
public function delSubCache()
{
if (Config::get('enable_sub_cache') === true) {
if (Tools::delSubCache() === true) {
echo (PHP_EOL . '订阅缓存清理成功.' . PHP_EOL);
} else {
echo (PHP_EOL . '订阅缓存清理失败.' . PHP_EOL);
}
} else {
echo (PHP_EOL . '订阅缓存未开启.' . PHP_EOL);
}
}
}

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

@ -19,7 +19,7 @@ class NodeController extends AdminController
{
$table_config['total_column'] = array('op' => '操作', 'id' => 'ID', 'name' => '节点名称',
'type' => '显示与隐藏', 'sort' => '类型',
'server' => '节点地址', 'outaddress' => '出口地址', 'node_ip' => '节点IP',
'server' => '节点地址', 'node_ip' => '节点IP',
'info' => '节点信息',
'status' => '状态', 'traffic_rate' => '流量比率', 'node_group' => '节点群组',
'node_class' => '节点等级', 'node_speedlimit' => '节点限速/Mbps',
@ -93,22 +93,20 @@ 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);
}
if (Config::getdb('Telegram.enable.AddNode') !== '0') {
if (Config::get('sendAddNode_Telegram') == 'true') {
Telegram::Send(
str_replace(
'%node_name%',
$request->getParam('name'),
Config::getdb('Telegram.msg.AddNode')
Config::get('sendAddNode_Msg')
)
);
}
Tools::delSubCache();
$rs['ret'] = 1;
$rs['msg'] = '节点添加成功';
return $response->getBody()->write(json_encode($rs));
@ -196,18 +194,16 @@ class NodeController extends AdminController
$node->save();
if (Config::getdb('Telegram.enable.UpdateNode') !== '0') {
if (Config::get('sendUpdateNode_Telegram') == 'true') {
Telegram::Send(
str_replace(
'%node_name%',
$request->getParam('name'),
Config::getdb('Telegram.msg.UpdateNode')
Config::get('sendUpdateNode_Msg')
)
);
}
Tools::delSubCache();
$rs['ret'] = 1;
$rs['msg'] = '修改成功';
return $response->getBody()->write(json_encode($rs));
@ -228,18 +224,16 @@ class NodeController extends AdminController
return $response->getBody()->write(json_encode($rs));
}
if (Config::getdb('Telegram.enable.DeleteNode') !== '0') {
if (Config::get('sendDeleteNode_Telegram') == 'true') {
Telegram::Send(
str_replace(
'%node_name%',
$node->name,
Config::getdb('Telegram.msg.DeleteNode')
Config::get('sendDeleteNode_Msg')
)
);
}
Tools::delSubCache();
$rs['ret'] = 1;
$rs['msg'] = '删除成功';
return $response->getBody()->write(json_encode($rs));
@ -252,7 +246,7 @@ class NodeController extends AdminController
$total_column = array('op' => '操作', 'id' => 'ID', 'name' => '节点名称',
'type' => '显示与隐藏', 'sort' => '类型',
'server' => '节点地址', 'outaddress' => '出口地址', 'node_ip' => '节点IP',
'server' => '节点地址', 'node_ip' => '节点IP',
'info' => '节点信息',
'status' => '状态', 'traffic_rate' => '流量比率', 'node_group' => '节点群组',
'node_class' => '节点等级', 'node_speedlimit' => '节点限速/Mbps',
@ -266,10 +260,6 @@ 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;
}
@ -280,10 +270,6 @@ 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']);
});
@ -322,9 +308,6 @@ class NodeController extends AdminController
case 13:
$sort = 'Shadowsocks - V2Ray-Plugin';
break;
case 14:
$sort = 'Trojan';
break;
default:
$sort = '系统保留';
}

@ -124,8 +124,6 @@ class RelayController extends AdminController
return $response->getBody()->write(json_encode($rs));
}
Tools::delSubCache();
$rs['ret'] = 1;
$rs['msg'] = '添加成功';
return $response->getBody()->write(json_encode($rs));
@ -236,8 +234,6 @@ class RelayController extends AdminController
return $response->getBody()->write(json_encode($rs));
}
Tools::delSubCache();
$rs['ret'] = 1;
$rs['msg'] = '修改成功';
return $response->getBody()->write(json_encode($rs));
@ -259,9 +255,6 @@ class RelayController extends AdminController
$rs['msg'] = '删除失败';
return $response->getBody()->write(json_encode($rs));
}
Tools::delSubCache();
$rs['ret'] = 1;
$rs['msg'] = '删除成功';
return $response->getBody()->write(json_encode($rs));

@ -17,10 +17,6 @@ use App\Utils\DatatablesHelper;
use App\Controllers\AdminController;
use App\Utils\Telegram;
use TelegramBot\Api\BotApi;
class TicketController extends AdminController
{
public function index($request, $response, $args)
@ -56,36 +52,24 @@ class TicketController extends AdminController
$ticket_main = Ticket::where('id', '=', $id)->where('rootid', '=', 0)->first();
$user = User::where('id','=', $ticket_main->userid)->first();
$ticket_url = Config::get('baseUrl') . '/user/ticket/' . $ticket_main->id . '/view';
$subject = '您提出的工单已被回复';
$to = $user->email;
$text = '管理员已回复您提出的工单';
try {
Mail::send($to, $subject, 'ticket/ticket_reply.tpl', [
'user' => $user, 'text' => $text, 'content' => $content, 'title' => $ticket_main->title, 'ticket_url' => $ticket_url
], [
]);
} catch (Exception $e) {
}
if (Config::get('enable_telegram') == 'true' && $user->telegram_id != null) {
$messageText = 'Hi,'.$user->user_name.PHP_EOL.'管理员已回复您提出的工单'.PHP_EOL.PHP_EOL.'工单标题: '.$ticket_main->title.PHP_EOL.'回复内容: '.$content;
$keyboard = new \TelegramBot\Api\Types\Inline\InlineKeyboardMarkup(
[
[
['text' => '回复工单', 'url' => $ticket_url]
]
]
);
$bot = new BotApi(Config::get('telegram_token'));
//if($status==1&&$ticket_main->status!=$status)
{
$adminUser = User::where('id', '=', $ticket_main->userid)->get();
foreach ($adminUser as $user) {
$subject = Config::get('appName') . '-工单被回复';
$to = $user->email;
$text = '您好,有人回复了<a href="' . Config::get('baseUrl') . '/user/ticket/' . $ticket_main->id . '/view">工单</a>,请您查看。';
try {
$bot->sendMessage($user->telegram_id, $messageText, null, null, null, $keyboard);
Mail::send($to, $subject, 'news/warn.tpl', [
'user' => $user, 'text' => $text
], [
]);
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
$antiXss = new AntiXSS();

@ -2,22 +2,22 @@
namespace App\Controllers\Admin;
use App\Controllers\AdminController;
use App\Models\Bought;
use App\Models\User;
use App\Models\Ip;
use App\Models\Bought;
use App\Models\Relay;
use App\Models\User;
use App\Models\DetectBanLog;
use App\Models\Shop;
use App\Services\Auth;
use App\Controllers\AdminController;
use App\Services\Config;
use App\Services\Auth;
use App\Services\Mail;
use App\Utils;
use App\Utils\GA;
use App\Utils\Hash;
use App\Utils\QQWry;
use App\Utils\Radius;
use App\Utils\QQWry;
use App\Utils\Check;
use App\Utils\Tools;
use App\Utils\GA;
use Exception;
@ -25,38 +25,19 @@ class UserController extends AdminController
{
public function index($request, $response, $args)
{
$table_config['total_column'] = array(
'op' => '操作',
'id' => 'ID',
'user_name' => '用户名',
'remark' => '备注',
'email' => '邮箱',
'money' => '金钱',
'im_type' => '联络方式类型',
'im_value' => '联络方式详情',
'node_group' => '群组',
'expire_in' => '账户过期时间',
'class' => '等级',
'class_expire' => '等级过期时间',
'passwd' => '连接密码',
'port' => '连接端口',
'method' => '加密方式',
'protocol' => '连接协议',
'obfs' => '混淆方式',
'obfs_param' => '混淆参数',
'online_ip_count' => '在线IP数',
'last_ss_time' => '上次使用时间',
'used_traffic' => '已用流量/GB',
'enable_traffic' => '总流量/GB',
'last_checkin_time' => '上次签到时间',
'today_traffic' => '今日流量/MB',
'enable' => '是否启用',
'reg_date' => '注册时间',
'reg_ip' => '注册IP',
'auto_reset_day' => '自动重置流量日',
'auto_reset_bandwidth' => '自动重置流量/GB',
'ref_by' => '邀请人ID',
'ref_by_user_name' => '邀请人用户名',
$table_config['total_column'] = array('op' => '操作', 'id' => 'ID', 'user_name' => '用户名',
'remark' => '备注', 'email' => '邮箱', 'money' => '金钱',
'im_type' => '联络方式类型', 'im_value' => '联络方式详情',
'node_group' => '群组', 'expire_in' => '账户过期时间',
'class' => '等级', 'class_expire' => '等级过期时间',
'passwd' => '连接密码', 'port' => '连接端口', 'method' => '加密方式',
'protocol' => '连接协议', 'obfs' => '连接混淆方式',
'online_ip_count' => '在线IP数', 'last_ss_time' => '上次使用时间',
'used_traffic' => '已用流量/GB', 'enable_traffic' => '总流量/GB',
'last_checkin_time' => '上次签到时间', 'today_traffic' => '今日流量/MB',
'enable' => '是否启用', 'reg_date' => '注册时间',
'reg_ip' => '注册IP', 'auto_reset_day' => '自动重置流量日',
'auto_reset_bandwidth' => '自动重置流量/GB', 'ref_by' => '邀请人ID', 'ref_by_user_name' => '邀请人用户名',
'top_up' => '累计充值');
$table_config['default_show_column'] = array('op', 'id', 'user_name', 'remark', 'email');
$table_config['ajax_url'] = 'user/ajax';
@ -135,7 +116,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) {
@ -196,6 +177,7 @@ class UserController extends AdminController
return $response->getBody()->write(json_encode($result));
}
public function search($request, $response, $args)
{
$pageNum = 1;
@ -207,9 +189,11 @@ class UserController extends AdminController
$users = User::where('email', 'LIKE', '%' . $text . '%')->orWhere('user_name', 'LIKE', '%' . $text . '%')->orWhere('im_value', 'LIKE', '%' . $text . '%')->orWhere('port', 'LIKE', '%' . $text . '%')->orWhere('remark', 'LIKE', '%' . $text . '%')->paginate(20, ['*'], 'page', $pageNum);
$users->setPath('/admin/user/search/' . $text);
//Ip::where("datetime","<",time()-90)->get()->delete();
$total = Ip::where('datetime', '>=', time() - 90)->orderBy('userid', 'desc')->get();
$userip = array();
$useripcount = array();
$regloc = array();
@ -223,6 +207,7 @@ class UserController extends AdminController
$regloc[$user->id] = iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']);
}
foreach ($total as $single) {
if (isset($useripcount[$single->userid]) && !isset($userip[$single->userid][$single->ip])) {
++$useripcount[$single->userid];
@ -231,6 +216,7 @@ class UserController extends AdminController
}
}
return $this->view()->assign('users', $users)->assign('regloc', $regloc)->assign('useripcount', $useripcount)->assign('userip', $userip)->display('admin/user/index.tpl');
}
@ -243,11 +229,14 @@ class UserController extends AdminController
$pageNum = $request->getQueryParams()['page'];
}
$users->setPath('/admin/user/sort/' . $text . '/' . $asc);
//Ip::where("datetime","<",time()-90)->get()->delete();
$total = Ip::where('datetime', '>=', time() - 90)->orderBy('userid', 'desc')->get();
$userip = array();
$useripcount = array();
$regloc = array();
@ -261,6 +250,7 @@ class UserController extends AdminController
$regloc[$user->id] = iconv('gbk', 'utf-8//IGNORE', $location['country'] . $location['area']);
}
foreach ($total as $single) {
if (isset($useripcount[$single->userid]) && !isset($userip[$single->userid][$single->ip])) {
++$useripcount[$single->userid];
@ -269,9 +259,11 @@ class UserController extends AdminController
}
}
return $this->view()->assign('users', $users)->assign('regloc', $regloc)->assign('useripcount', $useripcount)->assign('userip', $userip)->display('admin/user/index.tpl');
}
public function edit($request, $response, $args)
{
$id = $args['id'];
@ -294,6 +286,7 @@ class UserController extends AdminController
Radius::ChangeUserName($email1, $email2, $passwd);
if ($request->getParam('pass') != '') {
$user->pass = Hash::passwordHash($request->getParam('pass'));
$user->clean_link();
@ -335,21 +328,30 @@ 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;
}
// 手动封禁
$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;
if ($user->detect_ban == 0 && $detect_ban == 1) {
if ((int)$request->getParam('ban_time') == 0) {
$rs['ret'] = 0;
$rs['msg'] = "修改失败,封禁时长不能为 0";
return $response->getBody()->write(json_encode($rs));
}
$user->detect_ban = 1;
$end_time = date('Y-m-d H:i:s');
$user->last_detect_ban_time = $end_time;
$DetectBanLog = new DetectBanLog();
$DetectBanLog->user_name = $user->user_name;
$DetectBanLog->user_id = $user->id;
$DetectBanLog->email = $user->email;
$DetectBanLog->detect_number = '0';
$DetectBanLog->ban_time = (int)$request->getParam('ban_time');
$DetectBanLog->start_time = strtotime('1989-06-04 00:05:00');
$DetectBanLog->end_time = strtotime($end_time);
$DetectBanLog->all_detect_number = $user->all_detect_number;
$DetectBanLog->save();
}
@ -405,7 +407,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'] = '切换成功';
@ -508,7 +510,6 @@ 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;
@ -539,7 +540,6 @@ class UserController extends AdminController
$tempdata['method'] = $user->method;
$tempdata['protocol'] = $user->protocol;
$tempdata['obfs'] = $user->obfs;
$tempdata['obfs_param'] = $user->obfs_param;
$tempdata['online_ip_count'] = $user->online_ip_count();
$tempdata['last_ss_time'] = $user->lastSsTime();
$tempdata['used_traffic'] = Tools::flowToGB($user->u + $user->d);
@ -575,136 +575,4 @@ class UserController extends AdminController
];
return json_encode($info, true);
}
public function cleanSubCache($request, $response, $args)
{
$id = $args['id'];
$user_path = (BASE_PATH . '/storage/SubscribeCache/' . $id . '/');
Tools::delDirAndFile($user_path);
$res['ret'] = 1;
$res['msg'] = '清理成功';
return $this->echoJson($response, $res);
}
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,16 +21,7 @@ class AdminController extends UserController
public function index($request, $response, $args)
{
$sts = new Analytics();
$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');
return $this->view()->assign('sts', $sts)->display('admin/index.tpl');
}
public function node($request, $response, $args)
@ -247,79 +238,4 @@ 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));
}
}

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

@ -4,7 +4,6 @@ namespace App\Controllers;
use App\Models\InviteCode;
use App\Services\Config;
use App\Services\MalioConfig;
use App\Utils\Check;
use App\Utils\Tools;
use App\Utils\Radius;
@ -17,25 +16,20 @@ use App\Services\Mail;
use App\Models\User;
use App\Models\LoginIp;
use App\Models\EmailVerify;
use App\Models\SmsVerify;
use App\Utils\GA;
use App\Utils\Geetest;
use App\Utils\TelegramSessionManager;
use Ramsey\Uuid\Uuid;
use App\Services\Internationalization;
/**
* AuthController
*/
class AuthController extends BaseController
{
public function login($request, $response, $args)
public function login()
{
$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');
@ -47,7 +41,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];
@ -57,34 +51,13 @@ class AuthController extends BaseController
$login_number = '';
}
$welcome = '';
$time = date('G');
if ($time <= 4) {
$welcome = 'Good Night';
} else if ($time <= 12) {
$welcome = 'Good Morning';
} else if ($time <=18) {
$welcome = 'Good Afternoon';
} else {
$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)
->assign('login_number', $login_number)
->assign('welcome', $welcome)
->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');
}
@ -120,7 +93,7 @@ class AuthController extends BaseController
$code = $request->getParam('code');
$rememberMe = $request->getParam('remember_me');
if (Config::get('enable_login_captcha') === true) {
if (Config::get('enable_login_captcha') === 'true') {
switch (Config::get('captcha_provider')) {
case 'recaptcha':
$recaptcha = $request->getParam('recaptcha');
@ -176,7 +149,7 @@ class AuthController extends BaseController
$rcode = $ga->verifyCode($user->ga_token, $code);
if (!$rcode) {
$res['ret'] = 2;
$res['ret'] = 0;
$res['msg'] = '两步验证码错误,如果您是丢失了生成器或者错误地设置了这个选项,您可以尝试重置密码,即可取消这个选项。';
return $response->getBody()->write(json_encode($res));
}
@ -245,7 +218,7 @@ class AuthController extends BaseController
$GtSdk = null;
$recaptcha_sitekey = null;
if (Config::get('enable_reg_captcha') === true) {
if (Config::get('enable_reg_captcha') === 'true') {
switch (Config::get('captcha_provider')) {
case 'recaptcha':
$recaptcha_sitekey = Config::get('recaptcha_sitekey');
@ -257,15 +230,8 @@ 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)
@ -276,7 +242,7 @@ class AuthController extends BaseController
public function sendVerify($request, $response, $next)
{
if (Config::get('enable_email_verify') == true) {
if (Config::get('enable_email_verify') === 'true') {
$email = $request->getParam('email');
$email = trim($email);
@ -346,84 +312,6 @@ class AuthController extends BaseController
return $response->getBody()->write(json_encode($res));
}
public function sendSMS($request, $response, $next)
{
if (MalioConfig::get('enable_sms_verify') == true) {
$phone = $request->getParam('phone');
$phone = trim($phone);
$area_code = $request->getParam('area_code');
$full_phone = $area_code.$phone;
if ($phone == '' || $area_code == '') {
$res['ret'] = 0;
$res['msg'] = '请填写完整的手机号';
return $response->getBody()->write(json_encode($res));
}
$ipcount = SmsVerify::where('ip', '=', $_SERVER['REMOTE_ADDR'])->where('expire_in', '>', time())->count();
if ($ipcount >= (int)MalioConfig::get('sms_verify_iplimit')) {
$res['ret'] = 0;
$res['msg'] = '此IP请求次数过多';
return $response->getBody()->write(json_encode($res));
}
$code = Tools::genRandomNum(6);
$pamas = array(
'access_key' => MalioConfig::get('globalsent_access_key'),
'mobile' => $full_phone,
'content' => '您的注册验证码是 '.$code
);
$url = 'https://api.globalsent.com/send?'.http_build_query($pamas);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$return = curl_exec($ch);
curl_close($ch);
$return = json_decode($return);
if ($return->code != '0000') {
$res['ret'] = 0;
$res['msg'] = '发送短信验证码失败';
return $return->code;
return $response->getBody()->write(json_encode($res));
} else {
$sv = new SmsVerify();
$sv->expire_in = time() + Config::get('email_verify_ttl');
$sv->ip = $_SERVER['REMOTE_ADDR'];
$sv->phone = $full_phone;
$sv->code = $code;
$sv->save();
$res['ret'] = 1;
$res['msg'] = '验证码发送成功,请查收短信。';
return $response->getBody()->write(json_encode($res));
}
/*
{
"code": "0000",
"data": {
"send_id": "312312312",
"mobile": "861212131212",
"messages": "\u3010Malio\u4e91\u3011test",
"count": 1,
"per_price": 0.06,
"count_price": 0.06
},
"message": ""
}
*/
}
$res['ret'] = 0;
return $response->getBody()->write(json_encode($res));
}
public function registerHandle($request, $response)
{
if (Config::get('register_mode') === 'close') {
@ -446,17 +334,8 @@ class AuthController extends BaseController
$wechat = trim($wechat);
// check code
$sms_code = $request->getParam('sms_code');
$sms_code = trim($sms_code);
$phone = $request->getParam('phone');
$phone = trim($phone);
$area_code = $request->getParam('area_code');
$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');
@ -481,7 +360,7 @@ class AuthController extends BaseController
//dumplin:1、邀请人等级为0则邀请码不可用;2、邀请人invite_num为可邀请次数,填负数则为无限
$c = InviteCode::where('code', $code)->first();
if ($c == null && MalioConfig::get('code_required') == true) {
if ($c == null) {
if (Config::get('register_mode') === 'invite') {
$res['ret'] = 0;
$res['msg'] = '邀请码无效';
@ -495,13 +374,13 @@ class AuthController extends BaseController
return $response->getBody()->write(json_encode($res));
}
if ($gift_user->class == 0 && MalioConfig::get('code_required') == true) {
if ($gift_user->class == 0) {
$res['ret'] = 0;
$res['msg'] = '邀请人不是VIP';
return $response->getBody()->write(json_encode($res));
}
if ($gift_user->invite_num == 0 && MalioConfig::get('code_required') == true) {
if ($gift_user->invite_num == 0) {
$res['ret'] = 0;
$res['msg'] = '邀请人可用邀请次数为0';
return $response->getBody()->write(json_encode($res));
@ -515,19 +394,6 @@ class AuthController extends BaseController
$res['msg'] = '邮箱无效';
return $response->getBody()->write(json_encode($res));
}
$email_postfix = '@'.(explode("@",$email)[1]);
if (in_array($email_postfix, MalioConfig::get('register_email_black_list')) == true) {
$res['ret'] = 0;
$res['msg'] = '邮箱后缀已被拉黑';
return $response->getBody()->write(json_encode($res));
}
if (MalioConfig::get('enable_register_email_restrict') == true) {
if (in_array($email_postfix, MalioConfig::get('register_email_white_list')) == false) {
$res['ret'] = 0;
$res['msg'] = '小老弟还会发送post请求啊';
return $response->getBody()->write(json_encode($res));
}
}
// check email
$user = User::where('email', $email)->first();
if ($user != null) {
@ -536,7 +402,7 @@ class AuthController extends BaseController
return $response->getBody()->write(json_encode($res));
}
if (Config::get('enable_email_verify') == true) {
if (Config::get('enable_email_verify') === 'true') {
$mailcount = EmailVerify::where('email', '=', $email)->where('code', '=', $emailcode)->where('expire_in', '>', time())->first();
if ($mailcount == null) {
$res['ret'] = 0;
@ -545,15 +411,6 @@ class AuthController extends BaseController
}
}
if (MalioConfig::get('enable_sms_verify') == true) {
$smscount = SmsVerify::where('phone', '=', $full_phone)->where('code', '=', $sms_code)->where('expire_in', '>', time())->first();
if ($smscount == null) {
$res['ret'] = 0;
$res['msg'] = '您的短信验证码不正确';
return $response->getBody()->write(json_encode($res));
}
}
// check pwd length
if (strlen($passwd) < 8) {
$res['ret'] = 0;
@ -568,7 +425,6 @@ class AuthController extends BaseController
return $response->getBody()->write(json_encode($res));
}
/*
if ($imtype == '' || $wechat == '') {
$res['ret'] = 0;
$res['msg'] = '请填上你的联络方式';
@ -581,15 +437,9 @@ class AuthController extends BaseController
$res['msg'] = '此联络方式已注册';
return $response->getBody()->write(json_encode($res));
}
*/
if (Config::get('enable_email_verify') == true) {
if (Config::get('enable_email_verify') === 'true') {
EmailVerify::where('email', '=', $email)->delete();
}
if (MalioConfig::get('enable_sms_verify') == true) {
SmsVerify::where('phone', '=', $full_phone)->delete();
}
// do reg user
$user = new User();
@ -618,23 +468,16 @@ class AuthController extends BaseController
$user->auto_reset_day = Config::get('reg_auto_reset_day');
$user->auto_reset_bandwidth = Config::get('reg_auto_reset_bandwidth');
$user->money = 0;
if ($full_phone == '') {
$user->phone = null;
} else {
$user->phone = $full_phone;
}
//dumplin:填写邀请人,写入邀请奖励
$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) {
$user->ref_by = $c->user_id;
$user->money = Config::get('invite_get_money');
$gift_user->transfer_enable += Config::get('invite_gift') * 1024 * 1024 * 1024;
--$gift_user->invite_num;
$gift_user->save();
};
$user->ref_by = $c->user_id;
$user->money = Config::get('invite_get_money');
$gift_user->transfer_enable += Config::get('invite_gift') * 1024 * 1024 * 1024;
--$gift_user->invite_num;
$gift_user->save();
}
@ -659,11 +502,6 @@ class AuthController extends BaseController
$user->ga_enable = 0;
/* malio 增加UUID */
$user->uuid = Uuid::uuid3(Uuid::NAMESPACE_DNS, ($user->passwd) . Config::get('key') . $user->id)->toString();
/* malio end */
if ($user->save()) {
$res['ret'] = 1;
$res['msg'] = '注册成功!正在进入登录界面';
@ -692,7 +530,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));
@ -704,7 +542,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,10 +5,7 @@ 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
@ -32,7 +29,6 @@ class BaseController
{
$this->view = View::getSmarty();
$this->user = Auth::getUser();
$this->i18n = new Internationalization();
}
/**
@ -44,18 +40,13 @@ class BaseController
{
return $this->view;
}
// TODO: remove
/**
* Output JSON
*
* @param Response $response
* @param array|object $resource
*
* @return ResponseInterface
* @param $response
* @param $res
* @return mixed
*/
public function echoJson(Response $response, $resource)
public function echoJson($response, $res)
{
return $response->withJson($resource);
return $response->getBody()->write(json_encode($res));
}
}

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

@ -180,7 +180,7 @@ class ConfController extends BaseController
$return = null;
switch (true) {
case (isset($Rule['content']['class'])):
if (in_array($Proxy['class'], $Rule['content']['class'])) {
if ($Proxy['class'] == $Rule['content']['class']) {
if (isset($Rule['content']['regex'])) {
if (preg_match('/' . $Rule['content']['regex'] . '/i', $Proxy['remark'])) {
$return = $Proxy;
@ -191,7 +191,7 @@ class ConfController extends BaseController
}
break;
case (isset($Rule['content']['noclass'])):
if (!in_array($Proxy['class'], $Rule['content']['noclass'])) {
if ($Proxy['class'] != $Rule['content']['noclass']) {
if (isset($Rule['content']['regex'])) {
if (preg_match('/' . $Rule['content']['regex'] . '/i', $Proxy['remark'])) {
$return = $Proxy;
@ -358,17 +358,6 @@ class ConfController extends BaseController
*/
public static function getClashConfs($User, $AllProxys, $Configs, $local = false)
{
$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 {
@ -380,14 +369,14 @@ class ConfController extends BaseController
$Proxys[] = $Proxy;
}
$tmp = self::getClashConfGeneral($Configs['General']);
$tmp[$confStr['Proxy']] = $Proxys;
$tmp['Proxy'] = $Proxys;
if (isset($Configs['ProxyGroup'])) {
$tmp[$confStr['ProxyGroup']] = self::getClashConfProxyGroup(
$tmp['Proxy Group'] = self::getClashConfProxyGroup(
$AllProxys,
$Configs['ProxyGroup']
);
} else {
$tmp[$confStr['ProxyGroup']] = self::getClashConfProxyGroup(
$tmp['Proxy Group'] = self::getClashConfProxyGroup(
$AllProxys,
$Configs['Proxy Group']
);
@ -486,19 +475,14 @@ class ConfController extends BaseController
*/
public static function getClashConfRule($Rules, $local)
{
$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']));
return $render->fetch(trim($Rules['source']));
}
// 加载远程规则文件
$return = ('Rule:' . PHP_EOL);
if (isset($Rules['source']) && $Rules['source'] != '') {
$sourceURL = trim($Rules['source']);
// 远程规则仅支持 github 以及 gitlab
@ -516,10 +500,10 @@ class ConfController extends BaseController
} catch (ParseException $exception) {
$sourceRule['error'] = printf('无法解析 YAML 字符串: %s', $exception->getMessage());
}
if (isset($sourceRule['error']) || !isset($sourceRule[$confStr])) {
if (isset($sourceRule['error']) || !isset($sourceRule['Rule'])) {
$return .= $sourceContent;
} else {
$return .= Yaml::dump($sourceRule[$confStr], 4, 2);
$return .= Yaml::dump($sourceRule['Rule'], 4, 2);
}
}
} else {

@ -5,28 +5,19 @@ 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
{
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function index($request, $response, $args): ResponseInterface
public function index()
{
$GtSdk = null;
$recaptcha_sitekey = null;
@ -42,7 +33,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];
@ -52,170 +43,84 @@ class HomeController extends BaseController
$login_number = '';
}
if (Config::get('newIndex') === false && Config::get('theme') == 'material') {
return $response->write($this->view()->fetch('indexold.tpl'));
if (Config::get('newIndex') != 'true' && Config::get('theme') == 'material') {
return $this->view()->display('indexold.tpl');
} else {
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')
);
}
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');
}
}
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function indexold($request, $response, $args): ResponseInterface
public function indexold()
{
return $response->write($this->view()->fetch('indexold.tpl'));
return $this->view()->display('indexold.tpl');
}
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function code($request, $response, $args): ResponseInterface
public function code()
{
$codes = InviteCode::where('user_id', '=', '0')->take(10)->get();
return $response->write($this->view()->assign('codes', $codes)->fetch('code.tpl'));
return $this->view()->assign('codes', $codes)->display('code.tpl');
}
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function tos($request, $response, $args): ResponseInterface
{
return $response->write($this->view()->fetch('tos.tpl'));
}
public function down()
{ }
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function staff($request, $response, $args): ResponseInterface
public function tos()
{
return $response->write($this->view()->fetch('staff.tpl'));
return $this->view()->display('tos.tpl');
}
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function telegram($request, $response, $args): ResponseInterface
public function staff()
{
$token = $request->getQueryParam('token');
if ($token == Config::get('telegram_request_token')) {
TelegramProcess::process();
$result = '1';
} else {
$result = '0';
}
return $response->write($result);
return $this->view()->display('staff.tpl');
}
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function NewTelegram($request, $response, $args): ResponseInterface
public function telegram($request, $response, $args)
{
$token = $request->getQueryParam('token');
$token = $request->getQueryParams()['token'] ?? '';
if ($token == Config::get('telegram_request_token')) {
Process::index();
$result = '1';
TelegramProcess::process();
} else {
$result = '0';
echo ('不正确请求!');
}
return $response->write($result);
}
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function page404($request, $response, $args): ResponseInterface
public function page404($request, $response, $args)
{
return $response->write($this->view()->fetch('404.tpl'));
return $this->view()->display('404.tpl');
}
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function page405($request, $response, $args): ResponseInterface
public function page405($request, $response, $args)
{
return $response->write($this->view()->fetch('405.tpl'));
return $this->view()->display('405.tpl');
}
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function page500($request, $response, $args): ResponseInterface
public function page500($request, $response, $args)
{
return $response->write($this->view()->fetch('500.tpl'));
return $this->view()->display('500.tpl');
}
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function getOrderList($request, $response, $args): ResponseInterface
public function getOrderList($request, $response, $args)
{
$key = $request->getParam('key');
if (!$key || $key != Config::get('key')) {
$res['ret'] = 0;
$res['msg'] = '错误';
return $response->write(json_encode($res));
return $response->getBody()->write(json_encode($res));
}
return $response->write(json_encode(['data' => AliPay::getList()]));
return $response->getBody()->write(json_encode(['data' => AliPay::getList()]));
}
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
public function setOrder($request, $response, $args): ResponseInterface
public function setOrder($request, $response, $args)
{
$key = $request->getParam('key');
$sn = $request->getParam('sn');
@ -223,39 +128,38 @@ class HomeController extends BaseController
if (!$key || $key != Config::get('key')) {
$res['ret'] = 0;
$res['msg'] = '错误';
return $response->write(json_encode($res));
return $response->getBody()->write(json_encode($res));
}
return $response->write(json_encode(['res' => AliPay::setOrder($sn, $url)]));
return $response->getBody()->write(json_encode(['res' => AliPay::setOrder($sn, $url)]));
}
public function getDocCenter($request, $response, $args)
{
$user = Auth::getUser();
if (!$user->isLogin && Config::get('enable_documents') === false) {
if (!$user->isLogin && Config::get('enable_documents') != 'true') {
$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)
->fetch('doc/index.tpl');
->display('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 ($type) {
switch ($request->getParam('type')) {
case 'ssr':
$msg = [
'**订阅链接:**',
'```',
$subInfo['ssr'],
$subInfo['ssr'] . '&extend=1',
'```'
];
break;
@ -263,7 +167,7 @@ class HomeController extends BaseController
$msg = [
'**订阅链接:**',
'```',
$subInfo['v2ray'],
$subInfo['v2ray'] . '&extend=1',
'```'
];
break;
@ -299,7 +203,7 @@ class HomeController extends BaseController
$msg = [
'**包含 ss、v2ray 的合并订阅链接:**',
'```',
$subInfo['kitsunebi'],
$subInfo['kitsunebi'] . '&extend=1',
'```'
];
break;
@ -344,17 +248,9 @@ class HomeController extends BaseController
];
break;
default:
if (in_array($type, $subInfo)) {
$msg = [
'```',
$subInfo[$type],
'```'
];
} else {
$msg = [
'获取失败了呢...,请联系管理员。'
];
}
$msg = [
'获取失败了呢...,请联系管理员。'
];
break;
}
}

File diff suppressed because it is too large Load Diff

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

@ -58,16 +58,6 @@ 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' => [
@ -78,8 +68,7 @@ class NodeController extends BaseController
'mu_only' => $node->mu_only,
'sort' => $node->sort,
'server' => $node_server,
'type' => 'ss-panel-v3-mod_Uim',
'online' => $node_online
'type' => 'ss-panel-v3-mod_Uim'
],
];
return $this->echoJson($response, $res);

@ -13,7 +13,6 @@ use App\Controllers\BaseController;
use App\Services\Config;
use App\Utils\Tools;
use App\Utils\URL;
use App\Services\MalioConfig;
class UserController extends BaseController
{
@ -53,7 +52,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 +61,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 +89,10 @@ class UserController extends BaseController
)->orwhere('is_admin', 1);
}
}
)->where('enable', 1)->where('expire_in', '>', date('Y-m-d H:i:s'))->get();
)->where('enable', 1)->where("detect_ban", 0)->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 +108,7 @@ class UserController extends BaseController
}
)->orwhere('is_admin', 1);
}
)->where('enable', 1)->where('expire_in', '>', date('Y-m-d H:i:s'))->get();
)->where('enable', 1)->where("detect_ban", 0)->where('expire_in', '>', date('Y-m-d H:i:s'))->get();
$muPort = Tools::get_MuOutPortArray($node->server);
if ($muPort['type'] == 0) {
@ -131,26 +130,33 @@ 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', 'node_connector',
'sort', 'uuid', 'sha224uuid');
'is_multi_user', 'id', 'port', 'passwd', 'u', 'd');
$users = array();
foreach ($users_raw as $user_raw) {
if ($node->sort == 14) {
$user_raw->sha224uuid = hash('sha224', $user_raw->uuid);
if (Config::get('keep_connect') == 'true') {
foreach ($users_raw as $user_raw) {
if ($user_raw->transfer_enable > $user_raw->u + $user_raw->d) {
$user_raw = Tools::keyFilter($user_raw, $key_list);
$user_raw->uuid = $user_raw->getUuid();
$users[] = $user_raw;
} else {
// 流量耗尽用户限速至 1Mbps
$user_raw = Tools::keyFilter($user_raw, $key_list);
$user_raw->uuid = $user_raw->getUuid();
$user_raw->node_speedlimit = 1;
$users[] = $user_raw;
}
}
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;
} else {
foreach ($users_raw as $user_raw) {
if ($user_raw->transfer_enable > $user_raw->u + $user_raw->d) {
$user_raw = Tools::keyFilter($user_raw, $key_list);
$user_raw->uuid = $user_raw->getUuid();
$users[] = $user_raw;
}
}
}
$res = [
'ret' => 1,
@ -292,18 +298,49 @@ class UserController extends BaseController
return $this->echoJson($response, $res);
}
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 (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();
}
}
}
@ -313,4 +350,74 @@ class UserController extends BaseController
];
return $this->echoJson($response, $res);
}
public function DetectBan($detect_Users)
{
foreach ($detect_Users as $user_id) {
$User = User::find($user_id);
if ($User == null) {
continue;
}
if ($User->detect_ban == 1 || ($User->is_admin && Config::get('auto_detect_ban_allow_admin') == 'true') || in_array($User->id, Config::get('auto_detect_ban_allow_users'))) {
continue;
}
if (Config::get('auto_detect_ban_type') == '1') {
$last_DetectBanLog = DetectBanLog::where('user_id', $user_id)->orderBy("id", "desc")->first();
$last_all_detect_number = (
$last_DetectBanLog == null
? 0
: (int) $last_DetectBanLog->all_detect_number
);
$detect_number = ($User->all_detect_number - $last_all_detect_number);
if ($detect_number >= Config::get('auto_detect_ban_number')) {
$last_detect_ban_time = $User->last_detect_ban_time;
$end_time = date('Y-m-d H:i:s');
$User->detect_ban = 1;
$User->last_detect_ban_time = $end_time;
$User->save();
$DetectBanLog = new DetectBanLog();
$DetectBanLog->user_name = $User->user_name;
$DetectBanLog->user_id = $User->id;
$DetectBanLog->email = $User->email;
$DetectBanLog->detect_number = $detect_number;
$DetectBanLog->ban_time = Config::get('auto_detect_ban_time');
$DetectBanLog->start_time = strtotime($last_detect_ban_time);
$DetectBanLog->end_time = strtotime($end_time);
$DetectBanLog->all_detect_number = $User->all_detect_number;
$DetectBanLog->save();
}
} else {
$number = $User->all_detect_number;
$tmp = 0;
foreach (Config::get('auto_detect_ban') as $key => $value) {
if ($number >= $key) {
if ($key >= $tmp) {
$tmp = $key;
}
}
}
if ($tmp != 0) {
if (Config::get('auto_detect_ban')[$tmp]['type'] == 'kill') {
$User->kill_user();
} else {
$last_detect_ban_time = $User->last_detect_ban_time;
$end_time = date('Y-m-d H:i:s');
$User->detect_ban = 1;
$User->last_detect_ban_time = $end_time;
$User->save();
$DetectBanLog = new DetectBanLog();
$DetectBanLog->user_name = $User->user_name;
$DetectBanLog->user_id = $User->id;
$DetectBanLog->email = $User->email;
$DetectBanLog->detect_number = $number;
$DetectBanLog->ban_time = Config::get('auto_detect_ban')[$tmp]['time'];
$DetectBanLog->start_time = strtotime('1989-06-04 00:05:00');
$DetectBanLog->end_time = strtotime($end_time);
$DetectBanLog->all_detect_number = $number;
$DetectBanLog->save();
}
}
}
}
}
}

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

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

@ -86,10 +86,10 @@ class RelayController extends UserController
if ($single_path->end_node->id == $path->begin_node->id) {
$path->begin_node = $single_path->begin_node;
if ($path->begin_node->isNodeAccessable() == false) {
$path->path = '' . $single_path->begin_node->name . '' . ' <i class="fas fa-long-arrow-alt-right"></i> ' . $path->path;
$path->path = '<font color="#FF0000">' . $single_path->begin_node->name . '</font>' . ' → ' . $path->path;
$path->status = '阻断';
} else {
$path->path = $single_path->begin_node->name . ' <i class="fas fa-long-arrow-alt-right"></i> ' . $path->path;
$path->path = $single_path->begin_node->name . ' → ' . $path->path;
$path->status = '通畅';
}
@ -100,10 +100,10 @@ class RelayController extends UserController
if ($path->end_node->id == $single_path->begin_node->id) {
$path->end_node = $single_path->end_node;
if ($single_path->end_node->isNodeAccessable() == false) {
$path->path = $path->path . ' <i class="fas fa-long-arrow-alt-right"></i> ' . '' . $single_path->end_node->name . '';
$path->path = $path->path . ' → ' . '<font color="#FF0000">' . $single_path->end_node->name . '</font>';
$path->status = '阻断';
} else {
$path->path = $path->path . ' <i class="fas fa-long-arrow-alt-right"></i> ' . $single_path->end_node->name;
$path->path = $path->path . ' → ' . $single_path->end_node->name;
}
$pathset->offsetUnset($index);
@ -268,8 +268,6 @@ class RelayController extends UserController
return $response->getBody()->write(json_encode($rs));
}
Tools::delSubCache();
$rs['ret'] = 1;
$rs['msg'] = '添加成功';
return $response->getBody()->write(json_encode($rs));
@ -434,8 +432,6 @@ class RelayController extends UserController
return $response->getBody()->write(json_encode($rs));
}
Tools::delSubCache();
$rs['ret'] = 1;
$rs['msg'] = '修改成功';
return $response->getBody()->write(json_encode($rs));
@ -457,9 +453,6 @@ class RelayController extends UserController
$rs['msg'] = '删除失败';
return $response->getBody()->write(json_encode($rs));
}
Tools::delSubCache();
$rs['ret'] = 1;
$rs['msg'] = '删除成功';
return $response->getBody()->write(json_encode($rs));

@ -13,7 +13,6 @@ use App\Models\Coupon;
use App\Models\Bought;
use App\Models\Ticket;
use App\Services\Config;
use App\Services\MalioConfig;
use App\Services\Gateway\ChenPay;
use App\Services\BitPayment;
use App\Services\Payment;
@ -38,10 +37,8 @@ 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;
@ -51,8 +48,6 @@ use App\Utils\URL;
use App\Utils\DatatablesHelper;
use App\Services\Mail;
use TelegramBot\Api\BotApi;
/**
* HomeController
*/
@ -64,7 +59,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');
@ -78,36 +73,9 @@ class UserController extends BaseController
$Ann = Ann::orderBy('date', 'desc')->first();
if (!$paybacks_sum = Payback::where("ref_by", $this->user->id)->sum('ref_get')) {
$paybacks_sum = 0;
}
$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'))
@ -135,15 +103,7 @@ class UserController extends BaseController
$pageNum = $request->getQueryParams()['page'] ?? 1;
$codes = Code::where('type', '<>', '-2')->where('userid', '=', $this->user->id)->orderBy('id', 'desc')->paginate(15, ['*'], 'page', $pageNum);
$codes->setPath('/user/code');
$bought_pageNum = 1;
if (isset($request->getQueryParams()["bought"])) {
$bought_pageNum = $request->getQueryParams()["bought"];
}
$shops = Bought::where("userid", $this->user->id)->orderBy("id", "desc")->paginate(5, ['*'], 'bought', $bought_pageNum);
$shops->setPath('/user/code');
return $this->view()->assign('shops', $shops)->assign('codes', $codes)->assign('pmw', Payment::purchaseHTML())->assign('bitpay', BitPayment::purchaseHTML())->display('user/code.tpl');
return $this->view()->assign('codes', $codes)->assign('pmw', Payment::purchaseHTML())->assign('bitpay', BitPayment::purchaseHTML())->display('user/code.tpl');
}
public function orderDelete($request, $response, $args)
@ -153,7 +113,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);
}
@ -309,7 +269,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 {
@ -354,7 +314,7 @@ class UserController extends BaseController
if ($code == '') {
$res['ret'] = 0;
$res['msg'] = '6位验证码不能为空';
$res['msg'] = '二维码不能为空';
return $response->getBody()->write(json_encode($res));
}
@ -362,15 +322,13 @@ class UserController extends BaseController
$rcode = $ga->verifyCode($user->ga_token, $code);
if (!$rcode) {
$res['ret'] = 0;
$res['msg'] = '未成功开启';
$res['msg'] = '测试错误';
return $response->getBody()->write(json_encode($res));
}
$user->ga_enable = 1;
$user->save();
$res['ret'] = 1;
$res['msg'] = '成功开启二步验证';
$res['msg'] = '测试成功';
return $response->getBody()->write(json_encode($res));
}
@ -397,20 +355,77 @@ class UserController extends BaseController
public function ResetPort($request, $response, $args)
{
$price = Config::get('port_price');
$user = $this->user;
$temp = $user->ResetPort();
$res['msg'] = $temp['msg'];
$res['ret'] = ($temp['ok'] === true ? 1 : 0);
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;
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');
$temp = $user->SpecifyPort($port);
$res['msg'] = $temp['msg'];
$res['ret'] = ($temp['ok'] === true ? 1 : 0);
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'] = '钦定成功';
return $response->getBody()->write(json_encode($res));
}
@ -422,7 +437,7 @@ class UserController extends BaseController
$user->ga_token = $secret;
$user->save();
return $response->withStatus(302)->withHeader('Location', '/user/profile');
return $response->withStatus(302)->withHeader('Location', '/user/edit');
}
@ -468,7 +483,7 @@ class UserController extends BaseController
$server = Tools::ssv2Array($node->server);
$array_node['server'] = $server['add'];
} else {
$array_node['server'] = $node->getServer();
$array_node['server'] = $node->server;
}
$array_node['sort'] = $node->sort;
$array_node['info'] = $node->info;
@ -492,7 +507,7 @@ class UserController extends BaseController
if ($log['node_id'] != $node->id) {
continue;
}
if (in_array($sort, array(0, 7, 8, 10, 11, 12, 13, 14))) {
if (in_array($sort, array(0, 7, 8, 10, 11, 12, 13))) {
$array_node['online_user'] = $log['online_user'];
} else {
$array_node['online_user'] = -1;
@ -504,7 +519,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, 14)) || $node_heartbeat == 300) {
if (!in_array($sort, array(0, 7, 8, 10, 11, 12, 13)) || $node_heartbeat == 300) {
$array_node['online'] = 0;
} elseif ($node_heartbeat > time()) {
$array_node['online'] = 1;
@ -641,7 +656,7 @@ class UserController extends BaseController
$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);
@ -672,25 +687,7 @@ class UserController extends BaseController
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)) {
$nodes_muport = array();
if($node->mu_only != -1) {
$nodes = Node::where('type', 1)->orderBy('node_class')->orderBy('name')->get();
foreach($nodes as $node_mu){
if ($node_mu->sort == 9) {
$mu_user = User::where('port', '=', $node_mu->server)->first();
$mu_user->obfs_param = $this->user->getMuMd5();
$nodes_muport[] = array('server' => $node_mu, 'user' => $mu_user);
}
}
}
return $this->view()
->assign('nodes_muport', $nodes_muport)
->assign('node', $node)
->assign('user', $user)
->assign('mu', $mu)
->assign('relay_rule_id', $relay_rule_id)
->registerClass('URL', URL::class)
->display('user/nodeinfo.tpl');
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 1:
@ -731,11 +728,6 @@ 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 '微笑';
}
@ -743,11 +735,12 @@ 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();
@ -756,72 +749,37 @@ class UserController extends BaseController
$userloginip = array();
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 ($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') == '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) {
//if(isset($useripcount[$single->userid]))
{
$single->ip = Tools::getRealIp($single->ip);
$is_node = Node::where('node_ip', $single->ip)->first();
if ($is_node) {
continue;
}
}
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])) {
$userip[$single->ip] = $ip_location_geoip2->getLocation($single->ip, $user->lang);
}
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']);
}
}
}
$bind_token = TelegramSessionManager::add_bind_session($this->user);
return $this->view()
->assign('telegram_bot', Config::get('telegram_bot'))
->assign('bind_token', $bind_token)
->assign('userip', $userip)
->assign('userloginip', $userloginip)
->assign('paybacks', $paybacks)->display('user/profile.tpl');
return $this->view()->assign('userip', $userip)->assign('userloginip', $userloginip)->assign('paybacks', $paybacks)->display('user/profile.tpl');
}
@ -835,25 +793,7 @@ class UserController extends BaseController
public function tutorial($request, $response, $args)
{
$ssr_sub_token = LinkController::GenerateSSRSubCode($this->user->id, 0);
$opts = $request->getQueryParams();
if ($opts['os'] == 'faq') {
return $this->view()->display('user/tutorial/faq.tpl');
}
if ($opts['os'] != '' && $opts['client'] != '') {
$url = 'user/tutorial/'.$opts['os'].'-'.$opts['client'].'.tpl';
return $this->view()
->assign('subInfo', LinkController::getSubinfo($this->user, 0))
->assign('ssr_sub_token', $ssr_sub_token)
->assign('mergeSub', Config::get('mergeSub'))
->assign('subUrl', Config::get('subUrl'))
->assign('user', $this->user)
->registerClass('URL', URL::class)
->assign('baseUrl', Config::get('baseUrl'))
->display($url);
} else {
return $this->view()->display('user/tutorial.tpl');
}
return $this->view()->display('user/tutorial.tpl');
}
@ -874,10 +814,7 @@ class UserController extends BaseController
$config_service = new Config();
$ssr_sub_token = LinkController::GenerateSSRSubCode($this->user->id, 0);
return $this->view()
->assign('ssr_sub_token', $ssr_sub_token)
->assign('user', $this->user)
->assign('schemes', Config::get('user_agreement_scheme'))
->assign('themes', $themes)
@ -1094,14 +1031,10 @@ class UserController extends BaseController
if ($coupon == null) {
$res['ret'] = 0;
$res['msg'] = '此优惠码无效';
return $response->getBody()->write(json_encode($res));
}
if ($coupon->expire < time()) {
$res['ret'] = 0;
$res['msg'] = '优惠码已过期';
$res['msg'] = '优惠码无效';
return $response->getBody()->write(json_encode($res));
}
if ($coupon->order($shop->id) == false) {
$res['ret'] = 0;
$res['msg'] = '此优惠码不可用于此商品';
@ -1120,9 +1053,7 @@ class UserController extends BaseController
$res['ret'] = 1;
$res['name'] = $shop->name;
$res['credit'] = $coupon->credit;
$res['onetime'] = $coupon->onetime;
$res['shop'] = $coupon->shop;
$res['credit'] = $coupon->credit . ' %';
$res['total'] = $shop->price * ((100 - $coupon->credit) / 100) . '元';
return $response->getBody()->write(json_encode($res));
@ -1137,10 +1068,6 @@ 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) {
@ -1211,10 +1138,13 @@ class UserController extends BaseController
} else {
$bought->renew = time() + $shop->auto_renew * 86400;
}
$bought->coupon = $code;
if (isset($onetime)) {
$bought->renew = 0;
$price = $shop->price;
}
$bought->coupon = $code;
$bought->price = $price;
$bought->save();
@ -1263,7 +1193,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;
@ -1306,49 +1236,23 @@ class UserController extends BaseController
$ticket->datetime = time();
$ticket->save();
$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 && $markdown != '') {
if (Config::get('mail_ticket') == 'true' && $markdown != '') {
$adminUser = User::where('is_admin', '=', '1')->get();
foreach ($adminUser as $user) {
$subject = '新工单被开启';
$subject = Config::get('appName') . '-新工单被开启';
$to = $user->email;
$text = '有新工单需要您处理';
$text = '管理员,有人开启了新的工单,请您及时处理。';
try {
Mail::send($to, $subject, 'ticket/new_ticket.tpl', [
'user' => $this->user, 'admin' =>$user, 'text' => $text, 'title' => $title, 'content' => $content, 'ticket_url' =>$ticket_url
], [
]);
Mail::send($to, $subject, 'news/warn.tpl', [
'user' => $user, 'text' => $text
], []);
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
/* notify admins on telegram */
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(
[
[
['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) {
}
}
}
}
if (Config::get('useScFtqq') == true && $markdown != '') {
if (Config::get('useScFtqq') == 'true' && $markdown != '') {
$ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY');
$postdata = http_build_query(
array(
@ -1398,7 +1302,7 @@ class UserController extends BaseController
}
if ($status == 1 && $ticket_main->status != $status) {
if (Config::get('mail_ticket') == true && $markdown != '') {
if (Config::get('mail_ticket') == 'true' && $markdown != '') {
$adminUser = User::where('is_admin', '=', '1')->get();
foreach ($adminUser as $user) {
$subject = Config::get('appName') . '-工单被重新开启';
@ -1413,7 +1317,7 @@ class UserController extends BaseController
}
}
}
if (Config::get('useScFtqq') == true && $markdown != '') {
if (Config::get('useScFtqq') == 'true' && $markdown != '') {
$ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY');
$postdata = http_build_query(
array(
@ -1432,7 +1336,7 @@ class UserController extends BaseController
$useScFtqq = Config::get('ScFtqq_SCKEY');
}
} else {
if (Config::get('mail_ticket') == true && $markdown != '') {
if (Config::get('mail_ticket') == 'true' && $markdown != '') {
$adminUser = User::where('is_admin', '=', '1')->get();
foreach ($adminUser as $user) {
$subject = Config::get('appName') . '-工单被回复';
@ -1447,28 +1351,7 @@ class UserController extends BaseController
}
}
}
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]
]
]
);
$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 && $markdown != '') {
if (Config::get('useScFtqq') == 'true' && $markdown != '') {
$ScFtqq_SCKEY = Config::get('ScFtqq_SCKEY');
$postdata = http_build_query(
array(
@ -1486,7 +1369,6 @@ class UserController extends BaseController
file_get_contents('https://sc.ftqq.com/' . $ScFtqq_SCKEY . '.send', false, $context);
}
}
$antiXss = new AntiXSS();
@ -1523,7 +1405,7 @@ class UserController extends BaseController
$ticketset->setPath('/user/ticket/' . $id . '/view');
return $this->view()->assign('ticketset', $ticketset)->assign('ticket_status', $ticket_main->status)->assign('id', $id)->display('user/ticket_view.tpl');
return $this->view()->assign('ticketset', $ticketset)->assign('id', $id)->display('user/ticket_view.tpl');
}
@ -1541,6 +1423,12 @@ class UserController extends BaseController
return $response->getBody()->write(json_encode($res));
}
if ($user->discord != 0) {
$res['ret'] = 0;
$res['msg'] = '您绑定了 Discord ,所以此项并不能被修改。';
return $response->getBody()->write(json_encode($res));
}
if ($wechat == '' || $type == '') {
$res['ret'] = 0;
$res['msg'] = '非法输入';
@ -1611,8 +1499,6 @@ class UserController extends BaseController
$user->save();
$user->cleanSubCache();
if (!URL::SSCanConnect($user)) {
$res['ret'] = 1;
$res['msg'] = '设置成功,但您目前的协议,混淆,加密方式设置会导致 Shadowsocks原版客户端无法连接,请您自行更换到 ShadowsocksR 客户端。';
@ -1719,7 +1605,6 @@ class UserController extends BaseController
Radius::Add($user, $pwd);
$user->cleanSubCache();
return $this->echoJson($response, $res);
}
@ -1759,7 +1644,7 @@ class UserController extends BaseController
$user->updateMethod($method);
if (!URL::SSCanConnect($user)) {
$res['ret'] = 1;
$res['ret'] = 0;
$res['msg'] = '设置成功,但您目前的协议,混淆,加密方式设置会导致 Shadowsocks原版客户端无法连接,请您自行更换到 ShadowsocksR 客户端。';
return $this->echoJson($response, $res);
}
@ -1783,7 +1668,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');
@ -1811,21 +1696,23 @@ class UserController extends BaseController
return $response->getBody()->write(json_encode($res));
}
$checkin = $this->user->checkin();
if ($checkin['ok'] === false) {
if (!$this->user->isAbleToCheckin()) {
$res['ret'] = 0;
$res['msg'] = $checkin['msg'];
return $this->echoJson($response, $res);
}
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'));
$res['msg'] = '您似乎已经签到过了...';
return $response->getBody()->write(json_encode($res));
}
$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'] = $this->i18n->get('got-daily-bonus',[$traffic]);
$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['ret'] = 1;
return $this->echoJson($response, $res);
}
@ -1850,9 +1737,8 @@ class UserController extends BaseController
return $this->echoJson($response, $res);
}
if (Config::get('enable_kill') == true) {
if (Config::get('enable_kill') == 'true') {
Auth::logout();
$user->cleanSubCache();
$user->kill_user();
$res['ret'] = 1;
$res['msg'] = '您的帐号已经从我们的系统中删除。欢迎下次光临!';
@ -1891,10 +1777,19 @@ 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->TelegramReset();
$user->telegram_id = 0;
$user->save();
return $response->withStatus(302)->withHeader('Location', '/user/edit');
}
@ -1902,7 +1797,6 @@ class UserController extends BaseController
{
$user = $this->user;
$user->clean_link();
$user->cleanSubCache();
return $response->withStatus(302)->withHeader('Location', '/user');
}
@ -1978,11 +1872,8 @@ class UserController extends BaseController
$user->obfs = $scheme['obfs'];
$user->save();
$user->cleanSubCache();
$res['ret'] = 1;
$res['msg'] = '切换' . $scheme['name'] . '成功';
return $this->echoJson($response, $res);
}
@ -1999,7 +1890,7 @@ class UserController extends BaseController
$return .= URL::getAllUrl($user, 0, 0) . PHP_EOL;
break;
case 'ssd':
$return .= LinkController::getSSD($user, 1, [], ['type' => 'ss', 'is_mu' => 1], false) . PHP_EOL;
$return .= URL::getAllSSDUrl($user) . PHP_EOL;
break;
case 'v2ray':
$return .= URL::getAllVMessUrl($user) . PHP_EOL;
@ -2009,8 +1900,7 @@ class UserController extends BaseController
break;
}
$newResponse = $response->withHeader('Content-type', ' application/octet-stream; charset=utf-8')->withHeader('Cache-Control', 'no-store, no-cache, must-revalidate')->withHeader('Content-Disposition', ' attachment; filename=node.txt');
$newResponse->write($return);
$newResponse->getBody()->write($return);
return $newResponse;
}
@ -2025,127 +1915,6 @@ class UserController extends BaseController
return $this->view()->assign('logs', $logs)->assign('iplocation', $iplocation)->display('user/subscribe_log.tpl');
}
public function getmoney($request, $response, $args)
{
$user = $this->user;
$res['money'] = $user->money;
$res['ret'] = 1;
return $this->echoJson($response, $res);
}
public function getPlanInfo($request, $response, $args)
{
$plan_time = $request->getQueryParams()['time'];
$plan_num = $request->getQueryParams()['num'];
if (empty($plan_num) || empty($plan_time)) {
$res['ret'] = 0;
return $this->echoJson($response, $res);
}
$shop_id = (MalioConfig::get('plan_shop_id'))[$plan_num][$plan_time];
$shop = Shop::where('id', $shop_id)->first();
$res['id'] = $shop_id;
$res['name'] = $shop->name;
$res['price'] = $shop->price;
$res['ret'] = 1;
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');
$shop = Shop::where('id', $shopId)->where('status', 1)->first();
if ($shop == null) {
$res['ret'] = 0;
$res['msg'] = '非法请求';
return $response->getBody()->write(json_encode($res));
}
$price = $shop->price;
$user = $this->user;
if (!$user->isLogin) {
$res['ret'] = -1;
return $response->getBody()->write(json_encode($res));
}
if (bccomp($user->money, $price, 2) == -1) {
$res['ret'] = 0;
$res['msg'] = '喵喵喵~ 当前余额不足,总价为' . $price . '元。</br><a href="/user/code">点击进入充值界面</a>';
return $response->getBody()->write(json_encode($res));
}
$user->money = bcsub($user->money, $price, 2);
$traffic = $shop->bandwidth();
$user->transfer_enable += $traffic * 1024 * 1024 * 1024;
$user->save();
$bought = new Bought();
$bought->userid = $user->id;
$bought->shopid = $shop->id;
$bought->datetime = time();
$bought->coupon = '';
$bought->renew = 0;
$bought->price = $price;
$bought->save();
$res['ret'] = 1;
$res['msg'] = '购买成功';
return $response->getBody()->write(json_encode($res));
}
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();
@ -2174,12 +1943,6 @@ class UserController extends BaseController
$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';
}
@ -2197,41 +1960,9 @@ class UserController extends BaseController
$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));
$newResponse->getBody()->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,7 +68,6 @@ 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'),
);
@ -438,126 +437,4 @@ class VueController extends BaseController
return $response->getBody()->write(json_encode($res));
}
/**
* @param Request $requesr
* @param Response $response
* @param array $args
*/
public function getNodeInfo($request, $response, $args): ResponseInterface
{
$user = $this->user;
$id = $args['id'];
$mu = $request->getQueryParam('ismu');
$relay_rule_id = $request->getQueryParam('relay_rule');
$node = Node::find($id);
if ($node == null) {
return $response->withJson([null]);
}
switch ($node->sort) {
case 0:
if ((($user->class >= $node->node_class
&& ($user->node_group == $node->node_group || $node->node_group == 0)) || $user->is_admin)
&& ($node->node_bandwidth_limit == 0 || $node->node_bandwidth < $node->node_bandwidth_limit)
) {
return $response->withJson([
'ret' => 1,
'nodeInfo' => [
'node' => $node,
'user' => $user,
'mu' => $mu,
'relay_rule_id' => $relay_rule_id,
'URL' => URL::class,
],
]);
}
break;
case 1:
if ($user->class >= $node->node_class
&& ($user->node_group == $node->node_group || $node->node_group == 0)
) {
$email = $user->email;
$email = Radius::GetUserName($email);
$json_show = 'VPN 信息<br>地址:' . $node->server
. '<br>用户名:' . $email . '<br>密码:' . $this->user->passwd
. '<br>支持方式:' . $node->method . '<br>备注:' . $node->info;
return $response->write(
$this->view()->assign('json_show', $json_show)->fetch('user/nodeinfovpn.tpl')
);
}
break;
case 2:
if ($user->class >= $node->node_class
&& ($user->node_group == $node->node_group || $node->node_group == 0)) {
$email = $user->email;
$email = Radius::GetUserName($email);
$json_show = 'SSH 信息<br>地址:' . $node->server
. '<br>用户名:' . $email . '<br>密码:' . $this->user->passwd
. '<br>支持方式:' . $node->method . '<br>备注:' . $node->info;
return $response->write(
$this->view()->assign('json_show', $json_show)->fetch('user/nodeinfossh.tpl')
);
}
break;
case 5:
if ($user->class >= $node->node_class
&& ($user->node_group == $node->node_group || $node->node_group == 0)) {
$email = $user->email;
$email = Radius::GetUserName($email);
$json_show = 'Anyconnect 信息<br>地址:' . $node->server
. '<br>用户名:' . $email . '<br>密码:' . $this->user->passwd
. '<br>支持方式:' . $node->method . '<br>备注:' . $node->info;
return $response->write(
$this->view()->assign('json_show', $json_show)->fetch('user/nodeinfoanyconnect.tpl')
);
}
break;
case 10:
if ((($user->class >= $node->node_class
&& ($user->node_group == $node->node_group || $node->node_group == 0)) || $user->is_admin)
&& ($node->node_bandwidth_limit == 0 || $node->node_bandwidth < $node->node_bandwidth_limit)) {
return $response->withJson([
'ret' => 1,
'nodeInfo' => [
'node' => $node,
'user' => $user,
'mu' => $mu,
'relay_rule_id' => $relay_rule_id,
'URL' => URL::class,
],
]);
}
break;
case 13:
if ((($user->class >= $node->node_class
&& ($user->node_group == $node->node_group || $node->node_group == 0)) || $user->is_admin)
&& ($node->node_bandwidth_limit == 0 || $node->node_bandwidth < $node->node_bandwidth_limit)) {
return $response->withJson([
'ret' => 1,
'nodeInfo' => [
'node' => $node,
'user' => $user,
'mu' => $mu,
'relay_rule_id' => $relay_rule_id,
'URL' => URL::class,
],
]);
}
break;
}
// Default and judgement fail return
return $response->withJson([
'ret' => 0,
'nodeInfo' => [
'message' => ':)',
],
]);
}
}

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

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

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

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

@ -1,32 +1,46 @@
<?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
{
/**
* @param \Slim\Http\Request $request
* @param \Slim\Http\Response $response
* @param callable $next
*
* @return \Slim\Http\Response
*/
public function __invoke($request, $response, $next)
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
{
$key = $request->getQueryParam('key');
$key = Helper::getParam($request, 'key');
if ($key === null) {
return $response->withjson([
'ret' => 0,
'data' => 'Your key is null.'
]);
$res['ret'] = 0;
$res['data'] = 'null';
$response->getBody()->write(json_encode($res));
return $response;
}
$auth = false;
$keys = Config::getMuKey();
$auth = in_array($key, $keys);
foreach ($keys as $k) {
if ($key == $k) {
$auth = true;
break;
}
}
if (Config::get('checkNodeIp')){
$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'] = 'source is invalid, Your ip address is ' . $_SERVER['REMOTE_ADDR'];
$response->getBody()->write(json_encode($res));
return $response;
}
}
if ($auth == false) {
$res['ret'] = 0;
@ -35,16 +49,7 @@ class Mod_Mu
return $response;
}
if (Config::get('checkNodeIp') === true){
$node = Node::where('node_ip', 'LIKE', $_SERVER['REMOTE_ADDR'] . '%')->first();
if ($auth === false || ($node === null && $_SERVER['REMOTE_ADDR'] != '127.0.0.1')) {
return $response->withJson([
'ret' => 0,
'data' => 'Token or IP is invalid. Now, your IP address is ' . $_SERVER['REMOTE_ADDR']
]);
}
}
return $next($request, $response);
$response = $next($request, $response);
return $response;
}
}

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

@ -32,65 +32,4 @@ 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);
}
}

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

@ -6,9 +6,8 @@ namespace App\Models;
* Node Model
*/
use App\Utils\{Tools, URL};
use App\Utils\Tools;
use App\Utils\DNSoverHTTPS;
class Node extends Model
{
protected $connection = 'default';
@ -173,21 +172,4 @@ 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'];
}
}

@ -3,7 +3,6 @@
namespace App\Models;
use App\Services\Config;
use App\Services\MalioConfig;
class Shop extends Model
{
@ -136,16 +135,11 @@ 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;
$user->last_day_t = 0;
} elseif (MalioConfig::get('reset_bandwidth_and_expire_date_when_change_class') == true && $user->class != $content['class']) {
$user->transfer_enable = $value * 1024 * 1024 * 1024;
$user->u = 0;
$user->d = 0;
$user->last_day_t = 0;
} else {
$user->transfer_enable += $value * 1024 * 1024 * 1024;
}
@ -166,7 +160,7 @@ class Shop extends Model
}
break;
case 'class':
if (Config::get('enable_bought_extend') == true) {
if (Config::get('enable_bought_extend') == 'true') {
if ($user->class == $value) {
$user->class_expire = date('Y-m-d H:i:s', strtotime($user->class_expire) + $content['class_expire'] * 86400);
} else {

@ -1,12 +0,0 @@
<?php
namespace App\Models;
/**
* SmsVerify Model
*/
class SmsVerify extends Model
{
protected $connection = 'default';
protected $table = 'sms_verify';
}

@ -1,36 +0,0 @@
<?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 App\Utils\URL;
use Ramsey\Uuid\Uuid;
use App\Models\DetectLog;
use App\Models\DetectBanLog;
@ -39,13 +39,8 @@ class User extends Model
public function getGravatarAttribute()
{
$email_su=substr($this->attributes['email'],-6);
$email_pre=substr($this->attributes['email'],0,-7);
if($email_su=="qq.com" and is_numeric($email_pre)) {
return "https://q4.qlogo.cn/g?b=qq&nk=".$this->attributes['email']."&s=3";
}
$hash = md5(strtolower(trim($this->attributes['email'])));
return "https://secure.gravatar.com/avatar/".$hash;
return 'https://gravatar.loli.net/avatar/' . $hash;
}
public function isAdmin()
@ -139,59 +134,43 @@ class User extends Model
public function getUuid()
{
// return Uuid::uuid3(
// Uuid::NAMESPACE_DNS,
// $this->attributes['id'] . '|' . $this->attributes['passwd']
// )->toString();
return $this->attributes['uuid'];
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;
}
/*
* 总流量
*/
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'];
@ -199,75 +178,18 @@ class User extends Model
return Tools::flowAutoShow($transfer_enable - $total);
}
/*
* 剩余流量占总流量的百分比
*/
public function unusedTrafficPercent()
{
$transferEnable = $this->attributes['transfer_enable'];
if ($transferEnable == 0) {
return 0;
}
$unusedTraffic = $transferEnable - ($this->attributes['u'] + $this->attributes['d']);
$percent = $unusedTraffic / $transferEnable;
$percent = round($percent, 2);
$percent *= 100;
return $percent;
}
/*
* 今天使用的流量
*/
public function TodayusedTraffic()
{
$total = $this->attributes['u'] + $this->attributes['d'] - $this->attributes['last_day_t'];
return Tools::flowAutoShow($total);
}
/*
* 今天使用的流量占总流量的百分比
*/
public function TodayusedTrafficPercent()
{
$transferEnable = $this->attributes['transfer_enable'];
if ($transferEnable == 0) {
return 0;
}
$TodayusedTraffic = $this->attributes['u'] + $this->attributes['d'] - $this->attributes['last_day_t'];
$percent = $TodayusedTraffic / $transferEnable;
$percent = round($percent, 2);
$percent *= 100;
return $percent;
}
/*
* 今天之前已使用的流量
*/
public function LastusedTraffic()
{
$total = $this->attributes['last_day_t'];
return Tools::flowAutoShow($total);
}
/*
* 今天之前已使用的流量占总流量的百分比
*/
public function LastusedTrafficPercent()
{
$transferEnable = $this->attributes['transfer_enable'];
if ($transferEnable == 0) {
return 0;
}
$LastusedTraffic = $this->attributes['last_day_t'];
$percent = $LastusedTraffic / $transferEnable;
$percent = round($percent, 2);
$percent *= 100;
return $percent;
}
/*
* 是否可以签到
*/
public function isAbleToCheckin()
{
$last = $this->attributes['last_check_in_time'];
@ -429,7 +351,6 @@ class User extends Model
$this->attributes['method'],
$this->attributes['protocol'],
$this->attributes['obfs'],
$this->attributes['obfs_param'],
$this->online_ip_count(),
$this->lastSsTime(),
$used_traffic,
@ -474,8 +395,8 @@ class User extends Model
// 当前解封时间
public function relieve_time()
{
$logs = DetectBanLog::where('user_id', $this->attributes['id'])->orderBy('id', 'desc')->first();
if ($this->attributes['enable'] == 0 && $logs != null) {
if ($this->attributes['detect_ban'] == 1) {
$logs = DetectBanLog::where('user_id', $this->attributes['id'])->orderBy("id", "desc")->first();
$time = ($logs->end_time + $logs->ban_time * 60);
return date('Y-m-d H:i:s', $time);
} else {
@ -496,336 +417,44 @@ 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 yesterdayIncome()
{ $number = Code::where('usedatetime', 'like', date('Y-m-d%', strtotime('-1 days')))->sum('number');
return is_null($number)?0:$number;
}
public function paidUserCount()
public function todayIncome()
{
return self::where('class', '!=', '0')->count();
$number = Code::where('usedatetime', 'like', date('Y-m-d%'))->sum('number');
return is_null($number)?0:$number;
}
public function disableReason()
public function thisMonthIncome()
{
$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;
$number = Code::where('usedatetime', 'like', date('Y-m%'))->sum('number');
return is_null($number)?0:$number;
}
/**
* 清理订阅缓存
*/
public function cleanSubCache()
public function lastMonthIncome()
{
$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
];
$number = Code::where('usedatetime', 'like', date('Y-m%', strtotime('-1 months')))->sum('number');
return is_null($number)?0:$number;
}
/**
* 重置端口
*/
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 totalIncome()
{
$number = Code::where('usedatetime', 'like', date('%'))->sum('number');
return is_null($number)?0:$number;
}
/**
* 指定端口
*/
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 paidUserCount()
{
return self::where('class', '!=', '0')->count();
}
public function valid_use_loop()
public function disableReason()
{
$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 '多个有效套餐无法显示.';
$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;
}
}

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

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

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

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

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

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

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

@ -2,8 +2,6 @@
namespace App\Services;
use App\Models\GConfig;
class Config
{
// TODO: remove
@ -12,22 +10,12 @@ class Config
return $_ENV[$key];
}
public static function getdb($key)
{
$value = GConfig::find($key);
if ($value === null) {
$value = DefaultConfig::firstOrCreate($key);
}
return $value->value;
}
public static function getPublicConfig()
{
return [
'appName' => self::get('appName'),
'version' => VERSION,
'baseUrl' => self::get('baseUrl'),
'subUrl' => self::get('subUrl'),
'min_port' => self::get('min_port'),
'max_port' => self::get('max_port'),
'checkinMin' => self::get('checkinMin'),
@ -43,6 +31,7 @@ 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'),
@ -65,10 +54,7 @@ class Config
'auto_detect_ban_number' => self::get('auto_detect_ban_number'),
'auto_detect_ban_time' => self::get('auto_detect_ban_time'),
'auto_detect_ban' => self::get('auto_detect_ban'),
'subscribe_client' => self::get('subscribe_client'),
'enable_sub_cache' => self::get('enable_sub_cache'),
'use_new_telegram_bot' => self::get('use_new_telegram_bot'),
'subscribe_client_url' => self::get('subscribe_client_url'),
'subscribe_client' => self::get('subscribe_client')
];
}

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

@ -14,40 +14,19 @@ use App\Models\User;
use App\Models\Code;
use App\Services\Config;
use App\Utils\Telegram;
use Slim\Http\{Request, Response};
abstract class AbstractPayment
{
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
abstract public function purchase($request, $response, $args);
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
abstract public function notify($request, $response, $args);
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
abstract public function getPurchaseHTML();
abstract public function getReturnHTML($request, $response, $args);
/**
* @param Request $request
* @param Response $response
* @param array $args
*/
abstract public function getStatus($request, $response, $args);
abstract public function getPurchaseHTML();
public function postPayment($pid, $method)
{
$p = Paylist::where('tradeno', $pid)->first();
@ -83,58 +62,6 @@ 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,46 +69,6 @@ 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();

@ -165,7 +165,7 @@ class BitPay extends AbstractPayment
public function getPurchaseHTML()
{
return 0;
return View::getSmarty()->fetch('user/bitpay.tpl');
}
public function getReturnHTML($request, $response, $args)

@ -12,7 +12,6 @@ namespace App\Services\Gateway;
use App\Models\Paylist;
use App\Services\Auth;
use App\Services\Config;
use App\Services\MalioConfig;
use App\Services\View;
class BitPayX extends AbstractPayment
@ -87,38 +86,29 @@ class BitPayX extends AbstractPayment
{
$price = $request->getParam('price');
$type = $request->getParam('type');
$mobile = $request->getParam('mobile');
// file_put_contents(BASE_PATH.'/bitpay_purchase.log', $price . " " . $type . "\r\n", FILE_APPEND);
if ($price <= 0) {
return json_encode(['errcode' => -1, 'errmsg' => '请输入合理的金额。']);
}
if (MalioConfig::get('bitpyax_alipay_type') == 'ALIGLOBAL' && $type == 'ALIPAY') {
$type = 'ALIGLOBAL';
}
$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';
if ($type === 'WECHAT') {
$data['pay_currency'] = $type;
}
if ($type === 'ALIGLOBAL' || $type === 'ALIPAY') {
if ($type === 'WECHAT' || $type === 'ALIPAY') {
$data['pay_currency'] = $type;
}
$data['mobile'] = $mobile;
$data['title'] = '支付单号:' . $pl->tradeno;
$data['description'] = '充值:' . $price . ' 元';
$data['callback_url'] = Config::get('baseUrl') . '/payment/notify';
$data['success_url'] = Config::get('baseUrl') . '/user/payment/return?merchantTradeNo=';
$data['success_url'] .= $pl->tradeno;
$data['cancel_url'] = Config::get('baseUrl') . '/user/code';
$data['cancel_url'] = $data['success_url'];
$str_to_sign = $this->prepareSignId($pl->tradeno);
$data['token'] = $this->sign($str_to_sign);
@ -126,89 +116,13 @@ class BitPayX extends AbstractPayment
$result['pid'] = $pl->tradeno;
// file_put_contents(BASE_PATH.'/bitpay_purchase.log', json_encode($data)."\r\n", FILE_APPEND);
// file_put_contents(BASE_PATH.'/bitpay_purchase.log', json_encode($result)."\r\n", FILE_APPEND);
$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 = $base_url . $result['invoice']['qrcode'];
$click_url = "#";
}
}
// file_put_contents(BASE_PATH.'/bitpay_purchase.log', json_encode($result) . "\r\n" . $qrcode_url . "\r\n", FILE_APPEND);
return json_encode(array('url' => $result['payment_url'], 'qrcode_url' => $qrcode_url, 'click_url' => $click_url, 'errcode' => 0, 'pid' => $pl->tradeno));
return json_encode(array('url' => $result['payment_url'], 'errcode' => 0, 'pid' => $pl->id));
}
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 === '') {
@ -236,7 +150,7 @@ class BitPayX extends AbstractPayment
$isPaid = $data !== null && $data['status'] !== null && $data['status'] === 'PAID';
// file_put_contents(BASE_PATH.'/bitpay_notify.log', $resultVerify."\r\n".$isPaid."\r\n", FILE_APPEND);
if ($resultVerify && $isPaid) {
$this->postPayment($data['merchant_order_id'], 'BitPayX ' . $data['merchant_order_id']);
$this->postPayment($data['merchant_order_id'], 'BitPayX');
// echo 'SUCCESS';
$return = [];
$return['status'] = 200;
@ -251,7 +165,7 @@ class BitPayX extends AbstractPayment
public function getPurchaseHTML()
{
return 1;
return View::getSmarty()->fetch('user/bitpayx.tpl');
}
public function getReturnHTML($request, $response, $args)
@ -284,5 +198,4 @@ class BitPayX extends AbstractPayment
// file_put_contents(BASE_PATH.'/bitpay_status_success.log', json_encode($return)."\r\n", FILE_APPEND);
return json_encode($return);
}
}
}

@ -89,7 +89,8 @@ class Codepay extends AbstractPayment
$query = $urls . '&sign=' . md5($sign . $codepay_key); //创建订单所需的参数
$url = 'https://codepay.fateqq.com/creat_order/?' . $query; //支付页面
return json_encode(['code' => 0, 'url' => $url]);
header('Location:' . $url);
}
public function notify($request, $response, $args)

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

@ -1,236 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: tonyzou
* Date: 2018/9/24
* Time: 下午9:24
*/
namespace App\Services\Gateway;
use App\Services\Auth;
use App\Services\Config;
use App\Models\Paylist;
use App\Services\View;
use Exception;
use Omnipay\Omnipay;
class F2Fpay_PAYJS extends AbstractPayment
{
// f2fpay
private function createGateway()
{
$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');
$gateway->setNotifyUrl($notifyUrl);
return $gateway;
}
// f2fpay end
// payjs
public function __construct()
{
$this->appSecret = Config::get('payjs_key');
$this->gatewayUri = 'https://payjs.cn/api/';
}
public function prepareSign($data)
{
$data['mchid'] = Config::get('payjs_mchid');
$data = array_filter($data);
ksort($data);
return http_build_query($data);
}
public function sign($data)
{
return strtoupper(md5(urldecode($data) . '&key=' . $this->appSecret));
}
public function verify($data, $signature)
{
$mySign = $this->sign($data);
return $mySign === $signature;
}
public function post($data, $type = 'pay')
{
if ($type == 'pay') {
$this->gatewayUri .= 'cashier';
} elseif ($type == 'refund') {
$this->gatewayUri .= 'refund';
} else {
$this->gatewayUri .= 'check';
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $this->gatewayUri);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$data = curl_exec($curl);
curl_close($curl);
return $data;
}
public function query($tradeNo)
{
$data['payjs_order_id'] = $tradeNo;
$params = $this->prepareSign($data);
$data['sign'] = $this->sign($params);
return json_decode($this->post($data, $type = 'query'), true);
}
public function refund($merchantTradeNo)
{
$data['payjs_order_id'] = $merchantTradeNo;
$params = $this->prepareSign($data);
$data['sign'] = $this->sign($params);
return $this->post($data, 'refund');
}
// payjs end
public function purchase($request, $response, $args)
{
$payment = $request->getParam('payment');
if ($payment == 'alipay') {
$amount = $request->getParam('amount');
$user = Auth::getUser();
if ($amount == '') {
$res['ret'] = 0;
$res['msg'] = '订单金额错误:' . $amount;
return $response->getBody()->write(json_encode($res));
}
$pl = new Paylist();
$pl->userid = $user->id;
$pl->tradeno = self::generateGuid();
$pl->total = $amount;
$pl->save();
$gateway = $this->createGateway();
$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['ret'] = 1;
$return['qrcode'] = $qrCodeContent;
$return['amount'] = $pl->total;
$return['pid'] = $pl->tradeno;
return json_encode($return);
} else if ($payment == 'wechat') {
$price = $request->getParam('amount');
if ($price <= 0) {
return json_encode(['ret' => -1, 'errmsg' => '非法的金额.']);
}
$user = Auth::getUser();
$pl = new Paylist();
$pl->userid = $user->id;
$pl->total = $price;
$pl->tradeno = self::generateGuid();
$pl->save();
$data['mchid'] = Config::get('payjs_mchid');
$data['out_trade_no'] = $pl->tradeno;
$data['total_fee'] = (float) $price * 100;
$data['notify_url'] = Config::get('baseUrl') . '/payment/notify?way=payjs';
$params = $this->prepareSign($data);
$data['sign'] = $this->sign($params);
$url = 'https://payjs.cn/api/cashier?' . http_build_query($data);
return json_encode(['ret' => 1, 'qrcode' => $url, 'pid' => $data['out_trade_no']]);
} else {
$res['ret'] = 0;
$res['msg'] = 'payment参数缺失';
return $response->getBody()->write(json_encode($res));
}
}
public function notify($request, $response, $args)
{
$way = $_GET['way'];
if ($way == 'payjs') {
$data = $_POST;
if($data['return_code'] == 1){
// 验证签名
$in_sign = $data['sign'];
unset($data['sign']);
$data = array_filter($data);
ksort($data);
$sign = strtoupper(md5(urldecode(http_build_query($data) . '&key=' . $this->appSecret)));
$resultVerify = $sign ? true : false;
//$str_to_sign = $this->prepareSign($data);
//$resultVerify = $this->verify($str_to_sign, $request->getParam('sign'));
if ($resultVerify) {
// 验重
$p = Paylist::where('tradeno', '=', $data['out_trade_no'])->first();
$money = $p->total;
if ($p->status != 1) {
$this->postPayment($data['out_trade_no'], '微信支付');
echo 'SUCCESS';
} else {
echo 'ERROR';
}
} else {
echo 'FAIL2';
}
} else {
echo 'FAIL1';
}
} else {
$gateway = $this->createGateway();
$aliRequest = $gateway->completePurchase();
$aliRequest->setParams($_POST);
try {
/** @var \Omnipay\Alipay\Responses\AopCompletePurchaseResponse $response */
$aliResponse = $aliRequest->send();
$pid = $aliResponse->data('out_trade_no');
if ($aliResponse->isPaid()) {
$this->postPayment($pid, '支付宝当面付 ' . $pid);
die('success'); //The response should be 'success' only
}
} catch (Exception $e) {
die('fail');
}
}
}
public function getPurchaseHTML()
{
return 1;
}
public function getStatus($request, $response, $args)
{
$p = Paylist::where('tradeno', $_POST['pid'])->first();
$return['ret'] = 1;
$return['result'] = $p->status;
return json_encode($return);
}
public function getReturnHTML($request, $response, $args)
{
return 0;
}
}

@ -16,11 +16,11 @@
*/
function createLinkstring($para) {
$arg = "";
foreach ($para as $key=>$val){
while (list ($key, $val) = each ($para)) {
$arg.=$key."=".$val."&";
}
//去掉最后一个&字符
$arg = rtrim($arg,'&');
$arg = substr($arg,0,count($arg)-2);
//如果存在转义字符,那么去掉转义
if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}
@ -34,11 +34,11 @@ function createLinkstring($para) {
*/
function createLinkstringUrlencode($para) {
$arg = "";
foreach ($para as $key=>$val){
$arg.=$key."=".$val."&";
}
//去掉最后一个&字符
$arg = rtrim($arg,'&');
while (list ($key, $val) = each ($para)) {
$arg.=$key."=".urlencode($val)."&";
}
//去掉最后一个&字符
$arg = substr($arg,0,count($arg)-2);
//如果存在转义字符,那么去掉转义
if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}
@ -52,10 +52,10 @@ function createLinkstringUrlencode($para) {
*/
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];
}
while (list ($key, $val) = each ($para)) {
if($key == "sign" || $key == "sign_type" || $val == "")continue;
else $para_filter[$key] = $para[$key];
}
return $para_filter;
}
/**

@ -118,4 +118,4 @@ class AlipayNotify {
return $responseTxt;
}
}
?>
?>

@ -83,7 +83,7 @@ class AlipaySubmit {
$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){
while (list ($key, $val) = each ($para)) {
$sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
}

@ -250,4 +250,4 @@ class IDtPay extends AbstractPayment
// file_put_contents(BASE_PATH.'/bitpay_status_success.log', json_encode($return)."\r\n", FILE_APPEND);
return json_encode($return);
}
}
}

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

@ -150,7 +150,7 @@ class PAYJS extends AbstractPayment
}
public function getPurchaseHTML()
{
return 1;
return View::getSmarty()->fetch('user/payjs.tpl');
}
public function getReturnHTML($request, $response, $args)
{

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

@ -1,174 +0,0 @@
<?php
namespace App\Services\Gateway;
use App\Services\Auth;
use App\Services\Config;
use App\Models\Paylist;
use App\Services\View;
use App\Services\MalioConfig;
use Exception;
use App\Services\Gateway\PayssionClient;
class Payssion extends AbstractPayment
{
public function purchase($request, $response, $args)
{
$price = $request->getParam('price');
$type = $request->getParam('type');
$user = Auth::getUser();
if ($type != 'alipay' and $type != 'unionpay') {
return json_encode(['errcode' => -1, 'errmsg' => 'wrong payment.']);
}
if ($type == 'alipay') {
$type = 'alipay_cn';
} else if ($type == 'unionpay') {
$type = 'unionpay_cn';
}
$pl = new Paylist();
$pl->userid = $user->id;
$pl->total = $price;
$pl->tradeno = self::generateGuid();
$pl->save();
$payssion = new PayssionClient(Config::get('payssion_api_key'), Config::get('payssion_secret_key'));
$payssion_response = null;
try {
//$type = 'dotpay_pl'; // for test
$payssion_response = $payssion->create(array(
'amount' => $price,
'currency' => 'CNY',
'pm_id' => $type,
'description' => 'Shadowsocks Product',
'order_id' => $pl->tradeno,
'return_url' => Config::get('baseUrl').'/user/payment/return' //optional, the return url after payments (for both of paid and non-paid)
));
} catch (\Exception $e) {
$res['ret'] = 0;
$res['msg'] = "创建订单失败。".$e->getMessage();
return $response->getBody()->write(json_encode($res));
}
if ($payssion->isSuccess()) {
$todo = $payssion_response['todo'];
if ($todo) {
$todo_list = explode('|', $todo);
if (in_array("redirect", $todo_list)) {
$res['ret'] = 1;
$res['url'] = $payssion_response['redirect_url'];
$res['pid'] = $pl->id;
return $response->getBody()->write(json_encode($res));
}
} else {
//just in case, should not be here
}
} else {
return json_encode($payssion_response);
}
$res['ret'] = 0;
$res['msg'] = "购买失败";
return $response->getBody()->write(json_encode($res));
}
public function notify($request, $response, $args)
{
$api_key=Config::get('payssion_api_key');
$pm_id=$request->getParam('pm_id');
$amount=$request->getParam('amount');
$currency=$request->getParam('currency');
$order_id=$request->getParam('order_id');
$secret_key=Config::get('payssion_secret_key');
$state=$request->getParam('state');
$msg = implode('|', array($api_key, $pm_id, $amount, $currency,$order_id,$state, $secret_key));
if($request->getParam('notify_sig')!= md5($msg)){
return;
}
$state_code=3;
switch ($state) {
case 'error':
$state_code=2;
break;
case 'pending':
$state_code=3;
break;
case 'completed':
$state_code=4;
break;
case 'paid_partial':
$state_code=5;
break;
case 'failed':
$state_code=6;
break;
case 'cancelled':
$state_code=7;
break;
case 'expired':
$state_code=8;
break;
case 'refunded':
$state_code=9;
break;
case 'refund_pending':
$state_code=10;
break;
case 'refund_failed':
$state_code=11;
break;
case 'refund_cancelled':
$state_code=12;
break;
case 'chargeback':
$state_code=13;
break;
default:
$state_code=14;
break;
}
if ($state_code != 4) {
return;
}
$type = null;
if ($pm_id == 'alipay_cn') {
$type = '支付宝支付';
} else if ($pm_id == 'unionpay_cn') {
$type = '银联支付';
}
$order = Paylist::where('tradeno', '=', $order_id)->first();
if ($order->status != 1) {
$this->postPayment($order_id, 'Payssion '.$type);
echo 'SUCCESS';
} else {
echo 'ERROR';
}
}
public function getPurchaseHTML()
{
return 1;
}
public function getReturnHTML($request, $response, $args)
{
$pid = $_GET['order_id'];
$p = Paylist::where('tradeno', '=', $pid)->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)
{
return;
}
}

@ -1,313 +0,0 @@
<?php
namespace App\Services\Gateway;
/**
* Client library for Payssion API.
*/
class PayssionClient
{
/**
* @const string
*/
const VERSION = '1.3.0.160612';
/**
* @var string
*/
protected $api_url;
protected $api_key = ''; //your api key
protected $secret_key = ''; //your secret key
protected static $sig_keys = array(
'create' => array(
'api_key', 'pm_id', 'amount', 'currency', 'order_id', 'secret_key'
),
'details' => array(
'api_key', 'transaction_id', 'order_id', 'secret_key'
)
);
/**
* @var array
*/
protected $http_errors = array
(
400 => '400 Bad Request',
401 => '401 Unauthorized',
500 => '500 Internal Server Error',
501 => '501 Not Implemented',
502 => '502 Bad Gateway',
503 => '503 Service Unavailable',
504 => '504 Gateway Timeout',
);
/**
* @var bool
*/
protected $is_success = false;
/**
* @var array
*/
protected $allowed_request_methods = array(
'get',
'put',
'post',
'delete',
);
/**
* @var boolean
*/
protected $ssl_verify = true;
/**
* Constructor
*
* @param string $api_key Payssion App api_key
* @param string $secret_key Payssion App secret_key
* @param bool $is_livemode false if you use sandbox api_key and true for live mode
*/
public function __construct($api_key, $secret_key, $is_livemode = true)
{
$this->api_key = $api_key;
$this->secret_key = $secret_key;
$validate_params = array
(
false === extension_loaded('curl') => 'The curl extension must be loaded for using this class!',
false === extension_loaded('json') => 'The json extension must be loaded for using this class!',
empty($this->api_key) => 'api_key is not set!',
empty($this->secret_key) => 'secret_key is not set!',
);
$this->checkForErrors($validate_params);
$this->setLiveMode($is_livemode);
}
/**
* Set LiveMode
*
* @param bool $is_livemode
*/
public function setLiveMode($is_livemode)
{
if ($is_livemode) {
$this->api_url = 'https://www.payssion.com/api/v1/payment/';
} else {
$this->api_url = 'http://sandbox.payssion.com/api/v1/payment/';
}
}
/**
* Set Api URL
*
* @param string $url Api URL
*/
public function setUrl($url)
{
$this->api_url = $url;
}
/**
* Sets SSL verify
*
* @param bool $ssl_verify SSL verify
*/
public function setSSLverify($ssl_verify)
{
$this->ssl_verify = $ssl_verify;
}
/**
* Request state getter
*
* @return bool
*/
public function isSuccess()
{
return $this->is_success;
}
/**
* create payment order
*
* @param $params create Params
* @return array
*/
public function create(array $params)
{
return $this->call(
'create',
'post',
$params
);
}
/**
* get payment details
*
* @param $params query Params
* @return array
*/
public function getDetails(array $params)
{
return $this->call(
'details',
'post',
$params
);
}
/**
* Method responsible for preparing, setting state and returning answer from rest server
*
* @param string $method
* @param string $request
* @param array $params
* @return array
*/
protected function call($method, $request, $params)
{
$this->is_success = false;
$validate_params = array
(
false === is_string($method) => 'Method name must be string',
false === $this->checkRequestMethod($request) => 'Not allowed request method type',
true === empty($params) => 'params is null',
);
$this->checkForErrors($validate_params);
$params['api_key'] = $this->api_key;
$params['api_sig'] = $this->getSig($params, self::$sig_keys[$method]);
$response = $this->pushData($method, $request, $params);
$response = json_decode($response, true);
if (isset($response['result_code']) && 200 == $response['result_code'])
{
$this->is_success = true;
}
return $response;
}
/**
* Checking error mechanism
*
* @param array $validateArray
* @throws Exception
*/
protected function getSig(array &$params, array $sig_keys)
{
$msg_array = array();
foreach ($sig_keys as $key) {
$msg_array[$key] = isset($params[$key]) ? $params[$key] : '';
}
$msg_array['secret_key'] = $this->secret_key;
$msg = implode('|', $msg_array);
$sig = md5($msg);
return $sig;
}
/**
* Checking error mechanism
*
* @param array $validateArray
* @throws Exception
*/
protected function checkForErrors(&$validate_params)
{
foreach ($validate_params as $key => $error)
{
if ($key)
{
throw new Exception($error, -1);
}
}
}
/**
* Check if method is allowed
*
* @param string $method_type
* @return bool
*/
protected function checkRequestMethod($method_type)
{
$request_method = strtolower($method_type);
if(in_array($request_method, $this->allowed_request_methods))
{
return true;
}
return false;
}
/**
* Method responsible for pushing data to server
*
* @param string $method
* @param string $method_type
* @param array|string $vars
* @return array
* @throws Exception
*/
protected function pushData($method, $method_type, $vars)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->api_url. $method);
curl_setopt($ch, CURLOPT_POST, true);
if (is_array($vars)) $vars = http_build_query($vars, '', '&');
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getHeaders());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->ssl_verify);
$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (isset($this->http_errors[$code]))
{
throw new Exception('Response Http Error - ' . $this->http_errors[$code], $code);
}
$code = curl_errno($ch);
if (0 < $code)
{
throw new Exception('Unable to connect to ' . $this->api_url . ' Error: ' . "$code :". curl_error($ch), $code);
}
curl_close($ch);
return $response;
}
protected function &getHeaders() {
$langVersion = phpversion();
$uname = php_uname();
$ua = array(
'version' => self::VERSION,
'lang' => 'php',
'lang_version' => $langVersion,
'publisher' => 'payssion',
'uname' => $uname,
);
$headers = array(
'X-Payssion-Client-User-Agent: ' . json_encode($ua),
"User-Agent: Payssion/php/$langVersion/" . self::VERSION,
'Content-Type: application/x-www-form-urlencoded',
);
return $headers;
}
}

@ -62,7 +62,7 @@ class SPay extends AbstractPayment
//header("Location: http://www.dayyun.com/pay/pay/alipay.php?".http_build_query($data));
return json_encode(['code' => 0, 'url' => 'http://h.8889838.com/pay/pay/alipay.php?' . http_build_query($data)]);
return json_encode(['code' => 0, 'url' => 'http://www.dayyun.com/pay/pay/alipay.php?' . http_build_query($data)]);
}
public function notify($request, $response, $args)

@ -1,196 +0,0 @@
<?php
namespace App\Services\Gateway;
use App\Services\Auth;
use App\Services\Config;
use App\Models\Paylist;
use App\Services\View;
use App\Services\MalioConfig;
use Exception;
use Stripe\Stripe;
use Stripe\Charge;
use Stripe\Source;
class StripePay extends AbstractPayment
{
public function __construct()
{
Stripe::setApiKey(Config::get('stripe_key'));
}
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(['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);
$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 json_encode(array('url' => $source['redirect']['url'], 'errcode' => 0, 'pid' => $pl->id));
} 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);
$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)
{
$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->postPayment($source['id'], 'Stripe '.$type);
echo 'SUCCESS';
} else {
echo 'ERROR';
}
}
break;
default:
http_response_code(400);
exit();
}
http_response_code(200);
}
public function getPurchaseHTML()
{
return 1;
}
public function getReturnHTML($request, $response, $args)
{
$pid = $_GET['source'];
$p = Paylist::where('tradeno', '=', $pid)->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('id', $_POST['pid'])->first();
$return['ret'] = 1;
$return['result'] = $p->status;
return json_encode($return);
}
}

@ -1,202 +1,151 @@
<?php
namespace App\Services\Gateway;
use App\Services\View;
use App\Services\Auth;
use App\Services\Config;
use App\Models\Paylist;
class TomatoPay extends AbstractPayment
{
public function purchase($request, $response, $args)
{
$type = $request->getParam('type');
$price = $request->getParam('price');
if($price <= 0){
return json_encode(['errcode'=>-1,'errmsg'=>"非法的金额."]);
$type = $request->getParsedBodyParam('type');
$price = $request->getParsedBodyParam('price');
if ($price <= 0) {
return $response->write(json_encode(['errcode' => -1, 'errmsg' => "非法的金额."]));
}
$user = Auth::getUser();
$settings = Config::get("tomatopay")[$type];
$settings = $_ENV['tomatopay'][$type];
$pl = new Paylist();
$pl->userid = $user->id;
$pl->total = $price;
$pl->tradeno = self::generateGuid();
$pl->save();
$fqaccount=$settings['account'];
$fqkey=$settings['token'];
$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 = "<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)
{
$type = $args['type'];
$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'];
$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']);
$fqtrade = $pl->tradeno;
$fqcny = $price;
if ($sign == $signs) {
//验重
$p = Paylist::where('tradeno', '=', $order_data['out_trade_no'])->first();
$money = $p->total;
if ($p->status != 1) {
$this->postPayment($order_data['out_trade_no'], "在线支付");
echo 'SUCCESS';
} else {
echo 'ERROR';
}
echo 'success';
if($ispost==0) header("Location: /user/code");
$signs = md5(
'mchid=' . $fqmchid . '&account=' . $fqaccount . '&cny=' . $fqcny . '&type=1&trade=' . $fqtrade . $fqkey
);
$url = 'https://b.fanqieui.com/gateways/' . $type . '.php?account='
. $fqaccount . '&mchid=' . $fqmchid . '&type=1'
. '&trade=' . $fqtrade . '&cny=' . $fqcny . '&signs=' . $signs;
$result = "<script language='javascript' type='text/javascript'>window.location.href='" . $url . "';</script>";
return $response->write(json_encode(['code' => $result, 'errcode' => 0, 'pid' => $pl->id]));
}
}else{
echo '验证失败';
public function notify($request, $response, $args)
{
$type = $args['type'];
$settings = $_ENV['tomatopay'][$type];
$order_data = $request->getParsedBody();
$signs = $order_data['sign'];
unset($order_data['sign']);
$security = $order_data;
$o = '';
foreach ($security as $k => $v) {
$o .= "$k=" . urlencode($v) . "&";
}
$sign = md5(substr($o, 0, -1) . $settings['token']);
if ($sign == $signs) {
$this->postPayment($order_data['out_trade_no'], "在线支付");
return $response->write('success');
} else {
return $response->write('failed');
}
}
public function getPurchaseHTML()
{
return '
<div class="card-inner">
<p class="card-heading">充值</p>
<h5>支付方式:</h5>
<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="wxpay">微信支付</a>
</li>
<li>
<a class="waves-attach waves-effect type" data-toggle="tab" data-pay="alipay">支付宝</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>
<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="code-update" ><span class="icon">check</span>&nbsp;充值</NOtton>
</div>
</div>
<div class="card-action-btn pull-left">
<button class="btn btn-flat waves-attach" id="tomato_pay" ><span class="icon">check</span>&nbsp;充值</NOtton>
</div>
</div>
<script>
var type = "wxpay";
var type = "alipay";
var pid = 0;
$(".type").click(function(){
type = $(this).data("pay");
});
$("#code-update").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);
}
}
}
});
});
var type = "wxpay";
var type = "alipay";
var pid = 0;
$(".type").click(function(){
type = $(this).data("pay");
});
$("#tomato_pay").click(function(){
var price = parseFloat($("#amount").val());
console.log("将要使用"+type+"方法充值"+price+"元")
if(isNaN(price)){
$("#result").modal();
$("#msg").html("非法的金额!");
}
$.ajax({
\'url\':"/user/payment/purchase",
\'data\':{
\'price\':price,
\'type\':type,
},
\'dataType\':\'json\',
\'type\':"POST",
success:function(data){
console.log(data);
if(data.errcode==-1){
$("#result").modal();
$("#msg").html(data.errmsg);
}
if(data.errcode==0){
pid = data.pid;
if(type=="wxpay"){
$("#result").modal();
$("#msg").html("正在跳转到微信..."+data.code);
}else if(type=="alipay"){
$("#result").modal();
$("#msg").html("正在跳转到支付宝..."+data.code);
}
}
}
});
setTimeout(f, 1000);
});
</script>
';
}
public function getReturnHTML($request, $response, $args)
{
// TODO: Implement getReturnHTML() method.
}
public function getStatus($request, $response, $args)
{
// TODO: Implement getStatus() method.
$return = [];
$p = Paylist::where('tradeno', $_POST['pid'])->first();
$return['ret'] = 1;
$return['result'] = $p->status;
return json_encode($return);
}
}

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

@ -1,131 +0,0 @@
<?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) , '+/', '-_') , '=');
}
}

@ -1,335 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/10/10
* Time: 17:03
*/
namespace App\Services\Gateway;
use App\Models\Paylist;
use App\Services\Auth;
use App\Services\Config;
class YftPay extends AbstractPayment
{
private $user;
public function __construct()
{
$this->user = Auth::getUser();
}
public function purchase($request, $response, $args)
{
return $this->constructPayPara($request);
}
public function notify($request, $response, $args)
{
$yftUtil = new YftPayUtil();
$pay_config = new YftPayConfig();
$pay_config->init();
//价格
$total_fee = $request->getParam("total_fee");
//易付通返回的订单号
$yft_order_no = $request->getParam("trade_no");
//面板生成的订单号
$ss_order_no = $request->getParam("out_trade_no");
//订单说明
$subject = $request->getParam("subject");
//付款状态
$trade_status = $request->getParam("trade_status");
//加密验证字符串
$sign = $request->getParam("sign");
$verifyNotify = $yftUtil->md5Verify(floatval($total_fee), $ss_order_no, $yft_order_no, $trade_status, $sign);
if ($verifyNotify && $trade_status == 'TRADE_SUCCESS') {//验证成功
/*
加入您的入库及判断代码;
>>>>>>>!!!为了保证数据传达到回调地址,会请求4次。所以必须要先判断订单状态,然后再插入到数据库,这样后面即使请求3次,也不会造成订单重复!!!!<<<<<<<
判断返回金额与实金额是否想同;
判断订单当前状态;
完成以上才视为支付成功
*/
$order = Paylist::where('tradeno', $ss_order_no)->first();
if ($order->status == 0) {
$this->postPayment($ss_order_no, '易付 充值');
return "success";
}
return "fail";
} else {
//验证失败
return "fail";
}
}
/**
* @param $request
* @return string
*/
private function constructPayPara($request)
{
$yftLib = new YftPayUtil();
$pay_config = new YftPayConfig();
$pay_config->init();
/**************************请求参数**************************/
//订单名称
$subject = $request->getParams()['subject'];//必填
//付款金额
$total_fee = $request->getParams()['total_fee'];//必填 需为整数
//服务器异步通知页面路径
$notify_url = $request->getUri()->getScheme() . "://" . $request->getUri()->getHost() . "/payment/notify";
//需http://格式的完整路径,不能加?id=123这类自定义参数
//页面跳转同步通知页面路径
$return_url = $request->getUri()->getScheme() . "://" . $request->getUri()->getHost() . $pay_config->pay_config["return_url"];
//需http://格式的完整路径,不能加?id=123这类自定义参数,不能写成http://localhost/
$secret = Config::get('yft_secret');
$ss_order_no = self::genOrderNumber();
/************************************************************/
//构造要请求的参数数组,无需改动
$parameter = [
"total_fee" => $total_fee,
"notify_url" => $notify_url,
"return_url" => $return_url,
"secret" => $secret,
"out_trade_no" => $ss_order_no
];
//向数据库插入订单信息
$order = new Paylist();
$order->userid = $this->user->id;
$order->total = $total_fee;
$order->status = 0;
$order->tradeno = $ss_order_no;
$order->save();
//建立请求
$html_text = $yftLib->buildRequestForm($parameter, $ss_order_no, $pay_config);
return $html_text;
}
public function getPurchaseHTML()
{
return '
<div class="card-main">
<div class="card-inner">
<form action="/user/payment/purchase" method="post" target="_blank" onsubmit="return checkPost();">
<p class="card-heading">在线充值</p>
<div class="form-group form-group-label">
<label class="floating-label" for="total_fee">充值金额</label>
<input class="form-control" id="total_fee" name="total_fee" type="text">
<input class="form-control" name="subject" value="余额充值" type="hidden">
</div>
<div class="card-action">
<div class="card-action-btn pull-left">
<button type="submit" class="btn btn-flat waves-attach" ><span class="icon">check</span>&nbsp;充值</button>
</div>
</div>
</form>
</div>
</div>
<script>
function checkPost(){
var price = document.getElementById("total_fee");
if (price.value == ""){
$("#result").modal();
$$.getElementById("msg").innerHTML = "请填写充值金额";
document.getElementById("total_fee").focus();
return false;
}
if (price.value < 0.01){
$("#result").modal();
$$.getElementById("msg").innerHTML = "请填写充值金额";
document.getElementById("total_fee").focus();
return false;
}
return true;
}
</script>
<script>
//jquery控制只输入数字或小数点后几位
$(function () {
$.fn.decimalinput = function (intLen, decimallen, isNegative) {
curIntLen = intLen || 11;
decimallen = decimallen || 0;
isNegative = typeof isNegative == \'boolean\' ? isNegative : false;
$(this).css("ime-mode", "disabled");
/*
KeyPress (主要用来接收字母、数字等ANSI字符)
1.不区分小键盘和主键盘的数字字符。
2.区分大小写。
数字 1
主键盘区keyCode:49
小键盘区keyCode:49
KeyDown 、KeyUp (可以捕获键盘上除了PrScrn(在键盘右上角)之外的所有按键,可以捕获组合键)
1.区分小键盘和主键盘的数字字符。
2.不区分大小写。
数字 1
主键盘区keyCode:49
小键盘区keyCode:97
*/
this.bind("keypress", function (e) {
//微软中文输入法 状态下,无法监听 keypress
var _v = this.value;
if (e.charCode === 0) return true; //非字符键 for firefox
var keyCode = (e.keyCode ? e.keyCode : e.which); //兼容火狐 IE
var curPos = getCurPosition(this);
var selText = getSelectedText(this);
var dotPos = _v.indexOf(".");
var curLength = _v.length;
console.log(curPos)
if (isNegative && keyCode == 45 && curPos == 0) {
curIntLen = intLen + 1;
return true;
}
curIntLen = _v.indexOf(\'-\') > -1 ? intLen + 1 : intLen;
if (keyCode >= 48 && keyCode <= 57) {
//整数位 长度控制
if (dotPos > -1) { //存在小数点情况
if (curPos <= dotPos && dotPos >= curIntLen) {
return false;
}
} else {
if ((curLength + 1) > curIntLen && keyCode != 46) {
return false;
}
}
//小数位 长度控制
if (dotPos > 0 && curPos > dotPos) {
if (curPos > dotPos + decimallen) return false;
if (selText.length > 0 || _v.substr(dotPos + 1).length < decimallen)
return true;
else
return false;
}
return true;
}
//输入"."
// 输入的是小数点,并且参数可以有小数,不可在字符首位输入小数点,不存在小数点
if (keyCode == 46 && decimallen > 0 && curPos > 0 && _v.indexOf(".") < 0) {
return true;
}
return false;
});
this.bind("keydown", function (e) {
var _v = this.value;
var dotPos = _v.indexOf(".");
var curPos = getCurPosition(this);
var selText = getSelectedText(this);
//只能全选删除
if (e.keyCode == 8 && selText.length > 0 && selText.length != _v.length) {
return false;
}
//删除键,存在小数点,光标在小数点后 ,删除小数点的后的长度不能超过 整数长度限制,
if (e.keyCode == 8 &&
dotPos > 0 &&
curPos == (dotPos + 1) &&
(_v.length - 1) > curIntLen) {
return false;
}
})
this.bind("blur", function () {
if (this.value.lastIndexOf(".") == (this.value.length - 1)) {
this.value = this.value.substr(0, this.value.length - 1);
} else if (isNaN(this.value)) {
this.value = "";
}
if (this.value) {
var v = parseFloat(this.value).toFixed(decimallen);
if (v.indexOf(\'.\') > curIntLen) {
v = v.substr(v.indexOf(\'.\') - curIntLen)
}
this.value = v;
}
$(this).trigger("input");
});
this.bind("paste", function () {
return false;
});
this.bind("dragenter", function () { return false; });
this.bind("propertychange", function (e) {
if (isNaN(this.value))
this.value = this.value.replace(/[^0-9\.-]/g, "");
});
this.bind("input", function (e) {
if (isNaN(this.value))
this.value = this.value.replace(/[^0-9\.-]/g, "");
});
//获取当前光标在文本框的位置
function getCurPosition(domObj) {
var curPosition = 0;
if (domObj.selectionStart || domObj.selectionStart == \'0\') {
curPosition = domObj.selectionStart;
} else if (document.selection) { //for IE
domObj.focus();
var currentRange = document.selection.createRange();
var workRange = currentRange.duplicate();
domObj.select();
var allRange = document.selection.createRange();
while (workRange.compareEndPoints("StartToStart", allRange) > 0) {
workRange.moveStart("character", -1);
curPosition++;
}
currentRange.select();
}
return curPosition;
}
//获取当前文本框选中的文本
function getSelectedText(domObj) {
if (domObj.selectionStart || domObj.selectionStart == \'0\') {
return domObj.value.substring(domObj.selectionStart, domObj.selectionEnd);
} else if (document.selection) { //for IE
domObj.focus();
var sel = document.selection.createRange();
return sel.text;
} else return \'\';
}
};
$(\'#total_fee\').decimalinput(5, 2, true);
})
</script>
';
}
public function getReturnHTML($request, $response, $args)
{
// TODO: Implement getReturnHTML() method.
}
public function getStatus($request, $response, $args)
{
// TODO: Implement getStatus() method.
}
private function genOrderNumber()
{
//生成订单号
// 密码字符集,可任意添加你需要的字符
$date = time();
$date = "yft" . date("YmdHis", $date);
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$password = "";
for ($i = 0; $i < 8; $i++) {
// 这里提供两种字符获取方式
// 第一种是使用 substr 截取$chars中的任意一位字符;
// 第二种是取字符数组 $chars 的任意元素
$password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $date . $password;
}
}

@ -1,19 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/10/10
* Time: 17:05
*/
namespace App\Services\Gateway;
class YftPayConfig{
public $pay_config;
public function init()
{
$this->pay_config = [
"return_url" => "/user/code",
"type" => "aliPay"
];
}
}

@ -1,119 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/10/10
* Time: 17:21
*/
namespace App\Services\Gateway;
class YftPayUtil
{
public function md5Verify($p1, $p2, $p3, $p4, $sign)
{
$preStr = $p1 . $p2 . $p3 . $p4 . "yft";
$mySign = md5($preStr);
if ($mySign == $sign) {
return true;
} else {
return false;
}
}
/**
* 建立请求,以表单HTML形式构造(默认)
* @param $para_temp 请求参数数组
*
*/
public function buildRequestForm($para_temp, $ss_order_no, $pay_config)
{
//待请求参数数组
$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'>";
foreach ($para as $key => $val) {
$sHtml .= "<input type='hidden' name='" . $key . "' value='" . $val . "'/>";
}
if ($pay_config->pay_config["type"] == "aliPay") {
$sHtml .= "<input type='hidden' name='subject' value='余额充值'/>";
} else {
$sHtml .= "<input type='hidden' name='trade_no' value='" . $ss_order_no . "'/>";
}
//submit按钮控件请不要含有name属性
$sHtml = $sHtml . "</form>";
$sHtml = $sHtml . "<script>document.forms['paysubmit'].submit();</script>";
return $sHtml;
}
/**
* 生成要请求给易付的参数数组
* @param $para_temp 请求前的参数数组
* @return 要请求的参数数组
*/
static function buildRequestPara($para_temp)
{
//除去待签名参数数组中的空值和签名参数
$para_filter = YftPayUtil::paraFilter($para_temp);
//生成签名结果
$mysign = YftPayUtil::buildRequestMysign($para_filter);
//签名结果与签名方式加入请求提交参数组中
$para_filter['sign'] = $mysign;
return $para_filter;
}
/**
* 除去数组中的空值和签名参数
* @param $para 签名参数组
* return 去掉空值与签名参数后的新签名参数组
*/
static function paraFilter($para)
{
$para_filter = array();
foreach ($para as $key => $val) {
if ($key == "sign" || $val == "") continue;
else $para_filter[$key] = $para[$key];
}
return $para_filter;
}
/**
* 生成签名结果
* @param $para_filter 要签名的数组
* return 签名结果字符串
*/
static function buildRequestMysign($para_filter)
{
//把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
$prestr = YftPayUtil::createLinkstring($para_filter);
$mysign = MD5($prestr);
return $mysign;
}
static function md5Sign($prestr)
{
return md5($prestr);
}
/**
* 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
* @param $para 需要拼接的数组
* return 拼接完成以后的字符串
*/
static function createLinkstring($para)
{
$arg = "";
foreach ($para as $key => $val) {
$arg .= $key . "=" . $val . "&";
}
//去掉最后一个&字符
$arg = substr($arg, 0, strlen($arg) - 1);
//如果存在转义字符,那么去掉转义
if (get_magic_quotes_gpc()) {
$arg = stripslashes($arg);
}
return $arg;
}
}

@ -1,239 +0,0 @@
<?php
namespace App\Services\Gateway;
use App\Services\View;
use App\Services\Auth;
use App\Services\Config;
use App\Models\Paylist;
class Pays
{
private $pid;
private $key;
public function __construct($pid, $key)
{
$this->pid = $pid;
$this->key = $key;
}
/**
* @Note 支付发起
* @param $type 支付方式
* @param $out_trade_no 订单号
* @param $notify_url 异步通知地址
* @param $return_url 回调通知地址
* @param $name 商品名称
* @param $money 金额
* @param $sitename 站点名称
* @return string
*/
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);
$sign = $this->getsign($data);
return 'https://api.jxspay.cn/submit/?' . $string . '&sign=' . $sign . '&sign_type=MD5';
}
/**
* @Note 验证签名
* @param $data 待验证参数
* @return bool
*/
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;
}
/**
* @Note 生成签名
* @param $data 参与签名的参数
* @return string
*/
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;
}
}
class flyfoxpay extends AbstractPayment
{
public function purchase($request, $response, $args)
{
$type = $request->getParam('type');
$price = $request->getParam('price');
if($price <= 0){
return json_encode(['errcode'=>-1,'errmsg'=>"非法的金额."]);
}
$user = Auth::getUser();
$settings = Config::get("flyfoxpay")['config'];
$pl = new Paylist();
$pl->userid = $user->id;
$pl->total = $price;
$pl->tradeno = self::generateGuid();
$pl->save();
$return='https://'.$_SERVER['HTTP_HOST'].'/flyfoxpay_back/'.$type;
$pay = new Pays($settings['hid'], $settings['key']);
//支付方式
$type = 'all';
//订单号
$out_trade_no = $pl->tradeno;
//异步通知地址
$notify_url = $return;
//回调通知地址
$return_url = $return;
//商品名称
$name = 'SS商品-'.$_SERVER['HTTP_HOST'];
//支付金额(保留小数点后两位)
$money = $price;
//站点名称
$sitename = $_SERVER['HTTP_HOST'];
//发起支付
$url = $pay->submit($type, $out_trade_no, $notify_url, $return_url, $name, $money, $sitename);
$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 notify($request, $response, $args)
{
$type = $args['type'];
$settings = Config::get("flyfoxpay")['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']);
//接收异步通知数据
$data = $_GET;
//商户订单号
$out_trade_no = $data['out_trade_no'];
//验证签名
if ($pay->verify($data)) {
//验证支付状态
if ($data['trade_status'] == 'TRADE_SUCCESS') {
$this->postPayment($data['out_trade_no'], "在线支付");
header("Location: /user/code");
//这里就可以放心的处理您的业务流程了
//您可以通过上面的商户订单号进行业务流程处理
}
} else {
echo '錯誤';
}
}}
public function getPurchaseHTML()
{
return '
<div class="card-inner">
<p class="card-heading">充值</p>
<h5>支付方式:</h5>
<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="wxpay">聚合支付</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="code-updates" ><span class="icon">check</span>&nbsp;充值</button>
</div>
</div>
<script>
var type = "wxpay";
var pid = 0;
$(".type").click(function(){
type = $(this).data("pay");
});
$("#code-updates").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);
}
}
}
});
});
</script>
';
}
public function getReturnHTML($request, $response, $args)
{
}
public function getStatus($request, $response, $args)
{
// TODO: Implement getStatus() method.
}
}

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

@ -31,7 +31,7 @@ class SendGrid extends Base
public function send($to_address, $subject_raw, $text, $files)
{
$from = new Email(Config::get('appName'), $this->sender);
$from = new Email(null, $this->sender);
$subject = $subject_raw;
$to = new Email(null, $to_address);
$content = new Content('text/html', $text);

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

@ -1,18 +0,0 @@
<?php
namespace App\Services;
class MalioConfig
{
public static function get($key)
{
global $Malio_Config;
return $Malio_Config[$key];
}
public static function getPublicConfig()
{
global $Malio_Config;
return $Malio_Config;
}
}

@ -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, MalioPay, IDtPay
AopF2F, Codepay, DoiAMPay, PaymentWall, ChenPay, SPay, TrimePay, PAYJS, BitPayX,TomatoPay,IDtPay
};
class Payment
@ -20,6 +20,8 @@ class Payment
switch ($method) {
case ('codepay'):
return new Codepay();
case ('doiampay'):
return new DoiAMPay();
case ('paymentwall'):
return new PaymentWall();
case ('spay'):
@ -28,24 +30,14 @@ 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"):
return new TomatoPay();
case("flyfoxpay"):
return new flyfoxpay();
case ('payjs'):
return new PAYJS(Config::get('payjs_key'));
case ('f2fpay_payjs'):
return new F2Fpay_PAYJS();
case ('stripe'):
return new StripePay();
case ('payssion'):
return new Payssion();
case ('yftpay'):
return new YftPay();
case ('malio'):
return new MalioPay();
case ("tomatopay"):
return new TomatoPay();
case ("idtpay"):
return new IDtPay();
default:

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

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

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

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

Loading…
Cancel
Save