user = Auth::getUser(); $redis = new RedisClient(); $domain = $_SERVER['HTTP_HOST']; $configurations = $this->getDomainConfigurations(); $this->applyDomainTheme($configurations); if ($this->domainMatchesConfigHost($configurations, 'host_1', $domain)) { $this->cdn = $redis->get('admin_cdn', 60, function () { return Configurations::where('name', 'admin_cdn')->value('value'); }); } elseif ($this->domainMatchesConfigHost($configurations, 'host_5', $domain)) { $this->cdn = $redis->get('backup_cdn', 60, function () { return Configurations::where('name', 'backup_cdn')->value('value'); }); } else { $this->cdn = $redis->get('cdn', 60, function () { return Configurations::where('name', 'cdn')->value('value'); }); $this->backup_cdn = $redis->get('backup_cdn', 60, function () { return Configurations::where('name', 'backup_cdn')->value('value'); }); } $this->aff_method = $redis->get('aff_method', 60, function () { return Configurations::where('name', 'aff_method')->value('value'); }); } public function smarty() { $smarty = parent::smarty(); $smarty->assign('cdn', isset($this->cdn) ? $this->cdn : ''); $smarty->assign('backup_cdn', isset($this->backup_cdn) ? $this->backup_cdn : ''); return $smarty; } public function index($request, $response, $args) { $page = max(1, (int) ($request->getQueryParams()['page'] ?? 1)); $shops = Bought::where('userid', $this->user->id)->orderBy('id', 'desc')->paginate(15, ['*'], 'page', $page); $shops->setPath('/user'); $ann = Ann::orderBy('date', 'desc')->first(); $pendingSurvey = $this->getPendingSurvey($this->user); $ticketRestricted = UserFeatureRestrictionService::isTicketRestricted($this->user); $latestTicketReply = null; $latestTicketRoot = null; if (!$ticketRestricted) { $ids = Ticket::where('userid', $this->user->id)->where('rootid', 0)->pluck('id')->toArray(); if ($ids !== []) { $latestTicketReply = Ticket::whereIn('rootid', $ids)->where('userid', '!=', $this->user->id)->orderBy('datetime', 'desc')->first(); if ($latestTicketReply !== null) { $latestTicketRoot = Ticket::find($latestTicketReply->rootid); } } } return $this->view()->assign('ann', $ann)->assign('shops', $shops) ->assign('ticket_restricted', $ticketRestricted) ->assign('latest_ticket_reply', $latestTicketReply)->assign('latest_ticket_root', $latestTicketRoot) ->assign('pending_survey', $pendingSurvey) ->assign('notification_count', (int) ($ann !== null) + (int) ($latestTicketReply !== null) + (int) ($pendingSurvey !== null)) ->assign('cdn', $this->cdn)->assign('backup_cdn', $this->backup_cdn)->display('user/index.tpl'); } private function getPendingSurvey($user) { $now = time(); try { $surveys = UserSurvey::where('status', 1) ->where('start_at', '<=', $now) ->where(function ($query) use ($now) { $query->where('end_at', 0)->orWhere('end_at', '>=', $now); }) ->orderBy('priority', 'desc') ->orderBy('id', 'desc') ->get(); foreach ($surveys as $survey) { if (!$this->surveyAppliesToUser($survey, $user)) { continue; } $questions = $this->getSurveyQuestionRows($survey, $user, true); if (count($questions) === 0) { continue; } return [ 'id' => (int) $survey->id, 'title' => (string) $survey->title, 'description' => (string) $survey->description, 'display_mode' => (string) $survey->display_mode, 'allow_skip' => (int) $survey->allow_skip, 'questions' => $questions, ]; } } catch (\Exception $exception) { return null; } return null; } private function getSurveyQuestionRows($survey, $user, $onlyUnanswered) { $questionModels = UserSurveyQuestion::where('survey_id', (int) $survey->id) ->where('status', 1) ->orderBy('sort', 'asc') ->orderBy('id', 'asc') ->get(); $rows = []; foreach ($questionModels as $question) { $row = $this->buildSurveyQuestionRow($survey, (int) $question->id, (string) $question->title, (string) $question->description, $user, $onlyUnanswered); if ($row !== null) { $rows[] = $row; } } if (count($rows) === 0 && $questionModels->count() === 0) { $row = $this->buildSurveyQuestionRow($survey, 0, (string) $survey->title, (string) $survey->description, $user, $onlyUnanswered); if ($row !== null) { $rows[] = $row; } } return $rows; } private function buildSurveyQuestionRow($survey, $questionId, $title, $description, $user, $onlyUnanswered) { if ($onlyUnanswered) { $responded = UserSurveyResponse::where('survey_id', (int) $survey->id) ->where('question_id', (int) $questionId) ->where('user_id', (int) $user->id) ->first(); if ($responded !== null) { return null; } } $options = UserSurveyOption::where('survey_id', (int) $survey->id) ->where('question_id', (int) $questionId) ->where('status', 1) ->orderBy('sort', 'asc') ->orderBy('id', 'asc') ->get(); if ($options->count() < 2) { return null; } $optionRows = []; foreach ($options as $option) { $optionRows[] = [ 'id' => (int) $option->id, 'label' => (string) $option->label, 'content' => (string) $option->content, ]; } return [ 'id' => (int) $questionId, 'title' => (string) $title, 'description' => (string) $description, 'options' => $optionRows, ]; } private function surveyAppliesToUser($survey, $user) { $targetType = trim((string) $survey->target_type); if ($targetType === 'paid') { return Bought::where('userid', $user->id)->exists(); } return $targetType === '' || $targetType === 'all'; } public function submitSurvey($request, $response, $args) { $surveyId = (int) $request->getParam('survey_id', 0); $survey = $surveyId > 0 ? UserSurvey::find($surveyId) : null; if ($survey === null || !$this->surveyIsActive($survey) || !$this->surveyAppliesToUser($survey, $this->user)) { return $this->echoJson($response, [ 'ret' => 0, 'msg' => '调查不存在或已结束', ]); } try { $questions = $this->getSurveyQuestionRows($survey, $this->user, true); } catch (\Exception $exception) { return $this->echoJson($response, [ 'ret' => 0, 'msg' => '调查配置未完成,请稍后再试', ]); } if (count($questions) === 0) { return $this->echoJson($response, [ 'ret' => 1, 'msg' => '你已经提交过该调查', ]); } $answers = $request->getParam('answers', []); if (!is_array($answers)) { $answers = []; } $legacyOptionId = (int) $request->getParam('option_id', 0); if (count($answers) === 0 && $legacyOptionId > 0) { $legacyQuestionId = (int) $request->getParam('question_id', 0); $answers[$legacyQuestionId] = $legacyOptionId; } $prepared = []; foreach ($questions as $question) { $questionId = (int) $question['id']; if (!isset($answers[$questionId]) || (int) $answers[$questionId] <= 0) { return $this->echoJson($response, [ 'ret' => 0, 'msg' => '请完成所有调查题目后再提交', ]); } $optionId = (int) $answers[$questionId]; if (!$this->optionBelongsToQuestion($question, $optionId)) { return $this->echoJson($response, [ 'ret' => 0, 'msg' => '请选择有效的调查选项', ]); } $prepared[] = [ 'question_id' => $questionId, 'option_id' => $optionId, ]; } try { foreach ($prepared as $answer) { $record = new UserSurveyResponse(); $record->survey_id = $surveyId; $record->question_id = (int) $answer['question_id']; $record->option_id = (int) $answer['option_id']; $record->user_id = (int) $this->user->id; $record->ip = isset($_SERVER['REMOTE_ADDR']) ? substr((string) $_SERVER['REMOTE_ADDR'], 0, 64) : ''; $record->user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? substr((string) $_SERVER['HTTP_USER_AGENT'], 0, 255) : ''; $record->created_at = time(); $record->save(); } } catch (\Exception $exception) { return $this->echoJson($response, [ 'ret' => 1, 'msg' => '你已经提交过该调查', ]); } return $this->echoJson($response, [ 'ret' => 1, 'msg' => '感谢你的反馈,我们会参考统计结果优化服务方向。', ]); } private function optionBelongsToQuestion($question, $optionId) { foreach ($question['options'] as $option) { if ((int) $option['id'] === (int) $optionId) { return true; } } return false; } private function surveyIsActive($survey) { $now = time(); return (int) $survey->status === 1 && (int) $survey->start_at <= $now && ((int) $survey->end_at === 0 || (int) $survey->end_at >= $now); } public function code($request, $response, $args) { $codes = null; $transactionRecordsRestricted = UserFeatureRestrictionService::isTransactionRecordsRestricted($this->user); if (!$transactionRecordsRestricted) { $pageNum = 1; if (isset($request->getQueryParams()["page"])) { $pageNum = $request->getQueryParams()["page"]; } $codes = Code::where('type', '<>', '-2')->where('userid', '=', $this->user->id)->orderBy('id', 'desc')->paginate(15, ['*'], 'page', $pageNum); $codes->setPath('/user/code'); } $yipayConfig = YipayConfig::values(); $yipayMethods = YipayConfig::visibleMethods($this->user, $yipayConfig); $yipayAlipayVisible = in_array('alipay', $yipayMethods, true); $rechargeRestricted = UserFeatureRestrictionService::isRechargeRestricted($this->user); return $this->view() ->assign('codes', $codes) ->assign('usdt_enabled', UsdtConfig::isUserVisible($this->user)) ->assign('paytaro_enabled', PaytaroConfig::isUserVisible($this->user)) ->assign('yipay_alipay_enabled', $yipayAlipayVisible) ->assign('yipay_wxpay_enabled', in_array('wxpay', $yipayMethods, true)) ->assign('recharge_restricted', $rechargeRestricted) ->assign('transaction_records_restricted', $transactionRecordsRestricted) ->assign("cdn", $this->cdn) ->assign("backup_cdn", $this->backup_cdn) ->display('user/paytaro.tpl'); } public function code_check($request, $response, $args) { $time = $request->getQueryParams()["time"]; $codes = Code::where('userid', '=', $this->user->id)->where('usedatetime', '>', date('Y-m-d H:i:s', $time))->first(); if ($codes != null && strpos($codes->code, "充值") !== false) { $res['ret'] = 1; return $response->getBody()->write(json_encode($res)); } else { $res['ret'] = 0; return $response->getBody()->write(json_encode($res)); } } public function profile($request, $response, $args) { $format = static function ($rows) { $result = []; foreach ($rows as $row) { $result[] = [ 'ip' => $row->ip, 'datetime' => date('Y-m-d H:i:s', $row->datetime), 'request_domain' => $row->request_domain ?? '', ]; } return $result; }; $success = LoginIp::where('userid', $this->user->id)->where('type', 0)->orderBy('datetime', 'desc')->take(10)->get(); $failed = LoginIp::where('userid', $this->user->id)->where('type', 1)->orderBy('datetime', 'desc')->take(10)->get(); return $this->view()->assign('successLoginLogs', $format($success))->assign('failedLoginLogs', $format($failed)) ->assign('cdn', $this->cdn)->assign('backup_cdn', $this->backup_cdn)->display('user/profile.tpl'); } public function announcement($request, $response, $args) { $twoMonthsAgo = date('Y-m-d H:i:s', strtotime('-2 months')); $Anns = Ann::where('date', '>=', $twoMonthsAgo) ->orderBy('date', 'desc') ->get(); return $this->view() ->assign("anns", $Anns) ->assign("latestAnn", $Anns->first()) ->assign("cdn", $this->cdn) ->assign("backup_cdn", $this->backup_cdn) ->display('user/announcement.tpl'); } public function edit($request, $response, $args) { $enabled = $this->hasGoogleAuthenticator($this->user); $secret = $enabled ? '' : Totp::generateSecret(); return $this->view()->assign('user', $this->user) ->assign('ga_enabled', $enabled)->assign('ga_setup_secret', $secret) ->assign('ga_otpauth_uri', $secret === '' ? '' : Totp::otpauthUri(Config::get('appName'), $this->user->email, $secret)) ->assign('login_verify_method', $this->loginVerifyMethod($this->user)) ->assign('cdn', $this->cdn)->assign('backup_cdn', $this->backup_cdn)->display('user/edit.tpl'); } private function hasGoogleAuthenticator($user) { return $user !== null && (int) $user->ga_enable === 1 && Totp::normalizeSecret($user->ga_token) !== ''; } private function loginVerifyMethod($user) { if ($this->hasGoogleAuthenticator($user) && (string) $user->login_verify_method === 'ga') { return 'ga'; } return 'email'; } public function enableGoogleAuthenticator($request, $response, $args) { $user = $this->user; if ($this->hasGoogleAuthenticator($user)) { return $this->echoJson($response, [ 'ret' => 0, 'msg' => '谷歌验证器已绑定,如需更换请先解绑。' ]); } $secret = Totp::normalizeSecret($request->getParam('secret')); $code = $request->getParam('code'); if ($secret === '') { return $this->echoJson($response, [ 'ret' => 0, 'msg' => '谷歌验证器密钥无效,请刷新页面后重试。' ]); } if (!Totp::verify($secret, $code)) { return $this->echoJson($response, [ 'ret' => 0, 'msg' => '谷歌验证码不正确或已过期。' ]); } $user->ga_token = $secret; $user->ga_enable = 1; $user->login_verify_method = 'email'; $user->save(); return $this->echoJson($response, [ 'ret' => 1, 'msg' => '谷歌验证器已绑定,默认仍使用邮箱安全验证。' ]); } public function disableGoogleAuthenticator($request, $response, $args) { $user = $this->user; if (!$this->hasGoogleAuthenticator($user)) { return $this->echoJson($response, [ 'ret' => 1, 'msg' => '谷歌验证器未绑定。' ]); } if (!Totp::verify($user->ga_token, $request->getParam('code'))) { return $this->echoJson($response, [ 'ret' => 0, 'msg' => '谷歌验证码不正确或已过期。' ]); } $user->ga_token = ''; $user->ga_enable = 0; $user->login_verify_method = 'email'; $user->save(); return $this->echoJson($response, [ 'ret' => 1, 'msg' => '谷歌验证器已解绑,登录验证方式已恢复为邮箱验证。' ]); } public function updateLoginVerifyMethod($request, $response, $args) { $method = trim((string) $request->getParam('method', 'email')); if (!in_array($method, ['email', 'ga'], true)) { return $this->echoJson($response, [ 'ret' => 0, 'msg' => '登录验证方式无效。' ]); } if ($method === 'ga' && !$this->hasGoogleAuthenticator($this->user)) { return $this->echoJson($response, [ 'ret' => 0, 'msg' => '请先绑定谷歌验证器。' ]); } $this->user->login_verify_method = $method; $this->user->save(); return $this->echoJson($response, [ 'ret' => 1, 'msg' => $method === 'ga' ? '登录安全验证已切换为谷歌验证器。' : '登录安全验证已切换为邮箱验证。' ]); } public function invite($request, $response, $args) { $pageNum = 1; if (isset($request->getQueryParams()["page"])) { $pageNum = $request->getQueryParams()["page"]; } /* $codes=InviteCode::where('user_id', $this->user->id)->orderBy("created_at", "desc")->paginate(15, ['*'], 'page', $pageNum); $codes->setPath('/user/invite'); */ $user = Auth::getUser(); $inviteRestricted = UserFeatureRestrictionService::isInviteRestricted($user); $inviteEnabled = $user->canInvite(); $inviteCode = null; if ($this->aff_method === 'code') { $inviteCode = InviteCode::where('user_id', $user->id)->orderBy('id')->first(); $invite_link = !$inviteEnabled || $inviteCode === null ? '' : 'https://' . $_SERVER['HTTP_HOST'] . '/auth/register?code=' . $inviteCode->code; } else { $invite_link = $inviteEnabled ? $user->getAffLink() : ''; } $paybacks = Payback::where("ref_by", $this->user->id)->orderBy("datetime", "desc")->paginate(10, ['*'], 'page', $pageNum); $paybacks->setPath('/user/invite'); return $this->view()->assign('paybacks', $paybacks)->assign('invite_link', $invite_link)->assign('invite_enabled', $inviteEnabled)->assign('invite_restricted', $inviteRestricted)->assign('has_invite_code', $inviteCode !== null)->assign('aff_method', $this->aff_method)->assign("cdn", $this->cdn)->assign("backup_cdn", $this->backup_cdn)->display('user/invite.tpl'); } public function doAff($request, $response, $args) { $type = $request->getParam('type'); $amount = $request->getParam('amount'); $user = $this->user; if ($type == "1") { $moneyIn = floatval($amount); if ($moneyIn < 0) { $res['ret'] = 0; $res['msg'] = "操作有误"; return $response->getBody()->write(json_encode($res)); } if ((float) $user->aff_money < (float) $moneyIn) { $res['ret'] = 0; $res['msg'] = "返利余额不足,最多转入为" . (float) $user->aff_money . "元。"; return $response->getBody()->write(json_encode($res)); } $user->money = $user->money + $moneyIn; $user->aff_money = $user->aff_money - $moneyIn; $user->save(); $res['ret'] = 1; $res['msg'] = "转入金额为" . $moneyIn . "元。"; return $response->getBody()->write(json_encode($res)); } else if ($type == "2") { $moneyOut = floatval($amount); if ($moneyOut < 0) { $res['ret'] = 0; $res['msg'] = "操作有误"; return $response->getBody()->write(json_encode($res)); } if ((float) $user->aff_money < (float) $moneyOut) { $res['ret'] = 0; $res['msg'] = "返利余额不足,最多提现为" . (float) $user->aff_money . "元。"; return $response->getBody()->write(json_encode($res)); } $apply = new CheckoutApply(); $apply->email = $user->email; $apply->status = 0; $apply->zhifubao = $request->getParam('zhifubao'); $apply->userid = $user->id; $apply->datetime = time(); $apply->money = $moneyOut; $apply->endtime = time(); $apply->save(); $res['ret'] = 1; $res['msg'] = "USDT 提现申请已提交,请等待管理员处理"; return $response->getBody()->write(json_encode($res)); } $res['ret'] = 0; $res['msg'] = "操作失败"; return $response->getBody()->write(json_encode($res)); } public function doInvite($request, $response, $args) { if (UserFeatureRestrictionService::isInviteRestricted($this->user)) { return $this->echoJson($response, [ 'ret' => 0, 'msg' => UserFeatureRestrictionService::INVITE_MESSAGE, ]); } if (!$this->user->canInvite()) { return $this->echoJson($response, [ 'ret' => 0, 'msg' => '当前账户不能使用邀请功能。', ]); } if ($this->aff_method === 'code') { $existing = InviteCode::where('user_id', $this->user->id)->first(); if ($existing !== null) { return $this->echoJson($response, [ 'ret' => 1, 'msg' => '邀请码已经存在。', ]); } $code = new InviteCode(); $code->code = $this->newInviteCodeValue(); $code->user_id = $this->user->id; $code->save(); return $this->echoJson($response, [ 'ret' => 1, 'msg' => '邀请码生成成功,剩余邀请次数不变。', ]); } // Keep the historical affid behavior unchanged. $n = $this->user->invite_num; if ($n < 1) { $res['ret'] = 0; $res['msg'] = "失败"; return $response->getBody()->write(json_encode($res)); } for ($i = 0; $i < $n; $i++) { $char = Tools::genRandomChar(12); $code = new InviteCode(); $code->code = $char; $code->user_id = $this->user->id; $code->save(); } $this->user->invite_num = 0; $this->user->save(); $res['ret'] = 1; $res['msg'] = "生成成功。"; return $this->echoJson($response, $res); } public function updatePassword($request, $response, $args) { $old = $request->getParam('oldpwd'); $password = $request->getParam('pwd'); if (!Hash::checkPassword($this->user->pass, $old)) { return $this->echoJson($response, ['ret' => 0, 'msg' => '旧密码错误']); } $error = Hash::newPasswordError($password); if ($error !== null || $password !== $request->getParam('repwd')) { return $this->echoJson($response, ['ret' => 0, 'msg' => $error ?? '两次密码不一致']); } $this->user->updatePassword($password); Auth::logout(); return $this->echoJson($response, ['ret' => 1, 'msg' => '密码修改成功,请重新登录']); } public function shop($request, $response, $args) { $shops = Shop::where('status', 1)->where('stock', '!=', 0)->orderBy('sort', 'desc')->get(); return $this->view()->assign('shops', $shops) ->assign('balance_purchase_restricted', UserFeatureRestrictionService::isBalancePurchaseRestricted($this->user)) ->assign('provisioning_available', false) ->assign('cdn', $this->cdn)->assign('backup_cdn', $this->backup_cdn)->display('user/shop.tpl'); } public function CouponCheck($request, $response, $args) { $coupon = $request->getParam('coupon'); $shop = $request->getParam('shop'); $shop = Shop::where("id", $shop)->where("status", 1)->first(); if ($shop == null) { $res['ret'] = 0; $res['msg'] = "非法请求"; return $response->getBody()->write(json_encode($res)); } if ($coupon == "") { $res['ret'] = 1; $res['name'] = $shop->name; $res['credit'] = "0 %"; $res['total'] = $shop->price . "元"; return $response->getBody()->write(json_encode($res)); } $coupon = Coupon::where("code", $coupon)->first(); if ($coupon == null) { $res['ret'] = 0; $res['msg'] = "优惠码无效"; return $response->getBody()->write(json_encode($res)); } if ((int) $coupon->expire < time()) { $res['ret'] = 0; $res['msg'] = "此优惠码已过期"; return $response->getBody()->write(json_encode($res)); } if ($coupon->order($shop->id) == false) { $res['ret'] = 0; $res['msg'] = "此优惠码不可用于此商品"; return $response->getBody()->write(json_encode($res)); } $credit = max(0, min(100, (float) $coupon->credit)); $res['ret'] = 1; $res['name'] = $shop->name; $res['credit'] = $credit . " %"; $res['total'] = round($shop->price * ((100 - $credit) / 100), 2) . "元"; return $response->getBody()->write(json_encode($res)); } public function buy($request, $response, $args) { // Plans are editable, but no debit or order is allowed until provisioning is integrated. return $response->withJson(['ret' => 0, 'msg' => '虚拟化服务尚未接入,暂不能购买/开通'], 409); } public function bought($request, $response, $args) { if (UserFeatureRestrictionService::isTransactionRecordsRestricted($this->user)) { return $response->withStatus(302)->withHeader('Location', '/user/shop'); } $pageNum = 1; if (isset($request->getQueryParams()["page"])) { $pageNum = $request->getQueryParams()["page"]; } $shops = Bought::where("userid", $this->user->id)->orderBy("id", "desc")->paginate(15, ['*'], 'page', $pageNum); $shops->setPath('/user/bought'); return $this->view()->assign('shops', $shops)->display('user/bought.tpl'); } public function deleteBoughtGet($request, $response, $args) { return $response->withJson(['ret' => 0, 'msg' => '虚拟化服务尚未接入,暂不能变更实例订单'], 409); } public function boughtInvoice($request, $response, $args) { if (UserFeatureRestrictionService::isTransactionRecordsRestricted($this->user)) { return $response->withStatus(302)->withHeader('Location', '/user/shop'); } $id = $args['id']; $bought = Bought::where("id", $id)->where("userid", $this->user->id)->first(); if ($bought == null) { $newResponse = $response->withStatus(302)->withHeader('Location', '/user/bought'); return $newResponse; } $plan = $bought->shop(); $invoiceNo = 'INV-' . str_pad($bought->id, 8, '0', STR_PAD_LEFT); return $this->view() ->assign('bought', $bought) ->assign('plan', $plan) ->assign('invoiceNo', $invoiceNo) ->display('user/bought_invoice.tpl'); } public function ticket($request, $response, $args) { if ($this->ticketAccessRestricted()) { return $this->ticketPageRestrictedResponse($response); } $pageNum = 1; if (isset($request->getQueryParams()["page"])) { $pageNum = $request->getQueryParams()["page"]; } $openTickets = Ticket::where("userid", $this->user->id)->where("rootid", 0)->where("status", 1)->count(); $closedTickets = Ticket::where("userid", $this->user->id)->where("rootid", 0)->where("status", 0)->count(); $tickets = Ticket::where("userid", $this->user->id)->where("rootid", 0)->orderBy("datetime", "desc")->paginate(15, ['*'], 'page', $pageNum); $tickets->setPath('/user/ticket'); return $this->view()->assign('tickets', $tickets) ->assign('openTickets', $openTickets) ->assign('closedTickets', $closedTickets) ->assign("cdn", $this->cdn) ->assign("backup_cdn", $this->backup_cdn) ->display('user/ticket.tpl'); } public function ticket_create($request, $response, $args) { if ($this->ticketAccessRestricted()) { return $this->ticketPageRestrictedResponse($response); } return $this->view()->display('user/ticket_create.tpl'); } public function ticket_add($request, $response, $args) { if ($this->ticketAccessRestricted()) { return $this->ticketActionRestrictedResponse($response); } $title = $request->getParam('title'); $content = $request->getParam('content'); if (!is_string($title) || !is_string($content) || trim($title) === '' || trim($content) === '') { return $this->echoJson($response, ['ret' => 0, 'msg' => '请填全工单主题和内容']); } $cleaner = new AntiXSS(); $ticket = new Ticket(); $ticket->title = $cleaner->xss_clean($title); $ticket->content = $cleaner->xss_clean($content); $ticket->rootid = 0; $ticket->userid = $this->user->id; $ticket->datetime = time(); $ticket->status = 1; if (!$ticket->save()) { return $this->echoJson($response, ['ret' => 0, 'msg' => '工单保存失败']); } $this->notifyTicketAdmins('新工单', $ticket, $ticket->content); return $this->echoJson($response, ['ret' => 1, 'msg' => '提交成功']); } public function ticket_update($request, $response, $args) { if ($this->ticketAccessRestricted()) { return $this->ticketActionRestrictedResponse($response); } $content = $request->getParam('content'); $status = $request->getParam('status'); if (!is_string($content) || trim($content) === '' || !in_array((string) $status, ['0', '1'], true)) { return $this->echoJson($response, ['ret' => 0, 'msg' => '请填全']); } $main = Ticket::where('id', (int) $args['id'])->where('rootid', 0)->where('userid', $this->user->id)->first(); if ($main === null) { return $this->echoJson($response, ['ret' => 0, 'msg' => '工单不存在']); } $event = (int) $status === 1 && (int) $main->status !== 1 ? '工单重新开启' : '用户回复工单'; $reply = new Ticket(); $reply->title = $main->title; $reply->content = (new AntiXSS())->xss_clean($content); $reply->rootid = $main->id; $reply->userid = $this->user->id; $reply->datetime = time(); $reply->status = (int) $status; $connection = $main->getConnection(); try { $connection->transaction(function () use ($main, $reply, $status) { $main->status = (int) $status; if (!$main->save() || !$reply->save()) { throw new \RuntimeException('工单回复保存失败'); } }); } catch (\Throwable $exception) { return $this->echoJson($response, ['ret' => 0, 'msg' => '工单回复保存失败']); } $this->notifyTicketAdmins($event, $main, $reply->content); return $this->echoJson($response, ['ret' => 1, 'msg' => '提交成功']); } public function ticket_view($request, $response, $args) { if ($this->ticketAccessRestricted()) { return $this->ticketPageRestrictedResponse($response); } $id = $args['id']; $ticket_main = Ticket::where("id", "=", $id)->where("rootid", "=", 0)->first(); if ($ticket_main == null || $ticket_main->userid != $this->user->id) { $newResponse = $response->withStatus(302)->withHeader('Location', '/user/ticket'); return $newResponse; } $pageNum = 1; if (isset($request->getQueryParams()["page"])) { $pageNum = $request->getQueryParams()["page"]; } $ticketset = Ticket::where("id", $id)->orWhere("rootid", "=", $id)->orderBy("datetime", "desc")->paginate(8, ['*'], 'page', $pageNum); $ticketset->setPath('/user/ticket/' . $id . "/view"); return $this->view()->assign('ticketset', $ticketset) ->assign('ticket_status', $ticket_main->status) ->assign('ticket_main', $ticket_main) ->assign("id", $id) ->display('user/ticket_view.tpl'); } private function ticketAccessRestricted() { return UserFeatureRestrictionService::isTicketRestricted($this->user); } private function notifyTicketAdmins($event, $ticket, $content) { foreach (User::where('is_admin', 1)->get() as $admin) { try { Mail::send($admin->email, Config::get('appName') . ' - ' . $event, 'news/warn.tpl', [ 'user' => $admin, 'text' => '工单 #' . (int) $ticket->id . ' 有新的消息,请在网站管理页面查看。', ]); } catch (\Throwable $exception) { error_log('Ticket administrator email failed for ticket ' . (int) $ticket->id); } } TicketTelegramNotifier::notify($event, (int) $ticket->id, $ticket->title, $content); } private function ticketPageRestrictedResponse($response) { return $response->withStatus(302)->withHeader('Location', '/user'); } private function ticketActionRestrictedResponse($response) { return $this->echoJson($response, [ 'ret' => 0, 'msg' => UserFeatureRestrictionService::TICKET_MESSAGE, ]); } public function disable($request, $response, $args) { return $this->view()->display('user/disable.tpl'); } public function logout($request, $response, $args) { Auth::logout(); $newResponse = $response->withStatus(302)->withHeader('Location', '/auth/login'); return $newResponse; } public function doResetiv($request, $response, $args) { $user = Auth::getUser(); if (UserFeatureRestrictionService::isInviteRestricted($user)) { return $this->echoJson($response, [ 'ret' => 0, 'msg' => UserFeatureRestrictionService::INVITE_MESSAGE, ]); } if (!$user->canInvite()) { return $this->echoJson($response, [ 'ret' => 0, 'msg' => '当前账户不能使用邀请功能。', ]); } if ($this->aff_method === "code") { $code = InviteCode::where('user_id', $user->id)->orderBy('id')->first(); if ($code === null) { $code = new InviteCode(); $code->user_id = $user->id; } $code->code = $this->newInviteCodeValue(); $code->save(); InviteCode::where('user_id', $user->id)->where('id', '<>', $code->id)->delete(); $res['msg'] = "邀请码已重置,剩余邀请次数不变。"; $res['ret'] = 1; return $this->echoJson($response, $res); } $res['msg'] = "重置成功.."; $res['ret'] = 1; return $this->echoJson($response, $res); } private function newInviteCodeValue() { do { $value = Tools::genRandomChar(12); } while (InviteCode::where('code', $value)->exists()); return $value; } }