UserController.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Components\Helpers;
  4. use App\Components\ServerChan;
  5. use App\Http\Models\Article;
  6. use App\Http\Models\Coupon;
  7. use App\Http\Models\Goods;
  8. use App\Http\Models\GoodsLabel;
  9. use App\Http\Models\Invite;
  10. use App\Http\Models\Level;
  11. use App\Http\Models\Order;
  12. use App\Http\Models\ReferralApply;
  13. use App\Http\Models\ReferralLog;
  14. use App\Http\Models\SsGroup;
  15. use App\Http\Models\SsNodeInfo;
  16. use App\Http\Models\SsNodeLabel;
  17. use App\Http\Models\Ticket;
  18. use App\Http\Models\TicketReply;
  19. use App\Http\Models\User;
  20. use App\Http\Models\UserLabel;
  21. use App\Http\Models\UserLoginLog;
  22. use App\Http\Models\UserSubscribe;
  23. use App\Http\Models\UserTrafficDaily;
  24. use App\Http\Models\UserTrafficHourly;
  25. use App\Mail\newTicket;
  26. use App\Mail\replyTicket;
  27. use Auth;
  28. use Cache;
  29. use DB;
  30. use Exception;
  31. use Hash;
  32. use Illuminate\Http\Request;
  33. use Log;
  34. use Mail;
  35. use Redirect;
  36. use Response;
  37. use Session;
  38. use Validator;
  39. /**
  40. * 用户控制器
  41. *
  42. * Class UserController
  43. *
  44. * @package App\Http\Controllers
  45. */
  46. class UserController extends Controller
  47. {
  48. protected static $systemConfig;
  49. function __construct()
  50. {
  51. self::$systemConfig = Helpers::systemConfig();
  52. }
  53. public function index(Request $request)
  54. {
  55. $user = User::uid()->first();
  56. $user->totalTransfer = flowAutoShow($user->transfer_enable);
  57. $user->unusedTransfer = $user->transfer_enable - $user->u - $user->d > 0 ? $user->transfer_enable - $user->u - $user->d : 0;
  58. $user->unusedPercent = $user->transfer_enable > 0 ? round($user->unusedTransfer / $user->transfer_enable, 2) : 0;
  59. $user->unusedTransfer = flowAutoShow($user->unusedTransfer);
  60. $user->levelName = Level::query()->where('level', $user['level'])->first()['level_name'];
  61. $user->remainDays = date('Y-m-d') < $user->expire_time ? (strtotime($user->expire_time) - strtotime(date('Y-m-d'))) / 86400 : 0;
  62. $user->resetDays = date('d') > $user->traffic_reset_day ? (strtotime($user->traffic_reset_day) - strtotime(date('Y-m-d'))) / 86400 : strtotime($user->traffic_reset_day);
  63. $user_reset_day = $user->traffic_reset_day;
  64. $last_day = date('t');
  65. $today = date('d');
  66. if ($user_reset_day > $today) {
  67. $user->resetDays = $user_reset_day > $last_day ? $last_day - $today : $user_reset_day - $today;
  68. } else {
  69. $next_last_day = date('t', strtotime('next month'));
  70. $user->resetDays = $user_reset_day > $next_last_day ? $last_day - $today + $next_last_day : $last_day - $today + $user_reset_day;
  71. }
  72. $view['info'] = $user->toArray();
  73. $view['noticeList'] = Article::type(2)->orderBy('id', 'desc')->Paginate(1); // 公告
  74. $view['userLoginLog'] = UserLoginLog::query()->where('user_id', Auth::user()->id)->orderBy('id', 'desc')->first(); // 近期登录日志
  75. //流量异常判断
  76. $hourlyTraffic = UserTrafficHourly::query()->where('user_id', $user->id)->where('node_id', 0)->where('created_at', '>=', date('Y-m-d H:i:s', time() - 3900))->sum('total');
  77. $view['isTrafficWarning'] = $hourlyTraffic < (self::$systemConfig['traffic_ban_value'] * 1073741824) ? 0 : 1;
  78. //付费用户判断
  79. $view['is_paying_user'] = Order::uid()->where('status', 2)->where('is_expire', 0)->where('origin_amount', '>', 0)->get()->isEmpty();
  80. $dailyData = [];
  81. $hourlyData = [];
  82. // 节点一个月内的流量
  83. $userTrafficDaily = UserTrafficDaily::query()->where('user_id', Auth::user()->id)->where('node_id', 0)->where('created_at', '>=', date('Y-m', time()))->orderBy('created_at', 'asc')->pluck('total')->toArray();
  84. $dailyTotal = date('d') - 1; // 今天不算,减一
  85. $dailyCount = count($userTrafficDaily);
  86. for ($x = 0; $x < $dailyTotal - $dailyCount; $x++) {
  87. $dailyData[$x] = 0;
  88. }
  89. for ($x = $dailyTotal - $dailyCount; $x < $dailyTotal; $x++) {
  90. $dailyData[$x] = round($userTrafficDaily[$x - ($dailyTotal - $dailyCount)] / (1024 * 1024 * 1024), 3);
  91. }
  92. // 节点一天内的流量
  93. $userTrafficHourly = UserTrafficHourly::query()->where('user_id', Auth::user()->id)->where('node_id', 0)->where('created_at', '>=', date('Y-m-d', time()))->orderBy('created_at', 'asc')->pluck('total')->toArray();
  94. $hourlyTotal = date('H');
  95. $hourlyCount = count($userTrafficHourly);
  96. for ($x = 0; $x < $hourlyTotal - $hourlyCount; $x++) {
  97. $hourlyData[$x] = 0;
  98. }
  99. for ($x = ($hourlyTotal - $hourlyCount); $x < $hourlyTotal; $x++) {
  100. $hourlyData[$x] = round($userTrafficHourly[$x - ($hourlyTotal - $hourlyCount)] / (1024 * 1024 * 1024), 3);
  101. }
  102. // 本月天数数据
  103. $monthDays = [];
  104. for ($i = 1; $i <= date("d"); $i++) {
  105. $monthDays[] = $i;
  106. }
  107. // 本日小时数据
  108. $dayHours = [];
  109. for ($i = 1; $i <= date("H"); $i++) {
  110. $dayHours[] = $i;
  111. }
  112. $view['trafficDaily'] = "'" . implode("','", $dailyData) . "'";
  113. $view['trafficHourly'] = "'" . implode("','", $hourlyData) . "'";
  114. $view['monthDays'] = "'" . implode("','", $monthDays) . "'";
  115. $view['dayHours'] = "'" . implode("','", $dayHours) . "'";
  116. return Response::view('user.index', $view);
  117. }
  118. // 签到
  119. public function checkIn(Request $request)
  120. {
  121. // 系统开启登录加积分功能才可以签到
  122. if (!self::$systemConfig['is_checkin']) {
  123. return Response::json(['status' => 'fail', 'message' => '系统未开启签到功能']);
  124. }
  125. // 已签到过,验证是否有效
  126. if (Cache::has('userCheckIn_' . Auth::user()->id)) {
  127. return Response::json(['status' => 'fail', 'message' => '已经签到过了,明天再来吧']);
  128. }
  129. $traffic = mt_rand(self::$systemConfig['min_rand_traffic'], self::$systemConfig['max_rand_traffic']);
  130. $ret = User::uid()->increment('transfer_enable', $traffic * 1048576);
  131. if (!$ret) {
  132. return Response::json(['status' => 'fail', 'message' => '签到失败,系统异常']);
  133. }
  134. // 写入用户流量变动记录
  135. Helpers::addUserTrafficModifyLog(Auth::user()->id, 0, Auth::user()->transfer_enable, Auth::user()->transfer_enable + $traffic * 1048576, '[签到]');
  136. // 多久后可以再签到
  137. $ttl = self::$systemConfig['traffic_limit_time'] ? self::$systemConfig['traffic_limit_time'] : 1440;
  138. Cache::put('userCheckIn_' . Auth::user()->id, '1', $ttl);
  139. return Response::json(['status' => 'success', 'message' => '签到成功,系统送您 ' . $traffic . 'M 流量']);
  140. }
  141. // 节点列表
  142. public function nodeList(Request $request)
  143. {
  144. // 节点列表
  145. $userLabelIds = UserLabel::uid()->pluck('label_id');
  146. if (empty($userLabelIds)) {
  147. $view['nodeList'] = [];
  148. $view['allNodes'] = '';
  149. return Response::view('user.nodeList', $view);
  150. }
  151. // 获取当前用户可用节点
  152. $nodeList = DB::table('ss_node')
  153. ->selectRaw('ss_node.*')
  154. ->leftJoin('ss_node_label', 'ss_node.id', '=', 'ss_node_label.node_id')
  155. ->whereIn('ss_node_label.label_id', $userLabelIds)
  156. ->where('ss_node.status', 1)
  157. ->groupBy('ss_node.id')
  158. ->orderBy('ss_node.sort', 'desc')
  159. ->orderBy('ss_node.id', 'asc')
  160. ->get();
  161. $allNodes = ''; // 全部节点SSR链接,用于一键复制所有节点
  162. foreach ($nodeList as &$node) {
  163. // 获取分组名称
  164. $group = SsGroup::query()->where('id', $node->group_id)->first();
  165. if ($node->type == 1) {
  166. // 生成ssr scheme
  167. $obfs_param = Auth::user()->obfs_param ? Auth::user()->obfs_param : $node->obfs_param;
  168. $protocol_param = $node->single ? Auth::user()->port . ':' . Auth::user()->passwd : Auth::user()->protocol_param;
  169. $ssr_str = ($node->server ? $node->server : $node->ip) . ':' . ($node->single ? $node->single_port : Auth::user()->port);
  170. $ssr_str .= ':' . ($node->single ? $node->single_protocol : Auth::user()->protocol) . ':' . ($node->single ? $node->single_method : Auth::user()->method);
  171. $ssr_str .= ':' . ($node->single ? $node->single_obfs : Auth::user()->obfs) . ':' . ($node->single ? base64url_encode($node->single_passwd) : base64url_encode(Auth::user()->passwd));
  172. $ssr_str .= '/?obfsparam=' . base64url_encode($obfs_param);
  173. $ssr_str .= '&protoparam=' . ($node->single ? base64url_encode(Auth::user()->port . ':' . Auth::user()->passwd) : base64url_encode($protocol_param));
  174. $ssr_str .= '&remarks=' . base64url_encode($node->name);
  175. $ssr_str .= '&group=' . base64url_encode(empty($group) ? '' : $group->name);
  176. $ssr_str .= '&udpport=0';
  177. $ssr_str .= '&uot=0';
  178. $ssr_str = base64url_encode($ssr_str);
  179. $ssr_scheme = 'ssr://' . $ssr_str;
  180. // 生成ss scheme
  181. $ss_str = Auth::user()->method . ':' . Auth::user()->passwd . '@';
  182. $ss_str .= ($node->server ? $node->server : $node->ip) . ':' . Auth::user()->port;
  183. $ss_str = base64url_encode($ss_str) . '#' . 'VPN';
  184. $ss_scheme = 'ss://' . $ss_str;
  185. // 生成文本配置信息
  186. $txt = "服务器:" . ($node->server ? $node->server : $node->ip) . PHP_EOL;
  187. if ($node->ipv6) {
  188. $txt .= "IPv6:" . $node->ipv6 . PHP_EOL;
  189. }
  190. $txt .= "远程端口:" . ($node->single ? $node->single_port : Auth::user()->port) . PHP_EOL;
  191. $txt .= "密码:" . ($node->single ? $node->single_passwd : Auth::user()->passwd) . PHP_EOL;
  192. $txt .= "加密方法:" . ($node->single ? $node->single_method : Auth::user()->method) . PHP_EOL;
  193. $txt .= "路由:绕过局域网及中国大陆地址" . PHP_EOL . PHP_EOL;
  194. $txt .= "协议:" . ($node->single ? $node->single_protocol : Auth::user()->protocol) . PHP_EOL;
  195. $txt .= "协议参数:" . ($node->single ? Auth::user()->port . ':' . Auth::user()->passwd : Auth::user()->protocol_param) . PHP_EOL;
  196. $txt .= "混淆方式:" . ($node->single ? $node->single_obfs : Auth::user()->obfs) . PHP_EOL;
  197. $txt .= "混淆参数:" . (Auth::user()->obfs_param ? Auth::user()->obfs_param : $node->obfs_param) . PHP_EOL;
  198. $txt .= "本地端口:1080" . PHP_EOL;
  199. $node->txt = $txt;
  200. $node->ssr_scheme = $ssr_scheme;
  201. $node->ss_scheme = $node->compatible ? $ss_scheme : ''; // 节点兼容原版才显示
  202. $allNodes .= $ssr_scheme . '|';
  203. } else {
  204. // 生成v2ray scheme
  205. $v2_json = [
  206. "v" => "2",
  207. "ps" => $node->name,
  208. "add" => $node->server ? $node->server : $node->ip,
  209. "port" => $node->v2_port,
  210. "id" => Auth::user()->vmess_id,
  211. "aid" => $node->v2_alter_id,
  212. "net" => $node->v2_net,
  213. "type" => $node->v2_type,
  214. "host" => $node->v2_host,
  215. "path" => $node->v2_path,
  216. "tls" => $node->v2_tls == 1 ? "tls" : ""
  217. ];
  218. $v2_scheme = 'vmess://' . base64url_encode(json_encode($v2_json, JSON_PRETTY_PRINT));
  219. // 生成文本配置信息
  220. $txt = "服务器:" . ($node->server ? $node->server : $node->ip) . PHP_EOL;
  221. if ($node->ipv6) {
  222. $txt .= "IPv6:" . $node->ipv6 . PHP_EOL;
  223. }
  224. $txt .= "端口:" . $node->v2_port . PHP_EOL;
  225. $txt .= "加密方式:" . $node->v2_method . PHP_EOL;
  226. $txt .= "用户ID:" . Auth::user()->vmess_id . PHP_EOL;
  227. $txt .= "额外ID:" . $node->v2_alter_id . PHP_EOL;
  228. $txt .= "传输协议:" . $node->v2_net . PHP_EOL;
  229. $txt .= "伪装类型:" . $node->v2_type . PHP_EOL;
  230. $txt .= $node->v2_host ? "伪装域名:" . $node->v2_host . PHP_EOL : "";
  231. $txt .= $node->v2_path ? "路径:" . $node->v2_path . PHP_EOL : "";
  232. $txt .= $node->v2_tls ? "TLS:tls" . PHP_EOL : "";
  233. $node->txt = $txt;
  234. $node->v2_scheme = $v2_scheme;
  235. }
  236. // 节点在线状态
  237. $nodeInfo = SsNodeInfo::query()->where('node_id', $node->id)->where('log_time', '>=', strtotime("-10 minutes"))->orderBy('id', 'desc')->first();
  238. $node->online_status = empty($nodeInfo) || empty($nodeInfo->load) ? 0 : 1;
  239. // 节点标签
  240. $node->labels = SsNodeLabel::query()->with('labelInfo')->where('node_id', $node->id)->first();
  241. }
  242. $view['allNodes'] = rtrim($allNodes, "|");
  243. $view['nodeList'] = $nodeList;
  244. return Response::view('user.nodeList', $view);
  245. }
  246. // 公告详情
  247. public function article(Request $request)
  248. {
  249. $view['info'] = Article::query()->findOrFail($request->id);
  250. return Response::view('user.article', $view);
  251. }
  252. // 修改个人资料
  253. public function profile(Request $request)
  254. {
  255. if ($request->isMethod('POST')) {
  256. $old_password = trim($request->input('old_password'));
  257. $new_password = trim($request->input('new_password'));
  258. $wechat = $request->input('wechat');
  259. $qq = $request->input('qq');
  260. $passwd = trim($request->input('passwd'));
  261. // 修改密码
  262. if ($old_password && $new_password) {
  263. if (!Hash::check($old_password, Auth::user()->password)) {
  264. return Redirect::to('profile#tab_1')->withErrors('旧密码错误,请重新输入');
  265. } elseif (Hash::check($new_password, Auth::user()->password)) {
  266. return Redirect::to('profile#tab_1')->withErrors('新密码不可与旧密码一样,请重新输入');
  267. }
  268. // 演示环境禁止改管理员密码
  269. if (env('APP_DEMO') && Auth::user()->id == 1) {
  270. return Redirect::to('profile#tab_1')->withErrors('演示环境禁止修改管理员密码');
  271. }
  272. $ret = User::uid()->update(['password' => Hash::make($new_password)]);
  273. if (!$ret) {
  274. return Redirect::to('profile#tab_1')->withErrors('修改失败');
  275. } else {
  276. return Redirect::to('profile#tab_1')->with('successMsg', '修改成功');
  277. }
  278. }
  279. // 修改联系方式
  280. if ($wechat || $qq) {
  281. if (empty(clean($wechat)) && empty(clean($qq))) {
  282. return Redirect::to('profile#tab_2')->withErrors('修改失败');
  283. }
  284. $ret = User::uid()->update(['wechat' => $wechat, 'qq' => $qq]);
  285. if (!$ret) {
  286. return Redirect::to('profile#tab_2')->withErrors('修改失败');
  287. } else {
  288. return Redirect::to('profile#tab_2')->with('successMsg', '修改成功');
  289. }
  290. }
  291. // 修改代理密码
  292. if ($passwd) {
  293. $ret = User::uid()->update(['passwd' => $passwd]);
  294. if (!$ret) {
  295. return Redirect::to('profile#tab_3')->withErrors('修改失败');
  296. } else {
  297. return Redirect::to('profile#tab_3')->with('successMsg', '修改成功');
  298. }
  299. }
  300. return Redirect::to('profile#tab_1')->withErrors('非法请求');
  301. } else {
  302. return Response::view('user.profile');
  303. }
  304. }
  305. // 商品列表
  306. public function services(Request $request)
  307. {
  308. $user = User::uid()->first();
  309. $view['user_balance'] = $user->balance;
  310. // 余额充值商品,只取10个
  311. $view['chargeGoodsList'] = Goods::type(3)->where('status', 1)->orderBy('price', 'asc')->orderBy('price', 'asc')->limit(10)->get();
  312. $view['goodsList'] = Goods::query()->where('status', 1)->where('type', '<=', '2')->orderBy('type', 'desc')->orderBy('sort', 'desc')->paginate(10)->appends($request->except('page'));
  313. return Response::view('user.services', $view);
  314. }
  315. // 工单
  316. public function ticketList(Request $request)
  317. {
  318. $view['ticketList'] = Ticket::uid()->orderBy('id', 'desc')->paginate(10)->appends($request->except('page'));
  319. return Response::view('user.ticketList', $view);
  320. }
  321. // 订单
  322. public function invoices(Request $request)
  323. {
  324. $view['orderList'] = Order::uid()->with(['user', 'goods', 'coupon', 'payment'])->orderBy('oid', 'desc')->paginate(10)->appends($request->except('page'));
  325. return Response::view('user.invoices', $view);
  326. }
  327. // 订单明细
  328. public function invoiceDetail(Request $request, $sn)
  329. {
  330. $view['order'] = Order::uid()->with(['goods', 'coupon', 'payment'])->where('order_sn', $sn)->firstOrFail();
  331. return Response::view('user.invoiceDetail', $view);
  332. }
  333. // 添加工单
  334. public function addTicket(Request $request)
  335. {
  336. $title = $request->input('title');
  337. $content = clean($request->input('content'));
  338. $content = str_replace("eval", "", str_replace("atob", "", $content));
  339. if (empty($title) || empty($content)) {
  340. return Response::json(['status' => 'fail', 'data' => '', 'message' => '请输入标题和内容']);
  341. }
  342. $obj = new Ticket();
  343. $obj->user_id = Auth::user()->id;
  344. $obj->title = $title;
  345. $obj->content = $content;
  346. $obj->status = 0;
  347. $obj->save();
  348. if ($obj->id) {
  349. $emailTitle = "新工单提醒";
  350. $content = "标题:【" . $title . "】<br>内容:" . $content;
  351. // 发邮件通知管理员
  352. if (self::$systemConfig['crash_warning_email']) {
  353. $logId = Helpers::addEmailLog(self::$systemConfig['crash_warning_email'], $emailTitle, $content);
  354. Mail::to(self::$systemConfig['crash_warning_email'])->send(new newTicket($logId, $emailTitle, $content));
  355. }
  356. ServerChan::send($emailTitle, $content);
  357. return Response::json(['status' => 'success', 'data' => '', 'message' => '提交成功']);
  358. } else {
  359. return Response::json(['status' => 'fail', 'data' => '', 'message' => '提交失败']);
  360. }
  361. }
  362. // 回复工单
  363. public function replyTicket(Request $request)
  364. {
  365. $id = intval($request->input('id'));
  366. $ticket = Ticket::uid()->with('user')->where('id', $id)->firstOrFail();
  367. if ($request->isMethod('POST')) {
  368. $content = clean($request->input('content'));
  369. $content = str_replace("eval", "", str_replace("atob", "", $content));
  370. $content = substr($content, 0, 300);
  371. if (empty($content)) {
  372. return Response::json(['status' => 'fail', 'data' => '', 'message' => '回复内容不能为空']);
  373. }
  374. $obj = new TicketReply();
  375. $obj->ticket_id = $id;
  376. $obj->user_id = Auth::user()->id;
  377. $obj->content = $content;
  378. $obj->save();
  379. if ($obj->id) {
  380. // 重新打开工单
  381. $ticket->status = 0;
  382. $ticket->save();
  383. $title = "工单回复提醒";
  384. $content = "标题:【" . $ticket->title . "】<br>用户回复:" . $content;
  385. // 发邮件通知管理员
  386. if (self::$systemConfig['crash_warning_email']) {
  387. $logId = Helpers::addEmailLog(self::$systemConfig['crash_warning_email'], $title, $content);
  388. Mail::to(self::$systemConfig['crash_warning_email'])->send(new replyTicket($logId, $title, $content));
  389. }
  390. ServerChan::send($title, $content);
  391. return Response::json(['status' => 'success', 'data' => '', 'message' => '回复成功']);
  392. } else {
  393. return Response::json(['status' => 'fail', 'data' => '', 'message' => '回复失败']);
  394. }
  395. } else {
  396. $view['ticket'] = $ticket;
  397. $view['replyList'] = TicketReply::query()->where('ticket_id', $id)->with('user')->orderBy('id', 'asc')->get();
  398. return Response::view('user.replyTicket', $view);
  399. }
  400. }
  401. // 关闭工单
  402. public function closeTicket(Request $request)
  403. {
  404. $id = $request->input('id');
  405. $ret = Ticket::uid()->where('id', $id)->update(['status' => 2]);
  406. if ($ret) {
  407. ServerChan::send('工单关闭提醒', '工单:ID' . $id . '用户已手动关闭');
  408. return Response::json(['status' => 'success', 'data' => '', 'message' => '关闭成功']);
  409. } else {
  410. return Response::json(['status' => 'fail', 'data' => '', 'message' => '关闭失败']);
  411. }
  412. }
  413. // 邀请码
  414. public function invite(Request $request)
  415. {
  416. if (Order::uid()->where('status', 2)->where('is_expire', 0)->where('origin_amount', '>', 0)->get()->isEmpty()) {
  417. return Response::view('auth.error', ['message' => '本功能对非付费用户禁用!请 <a class="btn btn-sm btn-danger" href="/">返回</a>']);
  418. }
  419. $view['inviteList'] = Invite::uid()->with(['generator', 'user'])->paginate(10); // 邀请码列表
  420. $view['referral_traffic'] = flowAutoShow(self::$systemConfig['referral_traffic'] * 1048576);
  421. $view['referral_percent'] = self::$systemConfig['referral_percent'];
  422. return Response::view('user.invite', $view);
  423. }
  424. // 生成邀请码
  425. public function makeInvite(Request $request)
  426. {
  427. if (!Auth::user()->invite_num) {
  428. return Response::json(['status' => 'fail', 'data' => '', 'message' => '生成失败:邀请码数量不足']);
  429. }
  430. DB::beginTransaction();
  431. try {
  432. // 生成邀请码
  433. $obj = new Invite();
  434. $obj->uid = Auth::user()->id;
  435. $obj->fuid = 0;
  436. $obj->code = strtoupper(mb_substr(md5(microtime() . makeRandStr()), 8, 12));
  437. $obj->status = 0;
  438. $obj->dateline = date('Y-m-d H:i:s', strtotime("+" . self::$systemConfig['user_invite_days'] . " days"));
  439. $obj->save();
  440. // 扣减邀请码数
  441. User::uid()->decrement('invite_num', 1);
  442. DB::commit();
  443. return Response::json(['status' => 'success', 'data' => '', 'message' => '生成成功']);
  444. } catch (Exception $e) {
  445. Log::info("用户生成邀请码异常:" . $e);
  446. DB::rollBack();
  447. return Response::json(['status' => 'fail', 'data' => '', 'message' => '生成失败:邀请码数量不足']);
  448. }
  449. }
  450. // 使用优惠券
  451. public function redeemCoupon(Request $request)
  452. {
  453. $coupon_sn = $request->input('coupon_sn');
  454. if (empty($coupon_sn)) {
  455. return Response::json(['status' => 'fail', 'data' => '', 'message' => '优惠券不能为空']);
  456. }
  457. $coupon = Coupon::query()->where('sn', $coupon_sn)->whereIn('type', [1, 2])->first();
  458. if (!$coupon) {
  459. return Response::json(['status' => 'fail', 'data' => '', 'message' => '该优惠券不存在']);
  460. } elseif ($coupon->status == 1) {
  461. return Response::json(['status' => 'fail', 'data' => '', 'message' => '该优惠券已使用,请换一个试试']);
  462. } elseif ($coupon->status == 2) {
  463. return Response::json(['status' => 'fail', 'data' => '', 'message' => '该优惠券已失效,请换一个试试']);
  464. } elseif ($coupon->available_end < time()) {
  465. $coupon->status = 2;
  466. $coupon->save();
  467. return Response::json(['status' => 'fail', 'data' => '', 'message' => '该优惠券已失效,请换一个试试']);
  468. } elseif ($coupon->available_start > time()) {
  469. return Response::json(['status' => 'fail', 'data' => '', 'message' => '该优惠券尚不可用,请换一个试试']);
  470. }
  471. $data = [
  472. 'type' => $coupon->type,
  473. 'amount' => $coupon->amount,
  474. 'discount' => $coupon->discount
  475. ];
  476. return Response::json(['status' => 'success', 'data' => $data, 'message' => '该优惠券有效']);
  477. }
  478. // 购买服务
  479. public function buy(Request $request, $id)
  480. {
  481. $goods_id = intval($id);
  482. $coupon_sn = $request->input('coupon_sn');
  483. // 余额支付
  484. if ($request->isMethod('POST')) {
  485. $goods = Goods::query()->with(['label'])->where('status', 1)->where('id', $goods_id)->first();
  486. if (!$goods) {
  487. return Response::json(['status' => 'fail', 'data' => '', 'message' => '支付失败:商品或服务已下架']);
  488. }
  489. // 限购控制:all-所有商品限购, free-价格为0的商品限购, none-不限购(默认)
  490. $strategy = self::$systemConfig['goods_purchase_limit_strategy'];
  491. if ($strategy == 'all' || ($strategy == 'package' && $goods->type == 2) || ($strategy == 'free' && $goods->price == 0) || ($strategy == 'package&free' && ($goods->type == 2 || $goods->price == 0))) {
  492. $noneExpireGoodExist = Order::uid()->where('status', '>=', 0)->where('is_expire', 0)->where('goods_id', $goods_id)->exists();
  493. if ($noneExpireGoodExist) {
  494. return Response::json(['status' => 'fail', 'data' => '', 'message' => '支付失败:商品不可重复购买']);
  495. }
  496. }
  497. // 单个商品限购
  498. if ($goods->is_limit == 1) {
  499. $noneExpireOrderExist = Order::uid()->where('status', '>=', 0)->where('goods_id', $goods_id)->exists();
  500. if ($noneExpireOrderExist) {
  501. return Response::json(['status' => 'fail', 'data' => '', 'message' => '创建支付单失败:此商品每人限购1次']);
  502. }
  503. }
  504. // 使用优惠券
  505. if (!empty($coupon_sn)) {
  506. $coupon = Coupon::query()->where('status', 0)->whereIn('type', [1, 2])->where('sn', $coupon_sn)->first();
  507. if (empty($coupon)) {
  508. return Response::json(['status' => 'fail', 'data' => '', 'message' => '优惠券不存在']);
  509. }
  510. // 计算实际应支付总价
  511. $amount = $coupon->type == 2 ? $goods->price * $coupon->discount / 10 : $goods->price - $coupon->amount;
  512. $amount = $amount > 0 ? $amount : 0;
  513. } else {
  514. $amount = $goods->price;
  515. }
  516. // 价格异常判断
  517. if ($amount < 0) {
  518. return Response::json(['status' => 'fail', 'data' => '', 'message' => '支付失败:订单总价异常']);
  519. }
  520. // 验证账号余额是否充足
  521. $user = User::uid()->first();
  522. if ($user->balance < $amount) {
  523. return Response::json(['status' => 'fail', 'data' => '', 'message' => '支付失败:您的余额不足,请先充值']);
  524. }
  525. // 验证账号是否存在有效期更长的套餐
  526. if ($goods->type == 2) {
  527. $existOrderList = Order::uid()
  528. ->with(['goods'])
  529. ->whereHas('goods', function ($q) {
  530. $q->where('type', 2);
  531. })
  532. ->where('is_expire', 0)
  533. ->where('status', 2)
  534. ->get();
  535. foreach ($existOrderList as $vo) {
  536. if ($vo->goods->days > $goods->days) {
  537. return Response::json(['status' => 'fail', 'data' => '', 'message' => '支付失败:您已存在有效期更长的套餐,只能购买流量包']);
  538. }
  539. }
  540. }
  541. DB::beginTransaction();
  542. try {
  543. // 生成订单
  544. $order = new Order();
  545. $order->order_sn = date('ymdHis') . mt_rand(100000, 999999);
  546. $order->user_id = $user->id;
  547. $order->goods_id = $goods_id;
  548. $order->coupon_id = !empty($coupon) ? $coupon->id : 0;
  549. $order->origin_amount = $goods->price;
  550. $order->amount = $amount;
  551. $order->expire_at = date("Y-m-d H:i:s", strtotime("+" . $goods->days . " days"));
  552. $order->is_expire = 0;
  553. $order->pay_way = 1;
  554. $order->status = 2;
  555. $order->save();
  556. // 扣余额
  557. User::query()->where('id', $user->id)->decrement('balance', $amount * 100);
  558. // 记录余额操作日志
  559. $this->addUserBalanceLog($user->id, $order->oid, $user->balance, $user->balance - $amount, -1 * $amount, '购买服务:' . $goods->name);
  560. // 优惠券置为已使用
  561. if (!empty($coupon)) {
  562. if ($coupon->usage == 1) {
  563. $coupon->status = 1;
  564. $coupon->save();
  565. }
  566. // 写入日志
  567. Helpers::addCouponLog($coupon->id, $goods_id, $order->oid, '余额支付订单使用');
  568. }
  569. // 如果买的是套餐,则先将之前购买的所有套餐置都无效,并扣掉之前所有套餐的流量,重置用户已用流量为0
  570. if ($goods->type == 2) {
  571. $existOrderList = Order::query()
  572. ->with(['goods'])
  573. ->whereHas('goods', function ($q) {
  574. $q->where('type', 2);
  575. })
  576. ->where('user_id', $order->user_id)
  577. ->where('oid', '<>', $order->oid)
  578. ->where('is_expire', 0)
  579. ->where('status', 2)
  580. ->get();
  581. foreach ($existOrderList as $vo) {
  582. Order::query()->where('oid', $vo->oid)->update(['is_expire' => 1]);
  583. // 先判断,防止手动扣减过流量的用户流量被扣成负数
  584. if ($order->user->transfer_enable - $vo->goods->traffic * 1048576 <= 0) {
  585. // 写入用户流量变动记录
  586. Helpers::addUserTrafficModifyLog($user->id, $order->oid, 0, 0, '[余额支付]用户购买套餐,先扣减之前套餐的流量(扣完)');
  587. User::query()->where('id', $order->user_id)->update(['u' => 0, 'd' => 0, 'transfer_enable' => 0]);
  588. } else {
  589. // 写入用户流量变动记录
  590. $user = User::query()->where('id', $user->id)->first(); // 重新取出user信息
  591. Helpers::addUserTrafficModifyLog($user->id, $order->oid, $user->transfer_enable, ($user->transfer_enable - $vo->goods->traffic * 1048576), '[余额支付]用户购买套餐,先扣减之前套餐的流量(未扣完)');
  592. User::query()->where('id', $order->user_id)->update(['u' => 0, 'd' => 0]);
  593. User::query()->where('id', $order->user_id)->decrement('transfer_enable', $vo->goods->traffic * 1048576);
  594. }
  595. }
  596. }
  597. // 写入用户流量变动记录
  598. $user = User::query()->where('id', $user->id)->first(); // 重新取出user信息
  599. Helpers::addUserTrafficModifyLog($user->id, $order->oid, $user->transfer_enable, ($user->transfer_enable + $goods->traffic * 1048576), '[余额支付]用户购买商品,加上流量');
  600. // 把商品的流量加到账号上
  601. User::query()->where('id', $user->id)->increment('transfer_enable', $goods->traffic * 1048576);
  602. // 计算账号过期时间
  603. if ($user->expire_time < date('Y-m-d', strtotime("+" . $goods->days . " days"))) {
  604. $expireTime = date('Y-m-d', strtotime("+" . $goods->days . " days"));
  605. } else {
  606. $expireTime = $user->expire_time;
  607. }
  608. // 套餐就改流量重置日,流量包不改
  609. if ($goods->type == 2) {
  610. $traffic_reset_day = date('d');
  611. User::query()->where('id', $order->user_id)->update(['traffic_reset_day' => $traffic_reset_day, 'expire_time' => $expireTime, 'enable' => 1]);
  612. } else {
  613. User::query()->where('id', $order->user_id)->update(['expire_time' => $expireTime, 'enable' => 1]);
  614. }
  615. // 写入用户标签
  616. if ($goods->label) {
  617. // 用户默认标签
  618. $defaultLabels = [];
  619. if (self::$systemConfig['initial_labels_for_user']) {
  620. $defaultLabels = explode(',', self::$systemConfig['initial_labels_for_user']);
  621. }
  622. // 取出现有的标签
  623. $userLabels = UserLabel::query()->where('user_id', $user->id)->pluck('label_id')->toArray();
  624. $goodsLabels = GoodsLabel::query()->where('goods_id', $goods_id)->pluck('label_id')->toArray();
  625. // 标签去重
  626. $newUserLabels = array_values(array_unique(array_merge($userLabels, $goodsLabels, $defaultLabels)));
  627. // 删除用户所有标签
  628. UserLabel::query()->where('user_id', $user->id)->delete();
  629. // 生成标签
  630. foreach ($newUserLabels as $vo) {
  631. $obj = new UserLabel();
  632. $obj->user_id = $user->id;
  633. $obj->label_id = $vo;
  634. $obj->save();
  635. }
  636. }
  637. // 写入返利日志
  638. if ($user->referral_uid) {
  639. $this->addReferralLog($user->id, $user->referral_uid, $order->oid, $amount, $amount * self::$systemConfig['referral_percent']);
  640. }
  641. // 增加用户邀请码数量
  642. if ($goods->invite_num) {
  643. User::uid()->increment('invite_num', $goods->invite_num);
  644. }
  645. // 取消重复返利
  646. User::query()->where('id', $order->user_id)->update(['referral_uid' => 0]);
  647. DB::commit();
  648. return Response::json(['status' => 'success', 'data' => '', 'message' => '支付成功']);
  649. } catch (\Exception $e) {
  650. DB::rollBack();
  651. Log::error('支付订单失败:' . $e->getMessage());
  652. return Response::json(['status' => 'fail', 'data' => '', 'message' => '支付失败:' . $e->getMessage()]);
  653. }
  654. } else {
  655. $goods = Goods::query()->where('id', $goods_id)->where('status', 1)->first();
  656. if (empty($goods)) {
  657. return Redirect::to('services');
  658. }
  659. $view['goods'] = $goods;
  660. return Response::view('user.buy', $view);
  661. }
  662. }
  663. // 推广返利
  664. public function referral(Request $request)
  665. {
  666. if (Order::uid()->where('status', 2)->where('is_expire', 0)->where('origin_amount', '>', 0)->get()->isEmpty()) {
  667. return Response::view('auth.error', ['message' => '本功能对非付费用户禁用!请 <a class="btn btn-sm btn-danger" href="/">返回</a>']);
  668. }
  669. $view['referral_traffic'] = flowAutoShow(self::$systemConfig['referral_traffic'] * 1048576);
  670. $view['referral_percent'] = self::$systemConfig['referral_percent'];
  671. $view['referral_money'] = self::$systemConfig['referral_money'];
  672. $view['totalAmount'] = ReferralLog::uid()->sum('ref_amount') / 100;
  673. $view['canAmount'] = ReferralLog::uid()->where('status', 0)->sum('ref_amount') / 100;
  674. $view['link'] = self::$systemConfig['website_url'] . '/register?aff=' . Auth::user()->id;
  675. $view['referralLogList'] = ReferralLog::uid()->with('user')->orderBy('id', 'desc')->paginate(10);
  676. $view['referralApplyList'] = ReferralApply::uid()->with('user')->orderBy('id', 'desc')->paginate(10);
  677. $view['referralUserList'] = User::query()->select(['username', 'created_at'])->where('referral_uid', Auth::user()->id)->orderBy('id', 'desc')->paginate(10);
  678. return Response::view('user.referral', $view);
  679. }
  680. // 申请提现
  681. public function extractMoney(Request $request)
  682. {
  683. // 判断账户是否过期
  684. if (Auth::user()->expire_time < date('Y-m-d')) {
  685. return Response::json(['status' => 'fail', 'data' => '', 'message' => '申请失败:账号已过期,请先购买服务吧']);
  686. }
  687. // 判断是否已存在申请
  688. $referralApply = ReferralApply::uid()->whereIn('status', [0, 1])->first();
  689. if ($referralApply) {
  690. return Response::json(['status' => 'fail', 'data' => '', 'message' => '申请失败:已存在申请,请等待之前的申请处理完']);
  691. }
  692. // 校验可以提现金额是否超过系统设置的阀值
  693. $ref_amount = ReferralLog::uid()->where('status', 0)->sum('ref_amount');
  694. $ref_amount = $ref_amount / 100;
  695. if ($ref_amount < self::$systemConfig['referral_money']) {
  696. return Response::json(['status' => 'fail', 'data' => '', 'message' => '申请失败:满' . self::$systemConfig['referral_money'] . '元才可以提现,继续努力吧']);
  697. }
  698. // 取出本次申请关联返利日志ID
  699. $link_logs = '';
  700. $referralLog = ReferralLog::uid()->where('status', 0)->get();
  701. foreach ($referralLog as $log) {
  702. $link_logs .= $log->id . ',';
  703. }
  704. $link_logs = rtrim($link_logs, ',');
  705. $obj = new ReferralApply();
  706. $obj->user_id = Auth::user()->id;
  707. $obj->before = $ref_amount;
  708. $obj->after = 0;
  709. $obj->amount = $ref_amount;
  710. $obj->link_logs = $link_logs;
  711. $obj->status = 0;
  712. $obj->save();
  713. return Response::json(['status' => 'success', 'data' => '', 'message' => '申请成功,请等待管理员审核']);
  714. }
  715. // 帮助中心
  716. public function help(Request $request)
  717. {
  718. $view['articleList'] = Article::type(1)->orderBy('sort', 'desc')->orderBy('id', 'desc')->limit(10)->paginate(5);
  719. //付费用户判断
  720. $view['is_paying_user'] = Order::uid()->where('status', 2)->where('is_expire', 0)->where('origin_amount', '>', 0)->get()->isEmpty();
  721. //客户端安装
  722. $view['Shadowrocket_install'] = 'itms-services://?action=download-manifest&url=' . self::$systemConfig['website_url'] . '/clients/ipa.plist';
  723. $view['Quantumult_install'] = 'itms-services://?action=download-manifest&url=' . self::$systemConfig['website_url'] . '/ipa.plist';
  724. // 订阅连接
  725. $subscribe = UserSubscribe::query()->where('user_id', Auth::user()->id)->first();
  726. $view['subscribe_status'] = $subscribe->status;
  727. $subscribe_link = (self::$systemConfig['subscribe_domain'] ? self::$systemConfig['subscribe_domain'] : self::$systemConfig['website_url']) . '/s/' . $subscribe->code;
  728. $view['link'] = $subscribe_link;
  729. $view['Shadowrocket_link'] = 'shadowrocket://add/sub://' . base64url_encode($subscribe_link) . '?remarks=' . self::$systemConfig['website_name'] . '-' . self::$systemConfig['website_url'];
  730. $view['Shadowrocket_linkQrcode'] = 'sub://' . base64url_encode($subscribe_link) . '#' . base64url_encode(self::$systemConfig['website_name']);
  731. $view['Quantumult_linkOut'] = 'quantumult://configuration?server=' . base64url_encode($subscribe_link) . '&filter=' . base64url_encode('https://raw.githubusercontent.com/ConnersHua/Profiles/master/Quantumult/Pro.conf') . '&rejection=' . base64url_encode('https://raw.githubusercontent.com/ConnersHua/Profiles/master/Quantumult/Rejection.conf');
  732. $view['Quantumult_linkIn'] = 'quantumult://configuration?server=' . base64url_encode($subscribe_link) . '&filter=' . base64url_encode('https://raw.githubusercontent.com/ConnersHua/Profiles/master/Quantumult/BacktoCN.conf') . '&rejection=' . base64url_encode('https://raw.githubusercontent.com/ConnersHua/Profiles/master/Quantumult/Rejection.conf');
  733. return Response::view('user.help', $view);
  734. }
  735. // 更换订阅地址
  736. public function exchangeSubscribe(Request $request)
  737. {
  738. DB::beginTransaction();
  739. try {
  740. // 更换订阅码
  741. UserSubscribe::uid()->update(['code' => Helpers::makeSubscribeCode()]);
  742. // 更换连接密码
  743. User::uid()->update(['passwd' => makeRandStr()]);
  744. DB::commit();
  745. return Response::json(['status' => 'success', 'data' => '', 'message' => '更换成功']);
  746. } catch (\Exception $e) {
  747. DB::rollBack();
  748. Log::info("更换订阅地址异常:" . $e->getMessage());
  749. return Response::json(['status' => 'fail', 'data' => '', 'message' => '更换失败' . $e->getMessage()]);
  750. }
  751. }
  752. // 转换成管理员的身份
  753. public function switchToAdmin(Request $request)
  754. {
  755. if (!Session::has('admin')) {
  756. return Response::json(['status' => 'fail', 'data' => '', 'message' => '非法请求']);
  757. }
  758. // 管理员信息重新写入user
  759. Auth::loginUsingId(Session::get('admin'));
  760. Session::forget('admin');
  761. return Response::json(['status' => 'success', 'data' => '', 'message' => "身份切换成功"]);
  762. }
  763. // 卡券余额充值
  764. public function charge(Request $request)
  765. {
  766. $validator = Validator::make($request->all(), [
  767. 'coupon_sn' => [
  768. 'required',
  769. Rule::exists('coupon', 'sn')->where(function ($query) {
  770. $query->where('type', 3)->where('status', 0);
  771. }),
  772. ]
  773. ], [
  774. 'coupon_sn.required' => '券码不能为空',
  775. 'coupon_sn.exists' => '该券不可用'
  776. ]);
  777. if ($validator->fails()) {
  778. return Response::json(['status' => 'fail', 'data' => '', 'message' => $validator->getMessageBag()->first()]);
  779. }
  780. $coupon = Coupon::query()->where('sn', $request->input('coupon_sn'))->first();
  781. DB::beginTransaction();
  782. try {
  783. // 写入日志
  784. $this->addUserBalanceLog(Auth::user()->id, 0, Auth::user()->balance, Auth::user()->balance + $coupon->amount, $coupon->amount, '用户手动充值 - [充值券:' . $request->input('coupon_sn') . ']');
  785. // 余额充值
  786. User::uid()->increment('balance', $coupon->amount * 100);
  787. // 更改卡券状态
  788. $coupon->status = 1;
  789. $coupon->save();
  790. // 写入卡券日志
  791. Helpers::addCouponLog($coupon->id, 0, 0, '账户余额充值使用');
  792. DB::commit();
  793. return Response::json(['status' => 'success', 'data' => '', 'message' => '充值成功']);
  794. } catch (\Exception $e) {
  795. Log::error($e);
  796. DB::rollBack();
  797. return Response::json(['status' => 'fail', 'data' => '', 'message' => '充值失败']);
  798. }
  799. }
  800. }