Bläddra i källkod

feat: install and format with insights

Anankke 3 år sedan
förälder
incheckning
d85b7590d1
100 ändrade filer med 3370 tillägg och 3957 borttagningar
  1. 6 6
      app/container.php
  2. 3 1
      app/envload.php
  3. 1 1
      app/middleware.php
  4. 1 0
      app/predefine.php
  5. 236 238
      app/routes.php
  6. 3 0
      composer.json
  7. 5 4
      db/migrations/20220109130532_create_stream_media_table.php
  8. 6 5
      phinx.php
  9. 8 0
      phpinsights.php
  10. 12 10
      src/Command/Backup.php
  11. 107 129
      src/Command/ClientDownload.php
  12. 3 1
      src/Command/Command.php
  13. 42 43
      src/Command/DetectBan.php
  14. 17 18
      src/Command/DetectGFW.php
  15. 10 8
      src/Command/FinanceMail.php
  16. 75 82
      src/Command/Job.php
  17. 54 47
      src/Command/PortAutoChange.php
  18. 13 11
      src/Command/SendDiaryMail.php
  19. 51 52
      src/Command/Tool.php
  20. 65 63
      src/Command/Update.php
  21. 50 63
      src/Command/User.php
  22. 56 74
      src/Controllers/Admin/AnnController.php
  23. 18 20
      src/Controllers/Admin/ApiController.php
  24. 50 63
      src/Controllers/Admin/CodeController.php
  25. 35 39
      src/Controllers/Admin/DetectBanLogController.php
  26. 73 91
      src/Controllers/Admin/DetectController.php
  27. 38 46
      src/Controllers/Admin/GConfigController.php
  28. 103 125
      src/Controllers/Admin/IpController.php
  29. 102 121
      src/Controllers/Admin/NodeController.php
  30. 60 74
      src/Controllers/Admin/SettingController.php
  31. 96 120
      src/Controllers/Admin/ShopController.php
  32. 32 36
      src/Controllers/Admin/SubscribeLogController.php
  33. 69 83
      src/Controllers/Admin/TicketController.php
  34. 205 235
      src/Controllers/Admin/UserController.php
  35. 54 67
      src/Controllers/Admin/UserLog/BoughtLogController.php
  36. 24 32
      src/Controllers/Admin/UserLog/CodeLogController.php
  37. 35 43
      src/Controllers/Admin/UserLog/DetectLogController.php
  38. 26 34
      src/Controllers/Admin/UserLog/LoginLogController.php
  39. 27 35
      src/Controllers/Admin/UserLog/SubLogController.php
  40. 61 89
      src/Controllers/AdminController.php
  41. 153 190
      src/Controllers/AuthController.php
  42. 5 7
      src/Controllers/BaseController.php
  43. 13 33
      src/Controllers/HomeController.php
  44. 173 201
      src/Controllers/LinkController.php
  45. 21 37
      src/Controllers/Mod_Mu/FuncController.php
  46. 28 42
      src/Controllers/Mod_Mu/NodeController.php
  47. 43 58
      src/Controllers/Mod_Mu/UserController.php
  48. 30 39
      src/Controllers/PasswordController.php
  49. 123 127
      src/Controllers/SubController.php
  50. 50 63
      src/Controllers/User/NodeController.php
  51. 71 85
      src/Controllers/User/TicketController.php
  52. 157 255
      src/Controllers/UserController.php
  53. 5 10
      src/Middleware/Admin.php
  54. 6 11
      src/Middleware/Auth.php
  55. 14 18
      src/Middleware/AuthorizationBearer.php
  56. 3 8
      src/Middleware/Guest.php
  57. 14 19
      src/Middleware/Mod_Mu.php
  58. 3 0
      src/Models/Ann.php
  59. 4 4
      src/Models/BlockIp.php
  60. 16 17
      src/Models/Bought.php
  61. 6 4
      src/Models/Code.php
  62. 4 2
      src/Models/Coupon.php
  63. 5 5
      src/Models/DetectBanLog.php
  64. 11 15
      src/Models/DetectLog.php
  65. 3 1
      src/Models/DetectRule.php
  66. 2 0
      src/Models/EmailQueue.php
  67. 2 0
      src/Models/EmailVerify.php
  68. 18 23
      src/Models/GConfig.php
  69. 2 0
      src/Models/InviteCode.php
  70. 6 6
      src/Models/Ip.php
  71. 2 0
      src/Models/Link.php
  72. 6 8
      src/Models/LoginIp.php
  73. 25 21
      src/Models/Model.php
  74. 86 104
      src/Models/Node.php
  75. 2 0
      src/Models/NodeInfoLog.php
  76. 1 0
      src/Models/NodeOnlineLog.php
  77. 2 0
      src/Models/PasswordReset.php
  78. 10 8
      src/Models/Payback.php
  79. 2 0
      src/Models/Paylist.php
  80. 12 11
      src/Models/Setting.php
  81. 20 19
      src/Models/Shop.php
  82. 3 0
      src/Models/StreamMedia.php
  83. 3 1
      src/Models/TelegramSession.php
  84. 5 5
      src/Models/Ticket.php
  85. 2 0
      src/Models/Token.php
  86. 4 4
      src/Models/UnblockIp.php
  87. 168 201
      src/Models/User.php
  88. 1 0
      src/Models/UserHourlyUsage.php
  89. 13 18
      src/Models/UserSubscribeLog.php
  90. 2 0
      src/Services/Analytic.php
  91. 5 6
      src/Services/Analytics.php
  92. 10 11
      src/Services/Auth.php
  93. 5 3
      src/Services/Auth/Base.php
  94. 13 13
      src/Services/Auth/Cookie.php
  95. 9 7
      src/Services/Auth/JwtToken.php
  96. 5 3
      src/Services/Aws/Client.php
  97. 10 9
      src/Services/Aws/Factory.php
  98. 8 5
      src/Services/Boot.php
  99. 10 10
      src/Services/Captcha.php
  100. 3 1
      src/Services/CoinPayment.php

+ 6 - 6
app/container.php

@@ -2,8 +2,8 @@
 
 declare(strict_types=1);
 
-use Slim\Container;
 use App\Services\View;
+use Slim\Container;
 
 /**
  * Container Builder
@@ -16,19 +16,19 @@ $configuration = [
         'debug' => $_ENV['debug'],
         'whoops.editor' => 'sublime',
         'displayErrorDetails' => $_ENV['debug'],
-    ]
+    ],
 ];
 $container = new Container($configuration);
 
 $container['notFoundHandler'] = static function ($c) {
-    return static function ($request, $response) use ($c) {
+    return static function ($request, $response) {
         $view = View::getSmarty();
         return $response->withStatus(404)->write($view->fetch('404.tpl'));
     };
 };
 
 $container['notAllowedHandler'] = static function ($c) {
-    return static function ($request, $response, $methods) use ($c) {
+    return static function ($request, $response, $methods) {
         $view = View::getSmarty();
         return $response->withStatus(405)->write($view->fetch('405.tpl'));
     };
@@ -36,7 +36,7 @@ $container['notAllowedHandler'] = static function ($c) {
 
 if ($_ENV['debug'] === false) {
     $container['errorHandler'] = function ($c) {
-        return function ($request, $response, $exception) use ($c) {
+        return function ($request, $response, $exception) {
             $view = View::getSmarty();
             $exceptionId = empty($_ENV['sentry_dsn']) ? null : Sentry\captureException($exception);
             return $response->withStatus(500)
@@ -44,7 +44,7 @@ if ($_ENV['debug'] === false) {
         };
     };
     $container['phpErrorHandler'] = function ($c) {
-        return function ($request, $response, $exception) use ($c) {
+        return function ($request, $response, $exception) {
             $view = View::getSmarty();
             $exceptionId = empty($_ENV['sentry_dsn']) ? null : Sentry\captureException($exception);
             return $response->withStatus(500)

+ 3 - 1
app/envload.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 // make replace _ENV with env
 function searchEnvName($name)
 {
@@ -17,7 +19,7 @@ if (getenv('UIM_ENV_REPLACE_ENABLE')) {
         global $_ENV;
         $envUpKey = strtoupper($envKey);
         // Key starts with UIM_
-        if (strpos($envUpKey, "UIM_") === 0) {
+        if (strpos($envUpKey, 'UIM_') === 0) {
             // Valid env key, set to _ENV
             $configKey = substr($envUpKey, 4);
             $realKey = searchEnvName($configKey);

+ 1 - 1
app/middleware.php

@@ -4,7 +4,7 @@ declare(strict_types=1);
 
 use Slim\App;
 
-return static function (App $app) {
+return static function (App $app): void {
     if ($_ENV['debug'] === true) {
         $app->add(new Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware());
     }

+ 1 - 0
app/predefine.php

@@ -1,6 +1,7 @@
 <?php
 
 declare(strict_types=1);
+
 /**
  * To define global variable
  */

+ 236 - 238
app/routes.php

@@ -3,334 +3,332 @@
 declare(strict_types=1);
 
 use Slim\App as SlimApp;
-use App\Middleware\{Auth, Guest, Admin, Mod_Mu, AuthorizationBearer};
 
-return function (SlimApp $app) {
+return function (SlimApp $app): void {
     // Home
-    $app->get('/',          App\Controllers\HomeController::class . ':index');
-    $app->get('/404',       App\Controllers\HomeController::class . ':page404');
-    $app->get('/405',       App\Controllers\HomeController::class . ':page405');
-    $app->get('/500',       App\Controllers\HomeController::class . ':page500');
-    $app->get('/tos',       App\Controllers\HomeController::class . ':tos');
-    $app->get('/staff',     App\Controllers\HomeController::class . ':staff');
+    $app->get('/', App\Controllers\HomeController::class . ':index');
+    $app->get('/404', App\Controllers\HomeController::class . ':page404');
+    $app->get('/405', App\Controllers\HomeController::class . ':page405');
+    $app->get('/500', App\Controllers\HomeController::class . ':page500');
+    $app->get('/tos', App\Controllers\HomeController::class . ':tos');
+    $app->get('/staff', App\Controllers\HomeController::class . ':staff');
 
     // other
-    $app->post('/notify',               App\Controllers\HomeController::class . ':notify');
+    $app->post('/notify', App\Controllers\HomeController::class . ':notify');
 
     // Telegram
-    $app->post('/telegram_callback',    App\Controllers\HomeController::class . ':telegram');
+    $app->post('/telegram_callback', App\Controllers\HomeController::class . ':telegram');
 
     // User Center
-    $app->group('/user', function () {
-        $this->get('',                          App\Controllers\UserController::class . ':index');
-        $this->get('/',                         App\Controllers\UserController::class . ':index');
-
-        $this->post('/checkin',                 App\Controllers\UserController::class . ':doCheckin');
-
-        $this->get('/announcement',             App\Controllers\UserController::class . ':announcement');
-        $this->get('/media',                    App\Controllers\UserController::class . ':media');
-
-        $this->get('/donate',                   App\Controllers\UserController::class . ':donate');
-        $this->get('/profile',                  App\Controllers\UserController::class . ':profile');
-        $this->get('/invite',                   App\Controllers\UserController::class . ':invite');
-        $this->get('/disable',                  App\Controllers\UserController::class . ':disable');
-
-        $this->get('/node',                     App\Controllers\User\NodeController::class . ':user_node_page');
-        $this->get('/node/{id}/ajax',           App\Controllers\User\NodeController::class . ':user_node_ajax');
-        $this->get('/node/{id}',                App\Controllers\User\NodeController::class . ':user_node_info');
-
-        $this->get('/detect',                   App\Controllers\UserController::class . ':detect_index');
-        $this->get('/detect/log',               App\Controllers\UserController::class . ':detect_log');
-
-        $this->get('/shop',                     App\Controllers\UserController::class . ':shop');
-        $this->post('/coupon_check',            App\Controllers\UserController::class . ':CouponCheck');
-        $this->post('/buy',                     App\Controllers\UserController::class . ':buy');
-        $this->post('/buy_traffic_package',     App\Controllers\UserController::class . ':buy_traffic_package');
-
-        $this->get('/ticket',                   App\Controllers\User\TicketController::class . ':ticket');
-        $this->get('/ticket/create',            App\Controllers\User\TicketController::class . ':ticket_create');
-        $this->post('/ticket',                  App\Controllers\User\TicketController::class . ':ticket_add');
-        $this->get('/ticket/{id}/view',         App\Controllers\User\TicketController::class . ':ticket_view');
-        $this->put('/ticket/{id}',              App\Controllers\User\TicketController::class . ':ticket_update');
-
-        $this->post('/buy_invite',              App\Controllers\UserController::class . ':buyInvite');
-        $this->post('/custom_invite',           App\Controllers\UserController::class . ':customInvite');
-        $this->get('/edit',                     App\Controllers\UserController::class . ':edit');
-        $this->post('/email',                   App\Controllers\UserController::class . ':updateEmail');
-        $this->post('/username',                App\Controllers\UserController::class . ':updateUsername');
-        $this->post('/password',                App\Controllers\UserController::class . ':updatePassword');
-        $this->post('/send',                    App\Controllers\AuthController::class . ':sendVerify');
-        $this->post('/wechat',                  App\Controllers\UserController::class . ':updateWechat');
-        $this->post('/ssr',                     App\Controllers\UserController::class . ':updateSSR');
-        $this->post('/theme',                   App\Controllers\UserController::class . ':updateTheme');
-        $this->post('/mail',                    App\Controllers\UserController::class . ':updateMail');
-        $this->post('/sspwd',                   App\Controllers\UserController::class . ':updateSsPwd');
-        $this->post('/method',                  App\Controllers\UserController::class . ':updateMethod');
-        $this->post('/hide',                    App\Controllers\UserController::class . ':updateHide');
-        $this->get('/sys',                      App\Controllers\UserController::class . ':sys');
-        $this->get('/trafficlog',               App\Controllers\UserController::class . ':trafficLog');
-        $this->get('/kill',                     App\Controllers\UserController::class . ':kill');
-        $this->post('/kill',                    App\Controllers\UserController::class . ':handleKill');
-        $this->get('/logout',                   App\Controllers\UserController::class . ':logout');
-        $this->get('/backtoadmin',              App\Controllers\UserController::class . ':backtoadmin');
-        $this->get('/code',                     App\Controllers\UserController::class . ':code');
-
-        $this->get('/code_check',               App\Controllers\UserController::class . ':code_check');
-        $this->post('/code',                    App\Controllers\UserController::class . ':codepost');
-        $this->post('/gacheck',                 App\Controllers\UserController::class . ':GaCheck');
-        $this->post('/gaset',                   App\Controllers\UserController::class . ':GaSet');
-        $this->get('/gareset',                  App\Controllers\UserController::class . ':GaReset');
-        $this->get('/telegram_reset',           App\Controllers\UserController::class . ':telegram_reset');
-        $this->post('/resetport',               App\Controllers\UserController::class . ':ResetPort');
-        $this->post('/specifyport',             App\Controllers\UserController::class . ':SpecifyPort');
-        $this->post('/unblock',                 App\Controllers\UserController::class . ':Unblock');
-        $this->get('/bought',                   App\Controllers\UserController::class . ':bought');
-        $this->delete('/bought',                App\Controllers\UserController::class . ':deleteBoughtGet');
-        $this->get('/url_reset',                App\Controllers\UserController::class . ':resetURL');
-        $this->put('/invite',                   App\Controllers\UserController::class . ':resetInviteURL');
-
-        $this->get('/order',                    App\Controllers\UserController::class . ':user_order');
-        $this->get('/product',                  App\Controllers\UserController::class . ':product_index');
+    $app->group('/user', function (): void {
+        $this->get('', App\Controllers\UserController::class . ':index');
+        $this->get('/', App\Controllers\UserController::class . ':index');
+
+        $this->post('/checkin', App\Controllers\UserController::class . ':doCheckin');
+
+        $this->get('/announcement', App\Controllers\UserController::class . ':announcement');
+        $this->get('/media', App\Controllers\UserController::class . ':media');
+
+        $this->get('/donate', App\Controllers\UserController::class . ':donate');
+        $this->get('/profile', App\Controllers\UserController::class . ':profile');
+        $this->get('/invite', App\Controllers\UserController::class . ':invite');
+        $this->get('/disable', App\Controllers\UserController::class . ':disable');
+
+        $this->get('/node', App\Controllers\User\NodeController::class . ':user_node_page');
+        $this->get('/node/{id}/ajax', App\Controllers\User\NodeController::class . ':user_node_ajax');
+        $this->get('/node/{id}', App\Controllers\User\NodeController::class . ':user_node_info');
+
+        $this->get('/detect', App\Controllers\UserController::class . ':detect_index');
+        $this->get('/detect/log', App\Controllers\UserController::class . ':detect_log');
+
+        $this->get('/shop', App\Controllers\UserController::class . ':shop');
+        $this->post('/coupon_check', App\Controllers\UserController::class . ':CouponCheck');
+        $this->post('/buy', App\Controllers\UserController::class . ':buy');
+        $this->post('/buy_traffic_package', App\Controllers\UserController::class . ':buy_traffic_package');
+
+        $this->get('/ticket', App\Controllers\User\TicketController::class . ':ticket');
+        $this->get('/ticket/create', App\Controllers\User\TicketController::class . ':ticket_create');
+        $this->post('/ticket', App\Controllers\User\TicketController::class . ':ticket_add');
+        $this->get('/ticket/{id}/view', App\Controllers\User\TicketController::class . ':ticket_view');
+        $this->put('/ticket/{id}', App\Controllers\User\TicketController::class . ':ticket_update');
+
+        $this->post('/buy_invite', App\Controllers\UserController::class . ':buyInvite');
+        $this->post('/custom_invite', App\Controllers\UserController::class . ':customInvite');
+        $this->get('/edit', App\Controllers\UserController::class . ':edit');
+        $this->post('/email', App\Controllers\UserController::class . ':updateEmail');
+        $this->post('/username', App\Controllers\UserController::class . ':updateUsername');
+        $this->post('/password', App\Controllers\UserController::class . ':updatePassword');
+        $this->post('/send', App\Controllers\AuthController::class . ':sendVerify');
+        $this->post('/wechat', App\Controllers\UserController::class . ':updateWechat');
+        $this->post('/ssr', App\Controllers\UserController::class . ':updateSSR');
+        $this->post('/theme', App\Controllers\UserController::class . ':updateTheme');
+        $this->post('/mail', App\Controllers\UserController::class . ':updateMail');
+        $this->post('/sspwd', App\Controllers\UserController::class . ':updateSsPwd');
+        $this->post('/method', App\Controllers\UserController::class . ':updateMethod');
+        $this->post('/hide', App\Controllers\UserController::class . ':updateHide');
+        $this->get('/sys', App\Controllers\UserController::class . ':sys');
+        $this->get('/trafficlog', App\Controllers\UserController::class . ':trafficLog');
+        $this->get('/kill', App\Controllers\UserController::class . ':kill');
+        $this->post('/kill', App\Controllers\UserController::class . ':handleKill');
+        $this->get('/logout', App\Controllers\UserController::class . ':logout');
+        $this->get('/backtoadmin', App\Controllers\UserController::class . ':backtoadmin');
+        $this->get('/code', App\Controllers\UserController::class . ':code');
+
+        $this->get('/code_check', App\Controllers\UserController::class . ':code_check');
+        $this->post('/code', App\Controllers\UserController::class . ':codepost');
+        $this->post('/gacheck', App\Controllers\UserController::class . ':GaCheck');
+        $this->post('/gaset', App\Controllers\UserController::class . ':GaSet');
+        $this->get('/gareset', App\Controllers\UserController::class . ':GaReset');
+        $this->get('/telegram_reset', App\Controllers\UserController::class . ':telegram_reset');
+        $this->post('/resetport', App\Controllers\UserController::class . ':ResetPort');
+        $this->post('/specifyport', App\Controllers\UserController::class . ':SpecifyPort');
+        $this->post('/unblock', App\Controllers\UserController::class . ':Unblock');
+        $this->get('/bought', App\Controllers\UserController::class . ':bought');
+        $this->delete('/bought', App\Controllers\UserController::class . ':deleteBoughtGet');
+        $this->get('/url_reset', App\Controllers\UserController::class . ':resetURL');
+        $this->put('/invite', App\Controllers\UserController::class . ':resetInviteURL');
+
+        $this->get('/order', App\Controllers\UserController::class . ':user_order');
+        $this->get('/product', App\Controllers\UserController::class . ':product_index');
 
         // 订阅记录
-        $this->get('/subscribe_log',            App\Controllers\UserController::class . ':subscribe_log');
+        $this->get('/subscribe_log', App\Controllers\UserController::class . ':subscribe_log');
 
         // getUserAllURL
-        $this->get('/getUserAllURL',            App\Controllers\UserController::class . ':getUserAllURL');
+        $this->get('/getUserAllURL', App\Controllers\UserController::class . ':getUserAllURL');
 
         // getPcClient
-        $this->get('/getPcClient',              App\Controllers\UserController::class . ':getPcClient');
+        $this->get('/getPcClient', App\Controllers\UserController::class . ':getPcClient');
 
         //Reconstructed Payment System
-        $this->post('/payment/purchase/{type}',        App\Services\Payment::class . ':purchase');
-        $this->get('/payment/purchase/{type}',         App\Services\Payment::class . ':purchase');
-        $this->get('/payment/return/{type}',           App\Services\Payment::class . ':returnHTML');
-
+        $this->post('/payment/purchase/{type}', App\Services\Payment::class . ':purchase');
+        $this->get('/payment/purchase/{type}', App\Services\Payment::class . ':purchase');
+        $this->get('/payment/return/{type}', App\Services\Payment::class . ':returnHTML');
     })->add(new Auth());
 
-    $app->group('/payment', function () {
-        $this->get('/notify/{type}',           App\Services\Payment::class . ':notify');
-        $this->post('/notify/{type}',   App\Services\Payment::class . ':notify');
-        $this->post('/status/{type}',          App\Services\Payment::class . ':getStatus');
+    $app->group('/payment', function (): void {
+        $this->get('/notify/{type}', App\Services\Payment::class . ':notify');
+        $this->post('/notify/{type}', App\Services\Payment::class . ':notify');
+        $this->post('/status/{type}', App\Services\Payment::class . ':getStatus');
         // $this->post('/coinpay/notify',  App\Services\CoinPayment::class. ':notify');
     });
 
     // Auth
-    $app->group('/auth', function () {
-        $this->get('/login',            App\Controllers\AuthController::class . ':login');
-        $this->post('/qrcode_check',    App\Controllers\AuthController::class . ':qrcode_check');
-        $this->post('/login',           App\Controllers\AuthController::class . ':loginHandle');
-        $this->post('/qrcode_login',    App\Controllers\AuthController::class . ':qrcode_loginHandle');
-        $this->get('/register',         App\Controllers\AuthController::class . ':register');
-        $this->post('/register',        App\Controllers\AuthController::class . ':registerHandle');
-        $this->post('/send',            App\Controllers\AuthController::class . ':sendVerify');
-        $this->get('/logout',           App\Controllers\AuthController::class . ':logout');
-        $this->get('/telegram_oauth',   App\Controllers\AuthController::class . ':telegram_oauth');
+    $app->group('/auth', function (): void {
+        $this->get('/login', App\Controllers\AuthController::class . ':login');
+        $this->post('/qrcode_check', App\Controllers\AuthController::class . ':qrcode_check');
+        $this->post('/login', App\Controllers\AuthController::class . ':loginHandle');
+        $this->post('/qrcode_login', App\Controllers\AuthController::class . ':qrcode_loginHandle');
+        $this->get('/register', App\Controllers\AuthController::class . ':register');
+        $this->post('/register', App\Controllers\AuthController::class . ':registerHandle');
+        $this->post('/send', App\Controllers\AuthController::class . ':sendVerify');
+        $this->get('/logout', App\Controllers\AuthController::class . ':logout');
+        $this->get('/telegram_oauth', App\Controllers\AuthController::class . ':telegram_oauth');
         $this->get('/login_getCaptcha', App\Controllers\AuthController::class . ':getCaptcha');
     })->add(new Guest());
 
     // Password
-    $app->group('/password', function () {
-        $this->get('/reset',            App\Controllers\PasswordController::class . ':reset');
-        $this->post('/reset',           App\Controllers\PasswordController::class . ':handleReset');
-        $this->get('/token/{token}',    App\Controllers\PasswordController::class . ':token');
-        $this->post('/token/{token}',   App\Controllers\PasswordController::class . ':handleToken');
+    $app->group('/password', function (): void {
+        $this->get('/reset', App\Controllers\PasswordController::class . ':reset');
+        $this->post('/reset', App\Controllers\PasswordController::class . ':handleReset');
+        $this->get('/token/{token}', App\Controllers\PasswordController::class . ':token');
+        $this->post('/token/{token}', App\Controllers\PasswordController::class . ':handleToken');
     })->add(new Guest());
 
     // Admin
-    $app->group('/admin', function () {
-        $this->get('',                          App\Controllers\AdminController::class . ':index');
-        $this->get('/',                         App\Controllers\AdminController::class . ':index');
+    $app->group('/admin', function (): void {
+        $this->get('', App\Controllers\AdminController::class . ':index');
+        $this->get('/', App\Controllers\AdminController::class . ':index');
 
-        $this->get('/sys',                      App\Controllers\AdminController::class . ':sys');
-        $this->get('/invite',                   App\Controllers\AdminController::class . ':invite');
-        $this->post('/invite',                  App\Controllers\AdminController::class . ':addInvite');
-        $this->post('/chginvite',               App\Controllers\AdminController::class . ':chgInvite');
-        $this->post('/payback/ajax',            App\Controllers\AdminController::class . ':ajax_payback');
+        $this->get('/sys', App\Controllers\AdminController::class . ':sys');
+        $this->get('/invite', App\Controllers\AdminController::class . ':invite');
+        $this->post('/invite', App\Controllers\AdminController::class . ':addInvite');
+        $this->post('/chginvite', App\Controllers\AdminController::class . ':chgInvite');
+        $this->post('/payback/ajax', App\Controllers\AdminController::class . ':ajax_payback');
 
         // Node Mange
-        $this->get('/node',                     App\Controllers\Admin\NodeController::class . ':index');
-        $this->get('/node/create',              App\Controllers\Admin\NodeController::class . ':create');
-        $this->post('/node',                    App\Controllers\Admin\NodeController::class . ':add');
-        $this->get('/node/{id}/edit',           App\Controllers\Admin\NodeController::class . ':edit');
-        $this->put('/node/{id}',                App\Controllers\Admin\NodeController::class . ':update');
-        $this->delete('/node',                  App\Controllers\Admin\NodeController::class . ':delete');
-        $this->post('/node/ajax',               App\Controllers\Admin\NodeController::class . ':ajax');
+        $this->get('/node', App\Controllers\Admin\NodeController::class . ':index');
+        $this->get('/node/create', App\Controllers\Admin\NodeController::class . ':create');
+        $this->post('/node', App\Controllers\Admin\NodeController::class . ':add');
+        $this->get('/node/{id}/edit', App\Controllers\Admin\NodeController::class . ':edit');
+        $this->put('/node/{id}', App\Controllers\Admin\NodeController::class . ':update');
+        $this->delete('/node', App\Controllers\Admin\NodeController::class . ':delete');
+        $this->post('/node/ajax', App\Controllers\Admin\NodeController::class . ':ajax');
 
         // Ticket Mange
-        $this->get('/ticket',                   App\Controllers\Admin\TicketController::class . ':index');
-        $this->post('/ticket',                  App\Controllers\Admin\TicketController::class . ':add');
-        $this->get('/ticket/{id}/view',         App\Controllers\Admin\TicketController::class . ':show');
-        $this->put('/ticket/{id}',              App\Controllers\Admin\TicketController::class . ':update');
-        $this->post('/ticket/ajax',             App\Controllers\Admin\TicketController::class . ':ajax');
+        $this->get('/ticket', App\Controllers\Admin\TicketController::class . ':index');
+        $this->post('/ticket', App\Controllers\Admin\TicketController::class . ':add');
+        $this->get('/ticket/{id}/view', App\Controllers\Admin\TicketController::class . ':show');
+        $this->put('/ticket/{id}', App\Controllers\Admin\TicketController::class . ':update');
+        $this->post('/ticket/ajax', App\Controllers\Admin\TicketController::class . ':ajax');
 
         // Shop Mange
-        $this->get('/shop',                     App\Controllers\Admin\ShopController::class . ':index');
-        $this->post('/shop/ajax',               App\Controllers\Admin\ShopController::class . ':ajax_shop');
-        $this->get('/shop/create',              App\Controllers\Admin\ShopController::class . ':create');
-        $this->post('/shop',                    App\Controllers\Admin\ShopController::class . ':add');
-        $this->get('/shop/{id}/edit',           App\Controllers\Admin\ShopController::class . ':edit');
-        $this->put('/shop/{id}',                App\Controllers\Admin\ShopController::class . ':update');
-        $this->delete('/shop',                  App\Controllers\Admin\ShopController::class . ':deleteGet');
+        $this->get('/shop', App\Controllers\Admin\ShopController::class . ':index');
+        $this->post('/shop/ajax', App\Controllers\Admin\ShopController::class . ':ajax_shop');
+        $this->get('/shop/create', App\Controllers\Admin\ShopController::class . ':create');
+        $this->post('/shop', App\Controllers\Admin\ShopController::class . ':add');
+        $this->get('/shop/{id}/edit', App\Controllers\Admin\ShopController::class . ':edit');
+        $this->put('/shop/{id}', App\Controllers\Admin\ShopController::class . ':update');
+        $this->delete('/shop', App\Controllers\Admin\ShopController::class . ':deleteGet');
 
         // Bought Mange
-        $this->get('/bought',                   App\Controllers\Admin\ShopController::class . ':bought');
-        $this->delete('/bought',                App\Controllers\Admin\ShopController::class . ':deleteBoughtGet');
-        $this->post('/bought/ajax',             App\Controllers\Admin\ShopController::class . ':ajax_bought');
+        $this->get('/bought', App\Controllers\Admin\ShopController::class . ':bought');
+        $this->delete('/bought', App\Controllers\Admin\ShopController::class . ':deleteBoughtGet');
+        $this->post('/bought/ajax', App\Controllers\Admin\ShopController::class . ':ajax_bought');
 
         // Product
-        $this->get('/product',                  App\Controllers\Admin\ProductController::class . ':index');
-        $this->get('/product/create',           App\Controllers\Admin\ProductController::class . ':create');
-        $this->post('/product',                 App\Controllers\Admin\ProductController::class . ':save');
-        $this->get('/product/{id}/edit',        App\Controllers\Admin\ProductController::class . ':edit');
-        $this->put('/product/{id}',             App\Controllers\Admin\ProductController::class . ':update');
-        $this->delete('/product/{id}',          App\Controllers\Admin\ProductController::class . ':delete');
+        $this->get('/product', App\Controllers\Admin\ProductController::class . ':index');
+        $this->get('/product/create', App\Controllers\Admin\ProductController::class . ':create');
+        $this->post('/product', App\Controllers\Admin\ProductController::class . ':save');
+        $this->get('/product/{id}/edit', App\Controllers\Admin\ProductController::class . ':edit');
+        $this->put('/product/{id}', App\Controllers\Admin\ProductController::class . ':update');
+        $this->delete('/product/{id}', App\Controllers\Admin\ProductController::class . ':delete');
 
         // Ann Mange
-        $this->get('/announcement',             App\Controllers\Admin\AnnController::class . ':index');
-        $this->get('/announcement/create',      App\Controllers\Admin\AnnController::class . ':create');
-        $this->post('/announcement',            App\Controllers\Admin\AnnController::class . ':add');
-        $this->get('/announcement/{id}/edit',   App\Controllers\Admin\AnnController::class . ':edit');
-        $this->put('/announcement/{id}',        App\Controllers\Admin\AnnController::class . ':update');
-        $this->delete('/announcement',          App\Controllers\Admin\AnnController::class . ':delete');
-        $this->post('/announcement/ajax',       App\Controllers\Admin\AnnController::class . ':ajax');
+        $this->get('/announcement', App\Controllers\Admin\AnnController::class . ':index');
+        $this->get('/announcement/create', App\Controllers\Admin\AnnController::class . ':create');
+        $this->post('/announcement', App\Controllers\Admin\AnnController::class . ':add');
+        $this->get('/announcement/{id}/edit', App\Controllers\Admin\AnnController::class . ':edit');
+        $this->put('/announcement/{id}', App\Controllers\Admin\AnnController::class . ':update');
+        $this->delete('/announcement', App\Controllers\Admin\AnnController::class . ':delete');
+        $this->post('/announcement/ajax', App\Controllers\Admin\AnnController::class . ':ajax');
 
         // Detect Mange
-        $this->get('/detect',                   App\Controllers\Admin\DetectController::class . ':index');
-        $this->get('/detect/create',            App\Controllers\Admin\DetectController::class . ':create');
-        $this->post('/detect',                  App\Controllers\Admin\DetectController::class . ':add');
-        $this->get('/detect/{id}/edit',         App\Controllers\Admin\DetectController::class . ':edit');
-        $this->put('/detect/{id}',              App\Controllers\Admin\DetectController::class . ':update');
-        $this->delete('/detect',                App\Controllers\Admin\DetectController::class . ':delete');
-        $this->get('/detect/log',               App\Controllers\Admin\DetectController::class . ':log');
-        $this->post('/detect/ajax',             App\Controllers\Admin\DetectController::class . ':ajax_rule');
-        $this->post('/detect/log/ajax',         App\Controllers\Admin\DetectController::class . ':ajax_log');
+        $this->get('/detect', App\Controllers\Admin\DetectController::class . ':index');
+        $this->get('/detect/create', App\Controllers\Admin\DetectController::class . ':create');
+        $this->post('/detect', App\Controllers\Admin\DetectController::class . ':add');
+        $this->get('/detect/{id}/edit', App\Controllers\Admin\DetectController::class . ':edit');
+        $this->put('/detect/{id}', App\Controllers\Admin\DetectController::class . ':update');
+        $this->delete('/detect', App\Controllers\Admin\DetectController::class . ':delete');
+        $this->get('/detect/log', App\Controllers\Admin\DetectController::class . ':log');
+        $this->post('/detect/ajax', App\Controllers\Admin\DetectController::class . ':ajax_rule');
+        $this->post('/detect/log/ajax', App\Controllers\Admin\DetectController::class . ':ajax_log');
 
         // IP Mange
-        $this->get('/block',                    App\Controllers\Admin\IpController::class . ':block');
-        $this->get('/unblock',                  App\Controllers\Admin\IpController::class . ':unblock');
-        $this->post('/unblock',                 App\Controllers\Admin\IpController::class . ':doUnblock');
-        $this->get('/login',                    App\Controllers\Admin\IpController::class . ':index');
-        $this->get('/alive',                    App\Controllers\Admin\IpController::class . ':alive');
-        $this->post('/block/ajax',              App\Controllers\Admin\IpController::class . ':ajax_block');
-        $this->post('/unblock/ajax',            App\Controllers\Admin\IpController::class . ':ajax_unblock');
-        $this->post('/login/ajax',              App\Controllers\Admin\IpController::class . ':ajax_login');
-        $this->post('/alive/ajax',              App\Controllers\Admin\IpController::class . ':ajax_alive');
+        $this->get('/block', App\Controllers\Admin\IpController::class . ':block');
+        $this->get('/unblock', App\Controllers\Admin\IpController::class . ':unblock');
+        $this->post('/unblock', App\Controllers\Admin\IpController::class . ':doUnblock');
+        $this->get('/login', App\Controllers\Admin\IpController::class . ':index');
+        $this->get('/alive', App\Controllers\Admin\IpController::class . ':alive');
+        $this->post('/block/ajax', App\Controllers\Admin\IpController::class . ':ajax_block');
+        $this->post('/unblock/ajax', App\Controllers\Admin\IpController::class . ':ajax_unblock');
+        $this->post('/login/ajax', App\Controllers\Admin\IpController::class . ':ajax_login');
+        $this->post('/alive/ajax', App\Controllers\Admin\IpController::class . ':ajax_alive');
 
         // Code Mange
-        $this->get('/code',                     App\Controllers\Admin\CodeController::class . ':index');
-        $this->get('/code/create',              App\Controllers\Admin\CodeController::class . ':create');
-        $this->post('/code',                    App\Controllers\Admin\CodeController::class . ':add');
-        $this->get('/donate/create',            App\Controllers\Admin\CodeController::class . ':donate_create');
-        $this->post('/donate',                  App\Controllers\Admin\CodeController::class . ':donate_add');
-        $this->post('/code/ajax',               App\Controllers\Admin\CodeController::class . ':ajax_code');
+        $this->get('/code', App\Controllers\Admin\CodeController::class . ':index');
+        $this->get('/code/create', App\Controllers\Admin\CodeController::class . ':create');
+        $this->post('/code', App\Controllers\Admin\CodeController::class . ':add');
+        $this->get('/donate/create', App\Controllers\Admin\CodeController::class . ':donate_create');
+        $this->post('/donate', App\Controllers\Admin\CodeController::class . ':donate_add');
+        $this->post('/code/ajax', App\Controllers\Admin\CodeController::class . ':ajax_code');
 
         // User Mange
-        $this->get('/user',                     App\Controllers\Admin\UserController::class . ':index');
-        $this->get('/user/{id}/edit',           App\Controllers\Admin\UserController::class . ':edit');
-        $this->put('/user/{id}',                App\Controllers\Admin\UserController::class . ':update');
-        $this->delete('/user',                  App\Controllers\Admin\UserController::class . ':delete');
-        $this->post('/user/changetouser',       App\Controllers\Admin\UserController::class . ':changetouser');
-        $this->post('/user/ajax',               App\Controllers\Admin\UserController::class . ':ajax');
-        $this->post('/user/create',             App\Controllers\Admin\UserController::class . ':createNewUser');
+        $this->get('/user', App\Controllers\Admin\UserController::class . ':index');
+        $this->get('/user/{id}/edit', App\Controllers\Admin\UserController::class . ':edit');
+        $this->put('/user/{id}', App\Controllers\Admin\UserController::class . ':update');
+        $this->delete('/user', App\Controllers\Admin\UserController::class . ':delete');
+        $this->post('/user/changetouser', App\Controllers\Admin\UserController::class . ':changetouser');
+        $this->post('/user/ajax', App\Controllers\Admin\UserController::class . ':ajax');
+        $this->post('/user/create', App\Controllers\Admin\UserController::class . ':createNewUser');
 
         // Coupon Mange
-        $this->get('/coupon',                   App\Controllers\AdminController::class . ':coupon');
-        $this->post('/coupon',                  App\Controllers\AdminController::class . ':addCoupon');
-        $this->post('/coupon/ajax',             App\Controllers\AdminController::class . ':ajax_coupon');
+        $this->get('/coupon', App\Controllers\AdminController::class . ':coupon');
+        $this->post('/coupon', App\Controllers\AdminController::class . ':addCoupon');
+        $this->post('/coupon/ajax', App\Controllers\AdminController::class . ':ajax_coupon');
 
         // Subscribe Log Mange
-        $this->get('/subscribe',                App\Controllers\Admin\SubscribeLogController::class . ':index');
-        $this->post('/subscribe/ajax',          App\Controllers\Admin\SubscribeLogController::class . ':ajax_subscribe_log');
+        $this->get('/subscribe', App\Controllers\Admin\SubscribeLogController::class . ':index');
+        $this->post('/subscribe/ajax', App\Controllers\Admin\SubscribeLogController::class . ':ajax_subscribe_log');
 
         // Detect Ban Mange
-        $this->get('/detect/ban',               App\Controllers\Admin\DetectBanLogController::class . ':index');
-        $this->post('/detect/ban/ajax',         App\Controllers\Admin\DetectBanLogController::class . ':ajax_log');
+        $this->get('/detect/ban', App\Controllers\Admin\DetectBanLogController::class . ':index');
+        $this->post('/detect/ban/ajax', App\Controllers\Admin\DetectBanLogController::class . ':ajax_log');
 
         // 指定用户购买记录以及添加套餐
-        $this->get('/user/{id}/bought',         App\Controllers\Admin\UserLog\BoughtLogController::class . ':bought');
-        $this->post('/user/{id}/bought/ajax',   App\Controllers\Admin\UserLog\BoughtLogController::class . ':bought_ajax');
-        $this->delete('/user/bought',           App\Controllers\Admin\UserLog\BoughtLogController::class . ':bought_delete');
-        $this->post('/user/{id}/bought/buy',    App\Controllers\Admin\UserLog\BoughtLogController::class . ':bought_add');
+        $this->get('/user/{id}/bought', App\Controllers\Admin\UserLog\BoughtLogController::class . ':bought');
+        $this->post('/user/{id}/bought/ajax', App\Controllers\Admin\UserLog\BoughtLogController::class . ':bought_ajax');
+        $this->delete('/user/bought', App\Controllers\Admin\UserLog\BoughtLogController::class . ':bought_delete');
+        $this->post('/user/{id}/bought/buy', App\Controllers\Admin\UserLog\BoughtLogController::class . ':bought_add');
 
         // 指定用户充值记录
-        $this->get('/user/{id}/code',           App\Controllers\Admin\UserLog\CodeLogController::class . ':index');
-        $this->post('/user/{id}/code/ajax',     App\Controllers\Admin\UserLog\CodeLogController::class . ':ajax');
+        $this->get('/user/{id}/code', App\Controllers\Admin\UserLog\CodeLogController::class . ':index');
+        $this->post('/user/{id}/code/ajax', App\Controllers\Admin\UserLog\CodeLogController::class . ':ajax');
 
         // 指定用户订阅记录
-        $this->get('/user/{id}/sublog',         App\Controllers\Admin\UserLog\SubLogController::class . ':index');
-        $this->post('/user/{id}/sublog/ajax',   App\Controllers\Admin\UserLog\SubLogController::class . ':ajax');
+        $this->get('/user/{id}/sublog', App\Controllers\Admin\UserLog\SubLogController::class . ':index');
+        $this->post('/user/{id}/sublog/ajax', App\Controllers\Admin\UserLog\SubLogController::class . ':ajax');
 
         // 指定用户审计记录
-        $this->get('/user/{id}/detect',         App\Controllers\Admin\UserLog\DetectLogController::class . ':index');
-        $this->post('/user/{id}/detect/ajax',   App\Controllers\Admin\UserLog\DetectLogController::class . ':ajax');
+        $this->get('/user/{id}/detect', App\Controllers\Admin\UserLog\DetectLogController::class . ':index');
+        $this->post('/user/{id}/detect/ajax', App\Controllers\Admin\UserLog\DetectLogController::class . ':ajax');
 
         // 指定用户登录记录
-        $this->get('/user/{id}/login',          App\Controllers\Admin\UserLog\LoginLogController::class . ':index');
-        $this->post('/user/{id}/login/ajax',    App\Controllers\Admin\UserLog\LoginLogController::class . ':ajax');
+        $this->get('/user/{id}/login', App\Controllers\Admin\UserLog\LoginLogController::class . ':index');
+        $this->post('/user/{id}/login/ajax', App\Controllers\Admin\UserLog\LoginLogController::class . ':ajax');
 
         // 设置中心
-        $this->get('/setting',                  App\Controllers\Admin\SettingController::class . ':index');
-        $this->post('/setting',                 App\Controllers\Admin\SettingController::class . ':save');
-        $this->post('/setting/email',           App\Controllers\Admin\SettingController::class . ':test');
-        $this->post('/setting/payment',         App\Controllers\Admin\SettingController::class . ':payment');
+        $this->get('/setting', App\Controllers\Admin\SettingController::class . ':index');
+        $this->post('/setting', App\Controllers\Admin\SettingController::class . ':save');
+        $this->post('/setting/email', App\Controllers\Admin\SettingController::class . ':test');
+        $this->post('/setting/payment', App\Controllers\Admin\SettingController::class . ':payment');
 
         // Config Mange
-        $this->group('/config', function () {
-            $this->put('/update/{key}',         App\Controllers\Admin\GConfigController::class . ':update');
-            $this->get('/update/{key}/edit',    App\Controllers\Admin\GConfigController::class . ':edit');
+        $this->group('/config', function (): void {
+            $this->put('/update/{key}', App\Controllers\Admin\GConfigController::class . ':update');
+            $this->get('/update/{key}/edit', App\Controllers\Admin\GConfigController::class . ':edit');
 
-            $this->get('/telegram',             App\Controllers\Admin\GConfigController::class . ':telegram');
-            $this->post('/telegram/ajax',       App\Controllers\Admin\GConfigController::class . ':telegram_ajax');
+            $this->get('/telegram', App\Controllers\Admin\GConfigController::class . ':telegram');
+            $this->post('/telegram/ajax', App\Controllers\Admin\GConfigController::class . ':telegram_ajax');
         });
     })->add(new Admin());
 
-    if ($_ENV['enableAdminApi']){
-        $app->group('/admin/api', function () {
-            $this->get('/nodes',     App\Controllers\Admin\ApiController::class . ':getNodeList');
+    if ($_ENV['enableAdminApi']) {
+        $app->group('/admin/api', function (): void {
+            $this->get('/nodes', App\Controllers\Admin\ApiController::class . ':getNodeList');
             $this->get('/node/{id}', App\Controllers\Admin\ApiController::class . ':getNodeInfo');
-            $this->get('/ping',      App\Controllers\Admin\ApiController::class . ':ping');
+            $this->get('/ping', App\Controllers\Admin\ApiController::class . ':ping');
 
             // Re-bind controller, bypass admin token require
-            $this->post('/node',       App\Controllers\Admin\NodeController::class . ':add');
-            $this->put('/node/{id}',   App\Controllers\Admin\NodeController::class . ':update');
-            $this->delete('/node',     App\Controllers\Admin\NodeController::class . ':delete');
+            $this->post('/node', App\Controllers\Admin\NodeController::class . ':add');
+            $this->put('/node/{id}', App\Controllers\Admin\NodeController::class . ':update');
+            $this->delete('/node', App\Controllers\Admin\NodeController::class . ':delete');
         })->add(new AuthorizationBearer($_ENV['adminApiToken']));
     }
 
     // mu
-    $app->group('/mod_mu', function () {
+    $app->group('/mod_mu', function (): void {
         // 流媒体检测
-        $this->post('/media/saveReport',    App\Controllers\Mod_Mu\NodeController::class . ':saveReport');
+        $this->post('/media/saveReport', App\Controllers\Mod_Mu\NodeController::class . ':saveReport');
         // 其他
-        $this->get('/nodes/{id}/info',      App\Controllers\Mod_Mu\NodeController::class . ':get_info');
-        $this->post('/nodes/{id}/info',     App\Controllers\Mod_Mu\NodeController::class . ':info');
-        $this->get('/nodes',                App\Controllers\Mod_Mu\NodeController::class . ':get_all_info');
-        $this->post('/nodes/config',        App\Controllers\Mod_Mu\NodeController::class . ':getConfig');
-
-        $this->get('/users',                App\Controllers\Mod_Mu\UserController::class . ':index');
-        $this->post('/users/traffic',       App\Controllers\Mod_Mu\UserController::class . ':addTraffic');
-        $this->post('/users/aliveip',       App\Controllers\Mod_Mu\UserController::class . ':addAliveIp');
-        $this->post('/users/detectlog',     App\Controllers\Mod_Mu\UserController::class . ':addDetectLog');
-
-        $this->get('/func/detect_rules',    App\Controllers\Mod_Mu\FuncController::class . ':get_detect_logs');
-        $this->post('/func/block_ip',       App\Controllers\Mod_Mu\FuncController::class . ':addBlockIp');
-        $this->get('/func/block_ip',        App\Controllers\Mod_Mu\FuncController::class . ':get_blockip');
-        $this->get('/func/unblock_ip',      App\Controllers\Mod_Mu\FuncController::class . ':get_unblockip');
-        $this->get('/func/ping',            App\Controllers\Mod_Mu\FuncController::class . ':ping');
+        $this->get('/nodes/{id}/info', App\Controllers\Mod_Mu\NodeController::class . ':get_info');
+        $this->post('/nodes/{id}/info', App\Controllers\Mod_Mu\NodeController::class . ':info');
+        $this->get('/nodes', App\Controllers\Mod_Mu\NodeController::class . ':get_all_info');
+        $this->post('/nodes/config', App\Controllers\Mod_Mu\NodeController::class . ':getConfig');
+
+        $this->get('/users', App\Controllers\Mod_Mu\UserController::class . ':index');
+        $this->post('/users/traffic', App\Controllers\Mod_Mu\UserController::class . ':addTraffic');
+        $this->post('/users/aliveip', App\Controllers\Mod_Mu\UserController::class . ':addAliveIp');
+        $this->post('/users/detectlog', App\Controllers\Mod_Mu\UserController::class . ':addDetectLog');
+
+        $this->get('/func/detect_rules', App\Controllers\Mod_Mu\FuncController::class . ':get_detect_logs');
+        $this->post('/func/block_ip', App\Controllers\Mod_Mu\FuncController::class . ':addBlockIp');
+        $this->get('/func/block_ip', App\Controllers\Mod_Mu\FuncController::class . ':get_blockip');
+        $this->get('/func/unblock_ip', App\Controllers\Mod_Mu\FuncController::class . ':get_unblockip');
+        $this->get('/func/ping', App\Controllers\Mod_Mu\FuncController::class . ':ping');
         //============================================
     })->add(new Mod_Mu());
 
-    $app->group('/link', function () {
-        $this->get('/{token}',              App\Controllers\LinkController::class . ':GetContent');
+    $app->group('/link', function (): void {
+        $this->get('/{token}', App\Controllers\LinkController::class . ':GetContent');
     });
 
     //通用訂閲
-    $app->group('/sub', function () {
-        $this->get('/{token}/{subtype}',    App\Controllers\SubController::class . ':getContent');
+    $app->group('/sub', function (): void {
+        $this->get('/{token}/{subtype}', App\Controllers\SubController::class . ':getContent');
     });
 
-    $app->group('/getClient', function () {
-        $this->get('/{token}',              App\Controllers\UserController::class . ':getClientfromToken');
+    $app->group('/getClient', function (): void {
+        $this->get('/{token}', App\Controllers\UserController::class . ':getClientfromToken');
     });
 };

+ 3 - 0
composer.json

@@ -38,5 +38,8 @@
     "config": {
         "sort-packages": true,
         "optimize-autoloader": true
+    },
+    "require-dev": {
+        "nunomaduro/phpinsights": "^2.2"
     }
 }

+ 5 - 4
db/migrations/20220109130532_create_stream_media_table.php

@@ -1,4 +1,5 @@
 <?php
+
 declare(strict_types=1);
 
 use Phinx\Migration\AbstractMigration;
@@ -19,9 +20,9 @@ final class CreateStreamMediaTable extends AbstractMigration
     public function change(): void
     {
         $table = $this->table('stream_media');
-        $table->addColumn('node_id', 'integer', array('comment' => '节点id'))
-              ->addColumn('result', 'text', array('comment' => '检测结果'))
-              ->addColumn('created_at', 'integer', array('comment' => '创建时间'))
-              ->create();
+        $table->addColumn('node_id', 'integer', ['comment' => '节点id'])
+            ->addColumn('result', 'text', ['comment' => '检测结果'])
+            ->addColumn('created_at', 'integer', ['comment' => '创建时间'])
+            ->create();
     }
 }

+ 6 - 5
phinx.php

@@ -1,12 +1,13 @@
 <?php
 
+declare(strict_types=1);
+
 include './config/.config.php';
 
-return
-[
+return [
     'paths' => [
         'migrations' => '%%PHINX_CONFIG_DIR%%/db/migrations',
-        'seeds' => '%%PHINX_CONFIG_DIR%%/db/seeds'
+        'seeds' => '%%PHINX_CONFIG_DIR%%/db/seeds',
     ],
     'environments' => [
         'default_migration_table' => 'phinxlog',
@@ -37,7 +38,7 @@ return
             'pass' => '',
             'port' => '3306',
             'charset' => 'utf8',
-        ]
+        ],
     ],
-    'version_order' => 'creation'
+    'version_order' => 'creation',
 ];

+ 8 - 0
phpinsights.php

@@ -0,0 +1,8 @@
+<?php
+
+declare(strict_types=1);
+
+return [
+    'preset' => 'default',
+
+];

+ 12 - 10
src/Command/Backup.php

@@ -1,10 +1,12 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Command;
 
+use App\Models\Setting;
 use App\Services\Mail;
 use App\Utils\Telegram;
-use App\Models\Setting;
 use Exception;
 use RuntimeException;
 
@@ -15,13 +17,13 @@ class Backup extends Command
         . '│ ├─ full                    - 整体数据备份' . PHP_EOL
         . '│ ├─ simple                  - 只备份核心数据' . PHP_EOL;
 
-    public function boot()
+    public function boot(): void
     {
         if (count($this->argv) === 2) {
             echo $this->description;
         } else {
             $methodName = $this->argv[2];
-            if ($methodName == 'full') {
+            if ($methodName === 'full') {
                 $this->backup(true);
             } else {
                 $this->backup(false);
@@ -32,13 +34,13 @@ class Backup extends Command
     public function backup($full = false)
     {
         $configs = Setting::getClass('backup');
-        
+
         ini_set('memory_limit', '-1');
         $to = $configs['auto_backup_email'];
-        if ($to == null) {
+        if ($to === null) {
             return false;
         }
-        if (!mkdir('/tmp/ssmodbackup/') && !is_dir('/tmp/ssmodbackup/')) {
+        if (! mkdir('/tmp/ssmodbackup/') && ! is_dir('/tmp/ssmodbackup/')) {
             throw new RuntimeException(sprintf('Directory "%s" was not created', '/tmp/ssmodbackup/'));
         }
         $db_address_array = explode(':', $_ENV['db_host']);
@@ -57,15 +59,15 @@ class Backup extends Command
 
         system('cp ' . BASE_PATH . '/config/.config.php /tmp/ssmodbackup/configbak.php', $ret);
         echo $ret;
-        $backup_passwd = $configs["auto_backup_password"] == "" ? "" : " -P " . $configs["auto_backup_password"];
+        $backup_passwd = $configs['auto_backup_password'] === '' ? '' : ' -P ' . $configs['auto_backup_password'];
         system('zip -r /tmp/ssmodbackup.zip /tmp/ssmodbackup/* ' . $backup_passwd, $ret);
         $subject = $_ENV['appName'] . '-备份成功';
         $text = '您好,系统已经为您自动备份,请查看附件,用您设定的密码解压。';
         try {
             Mail::send($to, $subject, 'news/backup.tpl', [
-                'text' => $text
+                'text' => $text,
             ], [
-                '/tmp/ssmodbackup.zip'
+                '/tmp/ssmodbackup.zip',
             ]);
         } catch (Exception $e) {
             echo $e->getMessage();
@@ -73,7 +75,7 @@ class Backup extends Command
         system('rm -rf /tmp/ssmodbackup', $ret);
         system('rm /tmp/ssmodbackup.zip', $ret);
 
-        if ($configs['auto_backup_notify'] == true) {
+        if ($configs['auto_backup_notify'] === true) {
             Telegram::Send('备份工作已经完成');
         }
     }

+ 107 - 129
src/Command/ClientDownload.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Command;
 
 use Exception;
@@ -11,19 +13,19 @@ use Exception;
  */
 class ClientDownload extends Command
 {
-    public $description   = '├─=: php xcat ClientDownload - 定时更新客户端' . PHP_EOL;
+    public $description = '├─=: php xcat ClientDownload - 定时更新客户端' . PHP_EOL;
 
     private $client;
 
     /**
      * 保存基本路径
      */
-    private $basePath     = BASE_PATH . '/';
+    private $basePath = BASE_PATH . '/';
 
     /**
      * 下载配置
      */
-    private $softs        = [
+    private $softs = [
         // [
         //     'name'      => '示例名称备注',
         //     'tagMethod' => 'github_release | github_pre_release | apkpure',
@@ -38,206 +40,206 @@ class ClientDownload extends Command
         //     ],
         // ],
         [
-            'name'      => 'ShadowsocksR-Windows',
+            'name' => 'ShadowsocksR-Windows',
             'tagMethod' => 'github_release',
-            'gitRepo'   => 'HMBSbige/ShadowsocksR-Windows',
-            'savePath'  => 'public/clients/',
+            'gitRepo' => 'HMBSbige/ShadowsocksR-Windows',
+            'savePath' => 'public/clients/',
             'downloads' => [
                 [
                     'sourceName' => 'ShadowsocksR-%tagName%.7z',
-                    'saveName'   => 'ssr-win.7z',
-                    'apkpureUrl' => ''
-                ]
+                    'saveName' => 'ssr-win.7z',
+                    'apkpureUrl' => '',
+                ],
             ],
         ],
         [
-            'name'      => 'Netch',
+            'name' => 'Netch',
             'tagMethod' => 'github_release',
-            'gitRepo'   => 'netchx/Netch',
-            'savePath'  => 'public/clients/',
+            'gitRepo' => 'netchx/Netch',
+            'savePath' => 'public/clients/',
             'downloads' => [
                 [
                     'sourceName' => 'Netch.7z',
-                    'saveName'   => 'Netch.7z',
-                    'apkpureUrl' => ''
-                ]
+                    'saveName' => 'Netch.7z',
+                    'apkpureUrl' => '',
+                ],
             ],
         ],
         [
-            'name'      => 'ClashforWindows',
+            'name' => 'ClashforWindows',
             'tagMethod' => 'github_release',
-            'gitRepo'   => 'Fndroid/clash_for_windows_pkg',
-            'savePath'  => 'public/clients/',
+            'gitRepo' => 'Fndroid/clash_for_windows_pkg',
+            'savePath' => 'public/clients/',
             'downloads' => [
                 [
                     'sourceName' => 'Clash.for.Windows.Setup.%tagName%.exe',
-                    'saveName'   => 'Clash-Windows.exe',
-                    'apkpureUrl' => ''
+                    'saveName' => 'Clash-Windows.exe',
+                    'apkpureUrl' => '',
                 ],
                 [
                     'sourceName' => 'Clash.for.Windows-%tagName%.dmg',
-                    'saveName'   => 'Clash-Windows.dmg',
-                    'apkpureUrl' => ''
+                    'saveName' => 'Clash-Windows.dmg',
+                    'apkpureUrl' => '',
                 ],
                 [
                     'sourceName' => 'Clash.for.Windows-%tagName%-arm64.dmg',
-                    'saveName'   => 'Clash-Windows-arm64.dmg',
-                    'apkpureUrl' => ''
-                ]
+                    'saveName' => 'Clash-Windows-arm64.dmg',
+                    'apkpureUrl' => '',
+                ],
             ],
         ],
         [
-            'name'      => 'ClashX',
+            'name' => 'ClashX',
             'tagMethod' => 'github_release',
-            'gitRepo'   => 'yichengchen/clashX',
-            'savePath'  => 'public/clients/',
+            'gitRepo' => 'yichengchen/clashX',
+            'savePath' => 'public/clients/',
             'downloads' => [
                 [
                     'sourceName' => 'ClashX.dmg',
-                    'saveName'   => 'ClashX.dmg',
-                    'apkpureUrl' => ''
+                    'saveName' => 'ClashX.dmg',
+                    'apkpureUrl' => '',
                 ],
             ],
         ],
         [
-            'name'      => 'V2RayU',
+            'name' => 'V2RayU',
             'tagMethod' => 'github_release',
-            'gitRepo'   => 'yanue/V2rayU',
-            'savePath'  => 'public/clients/',
+            'gitRepo' => 'yanue/V2rayU',
+            'savePath' => 'public/clients/',
             'downloads' => [
                 [
                     'sourceName' => 'V2rayU.dmg',
-                    'saveName'   => 'V2rayU.dmg',
-                    'apkpureUrl' => ''
+                    'saveName' => 'V2rayU.dmg',
+                    'apkpureUrl' => '',
                 ],
             ],
         ],
         [
-            'name'      => 'ShadowsocksXNG',
+            'name' => 'ShadowsocksXNG',
             'tagMethod' => 'github_release',
-            'gitRepo'   => 'shadowsocks/ShadowsocksX-NG',
-            'savePath'  => 'public/clients/',
+            'gitRepo' => 'shadowsocks/ShadowsocksX-NG',
+            'savePath' => 'public/clients/',
             'downloads' => [
                 [
                     'sourceName' => 'ShadowsocksX-NG.%tagName1%.zip',
-                    'saveName'   => 'ss-mac.zip',
-                    'apkpureUrl' => ''
+                    'saveName' => 'ss-mac.zip',
+                    'apkpureUrl' => '',
                 ],
             ],
         ],
         [
-            'name'      => 'ShadowsocksXNGR',
+            'name' => 'ShadowsocksXNGR',
             'tagMethod' => 'github_pre_release',
-            'gitRepo'   => 'qinyuhang/ShadowsocksX-NG-R',
-            'savePath'  => 'public/clients/',
+            'gitRepo' => 'qinyuhang/ShadowsocksX-NG-R',
+            'savePath' => 'public/clients/',
             'downloads' => [
                 [
                     'sourceName' => 'ShadowsocksX-NG-R8.dmg',
-                    'saveName'   => 'ssr-mac.dmg',
-                    'apkpureUrl' => ''
+                    'saveName' => 'ssr-mac.dmg',
+                    'apkpureUrl' => '',
                 ],
             ],
         ],
         [
-            'name'      => 'V2RayNG',
+            'name' => 'V2RayNG',
             'tagMethod' => 'github_release',
-            'gitRepo'   => '2dust/v2rayNG',
-            'savePath'  => 'public/clients/',
+            'gitRepo' => '2dust/v2rayNG',
+            'savePath' => 'public/clients/',
             'downloads' => [
                 [
                     'sourceName' => 'v2rayNG_%tagName%_arm64-v8a.apk',
-                    'saveName'   => 'v2rayng.apk',
-                    'apkpureUrl' => ''
+                    'saveName' => 'v2rayng.apk',
+                    'apkpureUrl' => '',
                 ],
                 [
                     'sourceName' => 'v2rayNG_%tagName%_armeabi-v7a.apk',
-                    'saveName'   => 'v2rayng_armeabi-v7a.apk',
-                    'apkpureUrl' => ''
+                    'saveName' => 'v2rayng_armeabi-v7a.apk',
+                    'apkpureUrl' => '',
                 ],
                 [
                     'sourceName' => 'v2rayNG_%tagName%_x86.apk',
-                    'saveName'   => 'v2rayng_x86.apk',
-                    'apkpureUrl' => ''
+                    'saveName' => 'v2rayng_x86.apk',
+                    'apkpureUrl' => '',
                 ],
                 [
                     'sourceName' => 'v2rayNG_%tagName%_x86_64.apk',
-                    'saveName'   => 'v2rayng_x86_64.apk',
-                    'apkpureUrl' => ''
+                    'saveName' => 'v2rayng_x86_64.apk',
+                    'apkpureUrl' => '',
                 ],
             ],
         ],
         [
-            'name'      => 'Qv2ray',
+            'name' => 'Qv2ray',
             'tagMethod' => 'github_release',
-            'gitRepo'   => 'Qv2ray/Qv2ray',
-            'savePath'  => 'public/clients/',
+            'gitRepo' => 'Qv2ray/Qv2ray',
+            'savePath' => 'public/clients/',
             'downloads' => [
                 [
                     'sourceName' => 'Qv2ray-%tagName%-Windows.7z',
-                    'saveName'   => 'Qv2ray.7z',
-                    'apkpureUrl' => ''
+                    'saveName' => 'Qv2ray.7z',
+                    'apkpureUrl' => '',
                 ],
                 [
                     'sourceName' => 'Qv2ray-%tagName%-macOS-x64.dmg',
-                    'saveName'   => 'Qv2ray.dmg',
-                    'apkpureUrl' => ''
+                    'saveName' => 'Qv2ray.dmg',
+                    'apkpureUrl' => '',
                 ],
                 [
                     'sourceName' => 'Qv2ray-%tagName%-linux-x64.AppImage',
-                    'saveName'   => 'Qv2ray.AppImage',
-                    'apkpureUrl' => ''
+                    'saveName' => 'Qv2ray.AppImage',
+                    'apkpureUrl' => '',
                 ],
             ],
         ],
         [
-            'name'      => 'ClashforAndroid',
+            'name' => 'ClashforAndroid',
             'tagMethod' => 'github_pre_release',
-            'gitRepo'   => 'Kr328/ClashForAndroid',
-            'savePath'  => 'public/clients/',
+            'gitRepo' => 'Kr328/ClashForAndroid',
+            'savePath' => 'public/clients/',
             'downloads' => [
                 [
                     'sourceName' => 'cfa-%tagName1%-premium-universal-release.apk',
-                    'saveName'   => 'Clash-Android.apk',
-                    'apkpureUrl' => ''
+                    'saveName' => 'Clash-Android.apk',
+                    'apkpureUrl' => '',
                 ],
             ],
         ],
         [
-            'name'      => 'ShadowsocksAndroid',
+            'name' => 'ShadowsocksAndroid',
             'tagMethod' => 'github_release',
-            'gitRepo'   => 'shadowsocks/shadowsocks-android',
-            'savePath'  => 'public/clients/',
+            'gitRepo' => 'shadowsocks/shadowsocks-android',
+            'savePath' => 'public/clients/',
             'downloads' => [
                 [
                     'sourceName' => 'shadowsocks--universal-%tagName%.apk',
-                    'saveName'   => 'ss-android.apk',
-                    'apkpureUrl' => ''
+                    'saveName' => 'ss-android.apk',
+                    'apkpureUrl' => '',
                 ],
             ],
         ],
         [
-            'name'      => 'ShadowsocksR-Android',
+            'name' => 'ShadowsocksR-Android',
             'tagMethod' => 'github_release',
-            'gitRepo'   => 'HMBSbige/ShadowsocksR-Android',
-            'savePath'  => 'public/clients/',
+            'gitRepo' => 'HMBSbige/ShadowsocksR-Android',
+            'savePath' => 'public/clients/',
             'downloads' => [
                 [
                     'sourceName' => 'shadowsocksr-android-%tagName%.apk',
-                    'saveName'   => 'ssr-android.apk',
-                    'apkpureUrl' => ''
+                    'saveName' => 'ssr-android.apk',
+                    'apkpureUrl' => '',
                 ],
             ],
         ],
         [
-            'name'      => 'ElectronSSR',
+            'name' => 'ElectronSSR',
             'tagMethod' => 'github_pre_release',
-            'gitRepo'   => 'shadowsocksrr/electron-ssr',
-            'savePath'  => 'public/clients/',
+            'gitRepo' => 'shadowsocksrr/electron-ssr',
+            'savePath' => 'public/clients/',
             'downloads' => [
                 [
                     'sourceName' => 'electron-ssr-%tagName%.AppImage',
-                    'saveName'   => 'Electron-SSR.AppImage',
-                    'apkpureUrl' => ''
+                    'saveName' => 'Electron-SSR.AppImage',
+                    'apkpureUrl' => '',
                 ],
             ],
         ],
@@ -245,9 +247,9 @@ class ClientDownload extends Command
 
     private $version;
 
-    public function boot()
+    public function boot(): void
     {
-        $this->client  = new \GuzzleHttp\Client();
+        $this->client = new \GuzzleHttp\Client();
         $this->version = $this->getLocalVersions();
         foreach ($this->softs as $soft) {
             $this->getSoft($soft);
@@ -256,22 +258,16 @@ class ClientDownload extends Command
 
     /**
      * 下载远程文件
-     *
-     * @param string $fileName
-     * @param string $savePath
-     * @param string $url
-     *
-     * @return bool
      */
     private function getSourceFile(string $fileName, string $savePath, string $url): bool
     {
         try {
-            if (!file_exists($savePath)) {
+            if (! file_exists($savePath)) {
                 echo '目标文件夹 ' . $savePath . ' 不存在,创建中...' . PHP_EOL;
                 system('mkdir ' . $savePath);
             }
             echo '- 开始下载 ' . $fileName . '...' . PHP_EOL;
-            $request  = $this->client->get($url);
+            $request = $this->client->get($url);
             echo '- 下载 ' . $fileName . ' 成功,正在保存...' . PHP_EOL;
             $result = file_put_contents($savePath . $fileName, $request->getBody()->getContents());
             if ($result === false) {
@@ -290,14 +286,10 @@ class ClientDownload extends Command
 
     /**
      * 获取 GitHub 常规 Release
-     *
-     * @param string $repo
-     *
-     * @return string
      */
     private function getLatestReleaseTagName(string $repo): string
     {
-        $url     = 'https://api.github.com/repos/' . $repo . '/releases/latest' . ($_ENV['github_access_token'] != '' ? '?access_token=' . $_ENV['github_access_token'] : '');
+        $url = 'https://api.github.com/repos/' . $repo . '/releases/latest' . ($_ENV['github_access_token'] !== '' ? '?access_token=' . $_ENV['github_access_token'] : '');
         $request = $this->client->get($url);
         return (string) json_decode(
             $request->getBody()->getContents(),
@@ -307,16 +299,12 @@ class ClientDownload extends Command
 
     /**
      * 获取 GitHub Pre-Release
-     *
-     * @param string $repo
-     *
-     * @return string
      */
     private function getLatestPreReleaseTagName(string $repo): string
     {
-        $url     = 'https://api.github.com/repos/' . $repo . '/releases' . ($_ENV['github_access_token'] != '' ? '?access_token=' . $_ENV['github_access_token'] : '');
+        $url = 'https://api.github.com/repos/' . $repo . '/releases' . ($_ENV['github_access_token'] !== '' ? '?access_token=' . $_ENV['github_access_token'] : '');
         $request = $this->client->get($url);
-        $latest  = json_decode(
+        $latest = json_decode(
             $request->getBody()->getContents(),
             true
         )[0];
@@ -325,10 +313,6 @@ class ClientDownload extends Command
 
     /**
      * 获取 Apkpure TagName
-     *
-     * @param string $url
-     *
-     * @return string
      */
     private function getApkpureTagName(string $url): string
     {
@@ -340,14 +324,10 @@ class ClientDownload extends Command
 
     /**
      * 判断是否 JSON
-     *
-     * @param string $string
-     *
-     * @return bool
      */
     private function is_json(string $string): bool
     {
-        return (json_decode($string, true) !== false);
+        return json_decode($string, true) !== false;
     }
 
     /**
@@ -359,13 +339,13 @@ class ClientDownload extends Command
     {
         $fileName = 'ClientDownloadVersion.json';
         $filePath = BASE_PATH . '/config/' . $fileName;
-        if (!is_file($filePath)) {
+        if (! is_file($filePath)) {
             echo '本地软体版本库 ClientDownloadVersion.json 不存在,创建文件中...' . PHP_EOL;
             $result = file_put_contents(
                 $filePath,
                 json_encode(
                     [
-                        'createTime' => time()
+                        'createTime' => time(),
                     ]
                 )
             );
@@ -375,7 +355,7 @@ class ClientDownload extends Command
             }
         }
         $fileContent = file_get_contents($filePath);
-        if (!$this->is_json($fileContent)) {
+        if (! $this->is_json($fileContent)) {
             echo 'ClientDownloadVersion.json 文件格式异常,脚本中止.' . PHP_EOL;
             exit(0);
         }
@@ -384,8 +364,6 @@ class ClientDownload extends Command
 
     /**
      * 储存本地软体版本库
-     *
-     * @return bool
      */
     private function setLocalVersions(array $versions): bool
     {
@@ -399,7 +377,7 @@ class ClientDownload extends Command
         );
     }
 
-    private function getSoft(array $task)
+    private function getSoft(array $task): void
     {
         $savePath = $this->basePath . $task['savePath'];
         echo '====== ' . $task['name'] . ' 开始 ======' . PHP_EOL;
@@ -415,10 +393,10 @@ class ClientDownload extends Command
                 break;
         }
         $tagName = $this->$tagMethod($task['gitRepo']);
-        if (!isset($this->version[$task['name']])) {
+        if (! isset($this->version[$task['name']])) {
             echo '- 本地不存在 ' . $task['name'] . ',检测到当前最新版本为 ' . $tagName . PHP_EOL;
         } else {
-            if ($tagName == $this->version[$task['name']]) {
+            if ($tagName === $this->version[$task['name']]) {
                 echo '- 检测到当前 ' . $task['name'] . ' 最新版本与本地版本一致,跳过此任务.' . PHP_EOL;
                 echo '====== ' . $task['name'] . ' 结束 ======' . PHP_EOL;
                 return;
@@ -431,28 +409,28 @@ class ClientDownload extends Command
                 [
                     '%taskName%',
                     '%tagName%',
-                    '%tagName1%'
+                    '%tagName1%',
                 ],
                 [
                     $task['name'],
                     $tagName,
-                    substr($tagName, 1)
+                    substr($tagName, 1),
                 ],
                 $name
             );
         };
         foreach ($task['downloads'] as $download) {
-            $fileName   = $nameFunction(($download['saveName'] != '' ? $download['saveName'] : $download['sourceName']));
+            $fileName = $nameFunction(($download['saveName'] !== '' ? $download['saveName'] : $download['sourceName']));
             $sourceName = $nameFunction($download['sourceName']);
-            $filePath   = $savePath . $fileName;
+            $filePath = $savePath . $fileName;
             if (is_file($filePath)) {
                 echo '- 正在删除旧版本文件...' . PHP_EOL;
-                if (!unlink($filePath)) {
+                if (! unlink($filePath)) {
                     echo '- 删除旧版本文件失败,此任务跳过,请检查权限等...' . PHP_EOL;
                     continue;
                 }
             }
-            if ($task['tagMethod'] == 'apkpure') {
+            if ($task['tagMethod'] === 'apkpure') {
                 $request = $this->client->get($download['apkpureUrl']);
                 preg_match('#(?<=href=")https:\/\/download\.apkpure\.com\/b\/APK[^"]+#', $request->getBody()->getContents(), $downloadUrl);
                 $downloadUrl = $downloadUrl[0];

+ 3 - 1
src/Command/Command.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Command;
 
 /**
@@ -16,5 +18,5 @@ abstract class Command
         $this->argv = $argv;
     }
 
-    abstract public function boot();
+    abstract public function boot(): void;
 }

+ 42 - 43
src/Command/DetectBan.php

@@ -1,12 +1,12 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Command;
 
-use App\Models\{
-    User,
-    DetectLog,
-    DetectBanLog
-};
+use App\Models\DetectBanLog;
+use App\Models\DetectLog;
+use App\Models\User;
 
 class DetectBan extends Command
 {
@@ -15,19 +15,18 @@ class DetectBan extends Command
     /**
      * 审计封禁任务
      */
-    public function boot()
+    public function boot(): void
     {
         if ($_ENV['enable_auto_detect_ban'] === false) {
             return;
         }
         echo '审计封禁检查开始.' . PHP_EOL;
         $new_logs = DetectLog::where('status', '=', 0)->orderBy('id', 'asc')->take($_ENV['auto_detect_ban_numProcess'])->get();
-        if (count($new_logs) != 0) {
-
+        if (count($new_logs) !== 0) {
             $user_logs = [];
             foreach ($new_logs as $log) {
                 // 分类各个用户的记录数量
-                if (!in_array($log->user_id, array_keys($user_logs))) {
+                if (! in_array($log->user_id, array_keys($user_logs))) {
                     $user_logs[$log->user_id] = 0;
                 }
                 $user_logs[$log->user_id]++;
@@ -38,13 +37,13 @@ class DetectBan extends Command
             foreach ($user_logs as $userid => $value) {
                 // 执行封禁
                 $user = User::find($userid);
-                if ($user == null) {
+                if ($user === null) {
                     continue;
                 }
                 $user->all_detect_number += $value;
                 $user->save();
 
-                if ($user->enable == 0 || ($user->is_admin && $_ENV['auto_detect_ban_allow_admin'] === true) || in_array($user->id, $_ENV['auto_detect_ban_allow_users'])) {
+                if ($user->enable === 0 || ($user->is_admin && $_ENV['auto_detect_ban_allow_admin'] === true) || in_array($user->id, $_ENV['auto_detect_ban_allow_users'])) {
                     // 如果用户已被封禁
                     // 如果用户是管理员
                     // 如果属于钦定用户
@@ -52,25 +51,25 @@ class DetectBan extends Command
                     continue;
                 }
 
-                if ($_ENV['auto_detect_ban_type'] == 1) {
-                    $last_DetectBanLog      = DetectBanLog::where('user_id', $userid)->orderBy('id', 'desc')->first();
-                    $last_all_detect_number = ($last_DetectBanLog == null ? 0 : (int) $last_DetectBanLog->all_detect_number);
-                    $detect_number          = ($user->all_detect_number - $last_all_detect_number);
+                if ($_ENV['auto_detect_ban_type'] === 1) {
+                    $last_DetectBanLog = DetectBanLog::where('user_id', $userid)->orderBy('id', 'desc')->first();
+                    $last_all_detect_number = ($last_DetectBanLog === null ? 0 : (int) $last_DetectBanLog->all_detect_number);
+                    $detect_number = $user->all_detect_number - $last_all_detect_number;
                     if ($detect_number >= $_ENV['auto_detect_ban_number']) {
-                        $last_detect_ban_time               = $user->last_detect_ban_time;
-                        $end_time                           = date('Y-m-d H:i:s');
-                        $user->enable                       = 0;
-                        $user->last_detect_ban_time         = $end_time;
+                        $last_detect_ban_time = $user->last_detect_ban_time;
+                        $end_time = date('Y-m-d H:i:s');
+                        $user->enable = 0;
+                        $user->last_detect_ban_time = $end_time;
                         $user->save();
-                        $DetectBanLog                       = new DetectBanLog();
-                        $DetectBanLog->user_name            = $user->user_name;
-                        $DetectBanLog->user_id              = $user->id;
-                        $DetectBanLog->email                = $user->email;
-                        $DetectBanLog->detect_number        = $detect_number;
-                        $DetectBanLog->ban_time             = $_ENV['auto_detect_ban_time'];
-                        $DetectBanLog->start_time           = strtotime($last_detect_ban_time);
-                        $DetectBanLog->end_time             = strtotime($end_time);
-                        $DetectBanLog->all_detect_number    = $user->all_detect_number;
+                        $DetectBanLog = new DetectBanLog();
+                        $DetectBanLog->user_name = $user->user_name;
+                        $DetectBanLog->user_id = $user->id;
+                        $DetectBanLog->email = $user->email;
+                        $DetectBanLog->detect_number = $detect_number;
+                        $DetectBanLog->ban_time = $_ENV['auto_detect_ban_time'];
+                        $DetectBanLog->start_time = strtotime($last_detect_ban_time);
+                        $DetectBanLog->end_time = strtotime($end_time);
+                        $DetectBanLog->all_detect_number = $user->all_detect_number;
                         $DetectBanLog->save();
                     }
                 } else {
@@ -83,24 +82,24 @@ class DetectBan extends Command
                             }
                         }
                     }
-                    if ($tmp != 0) {
-                        if ($_ENV['auto_detect_ban'][$tmp]['type'] == 'kill') {
+                    if ($tmp !== 0) {
+                        if ($_ENV['auto_detect_ban'][$tmp]['type'] === 'kill') {
                             $user->kill_user();
                         } else {
-                            $last_detect_ban_time               = $user->last_detect_ban_time;
-                            $end_time                           = date('Y-m-d H:i:s');
-                            $user->enable                       = 0;
-                            $user->last_detect_ban_time         = $end_time;
+                            $last_detect_ban_time = $user->last_detect_ban_time;
+                            $end_time = date('Y-m-d H:i:s');
+                            $user->enable = 0;
+                            $user->last_detect_ban_time = $end_time;
                             $user->save();
-                            $DetectBanLog                       = new DetectBanLog();
-                            $DetectBanLog->user_name            = $user->user_name;
-                            $DetectBanLog->user_id              = $user->id;
-                            $DetectBanLog->email                = $user->email;
-                            $DetectBanLog->detect_number        = $number;
-                            $DetectBanLog->ban_time             = $_ENV['auto_detect_ban'][$tmp]['time'];
-                            $DetectBanLog->start_time           = strtotime('1989-06-04 00:05:00');
-                            $DetectBanLog->end_time             = strtotime($end_time);
-                            $DetectBanLog->all_detect_number    = $number;
+                            $DetectBanLog = new DetectBanLog();
+                            $DetectBanLog->user_name = $user->user_name;
+                            $DetectBanLog->user_id = $user->id;
+                            $DetectBanLog->email = $user->email;
+                            $DetectBanLog->detect_number = $number;
+                            $DetectBanLog->ban_time = $_ENV['auto_detect_ban'][$tmp]['time'];
+                            $DetectBanLog->start_time = strtotime('1989-06-04 00:05:00');
+                            $DetectBanLog->end_time = strtotime($end_time);
+                            $DetectBanLog->all_detect_number = $number;
                             $DetectBanLog->save();
                         }
                     }

+ 17 - 18
src/Command/DetectGFW.php

@@ -1,19 +1,18 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Command;
 
-use App\Models\{
-    Node,
-    User
-};
 use App\Services\Config;
 use App\Utils\Telegram;
+use Node;
 
 class DetectGFW extends Command
 {
     public $description = '├─=: php xcat DetectGFW      - 节点被墙检测定时任务' . PHP_EOL;
 
-    public function boot()
+    public function boot(): void
     {
         //节点被墙检测
         $last_time = file_get_contents(BASE_PATH . '/storage/last_detect_gfw_time');
@@ -26,16 +25,16 @@ class DetectGFW extends Command
                 $adminUser = User::where('is_admin', '=', '1')->get();
                 foreach ($nodes as $node) {
                     if (
-                        $node->node_ip == '' ||
-                        $node->node_ip == null ||
-                        $node->online == false
+                        $node->node_ip === '' ||
+                        $node->node_ip === null ||
+                        $node->online === false
                     ) {
                         continue;
                     }
                     $api_url = $_ENV['detect_gfw_url'];
                     $api_url = str_replace(
-                        array('{ip}', '{port}'),
-                        array($node->node_ip, $_ENV['detect_gfw_port']),
+                        ['{ip}', '{port}'],
+                        [$node->node_ip, $_ENV['detect_gfw_port']],
                         $api_url
                     );
                     //因为考虑到有v2ray之类的节点,所以不得不使用ip作为参数
@@ -48,11 +47,11 @@ class DetectGFW extends Command
                             break;
                         }
                     }
-                    if ($result_tcping == false) {
+                    if ($result_tcping === false) {
                         //被墙了
-                        echo ($node->id . ':false' . PHP_EOL);
+                        echo $node->id . ':false' . PHP_EOL;
                         //判断有没有发送过邮件
-                        if ($node->gfw_block == true) {
+                        if ($node->gfw_block === true) {
                             continue;
                         }
                         foreach ($adminUser as $user) {
@@ -61,7 +60,7 @@ class DetectGFW extends Command
                                 $_ENV['appName'] . '-系统警告',
                                 'news/warn.tpl',
                                 [
-                                    'text' => '管理员您好,系统发现节点 ' . $node->name . ' 被墙了,请您及时处理。'
+                                    'text' => '管理员您好,系统发现节点 ' . $node->name . ' 被墙了,请您及时处理。',
                                 ],
                                 []
                             );
@@ -78,8 +77,8 @@ class DetectGFW extends Command
                         $node->save();
                     } else {
                         //没有被墙
-                        echo ($node->id . ':true' . PHP_EOL);
-                        if ($node->gfw_block == false) {
+                        echo $node->id . ':true' . PHP_EOL;
+                        if ($node->gfw_block === false) {
                             continue;
                         }
                         foreach ($adminUser as $user) {
@@ -88,7 +87,7 @@ class DetectGFW extends Command
                                 $_ENV['appName'] . '-系统提示',
                                 'news/warn.tpl',
                                 [
-                                    'text' => '管理员您好,系统发现节点 ' . $node->name . ' 溜出墙了。'
+                                    'text' => '管理员您好,系统发现节点 ' . $node->name . ' 溜出墙了。',
                                 ],
                                 []
                             );
@@ -108,7 +107,7 @@ class DetectGFW extends Command
                 break;
             }
 
-            echo ($node->id . 'interval skip' . PHP_EOL);
+            echo $node->id . 'interval skip' . PHP_EOL;
             sleep(3);
         }
     }

+ 10 - 8
src/Command/FinanceMail.php

@@ -1,10 +1,12 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Command;
 
 use App\Models\User;
-use App\Utils\Telegram;
 use App\Utils\DatatablesHelper;
+use App\Utils\Telegram;
 use Ozdemir\Datatables\Datatables;
 
 class FinanceMail extends Command
@@ -15,7 +17,7 @@ class FinanceMail extends Command
         . '│ ├─ week                    - 周报' . PHP_EOL
         . '│ ├─ month                   - 月报' . PHP_EOL;
 
-    public function boot()
+    public function boot(): void
     {
         if (count($this->argv) === 2) {
             echo $this->description;
@@ -29,7 +31,7 @@ class FinanceMail extends Command
         }
     }
 
-    public function day()
+    public function day(): void
     {
         $datatables = new Datatables(new DatatablesHelper());
         $datatables->query(
@@ -65,7 +67,7 @@ class FinanceMail extends Command
                 'news/finance.tpl',
                 [
                     'title' => '财务日报',
-                    'text'  => $text_html
+                    'text' => $text_html,
                 ],
                 []
             );
@@ -81,7 +83,7 @@ class FinanceMail extends Command
         }
     }
 
-    public function week()
+    public function week(): void
     {
         $datatables = new Datatables(new DatatablesHelper());
         $datatables->query(
@@ -110,7 +112,7 @@ class FinanceMail extends Command
                 'news/finance.tpl',
                 [
                     'title' => '财务周报',
-                    'text'  => $text_html
+                    'text' => $text_html,
                 ],
                 []
             );
@@ -126,7 +128,7 @@ class FinanceMail extends Command
         }
     }
 
-    public function month()
+    public function month(): void
     {
         $datatables = new Datatables(new DatatablesHelper());
         $datatables->query(
@@ -153,7 +155,7 @@ class FinanceMail extends Command
                 'news/finance.tpl',
                 [
                     'title' => '财务月报',
-                    'text'  => $text_html
+                    'text' => $text_html,
                 ],
                 []
             );

+ 75 - 82
src/Command/Job.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Command;
 
 use App\Models\BlockIp;
@@ -35,7 +37,7 @@ class Job extends Command
         . '│ ├─ CheckJob                - 检查任务,每分钟' . PHP_EOL
         . '│ ├─ UserJob                 - 用户账户相关任务,每小时' . PHP_EOL;
 
-    public function boot()
+    public function boot(): void
     {
         if (count($this->argv) === 2) {
             echo $this->description;
@@ -57,7 +59,7 @@ class Job extends Command
     public function SendMail()
     {
         if (file_exists(BASE_PATH . '/storage/email_queue')) {
-            echo "程序正在运行中" . PHP_EOL;
+            echo '程序正在运行中' . PHP_EOL;
             return false;
         }
         $myfile = fopen(BASE_PATH . '/storage/email_queue', 'wb+') or die('Unable to open file!');
@@ -65,7 +67,7 @@ class Job extends Command
         fwrite($myfile, $txt);
         fclose($myfile);
         // 分块处理,节省内存
-        EmailQueue::chunkById(1000, function ($email_queues) {
+        EmailQueue::chunkById(1000, function ($email_queues): void {
             foreach ($email_queues as $email_queue) {
                 try {
                     Mail::send($email_queue->to_email, $email_queue->subject, $email_queue->template, json_decode($email_queue->array), []);
@@ -81,10 +83,8 @@ class Job extends Command
 
     /**
      * 每日任务
-     *
-     * @return void
      */
-    public function DailyJob()
+    public function DailyJob(): void
     {
         ini_set('memory_limit', '-1');
 
@@ -92,7 +92,7 @@ class Job extends Command
         Node::where('bandwidthlimit_resetday', date('d'))->update(['node_bandwidth' => 0]);
 
         // ------- 清理各表记录
-        UserSubscribeLog::where('request_time', '<', date('Y-m-d H:i:s', time() - 86400 * (int)$_ENV['subscribeLog_keep_days']))->delete();
+        UserSubscribeLog::where('request_time', '<', date('Y-m-d H:i:s', time() - 86400 * (int) $_ENV['subscribeLog_keep_days']))->delete();
         Token::where('expire_time', '<', time())->delete();
         NodeInfoLog::where('log_time', '<', time() - 86400 * 3)->delete();
         NodeOnlineLog::where('log_time', '<', time() - 86400 * 3)->delete();
@@ -105,7 +105,6 @@ class Job extends Command
         TelegramSession::where('datetime', '<', time() - 900)->delete();
         // ------- 清理各表记录
 
-
         // ------- 重置自增 ID
         $db = new DatatablesHelper();
         Tools::reset_auto_increment($db, 'node_online_log');
@@ -114,24 +113,24 @@ class Job extends Command
 
         // ------- 用户流量重置
         // 取消已下架的商品不支持重置的限制,因为目前没有库存限制
-        $shopid  = Shop::where('content->reset', '<>', 0)->where('content->reset_value', '<>', 0)->where('content->reset_exp', '<>', 0)->pluck('id')->toArray();
+        $shopid = Shop::where('content->reset', '<>', 0)->where('content->reset_value', '<>', 0)->where('content->reset_exp', '<>', 0)->pluck('id')->toArray();
         // 用 UserID 分组倒序取最新一条包含周期重置商品的购买记录
         $boughts = Bought::whereIn('shopid', $shopid)->orderBy('id', 'desc')->groupBy('userid')->get();
-        $bought_users = array();
+        $bought_users = [];
         foreach ($boughts as $bought) {
             /** @var Bought $bought */
             $user = $bought->user();
-            if ($user == null) {
+            if ($user === null) {
                 continue;
             }
             $shop = $bought->shop();
-            if ($shop == null) {
+            if ($shop === null) {
                 $bought->delete();
                 continue;
             }
             $bought_users[] = $bought->userid;
-            if ($bought->valid() && $bought->used_days() % $shop->reset() == 0 && $bought->used_days() != 0) {
-                echo ('流量重置-' . $user->id . "\n");
+            if ($bought->valid() && $bought->used_days() % $shop->reset() === 0 && $bought->used_days() !== 0) {
+                echo '流量重置-' . $user->id . "\n";
                 $user->transfer_enable = Tools::toGB($shop->reset_value());
                 $user->u = 0;
                 $user->d = 0;
@@ -141,7 +140,7 @@ class Job extends Command
                     $_ENV['appName'] . '-您的流量被重置了',
                     'news/warn.tpl',
                     [
-                        'text' => '您好,根据您所订购的订单 ID:' . $bought->id . ',流量已经被重置为' . $shop->reset_value() . 'GB'
+                        'text' => '您好,根据您所订购的订单 ID:' . $bought->id . ',流量已经被重置为' . $shop->reset_value() . 'GB',
                     ],
                     [],
                     $_ENV['email_queue']
@@ -150,15 +149,15 @@ class Job extends Command
         }
         // ------- 用户流量重置
 
-        User::chunkById(1000, function ($users) use ($bought_users) {
+        User::chunkById(1000, function ($users) use ($bought_users): void {
             foreach ($users as $user) {
                 /** @var User $user */
-                $user->last_day_t = ($user->u + $user->d);
+                $user->last_day_t = $user->u + $user->d;
                 $user->save();
                 if (in_array($user->id, $bought_users)) {
                     continue;
                 }
-                if (date('d') == $user->auto_reset_day) {
+                if (date('d') === $user->auto_reset_day) {
                     $user->u = 0;
                     $user->d = 0;
                     $user->last_day_t = 0;
@@ -168,7 +167,7 @@ class Job extends Command
                         $_ENV['appName'] . '-您的免费流量被重置了',
                         'news/warn.tpl',
                         [
-                            'text' => '您好,您的免费流量已经被重置为' . $user->auto_reset_bandwidth . 'GB'
+                            'text' => '您好,您的免费流量已经被重置为' . $user->auto_reset_bandwidth . 'GB',
                         ],
                         [],
                         $_ENV['email_queue']
@@ -190,35 +189,32 @@ class Job extends Command
 
     /**
      * 检查任务,每分钟
-     *
-     * @return void
      */
-    public function CheckJob()
+    public function CheckJob(): void
     {
         //节点掉线检测
-        if ($_ENV['enable_detect_offline'] == true) {
+        if ($_ENV['enable_detect_offline'] === true) {
             echo '节点掉线检测开始' . PHP_EOL;
             $adminUser = User::where('is_admin', '=', '1')->get();
             $nodes = Node::all();
             foreach ($nodes as $node) {
-                if ($node->isNodeOnline() === false && $node->online == true) {
-                    if ($_ENV['useScFtqq'] == true && $_ENV['enable_detect_offline_useScFtqq'] == true) {
+                if ($node->isNodeOnline() === false && $node->online === true) {
+                    if ($_ENV['useScFtqq'] === true && $_ENV['enable_detect_offline_useScFtqq'] === true) {
                         $ScFtqq_SCKEY = $_ENV['ScFtqq_SCKEY'];
                         $text = '管理员您好,系统发现节点 ' . $node->name . ' 掉线了,请您及时处理。';
                         $postdata = http_build_query(
-                            array(
+                            [
                                 'text' => $_ENV['appName'] . '-节点掉线了',
-                                'desp' => $text
-                            )
+                                'desp' => $text,
+                            ]
                         );
-                        $opts = array(
-                            'http' =>
-                            array(
+                        $opts = [
+                            'http' => [
                                 'method' => 'POST',
                                 'header' => 'Content-type: application/x-www-form-urlencoded',
-                                'content' => $postdata
-                            )
-                        );
+                                'content' => $postdata,
+                            ],
+                        ];
                         $context = stream_context_create($opts);
                         file_get_contents('https://sctapi.ftqq.com/' . $ScFtqq_SCKEY . '.send', false, $context);
                     }
@@ -229,7 +225,7 @@ class Job extends Command
                             $_ENV['appName'] . '-系统警告',
                             'news/warn.tpl',
                             [
-                                'text' => '管理员您好,系统发现节点 ' . $node->name . ' 掉线了,请您及时处理。'
+                                'text' => '管理员您好,系统发现节点 ' . $node->name . ' 掉线了,请您及时处理。',
                             ],
                             [],
                             $_ENV['email_queue']
@@ -247,25 +243,24 @@ class Job extends Command
 
                     $node->online = false;
                     $node->save();
-                } elseif ($node->isNodeOnline() === true && $node->online == false) {
-                    if ($_ENV['useScFtqq'] == true && $_ENV['enable_detect_offline_useScFtqq'] == true) {
+                } elseif ($node->isNodeOnline() === true && $node->online === false) {
+                    if ($_ENV['useScFtqq'] === true && $_ENV['enable_detect_offline_useScFtqq'] === true) {
                         $ScFtqq_SCKEY = $_ENV['ScFtqq_SCKEY'];
                         $text = '管理员您好,系统发现节点 ' . $node->name . ' 恢复上线了。';
                         $postdata = http_build_query(
-                            array(
+                            [
                                 'text' => $_ENV['appName'] . '-节点恢复上线了',
-                                'desp' => $text
-                            )
+                                'desp' => $text,
+                            ]
                         );
 
-                        $opts = array(
-                            'http' =>
-                            array(
+                        $opts = [
+                            'http' => [
                                 'method' => 'POST',
                                 'header' => 'Content-type: application/x-www-form-urlencoded',
-                                'content' => $postdata
-                            )
-                        );
+                                'content' => $postdata,
+                            ],
+                        ];
                         $context = stream_context_create($opts);
                         file_get_contents('https://sctapi.ftqq.com/' . $ScFtqq_SCKEY . '.send', false, $context);
                     }
@@ -275,7 +270,7 @@ class Job extends Command
                             $_ENV['appName'] . '-系统提示',
                             'news/warn.tpl',
                             [
-                                'text' => '管理员您好,系统发现节点 ' . $node->name . ' 恢复上线了。'
+                                'text' => '管理员您好,系统发现节点 ' . $node->name . ' 恢复上线了。',
                             ],
                             [],
                             $_ENV['email_queue']
@@ -303,7 +298,7 @@ class Job extends Command
         foreach ($nodes as $node) {
             /** @var Node $node */
             $server = $node->get_out_address();
-            if (!Tools::is_ip($server) && $node->changeNodeIp($server)) {
+            if (! Tools::is_ip($server) && $node->changeNodeIp($server)) {
                 $node->save();
             }
         }
@@ -311,14 +306,12 @@ class Job extends Command
 
     /**
      * 用户账户相关任务,每小时
-     *
-     * @return void
      */
-    public function UserJob()
+    public function UserJob(): void
     {
         $users = User::all();
         foreach ($users as $user) {
-            if (strtotime($user->expire_in) < time() && $user->expire_notified == false) {
+            if (strtotime($user->expire_in) < time() && $user->expire_notified === false) {
                 $user->transfer_enable = 0;
                 $user->u = 0;
                 $user->d = 0;
@@ -327,32 +320,32 @@ class Job extends Command
                     $_ENV['appName'] . '-您的用户账户已经过期了',
                     'news/warn.tpl',
                     [
-                        'text' => '您好,系统发现您的账号已经过期了。'
+                        'text' => '您好,系统发现您的账号已经过期了。',
                     ],
                     [],
                     $_ENV['email_queue']
                 );
                 $user->expire_notified = true;
                 $user->save();
-            } elseif (strtotime($user->expire_in) > time() && $user->expire_notified == true) {
+            } elseif (strtotime($user->expire_in) > time() && $user->expire_notified === true) {
                 $user->expire_notified = false;
                 $user->save();
             }
 
             //余量不足检测
-            if ($_ENV['notify_limit_mode'] != false) {
+            if ($_ENV['notify_limit_mode'] !== false) {
                 $user_traffic_left = $user->transfer_enable - $user->u - $user->d;
                 $under_limit = false;
 
-                if ($user->transfer_enable != 0 && $user->class != 0) {
+                if ($user->transfer_enable !== 0 && $user->class !== 0) {
                     if (
-                        $_ENV['notify_limit_mode'] == 'per' &&
+                        $_ENV['notify_limit_mode'] === 'per' &&
                         $user_traffic_left / $user->transfer_enable * 100 < $_ENV['notify_limit_value']
                     ) {
                         $under_limit = true;
                         $unit_text = '%';
                     } elseif (
-                        $_ENV['notify_limit_mode'] == 'mb' &&
+                        $_ENV['notify_limit_mode'] === 'mb' &&
                         Tools::flowToMB($user_traffic_left) < $_ENV['notify_limit_value']
                     ) {
                         $under_limit = true;
@@ -360,12 +353,12 @@ class Job extends Command
                     }
                 }
 
-                if ($under_limit == true && $user->traffic_notified == false) {
+                if ($under_limit === true && $user->traffic_notified === false) {
                     $result = $user->sendMail(
                         $_ENV['appName'] . '-您的剩余流量过低',
                         'news/warn.tpl',
                         [
-                            'text' => '您好,系统发现您剩余流量已经低于 ' . $_ENV['notify_limit_value'] . $unit_text . ' 。'
+                            'text' => '您好,系统发现您剩余流量已经低于 ' . $_ENV['notify_limit_value'] . $unit_text . ' 。',
                         ],
                         [],
                         $_ENV['email_queue']
@@ -374,7 +367,7 @@ class Job extends Command
                         $user->traffic_notified = true;
                         $user->save();
                     }
-                } elseif ($under_limit == false && $user->traffic_notified == true) {
+                } elseif ($under_limit === false && $user->traffic_notified === true) {
                     $user->traffic_notified = false;
                     $user->save();
                 }
@@ -389,7 +382,7 @@ class Job extends Command
                     $_ENV['appName'] . '-您的用户账户已经被删除了',
                     'news/warn.tpl',
                     [
-                        'text' => '您好,系统发现您的账户已经过期 ' . $_ENV['account_expire_delete_days'] . ' 天了,帐号已经被删除。'
+                        'text' => '您好,系统发现您的账户已经过期 ' . $_ENV['account_expire_delete_days'] . ' 天了,帐号已经被删除。',
                     ],
                     [],
                     $_ENV['email_queue']
@@ -404,14 +397,14 @@ class Job extends Command
                     $user->last_check_in_time,
                     strtotime($user->reg_date)
                 ) + ($_ENV['auto_clean_uncheck_days'] * 86400) < time() &&
-                $user->class == 0 &&
+                $user->class === 0 &&
                 $user->money <= $_ENV['auto_clean_min_money']
             ) {
                 $user->sendMail(
                     $_ENV['appName'] . '-您的用户账户已经被删除了',
                     'news/warn.tpl',
                     [
-                        'text' => '您好,系统发现您的账号已经 ' . $_ENV['auto_clean_uncheck_days'] . ' 天没签到了,帐号已经被删除。'
+                        'text' => '您好,系统发现您的账号已经 ' . $_ENV['auto_clean_uncheck_days'] . ' 天没签到了,帐号已经被删除。',
                     ],
                     [],
                     $_ENV['email_queue']
@@ -423,14 +416,14 @@ class Job extends Command
             if (
                 $_ENV['auto_clean_unused_days'] > 0 &&
                 max($user->t, strtotime($user->reg_date)) + ($_ENV['auto_clean_unused_days'] * 86400) < time() &&
-                $user->class == 0 &&
+                $user->class === 0 &&
                 $user->money <= $_ENV['auto_clean_min_money']
             ) {
                 $user->sendMail(
                     $_ENV['appName'] . '-您的用户账户已经被删除了',
                     'news/warn.tpl',
                     [
-                        'text' => '您好,系统发现您的账号已经 ' . $_ENV['auto_clean_unused_days'] . ' 天没使用了,帐号已经被删除。'
+                        'text' => '您好,系统发现您的账号已经 ' . $_ENV['auto_clean_unused_days'] . ' 天没使用了,帐号已经被删除。',
                     ],
                     [],
                     $_ENV['email_queue']
@@ -440,7 +433,7 @@ class Job extends Command
             }
 
             if (
-                $user->class != 0 &&
+                $user->class !== 0 &&
                 strtotime($user->class_expire) < time() &&
                 strtotime($user->class_expire) > 1420041600
             ) {
@@ -457,7 +450,7 @@ class Job extends Command
                     $_ENV['appName'] . '-您的账户等级已经过期了',
                     'news/warn.tpl',
                     [
-                        'text' => $text
+                        'text' => $text,
                     ],
                     [],
                     $_ENV['email_queue']
@@ -466,9 +459,9 @@ class Job extends Command
             }
 
             // 审计封禁解封
-            if ($user->enable == 0) {
+            if ($user->enable === 0) {
                 $logs = DetectBanLog::where('user_id', $user->id)->orderBy('id', 'desc')->first();
-                if ($logs != null) {
+                if ($logs !== null) {
                     if (($logs->end_time + $logs->ban_time * 60) <= time()) {
                         $user->enable = 1;
                     }
@@ -483,18 +476,18 @@ class Job extends Command
         foreach ($boughts as $bought) {
             /** @var Bought $bought */
             $user = $bought->user();
-            if ($user == null) {
+            if ($user === null) {
                 continue;
             }
 
             $shop = $bought->shop();
-            if ($shop == null) {
+            if ($shop === null) {
                 $bought->delete();
                 $user->sendMail(
                     $_ENV['appName'] . '-续费失败',
                     'news/warn.tpl',
                     [
-                        'text' => '您好,系统为您自动续费商品时,发现该商品已被下架,为能继续正常使用,建议您登录用户面板购买新的商品。'
+                        'text' => '您好,系统为您自动续费商品时,发现该商品已被下架,为能继续正常使用,建议您登录用户面板购买新的商品。',
                     ],
                     [],
                     $_ENV['email_queue']
@@ -510,20 +503,20 @@ class Job extends Command
                 $bought->renew = 0;
                 $bought->save();
 
-                $bought_new           = new Bought();
-                $bought_new->userid   = $user->id;
-                $bought_new->shopid   = $shop->id;
+                $bought_new = new Bought();
+                $bought_new->userid = $user->id;
+                $bought_new->shopid = $shop->id;
                 $bought_new->datetime = time();
-                $bought_new->renew    = time() + $shop->auto_renew * 86400;
-                $bought_new->price    = $shop->price;
-                $bought_new->coupon   = '';
+                $bought_new->renew = time() + $shop->auto_renew * 86400;
+                $bought_new->price = $shop->price;
+                $bought_new->coupon = '';
                 $bought_new->save();
 
                 $user->sendMail(
                     $_ENV['appName'] . '-续费成功',
                     'news/warn.tpl',
                     [
-                        'text' => '您好,系统已经为您自动续费,商品名:' . $shop->name . ',金额:' . $shop->price . ' 元。'
+                        'text' => '您好,系统已经为您自动续费,商品名:' . $shop->name . ',金额:' . $shop->price . ' 元。',
                     ],
                     [],
                     $_ENV['email_queue']
@@ -531,12 +524,12 @@ class Job extends Command
 
                 $bought->is_notified = true;
                 $bought->save();
-            } elseif ($bought->is_notified == false) {
+            } elseif ($bought->is_notified === false) {
                 $user->sendMail(
                     $_ENV['appName'] . '-续费失败',
                     'news/warn.tpl',
                     [
-                        'text' => '您好,系统为您自动续费商品名:' . $shop->name . ',金额:' . $shop->price . ' 元 时,发现您余额不足,请及时充值。充值后请稍等系统便会自动为您续费。'
+                        'text' => '您好,系统为您自动续费商品名:' . $shop->name . ',金额:' . $shop->price . ' 元 时,发现您余额不足,请及时充值。充值后请稍等系统便会自动为您续费。',
                     ],
                     [],
                     $_ENV['email_queue']

+ 54 - 47
src/Command/PortAutoChange.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 /**
  * [实验性] 检测到端口被墙则自动更换端口
  *
@@ -9,11 +11,8 @@
 
 namespace App\Command;
 
-use App\Models\{
-    User,
-    Node
-};
 use App\Utils\URL;
+use User;
 
 class PortAutoChange extends Command
 {
@@ -37,14 +36,14 @@ class PortAutoChange extends Command
         // 例外的节点,填写节点 ID,英文逗号分隔
         // 此处提供的节点将不会进行端口更换
         // 即使当原先的承载端口被更换时,也会将例外节点的端口偏移回去
-        'exception_node_id' => array(),
+        'exception_node_id' => [],
     ];
 
-    public function boot()
+    public function boot(): void
     {
         $gfw_port_nodes = [];
         $nodes = Node::where(
-            static function ($query) {
+            static function ($query): void {
                 $query->where('sort', 0)
                     ->orwhere('sort', 10);
             }
@@ -55,7 +54,7 @@ class PortAutoChange extends Command
         foreach ($nodes as $node) {
             $mu_nodes = Node::where('sort', 9)->where('type', '1')
                 ->where(
-                    static function ($query) use ($node) {
+                    static function ($query) use ($node): void {
                         $query->Where('node_group', '=', $node->node_group)
                             ->orWhere('node_group', '=', 0);
                     }
@@ -64,33 +63,39 @@ class PortAutoChange extends Command
                 ->get();
             foreach ($mu_nodes as $mu_node) {
                 $mu_user = User::where('enable', 1)->where('is_multi_user', '<>', 0)->where('port', '=', $mu_node->server)->first();
-                if ($mu_user == null) continue;
+                if ($mu_user === null) {
+                    continue;
+                }
                 $port = $this->OutPort($node->server, $mu_node->server);
                 $api_url = $_ENV['detect_gfw_url'];
                 $api_url = str_replace(
-                    array('{ip}', '{port}'),
-                    array($node->node_ip, $port),
+                    ['{ip}', '{port}'],
+                    [$node->node_ip, $port],
                     $api_url
                 );
                 $result_tcping = $this->DetectPort($api_url);
-                if ($result_tcping) continue;
+                if ($result_tcping) {
+                    continue;
+                }
                 $gfw_port_nodes[$mu_node->server][] = $node->id;
-                echo ('#' . $node->id . ' --- ' . $node->name . ' --- ' . $port . ' 端口不通' . PHP_EOL);
+                echo '#' . $node->id . ' --- ' . $node->name . ' --- ' . $port . ' 端口不通' . PHP_EOL;
             }
         }
         foreach ($gfw_port_nodes as $port => $array) {
             $mu_node = Node::where('sort', 9)->where('server', '=', $port)->where('type', '1')->first();
             $mu_user = User::where('enable', 1)->where('is_multi_user', '<>', 0)->where('port', '=', $port)->first();
-            if ($mu_node == null || $mu_user == null) continue;
+            if ($mu_node === null || $mu_user === null) {
+                continue;
+            }
             $mu_port_nodes = Node::where(
-                static function ($query) {
+                static function ($query): void {
                     $query->where('sort', 0)
                         ->orwhere('sort', 10);
                 }
             )
                 ->where(
-                    static function ($query) use ($mu_node) {
-                        if ($mu_node->node_group == 0) {
+                    static function ($query) use ($mu_node): void {
+                        if ($mu_node->node_group === 0) {
                             $query->where('node_group', '>=', 0);
                         } else {
                             $query->where('node_group', '=', $mu_node->node_group);
@@ -103,84 +108,86 @@ class PortAutoChange extends Command
                 ->get();
             for ($i = 0; $i <= 10; $i++) {
                 $new_port = rand((int) $this->Config['port_min'], (int) $this->Config['port_max']);
-                if (Node::where('sort', 9)->where('server', '=', $new_port)->first() == null && User::where('port', '=', $new_port)->first() == null) {
+                if (Node::where('sort', 9)->where('server', '=', $new_port)->first() === null && User::where('port', '=', $new_port)->first() === null) {
                     break;
                 }
             }
-            $number = (count($array) / count($mu_port_nodes)) * 100;
+            $number = count($array) / count($mu_port_nodes) * 100;
             if ($number >= $this->Config['mu_node_port_change_percent']) {
-                echo ('超过百分比:' . $number . '%' . PHP_EOL);
-                echo ('#' . $mu_node->id . ' - 单端口承载节点 - ' . $mu_node->name . ' - 更换了新的端口 ' . $new_port . PHP_EOL);
+                echo '超过百分比:' . $number . '%' . PHP_EOL;
+                echo '#' . $mu_node->id . ' - 单端口承载节点 - ' . $mu_node->name . ' - 更换了新的端口 ' . $new_port . PHP_EOL;
                 $mu_node->server = $new_port;
                 $mu_node->save();
-                echo ('#' . $mu_user->id . ' - 单端口承载用户 - ' . $mu_user->user_name . ' - 更换了新的端口 ' . $new_port . PHP_EOL);
+                echo '#' . $mu_user->id . ' - 单端口承载用户 - ' . $mu_user->user_name . ' - 更换了新的端口 ' . $new_port . PHP_EOL;
                 $mu_user->port = $new_port;
                 $mu_user->save();
                 foreach ($mu_port_nodes as $mu_port_node) {
                     $node_port = $this->OutPort($mu_port_node->server, $port);
-                    if (in_array($mu_port_node->id, $array) && !in_array($mu_port_node->id, $this->Config['exception_node_id'])) {
-                        if ($node_port != $port) {
-                            if ($node_port == $new_port) {
-                                if (strpos($mu_port_node->server, ($port . '#')) !== false) {
+                    if (in_array($mu_port_node->id, $array) && ! in_array($mu_port_node->id, $this->Config['exception_node_id'])) {
+                        if ($node_port !== $port) {
+                            if ($node_port === $new_port) {
+                                if (strpos($mu_port_node->server, $port . '#') !== false) {
                                     for ($i = 0; $i <= 10; $i++) {
                                         $new_mu_node_port = rand((int) $this->Config['port_min'], (int) $this->Config['port_max']);
-                                        if ($new_mu_node_port != $new_port && Node::where('port', '=', $new_mu_node_port)->first() == null && User::where('port', '=', $new_mu_node_port)->first() == null) {
+                                        if ($new_mu_node_port !== $new_port && Node::where('port', '=', $new_mu_node_port)->first() === null && User::where('port', '=', $new_mu_node_port)->first() === null) {
                                             break;
                                         }
                                     }
                                     $mu_port_node->server = str_replace(($port . '#' . $node_port), ($new_port . '#' . $new_mu_node_port), $mu_port_node->server);
-                                    echo ('#' . $mu_port_node->id . ' - 节点 - ' . $mu_port_node->name . ' - 端口从 ' . $node_port . ' 偏移到了新的端口 ' . $new_mu_node_port . PHP_EOL);
+                                    echo '#' . $mu_port_node->id . ' - 节点 - ' . $mu_port_node->name . ' - 端口从 ' . $node_port . ' 偏移到了新的端口 ' . $new_mu_node_port . PHP_EOL;
                                 }
                             } else {
-                                if (strpos($mu_port_node->server, ($port . '#')) !== false) {
+                                if (strpos($mu_port_node->server, $port . '#') !== false) {
                                     $mu_port_node->server = str_replace(('+' . $port . '#' . $node_port), '', $mu_port_node->server);
                                     $mu_port_node->server = str_replace(($port . '#' . $node_port . '+'), '', $mu_port_node->server);
                                     $mu_port_node->server = str_replace(($port . '#' . $node_port), '', $mu_port_node->server);
-                                    echo ('#' . $mu_port_node->id . ' - 节点 - ' . $mu_port_node->name . ' - 端口从 ' . $node_port . ' 偏移到了新的端口 ' . $new_port . PHP_EOL);
+                                    echo '#' . $mu_port_node->id . ' - 节点 - ' . $mu_port_node->name . ' - 端口从 ' . $node_port . ' 偏移到了新的端口 ' . $new_port . PHP_EOL;
                                 }
                             }
                         }
                     } else {
-                        if ($node_port == $port) {
+                        if ($node_port === $port) {
                             if (strpos($mu_port_node->server, ';') !== false) {
                                 if (strpos($mu_port_node->server, 'port=') !== false) {
                                     $mu_port_node->server = str_replace('port=', ('port=' . $new_port . '#' . $port . '+'), $mu_port_node->server);
                                 } else {
-                                    $mu_port_node->server = ($mu_port_node->server . ';port=' . $new_port . '#' . $port);
+                                    $mu_port_node->server .= ';port=' . $new_port . '#' . $port;
                                 }
                             } else {
-                                $mu_port_node->server = ($mu_port_node->server . ';port=' . $new_port . '#' . $port);
+                                $mu_port_node->server .= ';port=' . $new_port . '#' . $port;
                             }
                         } else {
-                            if (strpos($mu_port_node->server, ($port . '#')) !== false) {
-                                $mu_port_node->server = str_replace(($port . '#'), ($new_port . '#'), $mu_port_node->server);
+                            if (strpos($mu_port_node->server, $port . '#') !== false) {
+                                $mu_port_node->server = str_replace($port . '#', $new_port . '#', $mu_port_node->server);
                             }
                         }
-                        echo ('#' . $mu_port_node->id . ' - 节点 - ' . $mu_port_node->name . ' - 由于端口未被墙或例外设置,已将端口偏移回原端口 ' . $node_port . PHP_EOL);
+                        echo '#' . $mu_port_node->id . ' - 节点 - ' . $mu_port_node->name . ' - 由于端口未被墙或例外设置,已将端口偏移回原端口 ' . $node_port . PHP_EOL;
                     }
                     $mu_port_node->save();
                 }
             } else {
                 foreach ($array as $node_id) {
-                    if (in_array($node_id, $this->Config['exception_node_id'])) continue;
+                    if (in_array($node_id, $this->Config['exception_node_id'])) {
+                        continue;
+                    }
                     $node = Node::find($node_id);
                     $node_port = $this->OutPort($node->server, $port);
-                    if ($node_port != $port) {
-                        if (strpos($node->server, ('#' . $node_port)) !== false) {
-                            echo ('#' . $node->id . ' - 节点 - ' . $node->name . ' - 端口从' . $node_port . '偏移到了新的端口 ' . $new_port . PHP_EOL);
-                            $node->server = str_replace(('#' . $node_port), ('#' . $new_port), $node->server);
+                    if ($node_port !== $port) {
+                        if (strpos($node->server, '#' . $node_port) !== false) {
+                            echo '#' . $node->id . ' - 节点 - ' . $node->name . ' - 端口从' . $node_port . '偏移到了新的端口 ' . $new_port . PHP_EOL;
+                            $node->server = str_replace('#' . $node_port, '#' . $new_port, $node->server);
                         }
                     } else {
                         if (strpos($node->server, ';') !== false) {
                             if (strpos($node->server, 'port=') !== false) {
                                 $node->server = str_replace('port=', ('port=' . $port . '#' . $new_port . '+'), $node->server);
                             } else {
-                                $node->server = ($node->server . ';port=' . $port . '#' . $new_port);
+                                $node->server .= ';port=' . $port . '#' . $new_port;
                             }
                         } else {
-                            $node->server = ($node->server . ';port=' . $port . '#' . $new_port);
+                            $node->server .= ';port=' . $port . '#' . $new_port;
                         }
-                        echo ('#' . $node->id . ' - 节点 - ' . $node->name . ' - 端口从' . $node_port . '偏移到了新的端口 ' . $new_port . PHP_EOL);
+                        echo '#' . $node->id . ' - 节点 - ' . $node->name . ' - 端口从' . $node_port . '偏移到了新的端口 ' . $new_port . PHP_EOL;
                     }
                     $node->save();
                 }
@@ -199,17 +206,17 @@ class PortAutoChange extends Command
                     if (strpos($item['port'], '+') !== false) {
                         $args_explode = explode('+', $item['port']);
                         foreach ($args_explode as $arg) {
-                            if ((int) substr($arg, 0, strpos($arg, '#')) == $mu_port) {
+                            if ((int) substr($arg, 0, strpos($arg, '#')) === $mu_port) {
                                 $node_port = (int) substr($arg, strpos($arg, '#') + 1);
                             }
                         }
                     } else {
-                        if ((int) substr($item['port'], 0, strpos($item['port'], '#')) == $mu_port) {
+                        if ((int) substr($item['port'], 0, strpos($item['port'], '#')) === $mu_port) {
                             $node_port = (int) substr($item['port'], strpos($item['port'], '#') + 1);
                         }
                     }
                 } else {
-                    $node_port = ($mu_port + (int) $item['port']);
+                    $node_port = $mu_port + (int) $item['port'];
                 }
             }
         }

+ 13 - 11
src/Command/SendDiaryMail.php

@@ -1,19 +1,21 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Command;
 
-use App\Models\User;
 use App\Models\Ann;
+use App\Models\User;
+use App\Services\Analytics;
 use App\Services\Config;
 use App\Utils\Telegram;
 use App\Utils\Tools;
-use App\Services\Analytics;
 
 class SendDiaryMail extends Command
 {
     public $description = '├─=: php xcat SendDiaryMail  - 每日流量报告' . PHP_EOL;
 
-    public function boot()
+    public function boot(): void
     {
         $users = User::all();
         $logs = Ann::orderBy('id', 'desc')->get();
@@ -21,14 +23,14 @@ class SendDiaryMail extends Command
 
         foreach ($logs as $log) {
             if (strpos($log->content, 'Links') === false) {
-                $text1 = $text1 . $log->content . '<br><br>';
+                $text1 .= $log->content . '<br><br>';
             }
         }
 
         $lastday_total = 0;
 
         foreach ($users as $user) {
-            $lastday_total += (($user->u + $user->d) - $user->last_day_t);
+            $lastday_total += $user->u + $user->d - $user->last_day_t;
             $user->sendDailyNotification($text1);
         }
 
@@ -37,14 +39,14 @@ class SendDiaryMail extends Command
         if (Config::getconfig('Telegram.bool.Diary')) {
             Telegram::Send(
                 str_replace(
-                    array(
+                    [
                         '%getTodayCheckinUser%',
-                        '%lastday_total%'
-                    ),
-                    array(
+                        '%lastday_total%',
+                    ],
+                    [
                         $sts->getTodayCheckinUser(),
-                        Tools::flowAutoShow($lastday_total)
-                    ),
+                        Tools::flowAutoShow($lastday_total),
+                    ],
                     Config::getconfig('Telegram.string.Diary')
                 )
             );

+ 51 - 52
src/Command/Tool.php

@@ -1,10 +1,12 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Command;
 
-use App\Utils\QQWry;
 use App\Models\Setting;
 use App\Utils\DatatablesHelper;
+use App\Utils\QQWry;
 
 class Tool extends Command
 {
@@ -17,7 +19,7 @@ class Tool extends Command
         . '│ ├─ exportAllSettings       - 导出所有设置' . PHP_EOL
         . '│ ├─ importAllSettings       - 导入所有设置' . PHP_EOL;
 
-    public function boot()
+    public function boot(): void
     {
         if (count($this->argv) === 2) {
             echo $this->description;
@@ -30,15 +32,15 @@ class Tool extends Command
             }
         }
     }
-    
-    public function setTelegram()
+
+    public function setTelegram(): void
     {
         if ($_ENV['use_new_telegram_bot'] === true) {
-            $WebhookUrl = ($_ENV['baseUrl'] . '/telegram_callback?token=' . $_ENV['telegram_request_token']);
+            $WebhookUrl = $_ENV['baseUrl'] . '/telegram_callback?token=' . $_ENV['telegram_request_token'];
             $telegram = new \Telegram\Bot\Api($_ENV['telegram_token']);
             $telegram->removeWebhook();
             if ($telegram->setWebhook(['url' => $WebhookUrl])) {
-                echo ('New Bot @' . $telegram->getMe()->getUsername() . ' 设置成功!' . PHP_EOL);
+                echo 'New Bot @' . $telegram->getMe()->getUsername() . ' 设置成功!' . PHP_EOL;
             }
         } else {
             $bot = new \TelegramBot\Api\BotApi($_ENV['telegram_token']);
@@ -48,18 +50,18 @@ class Tool extends Command
             curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
             $deleteWebhookReturn = json_decode(curl_exec($ch));
             curl_close($ch);
-            if ($deleteWebhookReturn->ok && $deleteWebhookReturn->result && $bot->setWebhook($_ENV['baseUrl'] . '/telegram_callback?token=' . $_ENV['telegram_request_token']) == 1) {
-                echo ('Old Bot 设置成功!' . PHP_EOL);
+            if ($deleteWebhookReturn->ok && $deleteWebhookReturn->result && $bot->setWebhook($_ENV['baseUrl'] . '/telegram_callback?token=' . $_ENV['telegram_request_token']) === 1) {
+                echo 'Old Bot 设置成功!' . PHP_EOL;
             }
         }
     }
-    
-    public function initQQWry()
+
+    public function initQQWry(): void
     {
-        echo ('正在下载或更新纯真ip数据库...') . PHP_EOL;
-        $path  = BASE_PATH . '/storage/qqwry.dat';
+        echo '正在下载或更新纯真ip数据库...' . PHP_EOL;
+        $path = BASE_PATH . '/storage/qqwry.dat';
         $qqwry = file_get_contents('https://qqwry.mirror.noc.one/QQWry.Dat?from=sspanel_uim');
-        if ($qqwry != '') {
+        if ($qqwry !== '') {
             if (is_file($path)) {
                 rename($path, $path . '.bak');
             }
@@ -67,9 +69,9 @@ class Tool extends Command
             if ($fp) {
                 fwrite($fp, $qqwry);
                 fclose($fp);
-                echo ('纯真ip数据库下载成功.') . PHP_EOL;
-                $iplocation   = new QQWry();
-                $location     = $iplocation->getlocation('8.8.8.8');
+                echo '纯真ip数据库下载成功.' . PHP_EOL;
+                $iplocation = new QQWry();
+                $location = $iplocation->getlocation('8.8.8.8');
                 $Userlocation = $location['country'];
                 if (iconv('gbk', 'utf-8//IGNORE', $Userlocation) !== '美国') {
                     unlink($path);
@@ -78,24 +80,23 @@ class Tool extends Command
                     }
                 }
             } else {
-                echo ('纯真ip数据库保存失败,请检查权限') . PHP_EOL;
+                echo '纯真ip数据库保存失败,请检查权限' . PHP_EOL;
             }
         } else {
-            echo ('纯真ip数据库下载失败,请检查下载地址') . PHP_EOL;
+            echo '纯真ip数据库下载失败,请检查下载地址' . PHP_EOL;
         }
     }
-    
-    public function detectConfigs()
+
+    public function detectConfigs(): void
     {
         echo \App\Services\DefaultConfig::detectConfigs();
     }
-    
-    public function resetAllSettings()
+
+    public function resetAllSettings(): void
     {
         $settings = Setting::all();
-        
-        foreach ($settings as $setting)
-        {
+
+        foreach ($settings as $setting) {
             $setting->value = $setting->default;
             $setting->save();
         }
@@ -103,58 +104,56 @@ class Tool extends Command
         echo '已使用默认值覆盖所有设置.' . PHP_EOL;
     }
 
-    public function exportAllSettings()
+    public function exportAllSettings(): void
     {
         $settings = Setting::all();
-        foreach ($settings as $setting)
-        {
+        foreach ($settings as $setting) {
             // 因为主键自增所以即便设置为 null 也会在导入时自动分配 id
             // 同时避免多位开发者 pull request 时 settings.json 文件 id 重复所可能导致的冲突
             $setting->id = null;
             // 避免开发者调试配置泄露
             $setting->value = $setting->default;
         }
-        
+
         $json_settings = json_encode($settings, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
         file_put_contents('./config/settings.json', $json_settings);
 
         echo '已导出所有设置.' . PHP_EOL;
     }
 
-    public function importAllSettings()
+    public function importAllSettings(): void
     {
         $db = new DatatablesHelper();
-        
+
         $json_settings = file_get_contents('./config/settings.json');
-        $settings      = json_decode($json_settings, true);
-        $number        = count($settings);
-        $counter       = '0';
-        
-        for ($i = 0; $i < $number; $i++)
-        {
+        $settings = json_decode($json_settings, true);
+        $number = count($settings);
+        $counter = '0';
+
+        for ($i = 0; $i < $number; $i++) {
             $item = $settings[$i]['item'];
-            
-            if ($db->query("SELECT id FROM config WHERE item = '$item'") == null) {
-                $new_item            = new Setting;
-                $new_item->id        = null;
-                $new_item->item      = $settings[$i]['item'];
-                $new_item->value     = $settings[$i]['value'];
-                $new_item->class     = $settings[$i]['class'];
+
+            if ($db->query("SELECT id FROM config WHERE item = '${item}'") === null) {
+                $new_item = new Setting();
+                $new_item->id = null;
+                $new_item->item = $settings[$i]['item'];
+                $new_item->value = $settings[$i]['value'];
+                $new_item->class = $settings[$i]['class'];
                 $new_item->is_public = $settings[$i]['is_public'];
-                $new_item->type      = $settings[$i]['type'];
-                $new_item->default   = $settings[$i]['default'];
-                $new_item->mark      = $settings[$i]['mark'];
+                $new_item->type = $settings[$i]['type'];
+                $new_item->default = $settings[$i]['default'];
+                $new_item->mark = $settings[$i]['mark'];
                 $new_item->save();
-                
-                echo "添加新设置:$item" . PHP_EOL;
+
+                echo "添加新设置:${item}" . PHP_EOL;
                 $counter += 1;
             }
         }
 
-        if ($counter != '0') {
-            echo "总计添加了 $counter 条新设置." . PHP_EOL;
+        if ($counter !== '0') {
+            echo "总计添加了 ${counter} 条新设置." . PHP_EOL;
         } else {
-            echo "没有任何新设置需要添加." . PHP_EOL;
+            echo '没有任何新设置需要添加.' . PHP_EOL;
         }
     }
 }

+ 65 - 63
src/Command/Update.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Command;
 
 use App\Services\DefaultConfig;
@@ -15,23 +17,23 @@ class Update extends Command
     {
         global $_ENV;
         $copy_result = copy(BASE_PATH . '/config/.config.php', BASE_PATH . '/config/.config.php.bak');
-        if ($copy_result == true) {
-            echo ('备份成功' . PHP_EOL);
+        if ($copy_result === true) {
+            echo '备份成功' . PHP_EOL;
         } else {
-            echo ('备份失败,迁移终止' . PHP_EOL);
+            echo '备份失败,迁移终止' . PHP_EOL;
             return false;
         }
 
-        echo (PHP_EOL);
+        echo PHP_EOL;
 
         // 检查并创建新增的配置项
         echo DefaultConfig::detectConfigs();
 
-        echo ('开始升级 QQWry...' . PHP_EOL);
+        echo '开始升级 QQWry...' . PHP_EOL;
         (new Tool($this->argv))->initQQWry();
-        echo ('升级 QQWry结束' . PHP_EOL);
+        echo '升级 QQWry结束' . PHP_EOL;
 
-        echo (PHP_EOL);
+        echo PHP_EOL;
 
         $config_old = file_get_contents(BASE_PATH . '/config/.config.php');
         $config_new = file_get_contents(BASE_PATH . '/config/.config.example.php');
@@ -39,47 +41,47 @@ class Update extends Command
         //执行版本升级
         $version_old = $_ENV['version'] ?? 0;
         $this->old_to_new($version_old);
-        $this->addColumns('user', 'uuid', 'TEXT', TRUE, 'NULL', 'uuid', 'passwd');
+        $this->addColumns('user', 'uuid', 'TEXT', true, 'NULL', 'uuid', 'passwd');
 
         //将旧config迁移到新config上
-        $migrated = array();
+        $migrated = [];
         foreach ($_ENV as $key => $value_reserve) {
-            if ($key == 'config_migrate_notice' || $key == 'version') {
+            if ($key === 'config_migrate_notice' || $key === 'version') {
                 continue;
             }
 
             $regex = '/_ENV\[\'' . $key . '\'\].*?;/s';
-            $matches_new = array();
+            $matches_new = [];
             preg_match($regex, $config_new, $matches_new);
-            if (isset($matches_new[0]) == false) {
-                echo ('未找到配置项:' . $key . ' 未能在新config文件中找到,可能已被更名或废弃' . PHP_EOL);
+            if (isset($matches_new[0]) === false) {
+                echo '未找到配置项:' . $key . ' 未能在新config文件中找到,可能已被更名或废弃' . PHP_EOL;
                 continue;
             }
 
-            $matches_old = array();
+            $matches_old = [];
             preg_match($regex, $config_old, $matches_old);
 
             $config_new = str_replace($matches_new[0], $matches_old[0], $config_new);
             $migrated[] = '_ENV[\'' . $key . '\']';
         }
-        echo (PHP_EOL);
+        echo PHP_EOL;
 
         //检查新增了哪些config
         $regex_new = '/_ENV\[\'.*?\'\]/s';
-        $matches_new_all = array();
+        $matches_new_all = [];
         preg_match_all($regex_new, $config_new, $matches_new_all);
         $differences = array_diff($matches_new_all[0], $migrated);
         foreach ($differences as $difference) {
             if (
-                $difference == '_ENV[\'config_migrate_notice\']' ||
-                $difference == '_ENV[\'version\']'
+                $difference === '_ENV[\'config_migrate_notice\']' ||
+                $difference === '_ENV[\'version\']'
             ) {
                 continue;
             }
             //匹配注释
             $regex_comment = '/' . $difference . '.*?;.*?(?=\n)/s';
-            $regex_comment = str_replace(array('[', ']'), array('\[', '\]'), $regex_comment);
-            $matches_comment = array();
+            $regex_comment = str_replace(['[', ']'], ['\[', '\]'], $regex_comment);
+            $matches_comment = [];
             preg_match($regex_comment, $config_new, $matches_comment);
             $comment = '';
             if (isset($matches_comment[0])) {
@@ -97,13 +99,13 @@ class Update extends Command
             $difference = substr($difference, 15);
             $difference = substr($difference, 0, -2);
 
-            echo ('新增配置项:' . $difference . ':' . $comment . PHP_EOL);
+            echo '新增配置项:' . $difference . ':' . $comment . PHP_EOL;
         }
-        echo ('新增配置项通常带有默认值,因此通常即使不作任何改动网站也可以正常运行' . PHP_EOL);
+        echo '新增配置项通常带有默认值,因此通常即使不作任何改动网站也可以正常运行' . PHP_EOL;
 
         //输出notice
         $regex_notice = '/_ENV\[\'config_migrate_notice\'\].*?(?=\';)/s';
-        $matches_notice = array();
+        $matches_notice = [];
         preg_match($regex_notice, $config_new, $matches_notice);
         $notice_new = $matches_notice[0];
         $notice_new = substr(
@@ -114,56 +116,56 @@ class Update extends Command
                 strpos($notice_new, '=') //查找'='之后的第一个'\'',然后substr其后面的notice
             ) + 1
         );
-        echo ('以下是迁移附注:');
+        echo '以下是迁移附注:';
         if (isset($_ENV['config_migrate_notice'])) {
-            if ($_ENV['config_migrate_notice'] != $notice_new) {
-                echo ($notice_new);
+            if ($_ENV['config_migrate_notice'] !== $notice_new) {
+                echo $notice_new;
             }
         } else {
-            echo ($notice_new);
+            echo $notice_new;
         }
-        echo (PHP_EOL);
+        echo PHP_EOL;
 
         file_put_contents(BASE_PATH . '/config/.config.php', $config_new);
-        echo (PHP_EOL . '迁移完成' . PHP_EOL);
+        echo PHP_EOL . '迁移完成' . PHP_EOL;
 
-        echo (PHP_EOL);
+        echo PHP_EOL;
 
-        echo ('开始升级composer依赖...' . PHP_EOL);
+        echo '开始升级composer依赖...' . PHP_EOL;
         system('php ' . BASE_PATH . '/composer.phar selfupdate');
         system('php ' . BASE_PATH . '/composer.phar install -d ' . BASE_PATH);
-        echo ('升级composer依赖结束,请自行根据上方输出确认是否升级成功' . PHP_EOL);
+        echo '升级composer依赖结束,请自行根据上方输出确认是否升级成功' . PHP_EOL;
         system('rm -rf ' . BASE_PATH . '/storage/framework/smarty/compile/*');
         system('chown -R ' . $_ENV['php_user_group'] . ' ' . BASE_PATH . '/storage');
     }
 
-    public function addColumns($table, $columu, $type, $isnull, $default, $comment, $after)
+    public function addColumns($table, $columu, $type, $isnull, $default, $comment, $after): void
     {
         $datatables = new DatatablesHelper();
         $exists = $datatables->query("SELECT COUNT(*) as cc FROM information_schema.columns WHERE `table_schema` = '" . $_ENV['db_database'] . "' AND `table_name` = '" . $table . "' AND `column_name` = '" . $columu . "'");
-        if ($exists[0]['cc'] >0) {
+        if ($exists[0]['cc'] > 0) {
             return;
         }
-        $isnull = $isnull ? " NULL " : " NOT NULL ";
-        $datatables->query("ALTER TABLE `" . $table . "` ADD COLUMN `" . $columu . "` " . $type . $isnull . "DEFAULT " . $default . " COMMENT '" . $comment . "' AFTER `" . $after . "`");
+        $isnull = $isnull ? ' NULL ' : ' NOT NULL ';
+        $datatables->query('ALTER TABLE `' . $table . '` ADD COLUMN `' . $columu . '` ' . $type . $isnull . 'DEFAULT ' . $default . " COMMENT '" . $comment . "' AFTER `" . $after . '`');
     }
 
-    public function old_to_new($version_old)
+    public function old_to_new($version_old): void
     {
         if ($version_old < 2) {
             // 版本 2 开始
-            if (!is_file(BASE_PATH . '/config/appprofile.php')) {
-                echo ('创建 appprofile 文件.' . PHP_EOL);
+            if (! is_file(BASE_PATH . '/config/appprofile.php')) {
+                echo '创建 appprofile 文件.' . PHP_EOL;
                 system('cp ' . BASE_PATH . '/config/appprofile.example.php ' . BASE_PATH . '/config/appprofile.php', $ret);
                 echo $ret;
             }
-            if (!Capsule::schema()->hasTable('gconfig')) {
-                echo ('创建 gconfig 表.' . PHP_EOL);
+            if (! Capsule::schema()->hasTable('gconfig')) {
+                echo '创建 gconfig 表.' . PHP_EOL;
                 Capsule::schema()->create(
                     'gconfig',
-                    function (Blueprint $table) {
-                        $table->engine    = 'InnoDB';
-                        $table->charset   = 'utf8mb4';
+                    function (Blueprint $table): void {
+                        $table->engine = 'InnoDB';
+                        $table->charset = 'utf8mb4';
                         $table->collation = 'utf8mb4_unicode_ci';
                         $table->integer('id', true, true);
                         $table->string('key', 128)->comment('配置键名');
@@ -179,13 +181,13 @@ class Update extends Command
                     }
                 );
             }
-            if (!Capsule::schema()->hasTable('user_subscribe_log')) {
-                echo ('创建 user_subscribe_log 表.' . PHP_EOL);
+            if (! Capsule::schema()->hasTable('user_subscribe_log')) {
+                echo '创建 user_subscribe_log 表.' . PHP_EOL;
                 Capsule::schema()->create(
                     'user_subscribe_log',
-                    function (Blueprint $table) {
-                        $table->engine    = 'InnoDB';
-                        $table->charset   = 'utf8mb4';
+                    function (Blueprint $table): void {
+                        $table->engine = 'InnoDB';
+                        $table->charset = 'utf8mb4';
                         $table->collation = 'utf8mb4_unicode_ci';
                         $table->integer('id', true, true);
                         $table->string('user_name', 128)->comment('用户名');
@@ -198,13 +200,13 @@ class Update extends Command
                     }
                 );
             }
-            if (!Capsule::schema()->hasTable('detect_ban_log')) {
-                echo ('创建 detect_ban_log 表.' . PHP_EOL);
+            if (! Capsule::schema()->hasTable('detect_ban_log')) {
+                echo '创建 detect_ban_log 表.' . PHP_EOL;
                 Capsule::schema()->create(
                     'detect_ban_log',
-                    function (Blueprint $table) {
-                        $table->engine    = 'InnoDB';
-                        $table->charset   = 'utf8mb4';
+                    function (Blueprint $table): void {
+                        $table->engine = 'InnoDB';
+                        $table->charset = 'utf8mb4';
                         $table->collation = 'utf8mb4_unicode_ci';
                         $table->integer('id', true, true);
                         $table->string('user_name', 128)->comment('用户名');
@@ -228,20 +230,20 @@ class Update extends Command
             //     );
             // }
             $UserAttributes = array_keys((new \App\Models\User())->first()->getAttributes());
-            if (!in_array('last_detect_ban_time', $UserAttributes)) {
-                echo ('添加 last_detect_ban_time 到 user 表.' . PHP_EOL);
+            if (! in_array('last_detect_ban_time', $UserAttributes)) {
+                echo '添加 last_detect_ban_time 到 user 表.' . PHP_EOL;
                 Capsule::schema()->table(
                     'user',
-                    function (Blueprint $table) {
+                    function (Blueprint $table): void {
                         $table->dateTime('last_detect_ban_time')->default('1989-06-04 00:05:00')->after('enable');
                     }
                 );
             }
-            if (!in_array('all_detect_number', $UserAttributes)) {
-                echo ('添加 all_detect_number 到 user 表.' . PHP_EOL);
+            if (! in_array('all_detect_number', $UserAttributes)) {
+                echo '添加 all_detect_number 到 user 表.' . PHP_EOL;
                 Capsule::schema()->table(
                     'user',
-                    function (Blueprint $table) {
+                    function (Blueprint $table): void {
                         $table->integer('all_detect_number')->default(0)->after('last_detect_ban_time');
                     }
                 );
@@ -256,11 +258,11 @@ class Update extends Command
             $DetectLog->datetime = 0;
             $DetectLog->save();
             $DetectlogAttributes = array_keys((new \App\Models\DetectLog())->first()->getAttributes());
-            if (!in_array('status', $DetectlogAttributes)) {
-                echo ('添加 status 到 detect_log 表.' . PHP_EOL);
+            if (! in_array('status', $DetectlogAttributes)) {
+                echo '添加 status 到 detect_log 表.' . PHP_EOL;
                 Capsule::schema()->table(
                     'detect_log',
-                    function (Blueprint $table) {
+                    function (Blueprint $table): void {
                         $table->integer('status')->default(0)->after('node_id');
                     }
                 );

+ 50 - 63
src/Command/User.php

@@ -1,15 +1,16 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Command;
 
-use Exception;
+use App\Models\Setting;
+use App\Models\User as ModelsUser;
 use App\Utils\GA;
 use App\Utils\Hash;
 use App\Utils\Tools;
+use Exception;
 use Ramsey\Uuid\Uuid;
-use App\Services\Config;
-use App\Models\Setting;
-use App\Models\User as ModelsUser;
 
 class User extends Command
 {
@@ -23,7 +24,7 @@ class User extends Command
         . '│ ├─ generateUUID            - 为所有用户生成新的 UUID' . PHP_EOL
         . '│ ├─ generateGa              - 为所有用户生成新的 Ga Secret' . PHP_EOL;
 
-    public function boot()
+    public function boot(): void
     {
         if (count($this->argv) === 2) {
             echo $this->description;
@@ -39,10 +40,8 @@ class User extends Command
 
     /**
      * 重置用户端口
-     *
-     * @return void
      */
-    public function resetPort()
+    public function resetPort(): void
     {
         fwrite(STDOUT, '请输入用户id: ');
         $user = ModelsUser::find(trim(fgets(STDIN)));
@@ -58,15 +57,13 @@ class User extends Command
 
     /**
      * 重置所有用户端口
-     *
-     * @return void
      */
-    public function resetAllPort()
+    public function resetAllPort(): void
     {
         $users = ModelsUser::all();
         foreach ($users as $user) {
             $origin_port = $user->port;
-            $user->port  = Tools::getAvPort();
+            $user->port = Tools::getAvPort();
             echo '$origin_port=' . $origin_port . '&$user->port=' . $user->port . PHP_EOL;
             $user->save();
         }
@@ -74,15 +71,13 @@ class User extends Command
 
     /**
      * 重置所有用户流量
-     *
-     * @return void
      */
-    public function resetTraffic()
+    public function resetTraffic(): void
     {
         try {
             ModelsUser::where('enable', 1)->update([
-                'd'          => 0,
-                'u'          => 0,
+                'd' => 0,
+                'u' => 0,
                 'last_day_t' => 0,
             ]);
         } catch (Exception $e) {
@@ -94,10 +89,8 @@ class User extends Command
 
     /**
      * 为所有用户生成新的UUID
-     *
-     * @return void
      */
-    public function generateUUID()
+    public function generateUUID(): void
     {
         $users = ModelsUser::all();
         $current_timestamp = time();
@@ -110,10 +103,8 @@ class User extends Command
 
     /**
      * 二次验证
-     *
-     * @return void
      */
-    public function generateGa()
+    public function generateGa(): void
     {
         $users = ModelsUser::all();
         foreach ($users as $user) {
@@ -128,66 +119,64 @@ class User extends Command
 
     /**
      * 创建 Admin 账户
-     *
-     * @return void
      */
-    public function createAdmin()
+    public function createAdmin(): void
     {
         if (count($this->argv) === 3) {
             // ask for input
             fwrite(STDOUT, '(1/3) 请输入管理员邮箱:') . PHP_EOL;
             // get input
             $email = trim(fgets(STDIN));
-            if ($email == null) {
+            if ($email === null) {
                 die("必须输入管理员邮箱.\r\n");
             }
 
             // write input back
-            fwrite(STDOUT, "(2/3) 请输入管理员账户密码:") . PHP_EOL;
+            fwrite(STDOUT, '(2/3) 请输入管理员账户密码:') . PHP_EOL;
             $passwd = trim(fgets(STDIN));
-            if ($passwd == null) {
+            if ($passwd === null) {
                 die("必须输入管理员密码.\r\n");
             }
-            
-            fwrite(STDOUT, "(3/3) 按 Y 或 y 确认创建:");
+
+            fwrite(STDOUT, '(3/3) 按 Y 或 y 确认创建:');
             $y = trim(fgets(STDIN));
         } elseif (count($this->argv) === 5) {
             [,,, $email, $passwd] = $this->argv;
             $y = 'y';
         }
 
-        if (strtolower($y) == 'y') {
-            $current_timestamp          = time();
+        if (strtolower($y) === 'y') {
+            $current_timestamp = time();
             // create admin user
             $configs = Setting::getClass('register');
             // do reg user
-            $user                   = new ModelsUser();
-            $user->user_name        = 'admin';
-            $user->email            = $email;
-            $user->pass             = Hash::passwordHash($passwd);
-            $user->passwd           = Tools::genRandomChar(16);
-            $user->uuid             = Uuid::uuid3(Uuid::NAMESPACE_DNS, $email . '|' . $current_timestamp);
-            $user->port             = Tools::getLastPort() + 1;
-            $user->t                = 0;
-            $user->u                = 0;
-            $user->d                = 0;
-            $user->transfer_enable  = Tools::toGB($configs['sign_up_for_free_traffic']);
-            $user->invite_num       = $configs['sign_up_for_invitation_codes'];
-            $user->ref_by           = 0;
-            $user->is_admin         = 1;
-            $user->expire_in        = date('Y-m-d H:i:s', time() + $configs['sign_up_for_free_time'] * 86400);
-            $user->reg_date         = date('Y-m-d H:i:s');
-            $user->money            = 0;
-            $user->im_type          = 1;
-            $user->im_value         = '';
-            $user->class            = 0;
-            $user->node_speedlimit  = 0;
-            $user->theme            = $_ENV['theme'];
-
-            $ga                     = new GA();
-            $secret                 = $ga->createSecret();
-            $user->ga_token         = $secret;
-            $user->ga_enable        = 0;
+            $user = new ModelsUser();
+            $user->user_name = 'admin';
+            $user->email = $email;
+            $user->pass = Hash::passwordHash($passwd);
+            $user->passwd = Tools::genRandomChar(16);
+            $user->uuid = Uuid::uuid3(Uuid::NAMESPACE_DNS, $email . '|' . $current_timestamp);
+            $user->port = Tools::getLastPort() + 1;
+            $user->t = 0;
+            $user->u = 0;
+            $user->d = 0;
+            $user->transfer_enable = Tools::toGB($configs['sign_up_for_free_traffic']);
+            $user->invite_num = $configs['sign_up_for_invitation_codes'];
+            $user->ref_by = 0;
+            $user->is_admin = 1;
+            $user->expire_in = date('Y-m-d H:i:s', time() + $configs['sign_up_for_free_time'] * 86400);
+            $user->reg_date = date('Y-m-d H:i:s');
+            $user->money = 0;
+            $user->im_type = 1;
+            $user->im_value = '';
+            $user->class = 0;
+            $user->node_speedlimit = 0;
+            $user->theme = $_ENV['theme'];
+
+            $ga = new GA();
+            $secret = $ga->createSecret();
+            $user->ga_token = $secret;
+            $user->ga_enable = 0;
 
             if ($user->save()) {
                 echo '创建成功,请在主页登录' . PHP_EOL;
@@ -201,10 +190,8 @@ class User extends Command
 
     /**
      * 获取 USERID 的 Cookie
-     *
-     * @return void
      */
-    public function getCookie()
+    public function getCookie(): void
     {
         if (count($this->argv) === 4) {
             $user = ModelsUser::find($this->argv[3]);

+ 56 - 74
src/Controllers/Admin/AnnController.php

@@ -1,38 +1,32 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\Admin;
 
+use Ann;
 use App\Controllers\AdminController;
-use App\Models\{
-    Ann,
-    User
-};
 use App\Utils\Telegram;
-use Slim\Http\{
-    Request,
-    Response
-};
+use Request;
 
 class AnnController extends AdminController
 {
     /**
      * 后台公告页面
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function index($request, $response, $args)
+    public function index(Request $request, Response $response, array $args)
     {
-        $table_config['total_column'] = array(
-            'op'      => '操作',
-            'id'      => 'ID',
-            'date'    => '日期',
-            'content' => '内容'
-        );
-        $table_config['default_show_column'] = array(
-            'op', 'id', 'date', 'content'
-        );
+        $table_config['total_column'] = [
+            'op' => '操作',
+            'id' => 'ID',
+            'date' => '日期',
+            'content' => '内容',
+        ];
+        $table_config['default_show_column'] = [
+            'op', 'id', 'date', 'content',
+        ];
         $table_config['ajax_url'] = 'announcement/ajax';
         return $response->write(
             $this->view()
@@ -44,50 +38,46 @@ class AnnController extends AdminController
     /**
      * 后台公告页面 AJAX
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax($request, $response, $args)
+    public function ajax(Request $request, Response $response, array $args)
     {
         $query = Ann::getTableDataFromAdmin(
             $request,
-            static function (&$order_field) {
+            static function (&$order_field): void {
                 if (in_array($order_field, ['op'])) {
                     $order_field = 'id';
                 }
             }
         );
 
-        $data  = [];
+        $data = [];
         foreach ($query['datas'] as $value) {
             /** @var Ann $value */
 
-            $tempdata            = [];
-            $tempdata['op']      = '<a class="btn btn-brand" href="/admin/announcement/' . $value->id . '/edit">编辑</a> <a class="btn btn-brand-accent" id="delete" value="' . $value->id . '" href="javascript:void(0);" onClick="delete_modal_show(\'' . $value->id . '\')">删除</a>';
-            $tempdata['id']      = $value->id;
-            $tempdata['date']    = $value->date;
+            $tempdata = [];
+            $tempdata['op'] = '<a class="btn btn-brand" href="/admin/announcement/' . $value->id . '/edit">编辑</a> <a class="btn btn-brand-accent" id="delete" value="' . $value->id . '" href="javascript:void(0);" onClick="delete_modal_show(\'' . $value->id . '\')">删除</a>';
+            $tempdata['id'] = $value->id;
+            $tempdata['date'] = $value->date;
             $tempdata['content'] = $value->content;
 
             $data[] = $tempdata;
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => Ann::count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => Ann::count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 
     /**
      * 后台公告创建页面
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function create($request, $response, $args)
+    public function create(Request $request, Response $response, array $args)
     {
         return $response->write(
             $this->view()
@@ -98,72 +88,68 @@ class AnnController extends AdminController
     /**
      * 后台添加公告
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function add($request, $response, $args)
+    public function add(Request $request, Response $response, array $args)
     {
-        $issend   = $request->getParam('issend');
-        $vip      = $request->getParam('vip');
-        $content  = $request->getParam('content');
-        $subject  = $_ENV['appName'] . '-公告';
-
-        if ($request->getParam('page') == 1) {
-            $ann           = new Ann();
-            $ann->date     = date('Y-m-d H:i:s');
-            $ann->content  = $content;
+        $issend = $request->getParam('issend');
+        $vip = $request->getParam('vip');
+        $content = $request->getParam('content');
+        $subject = $_ENV['appName'] . '-公告';
+
+        if ($request->getParam('page') === 1) {
+            $ann = new Ann();
+            $ann->date = date('Y-m-d H:i:s');
+            $ann->content = $content;
             $ann->markdown = $request->getParam('markdown');
 
-            if (!$ann->save()) {
+            if (! $ann->save()) {
                 return $response->withJson([
                     'ret' => 0,
-                    'msg' => '添加失败'
+                    'msg' => '添加失败',
                 ]);
             }
         }
-        if ($issend == 1) {
+        if ($issend === 1) {
             $beginSend = ($request->getParam('page') - 1) * $_ENV['sendPageLimit'];
-            $users     = User::where('class', '>=', $vip)->skip($beginSend)->limit($_ENV['sendPageLimit'])->get();
+            $users = User::where('class', '>=', $vip)->skip($beginSend)->limit($_ENV['sendPageLimit'])->get();
             foreach ($users as $user) {
                 $user->sendMail(
                     $subject,
                     'news/warn.tpl',
                     [
                         'user' => $user,
-                        'text' => $content
+                        'text' => $content,
                     ],
                     [],
                     $_ENV['email_queue']
                 );
             }
-            if (count($users) == $_ENV['sendPageLimit']) {
+            if (count($users) === $_ENV['sendPageLimit']) {
                 return $response->withJson([
                     'ret' => 2,
-                    'msg' => $request->getParam('page') + 1
+                    'msg' => $request->getParam('page') + 1,
                 ]);
             }
         }
         Telegram::SendMarkdown('新公告:' . PHP_EOL . $request->getParam('markdown'));
-        if ($issend == 1) {
+        if ($issend === 1) {
             $msg = '公告添加成功,邮件发送成功';
         } else {
             $msg = '公告添加成功';
         }
         return $response->withJson([
             'ret' => 1,
-            'msg' => $msg
+            'msg' => $msg,
         ]);
     }
 
     /**
      * 后台编辑公告页面
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function edit($request, $response, $args)
+    public function edit(Request $request, Response $response, array $args)
     {
         $ann = Ann::find($args['id']);
         return $response->write(
@@ -176,48 +162,44 @@ class AnnController extends AdminController
     /**
      * 后台编辑公告提交
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function update($request, $response, $args)
+    public function update(Request $request, Response $response, array $args)
     {
-        $ann           = Ann::find($args['id']);
-        $ann->content  = $request->getParam('content');
+        $ann = Ann::find($args['id']);
+        $ann->content = $request->getParam('content');
         $ann->markdown = $request->getParam('markdown');
-        $ann->date     = date('Y-m-d H:i:s');
-        if (!$ann->save()) {
+        $ann->date = date('Y-m-d H:i:s');
+        if (! $ann->save()) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '修改失败'
+                'msg' => '修改失败',
             ]);
         }
         Telegram::SendMarkdown('公告更新:' . PHP_EOL . $request->getParam('markdown'));
         return $response->withJson([
             'ret' => 1,
-            'msg' => '修改成功'
+            'msg' => '修改成功',
         ]);
     }
 
     /**
      * 后台删除公告
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function delete($request, $response, $args)
+    public function delete(Request $request, Response $response, array $args)
     {
         $ann = Ann::find($request->getParam('id'));
-        if (!$ann->delete()) {
+        if (! $ann->delete()) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '删除失败'
+                'msg' => '删除失败',
             ]);
         }
         return $response->withJson([
             'ret' => 1,
-            'msg' => '删除成功'
+            'msg' => '删除成功',
         ]);
     }
 }

+ 18 - 20
src/Controllers/Admin/ApiController.php

@@ -1,50 +1,48 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\Admin;
+
 use App\Controllers\BaseController;
-use Psr\Http\Message\ResponseInterface;
 use App\Models\Node;
-use Slim\Http\{
-    Request,
-    Response
-};
+use Psr\Http\Message\ResponseInterface;
+use Request;
 
-class ApiController extends BaseController {
+class ApiController extends BaseController
+{
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function getNodeList($request, $response, $args): ResponseInterface {
+    public function getNodeList(Request $request, Response $response, array $args): ResponseInterface
+    {
         return $response->withJson([
-            "ret" => 1,
-            "nodes" => Node::all(),
+            'ret' => 1,
+            'nodes' => Node::all(),
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function getNodeInfo($request, $response, $args): ResponseInterface {
+    public function getNodeInfo(Request $request, Response $response, array $args): ResponseInterface
+    {
         $node = Node::find($args['id']);
 
         return $response->withJson([
-            "ret" => 1,
-            "node" => $node,
+            'ret' => 1,
+            'node' => $node,
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ping($request, $response, $args): ResponseInterface {
+    public function ping(Request $request, Response $response, array $args): ResponseInterface
+    {
         return $response->withJson([
             'ret' => 1,
-            'data' => 'pong'
+            'data' => 'pong',
         ]);
     }
 }

+ 50 - 63
src/Controllers/Admin/CodeController.php

@@ -1,39 +1,36 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\Admin;
 
 use App\Controllers\AdminController;
 use App\Models\Code;
 use App\Models\Setting;
-use App\Utils\Tools;
 use App\Services\Auth;
 use App\Services\Mail;
-use Slim\Http\{
-    Request,
-    Response
-};
+use App\Utils\Tools;
+use Request;
 
 class CodeController extends AdminController
 {
     /**
      * 后台充值码及充值记录页面
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function index($request, $response, $args)
+    public function index(Request $request, Response $response, array $args)
     {
-        $table_config['total_column'] = array(
-            'id'          => 'ID',
-            'code'        => '内容',
-            'type'        => '类型',
-            'number'      => '操作',
-            'isused'      => '是否已经使用',
-            'userid'      => '用户ID',
-            'user_name'   => '用户名',
-            'usedatetime' => '使用时间'
-        );
+        $table_config['total_column'] = [
+            'id' => 'ID',
+            'code' => '内容',
+            'type' => '类型',
+            'number' => '操作',
+            'isused' => '是否已经使用',
+            'userid' => '用户ID',
+            'user_name' => '用户名',
+            'usedatetime' => '使用时间',
+        ];
         $table_config['default_show_column'] = array_keys($table_config['total_column']);
         $table_config['ajax_url'] = 'code/ajax';
         return $response->write(
@@ -44,52 +41,48 @@ class CodeController extends AdminController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax_code($request, $response, $args)
+    public function ajax_code(Request $request, Response $response, array $args)
     {
         $query = Code::getTableDataFromAdmin(
             $request,
-            static function (&$order_field) {
+            static function (&$order_field): void {
                 if (in_array($order_field, ['user_name'])) {
                     $order_field = 'userid';
                 }
             }
         );
 
-        $data  = [];
+        $data = [];
         foreach ($query['datas'] as $value) {
             /** @var Code $value */
             /** 充值记录作为对账,用户不存在也不应删除 */
-            $tempdata                = [];
-            $tempdata['id']          = $value->id;
-            $tempdata['code']        = $value->code;
-            $tempdata['type']        = $value->type();
-            $tempdata['number']      = $value->number();
-            $tempdata['isused']      = $value->isused();
-            $tempdata['userid']      = $value->userid();
-            $tempdata['user_name']   = $value->user_name();
+            $tempdata = [];
+            $tempdata['id'] = $value->id;
+            $tempdata['code'] = $value->code;
+            $tempdata['type'] = $value->type();
+            $tempdata['number'] = $value->number();
+            $tempdata['isused'] = $value->isused();
+            $tempdata['userid'] = $value->userid();
+            $tempdata['user_name'] = $value->user_name();
             $tempdata['usedatetime'] = $value->usedatetime();
 
             $data[] = $tempdata;
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => Code::count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => Code::count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function create($request, $response, $args)
+    public function create(Request $request, Response $response, array $args)
     {
         return $response->write(
             $this->view()
@@ -98,11 +91,9 @@ class CodeController extends AdminController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function donate_create($request, $response, $args)
+    public function donate_create(Request $request, Response $response, array $args)
     {
         return $response->write(
             $this->view()
@@ -111,69 +102,65 @@ class CodeController extends AdminController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function add($request, $response, $args)
+    public function add(Request $request, Response $response, array $args)
     {
-        $cards       = [];
-        $user        = Auth::getUser();
-        $amount      = $request->getParam('amount');
-        $face_value  = $request->getParam('face_value');
+        $cards = [];
+        $user = Auth::getUser();
+        $amount = $request->getParam('amount');
+        $face_value = $request->getParam('face_value');
         $code_length = $request->getParam('code_length');
 
-        if (Tools::isInt($amount) == false) {
+        if (Tools::isInt($amount) === false) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '请填写充值码生成数量'
+                'msg' => '请填写充值码生成数量',
             ]);
         }
 
-        if ($face_value == '') {
+        if ($face_value === '') {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '请填写充值码面额'
+                'msg' => '请填写充值码面额',
             ]);
         }
 
         for ($i = 0; $i < $amount; $i++) {
             // save array
-            $recharge_code     = Tools::genRandomChar($code_length);
+            $recharge_code = Tools::genRandomChar($code_length);
             array_push($cards, $recharge_code);
             // save database
-            $code              = new Code();
-            $code->code        = $recharge_code;
-            $code->type        = -1;
-            $code->number      = $face_value;
-            $code->userid      = 0;
+            $code = new Code();
+            $code->code = $recharge_code;
+            $code->type = -1;
+            $code->number = $face_value;
+            $code->userid = 0;
             $code->usedatetime = '1989:06:04 02:30:00';
             $code->save();
         }
 
-        if (Setting::obtain('mail_driver') != 'none') {
+        if (Setting::obtain('mail_driver') !== 'none') {
             Mail::send(
                 $user->email,
                 $_ENV['appName'] . '- 充值码',
                 'giftcard.tpl',
                 [
-                    'text' => implode('<br/>', $cards)
+                    'text' => implode('<br/>', $cards),
                 ],
                 []
             );
         }
-        
+
         $rs['ret'] = 1;
         $rs['msg'] = '充值码添加成功';
         return $response->withJson($rs);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function donate_add($request, $response, $args)
+    public function donate_add(Request $request, Response $response, array $args)
     {
         $amount = $request->getParam('amount');
         $type = $request->getParam('type');

+ 35 - 39
src/Controllers/Admin/DetectBanLogController.php

@@ -1,36 +1,34 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\Admin;
 
 use App\Controllers\AdminController;
 use App\Models\DetectBanLog;
 use Psr\Http\Message\ResponseInterface;
-use Slim\Http\{
-    Request,
-    Response
-};
+use Slim\Http\Request;
+use Slim\Http\Response;
 
 class DetectBanLogController extends AdminController
 {
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function index($request, $response, $args): ResponseInterface
+    public function index(Request $request, Response $response, array $args): ResponseInterface
     {
-        $table_config['total_column'] = array(
-            'id'                => 'ID',
-            'user_id'           => '用户ID',
-            'user_name'         => '用户名',
-            'email'             => '用户邮箱',
-            'detect_number'     => '违规次数',
-            'ban_time'          => '封禁时长(分钟)',
-            'start_time'        => '统计开始时间',
-            'end_time'          => '统计结束以及封禁开始时间',
-            'ban_end_time'      => '封禁结束时间',
-            'all_detect_number' => '累计违规次数'
-        );
+        $table_config['total_column'] = [
+            'id' => 'ID',
+            'user_id' => '用户ID',
+            'user_name' => '用户名',
+            'email' => '用户邮箱',
+            'detect_number' => '违规次数',
+            'ban_time' => '封禁时长(分钟)',
+            'start_time' => '统计开始时间',
+            'end_time' => '统计结束以及封禁开始时间',
+            'ban_end_time' => '封禁结束时间',
+            'all_detect_number' => '累计违规次数',
+        ];
         $table_config['default_show_column'] = array_keys($table_config['total_column']);
         $table_config['ajax_url'] = 'ban/ajax';
         return $response->write(
@@ -41,49 +39,47 @@ class DetectBanLogController extends AdminController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax_log($request, $response, $args): ResponseInterface
+    public function ajax_log(Request $request, Response $response, array $args): ResponseInterface
     {
         $query = DetectBanLog::getTableDataFromAdmin(
             $request,
-            static function (&$order_field) {
+            static function (&$order_field): void {
                 if (in_array($order_field, ['ban_end_time'])) {
                     $order_field = 'end_time';
                 }
             }
         );
 
-        $data  = [];
+        $data = [];
         foreach ($query['datas'] as $value) {
             /** @var DetectBanLog $value */
 
-            if ($value->user() == null) {
+            if ($value->user() === null) {
                 DetectBanLog::user_is_null($value);
                 continue;
             }
-            $tempdata                         = [];
-            $tempdata['id']                   = $value->id;
-            $tempdata['user_id']              = $value->user_id;
-            $tempdata['user_name']            = $value->user_name;
-            $tempdata['email']                = $value->email;
-            $tempdata['detect_number']        = $value->detect_number;
-            $tempdata['ban_time']             = $value->ban_time;
-            $tempdata['start_time']           = $value->start_time();
-            $tempdata['end_time']             = $value->end_time();
-            $tempdata['ban_end_time']         = $value->ban_end_time();
-            $tempdata['all_detect_number']    = $value->all_detect_number;
+            $tempdata = [];
+            $tempdata['id'] = $value->id;
+            $tempdata['user_id'] = $value->user_id;
+            $tempdata['user_name'] = $value->user_name;
+            $tempdata['email'] = $value->email;
+            $tempdata['detect_number'] = $value->detect_number;
+            $tempdata['ban_time'] = $value->ban_time;
+            $tempdata['start_time'] = $value->start_time();
+            $tempdata['end_time'] = $value->end_time();
+            $tempdata['ban_end_time'] = $value->ban_end_time();
+            $tempdata['all_detect_number'] = $value->all_detect_number;
 
             $data[] = $tempdata;
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => DetectBanLog::count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => DetectBanLog::count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 }

+ 73 - 91
src/Controllers/Admin/DetectController.php

@@ -1,33 +1,31 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\Admin;
 
 use App\Controllers\AdminController;
 use App\Models\DetectLog;
 use App\Models\DetectRule;
 use App\Utils\Telegram;
-use Slim\Http\{
-    Request,
-    Response
-};
+use Slim\Http\Request;
+use Slim\Http\Response;
 
 class DetectController extends AdminController
 {
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function index($request, $response, $args)
+    public function index(Request $request, Response $response, array $args)
     {
-        $table_config['total_column'] = array(
-            'op'    => '操作',
-            'id'    => 'ID',
-            'name'  => '名称',
-            'text'  => '介绍',
+        $table_config['total_column'] = [
+            'op' => '操作',
+            'id' => 'ID',
+            'name' => '名称',
+            'text' => '介绍',
             'regex' => '正则表达式',
-            'type'  => '类型'
-        );
+            'type' => '类型',
+        ];
         $table_config['default_show_column'] = array_keys($table_config['total_column']);
         $table_config['ajax_url'] = 'detect/ajax';
         return $response->write(
@@ -38,50 +36,46 @@ class DetectController extends AdminController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax_rule($request, $response, $args)
+    public function ajax_rule(Request $request, Response $response, array $args)
     {
         $query = DetectRule::getTableDataFromAdmin(
             $request,
-            static function (&$order_field) {
+            static function (&$order_field): void {
                 if (in_array($order_field, ['op'])) {
                     $order_field = 'id';
                 }
             }
         );
 
-        $data  = [];
+        $data = [];
         foreach ($query['datas'] as $value) {
             /** @var DetectRule $value */
 
-            $tempdata             = [];
-            $tempdata['op']       = '<a class="btn btn-brand" href="/admin/detect/' . $value->id . '/edit">编辑</a> <a class="btn btn-brand-accent" id="delete" value="' . $value->id . '" href="javascript:void(0);" onClick="delete_modal_show(\'' . $value->id . '\')">删除</a>';
-            $tempdata['id']       = $value->id;
-            $tempdata['name']     = $value->name;
-            $tempdata['text']     = $value->text;
-            $tempdata['regex']    = $value->regex;
-            $tempdata['type']     = $value->type();
+            $tempdata = [];
+            $tempdata['op'] = '<a class="btn btn-brand" href="/admin/detect/' . $value->id . '/edit">编辑</a> <a class="btn btn-brand-accent" id="delete" value="' . $value->id . '" href="javascript:void(0);" onClick="delete_modal_show(\'' . $value->id . '\')">删除</a>';
+            $tempdata['id'] = $value->id;
+            $tempdata['name'] = $value->name;
+            $tempdata['text'] = $value->text;
+            $tempdata['regex'] = $value->regex;
+            $tempdata['type'] = $value->type();
 
             $data[] = $tempdata;
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => DetectRule::count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => DetectRule::count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function create($request, $response, $args)
+    public function create(Request $request, Response $response, array $args)
     {
         return $response->write(
             $this->view()
@@ -90,11 +84,9 @@ class DetectController extends AdminController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function add($request, $response, $args)
+    public function add(Request $request, Response $response, array $args)
     {
         $rule = new DetectRule();
         $rule->name = $request->getParam('name');
@@ -102,26 +94,24 @@ class DetectController extends AdminController
         $rule->regex = $request->getParam('regex');
         $rule->type = $request->getParam('type');
 
-        if (!$rule->save()) {
+        if (! $rule->save()) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '添加失败'
+                'msg' => '添加失败',
             ]);
         }
 
         Telegram::SendMarkdown('有新的审计规则:' . $rule->name);
         return $response->withJson([
             'ret' => 1,
-            'msg' => '添加成功'
+            'msg' => '添加成功',
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function edit($request, $response, $args)
+    public function edit(Request $request, Response $response, array $args)
     {
         $id = $args['id'];
         $rule = DetectRule::find($id);
@@ -133,11 +123,9 @@ class DetectController extends AdminController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function update($request, $response, $args)
+    public function update(Request $request, Response $response, array $args)
     {
         $id = $args['id'];
         $rule = DetectRule::find($id);
@@ -147,60 +135,56 @@ class DetectController extends AdminController
         $rule->regex = $request->getParam('regex');
         $rule->type = $request->getParam('type');
 
-        if (!$rule->save()) {
+        if (! $rule->save()) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '修改失败'
+                'msg' => '修改失败',
             ]);
         }
         Telegram::SendMarkdown('规则更新:' . PHP_EOL . $request->getParam('name'));
         return $response->withJson([
             'ret' => 1,
-            'msg' => '修改成功'
+            'msg' => '修改成功',
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function delete($request, $response, $args)
+    public function delete(Request $request, Response $response, array $args)
     {
         $id = $request->getParam('id');
         $rule = DetectRule::find($id);
-        if (!$rule->delete()) {
+        if (! $rule->delete()) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '删除失败'
+                'msg' => '删除失败',
             ]);
         }
         return $response->withJson([
             'ret' => 1,
-            'msg' => '删除成功'
+            'msg' => '删除成功',
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function log($request, $response, $args)
+    public function log(Request $request, Response $response, array $args)
     {
-        $table_config['total_column'] = array(
-            'id'          => 'ID',
-            'user_id'     => '用户ID',
-            'user_name'   => '用户名',
-            'node_id'     => '节点ID',
-            'node_name'   => '节点名',
-            'list_id'     => '规则ID',
-            'rule_name'   => '规则名',
-            'rule_text'   => '规则描述',
-            'rule_regex'  => '规则正则表达式',
-            'rule_type'   => '规则类型',
-            'datetime'    => '时间'
-        );
+        $table_config['total_column'] = [
+            'id' => 'ID',
+            'user_id' => '用户ID',
+            'user_name' => '用户名',
+            'node_id' => '节点ID',
+            'node_name' => '节点名',
+            'list_id' => '规则ID',
+            'rule_name' => '规则名',
+            'rule_text' => '规则描述',
+            'rule_regex' => '规则正则表达式',
+            'rule_type' => '规则类型',
+            'datetime' => '时间',
+        ];
         $table_config['default_show_column'] = array_keys($table_config['total_column']);
         $table_config['ajax_url'] = 'log/ajax';
         return $response->write(
@@ -211,15 +195,13 @@ class DetectController extends AdminController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax_log($request, $response, $args)
+    public function ajax_log(Request $request, Response $response, array $args)
     {
         $query = DetectLog::getTableDataFromAdmin(
             $request,
-            static function (&$order_field) {
+            static function (&$order_field): void {
                 if (in_array($order_field, ['node_name'])) {
                     $order_field = 'node_id';
                 }
@@ -232,43 +214,43 @@ class DetectController extends AdminController
             }
         );
 
-        $data  = [];
+        $data = [];
         foreach ($query['datas'] as $value) {
             /** @var DetectLog $value */
 
-            if ($value->rule() == null) {
+            if ($value->rule() === null) {
                 DetectLog::rule_is_null($value);
                 continue;
             }
-            if ($value->node() == null) {
+            if ($value->node() === null) {
                 DetectLog::node_is_null($value);
                 continue;
             }
-            if ($value->user() == null) {
+            if ($value->user() === null) {
                 DetectLog::user_is_null($value);
                 continue;
             }
-            $tempdata               = [];
-            $tempdata['id']         = $value->id;
-            $tempdata['user_id']    = $value->user_id;
-            $tempdata['user_name']  = $value->user_name();
-            $tempdata['node_id']    = $value->node_id;
-            $tempdata['node_name']  = $value->node_name();
-            $tempdata['list_id']    = $value->list_id;
-            $tempdata['rule_name']  = $value->rule_name();
-            $tempdata['rule_text']  = $value->rule_text();
+            $tempdata = [];
+            $tempdata['id'] = $value->id;
+            $tempdata['user_id'] = $value->user_id;
+            $tempdata['user_name'] = $value->user_name();
+            $tempdata['node_id'] = $value->node_id;
+            $tempdata['node_name'] = $value->node_name();
+            $tempdata['list_id'] = $value->list_id;
+            $tempdata['rule_name'] = $value->rule_name();
+            $tempdata['rule_text'] = $value->rule_text();
             $tempdata['rule_regex'] = $value->rule_regex();
-            $tempdata['rule_type']  = $value->rule_type();
-            $tempdata['datetime']   = $value->datetime();
+            $tempdata['rule_type'] = $value->rule_type();
+            $tempdata['datetime'] = $value->datetime();
 
             $data[] = $tempdata;
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => DetectLog::count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => DetectLog::count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 }

+ 38 - 46
src/Controllers/Admin/GConfigController.php

@@ -1,47 +1,43 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\Admin;
 
 use App\Controllers\AdminController;
 use App\Models\GConfig;
 use Psr\Http\Message\ResponseInterface;
-use Slim\Http\{
-    Request,
-    Response
-};
+use Slim\Http\Request;
+use Slim\Http\Response;
 
 class GConfigController extends AdminController
 {
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function update($request, $response, $args): ResponseInterface
+    public function update(Request $request, Response $response, array $args): ResponseInterface
     {
-        $key    = trim($args['key']);
-        $user   = $this->user;
+        $key = trim($args['key']);
+        $user = $this->user;
         $config = GConfig::where('key', '=', $key)->first();
-        if ($config != null && $config->setValue($request->getParam('value'), $user) === true) {
+        if ($config !== null && $config->setValue($request->getParam('value'), $user) === true) {
             return $response->withJson([
                 'ret' => 1,
-                'msg' => '修改成功'
+                'msg' => '修改成功',
             ]);
         }
         return $response->withJson([
             'ret' => 0,
-            'msg' => '修改失败'
+            'msg' => '修改失败',
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function edit($request, $response, $args): ResponseInterface
+    public function edit(Request $request, Response $response, array $args): ResponseInterface
     {
-        $key    = trim($args['key']);
+        $key = trim($args['key']);
         $config = GConfig::where('key', '=', $key)->first();
         return $response->write(
             $this->view()
@@ -49,25 +45,23 @@ class GConfigController extends AdminController
                 ->fetch('admin/config/edit.tpl')
         );
     }
-    
+
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function telegram($request, $response, $args): ResponseInterface
+    public function telegram(Request $request, Response $response, array $args): ResponseInterface
     {
-        $table_config['total_column'] = array(
-            'op'             => '操作',
-            'name'           => '配置名称',
-            'key'            => '配置名',
-            'value'          => '配置值',
-            'operator_id'    => '操作员 ID',
-            'operator_name'  => '操作员名称',
+        $table_config['total_column'] = [
+            'op' => '操作',
+            'name' => '配置名称',
+            'key' => '配置名',
+            'value' => '配置值',
+            'operator_id' => '操作员 ID',
+            'operator_name' => '操作员名称',
             'operator_email' => '操作员邮箱',
-            'last_update'    => '修改时间'
-        );
-        $table_config['default_show_column'] = array('op', 'name', 'value', 'last_update');
+            'last_update' => '修改时间',
+        ];
+        $table_config['default_show_column'] = ['op', 'name', 'value', 'last_update'];
         foreach ($table_config['total_column'] as $column => $value) {
             $table_config['default_show_column'][] = $column;
         }
@@ -80,15 +74,13 @@ class GConfigController extends AdminController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function telegram_ajax($request, $response, $args): ResponseInterface
+    public function telegram_ajax(Request $request, Response $response, array $args): ResponseInterface
     {
         $query = GConfig::getTableDataFromAdmin(
             $request,
-            static function (&$order_field) {
+            static function (&$order_field): void {
                 if (in_array($order_field, ['op'])) {
                     $order_field = 'id';
                 }
@@ -101,19 +93,19 @@ class GConfigController extends AdminController
             }
         );
 
-        $data  = [];
+        $data = [];
         foreach ($query['datas'] as $value) {
             /** @var GConfig $value */
 
-            $tempdata                   = [];
-            $tempdata['op']             = '<a class="btn btn-brand" href="/admin/config/update/' . $value->key . '/edit">编辑</a>';
-            $tempdata['name']           = $value->name;
-            $tempdata['key']            = $value->key;
-            $tempdata['value']          = $value->getValue();
-            $tempdata['operator_id']    = $value->operator_id;
-            $tempdata['operator_name']  = $value->operator_name;
+            $tempdata = [];
+            $tempdata['op'] = '<a class="btn btn-brand" href="/admin/config/update/' . $value->key . '/edit">编辑</a>';
+            $tempdata['name'] = $value->name;
+            $tempdata['key'] = $value->key;
+            $tempdata['value'] = $value->getValue();
+            $tempdata['operator_id'] = $value->operator_id;
+            $tempdata['operator_name'] = $value->operator_name;
             $tempdata['operator_email'] = $value->operator_email;
-            $tempdata['last_update']    = date('Y-m-d H:i:s', $value->last_update);
+            $tempdata['last_update'] = date('Y-m-d H:i:s', $value->last_update);
             if (strpos($value->key, '.bool.')) {
                 $tempdata['value'] = ($value->getValue() ? '开启' : '关闭');
             } else {
@@ -124,10 +116,10 @@ class GConfigController extends AdminController
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => GConfig::where('key', 'LIKE', "%Telegram%")->count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => GConfig::where('key', 'LIKE', '%Telegram%')->count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 }

+ 103 - 125
src/Controllers/Admin/IpController.php

@@ -1,43 +1,37 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\Admin;
 
 use App\Controllers\AdminController;
-use App\Models\{
-    BlockIp,
-    Ip,
-    LoginIp,
-    UnblockIp
-};
-use App\Utils\{
-    QQWry,
-    Tools
-};
-use Slim\Http\{
-    Request,
-    Response
-};
+use App\Models\BlockIp;
+use App\Models\Ip;
+use App\Models\LoginIp;
+use App\Models\UnblockIp;
+use App\Utils\QQWry;
+use App\Utils\Tools;
+use Slim\Http\Request;
+use Slim\Http\Response;
 
 class IpController extends AdminController
 {
     /**
      * 后台登录记录页面
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function index($request, $response, $args)
+    public function index(Request $request, Response $response, array $args)
     {
-        $table_config['total_column'] = array(
-            'id'        => 'ID',
-            'userid'    => '用户ID',
+        $table_config['total_column'] = [
+            'id' => 'ID',
+            'userid' => '用户ID',
             'user_name' => '用户名',
-            'ip'        => 'IP',
-            'location'  => '归属地',
-            'datetime'  => '时间',
-            'type'      => '类型'
-        );
+            'ip' => 'IP',
+            'location' => '归属地',
+            'datetime' => '时间',
+            'type' => '类型',
+        ];
         $table_config['default_show_column'] = array_keys($table_config['total_column']);
         $table_config['ajax_url'] = 'login/ajax';
         return $response->write(
@@ -50,15 +44,13 @@ class IpController extends AdminController
     /**
      * 后台登录记录页面 AJAX
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax_login($request, $response, $args)
+    public function ajax_login(Request $request, Response $response, array $args)
     {
         $query = LoginIp::getTableDataFromAdmin(
             $request,
-            static function (&$order_field) {
+            static function (&$order_field): void {
                 if (in_array($order_field, ['user_name'])) {
                     $order_field = 'userid';
                 }
@@ -68,55 +60,53 @@ class IpController extends AdminController
             }
         );
 
-        $data  = [];
+        $data = [];
         $QQWry = new QQWry();
         foreach ($query['datas'] as $value) {
             /** @var LoginIp $value */
 
-            if ($value->user() == null) {
+            if ($value->user() === null) {
                 LoginIp::user_is_null($value);
                 continue;
             }
-            $tempdata              = [];
-            $tempdata['id']        = $value->id;
-            $tempdata['userid']    = $value->userid;
+            $tempdata = [];
+            $tempdata['id'] = $value->id;
+            $tempdata['userid'] = $value->userid;
             $tempdata['user_name'] = $value->user_name();
-            $tempdata['ip']        = $value->ip;
-            $tempdata['location']  = $value->location($QQWry);
-            $tempdata['datetime']  = $value->datetime();
-            $tempdata['type']      = $value->type();
+            $tempdata['ip'] = $value->ip;
+            $tempdata['location'] = $value->location($QQWry);
+            $tempdata['datetime'] = $value->datetime();
+            $tempdata['type'] = $value->type();
 
             $data[] = $tempdata;
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => LoginIp::count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => LoginIp::count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 
     /**
      * 后台在线 IP 页面
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function alive($request, $response, $args)
+    public function alive(Request $request, Response $response, array $args)
     {
-        $table_config['total_column'] = array(
-            'id'        => 'ID',
-            'userid'    => '用户ID',
+        $table_config['total_column'] = [
+            'id' => 'ID',
+            'userid' => '用户ID',
             'user_name' => '用户名',
-            'nodeid'    => '节点ID',
+            'nodeid' => '节点ID',
             'node_name' => '节点名',
-            'ip'        => 'IP',
-            'location'  => '归属地',
-            'datetime'  => '时间',
-            'is_node'   => '是否为中转连接'
-        );
+            'ip' => 'IP',
+            'location' => '归属地',
+            'datetime' => '时间',
+            'is_node' => '是否为中转连接',
+        ];
         $table_config['default_show_column'] = array_keys($table_config['total_column']);
         $table_config['ajax_url'] = 'alive/ajax';
         return $response->write(
@@ -129,15 +119,13 @@ class IpController extends AdminController
     /**
      * 后台在线 IP 页面 AJAX
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax_alive($request, $response, $args)
+    public function ajax_alive(Request $request, Response $response, array $args)
     {
         $query = Ip::getTableDataFromAdmin(
             $request,
-            static function (&$order_field) {
+            static function (&$order_field): void {
                 if (in_array($order_field, ['user_name'])) {
                     $order_field = 'userid';
                 }
@@ -148,54 +136,52 @@ class IpController extends AdminController
                     $order_field = 'ip';
                 }
             },
-            static function ($query) {
+            static function ($query): void {
                 $query->where('datetime', '>=', time() - 60);
             }
         );
 
-        $data  = [];
+        $data = [];
         $QQWry = new QQWry();
         foreach ($query['datas'] as $value) {
             /** @var Ip $value */
 
-            $tempdata              = [];
-            $tempdata['id']        = $value->id;
-            $tempdata['userid']    = $value->userid;
+            $tempdata = [];
+            $tempdata['id'] = $value->id;
+            $tempdata['userid'] = $value->userid;
             $tempdata['user_name'] = $value->user_name();
-            $tempdata['nodeid']    = $value->nodeid;
+            $tempdata['nodeid'] = $value->nodeid;
             $tempdata['node_name'] = $value->node_name();
-            $tempdata['ip']        = Tools::getRealIp($value->ip);
-            $tempdata['location']  = $value->location($QQWry);
-            $tempdata['datetime']  = $value->datetime();
-            $tempdata['is_node']   = $value->is_node();
+            $tempdata['ip'] = Tools::getRealIp($value->ip);
+            $tempdata['location'] = $value->location($QQWry);
+            $tempdata['datetime'] = $value->datetime();
+            $tempdata['is_node'] = $value->is_node();
 
             $data[] = $tempdata;
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => Ip::count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => Ip::count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 
     /**
      * 节点被封IP
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function block($request, $response, $args)
+    public function block(Request $request, Response $response, array $args)
     {
-        $table_config['total_column'] = array(
-            'id'        => 'ID',
+        $table_config['total_column'] = [
+            'id' => 'ID',
             'node_name' => '节点名称',
-            'ip'        => 'IP',
-            'location'  => '归属地',
-            'datetime'  => '时间'
-        );
+            'ip' => 'IP',
+            'location' => '归属地',
+            'datetime' => '时间',
+        ];
         $table_config['default_show_column'] = array_keys($table_config['total_column']);
         $table_config['ajax_url'] = 'block/ajax';
         return $response->write(
@@ -208,15 +194,13 @@ class IpController extends AdminController
     /**
      * 节点被封IP AJAX
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax_block($request, $response, $args)
+    public function ajax_block(Request $request, Response $response, array $args)
     {
         $query = BlockIp::getTableDataFromAdmin(
             $request,
-            static function (&$order_field) {
+            static function (&$order_field): void {
                 if (in_array($order_field, ['node_name'])) {
                     $order_field = 'nodeid';
                 }
@@ -226,69 +210,65 @@ class IpController extends AdminController
             }
         );
 
-        $data  = [];
+        $data = [];
         $QQWry = new QQWry();
         foreach ($query['datas'] as $value) {
             /** @var BlockIp $value */
 
-            $tempdata              = [];
-            $tempdata['id']        = $value->id;
+            $tempdata = [];
+            $tempdata['id'] = $value->id;
             $tempdata['node_name'] = $value->node_name();
-            $tempdata['ip']        = $value->ip;
-            $tempdata['location']  = $value->location($QQWry);
-            $tempdata['datetime']  = $value->datetime();
+            $tempdata['ip'] = $value->ip;
+            $tempdata['location'] = $value->location($QQWry);
+            $tempdata['datetime'] = $value->datetime();
 
             $data[] = $tempdata;
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => BlockIp::count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => BlockIp::count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 
     /**
      * 解封IP
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function doUnblock($request, $response, $args)
+    public function doUnblock(Request $request, Response $response, array $args)
     {
-        $ip            = trim($request->getParam('ip'));
-        $BIP           = BlockIp::where('ip', $ip)->delete();
-        $UIP           = new UnblockIp();
-        $UIP->userid   = $this->user->id;
-        $UIP->ip       = $ip;
+        $ip = trim($request->getParam('ip'));
+        $BIP = BlockIp::where('ip', $ip)->delete();
+        $UIP = new UnblockIp();
+        $UIP->userid = $this->user->id;
+        $UIP->ip = $ip;
         $UIP->datetime = time();
         $UIP->save();
 
         return $response->withJson([
             'ret' => 1,
-            'msg' => '发送解封命令解封 ' . $ip . ' 成功'
+            'msg' => '发送解封命令解封 ' . $ip . ' 成功',
         ]);
     }
 
     /**
      * 解封IP记录
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function unblock($request, $response, $args)
+    public function unblock(Request $request, Response $response, array $args)
     {
-        $table_config['total_column'] = array(
-            'id'        => 'ID',
-            'userid'    => '用户ID',
+        $table_config['total_column'] = [
+            'id' => 'ID',
+            'userid' => '用户ID',
             'user_name' => '用户名',
-            'ip'        => 'IP',
-            'location'  => '归属地',
-            'datetime'  => '时间'
-        );
+            'ip' => 'IP',
+            'location' => '归属地',
+            'datetime' => '时间',
+        ];
         $table_config['default_show_column'] = array_keys($table_config['total_column']);
         $table_config['ajax_url'] = 'unblock/ajax';
         return $response->write(
@@ -301,15 +281,13 @@ class IpController extends AdminController
     /**
      * 解封IP记录 AJAX
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax_unblock($request, $response, $args)
+    public function ajax_unblock(Request $request, Response $response, array $args)
     {
         $query = UnblockIp::getTableDataFromAdmin(
             $request,
-            static function (&$order_field) {
+            static function (&$order_field): void {
                 if (in_array($order_field, ['user_name'])) {
                     $order_field = 'userid';
                 }
@@ -319,27 +297,27 @@ class IpController extends AdminController
             }
         );
 
-        $data  = [];
+        $data = [];
         $QQWry = new QQWry();
         foreach ($query['datas'] as $value) {
             /** @var UnblockIp $value */
 
-            $tempdata              = [];
-            $tempdata['id']        = $value->id;
-            $tempdata['userid']    = $value->userid;
+            $tempdata = [];
+            $tempdata['id'] = $value->id;
+            $tempdata['userid'] = $value->userid;
             $tempdata['user_name'] = $value->user_name();
-            $tempdata['ip']        = $value->ip;
-            $tempdata['location']  = $value->location($QQWry);
-            $tempdata['datetime']  = $value->datetime();
+            $tempdata['ip'] = $value->ip;
+            $tempdata['location'] = $value->location($QQWry);
+            $tempdata['datetime'] = $value->datetime();
 
             $data[] = $tempdata;
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => UnblockIp::count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => UnblockIp::count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 }

+ 102 - 121
src/Controllers/Admin/NodeController.php

@@ -1,55 +1,48 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\Admin;
 
 use App\Controllers\AdminController;
 use App\Models\Node;
-use App\Utils\{
-    Tools,
-    Telegram,
-    CloudflareDriver
-};
 use App\Services\Config;
 use Exception;
-use Slim\Http\{
-    Request,
-    Response
-};
 use Psr\Http\Message\ResponseInterface;
+use Request;
+use Tools;
 
 class NodeController extends AdminController
 {
     /**
      * 后台节点页面
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function index($request, $response, $args): ResponseInterface
+    public function index(Request $request, Response $response, array $args): ResponseInterface
     {
-        $table_config['total_column'] = array(
-            'op'                      => '操作',
-            'id'                      => 'ID',
-            'name'                    => '节点名称',
-            'type'                    => '显示与隐藏',
-            'sort'                    => '类型',
-            'server'                  => '节点地址',
-            'outaddress'              => '出口地址',
-            'node_ip'                 => '节点IP',
-            'info'                    => '节点信息',
-            'status'                  => '状态',
-            'traffic_rate'            => '流量比率',
-            'node_group'              => '节点群组',
-            'node_class'              => '节点等级',
-            'node_speedlimit'         => '节点限速/Mbps',
-            'node_bandwidth'          => '已走流量/GB',
-            'node_bandwidth_limit'    => '流量限制/GB',
+        $table_config['total_column'] = [
+            'op' => '操作',
+            'id' => 'ID',
+            'name' => '节点名称',
+            'type' => '显示与隐藏',
+            'sort' => '类型',
+            'server' => '节点地址',
+            'outaddress' => '出口地址',
+            'node_ip' => '节点IP',
+            'info' => '节点信息',
+            'status' => '状态',
+            'traffic_rate' => '流量比率',
+            'node_group' => '节点群组',
+            'node_class' => '节点等级',
+            'node_speedlimit' => '节点限速/Mbps',
+            'node_bandwidth' => '已走流量/GB',
+            'node_bandwidth_limit' => '流量限制/GB',
             'bandwidthlimit_resetday' => '流量重置日',
-            'node_heartbeat'          => '上一次活跃时间',
-            'mu_only'                 => '只启用单端口多用户'
-        );
-        $table_config['default_show_column'] = array('op', 'id', 'name', 'sort');
+            'node_heartbeat' => '上一次活跃时间',
+            'mu_only' => '只启用单端口多用户',
+        ];
+        $table_config['default_show_column'] = ['op', 'id', 'name', 'sort'];
         $table_config['ajax_url'] = 'node/ajax';
 
         return $response->write(
@@ -62,11 +55,9 @@ class NodeController extends AdminController
     /**
      * 后台创建节点页面
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function create($request, $response, $args): ResponseInterface
+    public function create(Request $request, Response $response, array $args): ResponseInterface
     {
         return $response->write(
             $this->view()
@@ -77,25 +68,23 @@ class NodeController extends AdminController
     /**
      * 后台添加节点
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function add($request, $response, $args): ResponseInterface
+    public function add(Request $request, Response $response, array $args): ResponseInterface
     {
-        $node                   = new Node();
-        $node->name             = $request->getParam('name');
-        $node->server           = trim($request->getParam('server'));
-        $node->mu_only          = $request->getParam('mu_only');
-        $node->traffic_rate     = $request->getParam('rate');
-        $node->info             = $request->getParam('info');
-        $node->type             = $request->getParam('type');
-        $node->node_group       = $request->getParam('group');
-        $node->node_speedlimit  = $request->getParam('node_speedlimit');
-        $node->status           = $request->getParam('status');
-        $node->sort             = $request->getParam('sort');
-
-        if ($request->getParam('custom_config') != null) {
+        $node = new Node();
+        $node->name = $request->getParam('name');
+        $node->server = trim($request->getParam('server'));
+        $node->mu_only = $request->getParam('mu_only');
+        $node->traffic_rate = $request->getParam('rate');
+        $node->info = $request->getParam('info');
+        $node->type = $request->getParam('type');
+        $node->node_group = $request->getParam('group');
+        $node->node_speedlimit = $request->getParam('node_speedlimit');
+        $node->status = $request->getParam('status');
+        $node->sort = $request->getParam('sort');
+
+        if ($request->getParam('custom_config') !== null) {
             $node->custom_config = $request->getParam('custom_config');
         } else {
             $node->custom_config = '{}';
@@ -111,20 +100,20 @@ class NodeController extends AdminController
             $success = $node->changeNodeIp($server_list[0]);
         }
 
-        if (!$success) {
+        if (! $success) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '获取节点IP失败,请检查您输入的节点地址是否正确!'
+                'msg' => '获取节点IP失败,请检查您输入的节点地址是否正确!',
             ]);
         }
 
-        $node->node_class                 = $request->getParam('class');
-        $node->node_bandwidth_limit       = $request->getParam('node_bandwidth_limit') * 1024 * 1024 * 1024;
-        $node->bandwidthlimit_resetday    = $request->getParam('bandwidthlimit_resetday');
+        $node->node_class = $request->getParam('class');
+        $node->node_bandwidth_limit = $request->getParam('node_bandwidth_limit') * 1024 * 1024 * 1024;
+        $node->bandwidthlimit_resetday = $request->getParam('bandwidthlimit_resetday');
 
         $node->save();
 
-        if ($_ENV['cloudflare_enable'] == true) {
+        if ($_ENV['cloudflare_enable'] === true) {
             $domain_name = explode('.' . $_ENV['cloudflare_name'], $node->server);
             CloudflareDriver::updateRecord($domain_name[0], $node->node_ip);
         }
@@ -142,7 +131,7 @@ class NodeController extends AdminController
                 return $response->withJson([
                     'ret' => 1,
                     'msg' => '节点添加成功,但Telegram通知失败',
-                    'node_id' => $node->id
+                    'node_id' => $node->id,
                 ]);
             }
         }
@@ -150,18 +139,16 @@ class NodeController extends AdminController
         return $response->withJson([
             'ret' => 1,
             'msg' => '节点添加成功',
-            'node_id' => $node->id
+            'node_id' => $node->id,
         ]);
     }
 
     /**
      * 后台编辑指定节点页面
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function edit($request, $response, $args): ResponseInterface
+    public function edit(Request $request, Response $response, array $args): ResponseInterface
     {
         $id = $args['id'];
         $node = Node::find($id);
@@ -175,25 +162,23 @@ class NodeController extends AdminController
     /**
      * 后台更新指定节点内容
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function update($request, $response, $args): ResponseInterface
+    public function update(Request $request, Response $response, array $args): ResponseInterface
     {
-        $id                     = $args['id'];
-        $node                   = Node::find($id);
-        $node->name             = $request->getParam('name');
-        $node->node_group       = $request->getParam('group');
-        $node->server           = trim($request->getParam('server'));
-        $node->mu_only          = $request->getParam('mu_only');
-        $node->traffic_rate     = $request->getParam('rate');
-        $node->info             = $request->getParam('info');
-        $node->node_speedlimit  = $request->getParam('node_speedlimit');
-        $node->type             = $request->getParam('type');
-        $node->sort             = $request->getParam('sort');
-
-        if ($request->getParam('custom_config') != null) {
+        $id = $args['id'];
+        $node = Node::find($id);
+        $node->name = $request->getParam('name');
+        $node->node_group = $request->getParam('group');
+        $node->server = trim($request->getParam('server'));
+        $node->mu_only = $request->getParam('mu_only');
+        $node->traffic_rate = $request->getParam('rate');
+        $node->info = $request->getParam('info');
+        $node->node_speedlimit = $request->getParam('node_speedlimit');
+        $node->type = $request->getParam('type');
+        $node->sort = $request->getParam('sort');
+
+        if ($request->getParam('custom_config') !== null) {
             $node->custom_config = $request->getParam('custom_config');
         } else {
             $node->custom_config = '{}';
@@ -210,17 +195,17 @@ class NodeController extends AdminController
             $success = $node->changeNodeIp($server_list[0]);
         }
 
-        if (!$success) {
+        if (! $success) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '更新节点IP失败,请检查您输入的节点地址是否正确!'
+                'msg' => '更新节点IP失败,请检查您输入的节点地址是否正确!',
             ]);
         }
 
-        $node->status                     = $request->getParam('status');
-        $node->node_class                 = $request->getParam('class');
-        $node->node_bandwidth_limit       = $request->getParam('node_bandwidth_limit') * 1024 * 1024 * 1024;
-        $node->bandwidthlimit_resetday    = $request->getParam('bandwidthlimit_resetday');
+        $node->status = $request->getParam('status');
+        $node->node_class = $request->getParam('class');
+        $node->node_bandwidth_limit = $request->getParam('node_bandwidth_limit') * 1024 * 1024 * 1024;
+        $node->bandwidthlimit_resetday = $request->getParam('bandwidthlimit_resetday');
 
         $node->save();
 
@@ -236,33 +221,31 @@ class NodeController extends AdminController
             } catch (Exception $e) {
                 return $response->withJson([
                     'ret' => 1,
-                    'msg' => '修改成功,但Telegram通知失败'
+                    'msg' => '修改成功,但Telegram通知失败',
                 ]);
             }
         }
 
         return $response->withJson([
             'ret' => 1,
-            'msg' => '修改成功'
+            'msg' => '修改成功',
         ]);
     }
 
     /**
      * 后台删除指定节点
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function delete($request, $response, $args): ResponseInterface
+    public function delete(Request $request, Response $response, array $args): ResponseInterface
     {
         $id = $request->getParam('id');
         $node = Node::find($id);
 
-        if (!$node->delete()) {
+        if (! $node->delete()) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '删除失败'
+                'msg' => '删除失败',
             ]);
         }
 
@@ -278,29 +261,27 @@ class NodeController extends AdminController
             } catch (Exception $e) {
                 return $response->withJson([
                     'ret' => 1,
-                    'msg' => '删除成功,但Telegram通知失败'
+                    'msg' => '删除成功,但Telegram通知失败',
                 ]);
             }
         }
 
         return $response->withJson([
             'ret' => 1,
-            'msg' => '删除成功'
+            'msg' => '删除成功',
         ]);
     }
 
     /**
      * 后台节点页面 AJAX
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax($request, $response, $args): ResponseInterface
+    public function ajax(Request $request, Response $response, array $args): ResponseInterface
     {
         $query = Node::getTableDataFromAdmin(
             $request,
-            static function (&$order_field) {
+            static function (&$order_field): void {
                 if (in_array($order_field, ['op'])) {
                     $order_field = 'id';
                 }
@@ -310,39 +291,39 @@ class NodeController extends AdminController
             }
         );
 
-        $data  = [];
+        $data = [];
         foreach ($query['datas'] as $value) {
             /** @var Node $value */
 
-            $tempdata                            = [];
-            $tempdata['op']                      = '<a class="btn btn-brand" href="/admin/node/' . $value->id . '/edit">编辑</a> <a class="btn btn-brand-accent" id="delete" value="' . $value->id . '" href="javascript:void(0);" onClick="delete_modal_show(\'' . $value->id . '\')">删除</a>';
-            $tempdata['id']                      = $value->id;
-            $tempdata['name']                    = $value->name;
-            $tempdata['type']                    = $value->type();
-            $tempdata['sort']                    = $value->sort();
-            $tempdata['server']                  = $value->server;
-            $tempdata['outaddress']              = $value->get_out_address();
-            $tempdata['node_ip']                 = $value->node_ip;
-            $tempdata['info']                    = $value->info;
-            $tempdata['status']                  = $value->status;
-            $tempdata['traffic_rate']            = $value->traffic_rate;
-            $tempdata['node_group']              = $value->node_group;
-            $tempdata['node_class']              = $value->node_class;
-            $tempdata['node_speedlimit']         = $value->node_speedlimit;
-            $tempdata['node_bandwidth']          = Tools::flowToGB($value->node_bandwidth);
-            $tempdata['node_bandwidth_limit']    = Tools::flowToGB($value->node_bandwidth_limit);
+            $tempdata = [];
+            $tempdata['op'] = '<a class="btn btn-brand" href="/admin/node/' . $value->id . '/edit">编辑</a> <a class="btn btn-brand-accent" id="delete" value="' . $value->id . '" href="javascript:void(0);" onClick="delete_modal_show(\'' . $value->id . '\')">删除</a>';
+            $tempdata['id'] = $value->id;
+            $tempdata['name'] = $value->name;
+            $tempdata['type'] = $value->type();
+            $tempdata['sort'] = $value->sort();
+            $tempdata['server'] = $value->server;
+            $tempdata['outaddress'] = $value->get_out_address();
+            $tempdata['node_ip'] = $value->node_ip;
+            $tempdata['info'] = $value->info;
+            $tempdata['status'] = $value->status;
+            $tempdata['traffic_rate'] = $value->traffic_rate;
+            $tempdata['node_group'] = $value->node_group;
+            $tempdata['node_class'] = $value->node_class;
+            $tempdata['node_speedlimit'] = $value->node_speedlimit;
+            $tempdata['node_bandwidth'] = Tools::flowToGB($value->node_bandwidth);
+            $tempdata['node_bandwidth_limit'] = Tools::flowToGB($value->node_bandwidth_limit);
             $tempdata['bandwidthlimit_resetday'] = $value->bandwidthlimit_resetday;
-            $tempdata['node_heartbeat']          = $value->node_heartbeat();
-            $tempdata['mu_only']                 = $value->mu_only();
+            $tempdata['node_heartbeat'] = $value->node_heartbeat();
+            $tempdata['mu_only'] = $value->mu_only();
 
             $data[] = $tempdata;
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => Node::count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => Node::count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 }

+ 60 - 74
src/Controllers/Admin/SettingController.php

@@ -1,35 +1,26 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\Admin;
 
 use App\Controllers\AdminController;
-use App\Models\{
-    Setting
-};
-use Slim\Http\{
-    Request,
-    Response
-};
-use App\Services\{
-    Mail
-};
 
 class SettingController extends AdminController
 {
     public function index($request, $response, $args)
     {
-        $config = array();
+        $config = [];
         $settings = Setting::get(['item', 'value', 'type']);
-        
-        foreach ($settings as $setting)
-        {
-        	if ($setting->type == 'bool') {
+
+        foreach ($settings as $setting) {
+            if ($setting->type === 'bool') {
                 $config[$setting->item] = (bool) $setting->value;
             } else {
                 $config[$setting->item] = (string) $setting->value;
             }
         }
-        
+
         return $response->write(
             $this->view()
                 //->registerClass('Setting', Setting::class)
@@ -39,120 +30,119 @@ class SettingController extends AdminController
                 ->display('admin/setting.tpl')
         );
     }
-    
+
     public function save($request, $response, $args)
     {
         $class = $request->getParam('class');
-        
+
         switch ($class) {
             // 支付
             case 'f2f_pay':
-                $list = array('f2f_pay_app_id', 'f2f_pay_pid', 'f2f_pay_public_key', 'f2f_pay_private_key', 'f2f_pay_notify_url');
+                $list = ['f2f_pay_app_id', 'f2f_pay_pid', 'f2f_pay_public_key', 'f2f_pay_private_key', 'f2f_pay_notify_url'];
                 break;
             case 'vmq_pay':
-                $list = array('vmq_gateway', 'vmq_key');
+                $list = ['vmq_gateway', 'vmq_key'];
                 break;
             case 'payjs_pay':
-                $list = array('payjs_mchid', 'payjs_key');
+                $list = ['payjs_mchid', 'payjs_key'];
                 break;
             case 'theadpay':
-                $list = array('theadpay_url', 'theadpay_mchid', 'theadpay_key');
+                $list = ['theadpay_url', 'theadpay_mchid', 'theadpay_key'];
                 break;
             case 'coinpay':
-                $list = array('coinpay_appid', 'coinpay_secret');
+                $list = ['coinpay_appid', 'coinpay_secret'];
                 break;
             case 'paymentwall':
-                $list = array('pmw_publickey', 'pmw_privatekey', 'pmw_widget', 'pmw_height');
+                $list = ['pmw_publickey', 'pmw_privatekey', 'pmw_widget', 'pmw_height'];
                 break;
             case 'stripe':
-                $list = array('stripe_card', 'stripe_currency', 'stripe_pk', 'stripe_sk', 'stripe_webhook_key', 'stripe_min_recharge', 'stripe_max_recharge');
+                $list = ['stripe_card', 'stripe_currency', 'stripe_pk', 'stripe_sk', 'stripe_webhook_key', 'stripe_min_recharge', 'stripe_max_recharge'];
                 break;
             // 邮件
             case 'mail':
-                $list = array('mail_driver');
+                $list = ['mail_driver'];
                 break;
             case 'smtp':
-                $list = array('smtp_host', 'smtp_username', 'smtp_password', 'smtp_port', 'smtp_name', 'smtp_sender', 'smtp_ssl', 'smtp_bbc');
+                $list = ['smtp_host', 'smtp_username', 'smtp_password', 'smtp_port', 'smtp_name', 'smtp_sender', 'smtp_ssl', 'smtp_bbc'];
                 break;
             case 'mailgun':
-                $list = array('mailgun_key', 'mailgun_domain', 'mailgun_sender');
+                $list = ['mailgun_key', 'mailgun_domain', 'mailgun_sender'];
                 break;
             case 'sendgrid':
-                $list = array('sendgrid_key', 'sendgrid_sender', 'sendgrid_name');
+                $list = ['sendgrid_key', 'sendgrid_sender', 'sendgrid_name'];
                 break;
             case 'ses':
-                $list = array('aws_access_key_id', 'aws_secret_access_key');
+                $list = ['aws_access_key_id', 'aws_secret_access_key'];
                 break;
             // 验证码
             case 'verify_code':
-                $list = array('captcha_provider', 'enable_reg_captcha', 'enable_login_captcha', 'enable_checkin_captcha');
+                $list = ['captcha_provider', 'enable_reg_captcha', 'enable_login_captcha', 'enable_checkin_captcha'];
                 break;
             case 'verify_code_recaptcha':
-                $list = array('recaptcha_sitekey', 'recaptcha_secret');
+                $list = ['recaptcha_sitekey', 'recaptcha_secret'];
                 break;
             case 'verify_code_geetest':
-                $list = array('geetest_id', 'geetest_key');
+                $list = ['geetest_id', 'geetest_key'];
                 break;
             // 备份
             case 'email_backup':
-                $list = array('auto_backup_email', 'auto_backup_password', 'auto_backup_notify');
+                $list = ['auto_backup_email', 'auto_backup_password', 'auto_backup_notify'];
                 break;
             // 客户服务
             case 'admin_contact':
-                $list = array('enable_admin_contact', 'admin_contact1', 'admin_contact2', 'admin_contact3');
+                $list = ['enable_admin_contact', 'admin_contact1', 'admin_contact2', 'admin_contact3'];
                 break;
             case 'web_customer_service_system':
-                $list = array('live_chat', 'tawk_id', 'crisp_id', 'livechat_id', 'mylivechat_id');
+                $list = ['live_chat', 'tawk_id', 'crisp_id', 'livechat_id', 'mylivechat_id'];
                 break;
             // 个性化
             case 'background_image':
-                $list = array('user_center_bg', 'admin_center_bg', 'user_center_bg_addr', 'admin_center_bg_addr');
+                $list = ['user_center_bg', 'admin_center_bg', 'user_center_bg_addr', 'admin_center_bg_addr'];
                 break;
             // 注册设置
             case 'register':
-                $list = array('reg_mode', 'reg_email_verify', 'email_verify_ttl', 'email_verify_ip_limit');
+                $list = ['reg_mode', 'reg_email_verify', 'email_verify_ttl', 'email_verify_ip_limit'];
                 break;
             case 'register_default_value':
-                $list = array('sign_up_for_free_traffic', 'sign_up_for_free_time', 'sign_up_for_class', 'sign_up_for_class_time', 'sign_up_for_invitation_codes', 'connection_device_limit', 'connection_rate_limit', 'sign_up_for_method', 'sign_up_for_protocol', 'sign_up_for_protocol_param', 'sign_up_for_obfs', 'sign_up_for_obfs_param', 'sign_up_for_daily_report');
+                $list = ['sign_up_for_free_traffic', 'sign_up_for_free_time', 'sign_up_for_class', 'sign_up_for_class_time', 'sign_up_for_invitation_codes', 'connection_device_limit', 'connection_rate_limit', 'sign_up_for_method', 'sign_up_for_protocol', 'sign_up_for_protocol_param', 'sign_up_for_obfs', 'sign_up_for_obfs_param', 'sign_up_for_daily_report'];
                 break;
             // 邀请设置
             case 'invitation_reward':
-                $list = array('invitation_to_register_balance_reward', 'invitation_to_register_traffic_reward');
+                $list = ['invitation_to_register_balance_reward', 'invitation_to_register_traffic_reward'];
                 break;
             // 返利设置
             case 'rebate_mode':
-                $list = array('invitation_mode', 'invite_rebate_mode', 'rebate_ratio', 'rebate_frequency_limit', 'rebate_amount_limit', 'rebate_time_range_limit');
+                $list = ['invitation_mode', 'invite_rebate_mode', 'rebate_ratio', 'rebate_frequency_limit', 'rebate_amount_limit', 'rebate_time_range_limit'];
                 break;
         }
-        
-        foreach ($list as $item)
-        {
+
+        foreach ($list as $item) {
             $setting = Setting::where('item', '=', $item)->first();
-            
-            if ($setting->type == 'array') {
-                $setting->value = json_encode($request->getParam("$item"));
+
+            if ($setting->type === 'array') {
+                $setting->value = json_encode($request->getParam("${item}"));
             } else {
-                $setting->value = $request->getParam("$item");
+                $setting->value = $request->getParam("${item}");
             }
 
-            if(!$setting->save()) {
+            if (! $setting->save()) {
                 return $response->withJson([
                     'ret' => 0,
-                    'msg' => "保存 $item 时出错"
+                    'msg' => "保存 ${item} 时出错",
                 ]);
             }
         }
-        
+
         return $response->withJson([
             'ret' => 1,
-            'msg' => "保存成功"
+            'msg' => '保存成功',
         ]);
     }
 
     public function test($request, $response, $args)
     {
         $to = $request->getParam('recipient');
-        
+
         try {
             Mail::send(
                 $to,
@@ -164,46 +154,42 @@ class SettingController extends AdminController
         } catch (Exception $e) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '测试邮件发送失败'
+                'msg' => '测试邮件发送失败',
             ]);
         }
         return $response->withJson([
             'ret' => 1,
-            'msg' => '测试邮件发送成功'
+            'msg' => '测试邮件发送成功',
         ]);
     }
 
     public function return_gateways_list()
     {
-        $payment_gateways = array(
+        return [
             // 网关名 网关代号
-            "CoinPay" => "coinpay",
-            "当面付" => "f2fpay",
-            "PayJs" => "payjs",
-            "PaymentWall" => "paymentwall",
-            "Stripe" => "stripe",
-            "TheadPay" => "theadpay",
-            "V免签" => "vmqpay"
-        );
-
-        return $payment_gateways;
+            'CoinPay' => 'coinpay',
+            '当面付' => 'f2fpay',
+            'PayJs' => 'payjs',
+            'PaymentWall' => 'paymentwall',
+            'Stripe' => 'stripe',
+            'TheadPay' => 'theadpay',
+            'V免签' => 'vmqpay',
+        ];
     }
 
     public function return_active_gateways()
     {
         $payment_gateways = Setting::where('item', '=', 'payment_gateway')->first();
-        $active_gateways = json_decode($payment_gateways->value);
-        return $active_gateways;
+        return json_decode($payment_gateways->value);
     }
 
     public function payment($request, $response, $args)
     {
-        $gateway_in_use = array();
+        $gateway_in_use = [];
         $payment_gateways = self::return_gateways_list();
-        foreach ($payment_gateways as $key => $value)
-        {
-            $payment_switch = $request->getParam("$value");
-            if ($payment_switch == '1') {
+        foreach ($payment_gateways as $key => $value) {
+            $payment_switch = $request->getParam("${value}");
+            if ($payment_switch === '1') {
                 array_push($gateway_in_use, $value);
             }
         }
@@ -214,7 +200,7 @@ class SettingController extends AdminController
 
         return $response->withJson([
             'ret' => 1,
-            'msg' => "保存成功"
+            'msg' => '保存成功',
         ]);
     }
 }

+ 96 - 120
src/Controllers/Admin/ShopController.php

@@ -1,40 +1,34 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\Admin;
 
 use App\Controllers\AdminController;
-use App\Models\{
-    Shop,
-    Bought
-};
-use Slim\Http\{
-    Request,
-    Response
-};
+use Request;
+use Shop;
 
 class ShopController extends AdminController
 {
     /**
      * 后台商品页面
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function index($request, $response, $args)
+    public function index(Request $request, Response $response, array $args)
     {
-        $table_config['total_column'] = array(
-            'op'                    => '操作',
-            'id'                    => 'ID',
-            'name'                  => '商品名称',
-            'price'                 => '价格',
-            'content'               => '商品内容',
-            'auto_renew'            => '自动续费',
-            'auto_reset_bandwidth'  => '续费时是否重置流量',
-            'status'                => '状态',
-            'period_sales'          => '周期销量'
-        );
-        $table_config['default_show_column'] = array();
+        $table_config['total_column'] = [
+            'op' => '操作',
+            'id' => 'ID',
+            'name' => '商品名称',
+            'price' => '价格',
+            'content' => '商品内容',
+            'auto_renew' => '自动续费',
+            'auto_reset_bandwidth' => '续费时是否重置流量',
+            'status' => '状态',
+            'period_sales' => '周期销量',
+        ];
+        $table_config['default_show_column'] = [];
         foreach ($table_config['total_column'] as $column => $value) {
             $table_config['default_show_column'][] = $column;
         }
@@ -49,11 +43,9 @@ class ShopController extends AdminController
     /**
      * 后台创建新商品页面
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function create($request, $response, $args)
+    public function create(Request $request, Response $response, array $args)
     {
         return $response->write(
             $this->view()
@@ -64,11 +56,9 @@ class ShopController extends AdminController
     /**
      * 后台添加新商品
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function add($request, $response, $args)
+    public function add(Request $request, Response $response, array $args)
     {
         $shop = new Shop();
         $shop->name = $request->getParam('name');
@@ -76,33 +66,33 @@ class ShopController extends AdminController
         $shop->auto_renew = $request->getParam('auto_renew');
         $shop->auto_reset_bandwidth = $request->getParam('auto_reset_bandwidth');
 
-        $content = array();
-        if ($request->getParam('bandwidth') != 0) {
+        $content = [];
+        if ($request->getParam('bandwidth') !== 0) {
             $content['bandwidth'] = $request->getParam('bandwidth');
         }
 
-        if ($request->getParam('expire') != 0) {
+        if ($request->getParam('expire') !== 0) {
             $content['expire'] = $request->getParam('expire');
         }
 
-        if ($request->getParam('class') != 0 && $request->getParam('class_expire') != 0) {
+        if ($request->getParam('class') !== 0 && $request->getParam('class_expire') !== 0) {
             $content['class'] = $request->getParam('class');
             $content['class_expire'] = $request->getParam('class_expire');
         }
 
-        if ($request->getParam('reset') != 0) {
+        if ($request->getParam('reset') !== 0) {
             $content['reset'] = $request->getParam('reset');
         }
 
-        if ($request->getParam('reset_value') != 0) {
+        if ($request->getParam('reset_value') !== 0) {
             $content['reset_value'] = $request->getParam('reset_value');
         }
 
-        if ($request->getParam('reset_exp') != 0) {
+        if ($request->getParam('reset_exp') !== 0) {
             $content['reset_exp'] = $request->getParam('reset_exp');
         }
 
-        if ($request->getParam('traffic_package') != 0) {
+        if ($request->getParam('traffic_package') !== 0) {
             $content['traffic_package'] = $request->getParam('traffic_package');
         }
 
@@ -110,32 +100,30 @@ class ShopController extends AdminController
 
         $content['connector'] = $request->getParam('connector');
 
-        if ($request->getParam('content_extra') != '') {
+        if ($request->getParam('content_extra') !== '') {
             $content['content_extra'] = $request->getParam('content_extra');
         }
 
         $shop->content = $content;
 
-        if (!$shop->save()) {
+        if (! $shop->save()) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '添加失败'
+                'msg' => '添加失败',
             ]);
         }
         return $response->withJson([
             'ret' => 1,
-            'msg' => '添加成功'
+            'msg' => '添加成功',
         ]);
     }
 
     /**
      * 后台编辑指定商品
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function edit($request, $response, $args)
+    public function edit(Request $request, Response $response, array $args)
     {
         $id = $args['id'];
         $shop = Shop::find($id);
@@ -149,11 +137,9 @@ class ShopController extends AdminController
     /**
      * 后台更新指定商品内容
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function update($request, $response, $args)
+    public function update(Request $request, Response $response, array $args)
     {
         $id = $args['id'];
         $shop = Shop::find($id);
@@ -162,7 +148,7 @@ class ShopController extends AdminController
         $shop->price = $request->getParam('price');
         $shop->auto_renew = $request->getParam('auto_renew');
 
-        if ($shop->auto_reset_bandwidth == 1 && $request->getParam('auto_reset_bandwidth') == 0) {
+        if ($shop->auto_reset_bandwidth === 1 && $request->getParam('auto_reset_bandwidth') === 0) {
             $boughts = Bought::where('shopid', $id)->get();
 
             foreach ($boughts as $bought) {
@@ -175,69 +161,67 @@ class ShopController extends AdminController
         $shop->status = 1;
 
         $content = [];
-        if ($request->getParam('bandwidth') != 0) {
+        if ($request->getParam('bandwidth') !== 0) {
             $content['bandwidth'] = $request->getParam('bandwidth');
         }
 
-        if ($request->getParam('expire') != 0) {
+        if ($request->getParam('expire') !== 0) {
             $content['expire'] = $request->getParam('expire');
         }
 
-        if ($request->getParam('class') != 0 && $request->getParam('class_expire') != 0) {
+        if ($request->getParam('class') !== 0 && $request->getParam('class_expire') !== 0) {
             $content['class'] = $request->getParam('class');
             $content['class_expire'] = $request->getParam('class_expire');
         }
 
-        if ($request->getParam('reset') != 0) {
+        if ($request->getParam('reset') !== 0) {
             $content['reset'] = $request->getParam('reset');
         }
 
-        if ($request->getParam('reset_value') != 0) {
+        if ($request->getParam('reset_value') !== 0) {
             $content['reset_value'] = $request->getParam('reset_value');
         }
 
-        if ($request->getParam('reset_exp') != 0) {
+        if ($request->getParam('reset_exp') !== 0) {
             $content['reset_exp'] = $request->getParam('reset_exp');
         }
 
-        if ($request->getParam('traffic_package') != 0) {
+        if ($request->getParam('traffic_package') !== 0) {
             $content['traffic_package'] = $request->getParam('traffic_package');
         }
 
         $content['speedlimit'] = $request->getParam('speedlimit');
         $content['connector'] = $request->getParam('connector');
-        if ($request->getParam('content_extra') != '') {
+        if ($request->getParam('content_extra') !== '') {
             $content['content_extra'] = $request->getParam('content_extra');
         }
         $shop->content = $content;
-        if (!$shop->save()) {
+        if (! $shop->save()) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '保存失败'
+                'msg' => '保存失败',
             ]);
         }
         return $response->withJson([
             'ret' => 1,
-            'msg' => '保存成功'
+            'msg' => '保存成功',
         ]);
     }
 
     /**
      * 后台下架指定商品
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function deleteGet($request, $response, $args)
+    public function deleteGet(Request $request, Response $response, array $args)
     {
         $id = $request->getParam('id');
         $shop = Shop::find($id);
         $shop->status = 0;
-        if (!$shop->save()) {
+        if (! $shop->save()) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '下架失败'
+                'msg' => '下架失败',
             ]);
         }
         $boughts = Bought::where('shopid', $id)->get();
@@ -247,31 +231,29 @@ class ShopController extends AdminController
         }
         return $response->withJson([
             'ret' => 1,
-            'msg' => '下架成功'
+            'msg' => '下架成功',
         ]);
     }
 
     /**
      * 后台购买记录页面
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function bought($request, $response, $args)
+    public function bought(Request $request, Response $response, array $args)
     {
-        $table_config['total_column'] = array(
-            'op'                    => '操作',
-            'id'                    => 'ID',
-            'datetime'              => '购买日期',
-            'content'               => '内容',
-            'price'                 => '价格',
-            'userid'                => '用户ID',
-            'user_name'             => '用户名',
-            'renew'                 => '自动续费时间',
-            'auto_reset_bandwidth'  => '续费时是否重置流量'
-        );
-        $table_config['default_show_column'] = array();
+        $table_config['total_column'] = [
+            'op' => '操作',
+            'id' => 'ID',
+            'datetime' => '购买日期',
+            'content' => '内容',
+            'price' => '价格',
+            'userid' => '用户ID',
+            'user_name' => '用户名',
+            'renew' => '自动续费时间',
+            'auto_reset_bandwidth' => '续费时是否重置流量',
+        ];
+        $table_config['default_show_column'] = [];
         foreach ($table_config['total_column'] as $column => $value) {
             $table_config['default_show_column'][] = $column;
         }
@@ -286,83 +268,77 @@ class ShopController extends AdminController
     /**
      * 后台退订指定购买记录的自动续费
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function deleteBoughtGet($request, $response, $args)
+    public function deleteBoughtGet(Request $request, Response $response, array $args)
     {
         $id = $request->getParam('id');
         $shop = Bought::find($id);
         $shop->renew = 0;
-        if (!$shop->save()) {
+        if (! $shop->save()) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '退订失败'
+                'msg' => '退订失败',
             ]);
         }
         return $response->withJson([
             'ret' => 1,
-            'msg' => '退订成功'
+            'msg' => '退订成功',
         ]);
     }
 
     /**
      * 后台商品页面 AJAX
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax_shop($request, $response, $args)
+    public function ajax_shop(Request $request, Response $response, array $args)
     {
         $query = Shop::getTableDataFromAdmin(
             $request,
-            static function (&$order_field) {
+            static function (&$order_field): void {
                 if (in_array($order_field, ['op', 'period_sales'])) {
                     $order_field = 'id';
                 }
             }
         );
 
-        $data  = [];
+        $data = [];
         foreach ($query['datas'] as $value) {
             /** @var Shop $value */
 
-            $tempdata                         = [];
-            $tempdata['op']                   = '<a class="btn btn-brand" href="/admin/shop/' . $value->id . '/edit">编辑</a> <a class = "btn btn-brand-accent" ' . ($value->status == 0 ? 'disabled' : 'id="row_delete_' . $value->id . '" href="javascript:void(0);" onClick="delete_modal_show(\'' . $value->id . '\')"') . '>下架</a>';
-            $tempdata['id']                   = $value->id;
-            $tempdata['name']                 = $value->name;
-            $tempdata['price']                = $value->price;
-            $tempdata['content']              = $value->content();
-            $tempdata['auto_renew']           = $value->auto_renew();
+            $tempdata = [];
+            $tempdata['op'] = '<a class="btn btn-brand" href="/admin/shop/' . $value->id . '/edit">编辑</a> <a class = "btn btn-brand-accent" ' . ($value->status === 0 ? 'disabled' : 'id="row_delete_' . $value->id . '" href="javascript:void(0);" onClick="delete_modal_show(\'' . $value->id . '\')"') . '>下架</a>';
+            $tempdata['id'] = $value->id;
+            $tempdata['name'] = $value->name;
+            $tempdata['price'] = $value->price;
+            $tempdata['content'] = $value->content();
+            $tempdata['auto_renew'] = $value->auto_renew();
             $tempdata['auto_reset_bandwidth'] = $value->auto_reset_bandwidth();
-            $tempdata['status']               = $value->status();
-            $tempdata['period_sales']         = $value->getSales();
+            $tempdata['status'] = $value->status();
+            $tempdata['period_sales'] = $value->getSales();
 
             $data[] = $tempdata;
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => Shop::count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => Shop::count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 
     /**
      * 后台购买记录 AJAX
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax_bought($request, $response, $args)
+    public function ajax_bought(Request $request, Response $response, array $args)
     {
         $query = Bought::getTableDataFromAdmin(
             $request,
-            static function (&$order_field) {
+            static function (&$order_field): void {
                 if (in_array($order_field, ['op'])) {
                     $order_field = 'id';
                 }
@@ -375,29 +351,29 @@ class ShopController extends AdminController
             }
         );
 
-        $data  = [];
+        $data = [];
         foreach ($query['datas'] as $value) {
             /** @var Bought $value */
 
-            $tempdata                         = [];
-            $tempdata['op']                   = '<a class="btn btn-brand-accent" ' . ($value->renew == 0 ? 'disabled' : ' id="row_delete_' . $value->id . '" href="javascript:void(0);" onClick="delete_modal_show(\'' . $value->id . '\')"') . '>中止</a>';
-            $tempdata['id']                   = $value->id;
-            $tempdata['datetime']             = $value->datetime();
-            $tempdata['content']              = $value->content();
-            $tempdata['price']                = $value->price;
-            $tempdata['userid']               = $value->userid;
-            $tempdata['user_name']            = $value->user_name();
-            $tempdata['renew']                = $value->renew();
+            $tempdata = [];
+            $tempdata['op'] = '<a class="btn btn-brand-accent" ' . ($value->renew === 0 ? 'disabled' : ' id="row_delete_' . $value->id . '" href="javascript:void(0);" onClick="delete_modal_show(\'' . $value->id . '\')"') . '>中止</a>';
+            $tempdata['id'] = $value->id;
+            $tempdata['datetime'] = $value->datetime();
+            $tempdata['content'] = $value->content();
+            $tempdata['price'] = $value->price;
+            $tempdata['userid'] = $value->userid;
+            $tempdata['user_name'] = $value->user_name();
+            $tempdata['renew'] = $value->renew();
             $tempdata['auto_reset_bandwidth'] = $value->auto_reset_bandwidth();
 
             $data[] = $tempdata;
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => Bought::count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => Bought::count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 }

+ 32 - 36
src/Controllers/Admin/SubscribeLogController.php

@@ -1,38 +1,36 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\Admin;
 
 use App\Controllers\AdminController;
 use App\Models\UserSubscribeLog;
 use App\Utils\QQWry;
 use Psr\Http\Message\ResponseInterface;
-use Slim\Http\{
-    Request,
-    Response
-};
+use Slim\Http\Request;
+use Slim\Http\Response;
 
 class SubscribeLogController extends AdminController
 {
     /**
      * 后台订阅记录页面
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function index($request, $response, $args): ResponseInterface
+    public function index(Request $request, Response $response, array $args): ResponseInterface
     {
-        $table_config['total_column'] = array(
-            'id'                  => 'ID',
-            'user_name'           => '用户名',
-            'user_id'             => '用户ID',
-            'email'               => '用户邮箱',
-            'subscribe_type'      => '类型',
-            'request_ip'          => 'IP',
-            'location'            => '归属地',
-            'request_time'        => '时间',
-            'request_user_agent'  => 'User-Agent'
-        );
+        $table_config['total_column'] = [
+            'id' => 'ID',
+            'user_name' => '用户名',
+            'user_id' => '用户ID',
+            'email' => '用户邮箱',
+            'subscribe_type' => '类型',
+            'request_ip' => 'IP',
+            'location' => '归属地',
+            'request_time' => '时间',
+            'request_user_agent' => 'User-Agent',
+        ];
         $table_config['default_show_column'] = ['id', 'user_name', 'subscribe_type', 'request_ip', 'location', 'request_time'];
         $table_config['ajax_url'] = 'subscribe/ajax';
         return $response->write(
@@ -45,49 +43,47 @@ class SubscribeLogController extends AdminController
     /**
      * 后台订阅记录页面 AJAX
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax_subscribe_log($request, $response, $args): ResponseInterface
+    public function ajax_subscribe_log(Request $request, Response $response, array $args): ResponseInterface
     {
         $query = UserSubscribeLog::getTableDataFromAdmin(
             $request,
-            static function (&$order_field) {
+            static function (&$order_field): void {
                 if (in_array($order_field, ['location'])) {
                     $order_field = 'request_ip';
                 }
             }
         );
 
-        $data  = [];
+        $data = [];
         $QQWry = new QQWry();
         foreach ($query['datas'] as $value) {
             /** @var UserSubscribeLog $value */
 
-            if ($value->user() == null) {
+            if ($value->user() === null) {
                 UserSubscribeLog::user_is_null($value);
                 continue;
             }
-            $tempdata                       = [];
-            $tempdata['id']                 = $value->id;
-            $tempdata['user_name']          = $value->user_name;
-            $tempdata['user_id']            = $value->user_id;
-            $tempdata['email']              = $value->email;
-            $tempdata['subscribe_type']     = $value->subscribe_type;
-            $tempdata['request_ip']         = $value->request_ip;
-            $tempdata['location']           = $value->location($QQWry);
-            $tempdata['request_time']       = $value->request_time;
+            $tempdata = [];
+            $tempdata['id'] = $value->id;
+            $tempdata['user_name'] = $value->user_name;
+            $tempdata['user_id'] = $value->user_id;
+            $tempdata['email'] = $value->email;
+            $tempdata['subscribe_type'] = $value->subscribe_type;
+            $tempdata['request_ip'] = $value->request_ip;
+            $tempdata['location'] = $value->location($QQWry);
+            $tempdata['request_time'] = $value->request_time;
             $tempdata['request_user_agent'] = $value->request_user_agent;
 
             $data[] = $tempdata;
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => UserSubscribeLog::count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => UserSubscribeLog::count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 }

+ 69 - 83
src/Controllers/Admin/TicketController.php

@@ -1,43 +1,37 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\Admin;
 
 use App\Controllers\AdminController;
-use App\Models\{
-    User,
-    Ticket
-};
 use App\Utils\Tools;
+use Request;
+use User;
 use voku\helper\AntiXSS;
-use Slim\Http\{
-    Request,
-    Response
-};
 
 class TicketController extends AdminController
 {
     /**
      * 后台工单页面
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function index($request, $response, $args)
+    public function index(Request $request, Response $response, array $args)
     {
-        $table_config['total_column'] = array(
-            'op'        => '操作',
-            'id'        => 'ID',
-            'datetime'  => '时间',
-            'title'     => '标题',
-            'userid'    => '用户ID',
+        $table_config['total_column'] = [
+            'op' => '操作',
+            'id' => 'ID',
+            'datetime' => '时间',
+            'title' => '标题',
+            'userid' => '用户ID',
             'user_name' => '用户名',
-            'status'    => '状态'
-        );
-        $table_config['default_show_column'] = array(
+            'status' => '状态',
+        ];
+        $table_config['default_show_column'] = [
             'op', 'id',
-            'datetime', 'title', 'userid', 'user_name', 'status'
-        );
+            'datetime', 'title', 'userid', 'user_name', 'status',
+        ];
         $table_config['ajax_url'] = 'ticket/ajax';
         return $response->write(
             $this->view()
@@ -49,35 +43,33 @@ class TicketController extends AdminController
     /**
      * 後臺創建新工單
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function add($request, $response, $args)
+    public function add(Request $request, Response $response, array $args)
     {
-        $title    = $request->getParam('title');
-        $content  = $request->getParam('content');
+        $title = $request->getParam('title');
+        $content = $request->getParam('content');
         $markdown = $request->getParam('markdown');
-        $userid   = $request->getParam('userid');
-        if ($title == '' || $content == '') {
+        $userid = $request->getParam('userid');
+        if ($title === '' || $content === '') {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '非法输入'
+                'msg' => '非法输入',
             ]);
         }
         if (strpos($content, 'admin') !== false || strpos($content, 'user') !== false) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '请求中有不当词语'
+                'msg' => '请求中有不当词语',
             ]);
         }
 
-        $ticket           = new Ticket();
-        $antiXss          = new AntiXSS();
-        $ticket->title    = $antiXss->xss_clean($title);
-        $ticket->content  = $antiXss->xss_clean($content);
-        $ticket->rootid   = 0;
-        $ticket->userid   = $userid;
+        $ticket = new Ticket();
+        $antiXss = new AntiXSS();
+        $ticket->title = $antiXss->xss_clean($title);
+        $ticket->content = $antiXss->xss_clean($content);
+        $ticket->rootid = 0;
+        $ticket->userid = $userid;
         $ticket->datetime = time();
         $ticket->save();
 
@@ -86,39 +78,37 @@ class TicketController extends AdminController
             $_ENV['appName'] . '-新管理员工单被开启',
             'news/warn.tpl',
             [
-                'text' => '管理员开启了新的工单,请您及时访问用户面板处理。'
+                'text' => '管理员开启了新的工单,请您及时访问用户面板处理。',
             ],
             []
         );
 
         return $response->withJson([
             'ret' => 1,
-            'msg' => '提交成功'
+            'msg' => '提交成功',
         ]);
     }
 
     /**
      * 后台 更新工单内容
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function update($request, $response, $args)
+    public function update(Request $request, Response $response, array $args)
     {
-        $id      = $args['id'];
+        $id = $args['id'];
         $content = $request->getParam('content');
-        $status  = $request->getParam('status');
-        if ($content == '' || $status == '') {
+        $status = $request->getParam('status');
+        if ($content === '' || $status === '') {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '请填全'
+                'msg' => '请填全',
             ]);
         }
         if (strpos($content, 'admin') !== false || strpos($content, 'user') !== false) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '请求中有不正当的词语。'
+                'msg' => '请求中有不正当的词语。',
             ]);
         }
         $main = Ticket::find($id);
@@ -127,45 +117,43 @@ class TicketController extends AdminController
             $_ENV['appName'] . '-工单被回复',
             'news/warn.tpl',
             [
-                'text' => '您好,有人回复了<a href="' . $_ENV['baseUrl'] . '/user/ticket/' . $main->id . '/view">工单</a>,请您查看。'
+                'text' => '您好,有人回复了<a href="' . $_ENV['baseUrl'] . '/user/ticket/' . $main->id . '/view">工单</a>,请您查看。',
             ],
             []
         );
 
-        $antiXss                = new AntiXSS();
-        $ticket                 = new Ticket();
-        $ticket->title          = $antiXss->xss_clean($main->title);
-        $ticket->content        = $antiXss->xss_clean($content);
-        $ticket->rootid         = $main->id;
-        $ticket->userid         = $this->user->id;
-        $ticket->datetime       = time();
+        $antiXss = new AntiXSS();
+        $ticket = new Ticket();
+        $ticket->title = $antiXss->xss_clean($main->title);
+        $ticket->content = $antiXss->xss_clean($content);
+        $ticket->rootid = $main->id;
+        $ticket->userid = $this->user->id;
+        $ticket->datetime = time();
         $ticket->save();
-        $main->status           = $status;
+        $main->status = $status;
         $main->save();
 
         return $response->withJson([
             'ret' => 1,
-            'msg' => '提交成功'
+            'msg' => '提交成功',
         ]);
     }
 
     /**
      * 后台 查看指定工单
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function show($request, $response, $args)
+    public function show(Request $request, Response $response, array $args)
     {
-        $id            = $args['id'];
-        $ticket = Ticket::where('id','=', $id)->first();
-        if($ticket == null) {
+        $id = $args['id'];
+        $ticket = Ticket::where('id', '=', $id)->first();
+        if ($ticket === null) {
             return $response->withStatus(302)->withHeader('Location', '/user/ticket');
         }
 
-        $pageNum       = $request->getQueryParams()['page'] ?? 1;
-        $ticketset     = Ticket::where('id', $id)->orWhere('rootid', '=', $id)->orderBy('datetime', 'desc')->paginate(5, ['*'], 'page', $pageNum);
+        $pageNum = $request->getQueryParams()['page'] ?? 1;
+        $ticketset = Ticket::where('id', $id)->orWhere('rootid', '=', $id)->orderBy('datetime', 'desc')->paginate(5, ['*'], 'page', $pageNum);
         $ticketset->setPath('/admin/ticket/' . $id . '/view');
 
         $render = Tools::paginate_render($ticketset);
@@ -181,15 +169,13 @@ class TicketController extends AdminController
     /**
      * 后台工单页面 AJAX
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax($request, $response, $args)
+    public function ajax(Request $request, Response $response, array $args)
     {
         $query = Ticket::getTableDataFromAdmin(
             $request,
-            static function (&$order_field) {
+            static function (&$order_field): void {
                 if (in_array($order_field, ['op'])) {
                     $order_field = 'id';
                 }
@@ -197,36 +183,36 @@ class TicketController extends AdminController
                     $order_field = 'userid';
                 }
             },
-            static function ($query) {
+            static function ($query): void {
                 $query->where('rootid', 0);
             }
         );
 
-        $data  = [];
+        $data = [];
         foreach ($query['datas'] as $value) {
             /** @var Ticket $value */
 
-            if ($value->user() == null) {
+            if ($value->user() === null) {
                 Ticket::user_is_null($value);
                 continue;
             }
-            $tempdata               = [];
-            $tempdata['op']         = '<a class="btn btn-brand" href="/admin/ticket/' . $value->id . '/view">查看</a>';
-            $tempdata['id']         = $value->id;
-            $tempdata['datetime']   = $value->datetime();
-            $tempdata['title']      = $value->title;
-            $tempdata['userid']     = $value->userid;
-            $tempdata['user_name']  = $value->user_name();
-            $tempdata['status']     = $value->status();
+            $tempdata = [];
+            $tempdata['op'] = '<a class="btn btn-brand" href="/admin/ticket/' . $value->id . '/view">查看</a>';
+            $tempdata['id'] = $value->id;
+            $tempdata['datetime'] = $value->datetime();
+            $tempdata['title'] = $value->title;
+            $tempdata['userid'] = $value->userid;
+            $tempdata['user_name'] = $value->user_name();
+            $tempdata['status'] = $value->status();
 
             $data[] = $tempdata;
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => Ticket::count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => Ticket::count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 }

+ 205 - 235
src/Controllers/Admin/UserController.php

@@ -1,149 +1,129 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\Admin;
 
 use App\Controllers\AdminController;
-use App\Models\{
-    User,
-    Shop,
-    Bought,
-    Setting,
-    DetectBanLog
-};
-use App\Services\{
-    Auth,
-    Mail,
-    Config
-};
-use App\Utils\{
-    GA,
-    Hash,
-    Tools,
-    Cookie
-};
+use Auth;
 use Exception;
+use GA;
 use Ramsey\Uuid\Uuid;
-use Slim\Http\{
-    Request,
-    Response
-};
+use Request;
+use User;
 
 class UserController extends AdminController
 {
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function index($request, $response, $args)
+    public function index(Request $request, Response $response, array $args)
     {
-        $table_config['total_column'] = array(
-            'op'                    => '操作',
-            'querys'                => '查询',
-            'id'                    => 'ID',
-            'user_name'             => '用户名',
-            'remark'                => '备注',
-            'email'                 => '邮箱',
-            'money'                 => '金钱',
-            'im_type'               => '联络方式类型',
-            'im_value'              => '联络方式详情',
-            'node_group'            => '群组',
-            'expire_in'             => '账户过期时间',
-            'class'                 => '等级',
-            'class_expire'          => '等级过期时间',
-            'passwd'                => '连接密码',
-            'port'                  => '连接端口',
-            'method'                => '加密方式',
-            'protocol'              => '连接协议',
-            'obfs'                  => '混淆方式',
-            'obfs_param'            => '混淆参数',
-            'online_ip_count'       => '在线IP数',
-            'last_ss_time'          => '上次使用时间',
-            'used_traffic'          => '已用流量/GB',
-            'enable_traffic'        => '总流量/GB',
-            'last_checkin_time'     => '上次签到时间',
-            'today_traffic'         => '今日流量',
-            'enable'                => '是否启用',
-            'reg_date'              => '注册时间',
-            'reg_ip'                => '注册IP',
-            'auto_reset_day'        => '免费用户流量重置日',
-            'auto_reset_bandwidth'  => '重置的免费流量/GB',
-            'ref_by'                => '邀请人ID',
-            'ref_by_user_name'      => '邀请人用户名',
-            'top_up'                => '累计充值'
-        );
-        $table_config['default_show_column'] = array('op', 'id', 'user_name', 'remark', 'email');
+        $table_config['total_column'] = [
+            'op' => '操作',
+            'querys' => '查询',
+            'id' => 'ID',
+            'user_name' => '用户名',
+            'remark' => '备注',
+            'email' => '邮箱',
+            'money' => '金钱',
+            'im_type' => '联络方式类型',
+            'im_value' => '联络方式详情',
+            'node_group' => '群组',
+            'expire_in' => '账户过期时间',
+            'class' => '等级',
+            'class_expire' => '等级过期时间',
+            'passwd' => '连接密码',
+            'port' => '连接端口',
+            'method' => '加密方式',
+            'protocol' => '连接协议',
+            'obfs' => '混淆方式',
+            'obfs_param' => '混淆参数',
+            'online_ip_count' => '在线IP数',
+            'last_ss_time' => '上次使用时间',
+            'used_traffic' => '已用流量/GB',
+            'enable_traffic' => '总流量/GB',
+            'last_checkin_time' => '上次签到时间',
+            'today_traffic' => '今日流量',
+            'enable' => '是否启用',
+            'reg_date' => '注册时间',
+            'reg_ip' => '注册IP',
+            'auto_reset_day' => '免费用户流量重置日',
+            'auto_reset_bandwidth' => '重置的免费流量/GB',
+            'ref_by' => '邀请人ID',
+            'ref_by_user_name' => '邀请人用户名',
+            'top_up' => '累计充值',
+        ];
+        $table_config['default_show_column'] = ['op', 'id', 'user_name', 'remark', 'email'];
         $table_config['ajax_url'] = 'user/ajax';
         return $response->write(
             $this->view()
-                ->assign('shops',        Shop::orderBy('name')->get())
+                ->assign('shops', Shop::orderBy('name')->get())
                 ->assign('table_config', $table_config)
                 ->display('admin/user/index.tpl')
         );
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function createNewUser($request, $response, $args)
+    public function createNewUser(Request $request, Response $response, array $args)
     {
-        $email   = strtolower(trim($request->getParam('email')));
-        $money   = (int) trim($request->getParam('balance'));
+        $email = strtolower(trim($request->getParam('email')));
+        $money = (int) trim($request->getParam('balance'));
         $shop_id = (int) $request->getParam('product');
 
         $user = User::where('email', $email)->first();
-        if ($user != null) {
+        if ($user !== null) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '邮箱已经被注册了'
+                'msg' => '邮箱已经被注册了',
             ]);
         }
 
-        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
+        if (! filter_var($email, FILTER_VALIDATE_EMAIL)) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '邮箱不规范'
+                'msg' => '邮箱不规范',
             ]);
         }
 
         $configs = Setting::getClass('register');
         // do reg user
-        $user                       = new User();
-        $current_timestamp          = time();
-        $pass                       = Tools::genRandomChar();
-        $user->user_name            = $email;
-        $user->email                = $email;
-        $user->pass                 = Hash::passwordHash($pass);
-        $user->passwd               = Tools::genRandomChar(16);
-        $user->uuid                 = Uuid::uuid3(Uuid::NAMESPACE_DNS, $email . '|' . $current_timestamp);
-        $user->port                 = Tools::getAvPort();
-        $user->t                    = 0;
-        $user->u                    = 0;
-        $user->d                    = 0;
-        $user->method               = $configs['sign_up_for_method'];
-        $user->protocol             = $configs['sign_up_for_protocol'];
-        $user->protocol_param       = $configs['sign_up_for_protocol_param'];
-        $user->obfs                 = $configs['sign_up_for_obfs'];
-        $user->obfs_param           = $configs['sign_up_for_obfs_param'];
-        $user->forbidden_ip         = $_ENV['reg_forbidden_ip'];
-        $user->forbidden_port       = $_ENV['reg_forbidden_port'];
-        $user->im_type              = 2;
-        $user->im_value             = $email;
-        $user->transfer_enable      = Tools::toGB($configs['sign_up_for_free_traffic']);
-        $user->invite_num           = $configs['sign_up_for_invitation_codes'];
-        $user->auto_reset_day       = $_ENV['free_user_reset_day'];
+        $user = new User();
+        $current_timestamp = time();
+        $pass = Tools::genRandomChar();
+        $user->user_name = $email;
+        $user->email = $email;
+        $user->pass = Hash::passwordHash($pass);
+        $user->passwd = Tools::genRandomChar(16);
+        $user->uuid = Uuid::uuid3(Uuid::NAMESPACE_DNS, $email . '|' . $current_timestamp);
+        $user->port = Tools::getAvPort();
+        $user->t = 0;
+        $user->u = 0;
+        $user->d = 0;
+        $user->method = $configs['sign_up_for_method'];
+        $user->protocol = $configs['sign_up_for_protocol'];
+        $user->protocol_param = $configs['sign_up_for_protocol_param'];
+        $user->obfs = $configs['sign_up_for_obfs'];
+        $user->obfs_param = $configs['sign_up_for_obfs_param'];
+        $user->forbidden_ip = $_ENV['reg_forbidden_ip'];
+        $user->forbidden_port = $_ENV['reg_forbidden_port'];
+        $user->im_type = 2;
+        $user->im_value = $email;
+        $user->transfer_enable = Tools::toGB($configs['sign_up_for_free_traffic']);
+        $user->invite_num = $configs['sign_up_for_invitation_codes'];
+        $user->auto_reset_day = $_ENV['free_user_reset_day'];
         $user->auto_reset_bandwidth = $_ENV['free_user_reset_bandwidth'];
-        $user->money                = ($money != -1 ? $money : 0);
-        $user->class_expire         = date('Y-m-d H:i:s', time() + $configs['sign_up_for_class_time'] * 86400);
-        $user->class                = $configs['sign_up_for_class'];
-        $user->node_connector       = $configs['connection_device_limit'];
-        $user->node_speedlimit      = $configs['connection_rate_limit'];
-        $user->expire_in            = date('Y-m-d H:i:s', time() + $configs['sign_up_for_free_time'] * 86400);
-        $user->reg_date             = date('Y-m-d H:i:s');
-        $user->reg_ip               = $_SERVER['REMOTE_ADDR'];
-        $user->theme                = $_ENV['theme'];
+        $user->money = ($money !== -1 ? $money : 0);
+        $user->class_expire = date('Y-m-d H:i:s', time() + $configs['sign_up_for_class_time'] * 86400);
+        $user->class = $configs['sign_up_for_class'];
+        $user->node_connector = $configs['connection_device_limit'];
+        $user->node_speedlimit = $configs['connection_rate_limit'];
+        $user->expire_in = date('Y-m-d H:i:s', time() + $configs['sign_up_for_free_time'] * 86400);
+        $user->reg_date = date('Y-m-d H:i:s');
+        $user->reg_ip = $_SERVER['REMOTE_ADDR'];
+        $user->theme = $_ENV['theme'];
 
         $groups = explode(',', $_ENV['random_group']);
 
@@ -155,19 +135,19 @@ class UserController extends AdminController
         $user->ga_token = $secret;
         $user->ga_enable = 0;
         if ($user->save()) {
-            $res['ret']         = 1;
-            $res['msg']         = '新用户注册成功 用户名: ' . $email . ' 随机初始密码: ' . $pass;
+            $res['ret'] = 1;
+            $res['msg'] = '新用户注册成功 用户名: ' . $email . ' 随机初始密码: ' . $pass;
             $res['email_error'] = 'success';
             if ($shop_id > 0) {
                 $shop = Shop::find($shop_id);
-                if ($shop != null) {
-                    $bought           = new Bought();
-                    $bought->userid   = $user->id;
-                    $bought->shopid   = $shop->id;
+                if ($shop !== null) {
+                    $bought = new Bought();
+                    $bought->userid = $user->id;
+                    $bought->shopid = $shop->id;
                     $bought->datetime = time();
-                    $bought->renew    = 0;
-                    $bought->coupon   = '';
-                    $bought->price    = $shop->price;
+                    $bought->renew = 0;
+                    $bought->coupon = '';
+                    $bought->price = $shop->price;
                     $bought->save();
                     $shop->buy($user);
                 } else {
@@ -175,9 +155,9 @@ class UserController extends AdminController
                 }
             }
             $user->addMoneyLog($user->money);
-            $subject            = $_ENV['appName'] . '-新用户注册通知';
-            $to                 = $user->email;
-            $text               = '您好,管理员已经为您生成账户,用户名: ' . $email . ',登录密码为:' . $pass . ',感谢您的支持。 ';
+            $subject = $_ENV['appName'] . '-新用户注册通知';
+            $to = $user->email;
+            $text = '您好,管理员已经为您生成账户,用户名: ' . $email . ',登录密码为:' . $pass . ',感谢您的支持。 ';
             try {
                 Mail::send($to, $subject, 'newuser.tpl', [
                     'user' => $user, 'text' => $text,
@@ -189,16 +169,14 @@ class UserController extends AdminController
         }
         return $response->withJson([
             'ret' => 0,
-            'msg' => '未知错误'
+            'msg' => '未知错误',
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function edit($request, $response, $args)
+    public function edit(Request $request, Response $response, array $args)
     {
         $user = User::find($args['id']);
         return $response->write(
@@ -209,11 +187,9 @@ class UserController extends AdminController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function update($request, $response, $args)
+    public function update(Request $request, Response $response, array $args)
     {
         $id = $args['id'];
         $user = User::find($id);
@@ -226,7 +202,7 @@ class UserController extends AdminController
 
         $passwd = $request->getParam('passwd');
 
-        if ($request->getParam('pass') != '') {
+        if ($request->getParam('pass') !== '') {
             $user->pass = Hash::passwordHash($request->getParam('pass'));
             $user->clean_link();
         }
@@ -238,200 +214,194 @@ class UserController extends AdminController
 
         $user->addMoneyLog($request->getParam('money') - $user->money);
 
-        $user->passwd           = $request->getParam('passwd');
-        $user->protocol         = $request->getParam('protocol');
-        $user->protocol_param   = $request->getParam('protocol_param');
-        $user->obfs             = $request->getParam('obfs');
-        $user->obfs_param       = $request->getParam('obfs_param');
-        $user->is_multi_user    = $request->getParam('is_multi_user');
-        $user->transfer_enable  = Tools::toGB($request->getParam('transfer_enable'));
-        $user->invite_num       = $request->getParam('invite_num');
-        $user->method           = $request->getParam('method');
-        $user->node_speedlimit  = $request->getParam('node_speedlimit');
-        $user->node_connector   = $request->getParam('node_connector');
-        $user->enable           = $request->getParam('enable');
-        $user->is_admin         = $request->getParam('is_admin');
-        $user->ga_enable        = $request->getParam('ga_enable');
-        $user->node_group       = $request->getParam('group');
-        $user->ref_by           = $request->getParam('ref_by');
-        $user->remark           = $request->getParam('remark');
-        $user->user_name        = $request->getParam('user_name');
-        $user->money            = $request->getParam('money');
-        $user->class            = $request->getParam('class');
-        $user->class_expire     = $request->getParam('class_expire');
-        $user->expire_in        = $request->getParam('expire_in');
-
-        $user->forbidden_ip     = str_replace(PHP_EOL, ',', $request->getParam('forbidden_ip'));
-        $user->forbidden_port   = str_replace(PHP_EOL, ',', $request->getParam('forbidden_port'));
+        $user->passwd = $request->getParam('passwd');
+        $user->protocol = $request->getParam('protocol');
+        $user->protocol_param = $request->getParam('protocol_param');
+        $user->obfs = $request->getParam('obfs');
+        $user->obfs_param = $request->getParam('obfs_param');
+        $user->is_multi_user = $request->getParam('is_multi_user');
+        $user->transfer_enable = Tools::toGB($request->getParam('transfer_enable'));
+        $user->invite_num = $request->getParam('invite_num');
+        $user->method = $request->getParam('method');
+        $user->node_speedlimit = $request->getParam('node_speedlimit');
+        $user->node_connector = $request->getParam('node_connector');
+        $user->enable = $request->getParam('enable');
+        $user->is_admin = $request->getParam('is_admin');
+        $user->ga_enable = $request->getParam('ga_enable');
+        $user->node_group = $request->getParam('group');
+        $user->ref_by = $request->getParam('ref_by');
+        $user->remark = $request->getParam('remark');
+        $user->user_name = $request->getParam('user_name');
+        $user->money = $request->getParam('money');
+        $user->class = $request->getParam('class');
+        $user->class_expire = $request->getParam('class_expire');
+        $user->expire_in = $request->getParam('expire_in');
+
+        $user->forbidden_ip = str_replace(PHP_EOL, ',', $request->getParam('forbidden_ip'));
+        $user->forbidden_port = str_replace(PHP_EOL, ',', $request->getParam('forbidden_port'));
 
         // 手动封禁
         $ban_time = (int) $request->getParam('ban_time');
         if ($ban_time > 0) {
-            $user->enable                       = 0;
-            $end_time                           = date('Y-m-d H:i:s');
-            $user->last_detect_ban_time         = $end_time;
-            $DetectBanLog                       = new DetectBanLog();
-            $DetectBanLog->user_name            = $user->user_name;
-            $DetectBanLog->user_id              = $user->id;
-            $DetectBanLog->email                = $user->email;
-            $DetectBanLog->detect_number        = '0';
-            $DetectBanLog->ban_time             = $ban_time;
-            $DetectBanLog->start_time           = strtotime('1989-06-04 00:05:00');
-            $DetectBanLog->end_time             = strtotime($end_time);
-            $DetectBanLog->all_detect_number    = $user->all_detect_number;
+            $user->enable = 0;
+            $end_time = date('Y-m-d H:i:s');
+            $user->last_detect_ban_time = $end_time;
+            $DetectBanLog = new DetectBanLog();
+            $DetectBanLog->user_name = $user->user_name;
+            $DetectBanLog->user_id = $user->id;
+            $DetectBanLog->email = $user->email;
+            $DetectBanLog->detect_number = '0';
+            $DetectBanLog->ban_time = $ban_time;
+            $DetectBanLog->start_time = strtotime('1989-06-04 00:05:00');
+            $DetectBanLog->end_time = strtotime($end_time);
+            $DetectBanLog->all_detect_number = $user->all_detect_number;
             $DetectBanLog->save();
         }
 
-        if (!$user->save()) {
+        if (! $user->save()) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '修改失败'
+                'msg' => '修改失败',
             ]);
         }
         return $response->withJson([
             'ret' => 1,
-            'msg' => '修改成功'
+            'msg' => '修改成功',
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function delete($request, $response, $args)
+    public function delete(Request $request, Response $response, array $args)
     {
         $user = User::find((int) $request->getParam('id'));
-        if (!$user->kill_user()) {
+        if (! $user->kill_user()) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '删除失败'
+                'msg' => '删除失败',
             ]);
         }
         return $response->withJson([
             'ret' => 1,
-            'msg' => '删除成功'
+            'msg' => '删除成功',
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function changetouser($request, $response, $args)
+    public function changetouser(Request $request, Response $response, array $args)
     {
-        $userid    = $request->getParam('userid');
-        $adminid   = $request->getParam('adminid');
-        $user      = User::find($userid);
-        $admin     = User::find($adminid);
+        $userid = $request->getParam('userid');
+        $adminid = $request->getParam('adminid');
+        $user = User::find($userid);
+        $admin = User::find($adminid);
         $expire_in = time() + 60 * 60;
 
-        if (!$admin->is_admin || !$user || !Auth::getUser()->isLogin) {
+        if (! $admin->is_admin || ! $user || ! Auth::getUser()->isLogin) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '非法请求'
+                'msg' => '非法请求',
             ]);
         }
 
         Cookie::set([
-            'uid'           => $user->id,
-            'email'         => $user->email,
-            'key'           => Hash::cookieHash($user->pass, $expire_in),
-            'ip'            => md5($_SERVER['REMOTE_ADDR'] . $_ENV['key'] . $user->id . $expire_in),
-            'expire_in'     => $expire_in,
-            'old_uid'       => Cookie::get('uid'),
-            'old_email'     => Cookie::get('email'),
-            'old_key'       => Cookie::get('key'),
-            'old_ip'        => Cookie::get('ip'),
+            'uid' => $user->id,
+            'email' => $user->email,
+            'key' => Hash::cookieHash($user->pass, $expire_in),
+            'ip' => md5($_SERVER['REMOTE_ADDR'] . $_ENV['key'] . $user->id . $expire_in),
+            'expire_in' => $expire_in,
+            'old_uid' => Cookie::get('uid'),
+            'old_email' => Cookie::get('email'),
+            'old_key' => Cookie::get('key'),
+            'old_ip' => Cookie::get('ip'),
             'old_expire_in' => Cookie::get('expire_in'),
-            'old_local'     => $request->getParam('local'),
+            'old_local' => $request->getParam('local'),
         ], $expire_in);
 
         return $response->withJson([
             'ret' => 1,
-            'msg' => '切换成功'
+            'msg' => '切换成功',
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax($request, $response, $args)
+    public function ajax(Request $request, Response $response, array $args)
     {
         $query = User::getTableDataFromAdmin(
             $request,
-            static function (&$order_field) {
-                if ($order_field == 'used_traffic') {
+            static function (&$order_field): void {
+                if ($order_field === 'used_traffic') {
                     $order_field = 'u + d';
-                } elseif ($order_field == 'enable_traffic') {
+                } elseif ($order_field === 'enable_traffic') {
                     $order_field = 'transfer_enable';
-                } elseif ($order_field == 'today_traffic') {
+                } elseif ($order_field === 'today_traffic') {
                     $order_field = 'u + d - last_day_t';
-                } elseif ($order_field == 'querys') {
+                } elseif ($order_field === 'querys') {
                     $order_field = 'id';
                 }
             }
         );
 
-        $data  = [];
+        $data = [];
         foreach ($query['datas'] as $value) {
             /** @var User $value */
 
-            $tempdata['op']                     = '' .
+            $tempdata['op'] = '' .
                 '<a class="btn btn-brand" href="/admin/user/' . $value->id . '/edit">编辑</a>' .
                 '<a class="btn btn-brand-accent" id="delete" href="javascript:void(0);" onClick="delete_modal_show(\'' . $value->id . '\')">删除</a>' .
                 '<a class="btn btn-brand" id="changetouser" href="javascript:void(0);" onClick="changetouser_modal_show(\'' . $value->id . '\')">切换为该用户</a>';
 
-            $tempdata['querys']                 = '' .
+            $tempdata['querys'] = '' .
                 '<a class="btn btn-brand" href="/admin/user/' . $value->id . '/bought">套餐</a>' .
                 '<a class="btn btn-brand" href="/admin/user/' . $value->id . '/code">充值</a>' .
                 '<a class="btn btn-brand" href="/admin/user/' . $value->id . '/sublog">订阅</a>' .
                 '<a class="btn btn-brand" href="/admin/user/' . $value->id . '/detect">审计</a>' .
                 '<a class="btn btn-brand" href="/admin/user/' . $value->id . '/login">登录</a>';
 
-            $tempdata['id']                     = $value->id;
-            $tempdata['user_name']              = $value->user_name;
-            $tempdata['remark']                 = $value->remark;
-            $tempdata['email']                  = $value->email;
-            $tempdata['money']                  = $value->money;
-            $tempdata['im_type']                = $value->im_type();
-            $tempdata['im_value']               = $value->im_value();
-            $tempdata['node_group']             = $value->node_group;
-            $tempdata['expire_in']              = $value->expire_in;
-            $tempdata['class']                  = $value->class;
-            $tempdata['class_expire']           = $value->class_expire;
-            $tempdata['passwd']                 = $value->passwd;
-            $tempdata['port']                   = $value->port;
-            $tempdata['method']                 = $value->method;
-            $tempdata['protocol']               = $value->protocol;
-            $tempdata['obfs']                   = $value->obfs;
-            $tempdata['obfs_param']             = $value->obfs_param;
-            $tempdata['online_ip_count']        = $value->online_ip_count();
-            $tempdata['last_ss_time']           = $value->lastSsTime();
-            $tempdata['used_traffic']           = Tools::flowToGB($value->u + $value->d);
-            $tempdata['enable_traffic']         = Tools::flowToGB($value->transfer_enable);
-            $tempdata['last_checkin_time']      = $value->lastCheckInTime();
-            $tempdata['today_traffic']          = $value->TodayusedTraffic();
-            $tempdata['enable']                 = $value->enable == 1 ? '可用' : '禁用';
-            $tempdata['reg_date']               = $value->reg_date;
-            $tempdata['reg_ip']                 = $value->reg_ip;
-            $tempdata['auto_reset_day']         = $value->auto_reset_day;
-            $tempdata['auto_reset_bandwidth']   = $value->auto_reset_bandwidth;
-            $tempdata['ref_by']                 = $value->ref_by;
-            $tempdata['ref_by_user_name']       = $value->ref_by_user_name();
-            $tempdata['top_up']                 = $value->get_top_up();
+            $tempdata['id'] = $value->id;
+            $tempdata['user_name'] = $value->user_name;
+            $tempdata['remark'] = $value->remark;
+            $tempdata['email'] = $value->email;
+            $tempdata['money'] = $value->money;
+            $tempdata['im_type'] = $value->im_type();
+            $tempdata['im_value'] = $value->im_value();
+            $tempdata['node_group'] = $value->node_group;
+            $tempdata['expire_in'] = $value->expire_in;
+            $tempdata['class'] = $value->class;
+            $tempdata['class_expire'] = $value->class_expire;
+            $tempdata['passwd'] = $value->passwd;
+            $tempdata['port'] = $value->port;
+            $tempdata['method'] = $value->method;
+            $tempdata['protocol'] = $value->protocol;
+            $tempdata['obfs'] = $value->obfs;
+            $tempdata['obfs_param'] = $value->obfs_param;
+            $tempdata['online_ip_count'] = $value->online_ip_count();
+            $tempdata['last_ss_time'] = $value->lastSsTime();
+            $tempdata['used_traffic'] = Tools::flowToGB($value->u + $value->d);
+            $tempdata['enable_traffic'] = Tools::flowToGB($value->transfer_enable);
+            $tempdata['last_checkin_time'] = $value->lastCheckInTime();
+            $tempdata['today_traffic'] = $value->TodayusedTraffic();
+            $tempdata['enable'] = $value->enable === 1 ? '可用' : '禁用';
+            $tempdata['reg_date'] = $value->reg_date;
+            $tempdata['reg_ip'] = $value->reg_ip;
+            $tempdata['auto_reset_day'] = $value->auto_reset_day;
+            $tempdata['auto_reset_bandwidth'] = $value->auto_reset_bandwidth;
+            $tempdata['ref_by'] = $value->ref_by;
+            $tempdata['ref_by_user_name'] = $value->ref_by_user_name();
+            $tempdata['top_up'] = $value->get_top_up();
 
             $data[] = $tempdata;
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => User::count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => User::count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 }

+ 54 - 67
src/Controllers/Admin/UserLog/BoughtLogController.php

@@ -1,42 +1,35 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\Admin\UserLog;
 
 use App\Controllers\AdminController;
-use App\Models\{
-    User,
-    Shop,
-    Bought
-};
-use Slim\Http\{
-    Request,
-    Response
-};
 use Psr\Http\Message\ResponseInterface;
+use Request;
+use User;
 
 class BoughtLogController extends AdminController
 {
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function bought($request, $response, $args): ResponseInterface
+    public function bought(Request $request, Response $response, array $args): ResponseInterface
     {
         $id = $args['id'];
         $user = User::find($id);
-        $table_config['total_column'] = array(
-            'op'         => '操作',
-            'id'         => 'ID',
-            'name'       => '商品名称',
-            'valid'      => '是否有效期内',
-            'renew'      => '自动续费时间',
+        $table_config['total_column'] = [
+            'op' => '操作',
+            'id' => 'ID',
+            'name' => '商品名称',
+            'valid' => '是否有效期内',
+            'renew' => '自动续费时间',
             'reset_time' => '流量重置时间',
-            'datetime'   => '套餐购买时间',
-            'exp_time'   => '套餐过期时间',
-            'content'    => '商品详细内容',
-        );
-        $table_config['default_show_column'] = array('op', 'name', 'valid', 'reset_time');
+            'datetime' => '套餐购买时间',
+            'exp_time' => '套餐过期时间',
+            'content' => '商品详细内容',
+        ];
+        $table_config['default_show_column'] = ['op', 'name', 'valid', 'reset_time'];
         $table_config['ajax_url'] = 'bought/ajax';
         $shops = Shop::where('status', 1)->orderBy('name')->get();
 
@@ -50,16 +43,14 @@ class BoughtLogController extends AdminController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function bought_ajax($request, $response, $args): ResponseInterface
+    public function bought_ajax(Request $request, Response $response, array $args): ResponseInterface
     {
-        $user  = User::find($args['id']);
+        $user = User::find($args['id']);
         $query = Bought::getTableDataFromAdmin(
             $request,
-            static function (&$order_field) {
+            static function (&$order_field): void {
                 if (in_array($order_field, ['op', 'reset_time', 'valid', 'exp_time'])) {
                     $order_field = 'id';
                 }
@@ -67,95 +58,91 @@ class BoughtLogController extends AdminController
                     $order_field = 'shopid';
                 }
             },
-            static function ($query) use ($user) {
+            static function ($query) use ($user): void {
                 $query->where('userid', $user->id);
             }
         );
 
-        $data  = [];
+        $data = [];
         foreach ($query['datas'] as $value) {
             /** @var Bought $value */
 
-            if ($value->shop() == null) {
+            if ($value->shop() === null) {
                 Bought::shop_is_null($value);
                 continue;
             }
-            $tempdata                = [];
-            $tempdata['op']          = '<a class="btn btn-brand-accent" id="delete" href="javascript:void(0);" onClick="delete_modal_show(\'' . $value->id . '\')">删除</a>';
-            $tempdata['id']          = $value->id;
-            $tempdata['name']        = $value->shop()->name;
-            $tempdata['content']     = $value->content();
-            $tempdata['renew']       = $value->renew();
-            $tempdata['datetime']    = $value->datetime();
+            $tempdata = [];
+            $tempdata['op'] = '<a class="btn btn-brand-accent" id="delete" href="javascript:void(0);" onClick="delete_modal_show(\'' . $value->id . '\')">删除</a>';
+            $tempdata['id'] = $value->id;
+            $tempdata['name'] = $value->shop()->name;
+            $tempdata['content'] = $value->content();
+            $tempdata['renew'] = $value->renew();
+            $tempdata['datetime'] = $value->datetime();
             if ($value->shop()->use_loop()) {
                 $tempdata['valid'] = ($value->valid() ? '有效' : '已过期');
             } else {
                 $tempdata['valid'] = '-';
             }
-            $tempdata['reset_time']  = $value->reset_time();
-            $tempdata['exp_time']    = $value->exp_time();
+            $tempdata['reset_time'] = $value->reset_time();
+            $tempdata['exp_time'] = $value->exp_time();
 
             $data[] = $tempdata;
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => Bought::where('userid', $user->id)->count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => Bought::where('userid', $user->id)->count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function bought_delete($request, $response, $args): ResponseInterface
+    public function bought_delete(Request $request, Response $response, array $args): ResponseInterface
     {
         $id = $request->getParam('id');
         $Bought = Bought::find($id);
-        if (!$Bought->delete()) {
+        if (! $Bought->delete()) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '删除失败'
+                'msg' => '删除失败',
             ]);
         }
         return $response->withJson([
             'ret' => 1,
-            'msg' => '删除成功'
+            'msg' => '删除成功',
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function bought_add($request, $response, $args): ResponseInterface
+    public function bought_add(Request $request, Response $response, array $args): ResponseInterface
     {
         $id = $args['id'];
         $user = User::find($id);
-        $shop_id  = (int) $request->getParam('buy_shop');
+        $shop_id = (int) $request->getParam('buy_shop');
         $buy_type = (int) $request->getParam('buy_type');
-        if ($shop_id == '') {
+        if ($shop_id === '') {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '请选择套餐'
+                'msg' => '请选择套餐',
             ]);
         }
         $shop = Shop::find($shop_id);
-        if ($shop == null) {
+        if ($shop === null) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '套餐不存在'
+                'msg' => '套餐不存在',
             ]);
         }
-        if ($buy_type != 0) {
-            if (bccomp($user->money, $shop->price, 2) == -1) {
+        if ($buy_type !== 0) {
+            if (bccomp($user->money, $shop->price, 2) === -1) {
                 return $response->withJson([
                     'ret' => 0,
-                    'msg' => '喵喵喵~ 该用户余额不足。'
+                    'msg' => '喵喵喵~ 该用户余额不足。',
                 ]);
             }
             $user->money = bcsub($user->money, $shop->price, 2);
@@ -166,19 +153,19 @@ class BoughtLogController extends AdminController
             $disable_bought->renew = 0;
             $disable_bought->save();
         }
-        $bought           = new Bought();
-        $bought->userid   = $user->id;
-        $bought->shopid   = $shop->id;
+        $bought = new Bought();
+        $bought->userid = $user->id;
+        $bought->shopid = $shop->id;
         $bought->datetime = time();
-        $bought->renew    = 0;
-        $bought->coupon   = '';
-        $bought->price    = $shop->price;
+        $bought->renew = 0;
+        $bought->coupon = '';
+        $bought->price = $shop->price;
         $bought->save();
         $shop->buy($user);
 
         return $response->withJson([
             'ret' => 1,
-            'msg' => ($buy_type != 0 ? '套餐购买成功' : '套餐添加成功')
+            'msg' => ($buy_type !== 0 ? '套餐购买成功' : '套餐添加成功'),
         ]);
     }
 }

+ 24 - 32
src/Controllers/Admin/UserLog/CodeLogController.php

@@ -1,36 +1,30 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\Admin\UserLog;
 
 use App\Controllers\AdminController;
-use App\Models\{
-    Code,
-    User,
-};
-use Slim\Http\{
-    Request,
-    Response
-};
+use Code;
 use Psr\Http\Message\ResponseInterface;
+use Request;
 
 class CodeLogController extends AdminController
 {
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function index($request, $response, $args): ResponseInterface
+    public function index(Request $request, Response $response, array $args): ResponseInterface
     {
         $id = $args['id'];
         $user = User::find($id);
-        $table_config['total_column'] = array(
-            'id'          => 'ID',
-            'code'        => '内容',
-            'type'        => '类型',
-            'number'      => '操作',
-            'usedatetime' => '时间'
-        );
+        $table_config['total_column'] = [
+            'id' => 'ID',
+            'code' => '内容',
+            'type' => '类型',
+            'number' => '操作',
+            'usedatetime' => '时间',
+        ];
         $table_config['default_show_column'] = array_keys($table_config['total_column']);
         $table_config['ajax_url'] = 'code/ajax';
         return $response->write(
@@ -42,40 +36,38 @@ class CodeLogController extends AdminController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax($request, $response, $args): ResponseInterface
+    public function ajax(Request $request, Response $response, array $args): ResponseInterface
     {
-        $user  = User::find($args['id']);
+        $user = User::find($args['id']);
         $query = Code::getTableDataFromAdmin(
             $request,
             null,
-            static function ($query) use ($user) {
+            static function ($query) use ($user): void {
                 $query->where('userid', $user->id);
             }
         );
 
-        $data  = [];
+        $data = [];
         foreach ($query['datas'] as $value) {
             /** @var Code $value */
 
-            $tempdata                = [];
-            $tempdata['id']          = $value->id;
-            $tempdata['code']        = $value->code;
-            $tempdata['type']        = $value->type();
-            $tempdata['number']      = $value->number();
+            $tempdata = [];
+            $tempdata['id'] = $value->id;
+            $tempdata['code'] = $value->code;
+            $tempdata['type'] = $value->type();
+            $tempdata['number'] = $value->number();
             $tempdata['usedatetime'] = $value->usedatetime;
 
             $data[] = $tempdata;
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => Code::where('userid', $user->id)->count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => Code::where('userid', $user->id)->count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 }

+ 35 - 43
src/Controllers/Admin/UserLog/DetectLogController.php

@@ -1,40 +1,34 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\Admin\UserLog;
 
 use App\Controllers\AdminController;
-use App\Models\{
-    User,
-    DetectLog
-};
-use Slim\Http\{
-    Request,
-    Response
-};
 use Psr\Http\Message\ResponseInterface;
+use Request;
+use User;
 
 class DetectLogController extends AdminController
 {
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function index($request, $response, $args): ResponseInterface
+    public function index(Request $request, Response $response, array $args): ResponseInterface
     {
         $id = $args['id'];
         $user = User::find($id);
-        $table_config['total_column'] = array(
-            'id'          => 'ID',
-            'node_id'     => '节点ID',
-            'node_name'   => '节点名',
-            'list_id'     => '规则ID',
-            'rule_name'   => '规则名',
-            'rule_text'   => '规则描述',
-            'rule_regex'  => '规则正则表达式',
-            'rule_type'   => '规则类型',
-            'datetime'    => '时间'
-        );
+        $table_config['total_column'] = [
+            'id' => 'ID',
+            'node_id' => '节点ID',
+            'node_name' => '节点名',
+            'list_id' => '规则ID',
+            'rule_name' => '规则名',
+            'rule_text' => '规则描述',
+            'rule_regex' => '规则正则表达式',
+            'rule_type' => '规则类型',
+            'datetime' => '时间',
+        ];
         $table_config['default_show_column'] = array_keys($table_config['total_column']);
         $table_config['ajax_url'] = 'detect/ajax';
 
@@ -47,16 +41,14 @@ class DetectLogController extends AdminController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax($request, $response, $args): ResponseInterface
+    public function ajax(Request $request, Response $response, array $args): ResponseInterface
     {
-        $user  = User::find($args['id']);
+        $user = User::find($args['id']);
         $query = DetectLog::getTableDataFromAdmin(
             $request,
-            static function (&$order_field) {
+            static function (&$order_field): void {
                 if (in_array($order_field, ['node_name'])) {
                     $order_field = 'node_id';
                 }
@@ -64,42 +56,42 @@ class DetectLogController extends AdminController
                     $order_field = 'list_id';
                 }
             },
-            static function ($query) use ($user) {
+            static function ($query) use ($user): void {
                 $query->where('user_id', $user->id);
             }
         );
 
-        $data  = [];
+        $data = [];
         foreach ($query['datas'] as $value) {
             /** @var DetectLog $value */
 
-            if ($value->rule() == null) {
+            if ($value->rule() === null) {
                 DetectLog::rule_is_null($value);
                 continue;
             }
-            if ($value->node() == null) {
+            if ($value->node() === null) {
                 DetectLog::node_is_null($value);
                 continue;
             }
-            $tempdata               = [];
-            $tempdata['id']         = $value->id;
-            $tempdata['node_id']    = $value->node_id;
-            $tempdata['node_name']  = $value->node_name();
-            $tempdata['list_id']    = $value->list_id;
-            $tempdata['rule_name']  = $value->rule_name();
-            $tempdata['rule_text']  = $value->rule_text();
+            $tempdata = [];
+            $tempdata['id'] = $value->id;
+            $tempdata['node_id'] = $value->node_id;
+            $tempdata['node_name'] = $value->node_name();
+            $tempdata['list_id'] = $value->list_id;
+            $tempdata['rule_name'] = $value->rule_name();
+            $tempdata['rule_text'] = $value->rule_text();
             $tempdata['rule_regex'] = $value->rule_regex();
-            $tempdata['rule_type']  = $value->rule_type();
-            $tempdata['datetime']   = $value->datetime();
+            $tempdata['rule_type'] = $value->rule_type();
+            $tempdata['datetime'] = $value->datetime();
 
             $data[] = $tempdata;
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => DetectLog::where('user_id', $user->id)->count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => DetectLog::where('user_id', $user->id)->count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 }

+ 26 - 34
src/Controllers/Admin/UserLog/LoginLogController.php

@@ -1,37 +1,31 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\Admin\UserLog;
 
 use App\Controllers\AdminController;
-use App\Models\{
-    User,
-    LoginIp
-};
 use App\Utils\QQWry;
-use Slim\Http\{
-    Request,
-    Response
-};
 use Psr\Http\Message\ResponseInterface;
+use Request;
+use User;
 
 class LoginLogController extends AdminController
 {
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function index($request, $response, $args): ResponseInterface
+    public function index(Request $request, Response $response, array $args): ResponseInterface
     {
         $id = $args['id'];
         $user = User::find($id);
-        $table_config['total_column'] = array(
-            'id'        => 'ID',
-            'ip'        => 'IP',
-            'location'  => '归属地',
-            'datetime'  => '时间',
-            'type'      => '类型'
-        );
+        $table_config['total_column'] = [
+            'id' => 'ID',
+            'ip' => 'IP',
+            'location' => '归属地',
+            'datetime' => '时间',
+            'type' => '类型',
+        ];
         $table_config['default_show_column'] = array_keys($table_config['total_column']);
         $table_config['ajax_url'] = 'login/ajax';
 
@@ -44,44 +38,42 @@ class LoginLogController extends AdminController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax($request, $response, $args): ResponseInterface
+    public function ajax(Request $request, Response $response, array $args): ResponseInterface
     {
-        $user  = User::find($args['id']);
+        $user = User::find($args['id']);
         $query = LoginIp::getTableDataFromAdmin(
             $request,
-            static function (&$order_field) {
+            static function (&$order_field): void {
                 if (in_array($order_field, ['location'])) {
                     $order_field = 'ip';
                 }
             },
-            static function ($query) use ($user) {
+            static function ($query) use ($user): void {
                 $query->where('userid', $user->id);
             }
         );
 
-        $data  = [];
+        $data = [];
         $QQWry = new QQWry();
         foreach ($query['datas'] as $value) {
             /** @var LoginIp $value */
-            $tempdata             = [];
-            $tempdata['id']        = $value->id;
-            $tempdata['ip']        = $value->ip;
-            $tempdata['location']  = $value->location($QQWry);
-            $tempdata['datetime']  = $value->datetime();
-            $tempdata['type']      = $value->type();
+            $tempdata = [];
+            $tempdata['id'] = $value->id;
+            $tempdata['ip'] = $value->ip;
+            $tempdata['location'] = $value->location($QQWry);
+            $tempdata['datetime'] = $value->datetime();
+            $tempdata['type'] = $value->type();
 
             $data[] = $tempdata;
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => LoginIp::where('userid', $user->id)->count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => LoginIp::where('userid', $user->id)->count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 }

+ 27 - 35
src/Controllers/Admin/UserLog/SubLogController.php

@@ -1,38 +1,32 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\Admin\UserLog;
 
 use App\Controllers\AdminController;
-use App\Models\{
-    User,
-    UserSubscribeLog
-};
 use App\Utils\QQWry;
-use Slim\Http\{
-    Request,
-    Response
-};
 use Psr\Http\Message\ResponseInterface;
+use Request;
+use User;
 
 class SubLogController extends AdminController
 {
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function index($request, $response, $args): ResponseInterface
+    public function index(Request $request, Response $response, array $args): ResponseInterface
     {
         $id = $args['id'];
         $user = User::find($id);
-        $table_config['total_column'] = array(
-            'id'                  => 'ID',
-            'subscribe_type'      => '类型',
-            'request_ip'          => 'IP',
-            'location'            => '归属地',
-            'request_time'        => '时间',
-            'request_user_agent'  => 'User-Agent'
-        );
+        $table_config['total_column'] = [
+            'id' => 'ID',
+            'subscribe_type' => '类型',
+            'request_ip' => 'IP',
+            'location' => '归属地',
+            'request_time' => '时间',
+            'request_user_agent' => 'User-Agent',
+        ];
         $table_config['default_show_column'] = array_keys($table_config['total_column']);
         $table_config['ajax_url'] = 'sublog/ajax';
 
@@ -45,46 +39,44 @@ class SubLogController extends AdminController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax($request, $response, $args): ResponseInterface
+    public function ajax(Request $request, Response $response, array $args): ResponseInterface
     {
-        $user  = User::find($args['id']);
+        $user = User::find($args['id']);
         $query = UserSubscribeLog::getTableDataFromAdmin(
             $request,
-            static function (&$order_field) {
+            static function (&$order_field): void {
                 if (in_array($order_field, ['location'])) {
                     $order_field = 'request_ip';
                 }
             },
-            static function ($query) use ($user) {
+            static function ($query) use ($user): void {
                 $query->where('user_id', $user->id);
             }
         );
 
-        $data  = [];
+        $data = [];
         $QQWry = new QQWry();
         foreach ($query['datas'] as $value) {
             /** @var UserSubscribeLog $value */
 
-            $tempdata                       = [];
-            $tempdata['id']                 = $value->id;
-            $tempdata['subscribe_type']     = $value->subscribe_type;
-            $tempdata['request_ip']         = $value->request_ip;
-            $tempdata['location']           = $value->location($QQWry);
-            $tempdata['request_time']       = $value->request_time;
+            $tempdata = [];
+            $tempdata['id'] = $value->id;
+            $tempdata['subscribe_type'] = $value->subscribe_type;
+            $tempdata['request_ip'] = $value->request_ip;
+            $tempdata['location'] = $value->location($QQWry);
+            $tempdata['request_time'] = $value->request_time;
             $tempdata['request_user_agent'] = $value->request_user_agent;
 
             $data[] = $tempdata;
         }
 
         return $response->withJson([
-            'draw'            => $request->getParam('draw'),
-            'recordsTotal'    => UserSubscribeLog::where('user_id', $user->id)->count(),
+            'draw' => $request->getParam('draw'),
+            'recordsTotal' => UserSubscribeLog::where('user_id', $user->id)->count(),
             'recordsFiltered' => $query['count'],
-            'data'            => $data,
+            'data' => $data,
         ]);
     }
 }

+ 61 - 89
src/Controllers/AdminController.php

@@ -1,23 +1,13 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers;
 
-use App\Models\{
-    User,
-    Coupon
-};
-use App\Utils\{
-    Tools,
-    DatatablesHelper
-};
-use App\Services\{
-    Analytics
-};
 use Ozdemir\Datatables\Datatables;
-use Slim\Http\{
-    Request,
-    Response
-};
+use Request;
+use Tools;
+use User;
 
 /**
  *  Admin Controller
@@ -27,11 +17,9 @@ class AdminController extends UserController
     /**
      * 后台首页
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function index($request, $response, $args)
+    public function index(Request $request, Response $response, array $args)
     {
         return $response->write(
             $this->view()
@@ -43,11 +31,9 @@ class AdminController extends UserController
     /**
      * 统计信息
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function sys($request, $response, $args)
+    public function sys(Request $request, Response $response, array $args)
     {
         return $response->write(
             $this->view()
@@ -58,23 +44,21 @@ class AdminController extends UserController
     /**
      * 后台邀请返利页面
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function invite($request, $response, $args)
+    public function invite(Request $request, Response $response, array $args)
     {
-        $table_config['total_column'] = array(
-            'id'              => 'ID',
-            'total'           => '原始金额',
-            'event_user_id'   => '发起用户ID',
+        $table_config['total_column'] = [
+            'id' => 'ID',
+            'total' => '原始金额',
+            'event_user_id' => '发起用户ID',
             'event_user_name' => '发起用户名',
-            'ref_user_id'     => '获利用户ID',
-            'ref_user_name'   => '获利用户名',
-            'ref_get'         => '获利金额',
-            'datetime'        => '时间'
-        );
-        $table_config['default_show_column'] = array();
+            'ref_user_id' => '获利用户ID',
+            'ref_user_name' => '获利用户名',
+            'ref_get' => '获利金额',
+            'datetime' => '时间',
+        ];
+        $table_config['default_show_column'] = [];
         foreach ($table_config['total_column'] as $column => $value) {
             $table_config['default_show_column'][] = $column;
         }
@@ -89,11 +73,9 @@ class AdminController extends UserController
     /**
      * 后台邀请返利页面 AJAX
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax_payback($request, $response, $args)
+    public function ajax_payback(Request $request, Response $response, array $args)
     {
         $datatables = new Datatables(new DatatablesHelper());
         $datatables->query('Select payback.id,payback.total,payback.userid as event_user_id,event_user.user_name as event_user_name,payback.ref_by as ref_user_id,ref_user.user_name as ref_user_name,payback.ref_get,payback.datetime from payback,user as event_user,user as ref_user where event_user.id = payback.userid and ref_user.id = payback.ref_by');
@@ -108,96 +90,90 @@ class AdminController extends UserController
     /**
      * 更改用户邀请者
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function chgInvite($request, $response, $args)
+    public function chgInvite(Request $request, Response $response, array $args)
     {
         $userid = $request->getParam('userid');
-        if ($userid == null) {
+        if ($userid === null) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '邀请者更改失败,检查用户id是否输入正确'
+                'msg' => '邀请者更改失败,检查用户id是否输入正确',
             ]);
         }
-        if (strpos($userid, '@') != false) {
+        if (strpos($userid, '@') !== false) {
             $user = User::where('email', '=', $userid)->first();
         } else {
             $user = User::find((int) $userid);
         }
-        if ($user == null) {
+        if ($user === null) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '邀请者更改失败,检查用户id是否输入正确'
+                'msg' => '邀请者更改失败,检查用户id是否输入正确',
             ]);
         }
         $user->ref_by = $request->getParam('refid', 0);  //如未提供,则删除用户的邀请者
         $user->save();
         return $response->withJson([
             'ret' => 1,
-            'msg' => '邀请者更改成功'
+            'msg' => '邀请者更改成功',
         ]);
     }
 
     /**
      * 为用户添加邀请次数
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function addInvite($request, $response, $args)
+    public function addInvite(Request $request, Response $response, array $args)
     {
         $num = $request->getParam('num');
-        if (Tools::isInt($num) == false) {
+        if (Tools::isInt($num) === false) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '非法请求'
+                'msg' => '非法请求',
             ]);
         }
-        if ($request->getParam('uid') == '0') {
+        if ($request->getParam('uid') === '0') {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '邀请次数添加失败,检查用户id或者用户邮箱是否输入正确'
+                'msg' => '邀请次数添加失败,检查用户id或者用户邮箱是否输入正确',
             ]);
         }
-        if (strpos($request->getParam('uid'), '@') != false) {
+        if (strpos($request->getParam('uid'), '@') !== false) {
             $user = User::where('email', '=', $request->getParam('uid'))->first();
         } else {
             $user = User::find((int) $request->getParam('uid'));
         }
-        if ($user == null) {
+        if ($user === null) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '邀请次数添加失败,检查用户id或者用户邮箱是否输入正确'
+                'msg' => '邀请次数添加失败,检查用户id或者用户邮箱是否输入正确',
             ]);
         }
         $user->addInviteNum($num);
         return $response->withJson([
             'ret' => 1,
-            'msg' => '邀请次数添加成功'
+            'msg' => '邀请次数添加成功',
         ]);
     }
 
     /**
      * 后台商品优惠码页面
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function coupon($request, $response, $args)
+    public function coupon(Request $request, Response $response, array $args)
     {
-        $table_config['total_column'] = array(
-            'id'        => 'ID',
-            'code'      => '优惠码',
-            'expire'    => '过期时间',
-            'shop'      => '限定商品ID',
-            'credit'    => '额度',
-            'onetime'   => '次数'
-        );
-        $table_config['default_show_column'] = array();
+        $table_config['total_column'] = [
+            'id' => 'ID',
+            'code' => '优惠码',
+            'expire' => '过期时间',
+            'shop' => '限定商品ID',
+            'credit' => '额度',
+            'onetime' => '次数',
+        ];
+        $table_config['default_show_column'] = [];
         foreach ($table_config['total_column'] as $column => $value) {
             $table_config['default_show_column'][] = $column;
         }
@@ -212,11 +188,9 @@ class AdminController extends UserController
     /**
      * 后台商品优惠码页面 AJAX
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ajax_coupon($request, $response, $args)
+    public function ajax_coupon(Request $request, Response $response, array $args)
     {
         $datatables = new Datatables(new DatatablesHelper());
         $datatables->query('Select id,code,expire,shop,credit,onetime from coupon');
@@ -231,50 +205,48 @@ class AdminController extends UserController
     /**
      * 添加优惠码
      *
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function addCoupon($request, $response, $args)
+    public function addCoupon(Request $request, Response $response, array $args)
     {
         $generate_type = (int) $request->getParam('generate_type');
-        $final_code    = $request->getParam('prefix');
+        $final_code = $request->getParam('prefix');
         if (empty($final_code) && in_array($generate_type, [1, 3])) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '优惠码不能为空'
+                'msg' => '优惠码不能为空',
             ]);
         }
-        if ($generate_type == 1) {
-            if (Coupon::where('code', $final_code)->count() != 0) {
+        if ($generate_type === 1) {
+            if (Coupon::where('code', $final_code)->count() !== 0) {
                 return $response->withJson([
                     'ret' => 0,
-                    'msg' => '优惠码已存在'
+                    'msg' => '优惠码已存在',
                 ]);
             }
         } else {
             while (true) {
                 $code_str = Tools::genRandomChar(8);
-                if ($generate_type == 3) {
+                if ($generate_type === 3) {
                     $final_code .= $code_str;
                 } else {
-                    $final_code  = $code_str;
+                    $final_code = $code_str;
                 }
-                if (Coupon::where('code', $final_code)->count() == 0) {
+                if (Coupon::where('code', $final_code)->count() === 0) {
                     break;
                 }
             }
         }
-        $code          = new Coupon();
+        $code = new Coupon();
         $code->onetime = $request->getParam('onetime');
-        $code->code    = $final_code;
-        $code->expire  = time() + $request->getParam('expire') * 3600;
-        $code->shop    = $request->getParam('shop');
-        $code->credit  = $request->getParam('credit');
+        $code->code = $final_code;
+        $code->expire = time() + $request->getParam('expire') * 3600;
+        $code->shop = $request->getParam('shop');
+        $code->credit = $request->getParam('credit');
         $code->save();
         return $response->withJson([
             'ret' => 1,
-            'msg' => '优惠码添加成功'
+            'msg' => '优惠码添加成功',
         ]);
     }
 }

+ 153 - 190
src/Controllers/AuthController.php

@@ -1,33 +1,16 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers;
 
-use App\Models\{
-    User,
-    Setting,
-    InviteCode,
-    EmailVerify
-};
-use App\Utils\{
-    GA,
-    Hash,
-    Check,
-    Tools,
-    TelegramSessionManager
-};
-use App\Services\{
-    Auth,
-    Captcha,
-    Mail,
-    Config
-};
-use voku\helper\AntiXSS;
+use Auth;
 use Exception;
+use GA;
 use Ramsey\Uuid\Uuid;
-use Slim\Http\{
-    Request,
-    Response
-};
+use Request;
+use User;
+use voku\helper\AntiXSS;
 
 /**
  *  AuthController
@@ -35,25 +18,23 @@ use Slim\Http\{
 class AuthController extends BaseController
 {
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function login($request, $response, $args)
+    public function login(Request $request, Response $response, array $args)
     {
         $captcha = Captcha::generate();
 
         if ($_ENV['enable_telegram_login'] === true) {
-            $login_text   = TelegramSessionManager::add_login_session();
-            $login        = explode('|', $login_text);
-            $login_token  = $login[0];
+            $login_text = TelegramSessionManager::add_login_session();
+            $login = explode('|', $login_text);
+            $login_token = $login[0];
             $login_number = $login[1];
         } else {
-            $login_token  = '';
+            $login_token = '';
             $login_number = '';
         }
 
-        if (Setting::obtain('enable_login_captcha') == true) {
+        if (Setting::obtain('enable_login_captcha') === true) {
             $geetest_html = $captcha['geetest'];
         } else {
             $geetest_html = null;
@@ -70,67 +51,63 @@ class AuthController extends BaseController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function getCaptcha($request, $response, $args)
+    public function getCaptcha(Request $request, Response $response, array $args)
     {
         $captcha = Captcha::generate();
         return $response->withJson([
             'recaptchaKey' => $captcha['recaptcha'],
-            'GtSdk'        => $captcha['geetest'],
-            'respon'       => 1,
+            'GtSdk' => $captcha['geetest'],
+            'respon' => 1,
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function loginHandle($request, $response, $args)
+    public function loginHandle(Request $request, Response $response, array $args)
     {
-        $email      = trim($request->getParam('email'));
-        $email      = strtolower($email);
-        $passwd     = $request->getParam('passwd');
-        $code       = $request->getParam('code');
+        $email = trim($request->getParam('email'));
+        $email = strtolower($email);
+        $passwd = $request->getParam('passwd');
+        $code = $request->getParam('code');
         $rememberMe = $request->getParam('remember_me');
 
-        if (Setting::obtain('enable_login_captcha') == true) {
+        if (Setting::obtain('enable_login_captcha') === true) {
             $ret = Captcha::verify($request->getParams());
-            if (!$ret) {
+            if (! $ret) {
                 return $response->withJson([
                     'ret' => 0,
-                    'msg' => '系统无法接受您的验证结果,请刷新页面后重试。'
+                    'msg' => '系统无法接受您的验证结果,请刷新页面后重试。',
                 ]);
             }
         }
 
         $user = User::where('email', $email)->first();
-        if ($user == null) {
+        if ($user === null) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '邮箱不存在'
+                'msg' => '邮箱不存在',
             ]);
         }
 
-        if (!Hash::checkPassword($user->pass, $passwd)) {
+        if (! Hash::checkPassword($user->pass, $passwd)) {
             // 记录登录失败
             $user->collectLoginIP($_SERVER['REMOTE_ADDR'], 1);
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '邮箱或者密码错误'
+                'msg' => '邮箱或者密码错误',
             ]);
         }
 
-        if ($user->ga_enable == 1) {
-            $ga    = new GA();
+        if ($user->ga_enable === 1) {
+            $ga = new GA();
             $rcode = $ga->verifyCode($user->ga_token, $code);
-            if (!$rcode) {
+            if (! $rcode) {
                 return $response->withJson([
                     'ret' => 0,
-                    'msg' => '两步验证码错误,如果您是丢失了生成器或者错误地设置了这个选项,您可以尝试重置密码,即可取消这个选项。'
+                    'msg' => '两步验证码错误,如果您是丢失了生成器或者错误地设置了这个选项,您可以尝试重置密码,即可取消这个选项。',
                 ]);
             }
         }
@@ -146,25 +123,23 @@ class AuthController extends BaseController
 
         return $response->withJson([
             'ret' => 1,
-            'msg' => '登录成功'
+            'msg' => '登录成功',
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function qrcode_loginHandle($request, $response, $args)
+    public function qrcode_loginHandle(Request $request, Response $response, array $args)
     {
-        $token  = $request->getParam('token');
+        $token = $request->getParam('token');
         $number = $request->getParam('number');
 
         $ret = TelegramSessionManager::step2_verify_login_session($token, $number);
         if ($ret === 0) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '此令牌无法被使用。'
+                'msg' => '此令牌无法被使用。',
             ]);
         }
 
@@ -176,37 +151,35 @@ class AuthController extends BaseController
 
         return $response->withJson([
             'ret' => 1,
-            'msg' => '登录成功'
+            'msg' => '登录成功',
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function register($request, $response, $next)
+    public function register(Request $request, Response $response, $next)
     {
-        $ary  = $request->getQueryParams();
+        $ary = $request->getQueryParams();
         $code = '';
         if (isset($ary['code'])) {
             $antiXss = new AntiXSS();
-            $code    = $antiXss->xss_clean($ary['code']);
+            $code = $antiXss->xss_clean($ary['code']);
         }
 
         $captcha = Captcha::generate();
 
         if ($_ENV['enable_telegram_login'] === true) {
-            $login_text   = TelegramSessionManager::add_login_session();
-            $login        = explode('|', $login_text);
-            $login_token  = $login[0];
+            $login_text = TelegramSessionManager::add_login_session();
+            $login = explode('|', $login_text);
+            $login_token = $login[0];
             $login_number = $login[1];
         } else {
-            $login_token  = '';
+            $login_token = '';
             $login_number = '';
         }
 
-        if (Setting::obtain('enable_reg_captcha') == true) {
+        if (Setting::obtain('enable_reg_captcha') === true) {
             $geetest_html = $captcha['geetest'];
         } else {
             $geetest_html = null;
@@ -225,53 +198,51 @@ class AuthController extends BaseController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function sendVerify($request, $response, $next)
+    public function sendVerify(Request $request, Response $response, $next)
     {
         if (Setting::obtain('reg_email_verify')) {
             $email = trim($request->getParam('email'));
             $email = strtolower($email);
-            if ($email == '') {
+            if ($email === '') {
                 return $response->withJson([
                     'ret' => 0,
-                    'msg' => '未填写邮箱'
+                    'msg' => '未填写邮箱',
                 ]);
             }
             // check email format
             $check_res = Check::isEmailLegal($email);
-            if ($check_res['ret'] == 0) {
+            if ($check_res['ret'] === 0) {
                 return $response->withJson($check_res);
             }
             $user = User::where('email', $email)->first();
-            if ($user != null) {
+            if ($user !== null) {
                 return $response->withJson([
                     'ret' => 0,
-                    'msg' => '此邮箱已经注册'
+                    'msg' => '此邮箱已经注册',
                 ]);
             }
             $ipcount = EmailVerify::where('ip', '=', $_SERVER['REMOTE_ADDR'])->where('expire_in', '>', time())->count();
             if ($ipcount >= Setting::obtain('email_verify_ip_limit')) {
                 return $response->withJson([
                     'ret' => 0,
-                    'msg' => '此IP请求次数过多'
+                    'msg' => '此IP请求次数过多',
                 ]);
             }
             $mailcount = EmailVerify::where('email', '=', $email)->where('expire_in', '>', time())->count();
             if ($mailcount >= 3) {
                 return $response->withJson([
                     'ret' => 0,
-                    'msg' => '此邮箱请求次数过多'
+                    'msg' => '此邮箱请求次数过多',
                 ]);
             }
-            $code          = Tools::genRandomNum(6);
-            $ev            = new EmailVerify();
+            $code = Tools::genRandomNum(6);
+            $ev = new EmailVerify();
             $ev->expire_in = time() + Setting::obtain('email_verify_ttl');
-            $ev->ip        = $_SERVER['REMOTE_ADDR'];
-            $ev->email     = $email;
-            $ev->code      = $code;
+            $ev->ip = $_SERVER['REMOTE_ADDR'];
+            $ev->email = $email;
+            $ev->code = $code;
             $ev->save();
             try {
                 Mail::send(
@@ -280,24 +251,24 @@ class AuthController extends BaseController
                     'auth/verify.tpl',
                     [
                         'code' => $code,
-                        'expire' => date('Y-m-d H:i:s', time() + Setting::obtain('email_verify_ttl'))
+                        'expire' => date('Y-m-d H:i:s', time() + Setting::obtain('email_verify_ttl')),
                     ],
                     []
                 );
             } catch (Exception $e) {
                 return $response->withJson([
                     'ret' => 0,
-                    'msg' => '邮件发送失败,请联系网站管理员。'
+                    'msg' => '邮件发送失败,请联系网站管理员。',
                 ]);
             }
             return $response->withJson([
                 'ret' => 1,
-                'msg' => '验证码发送成功,请查收邮件。'
+                'msg' => '验证码发送成功,请查收邮件。',
             ]);
         }
         return $response->withJson([
             'ret' => 0,
-            'msg' => ''
+            'msg' => '',
         ]);
     }
 
@@ -308,34 +279,34 @@ class AuthController extends BaseController
      */
     public function register_helper($name, $email, $passwd, $code, $imtype, $imvalue, $telegram_id)
     {
-        if (Setting::obtain('reg_mode') == 'close') {
+        if (Setting::obtain('reg_mode') === 'close') {
             $res['ret'] = 0;
             $res['msg'] = '暂时不对外开放注册';
             return $res;
         }
 
-        if ($code == '') {
+        if ($code === '') {
             $res['ret'] = 0;
             $res['msg'] = '注册需要填写邀请码';
             return $res;
         }
 
         $c = InviteCode::where('code', $code)->first();
-        if ($c == null) {
-            if (Setting::obtain('reg_mode') == 'invite') {
+        if ($c === null) {
+            if (Setting::obtain('reg_mode') === 'invite') {
                 $res['ret'] = 0;
                 $res['msg'] = '这个邀请码不存在';
                 return $res;
             }
-        } elseif ($c->user_id != 0) {
+        } elseif ($c->user_id !== 0) {
             $gift_user = User::where('id', $c->user_id)->first();
-            if ($gift_user == null) {
+            if ($gift_user === null) {
                 $res['ret'] = 0;
                 $res['msg'] = '邀请码已失效';
                 return $res;
             }
 
-            if ($gift_user->invite_num == 0) {
+            if ($gift_user->invite_num === 0) {
                 $res['ret'] = 0;
                 $res['msg'] = '邀请码不可用';
                 return $res;
@@ -344,46 +315,46 @@ class AuthController extends BaseController
 
         $configs = Setting::getClass('register');
         // do reg user
-        $user                       = new User();
-        $antiXss                    = new AntiXSS();
-        $current_timestamp          = time();
-
-        $user->user_name            = $antiXss->xss_clean($name);
-        $user->email                = $email;
-        $user->pass                 = Hash::passwordHash($passwd);
-        $user->passwd               = Tools::genRandomChar(16);
-        $user->uuid                 = Uuid::uuid3(Uuid::NAMESPACE_DNS, $email . '|' . $current_timestamp);
-        $user->port                 = Tools::getAvPort();
-        $user->t                    = 0;
-        $user->u                    = 0;
-        $user->d                    = 0;
-        $user->method               = $configs['sign_up_for_method'];
-        $user->protocol             = $configs['sign_up_for_protocol'];
-        $user->protocol_param       = $configs['sign_up_for_protocol_param'];
-        $user->obfs                 = $configs['sign_up_for_obfs'];
-        $user->obfs_param           = $configs['sign_up_for_obfs_param'];
-        $user->forbidden_ip         = $_ENV['reg_forbidden_ip'];
-        $user->forbidden_port       = $_ENV['reg_forbidden_port'];
-        $user->im_type              = $imtype;
-        $user->im_value             = $antiXss->xss_clean($imvalue);
-
-        $user->transfer_enable      = Tools::toGB($configs['sign_up_for_free_traffic']);
-        $user->invite_num           = $configs['sign_up_for_invitation_codes'];
-        $user->auto_reset_day       = $_ENV['free_user_reset_day'];
+        $user = new User();
+        $antiXss = new AntiXSS();
+        $current_timestamp = time();
+
+        $user->user_name = $antiXss->xss_clean($name);
+        $user->email = $email;
+        $user->pass = Hash::passwordHash($passwd);
+        $user->passwd = Tools::genRandomChar(16);
+        $user->uuid = Uuid::uuid3(Uuid::NAMESPACE_DNS, $email . '|' . $current_timestamp);
+        $user->port = Tools::getAvPort();
+        $user->t = 0;
+        $user->u = 0;
+        $user->d = 0;
+        $user->method = $configs['sign_up_for_method'];
+        $user->protocol = $configs['sign_up_for_protocol'];
+        $user->protocol_param = $configs['sign_up_for_protocol_param'];
+        $user->obfs = $configs['sign_up_for_obfs'];
+        $user->obfs_param = $configs['sign_up_for_obfs_param'];
+        $user->forbidden_ip = $_ENV['reg_forbidden_ip'];
+        $user->forbidden_port = $_ENV['reg_forbidden_port'];
+        $user->im_type = $imtype;
+        $user->im_value = $antiXss->xss_clean($imvalue);
+
+        $user->transfer_enable = Tools::toGB($configs['sign_up_for_free_traffic']);
+        $user->invite_num = $configs['sign_up_for_invitation_codes'];
+        $user->auto_reset_day = $_ENV['free_user_reset_day'];
         $user->auto_reset_bandwidth = $_ENV['free_user_reset_bandwidth'];
-        $user->money                = 0;
-        $user->sendDailyMail        = $configs['sign_up_for_daily_report'];
+        $user->money = 0;
+        $user->sendDailyMail = $configs['sign_up_for_daily_report'];
 
         //dumplin:填写邀请人,写入邀请奖励
         $user->ref_by = 0;
-        if ($c != null && $c->user_id != 0) {
+        if ($c !== null && $c->user_id !== 0) {
             $invitation = Setting::getClass('invite');
             // 设置新用户
             $user->ref_by = $c->user_id;
             $user->money = $invitation['invitation_to_register_balance_reward'];
             // 给邀请人反流量
             $gift_user->transfer_enable += $invitation['invitation_to_register_traffic_reward'] * 1024 * 1024 * 1024;
-            if (($gift_user->invite_num - 1) >= 0) {
+            if ($gift_user->invite_num - 1 >= 0) {
                 --$gift_user->invite_num;
                 // 避免设置为不限制邀请次数的值 -1 发生变动
             }
@@ -394,20 +365,20 @@ class AuthController extends BaseController
             $user->telegram_id = $telegram_id;
         }
 
-        $ga                     = new GA();
-        $secret                 = $ga->createSecret();
-        $user->ga_token         = $secret;
-        $user->ga_enable        = 0;
-        $user->class_expire     = date('Y-m-d H:i:s', time() + $configs['sign_up_for_class_time'] * 86400);
-        $user->class            = $configs['sign_up_for_class'];
-        $user->node_connector   = $configs['connection_device_limit'];
-        $user->node_speedlimit  = $configs['connection_rate_limit'];
-        $user->expire_in        = date('Y-m-d H:i:s', time() + $configs['sign_up_for_free_time'] * 86400);
-        $user->reg_date         = date('Y-m-d H:i:s');
-        $user->reg_ip           = $_SERVER['REMOTE_ADDR'];
-        $user->theme            = $_ENV['theme'];
-        $groups                 = explode(',', $_ENV['random_group']);
-        $user->node_group       = $groups[array_rand($groups)];
+        $ga = new GA();
+        $secret = $ga->createSecret();
+        $user->ga_token = $secret;
+        $user->ga_enable = 0;
+        $user->class_expire = date('Y-m-d H:i:s', time() + $configs['sign_up_for_class_time'] * 86400);
+        $user->class = $configs['sign_up_for_class'];
+        $user->node_connector = $configs['connection_device_limit'];
+        $user->node_speedlimit = $configs['connection_rate_limit'];
+        $user->expire_in = date('Y-m-d H:i:s', time() + $configs['sign_up_for_free_time'] * 86400);
+        $user->reg_date = date('Y-m-d H:i:s');
+        $user->reg_ip = $_SERVER['REMOTE_ADDR'];
+        $user->theme = $_ENV['theme'];
+        $groups = explode(',', $_ENV['random_group']);
+        $user->node_group = $groups[array_rand($groups)];
 
         if ($user->save()) {
             Auth::login($user->id, 3600);
@@ -424,80 +395,78 @@ class AuthController extends BaseController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function registerHandle($request, $response, $args)
+    public function registerHandle(Request $request, Response $response, array $args)
     {
-        if (Setting::obtain('reg_mode') == 'close') {
+        if (Setting::obtain('reg_mode') === 'close') {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '未开放注册。'
+                'msg' => '未开放注册。',
             ]);
         }
 
-        $name      = $request->getParam('name');
-        $email     = $request->getParam('email');
-        $email     = trim($email);
-        $email     = strtolower($email);
-        $passwd    = $request->getParam('passwd');
-        $repasswd  = $request->getParam('repasswd');
-        $code      = trim($request->getParam('code'));
+        $name = $request->getParam('name');
+        $email = $request->getParam('email');
+        $email = trim($email);
+        $email = strtolower($email);
+        $passwd = $request->getParam('passwd');
+        $repasswd = $request->getParam('repasswd');
+        $code = trim($request->getParam('code'));
         $emailcode = $request->getParam('emailcode');
         $emailcode = trim($emailcode);
 
         if ($_ENV['enable_reg_im'] === true) {
-            $imtype  = $request->getParam('im_type');
+            $imtype = $request->getParam('im_type');
             $imvalue = $request->getParam('im_value');
-            if ($imtype == '' || $imvalue == '') {
+            if ($imtype === '' || $imvalue === '') {
                 return $response->withJson([
                     'ret' => 0,
-                    'msg' => '请填上你的联络方式'
+                    'msg' => '请填上你的联络方式',
                 ]);
             }
             $user = User::where('im_value', $imvalue)->where('im_type', $imtype)->first();
-            if ($user != null) {
+            if ($user !== null) {
                 return $response->withJson([
                     'ret' => 0,
-                    'msg' => '此联络方式已注册'
+                    'msg' => '此联络方式已注册',
                 ]);
             }
         } else {
-            $imtype  = 1;
+            $imtype = 1;
             $imvalue = '';
         }
 
-        if (Setting::obtain('enable_reg_captcha') == true) {
+        if (Setting::obtain('enable_reg_captcha') === true) {
             $ret = Captcha::verify($request->getParams());
-            if (!$ret) {
+            if (! $ret) {
                 return $response->withJson([
                     'ret' => 0,
-                    'msg' => '系统无法接受您的验证结果,请刷新页面后重试。'
+                    'msg' => '系统无法接受您的验证结果,请刷新页面后重试。',
                 ]);
             }
         }
 
         // check email format
         $check_res = Check::isEmailLegal($email);
-        if ($check_res['ret'] == 0) {
+        if ($check_res['ret'] === 0) {
             return $response->withJson($check_res);
         }
         // check email
         $user = User::where('email', $email)->first();
-        if ($user != null) {
+        if ($user !== null) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '邮箱已经被注册了'
+                'msg' => '邮箱已经被注册了',
             ]);
         }
 
         if (Setting::obtain('reg_email_verify')) {
             $mailcount = EmailVerify::where('email', '=', $email)->where('code', '=', $emailcode)->where('expire_in', '>', time())->first();
-            if ($mailcount == null) {
+            if ($mailcount === null) {
                 return $response->withJson([
                     'ret' => 0,
-                    'msg' => '您的邮箱验证码不正确'
+                    'msg' => '您的邮箱验证码不正确',
                 ]);
             }
         }
@@ -506,15 +475,15 @@ class AuthController extends BaseController
         if (strlen($passwd) < 8) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '密码请大于8位'
+                'msg' => '密码请大于8位',
             ]);
         }
 
         // check pwd re
-        if ($passwd != $repasswd) {
+        if ($passwd !== $repasswd) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '两次密码输入不符'
+                'msg' => '两次密码输入不符',
             ]);
         }
 
@@ -528,29 +497,25 @@ class AuthController extends BaseController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function logout($request, $response, $next)
+    public function logout(Request $request, Response $response, $next)
     {
         Auth::logout();
         return $response->withStatus(302)->withHeader('Location', '/auth/login');
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function qrcode_check($request, $response, $args)
+    public function qrcode_check(Request $request, Response $response, array $args)
     {
-        $token  = $request->getParam('token');
+        $token = $request->getParam('token');
         $number = $request->getParam('number');
-        $user   = Auth::getUser();
+        $user = Auth::getUser();
         if ($user->isLogin) {
             return $response->withJson([
-                'ret' => 0
+                'ret' => 0,
             ]);
         }
         if ($_ENV['enable_telegram_login'] === true) {
@@ -559,23 +524,21 @@ class AuthController extends BaseController
             return $response->withJson($res);
         }
         return $response->withJson([
-            'ret' => 0
+            'ret' => 0,
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function telegram_oauth($request, $response, $args)
+    public function telegram_oauth(Request $request, Response $response, array $args)
     {
         if ($_ENV['enable_telegram_login'] === true) {
             $auth_data = $request->getQueryParams();
             if ($this->telegram_oauth_check($auth_data) === true) { // Looks good, proceed.
                 $telegram_id = $auth_data['id'];
-                $user        = User::query()->where('telegram_id', $telegram_id)->firstOrFail(); // Welcome Back :)
-                if ($user == null) {
+                $user = User::query()->where('telegram_id', $telegram_id)->firstOrFail(); // Welcome Back :)
+                if ($user === null) {
                     return $this->view()
                         ->assign('title', '您需要先进行邮箱注册后绑定Telegram才能使用授权登录')
                         ->assign('message', '很抱歉带来的不便,请重新试试')
@@ -612,7 +575,7 @@ class AuthController extends BaseController
     private function telegram_oauth_check($auth_data)
     {
         $check_hash = $auth_data['hash'];
-        $bot_token  = $_ENV['telegram_token'];
+        $bot_token = $_ENV['telegram_token'];
         unset($auth_data['hash']);
         $data_check_arr = [];
         foreach ($auth_data as $key => $value) {
@@ -620,13 +583,13 @@ class AuthController extends BaseController
         }
         sort($data_check_arr);
         $data_check_string = implode("\n", $data_check_arr);
-        $secret_key        = hash('sha256', $bot_token, true);
-        $hash              = hash_hmac('sha256', $data_check_string, $secret_key);
+        $secret_key = hash('sha256', $bot_token, true);
+        $hash = hash_hmac('sha256', $data_check_string, $secret_key);
         if (strcmp($hash, $check_hash) !== 0) {
             return false; // Bad Data :(
         }
 
-        if ((time() - $auth_data['auth_date']) > 300) { // Expire @ 5mins
+        if (time() - $auth_data['auth_date'] > 300) { // Expire @ 5mins
             return false;
         }
 

+ 5 - 7
src/Controllers/BaseController.php

@@ -1,12 +1,12 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers;
 
 use App\Models\User;
-use App\Services\{
-    Auth,
-    View
-};
+use App\Services\Auth;
+use App\Services\View;
 use Smarty;
 
 /**
@@ -35,10 +35,8 @@ class BaseController
 
     /**
      * Get smarty
-     *
-     * @return Smarty
      */
-    public function view()
+    public function view(): Smarty
     {
         if (View::$connection) {
             $this->view->assign('queryLog', View::$connection->connection('default')->getQueryLog())->assign('optTime', (microtime(true) - View::$beginTime) * 1000);

+ 13 - 33
src/Controllers/HomeController.php

@@ -1,17 +1,13 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers;
 
 use App\Models\InviteCode;
-use App\Utils\{
-    TelegramProcess,
-    Telegram\Process
-};
-use Slim\Http\{
-    Request,
-    Response
-};
 use Psr\Http\Message\ResponseInterface;
+use Request;
+use TelegramProcess;
 
 /**
  *  HomeController
@@ -19,55 +15,45 @@ use Psr\Http\Message\ResponseInterface;
 class HomeController extends BaseController
 {
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function index($request, $response, $args): ResponseInterface
+    public function index(Request $request, Response $response, array $args): ResponseInterface
     {
         return $response->write($this->view()->fetch('index.tpl'));
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function code($request, $response, $args): ResponseInterface
+    public function code(Request $request, Response $response, array $args): ResponseInterface
     {
         $codes = InviteCode::where('user_id', '=', '0')->take(10)->get();
         return $response->write($this->view()->assign('codes', $codes)->fetch('code.tpl'));
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function tos($request, $response, $args): ResponseInterface
+    public function tos(Request $request, Response $response, array $args): ResponseInterface
     {
         return $response->write($this->view()->fetch('tos.tpl'));
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function staff($request, $response, $args): ResponseInterface
+    public function staff(Request $request, Response $response, array $args): ResponseInterface
     {
         return $response->write($this->view()->fetch('staff.tpl'));
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function telegram($request, $response, $args): ResponseInterface
+    public function telegram(Request $request, Response $response, array $args): ResponseInterface
     {
         $token = $request->getQueryParam('token');
-        if ($token == $_ENV['telegram_request_token']) {
+        if ($token === $_ENV['telegram_request_token']) {
             if ($_ENV['use_new_telegram_bot']) {
                 Process::index();
             } else {
@@ -81,31 +67,25 @@ class HomeController extends BaseController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function page404($request, $response, $args): ResponseInterface
+    public function page404(Request $request, Response $response, array $args): ResponseInterface
     {
         return $response->write($this->view()->fetch('404.tpl'));
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function page405($request, $response, $args): ResponseInterface
+    public function page405(Request $request, Response $response, array $args): ResponseInterface
     {
         return $response->write($this->view()->fetch('405.tpl'));
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function page500($request, $response, $args): ResponseInterface
+    public function page500(Request $request, Response $response, array $args): ResponseInterface
     {
         return $response->write($this->view()->fetch('500.tpl'));
     }

+ 173 - 201
src/Controllers/LinkController.php

@@ -1,27 +1,16 @@
 <?php
 
+declare(strict_types=1);
+
 //Thanks to http://blog.csdn.net/jollyjumper/article/details/9823047
 
 namespace App\Controllers;
 
-use App\Models\{
-    Link,
-    User,
-    UserSubscribeLog
-};
-use App\Utils\{
-    URL,
-    Tools,
-    AppURI,
-    ConfGenerate,
-    ConfRender
-};
-use voku\helper\AntiXSS;
+use Link;
 use Psr\Http\Message\ResponseInterface;
-use Slim\Http\{
-    Request,
-    Response
-};
+use Request;
+use URL;
+use voku\helper\AntiXSS;
 
 /**
  *  LinkController
@@ -33,7 +22,7 @@ class LinkController extends BaseController
         for ($i = 0; $i < 10; $i++) {
             $token = Tools::genRandomChar(16);
             $Elink = Link::where('token', $token)->first();
-            if ($Elink == null) {
+            if ($Elink === null) {
                 return $token;
             }
         }
@@ -41,43 +30,38 @@ class LinkController extends BaseController
         return "couldn't alloc token";
     }
 
-    /**
-     * @param int $userid
-     */
     public static function GenerateSSRSubCode(int $userid): string
     {
         $Elink = Link::where('userid', $userid)->first();
-        if ($Elink != null) {
+        if ($Elink !== null) {
             return $Elink->token;
         }
-        $NLink         = new Link();
+        $NLink = new Link();
         $NLink->userid = $userid;
-        $NLink->token  = self::GenerateRandomLink();
+        $NLink->token = self::GenerateRandomLink();
         $NLink->save();
 
         return $NLink->token;
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public static function GetContent($request, $response, $args)
+    public static function GetContent(Request $request, Response $response, array $args)
     {
-        if (!$_ENV['Subscribe']) {
+        if (! $_ENV['Subscribe']) {
             return null;
         }
 
         $token = $args['token'];
 
         $Elink = Link::where('token', $token)->first();
-        if ($Elink == null) {
+        if ($Elink === null) {
             return null;
         }
 
         $user = $Elink->getUser();
-        if ($user == null) {
+        if ($user === null) {
             return null;
         }
 
@@ -86,7 +70,9 @@ class LinkController extends BaseController
         // 筛选节点部分
         $Rule['type'] = (isset($opts['type']) ? trim($opts['type']) : 'all');
         $Rule['is_mu'] = ($_ENV['mergeSub'] === true ? 1 : 0);
-        if (isset($opts['mu'])) $Rule['is_mu'] = (int) $opts['mu'];
+        if (isset($opts['mu'])) {
+            $Rule['is_mu'] = (int) $opts['mu'];
+        }
 
         if (isset($opts['class'])) {
             $class = trim(urldecode($opts['class']));
@@ -155,15 +141,15 @@ class LinkController extends BaseController
         foreach ($sub_type_array as $key) {
             if (isset($opts[$key])) {
                 $query_value = $opts[$key];
-                if ($query_value != '0' && $query_value != '') {
+                if ($query_value !== '0' && $query_value !== '') {
 
                     // 兼容代码开始
-                    if ($key == 'sub' && $query_value > 4) {
+                    if ($key === 'sub' && $query_value > 4) {
                         $query_value = 1;
                     }
                     // 兼容代码结束
 
-                    if ($key == 'list') {
+                    if ($key === 'list') {
                         $SubscribeExtend = self::getSubscribeExtend($query_value);
                     } else {
                         $SubscribeExtend = self::getSubscribeExtend($key, $query_value);
@@ -171,7 +157,7 @@ class LinkController extends BaseController
                     $filename = $SubscribeExtend['filename'] . '_' . time() . '.' . $SubscribeExtend['suffix'];
                     $subscribe_type = $SubscribeExtend['filename'];
 
-                    $class = ('get' . $SubscribeExtend['class']);
+                    $class = 'get' . $SubscribeExtend['class'];
                     $content = self::$class($user, $query_value, $opts, $Rule);
                     $getBody = self::getBody(
                         $user,
@@ -201,28 +187,28 @@ class LinkController extends BaseController
      *
      * @return array
      */
-    public static function getSubscribeExtend($type, $value = null)
+    public static function getSubscribeExtend(string $type, ?string $value = null): array
     {
         switch ($type) {
             case 'ss':
                 $return = [
                     'filename' => 'SS',
-                    'suffix'   => 'txt',
-                    'class'    => 'Sub'
+                    'suffix' => 'txt',
+                    'class' => 'Sub',
                 ];
                 break;
             case 'ssa':
                 $return = [
                     'filename' => 'SSA',
-                    'suffix'   => 'json',
-                    'class'    => 'Lists'
+                    'suffix' => 'json',
+                    'class' => 'Lists',
                 ];
                 break;
             case 'ssr':
                 $return = [
                     'filename' => 'SSR',
-                    'suffix'   => 'txt',
-                    'class'    => 'Sub'
+                    'suffix' => 'txt',
+                    'class' => 'Sub',
                 ];
                 break;
             case 'sub':
@@ -232,7 +218,7 @@ class LinkController extends BaseController
                     3 => 'v2rayn',
                     4 => 'trojan',
                 ];
-                $str = (!in_array($value, $strArray) ? $strArray[$value] : $strArray[1]);
+                $str = (! in_array($value, $strArray) ? $strArray[$value] : $strArray[1]);
                 $return = self::getSubscribeExtend($str);
                 break;
             case 'clash':
@@ -242,8 +228,8 @@ class LinkController extends BaseController
                 } else {
                     $return = [
                         'filename' => 'Clash',
-                        'suffix'   => 'yaml',
-                        'class'    => 'Lists'
+                        'suffix' => 'yaml',
+                        'class' => 'Lists',
                     ];
                 }
                 break;
@@ -251,56 +237,56 @@ class LinkController extends BaseController
                 if ($value !== null) {
                     $return = [
                         'filename' => 'Surge',
-                        'suffix'   => 'conf',
-                        'class'    => 'Surge'
+                        'suffix' => 'conf',
+                        'class' => 'Surge',
                     ];
                     $return['filename'] .= $value;
                 } else {
                     $return = [
                         'filename' => 'SurgeList',
-                        'suffix'   => 'list',
-                        'class'    => 'Lists'
+                        'suffix' => 'list',
+                        'class' => 'Lists',
                     ];
                 }
                 break;
             case 'v2rayn':
                 $return = [
                     'filename' => 'V2RayN',
-                    'suffix'   => 'txt',
-                    'class'    => 'Sub'
+                    'suffix' => 'txt',
+                    'class' => 'Sub',
                 ];
                 break;
             case 'trojan':
                 $return = [
                     'filename' => 'Trojan',
-                    'suffix'   => 'txt',
-                    'class'    => 'Sub'
+                    'suffix' => 'txt',
+                    'class' => 'Sub',
                 ];
                 break;
             case 'kitsunebi':
                 $return = [
                     'filename' => 'Kitsunebi',
-                    'suffix'   => 'txt',
-                    'class'    => 'Lists'
+                    'suffix' => 'txt',
+                    'class' => 'Lists',
                 ];
                 break;
             case 'anxray':
                 $return = [
                     'filename' => 'AnXray',
-                    'suffix'   => 'txt',
-                    'class'    => 'AnXray'
+                    'suffix' => 'txt',
+                    'class' => 'AnXray',
                 ];
-                break;	
+                break;
             case 'surfboard':
                 $return = [
                     'filename' => 'Surfboard',
-                    'suffix'   => 'conf',
-                    'class'    => 'Surfboard'
+                    'suffix' => 'conf',
+                    'class' => 'Surfboard',
                 ];
                 break;
             case 'quantumult':
                 if ($value !== null) {
-                    if ((int) $value == 2) {
+                    if ((int) $value === 2) {
                         $return = self::getSubscribeExtend('quantumult_sub');
                     } else {
                         $return = self::getSubscribeExtend('quantumult_conf');
@@ -308,16 +294,16 @@ class LinkController extends BaseController
                 } else {
                     $return = [
                         'filename' => 'Quantumult',
-                        'suffix'   => 'conf',
-                        'class'    => 'Lists'
+                        'suffix' => 'conf',
+                        'class' => 'Lists',
                     ];
                 }
                 break;
             case 'quantumultx':
                 $return = [
                     'filename' => 'QuantumultX',
-                    'suffix'   => 'txt',
-                    'class'    => 'Lists'
+                    'suffix' => 'txt',
+                    'class' => 'Lists',
                 ];
                 if ($value !== null) {
                     $return['class'] = 'QuantumultX';
@@ -326,74 +312,49 @@ class LinkController extends BaseController
             case 'shadowrocket':
                 $return = [
                     'filename' => 'Shadowrocket',
-                    'suffix'   => 'txt',
-                    'class'    => 'Lists'
+                    'suffix' => 'txt',
+                    'class' => 'Lists',
                 ];
                 break;
             case 'clash_provider':
                 $return = [
                     'filename' => 'ClashProvider',
-                    'suffix'   => 'yaml',
-                    'class'    => 'Lists'
+                    'suffix' => 'yaml',
+                    'class' => 'Lists',
                 ];
                 break;
             case 'quantumult_sub':
                 $return = [
                     'filename' => 'QuantumultSub',
-                    'suffix'   => 'conf',
-                    'class'    => 'Quantumult'
+                    'suffix' => 'conf',
+                    'class' => 'Quantumult',
                 ];
                 break;
             case 'quantumult_conf':
                 $return = [
                     'filename' => 'QuantumultConf',
-                    'suffix'   => 'conf',
-                    'class'    => 'Quantumult'
+                    'suffix' => 'conf',
+                    'class' => 'Quantumult',
                 ];
                 break;
             default:
                 $return = [
                     'filename' => 'UndefinedNode',
-                    'suffix'   => 'txt',
-                    'class'    => 'Sub'
+                    'suffix' => 'txt',
+                    'class' => 'Sub',
                 ];
                 break;
         }
         return $return;
     }
 
-    /**
-     * 记录订阅日志
-     *
-     * @param User   $user 用户
-     * @param string $type 订阅类型
-     * @param string $ua   UA
-     *
-     * @return void
-     */
-    private static function Subscribe_log($user, $type, $ua)
-    {
-        $log                     = new UserSubscribeLog();
-        $log->user_name          = $user->user_name;
-        $log->user_id            = $user->id;
-        $log->email              = $user->email;
-        $log->subscribe_type     = $type;
-        $log->request_ip         = $_SERVER['REMOTE_ADDR'];
-        $log->request_time       = date('Y-m-d H:i:s');
-        $antiXss                 = new AntiXSS();
-        $log->request_user_agent = $antiXss->xss_clean($ua);
-        $log->save();
-    }
-
     /**
      * 响应内容
      *
-     * @param User   $user
-     * @param object $response
      * @param string $content  订阅内容
      * @param string $filename 文件名
      */
-    public static function getBody($user, $response, $content, $filename): ResponseInterface
+    public static function getBody(User $user, object $response, string $content, string $filename): ResponseInterface
     {
         $response = $response
             ->withHeader(
@@ -427,42 +388,42 @@ class LinkController extends BaseController
      *
      * @return array
      */
-    public static function getSubinfo($user, $int = 0)
+    public static function getSubinfo(User $user, int $int = 0): array
     {
-        if ($int == 0) {
+        if ($int === 0) {
             $int = '';
         }
         $userapiUrl = $_ENV['subUrl'] . self::GenerateSSRSubCode($user->id);
         $return_info = [
-            'link'            => '',
+            'link' => '',
             // sub
-            'ss'              => '?sub=2',
-            'ssr'             => '?sub=1',
-            'v2ray'           => '?sub=3',
-            'trojan'          => '?sub=4',
+            'ss' => '?sub=2',
+            'ssr' => '?sub=1',
+            'v2ray' => '?sub=3',
+            'trojan' => '?sub=4',
             // apps
-            'ssa'             => '?list=ssa',
-            'anxray'		  => '?anxray=1',
-            'clash'           => '?clash=1',
-            'clash_provider'  => '?list=clash',
-            'surge'           => '?surge=' . $int,
-            'surge_node'      => '?list=surge',
-            'surge2'          => '?surge=2',
-            'surge3'          => '?surge=3',
-            'surge4'          => '?surge=4',
-            'surfboard'       => '?surfboard=1',
-            'quantumult'      => '?quantumult=' . $int,
-            'quantumult_v2'   => '?list=quantumult',
-            'quantumult_sub'  => '?quantumult=2',
+            'ssa' => '?list=ssa',
+            'anxray' => '?anxray=1',
+            'clash' => '?clash=1',
+            'clash_provider' => '?list=clash',
+            'surge' => '?surge=' . $int,
+            'surge_node' => '?list=surge',
+            'surge2' => '?surge=2',
+            'surge3' => '?surge=3',
+            'surge4' => '?surge=4',
+            'surfboard' => '?surfboard=1',
+            'quantumult' => '?quantumult=' . $int,
+            'quantumult_v2' => '?list=quantumult',
+            'quantumult_sub' => '?quantumult=2',
             'quantumult_conf' => '?quantumult=3',
-            'quantumultx'     => '?list=quantumultx',
-            'shadowrocket'    => '?list=shadowrocket',
-            'kitsunebi'       => '?list=kitsunebi'
+            'quantumultx' => '?list=quantumultx',
+            'shadowrocket' => '?list=shadowrocket',
+            'kitsunebi' => '?list=kitsunebi',
         ];
 
         return array_map(
             function ($item) use ($userapiUrl) {
-                return ($userapiUrl . $item);
+                return $userapiUrl . $item;
             },
             $return_info
         );
@@ -483,7 +444,7 @@ class LinkController extends BaseController
                 break;
             case 'anxray':
                 $return = AppURI::getAnXrayURI($item);
-                break;	
+                break;
             case 'surge':
                 $return = AppURI::getSurgeURI($item, 3);
                 break;
@@ -515,13 +476,13 @@ class LinkController extends BaseController
     public static function getLists($user, $list, $opts, $Rule)
     {
         $list = strtolower($list);
-        if ($list == 'ssa') {
+        if ($list === 'ssa') {
             $Rule['type'] = 'ss';
         }
-        if ($list == 'quantumult') {
+        if ($list === 'quantumult') {
             $Rule['type'] = 'vmess';
         }
-        if ($list == 'shadowrocket') {
+        if ($list === 'shadowrocket') {
             // Shadowrocket 自带 emoji
             $Rule['emoji'] = false;
         }
@@ -540,7 +501,7 @@ class LinkController extends BaseController
         }
         foreach ($items as $item) {
             $out = self::getListItem($item, $list);
-            if ($out != null) {
+            if ($out !== null) {
                 $return[] = $out;
             }
         }
@@ -562,70 +523,72 @@ class LinkController extends BaseController
     public static function getListExtend($user, $list)
     {
         $return = [];
-        $info_array = (count($_ENV['sub_message']) != 0 ? (array) $_ENV['sub_message'] : []);
+        $info_array = (count($_ENV['sub_message']) !== 0 ? (array) $_ENV['sub_message'] : []);
         if (strtotime($user->expire_in) > time()) {
-            if ($user->transfer_enable == 0) {
+            if ($user->transfer_enable === 0) {
                 $unusedTraffic = '剩余流量:0';
             } else {
                 $unusedTraffic = '剩余流量:' . $user->unusedTraffic();
             }
             $expire_in = '过期时间:';
-            if ($user->class_expire != '1989-06-04 00:05:00') {
+            if ($user->class_expire !== '1989-06-04 00:05:00') {
                 $userClassExpire = explode(' ', $user->class_expire);
                 $expire_in .= $userClassExpire[0];
             } else {
                 $expire_in .= '无限期';
             }
         } else {
-            $unusedTraffic  = '账户已过期,请续费后使用';
-            $expire_in      = '账户已过期,请续费后使用';
+            $unusedTraffic = '账户已过期,请续费后使用';
+            $expire_in = '账户已过期,请续费后使用';
         }
-        if (!in_array($list, ['quantumult', 'quantumultx', 'shadowrocket'])) {
+        if (! in_array($list, ['quantumult', 'quantumultx', 'shadowrocket'])) {
             $info_array[] = $unusedTraffic;
             $info_array[] = $expire_in;
         }
         $baseUrl = explode('//', $_ENV['baseUrl'])[1];
         $baseUrl = explode('/', $baseUrl)[0];
         $Extend = [
-            'remark'          => '',
-            'type'            => '',
-            'add'             => $baseUrl,
-            'address'         => $baseUrl,
-            'port'            => 10086,
-            'method'          => 'chacha20-ietf',
-            'passwd'          => $user->passwd,
-            'id'              => $user->uuid,
-            'aid'             => 0,
-            'net'             => 'tcp',
-            'headerType'      => 'none',
-            'host'            => '',
-            'path'            => '/',
-            'tls'             => '',
-            'protocol'        => 'origin',
-            'protocol_param'  => '',
-            'obfs'            => 'plain',
-            'obfs_param'      => '',
-            'group'           => $_ENV['appName']
+            'remark' => '',
+            'type' => '',
+            'add' => $baseUrl,
+            'address' => $baseUrl,
+            'port' => 10086,
+            'method' => 'chacha20-ietf',
+            'passwd' => $user->passwd,
+            'id' => $user->uuid,
+            'aid' => 0,
+            'net' => 'tcp',
+            'headerType' => 'none',
+            'host' => '',
+            'path' => '/',
+            'tls' => '',
+            'protocol' => 'origin',
+            'protocol_param' => '',
+            'obfs' => 'plain',
+            'obfs_param' => '',
+            'group' => $_ENV['appName'],
         ];
-        if ($list == 'shadowrocket') {
-            $return[] = ('STATUS=' . $unusedTraffic . '.♥.' . $expire_in . PHP_EOL . 'REMARKS=' . $_ENV['appName']);
+        if ($list === 'shadowrocket') {
+            $return[] = 'STATUS=' . $unusedTraffic . '.♥.' . $expire_in . PHP_EOL . 'REMARKS=' . $_ENV['appName'];
         }
         foreach ($info_array as $remark) {
             $Extend['remark'] = $remark;
             if (in_array($list, ['kitsunebi', 'quantumult', 'v2rayn'])) {
                 $Extend['type'] = 'vmess';
                 $out = self::getListItem($Extend, $list);
-            } elseif ($list == 'trojan') {
+            } elseif ($list === 'trojan') {
                 $Extend['type'] = 'trojan';
                 $out = self::getListItem($Extend, $list);
-            } elseif ($list == 'ssr') {
+            } elseif ($list === 'ssr') {
                 $Extend['type'] = 'ssr';
                 $out = self::getListItem($Extend, $list);
             } else {
                 $Extend['type'] = 'ss';
                 $out = self::getListItem($Extend, $list);
             }
-            if ($out !== null) $return[] = $out;
+            if ($out !== null) {
+                $return[] = $out;
+            }
         }
         return $return;
     }
@@ -637,14 +600,12 @@ class LinkController extends BaseController
      * @param int   $surge 订阅类型
      * @param array $opts  request
      * @param array $Rule  节点筛选规则
-     *
-     * @return string
      */
-    public static function getSurge($user, $surge, $opts, $Rule)
+    public static function getSurge(User $user, int $surge, array $opts, array $Rule): string
     {
         $subInfo = self::getSubinfo($user, $surge);
         $userapiUrl = $subInfo['surge'];
-        if ($surge != 4) {
+        if ($surge !== 4) {
             $Rule['type'] = 'ss';
         }
         $items = URL::getNew_AllItems($user, $Rule);
@@ -657,12 +618,12 @@ class LinkController extends BaseController
                 $All_Proxy .= $out . PHP_EOL;
             }
         }
-        $variable = ($surge == 2 ? 'Surge2_Profiles' : 'Surge_Profiles');
+        $variable = ($surge === 2 ? 'Surge2_Profiles' : 'Surge_Profiles');
         if (isset($opts['profiles']) && in_array($opts['profiles'], array_keys($_ENV[$variable]))) {
             $Profiles = $opts['profiles'];
-            $userapiUrl .= ('&profiles=' . $Profiles);
+            $userapiUrl .= '&profiles=' . $Profiles;
         } else {
-            $Profiles = ($surge == 2 ? $_ENV['Surge2_DefaultProfiles'] : $_ENV['Surge_DefaultProfiles']);
+            $Profiles = ($surge === 2 ? $_ENV['Surge2_DefaultProfiles'] : $_ENV['Surge_DefaultProfiles']);
         }
 
         return ConfGenerate::getSurgeConfs($user, $All_Proxy, $Nodes, $_ENV[$variable][$Profiles]);
@@ -675,10 +636,8 @@ class LinkController extends BaseController
      * @param int   $quantumult 订阅类型
      * @param array $opts       request
      * @param array $Rule       节点筛选规则
-     *
-     * @return string
      */
-    public static function getQuantumult($user, $quantumult, $opts, $Rule)
+    public static function getQuantumult(User $user, int $quantumult, array $opts, array $Rule): string
     {
         switch ($quantumult) {
             case 2:
@@ -696,7 +655,7 @@ class LinkController extends BaseController
                     'system, 119.29.29.29, 223.6.6.6, 114.114.114.114',
                     '',
                     '[STATE]',
-                    'STATE,AUTO'
+                    'STATE,AUTO',
                 ];
                 return implode(PHP_EOL, $str);
                 break;
@@ -708,9 +667,9 @@ class LinkController extends BaseController
                 break;
         }
 
-        $All_Proxy          = '';
-        $All_Proxy_name     = '';
-        $BackChina_name     = '';
+        $All_Proxy = '';
+        $All_Proxy_name = '';
+        $BackChina_name = '';
         foreach ($items as $item) {
             $out = AppURI::getQuantumultURI($item);
             if ($out !== null) {
@@ -723,12 +682,12 @@ class LinkController extends BaseController
             }
         }
         $ProxyGroups = [
-            'proxy_group'       => base64_encode("🍃 Proxy  :  static, 🏃 Auto\n🏃 Auto\n🚀 Direct\n" . $All_Proxy_name),
-            'domestic_group'    => base64_encode("🍂 Domestic  :  static, 🚀 Direct\n🚀 Direct\n🍃 Proxy\n" . $BackChina_name),
-            'others_group'      => base64_encode("☁️ Others  :   static, 🍃 Proxy\n🚀 Direct\n🍃 Proxy"),
-            'direct_group'      => base64_encode("🚀 Direct : static, DIRECT\nDIRECT"),
-            'apple_group'       => base64_encode("🍎 Only  :  static, 🚀 Direct\n🚀 Direct\n🍃 Proxy"),
-            'auto_group'        => base64_encode("🏃 Auto  :  auto\n" . $All_Proxy_name),
+            'proxy_group' => base64_encode("🍃 Proxy  :  static, 🏃 Auto\n🏃 Auto\n🚀 Direct\n" . $All_Proxy_name),
+            'domestic_group' => base64_encode("🍂 Domestic  :  static, 🚀 Direct\n🚀 Direct\n🍃 Proxy\n" . $BackChina_name),
+            'others_group' => base64_encode("☁️ Others  :   static, 🍃 Proxy\n🚀 Direct\n🍃 Proxy"),
+            'direct_group' => base64_encode("🚀 Direct : static, DIRECT\nDIRECT"),
+            'apple_group' => base64_encode("🍎 Only  :  static, 🚀 Direct\n🚀 Direct\n🍃 Proxy"),
+            'auto_group' => base64_encode("🏃 Auto  :  auto\n" . $All_Proxy_name),
         ];
         $render = ConfRender::getTemplateRender();
         $render->assign('All_Proxy', $All_Proxy)->assign('ProxyGroups', $ProxyGroups);
@@ -743,10 +702,8 @@ class LinkController extends BaseController
      * @param int   $quantumultx 订阅类型
      * @param array $opts        request
      * @param array $Rule        节点筛选规则
-     *
-     * @return string
      */
-    public static function getQuantumultX($user, $quantumultx, $opts, $Rule)
+    public static function getQuantumultX(User $user, int $quantumultx, array $opts, array $Rule): string
     {
         return '';
     }
@@ -758,10 +715,8 @@ class LinkController extends BaseController
      * @param int   $surfboard 订阅类型
      * @param array $opts      request
      * @param array $Rule      节点筛选规则
-     *
-     * @return string
      */
-    public static function getSurfboard($user, $surfboard, $opts, $Rule)
+    public static function getSurfboard(User $user, int $surfboard, array $opts, array $Rule): string
     {
         $subInfo = self::getSubinfo($user, 0);
         $userapiUrl = $subInfo['surfboard'];
@@ -777,7 +732,7 @@ class LinkController extends BaseController
         }
         if (isset($opts['profiles']) && in_array($opts['profiles'], array_keys($_ENV['Surfboard_Profiles']))) {
             $Profiles = $opts['profiles'];
-            $userapiUrl .= ('&profiles=' . $Profiles);
+            $userapiUrl .= '&profiles=' . $Profiles;
         } else {
             $Profiles = $_ENV['Surfboard_DefaultProfiles']; // 默认策略组
         }
@@ -792,10 +747,8 @@ class LinkController extends BaseController
      * @param int   $clash 订阅类型
      * @param array $opts  request
      * @param array $Rule  节点筛选规则
-     *
-     * @return string
      */
-    public static function getClash($user, $clash, $opts, $Rule)
+    public static function getClash(User $user, int $clash, array $opts, array $Rule): string
     {
         $subInfo = self::getSubinfo($user, $clash);
         $userapiUrl = $subInfo['clash'];
@@ -809,7 +762,7 @@ class LinkController extends BaseController
         }
         if (isset($opts['profiles']) && in_array($opts['profiles'], array_keys($_ENV['Clash_Profiles']))) {
             $Profiles = $opts['profiles'];
-            $userapiUrl .= ('&profiles=' . $Profiles);
+            $userapiUrl .= '&profiles=' . $Profiles;
         } else {
             $Profiles = $_ENV['Clash_DefaultProfiles']; // 默认策略组
         }
@@ -820,14 +773,14 @@ class LinkController extends BaseController
     public static function getAnXray($user, $anxray, $opts, $Rule)
     {
         $subInfo = self::getSubinfo($user, $anxray);
-        $All_Proxy  = '';
-        $userapiUrl = $subInfo['anxray'];	
-        $items = URL::getNew_AllItems($user, $Rule); 
+        $All_Proxy = '';
+        $userapiUrl = $subInfo['anxray'];
+        $items = URL::getNew_AllItems($user, $Rule);
         foreach ($items as $item) {
-                $out = AppURI::getAnXrayURI($item);	
-                if ($out !== null) {
-                  $All_Proxy .= $out . PHP_EOL;
-                }
+            $out = AppURI::getAnXrayURI($item);
+            if ($out !== null) {
+                $All_Proxy .= $out . PHP_EOL;
+            }
         }
         return base64_encode($All_Proxy);
     }
@@ -838,10 +791,8 @@ class LinkController extends BaseController
      * @param int    $sub  订阅类型
      * @param array  $opts request
      * @param array  $Rule 节点筛选规则
-     *
-     * @return string
      */
-    public static function getSub($user, $sub, $opts, $Rule)
+    public static function getSub(User $user, int $sub, array $opts, array $Rule): string
     {
         $return_url = '';
         switch ($sub) {
@@ -868,4 +819,25 @@ class LinkController extends BaseController
         $return_url .= URL::get_NewAllUrl($user, $Rule);
         return base64_encode($return_url);
     }
+
+    /**
+     * 记录订阅日志
+     *
+     * @param User   $user 用户
+     * @param string $type 订阅类型
+     * @param string $ua   UA
+     */
+    private static function Subscribe_log(User $user, string $type, string $ua): void
+    {
+        $log = new UserSubscribeLog();
+        $log->user_name = $user->user_name;
+        $log->user_id = $user->id;
+        $log->email = $user->email;
+        $log->subscribe_type = $type;
+        $log->request_ip = $_SERVER['REMOTE_ADDR'];
+        $log->request_time = date('Y-m-d H:i:s');
+        $antiXss = new AntiXSS();
+        $log->request_user_agent = $antiXss->xss_clean($ua);
+        $log->save();
+    }
 }

+ 21 - 37
src/Controllers/Mod_Mu/FuncController.php

@@ -1,119 +1,103 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\Mod_Mu;
 
 use App\Controllers\BaseController;
 use App\Utils\Tools;
-use App\Models\{
-    Node,
-    BlockIp,
-    UnblockIp,
-    DetectRule
-};
-use Slim\Http\{
-    Request,
-    Response
-};
+use Node;
 use Psr\Http\Message\ResponseInterface;
+use Request;
 
 class FuncController extends BaseController
 {
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ping($request, $response, $args)
+    public function ping(Request $request, Response $response, array $args)
     {
         $res = [
             'ret' => 1,
-            'data' => 'pong'
+            'data' => 'pong',
         ];
         return $response->withJson($res);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function get_detect_logs($request, $response, $args): ResponseInterface
+    public function get_detect_logs(Request $request, Response $response, array $args): ResponseInterface
     {
         $rules = DetectRule::all();
 
         $res = [
-            'ret'  => 1,
-            'data' => $rules
+            'ret' => 1,
+            'data' => $rules,
         ];
         $header_etag = $request->getHeaderLine('IF_NONE_MATCH');
         $etag = Tools::etag($rules);
-        if ($header_etag == $etag) {
+        if ($header_etag === $etag) {
             return $response->withStatus(304);
         }
         return $response->withHeader('ETAG', $etag)->withJson($res);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function get_blockip($request, $response, $args): ResponseInterface
+    public function get_blockip(Request $request, Response $response, array $args): ResponseInterface
     {
         $block_ips = BlockIp::Where('datetime', '>', time() - 60)->get();
 
         $res = [
             'ret' => 1,
-            'data' => $block_ips
+            'data' => $block_ips,
         ];
         $header_etag = $request->getHeaderLine('IF_NONE_MATCH');
         $etag = Tools::etag($block_ips);
-        if ($header_etag == $etag) {
+        if ($header_etag === $etag) {
             return $response->withStatus(304);
         }
         return $response->withHeader('ETAG', $etag)->withJson($res);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function get_unblockip($request, $response, $args): ResponseInterface
+    public function get_unblockip(Request $request, Response $response, array $args): ResponseInterface
     {
         $unblock_ips = UnblockIp::Where('datetime', '>', time() - 60)->get();
 
         $res = [
             'ret' => 1,
-            'data' => $unblock_ips
+            'data' => $unblock_ips,
         ];
         $header_etag = $request->getHeaderLine('IF_NONE_MATCH');
         $etag = Tools::etag($unblock_ips);
-        if ($header_etag == $etag) {
+        if ($header_etag === $etag) {
             return $response->withStatus(304);
         }
         return $response->withHeader('ETAG', $etag)->withJson($res);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function addBlockIp($request, $response, $args)
+    public function addBlockIp(Request $request, Response $response, array $args)
     {
         $params = $request->getQueryParams();
 
         $data = $request->getParam('data');
         $node_id = $params['node_id'];
-        if ($node_id == '0') {
+        if ($node_id === '0') {
             $node = Node::where('node_ip', $_SERVER['REMOTE_ADDR'])->first();
             $node_id = $node->id;
         }
         $node = Node::find($node_id);
-        if ($node == null) {
+        if ($node === null) {
             $res = [
-                'ret' => 0
+                'ret' => 0,
             ];
             return $response->withJson($res);
         }
@@ -123,7 +107,7 @@ class FuncController extends BaseController
                 $ip = $log['ip'];
 
                 $exist_ip = BlockIp::where('ip', $ip)->first();
-                if ($exist_ip != null) {
+                if ($exist_ip !== null) {
                     continue;
                 }
 

+ 28 - 42
src/Controllers/Mod_Mu/NodeController.php

@@ -1,28 +1,22 @@
 <?php
+
+declare(strict_types=1);
+
 namespace App\Controllers\Mod_Mu;
 
-use Slim\Http\{
-    Request,
-    Response
-};
-use App\Models\{
-    Node,
-    StreamMedia,
-    NodeInfoLog
-};
-use App\Utils\Tools;
-use App\Services\Config;
 use App\Controllers\BaseController;
+use App\Services\Config;
+use App\Utils\Tools;
+use Node;
 use Psr\Http\Message\ResponseInterface;
+use Request;
 
 class NodeController extends BaseController
 {
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function saveReport($request, $response, $args)
+    public function saveReport(Request $request, Response $response, array $args): void
     {
         // $request_ip = $_SERVER["REMOTE_ADDR"];
         $node_id = $request->getParam('node_id');
@@ -38,24 +32,22 @@ class NodeController extends BaseController
             $report->save();
             die('ok');
         } */
-        
-        $report = new StreamMedia;
+
+        $report = new StreamMedia();
         $report->node_id = $node_id;
         $report->result = json_encode($result);
         $report->created_at = time();
         $report->save();
         die('ok');
     }
-    
+
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function info($request, $response, $args)
+    public function info(Request $request, Response $response, array $args)
     {
         $node_id = $args['id'];
-        if ($node_id == '0') {
+        if ($node_id === '0') {
             $node = Node::where('node_ip', $_SERVER['REMOTE_ADDR'])->first();
             $node_id = $node->id;
         }
@@ -66,7 +58,7 @@ class NodeController extends BaseController
         $log->load = $load;
         $log->uptime = $uptime;
         $log->log_time = time();
-        if (!$log->save()) {
+        if (! $log->save()) {
             $res = [
                 'ret' => 0,
                 'data' => 'update failed',
@@ -81,21 +73,19 @@ class NodeController extends BaseController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function get_info($request, $response, $args): ResponseInterface
+    public function get_info(Request $request, Response $response, array $args): ResponseInterface
     {
         $node_id = $args['id'];
-        if ($node_id == '0') {
+        if ($node_id === '0') {
             $node = Node::where('node_ip', $_SERVER['REMOTE_ADDR'])->first();
             $node_id = $node->id;
         }
         $node = Node::find($node_id);
-        if ($node == null) {
+        if ($node === null) {
             $res = [
-                'ret' => 0
+                'ret' => 0,
             ];
             return $response->withJson($res);
         }
@@ -116,16 +106,16 @@ class NodeController extends BaseController
             'custom_config' => json_decode($node->custom_config, true, JSON_UNESCAPED_SLASHES),
             'disconnect_time' => $_ENV['disconnect_time'],
             'type' => 'SSPanel-UIM',
-            'version' => '2021.11'
+            'version' => '2021.11',
         ];
 
         $res = [
             'ret' => 1,
-            'data' => $data
+            'data' => $data,
         ];
         $header_etag = $request->getHeaderLine('IF_NONE_MATCH');
         $etag = Tools::etag($data);
-        if ($header_etag == $etag) {
+        if ($header_etag === $etag) {
             return $response->withStatus(304);
         }
 
@@ -133,14 +123,12 @@ class NodeController extends BaseController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function get_all_info($request, $response, $args): ResponseInterface
+    public function get_all_info(Request $request, Response $response, array $args): ResponseInterface
     {
         $nodes = Node::where('node_ip', '<>', null)->where(
-            static function ($query) {
+            static function ($query): void {
                 $query->where('sort', '=', 0)
                     ->orWhere('sort', '=', 10)
                     ->orWhere('sort', '=', 12)
@@ -150,12 +138,12 @@ class NodeController extends BaseController
         )->get();
         $res = [
             'ret' => 1,
-            'data' => $nodes
+            'data' => $nodes,
         ];
 
         $header_etag = $request->getHeaderLine('IF_NONE_MATCH');
         $etag = Tools::etag($nodes);
-        if ($header_etag == $etag) {
+        if ($header_etag === $etag) {
             return $response->withStatus(304);
         }
 
@@ -163,15 +151,13 @@ class NodeController extends BaseController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function getConfig($request, $response, $args)
+    public function getConfig(Request $request, Response $response, array $args)
     {
         $data = $request->getParsedBody();
         switch ($data['type']) {
-            case ('database'):
+            case 'database':
                 $db_config = Config::getDbConfig();
                 $db_config['host'] = $this->getServerIP();
                 $res = [
@@ -179,7 +165,7 @@ class NodeController extends BaseController
                     'data' => $db_config,
                 ];
                 break;
-            case ('webapi'):
+            case 'webapi':
                 $webapiConfig = [];
                 #todo
         }

+ 43 - 58
src/Controllers/Mod_Mu/UserController.php

@@ -1,43 +1,34 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\Mod_Mu;
 
 use App\Controllers\BaseController;
-use App\Models\{
-    Ip,
-    Node,
-    User,
-    DetectLog,
-    NodeOnlineLog
-};
 use App\Utils\Tools;
-use Slim\Http\{
-    Request,
-    Response
-};
+use Ip;
 use Psr\Http\Message\ResponseInterface;
+use Request;
 
 class UserController extends BaseController
 {
     /**
      * User List
      *
-     * @param \Slim\Http\Request    $request
-     * @param \Slim\Http\Response   $response
      * @param array                 $args
      *
      * @return \Slim\Http\Response
      */
-    public function index($request, $response, $args): ResponseInterface
+    public function index(\Slim\Http\Request $request, \Slim\Http\Response $response, array $args): ResponseInterface
     {
         $node_id = $request->getQueryParam('node_id', '0');
 
-        if ($node_id == '0') {
+        if ($node_id === '0') {
             $node = Node::where('node_ip', $_SERVER['REMOTE_ADDR'])->first();
             $node_id = $node->id;
         } else {
             $node = Node::where('id', '=', $node_id)->first();
-            if ($node == null) {
+            if ($node === null) {
                 return $response->withJson([
                     'ret' => 0,
                 ]);
@@ -47,15 +38,15 @@ class UserController extends BaseController
         $node->save();
 
         // 节点流量耗尽则返回 null
-        if (($node->node_bandwidth_limit != 0) && $node->node_bandwidth_limit < $node->node_bandwidth) {
+        if (($node->node_bandwidth_limit !== 0) && $node->node_bandwidth_limit < $node->node_bandwidth) {
             $users = null;
             return $response->withJson([
-                'ret'  => 1,
-                'data' => $users
+                'ret' => 1,
+                'data' => $users,
             ]);
         }
 
-        if (in_array($node->sort, [0, 10]) && $node->mu_only != -1) {
+        if (in_array($node->sort, [0, 10]) && $node->mu_only !== -1) {
             $mu_port_migration = $_ENV['mu_port_migration'];
             $muPort = Tools::get_MuOutPortArray($node->server);
         } else {
@@ -67,10 +58,10 @@ class UserController extends BaseController
          * 2. 请不要把真实用户作为单端口承载用户
          */
         $users_raw = User::where(
-            static function ($query) use ($node) {
+            static function ($query) use ($node): void {
                 $query->where(
-                    static function ($query1) use ($node) {
-                        if ($node->node_group != 0) {
+                    static function ($query1) use ($node): void {
+                        if ($node->node_group !== 0) {
                             $query1->where('class', '>=', $node->node_class)
                                 ->where('node_group', '=', $node->node_group);
                         } else {
@@ -81,21 +72,21 @@ class UserController extends BaseController
             }
         )->where('enable', 1)->where('expire_in', '>', date('Y-m-d H:i:s'))->get();
 
-        if ($node->sort == 14) {
-            $key_list = array('node_speedlimit', 'id', 'node_connector', 'uuid', 'alive_ip');
-        } elseif ($node->sort == 11) {
-            $key_list = array('node_speedlimit', 'id', 'node_connector', 'uuid', 'alive_ip');
+        if ($node->sort === 14) {
+            $key_list = ['node_speedlimit', 'id', 'node_connector', 'uuid', 'alive_ip'];
+        } elseif ($node->sort === 11) {
+            $key_list = ['node_speedlimit', 'id', 'node_connector', 'uuid', 'alive_ip'];
         } else {
-            $key_list = array(
+            $key_list = [
                 'method', 'obfs', 'obfs_param', 'protocol', 'protocol_param', 'node_speedlimit',
-                'is_multi_user', 'id', 'port', 'passwd', 'node_connector', 'alive_ip'
-            );
+                'is_multi_user', 'id', 'port', 'passwd', 'node_connector', 'alive_ip',
+            ];
         }
 
-        $alive_ip = (new \App\Models\Ip)->getUserAliveIpCount();
-        $users = array();
+        $alive_ip = (new \App\Models\Ip())->getUserAliveIpCount();
+        $users = [];
         foreach ($users_raw as $user_raw) {
-            if ($user_raw->node_connector != 0) {
+            if ($user_raw->node_connector !== 0) {
                 $user_raw->alive_ip = $alive_ip[strval($user_raw->id)];
             }
             if ($user_raw->transfer_enable <= $user_raw->u + $user_raw->d) {
@@ -106,14 +97,14 @@ class UserController extends BaseController
                     continue;
                 }
             }
-            if ($mu_port_migration === true && $user_raw->is_multi_user != 0) {
+            if ($mu_port_migration === true && $user_raw->is_multi_user !== 0) {
                 // 下发偏移后端口
-                if ($muPort['type'] == 0) {
+                if ($muPort['type'] === 0) {
                     if (in_array($user_raw->port, array_keys($muPort['port']))) {
                         $user_raw->port = $muPort['port'][$user_raw->port]['backend'];
                     }
                 } else {
-                    $user_raw->port = ($user_raw->port + $muPort['type']);
+                    $user_raw->port += $muPort['type'];
                 }
             }
             $user_raw = Tools::keyFilter($user_raw, $key_list);
@@ -122,34 +113,32 @@ class UserController extends BaseController
 
         $header_etag = $request->getHeaderLine('IF_NONE_MATCH');
         $etag = Tools::etag($users);
-        if ($header_etag == $etag) {
+        if ($header_etag === $etag) {
             return $response->withStatus(304);
         }
         return $response->withHeader('ETAG', $etag)->withJson([
-            'ret'  => 1,
-            'data' => $users
+            'ret' => 1,
+            'data' => $users,
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function addTraffic($request, $response, $args)
+    public function addTraffic(Request $request, Response $response, array $args)
     {
         $params = $request->getQueryParams();
 
         $data = $request->getParam('data');
         $this_time_total_bandwidth = 0;
         $node_id = $params['node_id'];
-        if ($node_id == '0') {
+        if ($node_id === '0') {
             $node = Node::where('node_ip', $_SERVER['REMOTE_ADDR'])->first();
             $node_id = $node->id;
         }
         $node = Node::find($node_id);
 
-        if ($node == null) {
+        if ($node === null) {
             return $response->withJson([
                 'ret' => 0,
             ]);
@@ -162,7 +151,7 @@ class UserController extends BaseController
                 $user_id = $log['user_id'];
                 $user = User::find($user_id);
 
-                if ($user == null) {
+                if ($user === null) {
                     continue;
                 }
 
@@ -170,7 +159,7 @@ class UserController extends BaseController
                 $user->u += $u * $node->traffic_rate;
                 $user->d += $d * $node->traffic_rate;
                 $this_time_total_bandwidth += $u + $d;
-                if (!$user->save()) {
+                if (! $user->save()) {
                     $res = [
                         'ret' => 0,
                         'data' => 'update failed',
@@ -197,25 +186,23 @@ class UserController extends BaseController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function addAliveIp($request, $response, $args)
+    public function addAliveIp(Request $request, Response $response, array $args)
     {
         $params = $request->getQueryParams();
 
         $data = $request->getParam('data');
         $node_id = $params['node_id'];
-        if ($node_id == '0') {
+        if ($node_id === '0') {
             $node = Node::where('node_ip', $_SERVER['REMOTE_ADDR'])->first();
             $node_id = $node->id;
         }
         $node = Node::find($node_id);
 
-        if ($node == null) {
+        if ($node === null) {
             $res = [
-                'ret' => 0
+                'ret' => 0,
             ];
             return $response->withJson($res);
         }
@@ -242,25 +229,23 @@ class UserController extends BaseController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function addDetectLog($request, $response, $args)
+    public function addDetectLog(Request $request, Response $response, array $args)
     {
         $params = $request->getQueryParams();
 
         $data = $request->getParam('data');
         $node_id = $params['node_id'];
-        if ($node_id == '0') {
+        if ($node_id === '0') {
             $node = Node::where('node_ip', $_SERVER['REMOTE_ADDR'])->first();
             $node_id = $node->id;
         }
         $node = Node::find($node_id);
 
-        if ($node == null) {
+        if ($node === null) {
             $res = [
-                'ret' => 0
+                'ret' => 0,
             ];
             return $response->withJson($res);
         }

+ 30 - 39
src/Controllers/PasswordController.php

@@ -1,31 +1,26 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers;
 
-use App\Models\{
-    User,
-    PasswordReset
-};
-use App\Utils\Hash;
 use App\Services\Password;
-use Slim\Http\{
-    Request,
-    Response
-};
+use App\Utils\Hash;
+use Request;
+use User;
 
-/***
+/*
  * Class Password
+ *
  * @package App\Controllers
  * 密码重置
  */
 class PasswordController extends BaseController
 {
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function reset($request, $response, $args)
+    public function reset(Request $request, Response $response, array $args)
     {
         return $response->write(
             $this->view()->display('password/reset.tpl')
@@ -33,18 +28,16 @@ class PasswordController extends BaseController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function handleReset($request, $response, $args)
+    public function handleReset(Request $request, Response $response, array $args)
     {
         $email = strtolower($request->getParam('email'));
-        $user  = User::where('email', $email)->first();
-        if ($user == null) {
+        $user = User::where('email', $email)->first();
+        if ($user === null) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '此邮箱不存在'
+                'msg' => '此邮箱不存在',
             ]);
         }
         if (Password::sendResetEmail($email)) {
@@ -54,79 +47,77 @@ class PasswordController extends BaseController
         }
         return $response->withJson([
             'ret' => 1,
-            'msg' => $msg
+            'msg' => $msg,
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function token($request, $response, $args)
+    public function token(Request $request, Response $response, array $args)
     {
         $token = PasswordReset::where('token', $args['token'])->where('expire_time', '>', time())->orderBy('id', 'desc')->first();
-        if ($token == null) return $response->withStatus(302)->withHeader('Location', '/password/reset');
+        if ($token === null) {
+            return $response->withStatus(302)->withHeader('Location', '/password/reset');
+        }
         return $response->write(
             $this->view()->display('password/token.tpl')
         );
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function handleToken($request, $response, $args)
+    public function handleToken(Request $request, Response $response, array $args)
     {
         $tokenStr = $args['token'];
         $password = $request->getParam('password');
         $repasswd = $request->getParam('repasswd');
 
-        if ($password != $repasswd) {
+        if ($password !== $repasswd) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '两次输入不符合'
+                'msg' => '两次输入不符合',
             ]);
         }
 
         if (strlen($password) < 8) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '密码太短啦'
+                'msg' => '密码太短啦',
             ]);
         }
 
         // check token
         $token = PasswordReset::where('token', $tokenStr)->where('expire_time', '>', time())->orderBy('id', 'desc')->first();
-        if ($token == null) {
+        if ($token === null) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '链接已经失效,请重新获取'
+                'msg' => '链接已经失效,请重新获取',
             ]);
         }
         /** @var PasswordReset $token */
         $user = $token->getUser();
-        if ($user == null) {
+        if ($user === null) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '链接已经失效,请重新获取'
+                'msg' => '链接已经失效,请重新获取',
             ]);
         }
 
         // reset password
-        $hashPassword    = Hash::passwordHash($password);
-        $user->pass      = $hashPassword;
+        $hashPassword = Hash::passwordHash($password);
+        $user->pass = $hashPassword;
         $user->ga_enable = 0;
 
-        if (!$user->save()) {
+        if (! $user->save()) {
             $rs['ret'] = 0;
             $rs['msg'] = '重置失败,请重试';
         } else {
             $rs['ret'] = 1;
             $rs['msg'] = '重置成功';
-            
-            if ($_ENV['enable_forced_replacement'] == true) {
+
+            if ($_ENV['enable_forced_replacement'] === true) {
                 $user->clean_link();
             }
 

+ 123 - 127
src/Controllers/SubController.php

@@ -1,18 +1,14 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers;
 
+use App\Models\Link;
+use App\Models\Node;
+use App\Models\UserSubscribeLog;
 use App\Utils\Tools;
-use App\Models\{
-    Link,
-    Node,
-    UserSubscribeLog
-};
 use Psr\Http\Message\ResponseInterface;
-use Slim\Http\{
-    Request,
-    Response
-};
 
 /**
  *  SubController
@@ -21,7 +17,7 @@ class SubController extends BaseController
 {
     public static function getContent($request, $response, $args): ResponseInterface
     {
-        if (!$_ENV['Subscribe']) {
+        if (! $_ENV['Subscribe']) {
             return $response->withJson([
                 'ret' => 0,
             ]);
@@ -31,32 +27,32 @@ class SubController extends BaseController
         $subtype = $args['subtype'];
 
         $sub_token = Link::where('token', $token)->first();
-        if ($sub_token == null) {
+        if ($sub_token === null) {
             return $response->withJson([
                 'ret' => 0,
             ]);
         }
 
         $user = $sub_token->getUser();
-        if ($user == null) {
+        if ($user === null) {
             return $response->withJson([
                 'ret' => 0,
             ]);
         }
 
         $subtype_list = ['all', 'ss', 'ssr', 'v2ray', 'trojan'];
-        if (!in_array($subtype, $subtype_list)) {
+        if (! in_array($subtype, $subtype_list)) {
             return $response->withJson([
                 'ret' => 0,
             ]);
         }
 
-        $nodes = array();
+        $nodes = [];
         //篩選出用戶能連接的節點,感謝 @AVX512
         $nodes_raw = Node::where('type', 1)
             ->where('node_class', '<=', $user->class)
             ->whereIn('node_group', [0, $user->group])
-            ->where(function ($query) {
+            ->where(function ($query): void {
                 $query->where('node_bandwidth_limit', '=', 0)->orWhereRaw('node_bandwidth < node_bandwidth_limit');
             })
             ->get();
@@ -64,15 +60,15 @@ class SubController extends BaseController
         foreach ($nodes_raw as $node_raw) {
             $node_custom_config = json_decode($node_raw->custom_config, true);
             //檢查是否配置“前端/订阅中下发的服务器地址”
-            if (!array_key_exists('server_user', $node_custom_config)) {
+            if (! array_key_exists('server_user', $node_custom_config)) {
                 $server = $node_raw->server;
             } else {
                 $server = $node_custom_config['server_user'];
             }
             switch ($node_raw->sort) {
-                case "0":
+                case '0':
                     //只給下發正確類型的節點
-                    if (!in_array($subtype, ['ss', 'all'])) {
+                    if (! in_array($subtype, ['ss', 'all'])) {
                         $node = null;
                         break;
                     }
@@ -80,46 +76,46 @@ class SubController extends BaseController
                     $plugin = $node_custom_config['plugin'] ?? '';
                     $plugin_option = $node_custom_config['plugin_option'] ?? '';
                     $node = [
-                        "name" => $node_raw->name,
-                        "id" => $node_raw->id,
-                        "type" => "ss",
-                        "address" => $server,
-                        "port" => $user->port,
-                        "password" => $user->passwd,
-                        "encryption" => $user->method,
-                        "plugin" => $plugin,
-                        "plugin_option" => $plugin_option,
-                        "remark" => $node_raw->info
+                        'name' => $node_raw->name,
+                        'id' => $node_raw->id,
+                        'type' => 'ss',
+                        'address' => $server,
+                        'port' => $user->port,
+                        'password' => $user->passwd,
+                        'encryption' => $user->method,
+                        'plugin' => $plugin,
+                        'plugin_option' => $plugin_option,
+                        'remark' => $node_raw->info,
                     ];
                     break;
                 //單獨加了一種SSR節點類型用來同時處理多端口和單端口SSR的訂閲下發
-                case "1":
-                    if (!in_array($subtype, ['ssr', 'all'])) {
+                case '1':
+                    if (! in_array($subtype, ['ssr', 'all'])) {
                         $node = null;
                         break;
                     }
                     //判斷一下是普通SSR節點還是單端口SSR節點,混淆式单端就去掉了,配起来怪麻烦的
-                    if ($node_raw->mu_only == -1) {
+                    if ($node_raw->mu_only === -1) {
                         $node = [
-                            "name" => $node_raw->name,
-                            "id" => $node_raw->id,
-                            "type" => "ssr",
-                            "address" => $server,
-                            "port" => $user->port,
-                            "password" => $user->passwd,
-                            "encryption" => $user->method,
-                            "protocol" => $user->protocol,
-                            "protocol_param" => $user->protocol_param,
-                            "obfs" => $user->obfs,
-                            "obfs_param" => $user->obfs_param,
-                            "remark" => $node_raw->info
+                            'name' => $node_raw->name,
+                            'id' => $node_raw->id,
+                            'type' => 'ssr',
+                            'address' => $server,
+                            'port' => $user->port,
+                            'password' => $user->passwd,
+                            'encryption' => $user->method,
+                            'protocol' => $user->protocol,
+                            'protocol_param' => $user->protocol_param,
+                            'obfs' => $user->obfs,
+                            'obfs_param' => $user->obfs_param,
+                            'remark' => $node_raw->info,
                         ];
                     } else {
                         //優先級是 mu_port > offset_port_user > offset_port_node ,v2 和 trojan 同理
-                        if (!array_key_exists('mu_port', $node_custom_config)
-                            && !array_key_exists('offset_port_user', $node_custom_config)) {
+                        if (! array_key_exists('mu_port', $node_custom_config)
+                            && ! array_key_exists('offset_port_user', $node_custom_config)) {
                             $mu_port = $node_custom_config['offset_port_node'];
-                        } elseif (!array_key_exists('mu_port', $node_custom_config)) {
+                        } elseif (! array_key_exists('mu_port', $node_custom_config)) {
                             $mu_port = $node_custom_config['offset_port_user'];
                         } else {
                             $mu_port = $node_custom_config['mu_port'];
@@ -132,34 +128,34 @@ class SubController extends BaseController
                         //現在就只能用協議式單端口。理論上應該加個協議式單端口和混淆式單端口的配置項,然後這裏寫個判斷切換的。先咕了,SSR不是重點。
                         $user_protocol_param = $user->id . ':' . $user->passwd;
                         $node = [
-                            "name" => $node_raw->name,
-                            "id" => $node_raw->id,
-                            "type" => "ssr",
-                            "address" => $server,
-                            "port" => $mu_port,
-                            "password" => $mu_password,
-                            "encryption" => $mu_encryption,
-                            "protocol" => $mu_protocol,
-                            "protocol_param" => $user_protocol_param,
-                            "obfs" => $mu_obfs,
-                            "obfs_param" => $mu_suffix,
-                            "remark" => $node_raw->info
+                            'name' => $node_raw->name,
+                            'id' => $node_raw->id,
+                            'type' => 'ssr',
+                            'address' => $server,
+                            'port' => $mu_port,
+                            'password' => $mu_password,
+                            'encryption' => $mu_encryption,
+                            'protocol' => $mu_protocol,
+                            'protocol_param' => $user_protocol_param,
+                            'obfs' => $mu_obfs,
+                            'obfs_param' => $mu_suffix,
+                            'remark' => $node_raw->info,
                         ];
                     }
                     break;
-                case "11":
-                    if (!in_array($subtype, ['v2ray', 'all'])) {
+                case '11':
+                    if (! in_array($subtype, ['v2ray', 'all'])) {
                         $node = null;
                         break;
                     }
-                    if (!array_key_exists('v2_port', $node_custom_config)
-                        && !array_key_exists('offset_port_user', $node_custom_config)
-                        && !array_key_exists('offset_port_node', $node_custom_config)) {
+                    if (! array_key_exists('v2_port', $node_custom_config)
+                        && ! array_key_exists('offset_port_user', $node_custom_config)
+                        && ! array_key_exists('offset_port_node', $node_custom_config)) {
                         $v2_port = 443;
-                    } elseif (!array_key_exists('v2_port', $node_custom_config)
-                        && !array_key_exists('offset_port_user', $node_custom_config)) {
+                    } elseif (! array_key_exists('v2_port', $node_custom_config)
+                        && ! array_key_exists('offset_port_user', $node_custom_config)) {
                         $v2_port = $node_custom_config['offset_port_node'];
-                    } elseif (!array_key_exists('v2_port', $node_custom_config)) {
+                    } elseif (! array_key_exists('v2_port', $node_custom_config)) {
                         $v2_port = $node_custom_config['offset_port_user'];
                     } else {
                         $v2_port = $node_custom_config['v2_port'];
@@ -170,7 +166,7 @@ class SubController extends BaseController
                     $flow = $node_custom_config['flow'] ?? '';
                     $encryption = $node_custom_config['encryption'] ?? '';
                     $network = $node_custom_config['network'] ?? '';
-                    $header = $node_custom_config['header'] ?? ["type" => "none"];
+                    $header = $node_custom_config['header'] ?? ['type' => 'none'];
                     $header_type = $header['type'] ?? '';
                     $host = $node_custom_config['host'] ?? '';
                     $servicename = $node_custom_config['servicename'] ?? '';
@@ -178,40 +174,40 @@ class SubController extends BaseController
                     $tls = in_array($security, ['tls', 'xtls']) ? '1' : '0';
                     $enable_vless = $node_custom_config['enable_vless'] ?? '0';
                     $node = [
-                        "name" => $node_raw->name,
-                        "id" => $node_raw->id,
-                        "type" => "v2ray",
-                        "address" => $server,
-                        "port" => $v2_port,
-                        "uuid" => $user->uuid,
-                        "alterid" => $alter_id,
-                        "security" => $security,
-                        "flow" => $flow,
-                        "encryption" => $encryption,
-                        "network" => $network,
-                        "header" => $header,
-                        "header_type" => $header_type,
-                        "host" => $host,
-                        "path" => $path,
-                        "servicename" => $servicename,
-                        "tls" => $tls,
-                        "enable_vless" => $enable_vless,
-                        "remark" => $node_raw->info
+                        'name' => $node_raw->name,
+                        'id' => $node_raw->id,
+                        'type' => 'v2ray',
+                        'address' => $server,
+                        'port' => $v2_port,
+                        'uuid' => $user->uuid,
+                        'alterid' => $alter_id,
+                        'security' => $security,
+                        'flow' => $flow,
+                        'encryption' => $encryption,
+                        'network' => $network,
+                        'header' => $header,
+                        'header_type' => $header_type,
+                        'host' => $host,
+                        'path' => $path,
+                        'servicename' => $servicename,
+                        'tls' => $tls,
+                        'enable_vless' => $enable_vless,
+                        'remark' => $node_raw->info,
                     ];
                     break;
-                case "14":
-                    if (!in_array($subtype, ['trojan', 'all'])) {
+                case '14':
+                    if (! in_array($subtype, ['trojan', 'all'])) {
                         $node = null;
                         break;
                     }
-                    if (!array_key_exists('trojan_port', $node_custom_config)
-                        && !array_key_exists('offset_port_user', $node_custom_config)
-                        && !array_key_exists('offset_port_node', $node_custom_config)) {
+                    if (! array_key_exists('trojan_port', $node_custom_config)
+                        && ! array_key_exists('offset_port_user', $node_custom_config)
+                        && ! array_key_exists('offset_port_node', $node_custom_config)) {
                         $trojan_port = 443;
-                    } elseif (!array_key_exists('trojan_port', $node_custom_config)
-                        && !array_key_exists('offset_port_user', $node_custom_config)) {
+                    } elseif (! array_key_exists('trojan_port', $node_custom_config)
+                        && ! array_key_exists('offset_port_user', $node_custom_config)) {
                         $trojan_port = $node_custom_config['offset_port_node'];
-                    } elseif (!array_key_exists('trojan_port', $node_custom_config)) {
+                    } elseif (! array_key_exists('trojan_port', $node_custom_config)) {
                         $trojan_port = $node_custom_config['offset_port_user'];
                     } else {
                         $trojan_port = $node_custom_config['trojan_port'];
@@ -219,50 +215,50 @@ class SubController extends BaseController
                     $host = $node_custom_config['host'] ?? '';
                     $allow_insecure = $node_custom_config['allow_insecure'] ?? '0';
                     //Trojan-Go 啥都好,就是特性連個支持的付費後端都沒有
-                    $security = $node_custom_config['security'] ?? $node_custom_config['enable_xtls'] == '1' ? 'xtls' : 'tls';
+                    $security = $node_custom_config['security'] ?? $node_custom_config['enable_xtls'] === '1' ? 'xtls' : 'tls';
                     $mux = $node_custom_config['mux'] ?? '';
-                    $transport = $node_custom_config['transport'] ?? $node_custom_config['grpc'] == '1' ? 'grpc' : 'tcp';;
+                    $transport = $node_custom_config['transport'] ?? $node_custom_config['grpc'] === '1' ? 'grpc' : 'tcp';
+
                     $transport_plugin = $node_custom_config['transport_plugin'] ?? '';
                     $transport_method = $node_custom_config['transport_method'] ?? '';
                     $servicename = $node_custom_config['servicename'] ?? '';
                     $path = $node_custom_config['path'] ?? '';
                     $node = [
-                        "name" => $node_raw->name,
-                        "id" => $node_raw->id,
-                        "type" => "trojan",
-                        "address" => $server,
-                        "host" => $host,
-                        "port" => $trojan_port,
-                        "uuid" => $user->uuid,
-                        "security" => $security,
-                        "mux" => $mux,
-                        "transport" => $transport,
-                        "transport_plugin" => $transport_plugin,
-                        "transport_method" => $transport_method,
-                        "allow_insecure" => $allow_insecure,
-                        "servicename" => $servicename,
-                        "path" => $path,
-                        "remark" => $node_raw->info,
+                        'name' => $node_raw->name,
+                        'id' => $node_raw->id,
+                        'type' => 'trojan',
+                        'address' => $server,
+                        'host' => $host,
+                        'port' => $trojan_port,
+                        'uuid' => $user->uuid,
+                        'security' => $security,
+                        'mux' => $mux,
+                        'transport' => $transport,
+                        'transport_plugin' => $transport_plugin,
+                        'transport_method' => $transport_method,
+                        'allow_insecure' => $allow_insecure,
+                        'servicename' => $servicename,
+                        'path' => $path,
+                        'remark' => $node_raw->info,
                     ];
                     break;
             }
-            if ($node == null) {
+            if ($node === null) {
                 continue;
-            } else {
-                $nodes[] = $node;
             }
+            $nodes[] = $node;
         }
 
         $sub_info = [
-            "version" => 1,
-            "sub_name" => $_ENV['appName'],
-            "user_email" => $user->email,
-            "user_name" => $user->user_name,
-            "user_class" => $user->class,
-            "user_class_expire_date" => $user->class_expire,
-            "user_total_traffic" => $user->transfer_enable,
-            "user_used_traffic" => $user->u + $user->d,
-            "nodes" => $nodes
+            'version' => 1,
+            'sub_name' => $_ENV['appName'],
+            'user_email' => $user->email,
+            'user_name' => $user->user_name,
+            'user_class' => $user->class,
+            'user_class_expire_date' => $user->class_expire,
+            'user_total_traffic' => $user->transfer_enable,
+            'user_used_traffic' => $user->u + $user->d,
+            'nodes' => $nodes,
         ];
 
         if ($_ENV['subscribeLog'] === true) {
@@ -271,11 +267,11 @@ class SubController extends BaseController
         //Etag相關,從 WebAPI 那邊抄的
         $header_etag = $request->getHeaderLine('IF_NONE_MATCH');
         $etag = Tools::etag($sub_info);
-        if ($header_etag == $etag) {
+        if ($header_etag === $etag) {
             return $response->withStatus(304);
         }
         return $response->withHeader('ETAG', $etag)->withJson([
-            $sub_info
+            $sub_info,
         ]);
     }
 
@@ -283,7 +279,7 @@ class SubController extends BaseController
     {
         $userid = $user->id;
         $token = Link::where('userid', $userid)->first();
-        if ($token == null) {
+        if ($token === null) {
             $token = new Link();
             $token = $userid;
             $token->token = Tools::genSubToken();

+ 50 - 63
src/Controllers/User/NodeController.php

@@ -1,21 +1,14 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\User;
 
 use App\Controllers\UserController;
-use App\Models\{
-    Node,
-    User
-};
-use App\Utils\{
-    URL,
-    Tools
-};
-use Slim\Http\{
-    Request,
-    Response
-};
+use Node;
 use Psr\Http\Message\ResponseInterface;
+use Request;
+use URL;
 
 /**
  *  User NodeController
@@ -23,53 +16,51 @@ use Psr\Http\Message\ResponseInterface;
 class NodeController extends UserController
 {
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function user_node_page($request, $response, $args): ResponseInterface
+    public function user_node_page(Request $request, Response $response, array $args): ResponseInterface
     {
-        $user  = $this->user;
+        $user = $this->user;
         $query = Node::query();
         $query->where('type', 1)->whereNotIn('sort', [9]);
-        if (!$user->is_admin) {
-            $group = ($user->node_group != 0 ? [0, $user->node_group] : [0]);
+        if (! $user->is_admin) {
+            $group = ($user->node_group !== 0 ? [0, $user->node_group] : [0]);
             $query->whereIn('node_group', $group);
         }
-        $nodes    = $query->orderBy('node_class')->orderBy('name')->get();
+        $nodes = $query->orderBy('node_class')->orderBy('name')->get();
         $all_node = [];
         foreach ($nodes as $node) {
             /** @var Node $node */
 
-            $array_node                   = [];
-            $array_node['id']             = $node->id;
-            $array_node['name']           = $node->name;
-            $array_node['class']          = $node->node_class;
-            $array_node['info']           = $node->info;
-            $array_node['flag']           = $node->get_node_flag();
-            $array_node['online_user']    = $node->get_node_online_user_count();
-            $array_node['online']         = $node->get_node_online_status();
-            $array_node['latest_load']    = $node->get_node_latest_load_text();
-            $array_node['traffic_rate']   = $node->traffic_rate;
-            $array_node['status']         = $node->status;
-            $array_node['traffic_used']   = (int) Tools::flowToGB($node->node_bandwidth);
-            $array_node['traffic_limit']  = (int) Tools::flowToGB($node->node_bandwidth_limit);
-            $array_node['bandwidth']      = $node->get_node_speedlimit();
+            $array_node = [];
+            $array_node['id'] = $node->id;
+            $array_node['name'] = $node->name;
+            $array_node['class'] = $node->node_class;
+            $array_node['info'] = $node->info;
+            $array_node['flag'] = $node->get_node_flag();
+            $array_node['online_user'] = $node->get_node_online_user_count();
+            $array_node['online'] = $node->get_node_online_status();
+            $array_node['latest_load'] = $node->get_node_latest_load_text();
+            $array_node['traffic_rate'] = $node->traffic_rate;
+            $array_node['status'] = $node->status;
+            $array_node['traffic_used'] = (int) Tools::flowToGB($node->node_bandwidth);
+            $array_node['traffic_limit'] = (int) Tools::flowToGB($node->node_bandwidth_limit);
+            $array_node['bandwidth'] = $node->get_node_speedlimit();
 
             $all_connect = [];
             if (in_array($node->sort, [0])) {
-                if ($node->mu_only != 1) {
+                if ($node->mu_only !== 1) {
                     $all_connect[] = 0;
                 }
-                if ($node->mu_only != -1) {
+                if ($node->mu_only !== -1) {
                     $mu_node_query = Node::query();
                     $mu_node_query->where('sort', 9)->where('type', '1');
-                    if (!$user->is_admin) {
+                    if (! $user->is_admin) {
                         $mu_node_query->where('node_class', '<=', $user->class)->whereIn('node_group', $group);
                     }
                     $mu_nodes = $mu_node_query->get();
                     foreach ($mu_nodes as $mu_node) {
-                        if (User::where('port', $mu_node->server)->where('is_multi_user', '<>', 0)->first() != null) {
+                        if (User::where('port', $mu_node->server)->where('is_multi_user', '<>', 0)->first() !== null) {
                             $all_connect[] = $node->getOffsetPort($mu_node->server);
                         }
                     }
@@ -90,15 +81,13 @@ class NodeController extends UserController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function user_node_ajax($request, $response, $args): ResponseInterface
+    public function user_node_ajax(Request $request, Response $response, array $args): ResponseInterface
     {
-        $id           = $args['id'];
-        $point_node   = Node::find($id);
-        $prefix       = explode(' - ', $point_node->name);
+        $id = $args['id'];
+        $point_node = Node::find($id);
+        $prefix = explode(' - ', $point_node->name);
         return $response->write(
             $this->view()
                 ->assign('point_node', $point_node)
@@ -109,19 +98,17 @@ class NodeController extends UserController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function user_node_info($request, $response, $args): ResponseInterface
+    public function user_node_info(Request $request, Response $response, array $args): ResponseInterface
     {
         $user = $this->user;
         $node = Node::find($args['id']);
-        if ($node == null) {
+        if ($node === null) {
             return $response->write('非法访问');
         }
-        if (!$user->is_admin) {
-            if ($user->node_group != $node->node_group && $node->node_group != 0) {
+        if (! $user->is_admin) {
+            if ($user->node_group !== $node->node_group && $node->node_group !== 0) {
                 return $response->write('无权查看该分组的节点');
             }
             if ($user->class < $node->node_class) {
@@ -139,24 +126,24 @@ class NodeController extends UserController
                 );
             case 11:
                 $server = $node->getV2RayItem($user);
-                $nodes  = [
-                    'url'  => URL::getV2Url($user, $node),
+                $nodes = [
+                    'url' => URL::getV2Url($user, $node),
                     'info' => [
                         '连接地址:' => $server['add'],
                         '连接端口:' => $server['port'],
-                        'UUID:'    => $user->uuid,
+                        'UUID:' => $user->uuid,
                         'AlterID:' => $server['aid'],
                         '传输协议:' => $server['net'],
                     ],
                 ];
-                if ($server['net'] == 'ws') {
+                if ($server['net'] === 'ws') {
                     $nodes['info']['PATH:'] = $server['path'];
                     $nodes['info']['HOST:'] = $server['host'];
                 }
-                if ($server['net'] == 'kcp') {
+                if ($server['net'] === 'kcp') {
                     $nodes['info']['伪装类型:'] = $server['type'];
                 }
-                if ($server['tls'] == 'tls') {
+                if ($server['tls'] === 'tls') {
                     $nodes['info']['TLS:'] = 'TLS';
                 }
                 return $response->write(
@@ -166,9 +153,9 @@ class NodeController extends UserController
                 );
             case 13:
                 $server = $node->getV2RayPluginItem($user);
-                if ($server != null) {
-                    $nodes  = [
-                        'url'  => URL::getItemUrl($server, 1),
+                if ($server !== null) {
+                    $nodes = [
+                        'url' => URL::getItemUrl($server, 1),
                         'info' => [
                             '连接地址:' => $server['address'],
                             '连接端口:' => $server['port'],
@@ -179,8 +166,8 @@ class NodeController extends UserController
                         ],
                     ];
                 } else {
-                    $nodes  = [
-                        'url'  => '',
+                    $nodes = [
+                        'url' => '',
                         'info' => [
                             '您的加密方式非 AEAD 系列' => '无法使用此节点.',
                         ],
@@ -193,15 +180,15 @@ class NodeController extends UserController
                 );
             case 14:
                 $server = $node->getTrojanItem($user);
-                $nodes  = [
-                    'url'  => URL::get_trojan_url($user, $node),
+                $nodes = [
+                    'url' => URL::get_trojan_url($user, $node),
                     'info' => [
                         '连接地址:' => $server['address'],
                         '连接端口:' => $server['port'],
                         '连接密码:' => $server['passwd'],
                     ],
                 ];
-                if ($server['host'] != $server['address']) {
+                if ($server['host'] !== $server['address']) {
                     $nodes['info']['HOST&PEER:'] = $server['host'];
                 }
                 return $response->write(

+ 71 - 85
src/Controllers/User/TicketController.php

@@ -1,19 +1,15 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Controllers\User;
 
 use App\Controllers\UserController;
-use App\Models\{
-    User,
-    Ticket
-};
 use App\Utils\Tools;
-use voku\helper\AntiXSS;
-use Slim\Http\{
-    Request,
-    Response
-};
 use Psr\Http\Message\ResponseInterface;
+use Request;
+use User;
+use voku\helper\AntiXSS;
 
 /**
  *  TicketController
@@ -21,23 +17,21 @@ use Psr\Http\Message\ResponseInterface;
 class TicketController extends UserController
 {
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ticket($request, $response, $args): ?ResponseInterface
+    public function ticket(Request $request, Response $response, array $args): ?ResponseInterface
     {
-        if ($_ENV['enable_ticket'] != true) {
+        if ($_ENV['enable_ticket'] !== true) {
             return null;
         }
         $pageNum = $request->getQueryParams()['page'] ?? 1;
         $tickets = Ticket::where('userid', $this->user->id)->where('rootid', 0)->orderBy('datetime', 'desc')->paginate(15, ['*'], 'page', $pageNum);
         $tickets->setPath('/user/ticket');
 
-        if ($request->getParam('json') == 1) {
+        if ($request->getParam('json') === 1) {
             return $response->withJson([
-                'ret'     => 1,
-                'tickets' => $tickets
+                'ret' => 1,
+                'tickets' => $tickets,
             ]);
         }
         $render = Tools::paginate_render($tickets);
@@ -51,11 +45,9 @@ class TicketController extends UserController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ticket_create($request, $response, $args): ResponseInterface
+    public function ticket_create(Request $request, Response $response, array $args): ResponseInterface
     {
         return $response->write(
             $this->view()
@@ -64,62 +56,60 @@ class TicketController extends UserController
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ticket_add($request, $response, $args): ResponseInterface
+    public function ticket_add(Request $request, Response $response, array $args): ResponseInterface
     {
-        $title    = $request->getParam('title');
-        $content  = $request->getParam('content');
+        $title = $request->getParam('title');
+        $content = $request->getParam('content');
         $markdown = $request->getParam('markdown');
-        if ($title == '' || $content == '') {
+        if ($title === '' || $content === '') {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '非法输入'
+                'msg' => '非法输入',
             ]);
         }
         if (strpos($content, 'admin') !== false || strpos($content, 'user') !== false) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '请求中有不当词语'
+                'msg' => '请求中有不当词语',
             ]);
         }
 
-        $ticket           = new Ticket();
-        $antiXss          = new AntiXSS();
-        $ticket->title    = $antiXss->xss_clean($title);
-        $ticket->content  = $antiXss->xss_clean($content);
-        $ticket->rootid   = 0;
-        $ticket->userid   = $this->user->id;
+        $ticket = new Ticket();
+        $antiXss = new AntiXSS();
+        $ticket->title = $antiXss->xss_clean($title);
+        $ticket->content = $antiXss->xss_clean($content);
+        $ticket->rootid = 0;
+        $ticket->userid = $this->user->id;
         $ticket->datetime = time();
         $ticket->save();
 
-        if ($_ENV['mail_ticket'] == true && $markdown != '') {
+        if ($_ENV['mail_ticket'] === true && $markdown !== '') {
             $adminUser = User::where('is_admin', 1)->get();
             foreach ($adminUser as $user) {
                 $user->sendMail(
                     $_ENV['appName'] . '-新工单被开启',
                     'news/warn.tpl',
                     [
-                        'text' => '管理员,有人开启了新的工单,请您及时处理。'
+                        'text' => '管理员,有人开启了新的工单,请您及时处理。',
                     ],
                     []
                 );
             }
         }
-        if ($_ENV['useScFtqq'] == true && $markdown != '') {
+        if ($_ENV['useScFtqq'] === true && $markdown !== '') {
             $ScFtqq_SCKEY = $_ENV['ScFtqq_SCKEY'];
             $postdata = http_build_query([
                 'text' => $_ENV['appName'] . '-新工单被开启',
-                'desp' => $markdown
+                'desp' => $markdown,
             ]);
             $opts = [
                 'http' => [
                     'method' => 'POST',
                     'header' => 'Content-type: application/x-www-form-urlencoded',
-                    'content' => $postdata
-                ]
+                    'content' => $postdata,
+                ],
             ];
             $context = stream_context_create($opts);
             file_get_contents('https://sctapi.ftqq.com/' . $ScFtqq_SCKEY . '.send', false, $context);
@@ -127,146 +117,142 @@ class TicketController extends UserController
 
         return $response->withJson([
             'ret' => 1,
-            'msg' => '提交成功'
+            'msg' => '提交成功',
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ticket_update($request, $response, $args): ResponseInterface
+    public function ticket_update(Request $request, Response $response, array $args): ResponseInterface
     {
-        $id       = $args['id'];
-        $content  = $request->getParam('content');
-        $status   = $request->getParam('status');
+        $id = $args['id'];
+        $content = $request->getParam('content');
+        $status = $request->getParam('status');
         $markdown = $request->getParam('markdown');
-        if ($content == '' || $status == '') {
+        if ($content === '' || $status === '') {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '非法输入'
+                'msg' => '非法输入',
             ]);
         }
         if (strpos($content, 'admin') !== false || strpos($content, 'user') !== false) {
             return $response->withJson([
                 'ret' => 0,
-                'msg' => '请求中有不当词语'
+                'msg' => '请求中有不当词语',
             ]);
         }
         $ticket_main = Ticket::where('id', $id)->where('userid', $this->user->id)->where('rootid', 0)->first();
-        if ($ticket_main == null) {
-            return $response->withStatus(302)->withHeader('Location', '/user/ticket');;
+        if ($ticket_main === null) {
+            return $response->withStatus(302)->withHeader('Location', '/user/ticket');
         }
-        if ($status == 1 && $ticket_main->status != $status) {
-            if ($_ENV['mail_ticket'] == true && $markdown != '') {
+        if ($status === 1 && $ticket_main->status !== $status) {
+            if ($_ENV['mail_ticket'] === true && $markdown !== '') {
                 $adminUser = User::where('is_admin', '=', '1')->get();
                 foreach ($adminUser as $user) {
                     $user->sendMail(
                         $_ENV['appName'] . '-工单被重新开启',
                         'news/warn.tpl',
                         [
-                            'text' => '管理员,有人重新开启了<a href="' . $_ENV['baseUrl'] . '/admin/ticket/' . $ticket_main->id . '/view">工单</a>,请您及时处理。'
+                            'text' => '管理员,有人重新开启了<a href="' . $_ENV['baseUrl'] . '/admin/ticket/' . $ticket_main->id . '/view">工单</a>,请您及时处理。',
                         ],
                         []
                     );
                 }
             }
-            if ($_ENV['useScFtqq'] == true && $markdown != '') {
+            if ($_ENV['useScFtqq'] === true && $markdown !== '') {
                 $ScFtqq_SCKEY = $_ENV['ScFtqq_SCKEY'];
                 $postdata = http_build_query([
                     'text' => $_ENV['appName'] . '-工单被重新开启',
-                    'desp' => $markdown
+                    'desp' => $markdown,
                 ]);
                 $opts = [
                     'http' => [
                         'method' => 'POST',
                         'header' => 'Content-type: application/x-www-form-urlencoded',
-                        'content' => $postdata
-                    ]
+                        'content' => $postdata,
+                    ],
                 ];
                 $context = stream_context_create($opts);
                 file_get_contents('https://sctapi.ftqq.com/' . $ScFtqq_SCKEY . '.send', false, $context);
             }
         } else {
-            if ($_ENV['mail_ticket'] == true && $markdown != '') {
+            if ($_ENV['mail_ticket'] === true && $markdown !== '') {
                 $adminUser = User::where('is_admin', 1)->get();
                 foreach ($adminUser as $user) {
                     $user->sendMail(
                         $_ENV['appName'] . '-工单被回复',
                         'news/warn.tpl',
                         [
-                            'text' => '管理员,有人回复了<a href="' . $_ENV['baseUrl'] . '/admin/ticket/' . $ticket_main->id . '/view">工单</a>,请您及时处理。'
+                            'text' => '管理员,有人回复了<a href="' . $_ENV['baseUrl'] . '/admin/ticket/' . $ticket_main->id . '/view">工单</a>,请您及时处理。',
                         ],
                         []
                     );
                 }
             }
-            if ($_ENV['useScFtqq'] == true && $markdown != '') {
+            if ($_ENV['useScFtqq'] === true && $markdown !== '') {
                 $ScFtqq_SCKEY = $_ENV['ScFtqq_SCKEY'];
                 $postdata = http_build_query([
                     'text' => $_ENV['appName'] . '-工单被回复',
-                    'desp' => $markdown
+                    'desp' => $markdown,
                 ]);
                 $opts = [
                     'http' => [
                         'method' => 'POST',
                         'header' => 'Content-type: application/x-www-form-urlencoded',
-                        'content' => $postdata
-                    ]
+                        'content' => $postdata,
+                    ],
                 ];
                 $context = stream_context_create($opts);
                 file_get_contents('https://sctapi.ftqq.com/' . $ScFtqq_SCKEY . '.send', false, $context);
             }
         }
 
-        $antiXss              = new AntiXSS();
-        $ticket               = new Ticket();
-        $ticket->title        = $antiXss->xss_clean($ticket_main->title);
-        $ticket->content      = $antiXss->xss_clean($content);
-        $ticket->rootid       = $ticket_main->id;
-        $ticket->userid       = $this->user->id;
-        $ticket->datetime     = time();
-        $ticket_main->status  = $status;
+        $antiXss = new AntiXSS();
+        $ticket = new Ticket();
+        $ticket->title = $antiXss->xss_clean($ticket_main->title);
+        $ticket->content = $antiXss->xss_clean($content);
+        $ticket->rootid = $ticket_main->id;
+        $ticket->userid = $this->user->id;
+        $ticket->datetime = time();
+        $ticket_main->status = $status;
 
         $ticket_main->save();
         $ticket->save();
 
         return $response->withJson([
             'ret' => 1,
-            'msg' => '提交成功'
+            'msg' => '提交成功',
         ]);
     }
 
     /**
-     * @param Request   $request
-     * @param Response  $response
      * @param array     $args
      */
-    public function ticket_view($request, $response, $args): ResponseInterface
+    public function ticket_view(Request $request, Response $response, array $args): ResponseInterface
     {
-        $id           = $args['id'];
-        $ticket_main  = Ticket::where('id', '=', $id)->where('userid', $this->user->id)->where('rootid', '=', 0)->first();
-        if ($ticket_main == null) {
-            if ($request->getParam('json') == 1) {
+        $id = $args['id'];
+        $ticket_main = Ticket::where('id', '=', $id)->where('userid', $this->user->id)->where('rootid', '=', 0)->first();
+        if ($ticket_main === null) {
+            if ($request->getParam('json') === 1) {
                 return $response->withJson([
                     'ret' => 0,
-                    'msg' => '这不是你的工单!'
+                    'msg' => '这不是你的工单!',
                 ]);
             }
             return $response->withStatus(302)->withHeader('Location', '/user/ticket');
         }
-        $pageNum   = $request->getQueryParams()['page'] ?? 1;
+        $pageNum = $request->getQueryParams()['page'] ?? 1;
         $ticketset = Ticket::where('id', $id)->orWhere('rootid', '=', $id)->orderBy('datetime', 'desc')->paginate(5, ['*'], 'page', $pageNum);
         $ticketset->setPath('/user/ticket/' . $id . '/view');
-        if ($request->getParam('json') == 1) {
+        if ($request->getParam('json') === 1) {
             foreach ($ticketset as $set) {
                 $set->username = $set->user()->user_name;
                 $set->datetime = $set->datetime();
             }
             return $response->withJson([
-                'ret'     => 1,
-                'tickets' => $ticketset
+                'ret' => 1,
+                'tickets' => $ticketset,
             ]);
         }
         $render = Tools::paginate_render($ticketset);

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 157 - 255
src/Controllers/UserController.php


+ 5 - 10
src/Middleware/Admin.php

@@ -1,25 +1,20 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Middleware;
 
 use App\Services\Auth as AuthService;
 
 class Admin
 {
-    /**
-     * @param \Slim\Http\Request    $request
-     * @param \Slim\Http\Response   $response
-     * @param callable              $next
-     *
-     * @return \Slim\Http\Response
-     */
-    public function __invoke($request, $response, $next)
+    public function __invoke(\Slim\Http\Request $request, \Slim\Http\Response $response, callable $next): \Slim\Http\Response
     {
         $user = AuthService::getUser();
-        if (!$user->isLogin) {
+        if (! $user->isLogin) {
             return $response->withStatus(302)->withHeader('Location', '/auth/login');
         }
-        if (!$user->is_admin) {
+        if (! $user->is_admin) {
             return $response->withStatus(302)->withHeader('Location', '/user');
         }
         return $next($request, $response);

+ 6 - 11
src/Middleware/Auth.php

@@ -1,26 +1,21 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Middleware;
 
 use App\Services\Auth as AuthService;
 
 class Auth
 {
-    /**
-     * @param \Slim\Http\Request    $request
-     * @param \Slim\Http\Response   $response
-     * @param callable              $next
-     *
-     * @return \Slim\Http\Response
-     */
-    public function __invoke($request, $response, $next)
+    public function __invoke(\Slim\Http\Request $request, \Slim\Http\Response $response, callable $next): \Slim\Http\Response
     {
         $user = AuthService::getUser();
-        if (!$user->isLogin) {
+        if (! $user->isLogin) {
             return $response->withStatus(302)->withHeader('Location', '/auth/login');
         }
-        $enablePages = array('/user/disable', '/user/backtoadmin', '/user/logout');
-        if ($user->enable == 0 && !in_array($_SERVER['REQUEST_URI'], $enablePages)) {
+        $enablePages = ['/user/disable', '/user/backtoadmin', '/user/logout'];
+        if ($user->enable === 0 && ! in_array($_SERVER['REQUEST_URI'], $enablePages)) {
             return $response->withStatus(302)->withHeader('Location', '/user/disable');
         }
         return $next($request, $response);

+ 14 - 18
src/Middleware/AuthorizationBearer.php

@@ -1,27 +1,23 @@
 <?php
 
-namespace App\Middleware;
+declare(strict_types=1);
 
-use App\Services\Config;
+namespace App\Middleware;
 
-class AuthorizationBearer {
+class AuthorizationBearer
+{
     protected string $token;
 
-    function __construct(string $token) {
+    public function __construct(string $token)
+    {
         $this->token = $token;
     }
 
-    /**
-     * @param \Slim\Http\Request    $request
-     * @param \Slim\Http\Response   $response
-     * @param callable              $next
-     *
-     * @return \Slim\Http\Response
-     */
-    public function __invoke($request, $response, $next) {
-        if (!$request->hasHeader('Authorization')) {
+    public function __invoke(\Slim\Http\Request $request, \Slim\Http\Response $response, callable $next): \Slim\Http\Response
+    {
+        if (! $request->hasHeader('Authorization')) {
             return $response->withStatus(401)->withJson([
-                'ret'  => 0,
+                'ret' => 0,
                 'data' => 'Authorization failed',
             ]);
         }
@@ -29,18 +25,18 @@ class AuthorizationBearer {
         $authHeader = $request->getHeaderLine('Authorization');
 
         // Bearer method token verify
-        if (strtoupper(substr($authHeader, 0, 6)) != 'BEARER') {
+        if (strtoupper(substr($authHeader, 0, 6)) !== 'BEARER') {
             return $response->withStatus(401)->withJson([
-                'ret'  => 0,
+                'ret' => 0,
                 'data' => 'Authorization failed',
             ]);
         }
 
         $realToken = substr($authHeader, 7);
 
-        if ($realToken != $this->token) {
+        if ($realToken !== $this->token) {
             return $response->withStatus(401)->withJson([
-                'ret'  => 0,
+                'ret' => 0,
                 'data' => 'Authorization failed',
             ]);
         }

+ 3 - 8
src/Middleware/Guest.php

@@ -1,19 +1,14 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Middleware;
 
 use App\Services\Auth as AuthService;
 
 class Guest
 {
-    /**
-     * @param \Slim\Http\Request    $request
-     * @param \Slim\Http\Response   $response
-     * @param callable              $next
-     *
-     * @return \Slim\Http\Response
-     */
-    public function __invoke($request, $response, $next)
+    public function __invoke(\Slim\Http\Request $request, \Slim\Http\Response $response, callable $next): \Slim\Http\Response
     {
         $user = AuthService::getUser();
         if ($user->isLogin) {

+ 14 - 19
src/Middleware/Mod_Mu.php

@@ -1,53 +1,48 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Middleware;
 
-use App\Services\Config;
 use App\Models\Node;
+use App\Services\Config;
 
 class Mod_Mu
 {
-    /**
-     * @param \Slim\Http\Request    $request
-     * @param \Slim\Http\Response   $response
-     * @param callable              $next
-     *
-     * @return \Slim\Http\Response
-     */
-    public function __invoke($request, $response, $next)
+    public function __invoke(\Slim\Http\Request $request, \Slim\Http\Response $response, callable $next): \Slim\Http\Response
     {
         $key = $request->getQueryParam('key');
         if ($key === null) {
             // 未提供 key
             return $response->withjson([
-                'ret'  => 0,
-                'data' => 'Your key is null.'
+                'ret' => 0,
+                'data' => 'Your key is null.',
             ]);
         }
 
-        if (!in_array($key, Config::getMuKey())) {
+        if (! in_array($key, Config::getMuKey())) {
             // key 不存在
             return $response->withJson([
-                'ret'  => 0,
-                'data' => 'Token is invalid.'
+                'ret' => 0,
+                'data' => 'Token is invalid.',
             ]);
         }
 
         if ($_ENV['WebAPI'] === false) {
             // 主站不提供 WebAPI
             return $response->withJson([
-                'ret'  => 0,
-                'data' => 'WebAPI is disabled.'
+                'ret' => 0,
+                'data' => 'WebAPI is disabled.',
             ]);
         }
 
         if ($_ENV['checkNodeIp'] === true) {
-            if ($_SERVER['REMOTE_ADDR'] != '127.0.0.1') {
+            if ($_SERVER['REMOTE_ADDR'] !== '127.0.0.1') {
                 $node = Node::where('node_ip', 'LIKE', $_SERVER['REMOTE_ADDR'] . '%')->first();
                 if ($node === null) {
                     return $response->withJson([
-                        'ret'  => 0,
-                        'data' => 'IP is invalid. Now, your IP address is ' . $_SERVER['REMOTE_ADDR']
+                        'ret' => 0,
+                        'data' => 'IP is invalid. Now, your IP address is ' . $_SERVER['REMOTE_ADDR'],
                     ]);
                 }
             }

+ 3 - 0
src/Models/Ann.php

@@ -1,11 +1,14 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 /**
  * Ann Model
  *
  * @property-read   int    $id         Announcement ID
+ *
  * @property        string $date       Date announcement posted
  * @property        string $content    Announcement in HTML
  * @property        string $markdown   Announcement in MarkDown

+ 4 - 4
src/Models/BlockIp.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 use App\Utils\QQWry;
@@ -23,7 +25,7 @@ class BlockIp extends Model
      */
     public function node_name(): string
     {
-        if ($this->node() == null) {
+        if ($this->node() === null) {
             return '节点已不存在';
         }
         return $this->node()->name;
@@ -31,10 +33,8 @@ class BlockIp extends Model
 
     /**
      * 获取 IP 位置
-     *
-     * @param QQWry $QQWry
      */
-    public function location(QQWry $QQWry = null): string
+    public function location(?QQWry $QQWry = null): string
     {
         if ($QQWry === null) {
             $QQWry = new QQWry();

+ 16 - 17
src/Models/Bought.php

@@ -1,11 +1,14 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 /**
  * Bought Model
  *
  * @property-read   int     $id         id
+ *
  * @property        int     $userid     User id
  * @property        int     $shopid     Shop id
  * @property        string  $datetime   Bought complete datetime
@@ -22,20 +25,16 @@ class Bought extends Model
 
     /**
      * [静态方法] 删除不存在的用户的记录
-     *
-     * @param Bought $Bought
      */
-    public static function user_is_null($Bought): void
+    public static function user_is_null(Bought $Bought): void
     {
         self::where('userid', $Bought->userid)->delete();
     }
 
     /**
      * [静态方法] 删除不存在的商品的记录
-     *
-     * @param Bought $Bought
      */
-    public static function shop_is_null($Bought): void
+    public static function shop_is_null(Bought $Bought): void
     {
         self::where('shopid', $Bought->shopid)->delete();
     }
@@ -45,7 +44,7 @@ class Bought extends Model
      */
     public function renew(): string
     {
-        if ($this->renew == 0) {
+        if ($this->renew === 0) {
             return '不自动续费';
         }
         return date('Y-m-d H:i:s', $this->renew) . ' 时续费';
@@ -72,7 +71,7 @@ class Bought extends Model
      */
     public function user_name(): string
     {
-        if ($this->user() == null) {
+        if ($this->user() === null) {
             return '用户已不存在';
         }
         return $this->user()->user_name;
@@ -91,7 +90,7 @@ class Bought extends Model
      */
     public function content(): string
     {
-        if ($this->shop() == null) {
+        if ($this->shop() === null) {
             return '商品已不存在';
         }
         return $this->shop()->content();
@@ -102,10 +101,10 @@ class Bought extends Model
      */
     public function auto_reset_bandwidth(): string
     {
-        if ($this->shop() == null) {
+        if ($this->shop() === null) {
             return '商品已不存在';
         }
-        return $this->shop()->auto_reset_bandwidth == 0 ? '不自动重置' : '自动重置';
+        return $this->shop()->auto_reset_bandwidth === 0 ? '不自动重置' : '自动重置';
     }
 
     /*
@@ -123,7 +122,7 @@ class Bought extends Model
     {
         $shop = $this->shop();
         if ($shop->use_loop()) {
-            return (time() - $shop->reset_exp() * 86400 < $this->datetime);
+            return time() - $shop->reset_exp() * 86400 < $this->datetime;
         }
         return false;
     }
@@ -136,12 +135,12 @@ class Bought extends Model
         $shop = $this->shop();
         if ($shop->use_loop()) {
             $day = 24 * 60 * 60;
-            $resetIndex = 1 +  (int)((time() - $this->datetime - $day) / ($shop->reset() * $day));
+            $resetIndex = 1 + (int) ((time() - $this->datetime - $day) / ($shop->reset() * $day));
             $restTime = $resetIndex * $shop->reset() * $day + $this->datetime;
             $time = time() + ($day * 86400);
-            return (!$unix ? date('Y-m-d', strtotime('+1 day', strtotime(date('Y-m-d', $restTime)))) : $time);
+            return ! $unix ? date('Y-m-d', strtotime('+1 day', strtotime(date('Y-m-d', $restTime)))) : $time;
         }
-        return (!$unix ? '-' : 0);
+        return ! $unix ? '-' : 0;
     }
 
     /*
@@ -152,8 +151,8 @@ class Bought extends Model
         $shop = $this->shop();
         if ($shop->use_loop()) {
             $time = $this->datetime + ($shop->reset_exp() * 86400);
-            return (!$unix ? date('Y-m-d H:i:s', $time) : $time);
+            return ! $unix ? date('Y-m-d H:i:s', $time) : $time;
         }
-        return (!$unix ? '-' : 0);
+        return ! $unix ? '-' : 0;
     }
 }

+ 6 - 4
src/Models/Code.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 /**
@@ -24,7 +26,7 @@ class Code extends Model
      */
     public function userid(): string
     {
-        return $this->userid == 0 ? '未使用' : $this->userid;
+        return $this->userid === 0 ? '未使用' : $this->userid;
     }
 
     /**
@@ -32,10 +34,10 @@ class Code extends Model
      */
     public function user_name(): string
     {
-        if ($this->userid == 0) {
+        if ($this->userid === 0) {
             return '未使用';
         }
-        if ($this->user() == null) {
+        if ($this->user() === null) {
             return '用户已不存在';
         }
         return $this->user()->user_name;
@@ -76,7 +78,7 @@ class Code extends Model
      */
     public function isused(): string
     {
-        return $this->isused == 1 ? '已使用' : '未使用';
+        return $this->isused === 1 ? '已使用' : '未使用';
     }
 
     /**

+ 4 - 2
src/Models/Coupon.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 class Coupon extends Model
@@ -14,14 +16,14 @@ class Coupon extends Model
 
     public function order($shop)
     {
-        if ($this->attributes['shop'] == '') {
+        if ($this->attributes['shop'] === '') {
             return true;
         }
 
         $shop_array = explode(',', $this->attributes['shop']);
 
         foreach ($shop_array as $shopid) {
-            if ($shopid == $shop) {
+            if ($shopid === $shop) {
                 return true;
             }
         }

+ 5 - 5
src/Models/DetectBanLog.php

@@ -1,19 +1,19 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 class DetectBanLog extends Model
 {
-    protected $connection = "default";
+    protected $connection = 'default';
 
-    protected $table = "detect_ban_log";
+    protected $table = 'detect_ban_log';
 
     /**
      * [静态方法] 删除不存在的用户的记录
-     *
-     * @param DetectBanLog $DetectBanLog
      */
-    public static function user_is_null($DetectBanLog): void
+    public static function user_is_null(DetectBanLog $DetectBanLog): void
     {
         self::where('user_id', $DetectBanLog->user_id)->delete();
     }

+ 11 - 15
src/Models/DetectLog.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 class DetectLog extends Model
@@ -10,30 +12,24 @@ class DetectLog extends Model
 
     /**
      * [静态方法] 删除不存在的节点的记录
-     *
-     * @param DetectLog $DetectLog
      */
-    public static function node_is_null($DetectLog): void
+    public static function node_is_null(DetectLog $DetectLog): void
     {
         self::where('node_id', $DetectLog->node_id)->delete();
     }
 
     /**
      * [静态方法] 删除不存在的规则的记录
-     *
-     * @param DetectLog $DetectLog
      */
-    public static function rule_is_null($DetectLog): void
+    public static function rule_is_null(DetectLog $DetectLog): void
     {
         self::where('list_id', $DetectLog->list_id)->delete();
     }
 
     /**
      * [静态方法] 删除不存在的用户的记录
-     *
-     * @param DetectLog $DetectLog
      */
-    public static function user_is_null($DetectLog): void
+    public static function user_is_null(DetectLog $DetectLog): void
     {
         self::where('user_id', $DetectLog->user_id)->delete();
     }
@@ -51,7 +47,7 @@ class DetectLog extends Model
      */
     public function user_name(): string
     {
-        if ($this->user() == null) {
+        if ($this->user() === null) {
             return '用户已不存在';
         }
         return $this->user()->user_name;
@@ -70,7 +66,7 @@ class DetectLog extends Model
      */
     public function node_name(): string
     {
-        if ($this->node() == null) {
+        if ($this->node() === null) {
             return '节点已不存在';
         }
         return $this->node()->name;
@@ -89,7 +85,7 @@ class DetectLog extends Model
      */
     public function rule_name(): string
     {
-        if ($this->rule() == null) {
+        if ($this->rule() === null) {
             return '规则已不存在';
         }
         return $this->rule()->name;
@@ -100,7 +96,7 @@ class DetectLog extends Model
      */
     public function rule_text(): string
     {
-        if ($this->rule() == null) {
+        if ($this->rule() === null) {
             return '规则已不存在';
         }
         return $this->rule()->text;
@@ -111,7 +107,7 @@ class DetectLog extends Model
      */
     public function rule_regex(): string
     {
-        if ($this->rule() == null) {
+        if ($this->rule() === null) {
             return '规则已不存在';
         }
         return $this->rule()->regex;
@@ -122,7 +118,7 @@ class DetectLog extends Model
      */
     public function rule_type(): string
     {
-        if ($this->rule() == null) {
+        if ($this->rule() === null) {
             return '规则已不存在';
         }
         return $this->rule()->type();

+ 3 - 1
src/Models/DetectRule.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 /**
@@ -16,6 +18,6 @@ class DetectRule extends Model
      */
     public function type(): string
     {
-        return $this->type == 1 ? '数据包明文匹配' : '数据包十六进制匹配';
+        return $this->type === 1 ? '数据包明文匹配' : '数据包十六进制匹配';
     }
 }

+ 2 - 0
src/Models/EmailQueue.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 /**

+ 2 - 0
src/Models/EmailVerify.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 /**

+ 18 - 23
src/Models/GConfig.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 use App\Services\DefaultConfig;
@@ -22,19 +24,15 @@ class GConfig extends Model
 
     /**
      * 恢复默认配置
-     *
-     * @param User $user
-     *
-     * @return void
      */
-    public function recover($user)
+    public function recover(User $user): void
     {
-        $this->oldvalue       = $this->value;
-        $this->value          = DefaultConfig::default_value($this->key)['value'];
-        $this->operator_id    = $user->id;
-        $this->operator_name  = ('[恢复默认] - ' . $user->user_name);
+        $this->oldvalue = $this->value;
+        $this->value = DefaultConfig::default_value($this->key)['value'];
+        $this->operator_id = $user->id;
+        $this->operator_name = '[恢复默认] - ' . $user->user_name;
         $this->operator_email = $user->email;
-        $this->last_update    = time();
+        $this->last_update = time();
         $this->save();
     }
 
@@ -47,13 +45,13 @@ class GConfig extends Model
     {
         switch ($this->type) {
             case 'bool':
-                return (bool)      $this->value;
+                return (bool) $this->value;
             case 'array':
                 return json_decode($this->value, true);
             case 'string':
-                return (string)    $this->value;
+                return (string) $this->value;
             default:
-                return (string)    $this->value;
+                return (string) $this->value;
         }
     }
 
@@ -61,25 +59,22 @@ class GConfig extends Model
      * 设定配置值
      *
      * @param mixed $value
-     * @param User  $user
-     *
-     * @return bool
      */
-    public function setValue($value, $user = null)
+    public function setValue($value, ?User $user = null): bool
     {
         $this->oldvalue = $this->value;
-        $this->value    = $this->typeConversion($value);
+        $this->value = $this->typeConversion($value);
         if ($user === null) {
-            $this->operator_id    = 0;
-            $this->operator_name  = '系统修改';
+            $this->operator_id = 0;
+            $this->operator_name = '系统修改';
             $this->operator_email = '[email protected]';
         } else {
-            $this->operator_id    = $user->id;
-            $this->operator_name  = $user->user_name;
+            $this->operator_id = $user->id;
+            $this->operator_name = $user->user_name;
             $this->operator_email = $user->email;
         }
         $this->last_update = time();
-        if (!$this->save()) {
+        if (! $this->save()) {
             return false;
         }
         return true;

+ 2 - 0
src/Models/InviteCode.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 /**

+ 6 - 6
src/Models/Ip.php

@@ -1,10 +1,12 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
+use App\Utils\DatatablesHelper;
 use App\Utils\QQWry;
 use App\Utils\Tools;
-use App\Utils\DatatablesHelper;
 
 /**
  * Ip Model
@@ -27,7 +29,7 @@ class Ip extends Model
      */
     public function user_name(): string
     {
-        if ($this->user() == null) {
+        if ($this->user() === null) {
             return '用户已不存在';
         }
         return $this->user()->user_name;
@@ -46,7 +48,7 @@ class Ip extends Model
      */
     public function node_name(): string
     {
-        if ($this->node() == null) {
+        if ($this->node() === null) {
             return '节点已不存在';
         }
         return $this->node()->name;
@@ -54,10 +56,8 @@ class Ip extends Model
 
     /**
      * 获取 IP 位置
-     *
-     * @param QQWry $QQWry
      */
-    public function location(QQWry $QQWry = null): string
+    public function location(?QQWry $QQWry = null): string
     {
         if ($QQWry === null) {
             $QQWry = new QQWry();

+ 2 - 0
src/Models/Link.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 class Link extends Model

+ 6 - 8
src/Models/LoginIp.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 use App\Utils\QQWry;
@@ -19,10 +21,8 @@ class LoginIp extends Model
 
     /**
      * [静态方法] 删除不存在的用户的记录
-     *
-     * @param LoginIp $LoginIp
      */
-    public static function user_is_null($LoginIp): void
+    public static function user_is_null(LoginIp $LoginIp): void
     {
         self::where('userid', $LoginIp->userid)->delete();
     }
@@ -40,7 +40,7 @@ class LoginIp extends Model
      */
     public function user_name(): string
     {
-        if ($this->user() == null) {
+        if ($this->user() === null) {
             return '用户已不存在';
         }
         return $this->user()->user_name;
@@ -56,10 +56,8 @@ class LoginIp extends Model
 
     /**
      * 获取 IP 位置
-     *
-     * @param QQWry $QQWry
      */
-    public function location(QQWry $QQWry = null): string
+    public function location(?QQWry $QQWry = null): string
     {
         if ($QQWry === null) {
             $QQWry = new QQWry();
@@ -73,6 +71,6 @@ class LoginIp extends Model
      */
     public function type(): string
     {
-        return $this->type == 0 ? '成功' : '失败';
+        return $this->type === 0 ? '成功' : '失败';
     }
 }

+ 25 - 21
src/Models/Model.php

@@ -1,19 +1,21 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 use Closure;
 use Illuminate\Contracts\Pagination;
+use Illuminate\Database\Capsule\Manager as Capsule;
 use Illuminate\Database\Eloquent;
 use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Database\Eloquent\Collection;
 use Illuminate\Database\Eloquent\Model as EloquentMedel;
 use Illuminate\Database\Eloquent\Relations\MorphTo;
-use Illuminate\Database\Query\Expression as QueryExpression;
 use Illuminate\Database\Query\Builder as QueryBuilder;
+use Illuminate\Database\Query\Expression as QueryExpression;
 use Illuminate\Support\Collection as SupportCollection;
 use Illuminate\Support\LazyCollection;
-use Illuminate\Database\Capsule\Manager as Capsule;
 
 /**
  * All function below could be staticly called via this function.\
@@ -23,7 +25,9 @@ use Illuminate\Database\Capsule\Manager as Capsule;
  * @version illuminate/database:v8.28.1
  *
  * @codingStandardsIgnoreStart
+ *
  * @package Illuminate\Database\Eloquent\Query
+ *
  * @method static static                            make(array $attributes = [])                                                                                        Create and return an un-saved model instance.
  * @method static $this                             withGlobalScope(string $identifier, Eloquent\Scope|Closure $scope)                                                  Register a new global scope.
  * @method static $this                             withoutGlobalScope(Eloquent\Scope|string $scope)                                                                    Remove a registered global scope.
@@ -38,9 +42,9 @@ use Illuminate\Database\Capsule\Manager as Capsule;
  * @method static $this                             oldest(string|QueryExpression $column = null)                                                                       Add an "order by" clause for a timestamp to the query.
  * @method static Collection                        hydrate(array $items)                                                                                               Create a collection of models from plain arrays.
  * @method static Collection                        fromQuery(string $query, array $bindings = [])                                                                      Create a collection of models from a raw query.
- * @method static Collection|static[]|static|null   find($id, array $columns = ['*'])                                                                                   Find a model by its primary key.
+ * @method static Collection|array<static>|static|null find($id, array $columns = ['*']) Find a model by its primary key.
  * @method static Collection                        findMany(\Illuminate\Contracts\Support\Arrayable|array $ids, array $columns = ['*'])                                Find multiple models by their primary keys.
- * @method static Collection|static|static[]        findOrFail($id, array $columns = ['*'])                                                                             Find a model by its primary key or throw an exception.
+ * @method static Collection|static|array<static> findOrFail($id, array $columns = ['*']) Find a model by its primary key or throw an exception.
  * @method static static                            findOrNew($id, array $columns = ['*'])                                                                              Find a model by its primary key or return fresh model instance.
  * @method static static                            firstOrNew(array $attributes = [], array $values = [])                                                              Get the first record matching the attributes or instantiate it.
  * @method static static                            firstOrCreate(array $attributes = [], array $values = [])                                                           Get the first record matching the attributes or create it.
@@ -49,8 +53,8 @@ use Illuminate\Database\Capsule\Manager as Capsule;
  * @method static static|mixed                      firstOr(Closure|array $columns = ['*'], Closure $callback = null)                                                   Execute the query and get the first result or call a callback.
  * @method static static                            sole(array|string $columns = ['*'])                                                                                 Execute the query and get the first result if it's the sole matching record.
  * @method static mixed                             value(string|QueryExpression $column)                                                                               Get a single column's value from the first result of a query.
- * @method static Collection|static[]               get(array|string $columns = ['*'])                                                                                  Execute the query as a "select" statement.
- * @method static static[]                          getModels(array|string $columns = ['*'])                                                                            Get the hydrated models without eager loading.
+ * @method static Collection|array<static> get(array|string $columns = ['*']) Execute the query as a "select" statement.
+ * @method static array<static> getModels(array|string $columns = ['*']) Get the hydrated models without eager loading.
  * @method static array                             eagerLoadRelations(array $models)                                                                                   Eager load the relationships for the models.
  * @method static Eloquent\Relations\Relation       getRelation(string $name)                                                                                           Get the relation instance for the given relation name.
  * @method static LazyCollection                    cursor()                                                                                                            Get a lazy collection for the given query.
@@ -86,6 +90,7 @@ use Illuminate\Database\Capsule\Manager as Capsule;
  * @method static bool                              hasMacro(string $name)                                                                                              Checks if a macro is registered.
  *
  * @package Illuminate\Database\Eloquent\Concerns\QueriesRelationships
+ *
  * @method static $this|static      has(\Illuminate\Database\Eloquent\Relations\Relation|string $relation, string $operator = '>=', int $count = 1, string $boolean = 'and', ?Closure $callback = null) Add a relationship count / exists condition to the query.
  * @method static $this|static      orHas(string $relation, string $operator = '>=', int $count = 1)                                                                                                    Add a relationship count / exists condition to the query with an "or".
  * @method static $this|static      doesntHave(string $relation, string $boolean = 'and', ?Closure $callback = null)                                                                                    Add a relationship count / exists condition to the query.
@@ -111,11 +116,13 @@ use Illuminate\Database\Capsule\Manager as Capsule;
  * @method static $this|static      mergeConstraintsFrom(Builder $from)                                                                                                                                 Merge the where constraints from another query to the current query.
  *
  * @package Illuminate\Database\Concerns\ExplainsQueries
+ *
  * @method SupportCollection explain() Explains the query.
  *
  * @package Illuminate\Support\Traits\ForwardsCalls
  *
  * @package Illuminate\Database\Concerns\BuildsQueries
+ *
  * @method static bool              chunk(int $count, callable $callback)                                                           Chunk the results of the query.
  * @method static SupportCollection chunkMap(callable $callback, int $count = 1000)                                                 Run a map over each item while chunking.
  * @method static bool              each(callable $callback, int $count = 1000)                                                     Execute a callback over each item while chunking.
@@ -126,6 +133,7 @@ use Illuminate\Database\Capsule\Manager as Capsule;
  * @method static mixed|$this       when(mixed $value, callback $callback, ?callback $default = null)                               Apply the callback's query changes if the given "value" is true.
  * @method static $this             tap(callback $callback)                                                                         Pass the query to a given callback.
  * @method static mixed|$this       unless(mixed $value, callback $callback, ?callback $default = null)                             Apply the callback's query changes if the given "value" is false.
+ *
  * @codingStandardsIgnoreEnd
  */
 class Model extends EloquentMedel
@@ -137,37 +145,33 @@ class Model extends EloquentMedel
      */
     public static function getTableName(): string
     {
-        $class = get_called_class();
-        return (new $class)->getTable();
+        $class = static::class;
+        return (new $class())->getTable();
     }
 
     /**
      * 获取表数据
      *
-     * @param \Slim\Http\Request $request
-     * @param callable           $callback
-     * @param callable           $precondition
-     *
      * @return array
      * [
      *  'datas' => \Illuminate\Database\Eloquent\Collection,
      *  'count' => int
      * ]
      */
-    public static function getTableDataFromAdmin(\Slim\Http\Request $request, $callback = null, $precondition = null): array
+    public static function getTableDataFromAdmin(\Slim\Http\Request $request, ?callable $callback = null, ?callable $precondition = null): array
     {
         //得到排序的方式
-        $order        = $request->getParam('order')[0]['dir'];
+        $order = $request->getParam('order')[0]['dir'];
         //得到排序字段的下标
         $order_column = $request->getParam('order')[0]['column'];
         //根据排序字段的下标得到排序字段
-        $order_field  = $request->getParam('columns')[$order_column]['data'];
+        $order_field = $request->getParam('columns')[$order_column]['data'];
         if ($callback !== null) {
             call_user_func_array($callback, [&$order_field]);
         }
-        $limit_start  = $request->getParam('start');
+        $limit_start = $request->getParam('start');
         $limit_length = $request->getParam('length');
-        $search       = $request->getParam('search')['value'];
+        $search = $request->getParam('search')['value'];
 
         $query = self::query();
         if ($precondition !== null) {
@@ -175,12 +179,12 @@ class Model extends EloquentMedel
         }
         if ($search) {
             $query->where(
-                function ($query) use ($search) {
-                    $query->where('id', 'LIKE binary', "%$search%");
+                function ($query) use ($search): void {
+                    $query->where('id', 'LIKE binary', "%${search}%");
                     $attributes = Capsule::schema()->getColumnListing(self::getTableName());
                     foreach ($attributes as $s) {
-                        if ($s != 'id') {
-                            $query->orwhere($s, 'LIKE binary', "%$search%");
+                        if ($s !== 'id') {
+                            $query->orwhere($s, 'LIKE binary', "%${search}%");
                         }
                     }
                 }

+ 86 - 104
src/Models/Node.php

@@ -1,11 +1,14 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 /**
  * Node Model
  *
  * @property-read   int     $id         id
+ *
  * @property        string  $name       Display name
  * @property        bool    $type       If node display @todo Correct column name and type
  * @property        string  $server     Domain
@@ -15,13 +18,16 @@ namespace App\Models;
  * @property        int     $sort       Node type @todo Correct column name to `type`
  * @property        int     $custom_method  Customs node crypt @deprecated
  * @property        float   $traffic_rate   Node traffic rate
+ *
  * @todo More property
+ *
  * @property        bool    $online     If node is online
  * @property        bool    $gfw_block  If node is blocked by GFW
  */
 
 use App\Services\Config;
-use App\Utils\{Tools, URL};
+use App\Utils\Tools;
+use App\Utils\URL;
 
 class Node extends Model
 {
@@ -31,11 +37,11 @@ class Node extends Model
 
     protected $casts = [
         'node_speedlimit' => 'float',
-        'traffic_rate'    => 'float',
-        'mu_only'         => 'int',
-        'sort'            => 'int',
-        'type'            => 'bool',
-        'node_heartbeat'  => 'int',
+        'traffic_rate' => 'float',
+        'mu_only' => 'int',
+        'sort' => 'int',
+        'type' => 'bool',
+        'node_heartbeat' => 'int',
     ];
 
     /**
@@ -101,7 +107,7 @@ class Node extends Model
      */
     public function get_node_flag(): string
     {
-        $regex   = $_ENV['flag_regex'];
+        $regex = $_ENV['flag_regex'];
         $matches = [];
         preg_match($regex, $this->name, $matches);
         return isset($matches[0]) ? $matches[0] . '.png' : 'unknown.png';
@@ -118,7 +124,7 @@ class Node extends Model
     public function getLastNodeInfoLog()
     {
         $log = NodeInfoLog::where('node_id', $this->id)->orderBy('id', 'desc')->first();
-        if ($log == null) {
+        if ($log === null) {
             return null;
         }
         return $log;
@@ -127,7 +133,7 @@ class Node extends Model
     public function getNodeUptime()
     {
         $log = $this->getLastNodeInfoLog();
-        if ($log == null) {
+        if ($log === null) {
             return '暂无数据';
         }
         return Tools::secondsToTime((int) $log->uptime);
@@ -141,14 +147,12 @@ class Node extends Model
 
     public function getNodeLoad()
     {
-        $log = NodeInfoLog::where('node_id', $this->id)->orderBy('id', 'desc')->whereRaw('`log_time`%1800<60')->limit(48)->get();
-        return $log;
+        return NodeInfoLog::where('node_id', $this->id)->orderBy('id', 'desc')->whereRaw('`log_time`%1800<60')->limit(48)->get();
     }
 
     public function getNodeAlive()
     {
-        $log = NodeOnlineLog::where('node_id', $this->id)->orderBy('id', 'desc')->whereRaw('`log_time`%1800<60')->limit(48)->get();
-        return $log;
+        return NodeOnlineLog::where('node_id', $this->id)->orderBy('id', 'desc')->whereRaw('`log_time`%1800<60')->limit(48)->get();
     }
 
     /**
@@ -160,7 +164,7 @@ class Node extends Model
             return -1;
         }
         $log = NodeOnlineLog::where('node_id', $this->id)->where('log_time', '>', time() - 300)->orderBy('id', 'desc')->first();
-        if ($log == null) {
+        if ($log === null) {
             return 0;
         }
         return $log->online_user;
@@ -174,7 +178,7 @@ class Node extends Model
     public function get_node_online_status(): int
     {
         // 类型 9 或者心跳为 0
-        if ($this->node_heartbeat == 0 || in_array($this->sort, [9])) {
+        if ($this->node_heartbeat === 0 || in_array($this->sort, [9])) {
             return 0;
         }
         return $this->node_heartbeat + 300 > time() ? 1 : -1;
@@ -186,10 +190,10 @@ class Node extends Model
     public function get_node_latest_load(): int
     {
         $log = NodeInfoLog::where('node_id', $this->id)->where('log_time', '>', time() - 300)->orderBy('id', 'desc')->first();
-        if ($log == null) {
+        if ($log === null) {
             return -1;
         }
-        return (explode(' ', $log->load))[0] * 100;
+        return explode(' ', $log->load)[0] * 100;
     }
 
     /**
@@ -198,7 +202,7 @@ class Node extends Model
     public function get_node_latest_load_text(): string
     {
         $load = $this->get_node_latest_load();
-        return $load == -1 ? 'N/A' : $load . '%';
+        return $load === -1 ? 'N/A' : $load . '%';
     }
 
     /**
@@ -206,13 +210,13 @@ class Node extends Model
      */
     public function get_node_speedlimit(): string
     {
-        if ($this->node_speedlimit == 0.0) {
+        if ($this->node_speedlimit === 0.0) {
             return 0;
-        } elseif ($this->node_speedlimit >= 1024.00) {
+        }
+        if ($this->node_speedlimit >= 1024.00) {
             return round($this->node_speedlimit / 1024.00, 1) . 'Gbps';
-        } else {
-            return $this->node_speedlimit . 'Mbps';
         }
+        return $this->node_speedlimit . 'Mbps';
     }
 
     /**
@@ -231,7 +235,7 @@ class Node extends Model
      */
     public function isNodeTrafficOut(): bool
     {
-        return !($this->node_bandwidth_limit == 0 || $this->node_bandwidth < $this->node_bandwidth_limit);
+        return ! ($this->node_bandwidth_limit === 0 || $this->node_bandwidth < $this->node_bandwidth_limit);
     }
 
     /**
@@ -239,19 +243,17 @@ class Node extends Model
      */
     public function isNodeAccessable(): bool
     {
-        return $this->isNodeTrafficOut() == false && $this->isNodeOnline() == true;
+        return $this->isNodeTrafficOut() === false && $this->isNodeOnline() === true;
     }
 
     /**
      * 更新节点 IP
-     *
-     * @param string $server_name
      */
     public function changeNodeIp(string $server_name): bool
     {
-        if (!Tools::is_ip($server_name)) {
+        if (! Tools::is_ip($server_name)) {
             $ip = gethostbyname($server_name);
-            if ($ip == '') {
+            if ($ip === '') {
                 return false;
             }
         } else {
@@ -266,7 +268,7 @@ class Node extends Model
      */
     public function getNodeIp(): string
     {
-        $node_ip_str   = $this->node_ip;
+        $node_ip_str = $this->node_ip;
         $node_ip_array = explode(',', $node_ip_str);
         return $node_ip_array[0];
     }
@@ -284,7 +286,7 @@ class Node extends Model
      */
     public function get_entrance_address(): string
     {
-        if ($this->sort == 13) {
+        if ($this->sort === 13) {
             $server = Tools::ssv2Array($this->server);
             return $server['add'];
         }
@@ -309,26 +311,21 @@ class Node extends Model
 
     /**
      * 获取 SS/SSR 节点
-     *
-     * @param User $user
-     * @param int  $mu_port
-     * @param int  $is_ss
-     * @param bool $emoji
      */
-    public function getItem(User $user, int $mu_port = 0, int $is_ss = 0, bool $emoji = false):? array
+    public function getItem(User $user, int $mu_port = 0, int $is_ss = 0, bool $emoji = false): ?array
     {
         $node_name = $this->name;
-        if ($mu_port != 0) {
+        if ($mu_port !== 0) {
             $mu_user = User::where('port', '=', $mu_port)->where('is_multi_user', '<>', 0)->first();
-            if ($mu_user == null) {
+            if ($mu_user === null) {
                 return null;
             }
             // 如果混淆和协议均为SS原生且为单端口的,即判断为AEAD单端口类型,密码配置为用户自身密码
-            if ($mu_user->obfs == "plain" && $mu_user->protocol == "origin"){
+            if ($mu_user->obfs === 'plain' && $mu_user->protocol === 'origin') {
                 $mu_user->passwd = $user->passwd;
-                $mu_user->obfs_param     = "";
-                $mu_user->protocol_param = "";
-            }else{
+                $mu_user->obfs_param = '';
+                $mu_user->protocol_param = '';
+            } else {
                 $mu_user->obfs_param = $user->getMuMd5();
                 $mu_user->protocol_param = $user->id . ':' . $user->passwd;
             }
@@ -336,93 +333,84 @@ class Node extends Model
             $node_name .= ($_ENV['disable_sub_mu_port'] ? '' : ' - ' . $mu_port . ' 单端口');
         }
         if ($is_ss) {
-            if (!URL::SSCanConnect($user)) {
+            if (! URL::SSCanConnect($user)) {
                 return null;
             }
             $user = URL::getSSConnectInfo($user);
             $return_array['type'] = 'ss';
         } else {
-            if (!URL::SSRCanConnect($user)) {
+            if (! URL::SSRCanConnect($user)) {
                 return null;
             }
             $user = URL::getSSRConnectInfo($user);
             $return_array['type'] = 'ssr';
         }
-        $return_array['address']        = $this->get_entrance_address();
-        $return_array['port']           = $user->port;
-        $return_array['protocol']       = $user->protocol;
+        $return_array['address'] = $this->get_entrance_address();
+        $return_array['port'] = $user->port;
+        $return_array['protocol'] = $user->protocol;
         $return_array['protocol_param'] = $user->protocol_param;
-        $return_array['obfs']           = $user->obfs;
-        $return_array['obfs_param']     = $user->obfs_param;
-        if ($mu_port != 0 && strpos($this->server, ';') !== false) {
-            $node_tmp             = Tools::OutPort($this->server, $this->name, $mu_port);
+        $return_array['obfs'] = $user->obfs;
+        $return_array['obfs_param'] = $user->obfs_param;
+        if ($mu_port !== 0 && strpos($this->server, ';') !== false) {
+            $node_tmp = Tools::OutPort($this->server, $this->name, $mu_port);
             $return_array['port'] = $node_tmp['port'];
-            $node_name            = $node_tmp['name'];
+            $node_name = $node_tmp['name'];
         }
         $return_array['passwd'] = $user->passwd;
         $return_array['method'] = $user->method;
         $return_array['remark'] = ($emoji ? Tools::addEmoji($node_name) : $node_name);
-        $return_array['class']  = $this->node_class;
-        $return_array['group']  = $_ENV['appName'];
-        $return_array['ratio']  = $this->traffic_rate;
+        $return_array['class'] = $this->node_class;
+        $return_array['group'] = $_ENV['appName'];
+        $return_array['ratio'] = $this->traffic_rate;
 
         return $return_array;
     }
 
     /**
      * 获取 V2Ray 节点
-     *
-     * @param User $user
-     * @param int  $mu_port
-     * @param int  $is_ss
-     * @param bool $emoji
      */
     public function getV2RayItem(User $user, int $mu_port = 0, int $is_ss = 0, bool $emoji = false): array
     {
-        $item           = Tools::v2Array($this->server);
-        $item['type']   = 'vmess';
+        $item = Tools::v2Array($this->server);
+        $item['type'] = 'vmess';
         $item['remark'] = ($emoji ? Tools::addEmoji($this->name) : $this->name);
-        $item['id']     = $user->uuid;
-        $item['class']  = $this->node_class;
+        $item['id'] = $user->uuid;
+        $item['class'] = $this->node_class;
         return $item;
     }
 
-
     /**
      * 获取 V2RayPlugin | obfs 节点
      *
      * @param User $user 用户
-     * @param int  $mu_port
-     * @param int  $is_ss
-     * @param bool $emoji
      *
      * @return array|null
      */
-    public function getV2RayPluginItem(User $user, int $mu_port = 0, int $is_ss = 0, bool $emoji = false)
+    public function getV2RayPluginItem(User $user, int $mu_port = 0, int $is_ss = 0, bool $emoji = false): ?array
     {
         $return_array = Tools::ssv2Array($this->server);
         // 非 AEAD 加密无法使用
-        if ($return_array['net'] != 'obfs' && !in_array($user->method, Config::getSupportParam('ss_aead_method'))) {
+        if ($return_array['net'] !== 'obfs' && ! in_array($user->method, Config::getSupportParam('ss_aead_method'))) {
             return null;
         }
-        $return_array['remark']         = ($emoji ? Tools::addEmoji($this->name) : $this->name);
-        $return_array['address']        = $return_array['add'];
-        $return_array['method']         = $user->method;
-        $return_array['passwd']         = $user->passwd;
-        $return_array['protocol']       = 'origin';
+        $return_array['remark'] = ($emoji ? Tools::addEmoji($this->name) : $this->name);
+        $return_array['address'] = $return_array['add'];
+        $return_array['method'] = $user->method;
+        $return_array['passwd'] = $user->passwd;
+        $return_array['protocol'] = 'origin';
         $return_array['protocol_param'] = '';
-        if ($return_array['net'] == 'obfs') {
+        if ($return_array['net'] === 'obfs') {
             $return_array['obfs_param'] = $user->getMuMd5();
         } else {
             $return_array['obfs'] = 'v2ray';
-            if ($return_array['tls'] == 'tls' && $return_array['net'] == 'ws') {
-                $return_array['obfs_param'] = ('mode=ws;security=tls;path=' . $return_array['path'] .
-                    ';host=' . $return_array['host']);
+            if ($return_array['tls'] === 'tls' && $return_array['net'] === 'ws') {
+                $return_array['obfs_param'] = 'mode=ws;security=tls;path=' . $return_array['path'] .
+                    ';host=' . $return_array['host'];
             } else {
-                $return_array['obfs_param'] = ('mode=ws;security=none;path=' . $return_array['path'] .
-                    ';host=' . $return_array['host']);
+                $return_array['obfs_param'] = 'mode=ws;security=none;path=' . $return_array['path'] .
+                    ';host=' . $return_array['host'];
             }
-            $return_array['path'] = ($return_array['path'] . '?redirect=' . $user->getMuMd5());
+            $return_array['path'] = $return_array['path'] . '?redirect=' . $user->getMuMd5();
         }
         $return_array['class'] = $this->node_class;
         $return_array['group'] = $_ENV['appName'];
@@ -436,38 +424,32 @@ class Node extends Model
      * Trojan 节点
      *
      * @param User $user 用户
-     * @param int  $mu_port
-     * @param int  $is_ss
-     * @param bool $emoji
      */
     public function getTrojanItem(User $user, int $mu_port = 0, int $is_ss = 0, bool $emoji = false): array
     {
         $server = explode(';', $this->server);
-        $opt    = [];
+        $opt = [];
         if (isset($server[1])) {
             $opt = URL::parse_args($server[1]);
         }
-        $item['remark']   = ($emoji ? Tools::addEmoji($this->name) : $this->name);
-        $item['type']     = 'trojan';
-        $item['address']  = $server[0];
-        $item['port']     = (isset($opt['port']) ? (int) $opt['port'] : 443);
-        $item['passwd']   = $user->uuid;
-        $item['host']     = $item['address'];
-        $item['net']	  = (isset($opt['grpc']) ? "grpc" :'');
-        $item['servicename'] = (isset($opt['servicename']) ? $opt['servicename'] :'');
-        $item['flow']	  = (isset($opt['flow']) ? $opt['flow'] :'');
-        $xtls			= (isset($opt['enable_xtls']) ? $opt['enable_xtls'] :'');
-        if($xtls == 'true'){
-          $item['tls'] =  'xtls';
-        }else {
-          $item['tls'] =  'tls';
+        $item['remark'] = ($emoji ? Tools::addEmoji($this->name) : $this->name);
+        $item['type'] = 'trojan';
+        $item['address'] = $server[0];
+        $item['port'] = (isset($opt['port']) ? (int) $opt['port'] : 443);
+        $item['passwd'] = $user->uuid;
+        $item['host'] = $item['address'];
+        $item['net'] = (isset($opt['grpc']) ? 'grpc' : '');
+        $item['servicename'] = ($opt['servicename'] ?? '');
+        $item['flow'] = ($opt['flow'] ?? '');
+        $xtls = ($opt['enable_xtls'] ?? '');
+        if ($xtls === 'true') {
+            $item['tls'] = 'xtls';
+        } else {
+            $item['tls'] = 'tls';
         }
         if (isset($opt['host'])) {
-          $item['host'] = $opt['host'];
+            $item['host'] = $opt['host'];
         }
         return $item;
     }
-
-
-
 }

+ 2 - 0
src/Models/NodeInfoLog.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 class NodeInfoLog extends Model

+ 1 - 0
src/Models/NodeOnlineLog.php

@@ -1,5 +1,6 @@
 <?php
 
+declare(strict_types=1);
 
 namespace App\Models;
 

+ 2 - 0
src/Models/PasswordReset.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 class PasswordReset extends Model

+ 10 - 8
src/Models/Payback.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 class Payback extends Model
@@ -10,7 +12,7 @@ class Payback extends Model
     public function user()
     {
         $user = User::where('id', $this->attributes['userid'])->first();
-        if ($user == null) {
+        if ($user === null) {
             Bought::where('id', '=', $this->attributes['id'])->delete();
             return null;
         }
@@ -18,25 +20,25 @@ class Payback extends Model
         return $user;
     }
 
-    public function rebate($user_id, $order_amount)
+    public function rebate($user_id, $order_amount): void
     {
         $configs = Setting::getClass('invite');
         $user = User::where('id', $user_id)->first();
         $gift_user_id = $user->ref_by;
-        
+
         // 判断
         $invite_rebate_mode = $configs['invite_rebate_mode'];
         $rebate_ratio = $configs['rebate_ratio'];
-        if ($invite_rebate_mode == 'continued') {
+        if ($invite_rebate_mode === 'continued') {
             // 不设限制
             self::executeRebate($user_id, $gift_user_id, $order_amount);
-        } elseif ($invite_rebate_mode == 'limit_frequency') {
+        } elseif ($invite_rebate_mode === 'limit_frequency') {
             // 限制返利次数
             $rebate_frequency = self::where('userid', $user_id)->count();
             if ($rebate_frequency < $configs['rebate_frequency_limit']) {
                 self::executeRebate($user_id, $gift_user_id, $order_amount);
             }
-        } elseif ($invite_rebate_mode == 'limit_amount') {
+        } elseif ($invite_rebate_mode === 'limit_amount') {
             // 限制返利金额
             $total_rebate_amount = self::where('userid', $user_id)->sum('ref_get');
             // 预计返利 (expected_rebate) 是指:订单金额 * 返点比例
@@ -52,14 +54,14 @@ class Payback extends Model
             } else {
                 self::executeRebate($user_id, $gift_user_id, $order_amount);
             }
-        } elseif ($invite_rebate_mode == 'limit_time_range') {
+        } elseif ($invite_rebate_mode === 'limit_time_range') {
             if (strtotime($user->reg_date) + $configs['rebate_time_range_limit'] * 86400 > time()) {
                 self::executeRebate($user_id, $gift_user_id, $order_amount);
             }
         }
     }
 
-    public function executeRebate($user_id, $gift_user_id, $order_amount, $adjust_rebate = null)
+    public function executeRebate($user_id, $gift_user_id, $order_amount, $adjust_rebate = null): void
     {
         $gift_user = User::where('id', $gift_user_id)->first();
         $rebate_amount = $order_amount * Setting::obtain('rebate_ratio');

+ 2 - 0
src/Models/Paylist.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 class Paylist extends Model

+ 12 - 11
src/Models/Setting.php

@@ -1,32 +1,34 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 class Setting extends Model
 {
     protected $connection = 'default';
     protected $table = 'config';
-    
+
     public static function obtain($item)
     {
         $config = self::where('item', '=', $item)->first();
-        
-        if ($config->type == 'bool') {
+
+        if ($config->type === 'bool') {
             return (bool) $config->value;
-        } elseif ($config->type == 'int') {
+        }
+        if ($config->type === 'int') {
             return (int) $config->value;
         }
-        
+
         return (string) $config->value;
     }
 
     public static function getClass($class)
     {
-        $configs = array();
+        $configs = [];
         $all_configs = Setting::where('class', $class)->get();
 
-        foreach ($all_configs as $config)
-        {
+        foreach ($all_configs as $config) {
             $configs[$config->item] = $config->value;
         }
 
@@ -35,11 +37,10 @@ class Setting extends Model
 
     public static function getPublicConfig()
     {
-        $configs = array();
+        $configs = [];
         $all_configs = Setting::where('is_public', '1')->get();
 
-        foreach ($all_configs as $config)
-        {
+        foreach ($all_configs as $config) {
             $configs[$config->item] = $config->value;
         }
 

+ 20 - 19
src/Models/Shop.php

@@ -1,9 +1,12 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 /**
  * @property-read   int     $id
+ *
  * @property        string  $name
  * @property        float   $price
  * @property        array   $content
@@ -39,14 +42,14 @@ class Shop extends Model
                     $content_text .= ', 在 ' . $this->content['reset_exp'] . ' 天内 ,每 ' . $value . ' 天重置流量为 ' . $this->content['reset_value'] . ' G ';
                     break;
                 case 'speedlimit':
-                    if ($value == 0) {
+                    if ($value === 0) {
                         $content_text .= ', 用户端口不限速 ';
                     } else {
                         $content_text .= ', 用户端口限速变为' . $value . ' Mbps ';
                     }
                     break;
                 case 'connector':
-                    if ($value == 0) {
+                    if ($value === 0) {
                         $content_text .= ', 用户IP不限制';
                     } else {
                         $content_text .= ', 用户IP限制变为 ' . $value . ' 个';
@@ -56,9 +59,7 @@ class Shop extends Model
             }
         }
 
-        $content_text = rtrim($content_text, ',');
-
-        return $content_text;
+        return rtrim($content_text, ',');
     }
 
     public function bandwidth()
@@ -97,14 +98,13 @@ class Shop extends Model
             $content_extra = explode(';', $this->content['content_extra']);
             $content_extra_new = [];
             foreach ($content_extra as $innerContent) {
-                if (false === strpos($innerContent, '-')) {
+                if (strpos($innerContent, '-') === false) {
                     $innerContent = 'check-' . $innerContent;
                 }
                 $innerContent = explode('-', $innerContent);
                 $content_extra_new[] = $innerContent;
             }
-            $content_extra = $content_extra_new;
-            return $content_extra;
+            return $content_extra_new;
         }
 
         return 0;
@@ -130,7 +130,7 @@ class Shop extends Model
         return $this->content['connector'] ?? 0;
     }
 
-    public function buy($user, $is_renew = 0)
+    public function buy($user, $is_renew = 0): void
     {
         if (isset($this->content['traffic_package'])) {
             $user->transfer_enable += $this->content['bandwidth'] * 1024 * 1024 * 1024;
@@ -141,8 +141,8 @@ class Shop extends Model
         foreach ($this->content as $key => $value) {
             switch ($key) {
                 case 'bandwidth':
-                    if ($is_renew == 0) {
-                        if ($_ENV['enable_bought_reset'] == true) {
+                    if ($is_renew === 0) {
+                        if ($_ENV['enable_bought_reset'] === true) {
                             $user->transfer_enable = $value * 1024 * 1024 * 1024;
                             $user->u = 0;
                             $user->d = 0;
@@ -150,7 +150,7 @@ class Shop extends Model
                         } else {
                             $user->transfer_enable += $value * 1024 * 1024 * 1024;
                         }
-                    } elseif ($this->auto_reset_bandwidth == 1) {
+                    } elseif ($this->auto_reset_bandwidth === 1) {
                         $user->transfer_enable = $value * 1024 * 1024 * 1024;
                         $user->u = 0;
                         $user->d = 0;
@@ -167,8 +167,8 @@ class Shop extends Model
                     }
                     break;
                 case 'class':
-                    if ($_ENV['enable_bought_extend'] == true) {
-                        if ($user->class == $value) {
+                    if ($_ENV['enable_bought_extend'] === true) {
+                        if ($user->class === $value) {
                             $user->class_expire = date('Y-m-d H:i:s', strtotime($user->class_expire) + $this->content['class_expire'] * 86400);
                         } else {
                             $user->class_expire = date('Y-m-d H:i:s', time() + $this->content['class_expire'] * 86400);
@@ -179,6 +179,7 @@ class Shop extends Model
                         $user->class_expire = date('Y-m-d H:i:s', time() + $this->content['class_expire'] * 86400);
                         break;
                     }
+                    // no break
                 case 'speedlimit':
                     $user->node_speedlimit = $value;
                     break;
@@ -197,7 +198,7 @@ class Shop extends Model
      */
     public function use_loop(): bool
     {
-        return ($this->reset() != 0 && $this->reset_value() != 0 && $this->reset_exp() != 0);
+        return $this->reset() !== 0 && $this->reset_value() !== 0 && $this->reset_exp() !== 0;
     }
 
     /*
@@ -206,7 +207,7 @@ class Shop extends Model
     public function getSales(): int
     {
         $period = $_ENV['sales_period'];
-        if ($period == 'expire') {
+        if ($period === 'expire') {
             $period = $this->content['class_expire'];
         }
         return Bought::where('shopid', $this->id)->where('datetime', '>', time() - $period * 86400)->count();
@@ -217,7 +218,7 @@ class Shop extends Model
      */
     public function auto_renew(): string
     {
-        return $this->auto_renew == 0 ? '不自动续费' : $this->auto_renew . ' 天后续费';
+        return $this->auto_renew === 0 ? '不自动续费' : $this->auto_renew . ' 天后续费';
     }
 
     /*
@@ -225,7 +226,7 @@ class Shop extends Model
      */
     public function auto_reset_bandwidth(): string
     {
-        return $this->auto_reset_bandwidth == 0 ? '不自动重置' : '自动重置';
+        return $this->auto_reset_bandwidth === 0 ? '不自动重置' : '自动重置';
     }
 
     /*
@@ -233,6 +234,6 @@ class Shop extends Model
      */
     public function status(): string
     {
-        return $this->status == 1 ? '上架' : '下架';
+        return $this->status === 1 ? '上架' : '下架';
     }
 }

+ 3 - 0
src/Models/StreamMedia.php

@@ -1,4 +1,7 @@
 <?php
+
+declare(strict_types=1);
+
 namespace App\Models;
 
 class StreamMedia extends Model

+ 3 - 1
src/Models/TelegramSession.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 /**
@@ -18,7 +20,7 @@ class TelegramSession extends Model
     public function User()
     {
         $user = User::where('id', $this->attributes['user_id'])->first();
-        if ($user == null) {
+        if ($user === null) {
             Ticket::where('id', '=', $this->attributes['id'])->delete();
             return null;
         }

+ 5 - 5
src/Models/Ticket.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 /**
@@ -13,10 +15,8 @@ class Ticket extends Model
 
     /**
      * [静态方法] 删除不存在的用户的记录
-     *
-     * @param Ticket $Ticket
      */
-    public static function user_is_null($Ticket): void
+    public static function user_is_null(Ticket $Ticket): void
     {
         $tickets = Ticket::where('userid', $Ticket->userid)->where('rootid', 0)->get();
         foreach ($tickets as $ticket) {
@@ -46,7 +46,7 @@ class Ticket extends Model
      */
     public function user_name(): string
     {
-        if ($this->user() == null) {
+        if ($this->user() === null) {
             return '用户已不存在';
         }
         return $this->user()->user_name;
@@ -57,6 +57,6 @@ class Ticket extends Model
      */
     public function status(): string
     {
-        return $this->status == 1 ? '开启' : '关闭';
+        return $this->status === 1 ? '开启' : '关闭';
     }
 }

+ 2 - 0
src/Models/Token.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 class Token extends Model

+ 4 - 4
src/Models/UnblockIp.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 use App\Utils\QQWry;
@@ -23,7 +25,7 @@ class UnblockIp extends Model
      */
     public function user_name(): string
     {
-        if ($this->user() == null) {
+        if ($this->user() === null) {
             return '用户已不存在';
         }
         return $this->user()->user_name;
@@ -31,10 +33,8 @@ class UnblockIp extends Model
 
     /**
      * 获取 IP 位置
-     *
-     * @param QQWry $QQWry
      */
-    public function location(QQWry $QQWry = null): string
+    public function location(?QQWry $QQWry = null): string
     {
         if ($QQWry === null) {
             $QQWry = new QQWry();

+ 168 - 201
src/Models/User.php

@@ -1,40 +1,37 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 use App\Controllers\LinkController;
-use App\Utils\{
-    Tools,
-    Hash,
-    GA,
-    Telegram,
-    URL
-};
-use App\Services\{Config, Mail};
-use Ramsey\Uuid\Uuid;
+use Config;
 use Exception;
+use Ramsey\Uuid\Uuid;
+use Tools;
 
 /**
  * User Model
  *
  * @property-read   int     $id         ID
+ *
  * @todo More property
+ *
  * @property        bool    $is_admin           是否管理员
  * @property        bool    $expire_notified    If user is notified for expire
  * @property        bool    $traffic_notified   If user is noticed for low traffic
  */
 class User extends Model
 {
-    protected $connection = 'default';
-
-    protected $table = 'user';
-
     /**
      * 已登录
      *
      * @var bool
      */
     public $isLogin;
+    protected $connection = 'default';
+
+    protected $table = 'user';
 
     /**
      * 强制类型转换
@@ -42,17 +39,17 @@ class User extends Model
      * @var array
      */
     protected $casts = [
-        't'               => 'float',
-        'u'               => 'float',
-        'd'               => 'float',
-        'port'            => 'int',
+        't' => 'float',
+        'u' => 'float',
+        'd' => 'float',
+        'port' => 'int',
         'transfer_enable' => 'float',
-        'enable'          => 'int',
-        'is_admin'        => 'boolean',
-        'is_multi_user'   => 'int',
+        'enable' => 'int',
+        'is_admin' => 'boolean',
+        'is_multi_user' => 'int',
         'node_speedlimit' => 'float',
-        'sendDailyMail'   => 'int',
-        'ref_by'          => 'int'
+        'sendDailyMail' => 'int',
+        'ref_by' => 'int',
     ];
 
     /**
@@ -99,15 +96,15 @@ class User extends Model
     public function getMuMd5()
     {
         $str = str_replace(
-            array('%id', '%suffix'),
-            array($this->id, $_ENV['mu_suffix']),
+            ['%id', '%suffix'],
+            [$this->id, $_ENV['mu_suffix']],
             $_ENV['mu_regex']
         );
         preg_match_all("|%-?[1-9]\d*m|U", $str, $matches, PREG_PATTERN_ORDER);
         foreach ($matches[0] as $key) {
-            $key_match = str_replace(array('%', 'm'), '', $key);
+            $key_match = str_replace(['%', 'm'], '', $key);
             $md5 = substr(
-                MD5($this->id . $this->passwd . $this->method . $this->obfs . $this->protocol),
+                md5($this->id . $this->passwd . $this->method . $this->obfs . $this->protocol),
                 ($key_match < 0 ? $key_match : 0),
                 abs($key_match)
             );
@@ -121,7 +118,7 @@ class User extends Model
      */
     public function lastSsTime(): string
     {
-        return $this->t == 0 ? '从未使用喵' : Tools::toDateTime($this->t);
+        return $this->t === 0 ? '从未使用喵' : Tools::toDateTime($this->t);
     }
 
     /**
@@ -129,13 +126,11 @@ class User extends Model
      */
     public function lastCheckInTime(): string
     {
-        return $this->last_check_in_time == 0 ? '从未签到' : Tools::toDateTime($this->last_check_in_time);
+        return $this->last_check_in_time === 0 ? '从未签到' : Tools::toDateTime($this->last_check_in_time);
     }
 
     /**
      * 更新密码
-     *
-     * @param string $pwd
      */
     public function updatePassword(string $pwd): bool
     {
@@ -155,8 +150,6 @@ class User extends Model
 
     /**
      * 更新连接密码
-     *
-     * @param string $pwd
      */
     public function updateSsPwd(string $pwd): bool
     {
@@ -166,38 +159,36 @@ class User extends Model
 
     /**
      * 更新加密方式
-     *
-     * @param string $method
      */
     public function updateMethod(string $method): array
     {
         $return = [
-            'ok' => false
+            'ok' => false,
         ];
-        if ($method == '') {
+        if ($method === '') {
             $return['msg'] = '非法输入';
             return $return;
         }
-        if (!Tools::is_param_validate('method', $method)) {
+        if (! Tools::is_param_validate('method', $method)) {
             $return['msg'] = '加密无效';
             return $return;
         }
         $this->method = $method;
-        if (!Tools::checkNoneProtocol($this)) {
+        if (! Tools::checkNoneProtocol($this)) {
             $return['msg'] = '系统检测到您将要设置的加密方式为 none ,但您的协议并不在以下协议【' . implode(',', Config::getSupportParam('allow_none_protocol')) . '】之内,请您先修改您的协议,再来修改此处设置。';
             return $return;
         }
-        if (!URL::SSCanConnect($this) && !URL::SSRCanConnect($this)) {
+        if (! URL::SSCanConnect($this) && ! URL::SSRCanConnect($this)) {
             $return['msg'] = '您这样设置之后,就没有客户端能连接上了,所以系统拒绝了您的设置,请您检查您的设置之后再进行操作。';
             return $return;
         }
         $this->save();
         $return['ok'] = true;
-        if (!URL::SSCanConnect($this)) {
-            $return['msg']  = '设置成功,但您目前的协议,混淆,加密方式设置会导致 Shadowsocks 原版客户端无法连接,请您自行更换到 ShadowsocksR 客户端。';
+        if (! URL::SSCanConnect($this)) {
+            $return['msg'] = '设置成功,但您目前的协议,混淆,加密方式设置会导致 Shadowsocks 原版客户端无法连接,请您自行更换到 ShadowsocksR 客户端。';
         }
-        if (!URL::SSRCanConnect($this)) {
-            $return['msg']  = '设置成功,但您目前的协议,混淆,加密方式设置会导致 ShadowsocksR 客户端无法连接,请您自行更换到 Shadowsocks 客户端。';
+        if (! URL::SSRCanConnect($this)) {
+            $return['msg'] = '设置成功,但您目前的协议,混淆,加密方式设置会导致 ShadowsocksR 客户端无法连接,请您自行更换到 Shadowsocks 客户端。';
         }
         $return['msg'] = '设置成功,您可自由选用两种客户端来进行连接。';
         return $return;
@@ -210,16 +201,15 @@ class User extends Model
     {
         while (true) {
             $temp_code = Tools::genRandomChar(10);
-            if (InviteCode::where('code', $temp_code)->first() == null) {
-                if (InviteCode::where('user_id', $this->id)->count() == 0) {
-                    $code          = new InviteCode();
-                    $code->code    = $temp_code;
+            if (InviteCode::where('code', $temp_code)->first() === null) {
+                if (InviteCode::where('user_id', $this->id)->count() === 0) {
+                    $code = new InviteCode();
+                    $code->code = $temp_code;
                     $code->user_id = $this->id;
                     $code->save();
                     return $temp_code;
-                } else {
-                    return (InviteCode::where('user_id', $this->id)->first())->code;
                 }
+                return (InviteCode::where('user_id', $this->id)->first())->code;
             }
         }
     }
@@ -274,13 +264,12 @@ class User extends Model
      */
     public function trafficUsagePercent(): int
     {
-        if ($this->transfer_enable == 0) {
+        if ($this->transfer_enable === 0) {
             return 0;
         }
-        $percent  = ($this->u + $this->d) / $this->transfer_enable;
-        $percent  = round($percent, 2);
-        $percent *= 100;
-        return $percent;
+        $percent = ($this->u + $this->d) / $this->transfer_enable;
+        $percent = round($percent, 2);
+        return $percent * 100;
     }
 
     /*
@@ -296,14 +285,13 @@ class User extends Model
      */
     public function unusedTrafficPercent(): int
     {
-        if ($this->transfer_enable == 0) {
+        if ($this->transfer_enable === 0) {
             return 0;
         }
-        $unused   = $this->transfer_enable - ($this->u + $this->d);
-        $percent  = $unused / $this->transfer_enable;
-        $percent  = round($percent, 2);
-        $percent *= 100;
-        return $percent;
+        $unused = $this->transfer_enable - ($this->u + $this->d);
+        $percent = $unused / $this->transfer_enable;
+        $percent = round($percent, 2);
+        return $percent * 100;
     }
 
     /*
@@ -319,14 +307,13 @@ class User extends Model
      */
     public function TodayusedTrafficPercent(): int
     {
-        if ($this->transfer_enable == 0) {
+        if ($this->transfer_enable === 0) {
             return 0;
         }
         $Todayused = $this->u + $this->d - $this->last_day_t;
-        $percent   = $Todayused / $this->transfer_enable;
-        $percent   = round($percent, 2);
-        $percent  *= 100;
-        return $percent;
+        $percent = $Todayused / $this->transfer_enable;
+        $percent = round($percent, 2);
+        return $percent * 100;
     }
 
     /*
@@ -342,14 +329,13 @@ class User extends Model
      */
     public function LastusedTrafficPercent(): int
     {
-        if ($this->transfer_enable == 0) {
+        if ($this->transfer_enable === 0) {
             return 0;
         }
         $Lastused = $this->last_day_t;
-        $percent  = $Lastused / $this->transfer_enable;
-        $percent  = round($percent, 2);
-        $percent *= 100;
-        return $percent;
+        $percent = $Lastused / $this->transfer_enable;
+        $percent = round($percent, 2);
+        return $percent * 100;
     }
 
     /*
@@ -357,17 +343,16 @@ class User extends Model
      */
     public function isAbleToCheckin(): bool
     {
-        return date('Ymd') != date('Ymd', $this->last_check_in_time);
+        return date('Ymd') !== date('Ymd', $this->last_check_in_time);
     }
 
     public function getGAurl()
     {
         $ga = new GA();
-        $url = $ga->getUrl(
+        return $ga->getUrl(
             urlencode($_ENV['appName'] . '-' . $this->user_name . '-两步验证码'),
             $this->ga_token
         );
-        return $url;
     }
 
     /**
@@ -391,21 +376,19 @@ class User extends Model
      */
     public function ref_by_user_name(): string
     {
-        if ($this->ref_by == 0) {
+        if ($this->ref_by === 0) {
             return '系统邀请';
-        } else {
-            if ($this->ref_by_user() == null) {
-                return '邀请人已经被删除';
-            } else {
-                return $this->ref_by_user()->user_name;
-            }
         }
+        if ($this->ref_by_user() === null) {
+            return '邀请人已经被删除';
+        }
+        return $this->ref_by_user()->user_name;
     }
 
     /**
      * 删除用户的订阅链接
      */
-    public function clean_link()
+    public function clean_link(): void
     {
         Link::where('userid', $this->id)->delete();
     }
@@ -421,7 +404,7 @@ class User extends Model
     /**
      * 删除用户的邀请码
      */
-    public function clear_inviteCodes()
+    public function clear_inviteCodes(): void
     {
         InviteCode::where('user_id', $this->id)->delete();
     }
@@ -436,7 +419,7 @@ class User extends Model
         $ip_list = [];
         foreach ($total as $single_record) {
             $ip = Tools::getRealIp($single_record->ip);
-            if (Node::where('node_ip', $ip)->first() != null) {
+            if (Node::where('node_ip', $ip)->first() !== null) {
                 continue;
             }
             $ip_list[] = $ip;
@@ -449,7 +432,7 @@ class User extends Model
      */
     public function kill_user(): bool
     {
-        $uid   = $this->id;
+        $uid = $this->id;
         $email = $this->email;
 
         Bought::where('userid', '=', $uid)->delete();
@@ -483,22 +466,20 @@ class User extends Model
 
     /**
      * 获取累计收入
-     *
-     * @param string $req
      */
     public function calIncome(string $req): float
     {
         switch ($req) {
-            case "yesterday":
+            case 'yesterday':
                 $number = Code::whereDate('usedatetime', '=', date('Y-m-d', strtotime('-1 days')))->sum('number');
                 break;
-            case "today":
+            case 'today':
                 $number = Code::whereDate('usedatetime', '=', date('Y-m-d'))->sum('number');
                 break;
-            case "this month":
+            case 'this month':
                 $number = Code::whereYear('usedatetime', '=', date('Y'))->whereMonth('usedatetime', '=', date('m'))->sum('number');
                 break;
-            case "last month":
+            case 'last month':
                 $number = Code::whereYear('usedatetime', '=', date('Y'))->whereMonth('usedatetime', '=', date('m', strtotime('last month')))->sum('number');
                 break;
             default:
@@ -522,7 +503,7 @@ class User extends Model
     public function disableReason(): string
     {
         $reason_id = DetectLog::where('user_id', $this->id)->orderBy('id', 'DESC')->first();
-        $reason    = DetectRule::find($reason_id->list_id);
+        $reason = DetectRule::find($reason_id->list_id);
         if (is_null($reason)) {
             return '特殊原因被禁用,了解详情请联系管理员';
         }
@@ -534,7 +515,7 @@ class User extends Model
      */
     public function last_detect_ban_time(): string
     {
-        return ($this->last_detect_ban_time == '1989-06-04 00:05:00' ? '未被封禁过' : $this->last_detect_ban_time);
+        return $this->last_detect_ban_time === '1989-06-04 00:05:00' ? '未被封禁过' : $this->last_detect_ban_time;
     }
 
     /**
@@ -543,12 +524,11 @@ class User extends Model
     public function relieve_time(): string
     {
         $logs = DetectBanLog::where('user_id', $this->id)->orderBy('id', 'desc')->first();
-        if ($this->enable == 0 && $logs != null) {
-            $time = ($logs->end_time + $logs->ban_time * 60);
+        if ($this->enable === 0 && $logs !== null) {
+            $time = $logs->end_time + $logs->ban_time * 60;
             return date('Y-m-d H:i:s', $time);
-        } else {
-            return '当前未被封禁';
         }
+        return '当前未被封禁';
     }
 
     /**
@@ -574,11 +554,11 @@ class User extends Model
     public function checkin(): array
     {
         $return = [
-            'ok'  => true,
-            'msg' => ''
+            'ok' => true,
+            'msg' => '',
         ];
-        if (!$this->isAbleToCheckin()) {
-            $return['ok']  = false;
+        if (! $this->isAbleToCheckin()) {
+            $return['ok'] = false;
             $return['msg'] = '您似乎已经签到过了...';
         } else {
             $traffic = random_int((int) $_ENV['checkinMin'], (int) $_ENV['checkinMax']);
@@ -593,83 +573,79 @@ class User extends Model
 
     /**
      * 更新协议
-     *
-     * @param string $Protocol
      */
-    public function setProtocol($Protocol): array
+    public function setProtocol(string $Protocol): array
     {
         $return = [
-            'ok'  => true,
-            'msg' => '设置成功,您可自由选用客户端来连接。'
+            'ok' => true,
+            'msg' => '设置成功,您可自由选用客户端来连接。',
         ];
-        if ($Protocol == '') {
-            $return['ok']   = false;
-            $return['msg']  = '非法输入';
+        if ($Protocol === '') {
+            $return['ok'] = false;
+            $return['msg'] = '非法输入';
             return $return;
         }
-        if (!Tools::is_param_validate('protocol', $Protocol)) {
-            $return['ok']   = false;
-            $return['msg']  = '协议无效';
+        if (! Tools::is_param_validate('protocol', $Protocol)) {
+            $return['ok'] = false;
+            $return['msg'] = '协议无效';
             return $return;
         }
         $this->protocol = $Protocol;
-        if (!Tools::checkNoneProtocol($this)) {
-            $return['ok']   = false;
-            $return['msg']  = '系统检测到您目前的加密方式为 none ,但您将要设置为的协议并不在以下协议【' . implode(',', Config::getSupportParam('allow_none_protocol')) . '】之内,请您先修改您的加密方式,再来修改此处设置。';
+        if (! Tools::checkNoneProtocol($this)) {
+            $return['ok'] = false;
+            $return['msg'] = '系统检测到您目前的加密方式为 none ,但您将要设置为的协议并不在以下协议【' . implode(',', Config::getSupportParam('allow_none_protocol')) . '】之内,请您先修改您的加密方式,再来修改此处设置。';
             return $return;
         }
-        if (!URL::SSCanConnect($this) && !URL::SSRCanConnect($this)) {
-            $return['ok']   = false;
-            $return['msg']  = '您这样设置之后,就没有客户端能连接上了,所以系统拒绝了您的设置,请您检查您的设置之后再进行操作。';
+        if (! URL::SSCanConnect($this) && ! URL::SSRCanConnect($this)) {
+            $return['ok'] = false;
+            $return['msg'] = '您这样设置之后,就没有客户端能连接上了,所以系统拒绝了您的设置,请您检查您的设置之后再进行操作。';
             return $return;
         }
         $this->save();
-        if (!URL::SSCanConnect($this)) {
-            $return['ok']   = true;
-            $return['msg']  = '设置成功,但您目前的协议,混淆,加密方式设置会导致 Shadowsocks 原版客户端无法连接,请您自行更换到 ShadowsocksR 客户端。';
+        if (! URL::SSCanConnect($this)) {
+            $return['ok'] = true;
+            $return['msg'] = '设置成功,但您目前的协议,混淆,加密方式设置会导致 Shadowsocks 原版客户端无法连接,请您自行更换到 ShadowsocksR 客户端。';
         }
-        if (!URL::SSRCanConnect($this)) {
-            $return['ok']   = true;
-            $return['msg']  = '设置成功,但您目前的协议,混淆,加密方式设置会导致 ShadowsocksR 客户端无法连接,请您自行更换到 Shadowsocks 客户端。';
+        if (! URL::SSRCanConnect($this)) {
+            $return['ok'] = true;
+            $return['msg'] = '设置成功,但您目前的协议,混淆,加密方式设置会导致 ShadowsocksR 客户端无法连接,请您自行更换到 Shadowsocks 客户端。';
         }
         return $return;
     }
 
     /**
      * 更新混淆
-     *
-     * @param string $Obfs
      */
-    public function setObfs($Obfs): array
+    public function setObfs(string $Obfs): array
     {
         $return = [
-            'ok'  => true,
-            'msg' => '设置成功,您可自由选用客户端来连接。'
+            'ok' => true,
+            'msg' => '设置成功,您可自由选用客户端来连接。',
         ];
-        if ($Obfs == '') {
-            $return['ok']   = false;
-            $return['msg']  = '非法输入';
+        if ($Obfs === '') {
+            $return['ok'] = false;
+            $return['msg'] = '非法输入';
             return $return;
         }
-        if (!Tools::is_param_validate('obfs', $Obfs)) {
-            $return['ok']   = false;
-            $return['msg']  = '混淆无效';
+        if (! Tools::is_param_validate('obfs', $Obfs)) {
+            $return['ok'] = false;
+            $return['msg'] = '混淆无效';
             return $return;
         }
         $this->obfs = $Obfs;
-        if (!URL::SSCanConnect($this) && !URL::SSRCanConnect($this)) {
-            $return['ok']   = false;
-            $return['msg']  = '您这样设置之后,就没有客户端能连接上了,所以系统拒绝了您的设置,请您检查您的设置之后再进行操作。';
+        if (! URL::SSCanConnect($this) && ! URL::SSRCanConnect($this)) {
+            $return['ok'] = false;
+            $return['msg'] = '您这样设置之后,就没有客户端能连接上了,所以系统拒绝了您的设置,请您检查您的设置之后再进行操作。';
             return $return;
         }
         $this->save();
-        if (!URL::SSCanConnect($this)) {
-            $return['ok']   = true;
-            $return['msg']  = '设置成功,但您目前的协议,混淆,加密方式设置会导致 Shadowsocks 原版客户端无法连接,请您自行更换到 ShadowsocksR 客户端。';
+        if (! URL::SSCanConnect($this)) {
+            $return['ok'] = true;
+            $return['msg'] = '设置成功,但您目前的协议,混淆,加密方式设置会导致 Shadowsocks 原版客户端无法连接,请您自行更换到 ShadowsocksR 客户端。';
         }
-        if (!URL::SSRCanConnect($this)) {
-            $return['ok']   = true;
-            $return['msg']  = '设置成功,但您目前的协议,混淆,加密方式设置会导致 ShadowsocksR 客户端无法连接,请您自行更换到 Shadowsocks 客户端。';
+        if (! URL::SSRCanConnect($this)) {
+            $return['ok'] = true;
+            $return['msg'] = '设置成功,但您目前的协议,混淆,加密方式设置会导致 ShadowsocksR 客户端无法连接,请您自行更换到 Shadowsocks 客户端。';
         }
         return $return;
     }
@@ -680,8 +656,8 @@ class User extends Model
     public function TelegramReset(): array
     {
         $return = [
-            'ok'  => true,
-            'msg' => '解绑成功.'
+            'ok' => true,
+            'msg' => '解绑成功.',
         ];
         $telegram_id = $this->telegram_id;
         $this->telegram_id = 0;
@@ -693,20 +669,20 @@ class User extends Model
                 &&
                 Config::getconfig('Telegram.bool.unbind_kick_member') === true
                 &&
-                !$this->is_admin
+                ! $this->is_admin
             ) {
                 \App\Utils\Telegram\TelegramTools::SendPost(
                     'kickChatMember',
                     [
-                        'chat_id'   => $_ENV['telegram_chatid'],
-                        'user_id'   => $telegram_id,
+                        'chat_id' => $_ENV['telegram_chatid'],
+                        'user_id' => $telegram_id,
                     ]
                 );
             }
         } else {
             $return = [
-                'ok'  => false,
-                'msg' => '解绑失败.'
+                'ok' => false,
+                'msg' => '解绑失败.',
             ];
         }
 
@@ -715,23 +691,21 @@ class User extends Model
 
     /**
      * 更新端口
-     *
-     * @param int $Port
      */
-    public function setPort($Port): array
+    public function setPort(int $Port): array
     {
         $PortOccupied = User::pluck('port')->toArray();
-        if (in_array($Port, $PortOccupied) == true) {
+        if (in_array($Port, $PortOccupied) === true) {
             return [
-                'ok'  => false,
-                'msg' => '端口已被占用'
+                'ok' => false,
+                'msg' => '端口已被占用',
             ];
         }
         $this->port = $Port;
         $this->save();
         return [
-            'ok'  => true,
-            'msg' => $this->port
+            'ok' => true,
+            'msg' => $this->port,
         ];
     }
 
@@ -743,8 +717,8 @@ class User extends Model
         $price = $_ENV['port_price'];
         if ($this->money < $price) {
             return [
-                'ok'  => false,
-                'msg' => '余额不足'
+                'ok' => false,
+                'msg' => '余额不足',
             ];
         }
         $this->money -= $price;
@@ -752,44 +726,42 @@ class User extends Model
         $this->setPort($Port);
         $this->save();
         return [
-            'ok'  => true,
-            'msg' => $this->port
+            'ok' => true,
+            'msg' => $this->port,
         ];
     }
 
     /**
      * 指定端口
-     *
-     * @param int $Port
      */
-    public function SpecifyPort($Port): array
+    public function SpecifyPort(int $Port): array
     {
         $price = $_ENV['port_price_specify'];
         if ($this->money < $price) {
             return [
-                'ok'  => false,
-                'msg' => '余额不足'
+                'ok' => false,
+                'msg' => '余额不足',
             ];
         }
-        if ($Port < $_ENV['min_port'] || $Port > $_ENV['max_port'] || Tools::isInt($Port) == false) {
+        if ($Port < $_ENV['min_port'] || $Port > $_ENV['max_port'] || Tools::isInt($Port) === false) {
             return [
-                'ok'  => false,
-                'msg' => '端口不在要求范围内'
+                'ok' => false,
+                'msg' => '端口不在要求范围内',
             ];
         }
         $PortOccupied = User::pluck('port')->toArray();
-        if (in_array($Port, $PortOccupied) == true) {
+        if (in_array($Port, $PortOccupied) === true) {
             return [
-                'ok'  => false,
-                'msg' => '端口已被占用'
+                'ok' => false,
+                'msg' => '端口已被占用',
             ];
         }
         $this->money -= $price;
         $this->setPort($Port);
         $this->save();
         return [
-            'ok'  => true,
-            'msg' => '钦定成功'
+            'ok' => true,
+            'msg' => '钦定成功',
         ];
     }
 
@@ -802,14 +774,14 @@ class User extends Model
         $data = [];
         foreach ($boughts as $bought) {
             $shop = $bought->shop();
-            if ($shop != null && $bought->valid()) {
+            if ($shop !== null && $bought->valid()) {
                 $data[] = $bought->reset_time();
             }
         }
-        if (count($data) == 0) {
+        if (count($data) === 0) {
             return '未购买套餐.';
         }
-        if (count($data) == 1) {
+        if (count($data) === 1) {
             return $data[0];
         }
         return '多个有效套餐无法显示.';
@@ -822,14 +794,14 @@ class User extends Model
      */
     public function addMoneyLog($total): void
     {
-        if ($_ENV['money_from_admin'] && $total != 0) {
-            $codeq              = new Code();
-            $codeq->code        = ($total > 0 ? '管理员赏赐' : '管理员惩戒');
-            $codeq->isused      = 1;
-            $codeq->type        = -1;
-            $codeq->number      = $total;
+        if ($_ENV['money_from_admin'] && $total !== 0) {
+            $codeq = new Code();
+            $codeq->code = ($total > 0 ? '管理员赏赐' : '管理员惩戒');
+            $codeq->isused = 1;
+            $codeq->type = -1;
+            $codeq->number = $total;
             $codeq->usedatetime = date('Y-m-d H:i:s');
-            $codeq->userid      = $this->id;
+            $codeq->userid = $this->id;
             $codeq->save();
         }
     }
@@ -837,8 +809,6 @@ class User extends Model
     /**
      * 发送邮件
      *
-     * @param string $subject
-     * @param string $template
      * @param array  $ary
      * @param array  $files
      */
@@ -846,7 +816,7 @@ class User extends Model
     {
         $result = false;
         if ($is_queue) {
-            $new_emailqueue = new EmailQueue;
+            $new_emailqueue = new EmailQueue();
             $new_emailqueue->to_email = $this->email;
             $new_emailqueue->subject = $subject;
             $new_emailqueue->template = $template;
@@ -866,7 +836,7 @@ class User extends Model
                     $template,
                     array_merge(
                         [
-                            'user' => $this
+                            'user' => $this,
                         ],
                         $ary
                     ),
@@ -882,8 +852,6 @@ class User extends Model
 
     /**
      * 发送 Telegram 讯息
-     *
-     * @param string $text
      */
     public function sendTelegram(string $text): bool
     {
@@ -905,7 +873,7 @@ class User extends Model
      */
     public function sendDailyNotification(string $ann = ''): void
     {
-        $lastday = (($this->u + $this->d) - $this->last_day_t) / 1024 / 1024;
+        $lastday = ($this->u + $this->d - $this->last_day_t) / 1024 / 1024;
         switch ($this->sendDailyMail) {
             case 0:
                 return;
@@ -915,16 +883,16 @@ class User extends Model
                     $_ENV['appName'] . '-每日流量报告以及公告',
                     'news/daily-traffic-report.tpl',
                     [
-                        'user'    => $this,
-                        'text'    => '下面是系统中目前的公告:<br><br>' . $ann . '<br><br>晚安!',
-                        'lastday' => $lastday
+                        'user' => $this,
+                        'text' => '下面是系统中目前的公告:<br><br>' . $ann . '<br><br>晚安!',
+                        'lastday' => $lastday,
                     ],
                     []
                 );
                 break;
             case 2:
                 echo 'Send daily Telegram message to user: ' . $this->id;
-                $text  = date('Y-m-d') . ' 流量使用报告' . PHP_EOL . PHP_EOL;
+                $text = date('Y-m-d') . ' 流量使用报告' . PHP_EOL . PHP_EOL;
                 $text .= '流量总计:' . $this->enableTraffic() . PHP_EOL;
                 $text .= '已用流量:' . $this->usedTraffic() . PHP_EOL;
                 $text .= '剩余流量:' . $this->unusedTraffic() . PHP_EOL;
@@ -939,16 +907,15 @@ class User extends Model
     /**
      * 记录登录 IP
      *
-     * @param string $ip
      * @param int    $type 登录失败为 1
      */
     public function collectLoginIP(string $ip, int $type = 0): bool
     {
-        $loginip           = new LoginIp();
-        $loginip->ip       = $ip;
-        $loginip->userid   = $this->id;
+        $loginip = new LoginIp();
+        $loginip->ip = $ip;
+        $loginip->userid = $this->id;
         $loginip->datetime = time();
-        $loginip->type     = $type;
+        $loginip->type = $type;
 
         return $loginip->save();
     }

+ 1 - 0
src/Models/UserHourlyUsage.php

@@ -1,5 +1,6 @@
 <?php
 
+declare(strict_types=1);
 
 namespace App\Models;
 

+ 13 - 18
src/Models/UserSubscribeLog.php

@@ -1,9 +1,10 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Models;
 
 use App\Utils\QQWry;
-
 use voku\helper\AntiXSS;
 
 class UserSubscribeLog extends Model
@@ -14,10 +15,8 @@ class UserSubscribeLog extends Model
 
     /**
      * [静态方法] 删除不存在的用户的记录
-     *
-     * @param UserSubscribeLog $UserSubscribeLog
      */
-    public static function user_is_null($UserSubscribeLog): void
+    public static function user_is_null(UserSubscribeLog $UserSubscribeLog): void
     {
         self::where('user_id', $UserSubscribeLog->user_id)->delete();
     }
@@ -32,10 +31,8 @@ class UserSubscribeLog extends Model
 
     /**
      * 获取 IP 位置
-     *
-     * @param QQWry $QQWry
      */
-    public function location(QQWry $QQWry = null)
+    public function location(?QQWry $QQWry = null)
     {
         if ($QQWry === null) {
             $QQWry = new QQWry();
@@ -50,19 +47,17 @@ class UserSubscribeLog extends Model
      * @param User   $user 用户
      * @param string $type 订阅类型
      * @param string $ua   UA
-     *
-     * @return void
      */
-    public static function addSubscribeLog($user, $type, $ua)
+    public static function addSubscribeLog(User $user, string $type, string $ua): void
     {
-        $log                     = new UserSubscribeLog();
-        $log->user_name          = $user->user_name;
-        $log->user_id            = $user->id;
-        $log->email              = $user->email;
-        $log->subscribe_type     = $type;
-        $log->request_ip         = $_SERVER['REMOTE_ADDR'];
-        $log->request_time       = date('Y-m-d H:i:s');
-        $antiXss                 = new AntiXSS();
+        $log = new UserSubscribeLog();
+        $log->user_name = $user->user_name;
+        $log->user_id = $user->id;
+        $log->email = $user->email;
+        $log->subscribe_type = $type;
+        $log->request_ip = $_SERVER['REMOTE_ADDR'];
+        $log->request_time = date('Y-m-d H:i:s');
+        $antiXss = new AntiXSS();
         $log->request_user_agent = $antiXss->xss_clean($ua);
         $log->save();
     }

+ 2 - 0
src/Services/Analytic.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Services;
 
 use App\Models\User;

+ 5 - 6
src/Services/Analytics.php

@@ -1,9 +1,11 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Services;
 
-use App\Models\User;
 use App\Models\Node;
+use App\Models\User;
 use App\Utils\Tools;
 
 class Analytics
@@ -35,7 +37,6 @@ class Analytics
         return Tools::flowAutoShow($total);
     }
 
-
     public function getRawTodayTrafficUsage()
     {
         return User::sum('u') + User::sum('d') - User::sum('last_day_t');
@@ -47,7 +48,6 @@ class Analytics
         return Tools::flowAutoShow($total);
     }
 
-
     public function getRawLastTrafficUsage()
     {
         return User::sum('last_day_t');
@@ -64,7 +64,6 @@ class Analytics
         return User::sum('transfer_enable') - User::sum('u') - User::sum('d');
     }
 
-
     public function getTotalTraffic()
     {
         $total = User::sum('transfer_enable');
@@ -95,7 +94,7 @@ class Analytics
     public function getTotalNodes()
     {
         return Node::where('node_heartbeat', '>', 0)->where(
-            static function ($query) {
+            static function ($query): void {
                 $query->Where('sort', '=', 0)
                     ->orWhere('sort', '=', 10)
                     ->orWhere('sort', '=', 11)
@@ -109,7 +108,7 @@ class Analytics
     public function getAliveNodes()
     {
         return Node::where(
-            static function ($query) {
+            static function ($query): void {
                 $query->Where('sort', '=', 0)
                     ->orWhere('sort', '=', 10)
                     ->orWhere('sort', '=', 11)

+ 10 - 11
src/Services/Auth.php

@@ -1,28 +1,22 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Services;
 
 class Auth
 {
-
     protected $user;
 
-    private static function getDriver()
-    {
-        return Factory::createAuth();
-    }
-
-    public static function login($uid, $time)
+    public static function login($uid, $time): void
     {
         self::getDriver()->login($uid, $time);
     }
 
     /**
      * Get current user(cached)
-     *
-     * @return \App\Models\User
      */
-    public static function getUser()
+    public static function getUser(): \App\Models\User
     {
         global $user;
         if ($user === null) {
@@ -31,8 +25,13 @@ class Auth
         return $user;
     }
 
-    public static function logout()
+    public static function logout(): void
     {
         self::getDriver()->logout();
     }
+
+    private static function getDriver()
+    {
+        return Factory::createAuth();
+    }
 }

+ 5 - 3
src/Services/Auth/Base.php

@@ -1,12 +1,14 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Services\Auth;
 
 abstract class Base
 {
-    abstract public function login($uid, $time);
+    abstract public function login($uid, $time): void;
 
-    abstract public function logout();
+    abstract public function logout(): void;
 
-    abstract public function getUser();
+    abstract public function getUser(): void;
 }

+ 13 - 13
src/Services/Auth/Cookie.php

@@ -1,15 +1,17 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Services\Auth;
 
-use App\Models\User;
 use App\Models\Node;
+use App\Models\User;
 use App\Utils;
 use App\Utils\Hash;
 
 class Cookie extends Base
 {
-    public function login($uid, $time)
+    public function login($uid, $time): void
     {
         $user = User::find($uid);
         $expire_in = $time + time();
@@ -19,7 +21,7 @@ class Cookie extends Base
             'email' => $user->email,
             'key' => $key,
             'ip' => md5($_SERVER['REMOTE_ADDR'] . $_ENV['key'] . $uid . $expire_in),
-            'expire_in' => $expire_in
+            'expire_in' => $expire_in,
         ], $expire_in);
     }
 
@@ -34,7 +36,7 @@ class Cookie extends Base
         $user = new User();
         $user->isLogin = false;
 
-        if ($uid == null) {
+        if ($uid === null) {
             return $user;
         }
 
@@ -42,44 +44,42 @@ class Cookie extends Base
             return $user;
         }
 
-        if ($_ENV['enable_login_bind_ip'] == true) {
+        if ($_ENV['enable_login_bind_ip'] === true) {
             $nodes = Node::where('node_ip', '=', $_SERVER['REMOTE_ADDR'])->first();
-            if (($nodes == null) && $ipHash != md5($_SERVER['REMOTE_ADDR'] . $_ENV['key'] . $uid . $expire_in)) {
+            if (($nodes === null) && $ipHash !== md5($_SERVER['REMOTE_ADDR'] . $_ENV['key'] . $uid . $expire_in)) {
                 return $user;
             }
         }
 
         $user = User::find($uid);
-        if ($user == null) {
+        if ($user === null) {
             $user = new User();
             $user->isLogin = false;
             return $user;
         }
 
-        if ($user->email != $email) {
+        if ($user->email !== $email) {
             $user = new User();
             $user->isLogin = false;
         }
 
-
-        if (Hash::cookieHash($user->pass, $expire_in) != $key) {
+        if (Hash::cookieHash($user->pass, $expire_in) !== $key) {
             $user = new User();
             $user->isLogin = false;
             return $user;
         }
 
-
         $user->isLogin = true;
         return $user;
     }
 
-    public function logout()
+    public function logout(): void
     {
         $time = time() - 1000;
         Utils\Cookie::set([
             'uid' => null,
             'email' => null,
-            'key' => null
+            'key' => null,
         ], $time);
     }
 }

+ 9 - 7
src/Services/Auth/JwtToken.php

@@ -1,35 +1,37 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Services\Auth;
 
-use App\Utils;
 use App\Services\Jwt;
+use App\Utils;
 
 class JwtToken extends Base
 {
-    public function login($uid, $time)
+    public function login($uid, $time): void
     {
         $expireTime = time() + $time;
         $ary = [
             'uid' => $uid,
-            'expire_time' => $expireTime
+            'expire_time' => $expireTime,
         ];
         $decode = Jwt::encode($ary);
         Utils\Cookie::set([
             //"uid" => $uid,
-            'token' => $decode
+            'token' => $decode,
         ], $expireTime);
     }
 
-    public function logout()
+    public function logout(): void
     {
         Utils\Cookie::set([
             //"uid" => $uid,
-            'token' => ''
+            'token' => '',
         ], time() - 3600);
     }
 
-    public function getUser()
+    public function getUser(): void
     {
         $token = Utils\Cookie::get('token');
         $tokenInfo = Jwt::decodeArray($token);

+ 5 - 3
src/Services/Aws/Client.php

@@ -1,19 +1,21 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Services\Aws;
 
 use Aws\Sdk;
 
 class Client
 {
-    public function getClient()
+    public function getClient(): void
     {
         $sdk = new Sdk([
             'region' => 'us-west-2',
             'version' => 'latest',
             'DynamoDb' => [
-                'region' => 'eu-central-1'
-            ]
+                'region' => 'eu-central-1',
+            ],
         ]);
     }
 }

+ 10 - 9
src/Services/Aws/Factory.php

@@ -1,28 +1,29 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Services\Aws;
 
-use Aws\Sdk;
 use App\Models\Setting;
+use Aws\Sdk;
 
 class Factory
 {
     public static function createAwsClient()
     {
         $configs = Setting::getClass('aws_ses');
-        
-        $sdk = new Sdk([
-            'credentials' => array(
+
+        return new Sdk([
+            'credentials' => [
                 'key' => $configs['aws_access_key_id'],
                 'secret' => $configs['aws_secret_access_key'],
-            ),
+            ],
             'region' => $_ENV['aws_region'],
             'version' => 'latest',
             'DynamoDb' => [
-                'region' => $_ENV['aws_region']
-            ]
+                'region' => $_ENV['aws_region'],
+            ],
         ]);
-        return $sdk;
     }
 
     public static function createDynamodb()
@@ -30,7 +31,7 @@ class Factory
         return self::createAwsClient()->createDynamoDb();
     }
 
-    public static function createSes()
+    public static function createSes(): void
     {
     }
 }

+ 8 - 5
src/Services/Boot.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Services;
 
 use Illuminate\Database\Capsule\Manager as Capsule;
@@ -7,13 +9,13 @@ use Sentry;
 
 class Boot
 {
-    public static function setTime()
+    public static function setTime(): void
     {
         date_default_timezone_set($_ENV['timeZone']);
         View::$beginTime = microtime(true);
     }
 
-    public static function bootDb()
+    public static function bootDb(): void
     {
         // Init Eloquent ORM Connection
         $capsule = new Capsule();
@@ -31,12 +33,13 @@ class Boot
         $capsule->getDatabaseManager()->connection('default')->enableQueryLog();
     }
 
-    public static function bootSentry() {
-        if (!empty($_ENV['sentry_dsn'])) {
+    public static function bootSentry(): void
+    {
+        if (! empty($_ENV['sentry_dsn'])) {
             Sentry\init([
                 'dsn' => $_ENV['sentry_dsn'],
                 'prefixes' => [
-                    realpath(__DIR__ . '/../../')
+                    realpath(__DIR__ . '/../../'),
                 ],
                 'in_app_exclude' => [
                     realpath(__DIR__ . '/../../vendor'),

+ 10 - 10
src/Services/Captcha.php

@@ -1,19 +1,20 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Services;
 
-use App\Utils\Geetest;
 use App\Models\Setting;
+use App\Utils\Geetest;
 
 class Captcha
 {
     public static function generate(): array
     {
-        $geetest   = null;
+        $geetest = null;
         $recaptcha = null;
 
-        switch (Setting::obtain('captcha_provider'))
-        {
+        switch (Setting::obtain('captcha_provider')) {
             case 'recaptcha':
                 $recaptcha = Setting::obtain('recaptcha_sitekey');
                 break;
@@ -23,8 +24,8 @@ class Captcha
         }
 
         return [
-            'geetest'   => $geetest,
-            'recaptcha' => $recaptcha
+            'geetest' => $geetest,
+            'recaptcha' => $recaptcha,
         ];
     }
 
@@ -35,12 +36,11 @@ class Captcha
     {
         $result = false;
 
-        switch (Setting::obtain('captcha_provider'))
-        {
+        switch (Setting::obtain('captcha_provider')) {
             case 'recaptcha':
                 if (isset($param['recaptcha'])) {
-                    if ($param['recaptcha'] != '') {
-                        $json   = file_get_contents('https://recaptcha.net/recaptcha/api/siteverify?secret=' . Setting::obtain('recaptcha_secret') . '&response=' . $param['recaptcha']);
+                    if ($param['recaptcha'] !== '') {
+                        $json = file_get_contents('https://recaptcha.net/recaptcha/api/siteverify?secret=' . Setting::obtain('recaptcha_secret') . '&response=' . $param['recaptcha']);
                         $result = json_decode($json)->success;
                     }
                 }

+ 3 - 1
src/Services/CoinPayment.php

@@ -1,5 +1,7 @@
 <?php
 
+declare(strict_types=1);
+
 namespace App\Services;
 
 use App\Models\Setting;
@@ -26,7 +28,7 @@ class CoinPayment
     public static function purchaseHTML()
     {
         $coinpay_secret = Setting::obtain('coinpay_secret');
-        if (self::getClient() != null && $coinpay_secret != '') {
+        if (self::getClient() !== null && $coinpay_secret !== '') {
             return self::getClient()->getPurchaseHTML();
         }
 

Vissa filer visades inte eftersom för många filer har ändrats