UserController.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Components\Helpers;
  4. use App\Components\PushNotification;
  5. use App\Mail\newTicket;
  6. use App\Mail\replyTicket;
  7. use App\Models\Article;
  8. use App\Models\Coupon;
  9. use App\Models\Goods;
  10. use App\Models\Invite;
  11. use App\Models\Order;
  12. use App\Models\SsNode;
  13. use App\Models\SsNodeInfo;
  14. use App\Models\SsNodeLabel;
  15. use App\Models\SsNodePing;
  16. use App\Models\Ticket;
  17. use App\Models\TicketReply;
  18. use App\Models\User;
  19. use App\Models\UserLoginLog;
  20. use App\Models\UserSubscribe;
  21. use App\Models\UserTrafficDaily;
  22. use App\Models\UserTrafficHourly;
  23. use Auth;
  24. use Cache;
  25. use DB;
  26. use Exception;
  27. use Hash;
  28. use Illuminate\Http\JsonResponse;
  29. use Illuminate\Http\Request;
  30. use Illuminate\Validation\Rule;
  31. use Log;
  32. use Mail;
  33. use Redirect;
  34. use Response;
  35. use Session;
  36. use Validator;
  37. /**
  38. * 用户控制器
  39. *
  40. * Class UserController
  41. *
  42. * @package App\Http\Controllers
  43. */
  44. class UserController extends Controller {
  45. protected static $systemConfig;
  46. public function __construct() {
  47. self::$systemConfig = Helpers::systemConfig();
  48. }
  49. public function index(): \Illuminate\Http\Response {
  50. $user = Auth::getUser();
  51. $totalTransfer = $user->transfer_enable;
  52. $usedTransfer = $user->u + $user->d;
  53. $unusedTransfer = $totalTransfer - $usedTransfer > 0? $totalTransfer - $usedTransfer : 0;
  54. $expireTime = $user->expire_time;
  55. $view['remainDays'] = $expireTime < date('Y-m-d')? -1 : (strtotime($expireTime) - strtotime(date('Y-m-d'))) / Day;
  56. $view['resetDays'] = $user->reset_time? round((strtotime($user->reset_time) - strtotime(date('Y-m-d'))) / Day) : 0;
  57. $view['unusedTransfer'] = $unusedTransfer;
  58. $view['expireTime'] = $expireTime;
  59. $view['banedTime'] = $user->ban_time? date('Y-m-d H:i:s', $user->ban_time) : 0;
  60. $view['unusedPercent'] = $totalTransfer > 0? round($unusedTransfer / $totalTransfer, 2) : 0;
  61. $view['noticeList'] = Article::type(2)->orderByDesc('id')->Paginate(1); // 公告
  62. //流量异常判断
  63. $hourlyTraffic = UserTrafficHourly::query()
  64. ->whereUserId($user->id)
  65. ->whereNodeId(0)
  66. ->where('created_at', '>=', date('Y-m-d H:i:s', time() - Minute * 65))
  67. ->sum('total');
  68. $view['isTrafficWarning'] = $hourlyTraffic >= (self::$systemConfig['traffic_ban_value'] * GB)?: 0;
  69. //付费用户判断
  70. $view['not_paying_user'] = Order::uid()
  71. ->whereStatus(2)
  72. ->whereIsExpire(0)
  73. ->where('origin_amount', '>', 0)
  74. ->doesntExist();
  75. $view['userLoginLog'] = UserLoginLog::query()->whereUserId($user->id)->orderByDesc('id')->first(); // 近期登录日志
  76. $dailyData = [];
  77. $hourlyData = [];
  78. // 节点一个月内的流量
  79. // TODO:有bug
  80. $userTrafficDaily = UserTrafficDaily::query()
  81. ->whereUserId($user->id)
  82. ->whereNodeId(0)
  83. ->where('created_at', '<=', date('Y-m-d'))
  84. ->orderBy('created_at')
  85. ->pluck('total')
  86. ->toArray();
  87. $dailyTotal = date('d') - 1; // 今天不算,减一
  88. $dailyCount = count($userTrafficDaily);
  89. for($x = 0; $x < $dailyTotal - $dailyCount; $x++){
  90. $dailyData[$x] = 0;
  91. }
  92. for($x = $dailyTotal - $dailyCount; $x < $dailyTotal; $x++){
  93. $dailyData[$x] = round($userTrafficDaily[$x - ($dailyTotal - $dailyCount)] / GB, 3);
  94. }
  95. // 节点一天内的流量
  96. $userTrafficHourly = UserTrafficHourly::query()
  97. ->whereUserId($user->id)
  98. ->whereNodeId(0)
  99. ->where('created_at', '>=', date('Y-m-d'))
  100. ->orderBy('created_at')
  101. ->pluck('total')
  102. ->toArray();
  103. $hourlyTotal = date('H');
  104. $hourlyCount = count($userTrafficHourly);
  105. for($x = 0; $x < $hourlyTotal - $hourlyCount; $x++){
  106. $hourlyData[$x] = 0;
  107. }
  108. for($x = ($hourlyTotal - $hourlyCount); $x < $hourlyTotal; $x++){
  109. $hourlyData[$x] = round($userTrafficHourly[$x - ($hourlyTotal - $hourlyCount)] / GB, 3);
  110. }
  111. // 本月天数数据
  112. $monthDays = [];
  113. for($i = 1; $i <= date("d"); $i++){
  114. $monthDays[] = $i;
  115. }
  116. // 本日小时数据
  117. $dayHours = [];
  118. for($i = 1; $i <= date("H"); $i++){
  119. $dayHours[] = $i;
  120. }
  121. $view['trafficDaily'] = json_encode($dailyData);
  122. $view['trafficHourly'] = json_encode($hourlyData);
  123. $view['monthDays'] = json_encode($monthDays);
  124. $view['dayHours'] = json_encode($dayHours);
  125. return Response::view('user.index', $view);
  126. }
  127. // 签到
  128. public function checkIn(): JsonResponse {
  129. $user = Auth::getUser();
  130. // 系统开启登录加积分功能才可以签到
  131. if(!self::$systemConfig['is_checkin']){
  132. return Response::json(['status' => 'fail', 'message' => '系统未开启签到功能']);
  133. }
  134. // 已签到过,验证是否有效
  135. if(Cache::has('userCheckIn_'.$user->id)){
  136. return Response::json(['status' => 'fail', 'message' => '已经签到过了,明天再来吧']);
  137. }
  138. $traffic = random_int((int) self::$systemConfig['min_rand_traffic'],
  139. (int) self::$systemConfig['max_rand_traffic']) * MB;
  140. $ret = User::uid()->increment('transfer_enable', $traffic);
  141. if(!$ret){
  142. return Response::json(['status' => 'fail', 'message' => '签到失败,系统异常']);
  143. }
  144. // 写入用户流量变动记录
  145. Helpers::addUserTrafficModifyLog($user->id, 0, $user->transfer_enable, $user->transfer_enable + $traffic,
  146. '[签到]');
  147. // 多久后可以再签到
  148. $ttl = self::$systemConfig['traffic_limit_time']? self::$systemConfig['traffic_limit_time'] * Minute : Day;
  149. Cache::put('userCheckIn_'.$user->id, '1', $ttl);
  150. return Response::json(['status' => 'success', 'message' => '签到成功,系统送您 '.flowAutoShow($traffic).'流量']);
  151. }
  152. // 节点列表
  153. public function nodeList(Request $request) {
  154. if($request->isMethod('POST')){
  155. $node_id = $request->input('id');
  156. $infoType = $request->input('type');
  157. $node = SsNode::query()->whereId($node_id)->first();
  158. // 生成节点信息
  159. if($node->type == 1){
  160. $proxyType = $node->compatible? 'SS' : 'SSR';
  161. }else{
  162. $proxyType = 'V2Ray';
  163. }
  164. $data = $this->getUserNodeInfo(Auth::id(), $node->id, $infoType !== 'text'? 0 : 1);
  165. return Response::json(['status' => 'success', 'data' => $data, 'title' => $proxyType]);
  166. }
  167. // 获取当前用户可用节点
  168. $nodeList = SsNode::query()
  169. ->whereStatus(1)
  170. ->where('level', '<=', Auth::getUser()->level)
  171. ->orderByDesc('sort')
  172. ->orderBy('id')
  173. ->get();
  174. foreach($nodeList as $node){
  175. $node->ct = number_format(SsNodePing::query()->whereNodeId($node->id)->where('ct', '>', '0')->avg('ct'), 1,
  176. '.', '');
  177. $node->cu = number_format(SsNodePing::query()->whereNodeId($node->id)->where('cu', '>', '0')->avg('cu'), 1,
  178. '.', '');
  179. $node->cm = number_format(SsNodePing::query()->whereNodeId($node->id)->where('cm', '>', '0')->avg('cm'), 1,
  180. '.', '');
  181. $node->hk = number_format(SsNodePing::query()->whereNodeId($node->id)->where('hk', '>', '0')->avg('hk'), 1,
  182. '.', '');
  183. // 节点在线状态
  184. $node->offline = SsNodeInfo::query()
  185. ->whereNodeId($node->id)
  186. ->where('log_time', '>=', strtotime("-10 minutes"))
  187. ->orderByDesc('id')
  188. ->doesntExist();
  189. // 节点标签
  190. $node->labels = SsNodeLabel::query()->whereNodeId($node->id)->get();
  191. }
  192. $view['nodeList'] = $nodeList?: [];
  193. return Response::view('user.nodeList', $view);
  194. }
  195. // 公告详情
  196. public function article(Request $request): \Illuminate\Http\Response {
  197. $view['info'] = Article::query()->findOrFail($request->input('id'));
  198. return Response::view('user.article', $view);
  199. }
  200. // 修改个人资料
  201. public function profile(Request $request) {
  202. $user = Auth::getUser();
  203. if($request->isMethod('POST')){
  204. $old_password = $request->input('old_password');
  205. $new_password = $request->input('new_password');
  206. $username = $request->input('username');
  207. $wechat = $request->input('wechat');
  208. $qq = $request->input('qq');
  209. $passwd = $request->input('passwd');
  210. // 修改密码
  211. if($old_password && $new_password){
  212. if(!Hash::check($old_password, $user->password)){
  213. return Redirect::to('profile#tab_1')->withErrors('旧密码错误,请重新输入');
  214. }
  215. if(Hash::check($new_password, $user->password)){
  216. return Redirect::to('profile#tab_1')->withErrors('新密码不可与旧密码一样,请重新输入');
  217. }
  218. // 演示环境禁止改管理员密码
  219. if($user->id == 1 && env('APP_DEMO')){
  220. return Redirect::to('profile#tab_1')->withErrors('演示环境禁止修改管理员密码');
  221. }
  222. $ret = User::uid()->update(['password' => Hash::make($new_password)]);
  223. if(!$ret){
  224. return Redirect::to('profile#tab_1')->withErrors('修改失败');
  225. }
  226. return Redirect::to('profile#tab_1')->with('successMsg', '修改成功');
  227. // 修改代理密码
  228. }
  229. if($passwd){
  230. $ret = User::uid()->update(['passwd' => $passwd]);
  231. if(!$ret){
  232. return Redirect::to('profile#tab_3')->withErrors('修改失败');
  233. }
  234. return Redirect::to('profile#tab_3')->with('successMsg', '修改成功');
  235. }
  236. // 修改联系方式
  237. if(empty($username)){
  238. return Redirect::to('profile#tab_2')->withErrors('修改失败,昵称不能为空值');
  239. }
  240. $ret = User::uid()->update(['username' => $username, 'wechat' => $wechat, 'qq' => $qq]);
  241. if(!$ret){
  242. return Redirect::to('profile#tab_2')->withErrors('修改失败');
  243. }
  244. return Redirect::to('profile#tab_2')->with('successMsg', '修改成功');
  245. }
  246. return Response::view('user.profile');
  247. }
  248. // 商品列表
  249. public function services(Request $request): \Illuminate\Http\Response {
  250. $user = Auth::getUser();
  251. // 余额充值商品,只取10个
  252. $view['chargeGoodsList'] = Goods::type(3)->whereStatus(1)->orderBy('price')->limit(10)->get();
  253. $view['goodsList'] = Goods::query()
  254. ->whereStatus(1)
  255. ->where('type', '<=', '2')
  256. ->orderByDesc('type')
  257. ->orderByDesc('sort')
  258. ->paginate(10)
  259. ->appends($request->except('page'));
  260. $renewOrder = Order::query()
  261. ->with(['goods'])
  262. ->whereUserId($user->id)
  263. ->whereStatus(2)
  264. ->whereIsExpire(0)
  265. ->whereHas('goods', static function($q) {
  266. $q->whereType(2);
  267. })
  268. ->first();
  269. $renewPrice = $renewOrder? Goods::query()->whereId($renewOrder->goods_id)->first() : 0;
  270. $view['renewTraffic'] = $renewPrice? $renewPrice->renew : 0;
  271. // 有重置日时按照重置日为标准,否者就以过期日为标准
  272. $dataPlusDays = $user->reset_time?: $user->expire_time;
  273. $view['dataPlusDays'] = $dataPlusDays > date('Y-m-d')? round((strtotime($dataPlusDays) - strtotime(date('Y-m-d'))) / Day) : 0;
  274. return Response::view('user.services', $view);
  275. }
  276. //重置流量
  277. public function resetUserTraffic(): ?JsonResponse {
  278. $user = Auth::getUser();
  279. $temp = Order::uid()->whereStatus(2)->whereIsExpire(0)->with(['goods'])->whereHas('goods', static function($q) {
  280. $q->whereType(2);
  281. })->first();
  282. $renewCost = Goods::query()->whereId($temp->goods_id)->first()->renew;
  283. if($user->credit < $renewCost){
  284. return Response::json(['status' => 'fail', 'message' => '余额不足,请充值余额']);
  285. }
  286. User::uid()->update(['u' => 0, 'd' => 0]);
  287. // 扣余额
  288. User::query()->whereId($user->id)->decrement('credit', $renewCost * 100);
  289. // 记录余额操作日志
  290. Helpers::addUserCreditLog($user->id, '', $user->credit, $user->credit - $renewCost, -1 * $renewCost,
  291. '用户自行重置流量');
  292. return Response::json(['status' => 'success', 'message' => '重置成功']);
  293. }
  294. // 工单
  295. public function ticketList(Request $request): \Illuminate\Http\Response {
  296. $view['ticketList'] = Ticket::uid()->orderByDesc('id')->paginate(10)->appends($request->except('page'));
  297. return Response::view('user.ticketList', $view);
  298. }
  299. // 订单
  300. public function invoices(Request $request): \Illuminate\Http\Response {
  301. $view['orderList'] = Order::uid()
  302. ->with(['user', 'goods', 'coupon', 'payment'])
  303. ->orderByDesc('oid')
  304. ->paginate(10)
  305. ->appends($request->except('page'));
  306. return Response::view('user.invoices', $view);
  307. }
  308. public function activeOrder(Request $request): JsonResponse {
  309. $oid = $request->input('oid');
  310. $prepaidOrder = Order::query()->whereOid($oid)->first();
  311. if(!$prepaidOrder){
  312. return Response::json(['status' => 'fail', 'message' => '查无此单!']);
  313. }
  314. if($prepaidOrder->status != 3){
  315. return Response::json(['status' => 'fail', 'message' => '非预支付订单,无需再次启动!']);
  316. }
  317. (new ServiceController)->activePrepaidOrder($oid);
  318. return Response::json(['status' => 'success', 'message' => '激活成功']);
  319. }
  320. // 订单明细
  321. public function invoiceDetail($sn): \Illuminate\Http\Response {
  322. $view['order'] = Order::uid()->with(['goods', 'coupon', 'payment'])->whereOrderSn($sn)->firstOrFail();
  323. return Response::view('user.invoiceDetail', $view);
  324. }
  325. // 添加工单
  326. public function createTicket(Request $request): ?JsonResponse {
  327. $title = $request->input('title');
  328. $content = clean($request->input('content'));
  329. $content = str_replace(["atob", "eval"], "", $content);
  330. if(empty($title) || empty($content)){
  331. return Response::json(['status' => 'fail', 'message' => '请输入标题和内容']);
  332. }
  333. $obj = new Ticket();
  334. $obj->user_id = Auth::id();
  335. $obj->title = $title;
  336. $obj->content = $content;
  337. $obj->status = 0;
  338. $obj->save();
  339. if($obj->id){
  340. $emailTitle = "新工单提醒";
  341. $content = "标题:【".$title."】<br>用户:".Auth::getUser()->email."<br>内容:".$content;
  342. // 发邮件通知管理员
  343. if(self::$systemConfig['webmaster_email']){
  344. $logId = Helpers::addNotificationLog($emailTitle, $content, 1, self::$systemConfig['webmaster_email']);
  345. Mail::to(self::$systemConfig['webmaster_email'])->send(new newTicket($logId, $emailTitle, $content));
  346. }
  347. PushNotification::send($emailTitle, $content);
  348. return Response::json(['status' => 'success', 'message' => '提交成功']);
  349. }
  350. return Response::json(['status' => 'fail', 'message' => '提交失败']);
  351. }
  352. // 回复工单
  353. public function replyTicket(Request $request) {
  354. $id = $request->input('id');
  355. $ticket = Ticket::uid()->with('user')->whereId($id)->firstOrFail();
  356. if($request->isMethod('POST')){
  357. $content = clean($request->input('content'));
  358. $content = str_replace(["atob", "eval"], "", $content);
  359. $content = substr($content, 0, 300);
  360. if(empty($content)){
  361. return Response::json(['status' => 'fail', 'message' => '回复内容不能为空']);
  362. }
  363. if($ticket->status == 2){
  364. return Response::json(['status' => 'fail', 'message' => '错误:该工单已关闭']);
  365. }
  366. $obj = new TicketReply();
  367. $obj->ticket_id = $id;
  368. $obj->user_id = Auth::id();
  369. $obj->content = $content;
  370. $obj->save();
  371. if($obj->id){
  372. // 重新打开工单
  373. $ticket->status = 0;
  374. $ticket->save();
  375. $title = "工单回复提醒";
  376. $content = "标题:【".$ticket->title."】<br>用户回复:".$content;
  377. // 发邮件通知管理员
  378. if(self::$systemConfig['webmaster_email']){
  379. $logId = Helpers::addNotificationLog($title, $content, 1, self::$systemConfig['webmaster_email']);
  380. Mail::to(self::$systemConfig['webmaster_email'])->send(new replyTicket($logId, $title, $content));
  381. }
  382. PushNotification::send($title, $content);
  383. return Response::json(['status' => 'success', 'message' => '回复成功']);
  384. }
  385. return Response::json(['status' => 'fail', 'message' => '回复失败']);
  386. }
  387. $view['ticket'] = $ticket;
  388. $view['replyList'] = TicketReply::query()->whereTicketId($id)->with('user')->orderBy('id')->get();
  389. return Response::view('user.replyTicket', $view);
  390. }
  391. // 关闭工单
  392. public function closeTicket(Request $request): ?JsonResponse {
  393. $id = $request->input('id');
  394. $ret = Ticket::uid()->whereId($id)->update(['status' => 2]);
  395. if($ret){
  396. PushNotification::send('工单关闭提醒', '工单:ID'.$id.'用户已手动关闭');
  397. return Response::json(['status' => 'success', 'message' => '关闭成功']);
  398. }
  399. return Response::json(['status' => 'fail', 'message' => '关闭失败']);
  400. }
  401. // 邀请码
  402. public function invite(): \Illuminate\Http\Response {
  403. if(Order::uid()->whereStatus(2)->whereIsExpire(0)->where('origin_amount', '>', 0)->doesntExist()){
  404. return Response::view('auth.error',
  405. ['message' => '本功能对非付费用户禁用!请 <a class="btn btn-sm btn-danger" href="/">返 回</a>']);
  406. }
  407. $view['num'] = Auth::getUser()->invite_num; // 还可以生成的邀请码数量
  408. $view['inviteList'] = Invite::uid()->with(['generator', 'user'])->paginate(10); // 邀请码列表
  409. $view['referral_traffic'] = flowAutoShow(self::$systemConfig['referral_traffic'] * MB);
  410. $view['referral_percent'] = self::$systemConfig['referral_percent'];
  411. return Response::view('user.invite', $view);
  412. }
  413. // 生成邀请码
  414. public function makeInvite(): JsonResponse {
  415. if(Auth::getUser()->invite_num <= 0){
  416. return Response::json(['status' => 'fail', 'message' => '生成失败:已无邀请码生成名额']);
  417. }
  418. $obj = new Invite();
  419. $obj->uid = Auth::id();
  420. $obj->fuid = 0;
  421. $obj->code = strtoupper(mb_substr(md5(microtime().makeRandStr()), 8, 12));
  422. $obj->status = 0;
  423. $obj->dateline = date('Y-m-d H:i:s', strtotime("+".self::$systemConfig['user_invite_days']." days"));
  424. $obj->save();
  425. User::uid()->decrement('invite_num', 1);
  426. return Response::json(['status' => 'success', 'message' => '生成成功']);
  427. }
  428. // 使用优惠券
  429. public function redeemCoupon(Request $request): JsonResponse {
  430. $coupon_sn = $request->input('coupon_sn');
  431. $good_price = $request->input('price');
  432. if(empty($coupon_sn)){
  433. return Response::json(['status' => 'fail', 'title' => '使用失败', 'message' => '请输入您的优惠劵!']);
  434. }
  435. $coupon = Coupon::query()->whereSn($coupon_sn)->whereIn('type', [1, 2])->first();
  436. if(!$coupon){
  437. return Response::json(['status' => 'fail', 'title' => '优惠券不存在', 'message' => '请确认优惠券是否输入正确!']);
  438. }
  439. if($coupon->status == 1){
  440. return Response::json(['status' => 'fail', 'title' => '抱歉', 'message' => '优惠券已被使用!']);
  441. }
  442. if($coupon->status == 2){
  443. return Response::json(['status' => 'fail', 'title' => '抱歉', 'message' => '优惠券已失效!']);
  444. }
  445. if($coupon->available_end < time()){
  446. $coupon->status = 2;
  447. $coupon->save();
  448. return Response::json(['status' => 'fail', 'title' => '抱歉', 'message' => '优惠券已失效!']);
  449. }
  450. if($coupon->available_start > time()){
  451. return Response::json(['status' => 'fail', 'title' => '优惠券尚未生效', 'message' => '请等待活动正式开启']);
  452. }
  453. if($good_price < $coupon->rule){
  454. return Response::json(['status' => 'fail', 'title' => '使用条件未满足', 'message' => '请购买价格更高的套餐']);
  455. }
  456. $data = [
  457. 'name' => $coupon->name,
  458. 'type' => $coupon->type,
  459. 'amount' => $coupon->amount,
  460. 'discount' => $coupon->discount
  461. ];
  462. return Response::json(['status' => 'success', 'data' => $data, 'message' => '优惠券有效']);
  463. }
  464. // 购买服务
  465. public function buy($goods_id) {
  466. $goods = Goods::query()->whereId($goods_id)->whereStatus(1)->first();
  467. if(empty($goods)){
  468. return Redirect::to('services');
  469. }
  470. // 有重置日时按照重置日为标准,否者就以过期日为标准
  471. $dataPlusDays = Auth::getUser()->reset_time?: Auth::getUser()->expire_time;
  472. $view['dataPlusDays'] = $dataPlusDays > date('Y-m-d')? round((strtotime($dataPlusDays) - strtotime(date('Y-m-d'))) / Day) : 0;
  473. $view['activePlan'] = Order::uid()
  474. ->with(['goods'])
  475. ->whereIsExpire(0)
  476. ->whereStatus(2)
  477. ->whereHas('goods', static function($q) {
  478. $q->whereType(2);
  479. })
  480. ->exists();
  481. $view['goods'] = $goods;
  482. return Response::view('user.buy', $view);
  483. }
  484. // 帮助中心
  485. public function help(): \Illuminate\Http\Response {
  486. //$view['articleList'] = Article::type(1)->orderByDesc('sort')->orderByDesc('id')->limit(10)->paginate(5);
  487. $data = [];
  488. if(SsNode::query()->whereType(1)->whereStatus(1)->exists()){
  489. $data[] = 'ss';
  490. //array_push
  491. }
  492. if(SsNode::query()->whereType(2)->whereStatus(1)->exists()){
  493. $data[] = 'v2';
  494. }
  495. if(SsNode::query()->whereType(3)->whereStatus(1)->exists()){
  496. $data[] = 'trojan';
  497. }
  498. $view['sub'] = $data;
  499. //付费用户判断
  500. $view['not_paying_user'] = Order::uid()
  501. ->whereStatus(2)
  502. ->whereIsExpire(0)
  503. ->where('origin_amount', '>', 0)
  504. ->doesntExist();
  505. //客户端安装
  506. $view['Shadowrocket_install'] = 'itms-services://?action=download-manifest&url='.self::$systemConfig['website_url'].'/clients/Shadowrocket.plist';
  507. $view['Quantumult_install'] = 'itms-services://?action=download-manifest&url='.self::$systemConfig['website_url'].'/clients/Quantumult.plist';
  508. // 订阅连接
  509. $subscribe = UserSubscribe::query()->whereUserId(Auth::id())->first();
  510. $view['subscribe_status'] = $subscribe->status;
  511. $subscribe_link = (self::$systemConfig['subscribe_domain']?: self::$systemConfig['website_url']).'/s/'.$subscribe->code;
  512. $view['link'] = $subscribe_link;
  513. $view['subscribe_link'] = 'sub://'.base64url_encode($subscribe_link);
  514. $view['Shadowrocket_link'] = 'shadowrocket://add/sub://'.base64url_encode($subscribe_link).'?remarks='.(self::$systemConfig['website_name'].'-'.self::$systemConfig['website_url']);
  515. $view['Shadowrocket_linkQrcode'] = 'sub://'.base64url_encode($subscribe_link).'#'.base64url_encode(self::$systemConfig['website_name']);
  516. $view['Quantumult_linkOut'] = 'quantumult://configuration?server='.base64url_encode($subscribe_link).'&filter='.base64url_encode('https://raw.githubusercontent.com/ZBrettonYe/VPN-Rules-Collection/master/Profiles/Quantumult/Pro.conf').'&rejection='.base64url_encode('https://raw.githubusercontent.com/ZBrettonYe/VPN-Rules-Collection/master/Profiles/Quantumult/Rejection.conf');
  517. $view['Quantumult_linkIn'] = 'quantumult://configuration?server='.base64url_encode($subscribe_link).'&filter='.base64url_encode('https://raw.githubusercontent.com/ZBrettonYe/VPN-Rules-Collection/master/Profiles/Quantumult/BacktoCN.conf').'&rejection='.base64url_encode('https://raw.githubusercontent.com/ZBrettonYe/VPN-Rules-Collection/master/Profiles/Quantumult/Rejection.conf');
  518. return Response::view('user.help', $view);
  519. }
  520. // 更换订阅地址
  521. public function exchangeSubscribe(): ?JsonResponse {
  522. DB::beginTransaction();
  523. try{
  524. // 更换订阅码
  525. UserSubscribe::uid()->update(['code' => Helpers::makeSubscribeCode()]);
  526. // 更换连接密码
  527. User::uid()->update(['passwd' => makeRandStr()]);
  528. DB::commit();
  529. return Response::json(['status' => 'success', 'message' => '更换成功']);
  530. }catch(Exception $e){
  531. DB::rollBack();
  532. Log::info("更换订阅地址异常:".$e->getMessage());
  533. return Response::json(['status' => 'fail', 'message' => '更换失败'.$e->getMessage()]);
  534. }
  535. }
  536. // 转换成管理员的身份
  537. public function switchToAdmin(): JsonResponse {
  538. if(!Session::has('admin')){
  539. return Response::json(['status' => 'fail', 'message' => '非法请求']);
  540. }
  541. // 管理员信息重新写入user
  542. Auth::loginUsingId(Session::get('admin'));
  543. Session::forget('admin');
  544. return Response::json(['status' => 'success', 'message' => "身份切换成功"]);
  545. }
  546. // 卡券余额充值
  547. public function charge(Request $request): ?JsonResponse {
  548. $validator = Validator::make($request->all(), [
  549. 'coupon_sn' => [
  550. 'required',
  551. Rule::exists('coupon', 'sn')->where(static function($query) {
  552. $query->whereType(3)->whereStatus(0);
  553. }),
  554. ]
  555. ], ['coupon_sn.required' => '券码不能为空', 'coupon_sn.exists' => '该券不可用']);
  556. if($validator->fails()){
  557. return Response::json(['status' => 'fail', 'message' => $validator->getMessageBag()->first()]);
  558. }
  559. $coupon = Coupon::query()->whereSn($request->input('coupon_sn'))->first();
  560. try{
  561. DB::beginTransaction();
  562. // 写入日志
  563. $user = Auth::getUser();
  564. Helpers::addUserCreditLog($user->id, 0, $user->credit, $user->credit + $coupon->amount, $coupon->amount,
  565. '用户手动充值 - [充值券:'.$request->input('coupon_sn').']');
  566. // 余额充值
  567. User::uid()->increment('credit', $coupon->amount * 100);
  568. // 更改卡券状态
  569. Coupon::query()->whereId($coupon->id)->update(['status' => 1]);
  570. // 写入卡券日志
  571. Helpers::addCouponLog($coupon->id, 0, 0, '账户余额充值使用');
  572. DB::commit();
  573. return Response::json(['status' => 'success', 'message' => '充值成功']);
  574. }catch(Exception $e){
  575. Log::error($e);
  576. DB::rollBack();
  577. return Response::json(['status' => 'fail', 'message' => '充值失败']);
  578. }
  579. }
  580. }