You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Controllers/UserController.php

923 lines
34 KiB
PHP

<?php
namespace App\Controllers;
use App\Services\Auth;
use App\Models\InviteCode;
use App\Models\CloudInvoice;
use App\Models\Ticket;
use App\Models\TicketAttachment;
use App\Models\CloudInstance;
use App\Services\Config;
use App\Utils\Hash;
use App\Utils\Totp;
use App\Utils\Tools;
use voku\helper\AntiXSS;
use App\Models\User;
use App\Models\Configurations;
use App\Models\Code;
use App\Models\UserSurvey;
use App\Models\UserSurveyOption;
use App\Models\UserSurveyQuestion;
use App\Models\UserSurveyResponse;
use App\Models\CheckoutApply;
use App\Services\Mail;
use App\Services\TicketTelegramNotifier;
use App\Services\RedisClient;
use App\Services\AdminCsrf;
use App\Services\AccountSecurityService;
use App\Services\ReferralService;
use App\Services\ReferralConfig;
use App\Services\Payment\UsdtConfig;
use App\Services\Payment\YipayConfig;
use App\Services\Payment\PaytaroConfig;
use App\Services\TicketAttachmentService;
use App\Services\TicketReplyService;
use App\Services\Ticket\TicketQueueQuery;
use App\Services\Ticket\TicketReadModel;
use App\Services\Ticket\TicketThreadQuery;
use App\Services\Ticket\TicketViewer;
use App\Services\UserDrawerService;
/**
* Account and ticket pages.
*/
class UserController extends BaseController
{
private $user;
private $cdn = '';
private $backup_cdn = '';
private $aff_method;
public function __construct()
{
$this->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');
});
if (!in_array($this->aff_method, ['code', 'affid'], true)) {
$this->aff_method = 'affid';
}
}
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 : '');
$smarty->assign('account_csrf_token', AdminCsrf::token());
$smarty->assign('panel_announcements_bootstrap_json', empty($_GET['drawer'])
? UserDrawerService::announcementBootstrapJson() : '{}');
return $smarty;
}
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 CloudInvoice::where('user_id', $user->id)
->where('status', 'paid')->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)
{
$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);
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("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 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)
{
$csrf = $this->verifyAccountCsrf($request, $response);
if ($csrf !== null) {
return $csrf;
}
$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)
{
$csrf = $this->verifyAccountCsrf($request, $response);
if ($csrf !== null) {
return $csrf;
}
$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)
{
$csrf = $this->verifyAccountCsrf($request, $response);
if ($csrf !== null) {
return $csrf;
}
$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)
{
$user = Auth::getUser();
$inviteEnabled = $user->canInvite();
$inviteCode = null;
if ($inviteEnabled) {
$inviteCode = ReferralService::codeForUser($user);
}
$invite_link = $inviteEnabled ? $user->getAffLink() : '';
$referralValues = ReferralConfig::values();
$referralDays = ReferralConfig::normalizeDays(
$referralValues[ReferralConfig::VALID_DAYS_KEY] ?? ReferralConfig::DEFAULT_VALID_DAYS
);
return $this->view()->assign('invite_link', $invite_link)->assign('invite_enabled', $inviteEnabled)->assign('has_invite_code', $inviteCode !== null)->assign('aff_method', $this->aff_method)->assign('referral_rate', number_format(ReferralConfig::rateFor($user), 2, '.', ''))->assign('referral_days', $referralDays)->assign("cdn", $this->cdn)->assign("backup_cdn", $this->backup_cdn)->display('user/invite.tpl');
}
public function doAff($request, $response, $args)
{
$csrf = $this->verifyAccountCsrf($request, $response);
if ($csrf !== null) {
return $csrf;
}
$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)
{
$csrf = $this->verifyAccountCsrf($request, $response);
if ($csrf !== null) {
return $csrf;
}
if (!$this->user->canInvite()) {
return $this->echoJson($response, [
'ret' => 0,
'msg' => '当前账户不能使用邀请功能。',
]);
}
if ($this->aff_method === 'code' || $this->aff_method === 'affid') {
ReferralService::codeForUser($this->user);
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)
{
$csrf = $this->verifyAccountCsrf($request, $response);
if ($csrf !== null) {
return $csrf;
}
$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 ?? '两次密码不一致']);
}
$factor = AccountSecurityService::consumePasswordFactor(
$this->user,
$request->getParam('emailcode', ''),
$request->getParam('gacode', ''),
$request->getServerParam('REMOTE_ADDR', '')
);
if ($factor === null) {
$hasTotp = AccountSecurityService::hasTotp($this->user);
return $this->echoJson($response, [
'ret' => 0,
'need_security_verify' => 1,
'need_email_verify' => 1,
'need_ga_verify' => $hasTotp ? 1 : 0,
'msg' => $hasTotp ? '请使用邮箱验证码或谷歌验证器完成安全验证' : '请先获取邮箱验证码完成安全验证',
]);
}
$this->user->updatePassword($password);
Auth::logout();
return $this->echoJson($response, ['ret' => 1, 'msg' => '密码修改成功,请重新登录']);
}
public function ticket($request, $response, $args)
{
$pageNum = 1;
if (isset($request->getQueryParams()["page"])) {
$pageNum = max(1, (int) $request->getQueryParams()["page"]);
}
$queue = (new TicketReadModel())->queue(
new TicketQueueQuery($pageNum, 15),
TicketViewer::user((int) $this->user->id)
);
$tickets = $queue['tickets'];
$tickets->setPath('/user/ticket');
return $this->view()->assign('tickets', $tickets)
->assign('openTickets', $queue['open_count'])
->assign('closedTickets', $queue['closed_count'])
->assign("cdn", $this->cdn)
->assign("backup_cdn", $this->backup_cdn)
->display('user/ticket.tpl');
}
public function ticket_create($request, $response, $args)
{
return $this->view()->assign('instances', $this->ticketInstances())
->display('user/ticket_create.tpl');
}
public function ticket_add($request, $response, $args)
{
if (!AdminCsrf::verify($request)) {
return $this->echoJson($response, ['ret' => 0, 'msg' => '请求已过期,请刷新页面后重试']);
}
$title = $request->getParam('title');
$content = $request->getParam('content');
$ticketType = $this->ticketType($request->getParam('ticket_type'));
$priority = $this->ticketPriority($request->getParam('priority'));
$instanceId = $this->ticketInstanceId($request->getParam('instance_id'));
$instanceInput = $request->getParam('instance_id');
if ($instanceInput !== null && $instanceInput !== '' && $instanceId === null) {
return $this->echoJson($response, ['ret' => 0, 'msg' => '关联实例不存在或无权访问']);
}
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;
$ticket->ticket_type = $ticketType;
$ticket->priority = $priority;
$ticket->instance_id = $instanceId;
$connection = $ticket->getConnection();
$createdPaths = [];
try {
$connection->transaction(function () use ($ticket, $request, &$createdPaths) {
if (!$ticket->save()) {
throw new \RuntimeException('工单保存失败');
}
TicketAttachmentService::store(
$request,
(int) $ticket->id,
(int) $ticket->id,
(int) $this->user->id,
$createdPaths
);
}, 1);
} catch (\Throwable $exception) {
TicketAttachmentService::discardPaths($createdPaths);
error_log('Ticket creation failed: ' . $exception->getMessage());
$message = $exception instanceof \InvalidArgumentException
? $exception->getMessage()
: '工单保存失败';
return $this->echoJson($response, ['ret' => 0, 'msg' => $message]);
}
try {
// The ticket is already committed; notification failure must not
// make the client retry and create a duplicate thread.
$this->notifyTicketCreated($ticket);
} catch (\Throwable $exception) {
error_log('Ticket creation notification failed: ' . $exception->getMessage());
}
return $this->echoJson($response, ['ret' => 1, 'msg' => '提交成功']);
}
public function ticket_update($request, $response, $args)
{
if (!AdminCsrf::verify($request)) {
return $this->echoJson($response, ['ret' => 0, 'msg' => '请求已过期,请刷新页面后重试']);
}
$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' => '请填全']);
}
$cleanContent = (new AntiXSS())->xss_clean($content);
try {
$result = TicketReplyService::create(
(int) $args['id'],
(int) $this->user->id,
$cleanContent,
(int) $status,
$request,
(int) $this->user->id
);
} catch (\Throwable $exception) {
error_log('User ticket reply failed: ' . $exception->getMessage());
return $this->echoJson($response, [
'ret' => 0,
'msg' => $exception instanceof \InvalidArgumentException
? $exception->getMessage()
: '工单回复保存失败',
]);
}
if ($result === null) {
return $this->echoJson($response, ['ret' => 0, 'msg' => '工单不存在']);
}
try {
// Notifications are best-effort and deliberately happen only
// after the reply transaction has committed. A mail/Telegram
// outage must not make the client retry an already saved reply.
$this->notifyTicketAdmins($result['event'], $result['root'], $result['reply']->content);
} catch (\Throwable $exception) {
error_log('Ticket administrator notification failed: ' . $exception->getMessage());
}
return $this->echoJson($response, ['ret' => 1, 'msg' => '提交成功']);
}
public function ticket_view($request, $response, $args)
{
$id = (int) ($args['id'] ?? 0);
$pageNum = isset($request->getQueryParams()['page'])
? max(1, (int) $request->getQueryParams()['page'])
: 1;
$thread = (new TicketReadModel())->thread(
new TicketThreadQuery($id, $pageNum, 8),
TicketViewer::user((int) $this->user->id)
);
if ($thread === null) {
$newResponse = $response->withStatus(302)->withHeader('Location', '/user/ticket');
return $newResponse;
}
$ticket_main = $thread['root'];
$ticketset = $thread['messages'];
$ticketset->setPath('/user/ticket/' . $id . "/view");
return $this->view()->assign('ticketset', $ticketset)
->assign('ticket_status', $ticket_main->status)
->assign('ticket_main', $ticket_main)
->assign('ticket_display_title', $thread['title'])
->assign("id", $id)
->display('user/ticket_view.tpl');
}
public function ticket_attachment($request, $response, $args)
{
try {
$ticket = Ticket::where('id', (int) ($args['id'] ?? 0))->where('rootid', 0)
->where('userid', (int) $this->user->id)->first();
$attachment = TicketAttachment::where('id', (int) ($args['attachment_id'] ?? 0))
->where('ticket_id', $ticket ? (int) $ticket->id : -1)->first();
} catch (\Throwable $exception) {
return $response->withStatus(404);
}
return $this->streamTicketAttachment($response, $attachment);
}
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 notifyTicketCreated($ticket)
{
$url = rtrim((string) Config::get('baseUrl'), '/') . '/user/ticket/' . (int) $ticket->id . '/view';
Mail::send($this->user->email, Config::get('appName') . ' - 工单已创建', 'ticket/created.tpl', [
'user' => $this->user, 'ticket' => $ticket, 'ticket_url' => $url,
], [], 'ticket_created');
try {
$this->notifyTicketAdmins('新工单', $ticket, $ticket->content);
} catch (\Throwable $exception) {
error_log('Ticket administrator notification failed: ' . $exception->getMessage());
}
}
private function ticketInstances(): array
{
try {
return CloudInstance::where('user_id', (int) $this->user->id)
->where('status', '<>', 'deleted')->orderBy('id')->get(['id', 'name', 'uuid', 'status'])->all();
} catch (\Throwable $exception) {
return [];
}
}
private function ticketType($value): string
{
$value = is_scalar($value) ? (string) $value : '';
return in_array($value, ['pre_sales', 'after_sales', 'technical', 'finance'], true)
? $value : 'technical';
}
private function ticketPriority($value): string
{
$value = is_scalar($value) ? (string) $value : '';
return in_array($value, ['high', 'medium', 'low'], true) ? $value : 'medium';
}
private function ticketInstanceId($value): ?int
{
if (!is_scalar($value) || $value === null || $value === '' || !ctype_digit((string) $value)) {
return null;
}
try {
$instance = CloudInstance::where('id', (int) $value)->where('user_id', (int) $this->user->id)
->where('status', '<>', 'deleted')->first();
return $instance === null ? null : (int) $instance->id;
} catch (\Throwable $exception) {
return null;
}
}
protected function streamTicketAttachment($response, $attachment)
{
if (!$attachment instanceof TicketAttachment) {
return $response->withStatus(404);
}
$path = TicketAttachmentService::path($attachment);
if (!is_file($path)) {
return $response->withStatus(404);
}
$response = $response->withHeader('Content-Type', (string) $attachment->mime_type)
->withHeader('Content-Length', (string) filesize($path))
->withHeader('Content-Disposition', 'inline; filename*=UTF-8\'\'' . rawurlencode((string) $attachment->original_name))
->withHeader('Cache-Control', 'private, no-store')
->withHeader('X-Content-Type-Options', 'nosniff');
$response->getBody()->write((string) file_get_contents($path));
return $response;
}
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)
{
$csrf = $this->verifyAccountCsrf($request, $response);
if ($csrf !== null) {
return $csrf;
}
$user = Auth::getUser();
if (!$user->canInvite()) {
return $this->echoJson($response, [
'ret' => 0,
'msg' => '当前账户不能使用邀请功能。',
]);
}
if ($this->aff_method === "code" || $this->aff_method === 'affid') {
ReferralService::rotateForUser($user);
$res['msg'] = "推广链接已重置,剩余邀请次数不变。";
$res['ret'] = 1;
return $this->echoJson($response, $res);
}
$res['msg'] = "重置成功..";
$res['ret'] = 1;
return $this->echoJson($response, $res);
}
private function newInviteCodeValue()
{
return ReferralService::generateCode();
}
private function verifyAccountCsrf($request, $response)
{
if (AdminCsrf::verify($request)) {
return null;
}
return $this->echoJson($response, [
'ret' => 0,
'msg' => '请求已过期,请刷新页面后重试',
]);
}
}