AdminController.php 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Components\Helpers;
  4. use App\Components\IPIP;
  5. use App\Components\PushNotification;
  6. use App\Components\QQWry;
  7. use App\Models\Article;
  8. use App\Models\Config;
  9. use App\Models\Country;
  10. use App\Models\Invite;
  11. use App\Models\Label;
  12. use App\Models\Level;
  13. use App\Models\NotificationLog;
  14. use App\Models\Order;
  15. use App\Models\ReferralApply;
  16. use App\Models\ReferralLog;
  17. use App\Models\SsConfig;
  18. use App\Models\SsNode;
  19. use App\Models\SsNodeIp;
  20. use App\Models\SsNodeLabel;
  21. use App\Models\SsNodeTrafficDaily;
  22. use App\Models\User;
  23. use App\Models\UserBanLog;
  24. use App\Models\UserCreditLog;
  25. use App\Models\UserGroup;
  26. use App\Models\UserLoginLog;
  27. use App\Models\UserSubscribe;
  28. use App\Models\UserTrafficHourly;
  29. use App\Models\UserTrafficLog;
  30. use App\Models\UserTrafficModifyLog;
  31. use Auth;
  32. use DB;
  33. use Exception;
  34. use Hash;
  35. use Illuminate\Http\JsonResponse;
  36. use Illuminate\Http\RedirectResponse;
  37. use Illuminate\Http\Request;
  38. use Log;
  39. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  40. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  41. use Redirect;
  42. use Response;
  43. use Session;
  44. use Str;
  45. use Validator;
  46. /**
  47. * 管理员控制器
  48. *
  49. * Class AdminController
  50. *
  51. * @package App\Http\Controllers
  52. */
  53. class AdminController extends Controller {
  54. protected static $systemConfig;
  55. public function __construct() {
  56. self::$systemConfig = Helpers::systemConfig();
  57. }
  58. public function index(): \Illuminate\Http\Response {
  59. $past = strtotime("-".self::$systemConfig['expire_days']." days");
  60. $view['expireDays'] = self::$systemConfig['expire_days'];
  61. $view['totalUserCount'] = User::query()->count(); // 总用户数
  62. $view['enableUserCount'] = User::query()->whereEnable(1)->count(); // 有效用户数
  63. $view['activeUserCount'] = User::query()->where('t', '>=', $past)->count(); // 活跃用户数
  64. $view['unActiveUserCount'] = User::query()->whereBetween('t', [1, $past])->whereEnable(1)->count(); // 不活跃用户数
  65. $view['onlineUserCount'] = User::query()->where('t', '>=', strtotime("-10 minutes"))->count(); // 10分钟内在线用户数
  66. $view['expireWarningUserCount'] = User::query()->whereBetween('expire_time', [
  67. date('Y-m-d'),
  68. strtotime("+".self::$systemConfig['expire_days']." days")
  69. ])->count(); // 临近过期用户数
  70. $view['largeTrafficUserCount'] = User::query()
  71. ->whereRaw('(u + d) >= 107374182400')
  72. ->where('status', '<>', -1)
  73. ->count(); // 流量超过100G的用户
  74. $view['flowAbnormalUserCount'] = count($this->trafficAbnormal());// 1小时内流量异常用户
  75. $view['nodeCount'] = SsNode::query()->count();
  76. $view['unnormalNodeCount'] = SsNode::query()->whereStatus(0)->count();
  77. $view['flowCount'] = flowAutoShow(SsNodeTrafficDaily::query()
  78. ->where('created_at', '>=',
  79. date('Y-m-d', strtotime("-30 days")))
  80. ->sum('total'));
  81. $view['totalFlowCount'] = flowAutoShow(SsNodeTrafficDaily::query()->sum('total'));
  82. $view['totalCredit'] = User::query()->where('credit', '<>', 0)->sum('credit') / 100;
  83. $view['totalWaitRefAmount'] = ReferralLog::query()->whereIn('status', [0, 1])->sum('ref_amount') / 100;
  84. $view['totalRefAmount'] = ReferralApply::query()->whereStatus(2)->sum('amount') / 100;
  85. $view['totalOrder'] = Order::query()->count();
  86. $view['totalOnlinePayOrder'] = Order::query()->wherePayWay(2)->count();
  87. $view['totalSuccessOrder'] = Order::query()->whereStatus(2)->count();
  88. $view['todaySuccessOrder'] = Order::query()->whereStatus(2)->whereDate('created_at', date('Y-m-d'))->count();
  89. // 今日
  90. $view['todayRegister'] = User::query()->whereDate('created_at', date('Y-m-d'))->count();
  91. return Response::view('admin.index', $view);
  92. }
  93. // 1小时内流量异常用户
  94. private function trafficAbnormal(): array {
  95. $result = [];
  96. $userTotalTrafficList = UserTrafficHourly::query()
  97. ->whereNodeId(0)
  98. ->where('total', '>', MB * 50)
  99. ->where('created_at', '>=', date('Y-m-d H:i:s', time() - 3900))
  100. ->groupBy('user_id')
  101. ->selectRaw("user_id, sum(total) as totalTraffic")
  102. ->get(); // 只统计50M以上的记录,加快速度
  103. foreach($userTotalTrafficList as $user){
  104. if($user->totalTraffic > self::$systemConfig['traffic_ban_value'] * GB){
  105. $result[] = $user->user_id;
  106. }
  107. }
  108. return $result;
  109. }
  110. // 用户列表
  111. public function userList(Request $request): \Illuminate\Http\Response {
  112. $id = $request->input('id');
  113. $email = $request->input('email');
  114. $wechat = $request->input('wechat');
  115. $qq = $request->input('qq');
  116. $port = $request->input('port');
  117. $status = $request->input('status');
  118. $enable = $request->input('enable');
  119. $online = $request->input('online');
  120. $flowAbnormal = $request->input('flowAbnormal');
  121. $expireWarning = $request->input('expireWarning');
  122. $largeTraffic = $request->input('largeTraffic');
  123. $query = User::query()->with(['subscribe']);
  124. if(isset($id)){
  125. $query->whereId($id);
  126. }
  127. if(isset($email)){
  128. $query->where('email', 'like', '%'.$email.'%');
  129. }
  130. if(isset($wechat)){
  131. $query->where('wechat', 'like', '%'.$wechat.'%');
  132. }
  133. if(isset($qq)){
  134. $query->where('qq', 'like', '%'.$qq.'%');
  135. }
  136. if(isset($port)){
  137. $query->wherePort($port);
  138. }
  139. if(isset($status)){
  140. $query->whereStatus($status);
  141. }
  142. if(isset($enable)){
  143. $query->whereEnable($enable);
  144. }
  145. // 流量超过100G的
  146. if($largeTraffic){
  147. $query->whereIn('status', [0, 1])->whereRaw('(u + d) >= 107374182400');
  148. }
  149. // 临近过期提醒
  150. if($expireWarning){
  151. $query->whereBetween('expire_time',
  152. [date('Y-m-d'), date('Y-m-d', strtotime("+".self::$systemConfig['expire_days']." days"))]);
  153. }
  154. // 当前在线
  155. if($online){
  156. $query->where('t', '>=', strtotime("-10 minutes"));
  157. }
  158. // 不活跃用户
  159. if($request->input('unActive')){
  160. $query->whereBetween('t', [1, strtotime("-".self::$systemConfig['expire_days']." days")])->whereEnable(1);
  161. }
  162. // 1小时内流量异常用户
  163. if($flowAbnormal){
  164. $query->whereIn('id', $this->trafficAbnormal());
  165. }
  166. $userList = $query->latest()->paginate(15)->appends($request->except('page'));
  167. foreach($userList as $user){
  168. $user->transfer_enable = flowAutoShow($user->transfer_enable);
  169. $user->used_flow = flowAutoShow($user->u + $user->d);
  170. if($user->expire_time < date('Y-m-d')){
  171. $user->expireWarning = -1; // 已过期
  172. }elseif($user->expire_time == date('Y-m-d')){
  173. $user->expireWarning = 0; // 今天过期
  174. }elseif($user->expire_time > date('Y-m-d') && $user->expire_time <= date('Y-m-d', strtotime("+30 days"))){
  175. $user->expireWarning = 1; // 最近一个月过期
  176. }else{
  177. $user->expireWarning = 2; // 大于一个月过期
  178. }
  179. // 流量异常警告
  180. $time = date('Y-m-d H:i:s', time() - 3900);
  181. $totalTraffic = UserTrafficHourly::query()
  182. ->userHourly($user->id)
  183. ->where('created_at', '>=', $time)
  184. ->sum('total');
  185. $user->trafficWarning = $totalTraffic > (self::$systemConfig['traffic_ban_value'] * GB)? 1 : 0;
  186. // 订阅地址
  187. $user->link = (self::$systemConfig['subscribe_domain']?: self::$systemConfig['website_url']).'/s/'.$user->subscribe->code;
  188. }
  189. $view['userList'] = $userList;
  190. return Response::view('admin.user.userList', $view);
  191. }
  192. // 添加账号
  193. public function addUser(Request $request) {
  194. if($request->isMethod('POST')){
  195. // 校验email是否已存在
  196. $exists = User::query()->whereEmail($request->input('email'))->first();
  197. if($exists){
  198. return Response::json(['status' => 'fail', 'message' => '用户名已存在,请重新输入']);
  199. }
  200. $user = new User();
  201. $user->username = $request->input('username');
  202. $user->email = $request->input('email');
  203. $user->password = Hash::make($request->input('password')?: makeRandStr());
  204. $user->port = $request->input('port')?: $this->makePort();
  205. $user->passwd = $request->input('passwd')?: makeRandStr();
  206. $user->vmess_id = $request->input('uuid')?: Str::uuid();
  207. $user->transfer_enable = toGB($request->input('transfer_enable')?: 0);
  208. $user->enable = $request->input('enable')?: 0;
  209. $user->method = $request->input('method');
  210. $user->protocol = $request->input('protocol');
  211. $user->obfs = $request->input('obfs');
  212. $user->speed_limit = $request->input('speed_limit') * Mbps;
  213. $user->wechat = $request->input('wechat');
  214. $user->qq = $request->input('qq');
  215. $user->enable_time = $request->input('enable_time')?: date('Y-m-d');
  216. $user->expire_time = $request->input('expire_time')?: date('Y-m-d', strtotime("+365 days"));
  217. $user->remark = str_replace(["atob", "eval"], "", $request->input('remark'));
  218. $user->level = $request->input('level')?: 0;
  219. $user->group_id = $request->input('group_id')?: 0;
  220. $user->reg_ip = getClientIp();
  221. $user->reset_time = $request->input('reset_time') > date('Y-m-d')? $request->input('reset_time') : null;
  222. $user->invite_num = $request->input('invite_num')?: 0;
  223. $user->status = $request->input('status')?: 0;
  224. $user->save();
  225. if($user->id){
  226. // 生成订阅码
  227. $subscribe = new UserSubscribe();
  228. $subscribe->user_id = $user->id;
  229. $subscribe->code = Helpers::makeSubscribeCode();
  230. $subscribe->times = 0;
  231. $subscribe->save();
  232. // 写入用户流量变动记录
  233. Helpers::addUserTrafficModifyLog($user->id, 0, 0, toGB($request->input('transfer_enable', 0)),
  234. '后台手动添加用户');
  235. return Response::json(['status' => 'success', 'message' => '添加成功']);
  236. }
  237. return Response::json(['status' => 'fail', 'message' => '添加失败']);
  238. }
  239. // 生成一个可用端口
  240. $view['methodList'] = Helpers::methodList();
  241. $view['protocolList'] = Helpers::protocolList();
  242. $view['obfsList'] = Helpers::obfsList();
  243. $view['levelList'] = Level::query()->orderBy('level')->get();
  244. $view['groupList'] = UserGroup::query()->orderBy('id')->get();
  245. return Response::view('admin.user.userInfo', $view);
  246. }
  247. // 生成端口
  248. public function makePort() {
  249. return self::$systemConfig['is_rand_port']? Helpers::getRandPort() : Helpers::getOnlyPort();
  250. }
  251. // 批量生成账号
  252. public function batchAddUsers(Request $request): ?JsonResponse {
  253. $amount = $request->input('amount');
  254. try{
  255. DB::beginTransaction();
  256. for($i = 0; $i < $amount; $i++){
  257. $uid = Helpers::addUser('批量生成-'.makeRandStr(), Hash::make(makeRandStr()), toGB(1024), 365);
  258. // 生成一个可用端口
  259. if($uid){
  260. // 生成订阅码
  261. $subscribe = new UserSubscribe();
  262. $subscribe->user_id = $uid;
  263. $subscribe->code = Helpers::makeSubscribeCode();
  264. $subscribe->times = 0;
  265. $subscribe->save();
  266. // 写入用户流量变动记录
  267. Helpers::addUserTrafficModifyLog($uid, 0, 0, toGB(1024), '后台批量生成用户');
  268. }
  269. }
  270. DB::commit();
  271. return Response::json(['status' => 'success', 'message' => '批量生成账号成功']);
  272. }catch(Exception $e){
  273. DB::rollBack();
  274. return Response::json(['status' => 'fail', 'message' => '批量生成账号失败:'.$e->getMessage()]);
  275. }
  276. }
  277. // 编辑账号
  278. public function editUser(Request $request, $id) {
  279. if($request->isMethod('POST')){
  280. $email = $request->input('email');
  281. $password = $request->input('password');
  282. $port = $request->input('port');
  283. $transfer_enable = $request->input('transfer_enable');
  284. $is_admin = $request->input('is_admin');
  285. $status = $request->input('status');
  286. // 校验email是否已存在
  287. $exists = User::query()->where('id', '<>', $id)->whereEmail($email)->first();
  288. if($exists){
  289. return Response::json(['status' => 'fail', 'message' => '用户名已存在,请重新输入']);
  290. }
  291. // 校验端口是否已存在
  292. $exists = User::query()->where('id', '<>', $id)->where('port', '>', 0)->wherePort($port)->first();
  293. if($exists){
  294. return Response::json(['status' => 'fail', 'message' => '端口已存在,请重新输入']);
  295. }
  296. // 禁止取消默认管理员
  297. if($id == 1 && $is_admin == 0){
  298. return Response::json(['status' => 'fail', 'message' => '系统默认管理员不可取消']);
  299. }
  300. // 用户编辑前的信息
  301. $user = User::find($id);
  302. try{
  303. DB::beginTransaction();
  304. $data = [
  305. 'username' => $request->input('username'),
  306. 'email' => $email,
  307. 'port' => $port,
  308. 'passwd' => $request->input('passwd')?: makeRandStr(),
  309. 'vmess_id' => $request->input('uuid')?: Str::uuid(),
  310. 'transfer_enable' => toGB($transfer_enable?: 0),
  311. 'enable' => $status < 0? 0 : $request->input('enable'),
  312. 'method' => $request->input('method'),
  313. 'protocol' => $request->input('protocol'),
  314. 'obfs' => $request->input('obfs'),
  315. 'speed_limit' => $request->input('speed_limit') * Mbps,
  316. 'wechat' => $request->input('wechat'),
  317. 'qq' => $request->input('qq'),
  318. 'enable_time' => $request->input('enable_time')?: date('Y-m-d'),
  319. 'expire_time' => $request->input('expire_time')?: date('Y-m-d', strtotime("+365 days")),
  320. 'remark' => str_replace("eval", "", str_replace("atob", "", $request->input('remark'))),
  321. 'level' => $request->input('level'),
  322. 'group_id' => $request->input('group_id'),
  323. 'reset_time' => $request->input('reset_time'),
  324. 'status' => $status
  325. ];
  326. // 只有admin才有权限操作管理员属性
  327. if(Auth::getUser()->is_admin == 1){
  328. $data['is_admin'] = (int) $is_admin;
  329. }
  330. // 非演示环境才可以修改管理员密码
  331. if(!empty($password) && !(config('app.demo') && $id == 1)){
  332. $data['password'] = Hash::make($password);
  333. }
  334. User::query()->whereId($id)->update($data);
  335. // 写入用户流量变动记录
  336. if($user->transfer_enable != toGB($transfer_enable)){
  337. Helpers::addUserTrafficModifyLog($id, 0, $user->transfer_enable, toGB($transfer_enable),
  338. '后台手动编辑用户');
  339. }
  340. DB::commit();
  341. return Response::json(['status' => 'success', 'message' => '编辑成功']);
  342. }catch(Exception $e){
  343. DB::rollBack();
  344. Log::error('编辑用户信息异常:'.$e->getMessage());
  345. return Response::json(['status' => 'fail', 'message' => '编辑失败']);
  346. }
  347. }else{
  348. $user = User::query()->with(['referral'])->whereId($id)->first();
  349. if($user){
  350. $user->transfer_enable = flowToGB($user->transfer_enable);
  351. }
  352. $view['user'] = $user;
  353. $view['methodList'] = Helpers::methodList();
  354. $view['protocolList'] = Helpers::protocolList();
  355. $view['obfsList'] = Helpers::obfsList();
  356. $view['levelList'] = Level::query()->orderBy('level')->get();
  357. $view['groupList'] = UserGroup::query()->orderBy('id')->get();
  358. return view('admin.user.userInfo', $view)->with(compact('user'));
  359. }
  360. }
  361. // 删除用户
  362. public function delUser(Request $request): ?JsonResponse {
  363. $id = $request->input('id');
  364. if($id <= 1){
  365. return Response::json(['status' => 'fail', 'message' => '系统管理员不可删除']);
  366. }
  367. try{
  368. DB::beginTransaction();
  369. User::query()->whereId($id)->delete();
  370. UserSubscribe::query()->whereUserId($id)->delete();
  371. UserBanLog::query()->whereUserId($id)->delete();
  372. UserCreditLog::query()->whereUserId($id)->delete();
  373. UserTrafficModifyLog::query()->whereUserId($id)->delete();
  374. UserLoginLog::query()->whereUserId($id)->delete();
  375. DB::commit();
  376. return Response::json(['status' => 'success', 'message' => '删除成功']);
  377. }catch(Exception $e){
  378. Log::error($e);
  379. DB::rollBack();
  380. return Response::json(['status' => 'fail', 'message' => '删除失败']);
  381. }
  382. }
  383. // 文章列表
  384. public function articleList(Request $request): \Illuminate\Http\Response {
  385. $view['list'] = Article::query()->orderByDesc('sort')->paginate(15)->appends($request->except('page'));
  386. return Response::view('admin.article.articleList', $view);
  387. }
  388. // 添加文章
  389. public function addArticle(Request $request) {
  390. if($request->isMethod('POST')){
  391. $article = new Article();
  392. $article->title = $request->input('title');
  393. $article->type = $request->input('type', 1);
  394. $article->author = '管理员';
  395. $article->summary = $request->input('summary');
  396. // LOGO
  397. if($article->type == 4){
  398. $article->logo = $request->input('logo');
  399. }else{
  400. $logo = '';
  401. if($request->hasFile('logo')){
  402. $logo = $this->uploadFile($request->file('logo'));
  403. if(!$logo){
  404. Session::flash('errorMsg', 'LOGO不合法');
  405. return Redirect::back()->withInput();
  406. }
  407. }
  408. $article = new Article();
  409. $article->title = $request->input('title');
  410. $article->type = $request->input('type', 1);
  411. $article->author = '管理员';
  412. $article->summary = $request->input('summary');
  413. $article->logo = $logo;
  414. }
  415. $article->content = $request->input('content');
  416. $article->sort = $request->input('sort', 0);
  417. $article->save();
  418. if($article->id){
  419. Session::flash('successMsg', '添加成功');
  420. }else{
  421. Session::flash('errorMsg', '添加失败');
  422. }
  423. return Redirect::to('admin/articleList');
  424. }
  425. return Response::view('admin.article.addArticle');
  426. }
  427. // 编辑文章
  428. public function editArticle(Request $request) {
  429. $id = $request->input('id');
  430. if($request->isMethod('POST')){
  431. $title = $request->input('title');
  432. $type = $request->input('type');
  433. $summary = $request->input('summary');
  434. $content = $request->input('content');
  435. $sort = $request->input('sort');
  436. // 商品LOGO
  437. if($type == 4){
  438. $logo = $request->input('logo');
  439. }else{
  440. $logo = '';
  441. if($request->hasFile('logo')){
  442. $logo = $this->uploadFile($request->file('logo'));
  443. if(!$logo){
  444. Session::flash('errorMsg', 'LOGO不合法');
  445. return Redirect::back()->withInput();
  446. }
  447. }
  448. }
  449. $data = ['type' => $type, 'title' => $title, 'summary' => $summary, 'content' => $content, 'sort' => $sort];
  450. if($logo){
  451. $data['logo'] = $logo;
  452. }
  453. $ret = Article::query()->whereId($id)->update($data);
  454. if($ret){
  455. Session::flash('successMsg', '编辑成功');
  456. }else{
  457. Session::flash('errorMsg', '编辑失败');
  458. }
  459. return Redirect::to('admin/editArticle?id='.$id);
  460. }
  461. $view['article'] = Article::find($id);
  462. return Response::view('admin.article.editArticle', $view);
  463. }
  464. // 删除文章
  465. public function delArticle(Request $request): ?JsonResponse {
  466. $id = $request->input('id');
  467. $ret = Article::query()->whereId($id)->delete();
  468. if($ret){
  469. return Response::json(['status' => 'success', 'message' => '删除成功']);
  470. }
  471. return Response::json(['status' => 'fail', 'message' => '删除失败']);
  472. }
  473. // 流量日志
  474. public function trafficLog(Request $request): \Illuminate\Http\Response {
  475. $port = $request->input('port');
  476. $user_id = $request->input('user_id');
  477. $email = $request->input('email');
  478. $nodeId = $request->input('nodeId');
  479. $startTime = $request->input('startTime');
  480. $endTime = $request->input('endTime');
  481. $query = UserTrafficLog::query()->with(['user', 'node']);
  482. if(isset($port)){
  483. $query->whereHas('user', static function($q) use ($port) {
  484. $q->wherePort($port);
  485. });
  486. }
  487. if(isset($user_id)){
  488. $query->whereUserId($user_id);
  489. }
  490. if(isset($email)){
  491. $query->whereHas('user', static function($q) use ($email) {
  492. $q->where('email', 'like', '%'.$email.'%');
  493. });
  494. }
  495. if(isset($nodeId)){
  496. $query->whereNodeId($nodeId);
  497. }
  498. if(isset($startTime)){
  499. $query->where('log_time', '>=', strtotime($startTime));
  500. }
  501. if(isset($endTime)){
  502. $query->where('log_time', '<=', strtotime($endTime));
  503. }
  504. // 已使用流量
  505. $view['totalTraffic'] = flowAutoShow($query->sum('u') + $query->sum('d'));
  506. $list = $query->latest('log_time')->paginate(20)->appends($request->except('page'));
  507. foreach($list as $vo){
  508. $vo->u = flowAutoShow($vo->u);
  509. $vo->d = flowAutoShow($vo->d);
  510. $vo->log_time = date('Y-m-d H:i:s', $vo->log_time);
  511. }
  512. $view['list'] = $list;
  513. $view['nodeList'] = SsNode::query()->whereStatus(1)->orderByDesc('sort')->latest()->get();
  514. return Response::view('admin.logs.trafficLog', $view);
  515. }
  516. // 导出配置信息
  517. public function export(Request $request, $id) {
  518. if(empty($id)){
  519. return Redirect::to('admin/userList');
  520. }
  521. $user = User::find($id);
  522. if(empty($user)){
  523. return Redirect::to('admin/userList');
  524. }
  525. if($request->isMethod('POST')){
  526. $infoType = $request->input('type');
  527. $node = SsNode::find($request->input('id'));
  528. if($node->type == 1){
  529. if($node->compatible){
  530. $proxyType = 'SS';
  531. }else{
  532. $proxyType = 'SSR';
  533. }
  534. }else{
  535. $proxyType = 'V2Ray';
  536. }
  537. $data = $this->getUserNodeInfo($id, $node->id, $infoType !== 'text'? 0 : 1);
  538. return Response::json(['status' => 'success', 'data' => $data, 'title' => $proxyType]);
  539. }
  540. $view['nodeList'] = SsNode::query()
  541. ->whereStatus(1)
  542. ->orderByDesc('sort')
  543. ->orderBy('id')
  544. ->paginate(15)
  545. ->appends($request->except('page'));
  546. $view['user'] = $user;
  547. return Response::view('admin.user.export', $view);
  548. }
  549. // 导出原版SS用户配置信息
  550. public function exportSSJson() {
  551. $userList = User::query()->where('port', '>', 0)->get();
  552. $json = '';
  553. if(!$userList->isEmpty()){
  554. $userPassword = [];
  555. foreach($userList as $user){
  556. $userPassword[] = $user->port.":".$user->passwd;
  557. }
  558. $json = json_encode([
  559. 'server' => '0.0.0.0',
  560. 'local_address' => '127.0.0.1',
  561. 'local_port' => 1080,
  562. 'port_password' => $userPassword,
  563. 'timeout' => 300,
  564. 'method' => Helpers::getDefaultMethod(),
  565. 'fast_open' => false,
  566. ]);
  567. }
  568. // 生成JSON文件
  569. $fileName = makeRandStr('16').'_shadowsocks.json';
  570. $filePath = public_path('downloads/'.$fileName);
  571. file_put_contents($filePath, $json);
  572. if(!is_file($filePath)){
  573. exit('文件生成失败,请检查目录权限');
  574. }
  575. return Response::download($filePath);
  576. }
  577. // 修改个人资料
  578. public function profile(Request $request) {
  579. if($request->isMethod('POST')){
  580. $new_password = $request->input('new_password');
  581. if(!Hash::check($request->input('old_password'), Auth::getUser()->password)){
  582. return Redirect::back()->withErrors('旧密码错误,请重新输入');
  583. }
  584. if(Hash::check($new_password, Auth::getUser()->password)){
  585. return Redirect::back()->withErrors('新密码不可与旧密码一样,请重新输入');
  586. }
  587. $ret = User::uid()->update(['password' => Hash::make($new_password)]);
  588. if(!$ret){
  589. return Redirect::back()->withErrors('修改失败');
  590. }
  591. return Redirect::back()->with('successMsg', '修改成功');
  592. }
  593. return Response::view('admin.config.profile');
  594. }
  595. // 用户流量监控
  596. public function userMonitor(Request $request) {
  597. $id = $request->input('id');
  598. if(empty($id)){
  599. return Redirect::to('admin/userList');
  600. }
  601. $user = User::find($id);
  602. if(empty($user)){
  603. return Redirect::to('admin/userList');
  604. }
  605. $view['email'] = $user->email;
  606. $view = array_merge($view, $this->dataFlowChart($user->id));
  607. return Response::view('admin.logs.userMonitor', $view);
  608. }
  609. // 加密方式、混淆、协议、等级、国家地区
  610. public function config(Request $request) {
  611. if($request->isMethod('POST')){
  612. $name = $request->input('name');
  613. $type = $request->input('type', 1); // 类型:1-加密方式(method)、2-协议(protocol)、3-混淆(obfs)
  614. $is_default = $request->input('is_default', 0);
  615. $sort = $request->input('sort', 0);
  616. if(empty($name)){
  617. return Response::json(['status' => 'fail', 'message' => '配置名称不能为空']);
  618. }
  619. // 校验是否已存在
  620. $config = SsConfig::type($type)->whereName($name)->first();
  621. if($config){
  622. return Response::json(['status' => 'fail', 'message' => '配置已经存在,请勿重复添加']);
  623. }
  624. $ssConfig = new SsConfig();
  625. $ssConfig->name = $name;
  626. $ssConfig->type = $type;
  627. $ssConfig->is_default = $is_default;
  628. $ssConfig->sort = $sort;
  629. $ssConfig->save();
  630. return Response::json(['status' => 'success', 'message' => '添加成功']);
  631. }
  632. $labelList = Label::all();
  633. foreach($labelList as $label){
  634. $label->nodeCount = SsNodeLabel::query()->whereLabelId($label->id)->groupBy('label_id')->count();
  635. }
  636. $view['methodList'] = SsConfig::type(1)->get();
  637. $view['protocolList'] = SsConfig::type(2)->get();
  638. $view['obfsList'] = SsConfig::type(3)->get();
  639. $view['countryList'] = Country::all();
  640. $view['levelList'] = Level::all();
  641. $view['labelList'] = $labelList;
  642. return Response::view('admin.config.config', $view);
  643. }
  644. // 删除配置
  645. public function delConfig(Request $request): ?JsonResponse {
  646. $id = $request->input('id');
  647. $ret = SsConfig::query()->whereId($id)->delete();
  648. if($ret){
  649. return Response::json(['status' => 'success', 'message' => '删除成功']);
  650. }
  651. return Response::json(['status' => 'fail', 'message' => '删除失败']);
  652. }
  653. // 设置默认配置
  654. public function setDefaultConfig(Request $request): JsonResponse {
  655. $id = $request->input('id');
  656. if(empty($id)){
  657. return Response::json(['status' => 'fail', 'message' => '非法请求']);
  658. }
  659. $config = SsConfig::find($id);
  660. if(!$config){
  661. return Response::json(['status' => 'fail', 'message' => '配置不存在']);
  662. }
  663. // 去除该配置所属类型的默认值
  664. SsConfig::default()->type($config->type)->update(['is_default' => 0]);
  665. // 将该ID对应记录值置为默认值
  666. SsConfig::query()->whereId($id)->update(['is_default' => 1]);
  667. return Response::json(['status' => 'success', 'message' => '操作成功']);
  668. }
  669. // 设置系统扩展信息,例如客服、统计代码
  670. public function setExtend(Request $request): ?RedirectResponse {
  671. $websiteAnalytics = $request->input('website_analytics');
  672. $websiteCustomerService = $request->input('website_customer_service');
  673. try{
  674. DB::beginTransaction();
  675. // 首页LOGO
  676. if($request->hasFile('website_home_logo')){
  677. $ret = $this->uploadFile($request->file('website_home_logo'));
  678. if(!$ret){
  679. Session::flash('errorMsg', 'LOGO不合法');
  680. return Redirect::back();
  681. }
  682. Config::query()->whereName('website_home_logo')->update(['value' => $ret]);
  683. }
  684. // 站内LOGO
  685. if($request->hasFile('website_logo')){
  686. $ret = $this->uploadFile($request->file('website_logo'));
  687. if(!$ret){
  688. Session::flash('errorMsg', 'LOGO不合法');
  689. return Redirect::back();
  690. }
  691. Config::query()->whereName('website_logo')->update(['value' => $ret]);
  692. }
  693. Config::query()->whereName('website_analytics')->update(['value' => $websiteAnalytics]);
  694. Config::query()->whereName('website_customer_service')->update(['value' => $websiteCustomerService]);
  695. Session::flash('successMsg', '更新成功');
  696. DB::commit();
  697. return Redirect::back();
  698. }catch(Exception $e){
  699. DB::rollBack();
  700. Session::flash('errorMsg', '更新失败');
  701. return Redirect::back();
  702. }
  703. }
  704. // 添加等级
  705. public function addLevel(Request $request): ?JsonResponse {
  706. $validator = Validator::make($request->all(), [
  707. 'level' => 'required|numeric|unique:level,level',
  708. 'level_name' => 'required',
  709. ]);
  710. if($validator->fails()){
  711. return Response::json(['status' => 'fail', 'message' => $validator->errors()->all()]);
  712. }
  713. $obj = new Level();
  714. $obj->level = $request->input('level');
  715. $obj->name = $request->input('level_name');
  716. $obj->save();
  717. if($obj->id){
  718. return Response::json(['status' => 'success', 'message' => '提交成功']);
  719. }
  720. return Response::json(['status' => 'fail', 'message' => '操作失败']);
  721. }
  722. // 编辑等级
  723. public function updateLevel(Request $request): JsonResponse {
  724. $id = $request->input('id');
  725. $level = $request->input('level');
  726. $validator = Validator::make($request->all(), [
  727. 'id' => 'required|numeric',
  728. 'level' => 'required|numeric',
  729. 'level_name' => 'required',
  730. ]);
  731. if($validator->fails()){
  732. return Response::json(['status' => 'fail', 'message' => $validator->errors()->all()]);
  733. }
  734. // 校验该等级下是否存在关联账号
  735. $levelCheck = Level::query()->where('id', '<>', $id)->whereLevel($level)->exists();
  736. if($levelCheck){
  737. return Response::json(['status' => 'fail', 'message' => '该等级已存在!']);
  738. }
  739. // 校验该等级下是否存在关联账号
  740. $userCount = User::query()->whereLevel($level)->count();
  741. if($userCount){
  742. return Response::json(['status' => 'fail', 'message' => '该等级下存在关联账号,请先取消关联!']);
  743. }
  744. Level::query()->whereId($id)->update(['level' => $level, 'name' => $request->input('level_name')]);
  745. return Response::json(['status' => 'success', 'message' => '操作成功']);
  746. }
  747. // 删除等级
  748. public function delLevel(Request $request): ?JsonResponse {
  749. $id = $request->input('id');
  750. $validator = Validator::make($request->all(), [
  751. 'id' => 'required|numeric|exists:level,id',
  752. ]);
  753. if($validator->fails()){
  754. return Response::json(['status' => 'fail', 'message' => $validator->errors()->all()]);
  755. }
  756. $level = Level::find($id);
  757. // 校验该等级下是否存在关联账号
  758. $userCount = User::query()->whereLevel($level->level)->count();
  759. if($userCount){
  760. return Response::json(['status' => 'fail', 'message' => '该等级下存在关联账号,请先取消关联']);
  761. }
  762. $ret = false;
  763. try{
  764. $ret = Level::query()->whereId($id)->delete();
  765. }catch(Exception $e){
  766. Log::error('删除等级时报错:'.$e);
  767. }
  768. if($ret){
  769. return Response::json(['status' => 'success', 'message' => '操作成功']);
  770. }
  771. return Response::json(['status' => 'fail', 'message' => '操作失败']);
  772. }
  773. // 添加国家/地区
  774. public function addCountry(Request $request): ?JsonResponse {
  775. $name = $request->input('country_name');
  776. $code = $request->input('country_code');
  777. if(empty($name)){
  778. return Response::json(['status' => 'fail', 'message' => '国家/地区名称不能为空']);
  779. }
  780. if(empty($code)){
  781. return Response::json(['status' => 'fail', 'message' => '国家/地区代码不能为空']);
  782. }
  783. $exists = Country::query()->whereName($name)->first();
  784. if($exists){
  785. return Response::json(['status' => 'fail', 'message' => '该国家/地区名称已存在,请勿重复添加']);
  786. }
  787. $obj = new Country();
  788. $obj->name = $name;
  789. $obj->code = $code;
  790. $obj->save();
  791. if($obj->id){
  792. return Response::json(['status' => 'success', 'message' => '提交成功']);
  793. }
  794. return Response::json(['status' => 'fail', 'message' => '操作失败']);
  795. }
  796. // 编辑国家/地区
  797. public function updateCountry(Request $request): ?JsonResponse {
  798. $id = $request->input('id');
  799. $name = $request->input('country_name');
  800. $code = $request->input('country_code');
  801. if(empty($id)){
  802. return Response::json(['status' => 'fail', 'message' => 'ID不能为空']);
  803. }
  804. if(empty($name)){
  805. return Response::json(['status' => 'fail', 'message' => '国家/地区名称不能为空']);
  806. }
  807. if(empty($code)){
  808. return Response::json(['status' => 'fail', 'message' => '国家/地区代码不能为空']);
  809. }
  810. $country = Country::find($id);
  811. if($country){
  812. return Response::json(['status' => 'fail', 'message' => '国家/地区不存在']);
  813. }
  814. // 校验该国家/地区下是否存在关联节点
  815. $existNode = SsNode::query()->whereCountryCode($country->code)->get();
  816. if(!$existNode){
  817. return Response::json(['status' => 'fail', 'message' => '该国家/地区下存在关联节点,请先取消关联']);
  818. }
  819. $ret = Country::query()->whereId($id)->update(['name' => $name, 'code' => $code]);
  820. if($ret){
  821. return Response::json(['status' => 'success', 'message' => '操作成功']);
  822. }
  823. return Response::json(['status' => 'fail', 'message' => '操作失败']);
  824. }
  825. // 删除国家/地区
  826. public function delCountry(Request $request): ?JsonResponse {
  827. $id = $request->input('id');
  828. if(empty($id)){
  829. return Response::json(['status' => 'fail', 'message' => 'ID不能为空']);
  830. }
  831. $country = Country::find($id);
  832. if(!$country){
  833. return Response::json(['status' => 'fail', 'message' => '国家/地区不存在']);
  834. }
  835. // 校验该国家/地区下是否存在关联节点
  836. $existNode = SsNode::query()->whereCountryCode($country->code)->get();
  837. if(!$existNode){
  838. return Response::json(['status' => 'fail', 'message' => '该国家/地区下存在关联节点,请先取消关联']);
  839. }
  840. $ret = false;
  841. try{
  842. $ret = Country::query()->whereId($id)->delete();
  843. }catch(Exception $e){
  844. Log::error('删除国家/地区时报错:'.$e);
  845. }
  846. if($ret){
  847. return Response::json(['status' => 'success', 'message' => '操作成功']);
  848. }
  849. return Response::json(['status' => 'fail', 'message' => '操作失败']);
  850. }
  851. // 系统设置
  852. public function system(): \Illuminate\Http\Response {
  853. $view = self::$systemConfig;
  854. $view['labelList'] = Label::query()->orderByDesc('sort')->orderBy('id')->get();
  855. return Response::view('admin.config.system', $view);
  856. }
  857. // 设置某个配置项
  858. public function setConfig(Request $request): JsonResponse {
  859. $name = (string) $request->input('name');
  860. $value = $request->input('value');
  861. if(!$name){
  862. return Response::json(['status' => 'fail', 'message' => '设置失败:请求参数异常']);
  863. }
  864. // 屏蔽异常配置
  865. if(!array_key_exists($name, self::$systemConfig)){
  866. return Response::json(['status' => 'fail', 'message' => '设置失败:配置不存在']);
  867. }
  868. // 如果开启用户邮件重置密码,则先设置网站名称和网址
  869. if($value !== '0'
  870. && in_array($name, ['is_reset_password', 'is_activate_account', 'expire_warning', 'traffic_warning'], true)){
  871. $config = Config::query()->whereName('website_name')->firstOrFail();
  872. if(!$config->value){
  873. return Response::json(['status' => 'fail', 'message' => '设置失败:启用该配置需要先设置【网站名称】']);
  874. }
  875. $config = Config::query()->whereName('website_url')->firstOrFail();
  876. if(!$config->value){
  877. return Response::json(['status' => 'fail', 'message' => '设置失败:启用该配置需要先设置【网站地址】']);
  878. }
  879. }
  880. // 支付设置判断
  881. if($value !== '' && in_array($name, ['is_AliPay', 'is_QQPay', 'is_WeChatPay', 'is_otherPay'], true)){
  882. switch($value){
  883. case 'f2fpay':
  884. if(!self::$systemConfig['f2fpay_app_id'] || !self::$systemConfig['f2fpay_private_key']
  885. || !self::$systemConfig['f2fpay_public_key']){
  886. return Response::json(['status' => 'fail', 'message' => '请先设置【支付宝F2F】必要参数']);
  887. }
  888. break;
  889. case 'codepay':
  890. if(!self::$systemConfig['codepay_url'] || !self::$systemConfig['codepay_id']
  891. || !self::$systemConfig['codepay_key']){
  892. return Response::json(['status' => 'fail', 'message' => '请先设置【码支付】必要参数']);
  893. }
  894. break;
  895. case 'epay':
  896. if(!self::$systemConfig['epay_url'] || !self::$systemConfig['epay_mch_id'] || !self::$systemConfig['epay_key']){
  897. return Response::json(['status' => 'fail', 'message' => '请先设置【易支付】必要参数']);
  898. }
  899. break;
  900. case 'payjs':
  901. if(!self::$systemConfig['payjs_mch_id'] || !self::$systemConfig['payjs_key']){
  902. return Response::json(['status' => 'fail', 'message' => '请先设置【PayJs】必要参数']);
  903. }
  904. break;
  905. case 'bitpayx':
  906. if(!self::$systemConfig['bitpay_secret']){
  907. return Response::json(['status' => 'fail', 'message' => '请先设置【麻瓜宝】必要参数']);
  908. }
  909. break;
  910. case 'paypal':
  911. if(!self::$systemConfig['paypal_username'] || !self::$systemConfig['paypal_password']
  912. || !self::$systemConfig['paypal_secret']){
  913. return Response::json(['status' => 'fail', 'message' => '请先设置【PayPal】必要参数']);
  914. }
  915. break;
  916. default:
  917. return Response::json(['status' => 'fail', 'message' => '未知支付渠道']);
  918. }
  919. }
  920. // 演示环境禁止修改特定配置项
  921. if(config('app.demo')){
  922. $denyConfig = [
  923. 'website_url',
  924. 'min_rand_traffic',
  925. 'max_rand_traffic',
  926. 'push_bear_send_key',
  927. 'push_bear_qrcode',
  928. 'is_forbid_china',
  929. 'website_security_code'
  930. ];
  931. if(in_array($name, $denyConfig, true)){
  932. return Response::json(['status' => 'fail', 'message' => '演示环境禁止修改该配置']);
  933. }
  934. }
  935. // 如果是返利比例,则需要除100
  936. if($name === 'referral_percent'){
  937. $value = (int) $value / 100;
  938. }
  939. // 更新配置
  940. Config::query()->whereName($name)->update(['value' => $value]);
  941. return Response::json(['status' => 'success', 'message' => '操作成功']);
  942. }
  943. // 推送通知测试
  944. public function sendTestNotification(): JsonResponse {
  945. if(self::$systemConfig['is_notification']){
  946. $result = PushNotification::send('这是测试的标题', 'ProxyPanel测试内容');
  947. if($result === false){
  948. return Response::json(['status' => 'fail', 'message' => '发送失败,请重新尝试!']);
  949. }
  950. switch(self::$systemConfig['is_notification']){
  951. case 'serverChan':
  952. if(!$result['errno']){
  953. return Response::json(['status' => 'success', 'message' => '发送成功,请查看手机是否收到推送消息']);
  954. }
  955. return Response::json(['status' => 'fail', 'message' => $result? $result['errmsg'] : '未知']);
  956. case 'bark':
  957. if($result['code'] == 200){
  958. return Response::json(['status' => 'success', 'message' => '发送成功,请查看手机是否收到推送消息']);
  959. }
  960. return Response::json(['status' => 'fail', 'message' => $result['message']]);
  961. default:
  962. }
  963. }
  964. return Response::json(['status' => 'fail', 'message' => '请先选择【日志通知】渠道']);
  965. }
  966. // 邀请码列表
  967. public function inviteList(Request $request): \Illuminate\Http\Response {
  968. $view['inviteList'] = Invite::query()
  969. ->with(['generator', 'user'])
  970. ->orderBy('status')
  971. ->latest()
  972. ->paginate(15)
  973. ->appends($request->except('page'));
  974. return Response::view('admin.inviteList', $view);
  975. }
  976. // 生成邀请码
  977. public function makeInvite(): JsonResponse {
  978. for($i = 0; $i < 10; $i++){
  979. $obj = new Invite();
  980. $obj->uid = 0;
  981. $obj->fuid = 0;
  982. $obj->code = strtoupper(substr(md5(microtime().makeRandStr()), 8, 12));
  983. $obj->status = 0;
  984. $obj->dateline = date('Y-m-d H:i:s', strtotime("+".self::$systemConfig['admin_invite_days']." days"));
  985. $obj->save();
  986. }
  987. return Response::json(['status' => 'success', 'message' => '生成成功']);
  988. }
  989. // 导出邀请码
  990. public function exportInvite(): void {
  991. $inviteList = Invite::query()->whereStatus(0)->orderBy('id')->get();
  992. $filename = '邀请码'.date('Ymd').'.xlsx';
  993. $spreadsheet = new Spreadsheet();
  994. $spreadsheet->getProperties()
  995. ->setCreator('ProxyPanel')
  996. ->setLastModifiedBy('ProxyPanel')
  997. ->setTitle('邀请码')
  998. ->setSubject('邀请码')
  999. ->setDescription('')
  1000. ->setKeywords('')
  1001. ->setCategory('');
  1002. try{
  1003. $spreadsheet->setActiveSheetIndex(0);
  1004. $sheet = $spreadsheet->getActiveSheet();
  1005. $sheet->setTitle('邀请码');
  1006. $sheet->fromArray(['邀请码', '有效期'], null);
  1007. foreach($inviteList as $k => $vo){
  1008. $sheet->fromArray([$vo->code, $vo->dateline], null, 'A'.($k + 2));
  1009. }
  1010. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); // 输出07Excel文件
  1011. //header('Content-Type:application/vnd.ms-excel'); // 输出Excel03版本文件
  1012. header('Content-Disposition: attachment;filename="'.$filename.'"');
  1013. header('Cache-Control: max-age=0');
  1014. $writer = new Xlsx($spreadsheet);
  1015. $writer->save('php://output');
  1016. }catch(\PhpOffice\PhpSpreadsheet\Exception $e){
  1017. Log::error('导出优惠券时报错'.$e);
  1018. }
  1019. }
  1020. // 订单列表
  1021. public function orderList(Request $request): \Illuminate\Http\Response {
  1022. $email = $request->input('email');
  1023. $order_sn = $request->input('order_sn');
  1024. $is_coupon = $request->input('is_coupon');
  1025. $is_expire = $request->input('is_expire');
  1026. $pay_way = $request->input('pay_way');
  1027. $status = $request->input('status');
  1028. $range_time = $request->input('range_time');
  1029. $sort = $request->input('sort'); // 0-按创建时间降序、1-按创建时间升序
  1030. $order_id = $request->input('oid');
  1031. $query = Order::query()->with(['user', 'goods', 'coupon']);
  1032. if(isset($email)){
  1033. $query->whereHas('user', static function($q) use ($email) {
  1034. $q->where('email', 'like', '%'.$email.'%');
  1035. });
  1036. }
  1037. if(isset($order_sn)){
  1038. $query->where('order_sn', 'like', '%'.$order_sn.'%');
  1039. }
  1040. if(isset($is_coupon)){
  1041. if($is_coupon){
  1042. $query->where('coupon_id', '<>', 0);
  1043. }else{
  1044. $query->whereCouponId(0);
  1045. }
  1046. }
  1047. if(isset($is_expire)){
  1048. $query->whereIsExpire($is_expire);
  1049. }
  1050. if(isset($pay_way)){
  1051. $query->wherePayWay($pay_way);
  1052. }
  1053. if(isset($status)){
  1054. $query->whereStatus($status);
  1055. }
  1056. if(isset($range_time) && $range_time !== ','){
  1057. $range_time = explode(',', $range_time);
  1058. $query->where('created_at', '>=', $range_time[0])->where('created_at', '<=', $range_time[1]);
  1059. }
  1060. if(isset($order_id)){
  1061. $query->whereOid($order_id);
  1062. }
  1063. if($sort){
  1064. $query->orderBy('oid');
  1065. }else{
  1066. $query->orderByDesc('oid');
  1067. }
  1068. $view['orderList'] = $query->paginate(15)->appends($request->except('page'));
  1069. return Response::view('admin.logs.orderList', $view);
  1070. }
  1071. // 重置用户流量
  1072. public function resetUserTraffic(Request $request): JsonResponse {
  1073. $id = $request->input('id');
  1074. User::query()->whereId($id)->update(['u' => 0, 'd' => 0]);
  1075. return Response::json(['status' => 'success', 'message' => '操作成功']);
  1076. }
  1077. // 操作用户余额
  1078. public function handleUserCredit(Request $request) {
  1079. if($request->isMethod('POST')){
  1080. $userId = $request->input('user_id');
  1081. $amount = $request->input('amount');
  1082. if(empty($userId) || empty($amount)){
  1083. return Response::json(['status' => 'fail', 'message' => '充值异常']);
  1084. }
  1085. $user = User::find($userId);
  1086. // 写入余额变动日志
  1087. Helpers::addUserCreditLog($userId, 0, $user->credit, $user->credit + $amount, $amount, '后台手动充值');
  1088. // 加减余额
  1089. if($amount < 0){
  1090. $ret = User::whereId($user->id)->decrement('credit', abs($amount) * 100);
  1091. }else{
  1092. $ret = User::whereId($user->id)->increment('credit', $amount * 100);
  1093. }
  1094. if($ret){
  1095. return Response::json(['status' => 'success', 'message' => '充值成功']);
  1096. }
  1097. return Response::json(['status' => 'fail', 'message' => '充值失败']);
  1098. }
  1099. return Response::view('admin.handleUserCredit');
  1100. }
  1101. // 用户余额变动记录
  1102. public function userCreditLogList(Request $request): \Illuminate\Http\Response {
  1103. $email = $request->input('email');
  1104. $query = UserCreditLog::query()->with(['user'])->latest();
  1105. if(isset($email)){
  1106. $query->whereHas('user', static function($q) use ($email) {
  1107. $q->where('email', 'like', '%'.$email.'%');
  1108. });
  1109. }
  1110. $view['list'] = $query->paginate(15)->appends($request->except('page'));
  1111. return Response::view('admin.logs.userCreditLogList', $view);
  1112. }
  1113. // 用户封禁记录
  1114. public function userBanLogList(Request $request): \Illuminate\Http\Response {
  1115. $email = $request->input('email');
  1116. $query = UserBanLog::query()->with(['user'])->latest();
  1117. if(isset($email)){
  1118. $query->whereHas('user', static function($q) use ($email) {
  1119. $q->where('email', 'like', '%'.$email.'%');
  1120. });
  1121. }
  1122. $view['list'] = $query->paginate(15)->appends($request->except('page'));
  1123. return Response::view('admin.logs.userBanLogList', $view);
  1124. }
  1125. // 用户流量变动记录
  1126. public function userTrafficLogList(Request $request): \Illuminate\Http\Response {
  1127. $email = $request->input('email');
  1128. $query = UserTrafficModifyLog::query()->with(['user', 'order', 'order.goods']);
  1129. if(isset($email)){
  1130. $query->whereHas('user', static function($q) use ($email) {
  1131. $q->where('email', 'like', '%'.$email.'%');
  1132. });
  1133. }
  1134. $view['list'] = $query->latest()->paginate(15)->appends($request->except('page'));
  1135. return Response::view('admin.logs.userTrafficLogList', $view);
  1136. }
  1137. // 用户在线IP记录
  1138. public function userOnlineIPList(Request $request): \Illuminate\Http\Response {
  1139. $email = $request->input('email');
  1140. $port = $request->input('port');
  1141. $wechat = $request->input('wechat');
  1142. $qq = $request->input('qq');
  1143. $query = User::query()->activeUser();
  1144. if(isset($email)){
  1145. $query->where('email', 'like', '%'.$email.'%');
  1146. }
  1147. if(isset($wechat)){
  1148. $query->where('wechat', 'like', '%'.$wechat.'%');
  1149. }
  1150. if(isset($qq)){
  1151. $query->where('qq', 'like', '%'.$qq.'%');
  1152. }
  1153. if(isset($port)){
  1154. $query->wherePort($port);
  1155. }
  1156. $userList = $query->paginate(15)->appends($request->except('page'));
  1157. if(!$userList->isEmpty()){
  1158. foreach($userList as $user){
  1159. // 最近5条在线IP记录,如果后端设置为60秒上报一次,则为10分钟内的在线IP
  1160. $user->onlineIPList = SsNodeIp::query()
  1161. ->with(['node'])
  1162. ->whereType('tcp')
  1163. ->wherePort($user->port)
  1164. ->where('created_at', '>=', strtotime("-10 minutes"))
  1165. ->latest()
  1166. ->limit(5)
  1167. ->get();
  1168. }
  1169. }
  1170. $view['userList'] = $userList;
  1171. return Response::view('admin.logs.userOnlineIPList', $view);
  1172. }
  1173. // 转换成某个用户的身份
  1174. public function switchToUser(Request $request): JsonResponse {
  1175. $id = $request->input('user_id');
  1176. $user = User::find($id);
  1177. if(!$user){
  1178. return Response::json(['status' => 'fail', 'message' => "用户不存在"]);
  1179. }
  1180. // 存储当前管理员ID,并将当前登录信息改成要切换的用户的身份信息
  1181. Session::put('admin', Auth::id());
  1182. Auth::login($user);
  1183. return Response::json(['status' => 'success', 'message' => "身份切换成功"]);
  1184. }
  1185. // 添加标签
  1186. public function addLabel(Request $request) {
  1187. if($request->isMethod('POST')){
  1188. $name = $request->input('name');
  1189. $sort = $request->input('sort');
  1190. $label = new Label();
  1191. $label->name = $name;
  1192. $label->sort = $sort;
  1193. $label->save();
  1194. return Response::json(['status' => 'success', 'message' => '添加成功']);
  1195. }
  1196. return Response::view('admin.label.addLabel');
  1197. }
  1198. // 编辑标签
  1199. public function editLabel(Request $request) {
  1200. if($request->isMethod('POST')){
  1201. $id = $request->input('id');
  1202. $name = $request->input('name');
  1203. $sort = $request->input('sort');
  1204. Label::query()->whereId($id)->update(['name' => $name, 'sort' => $sort]);
  1205. return Response::json(['status' => 'success', 'message' => '添加成功']);
  1206. }
  1207. $id = $request->input('id');
  1208. $view['label'] = Label::find($id);
  1209. return Response::view('admin.label.editLabel', $view);
  1210. }
  1211. // 删除标签
  1212. public function delLabel(Request $request): ?JsonResponse {
  1213. $id = $request->input('id');
  1214. try{
  1215. DB::beginTransaction();
  1216. Label::query()->whereId($id)->delete();
  1217. SsNodeLabel::query()->whereLabelId($id)->delete(); // 删除节点关联
  1218. DB::commit();
  1219. return Response::json(['status' => 'success', 'message' => '删除成功']);
  1220. }catch(Exception $e){
  1221. DB::rollBack();
  1222. return Response::json(['status' => 'fail', 'message' => '删除失败:'.$e->getMessage()]);
  1223. }
  1224. }
  1225. // 邮件发送日志列表
  1226. public function notificationLog(Request $request): \Illuminate\Http\Response {
  1227. $email = $request->input('email');
  1228. $type = $request->input('type');
  1229. $query = NotificationLog::query();
  1230. if(isset($email)){
  1231. $query->where('address', 'like', '%'.$email.'%');
  1232. }
  1233. if(isset($type)){
  1234. $query->whereType($type);
  1235. }
  1236. $view['list'] = $query->latest()->paginate(15)->appends($request->except('page'));
  1237. return Response::view('admin.logs.notificationLog', $view);
  1238. }
  1239. // 在线IP监控(实时)
  1240. public function onlineIPMonitor(Request $request): \Illuminate\Http\Response {
  1241. $ip = $request->input('ip');
  1242. $email = $request->input('email');
  1243. $port = $request->input('port');
  1244. $nodeId = $request->input('nodeId');
  1245. $userId = $request->input('id');
  1246. $query = SsNodeIp::query()->with(['node', 'user'])->where('created_at', '>=', strtotime("-120 seconds"));
  1247. if(isset($ip)){
  1248. $query->whereIp($ip);
  1249. }
  1250. if(isset($email)){
  1251. $query->whereHas('user', static function($q) use ($email) {
  1252. $q->where('email', 'like', '%'.$email.'%');
  1253. });
  1254. }
  1255. if(isset($port)){
  1256. $query->whereHas('user', static function($q) use ($port) {
  1257. $q->wherePort($port);
  1258. });
  1259. }
  1260. if(isset($nodeId)){
  1261. $query->whereHas('node', static function($q) use ($nodeId) {
  1262. $q->whereId($nodeId);
  1263. });
  1264. }
  1265. if(isset($userId)){
  1266. $query->whereHas('user', static function($q) use ($userId) {
  1267. $q->whereId($userId);
  1268. });
  1269. }
  1270. $list = $query->groupBy('user_id', 'node_id')->latest();
  1271. foreach($list as $vo){
  1272. // 跳过上报多IP的
  1273. if($vo->ip == null || strpos($vo->ip, ',') === true){
  1274. continue;
  1275. }
  1276. $ipInfo = QQWry::ip($vo->ip);
  1277. if(isset($ipInfo['error'])){
  1278. // 用IPIP的库再试一下
  1279. $ipip = IPIP::ip($vo->ip);
  1280. $ipInfo = [
  1281. 'country' => $ipip['country_name'],
  1282. 'province' => $ipip['region_name'],
  1283. 'city' => $ipip['city_name']
  1284. ];
  1285. }
  1286. $vo->ipInfo = $ipInfo['country'].' '.$ipInfo['province'].' '.$ipInfo['city'];
  1287. }
  1288. $view['list'] = $list->paginate(20)->appends($request->except('page'));
  1289. $view['nodeList'] = SsNode::query()->whereStatus(1)->orderByDesc('sort')->latest()->get();
  1290. return Response::view('admin.logs.onlineIPMonitor', $view);
  1291. }
  1292. }