diff --git a/application/Components/Auth.php b/application/Components/Auth.php index 301f653..16f83bd 100644 --- a/application/Components/Auth.php +++ b/application/Components/Auth.php @@ -66,14 +66,18 @@ public function getGrant(): string protected function loadCurUser($grant = 'cookies') { $user_id = false; - if ($grant == 'cookies') $user_id = $this->loadCurUserIdFromCookies(); - elseif ($grant == 'passkey') $user_id = $this->loadCurUserIdFromPasskey(); + if ($grant == 'cookies') { + $user_id = $this->loadCurUserIdFromCookies(); + } elseif ($grant == 'passkey') { + $user_id = $this->loadCurUserIdFromPasskey(); + } if ($user_id !== false && is_int($user_id) && $user_id > 0) { $user_id = intval($user_id); $curuser = app()->site->getUser($user_id); - if ($curuser->getStatus() !== UserStatus::DISABLED) // user status shouldn't be disabled + if ($curuser->getStatus() !== UserStatus::DISABLED) { // user status shouldn't be disabled return $curuser; + } } return false; @@ -82,16 +86,24 @@ protected function loadCurUser($grant = 'cookies') protected function loadCurUserIdFromCookies() { $user_session = app()->request->cookie(Constant::cookie_name); - if (is_null($user_session)) return false; // quick return when cookies is not exist + if (is_null($user_session)) { + return false; + } // quick return when cookies is not exist $payload = JWTHelper::decode($user_session); - if ($payload === false) return false; - if (!isset($payload['jti']) || !isset($payload['aud'])) return false; + if ($payload === false) { + return false; + } + if (!isset($payload['jti']) || !isset($payload['aud'])) { + return false; + } // Check if user lock access ip ? if (isset($payload['ip'])) { $now_ip_crc = sprintf('%08x', crc32(app()->request->getClientIp())); - if (strcasecmp($payload['ip'], $now_ip_crc) !== 0) return false; + if (strcasecmp($payload['ip'], $now_ip_crc) !== 0) { + return false; + } } // Verity $jti is force expired or not by checking mapUserSessionToId @@ -101,14 +113,19 @@ protected function loadCurUserIdFromCookies() 'sid' => $payload['jti'] ])->queryScalar(); app()->redis->zAdd(Constant::mapUserSessionToId, $uid ?: 0, $payload['jti']); // Store 0 if session -> uid is invalid - if ($uid === false) return false; // this session is not exist or marked as expired - } elseif ($expired_check != $payload['aud']) return false; // may return (double) 0 , which means already make invalid ; or it check if user obtain this session (may Overdesign) + if ($uid === false) { + return false; + } // this session is not exist or marked as expired + } elseif ($expired_check != $payload['aud']) { + return false; + } // may return (double) 0 , which means already make invalid ; or it check if user obtain this session (may Overdesign) $this->cur_user_jit = $payload['jti']; // Check if user want secure access but his environment is not secure if (!app()->request->isSecure() && // if User requests is not secure , and - (config('security.ssl_login') > 1 || // if Our site FORCE enabled ssl feature + ( + config('security.ssl_login') > 1 || // if Our site FORCE enabled ssl feature (config('security.ssl_login') > 0 && isset($payload['ssl']) && $payload['ssl']) // if Our site support ssl feature and User want secure access ) ) { @@ -122,7 +139,9 @@ protected function loadCurUserIdFromCookies() protected function loadCurUserIdFromPasskey() { $passkey = app()->request->get('passkey'); - if (is_null($passkey)) return false; + if (is_null($passkey)) { + return false; + } // FIXME merge same function as tracker so $user_id = app()->redis->zScore(Constant::mapUserPasskeyToId, $passkey); diff --git a/application/Components/Site.php b/application/Components/Site.php index 9fea385..e23c006 100644 --- a/application/Components/Site.php +++ b/application/Components/Site.php @@ -106,7 +106,9 @@ public function sendPM($sender, $receiver, $subject, $msg, $save = 'no', $locati ])->execute(); app()->redis->hDel(Constant::userContent($receiver), 'unread_message_count', 'inbox_count'); - if ($sender != 0) app()->redis->hDel(Constant::userContent($sender), 'outbox_count'); + if ($sender != 0) { + app()->redis->hDel(Constant::userContent($sender), 'outbox_count'); + } } public function sendEmail($receivers, $subject, $template, $data = []) @@ -143,7 +145,9 @@ public function ruleCategory(): array $cats = []; $cats_raw = app()->pdo->createCommand('SELECT * FROM `categories` WHERE `id` > 0 ORDER BY `full_path`')->queryAll(); - foreach ($cats_raw as $cat_raw) $cats[$cat_raw['id']] = $cat_raw; + foreach ($cats_raw as $cat_raw) { + $cats[$cat_raw['id']] = $cat_raw; + } app()->config->set('runtime.enabled_torrent_category', $cats, 'json'); } @@ -164,13 +168,17 @@ public function ruleCanUsedCategory(): array public function ruleQuality($quality): array { - if (!in_array($quality, array_keys($this->getQualityTableList()))) throw new \RuntimeException('Unregister quality : ' . $quality); + if (!in_array($quality, array_keys($this->getQualityTableList()))) { + throw new \RuntimeException('Unregister quality : ' . $quality); + } if (false === $data = config('runtime.enabled_quality_' . $quality)) { $data = []; /** @noinspection SqlResolve */ $data_raws = app()->pdo->createCommand("SELECT * FROM `quality_$quality` WHERE `id` > 0 AND `enabled` = 1 ORDER BY `sort_index`,`id`")->queryAll(); - foreach ($data_raws as $data_raw) $data[$data_raw['id']] = $data_raw; + foreach ($data_raws as $data_raw) { + $data[$data_raw['id']] = $data_raw; + } app()->config->set('runtime.enabled_quality_' . $quality, $data, 'json'); } return $data ?: []; @@ -181,7 +189,9 @@ public function ruleTeam(): array if (false === $data = config('runtime.enabled_teams')) { $data = []; $data_raws = app()->pdo->createCommand('SELECT * FROM `teams` WHERE `id` > 0 AND `enabled` = 1 ORDER BY `sort_index`,`id`')->queryAll(); - foreach ($data_raws as $data_raw) $data[$data_raw['id']] = $data_raw; + foreach ($data_raws as $data_raw) { + $data[$data_raw['id']] = $data_raw; + } app()->config->set('runtime.enabled_teams', $data, 'json'); } @@ -219,7 +229,9 @@ public function banIp($ip, $persistence = false, $commit = null) $banips = $this->getBanIpsList(); // Add ip if not exist - if (in_array($ip, $banips)) return; + if (in_array($ip, $banips)) { + return; + } // Rewrite config $banips[] = $ip; diff --git a/application/Controllers/AdminController.php b/application/Controllers/AdminController.php index e49cb1b..eae56c0 100644 --- a/application/Controllers/AdminController.php +++ b/application/Controllers/AdminController.php @@ -8,7 +8,6 @@ namespace App\Controllers; - use Rid\Http\Controller; class AdminController extends Controller diff --git a/application/Controllers/Api/v1/ApiController.php b/application/Controllers/Api/v1/ApiController.php index a8c4863..fd403f3 100644 --- a/application/Controllers/Api/v1/ApiController.php +++ b/application/Controllers/Api/v1/ApiController.php @@ -8,7 +8,6 @@ namespace App\Controllers\Api\v1; - use Rid\Http\Controller; class ApiController extends Controller @@ -17,19 +16,25 @@ class ApiController extends Controller * @param array|string $methods * @return bool */ - protected function checkMethod($methods) { - if (is_string($methods)) $methods = [$methods]; + protected function checkMethod($methods) + { + if (is_string($methods)) { + $methods = [$methods]; + } foreach ($methods as $method) { - if (strtolower(app()->request->method()) == strtolower($method)) + if (strtolower(app()->request->method()) == strtolower($method)) { return true; + } } return false; } protected function buildMethodFailMsg($want_methods) { - if (is_array($want_methods)) $want_methods = implode(',', $want_methods); + if (is_array($want_methods)) { + $want_methods = implode(',', $want_methods); + } app()->response->setStatusCode(405); $method = app()->request->method(); diff --git a/application/Controllers/Api/v1/TorrentController.php b/application/Controllers/Api/v1/TorrentController.php index d65ee23..f0abe5c 100644 --- a/application/Controllers/Api/v1/TorrentController.php +++ b/application/Controllers/Api/v1/TorrentController.php @@ -12,7 +12,8 @@ class TorrentController extends ApiController { - public function actionBookmark() { + public function actionBookmark() + { if ($this->checkMethod('POST')) { $bookmark = new TorrentsForm(); $bookmark->setInput(app()->request->post()); @@ -34,7 +35,8 @@ public function actionBookmark() { } } - public function actionFileList() { + public function actionFileList() + { if ($this->checkMethod('GET')) { $filelist = new TorrentsForm(); $filelist->setInput(app()->request->get()); @@ -51,7 +53,6 @@ public function actionFileList() { $ret ); } - } else { return $this->buildMethodFailMsg('GET'); } diff --git a/application/Controllers/AuthController.php b/application/Controllers/AuthController.php index bc01caa..4f90291 100644 --- a/application/Controllers/AuthController.php +++ b/application/Controllers/AuthController.php @@ -13,7 +13,6 @@ use Rid\Http\Controller; - class AuthController extends Controller { diff --git a/application/Controllers/MaintenanceController.php b/application/Controllers/MaintenanceController.php index 697a5fe..c7184bb 100644 --- a/application/Controllers/MaintenanceController.php +++ b/application/Controllers/MaintenanceController.php @@ -12,10 +12,12 @@ class MaintenanceController extends Controller { - public function actionIndex() { + public function actionIndex() + { // Check if site is on maintenance status - if (!config('base.maintenance')) + if (!config('base.maintenance')) { return app()->response->redirect('/index'); + } return $this->render('maintenance'); } diff --git a/application/Controllers/NewsController.php b/application/Controllers/NewsController.php index 43bf4df..58c4259 100644 --- a/application/Controllers/NewsController.php +++ b/application/Controllers/NewsController.php @@ -8,13 +8,13 @@ namespace App\Controllers; - use App\Models\Form\News; use Rid\Http\Controller; class NewsController extends Controller { - public function actionIndex() { + public function actionIndex() + { $pager = new News\SearchForm(); $pager->setInput(app()->request->get()); @@ -26,7 +26,8 @@ public function actionIndex() { } } - public function actionNew() { + public function actionNew() + { if (app()->request->isPost()) { $newform = new News\EditForm(); $newform->setInput(app()->request->post()); @@ -66,16 +67,16 @@ public function actionEdit() return $this->render('action/fail', ['title' => 'Action Failed', 'msg' => 'action not allowed']); } - public function actionDelete() { + public function actionDelete() + { if (app()->auth->getCurUser()->isPrivilege('manage_news')) { - $id = app()->request->get('id',0); - if (filter_var($id,FILTER_VALIDATE_INT) && $id > 0) { + $id = app()->request->get('id', 0); + if (filter_var($id, FILTER_VALIDATE_INT) && $id > 0) { // TODO add other check app()->pdo->createCommand('DELETE FROM news WHERE id= :id')->bindParams(['id'=>$id])->execute(); } return app()->response->redirect('/news'); } return $this->render('action/fail', ['title' => 'Action Failed', 'msg' => 'action not allowed']); - } } diff --git a/application/Controllers/SiteController.php b/application/Controllers/SiteController.php index b8c57f8..b3bfe53 100644 --- a/application/Controllers/SiteController.php +++ b/application/Controllers/SiteController.php @@ -8,7 +8,6 @@ namespace App\Controllers; - use App\Models\Form\Site; use Rid\Http\Controller; @@ -23,8 +22,8 @@ public function actionLogs() { $logs = new Site\Logs(); if (!$logs->validate()) { - return $this->render('action/fail',['msg'=>$logs->getError()]); + return $this->render('action/fail', ['msg'=>$logs->getError()]); } - return $this->render('site/logs',['logs'=>$logs]); + return $this->render('site/logs', ['logs'=>$logs]); } } diff --git a/application/Controllers/SubtitlesController.php b/application/Controllers/SubtitlesController.php index 50f6a0c..2130c36 100644 --- a/application/Controllers/SubtitlesController.php +++ b/application/Controllers/SubtitlesController.php @@ -60,7 +60,7 @@ public function actionDelete() return $this->render('action/fail', ['msg' => $delete->getError()]); // TODO add redirect } else { $delete->flush(); - return $this->render('action/success',['redirect' => '/subtitles']); // TODO add redirect + return $this->render('action/success', ['redirect' => '/subtitles']); // TODO add redirect } } } diff --git a/application/Controllers/TorrentsController.php b/application/Controllers/TorrentsController.php index 7e072bc..0541369 100644 --- a/application/Controllers/TorrentsController.php +++ b/application/Controllers/TorrentsController.php @@ -14,7 +14,6 @@ class TorrentsController extends Controller { - public function actionIndex() { return $this->actionSearch(); @@ -47,6 +46,5 @@ public function actionTags() } return $this->render('torrents/tags', ['pager' => $pager]); } - } } diff --git a/application/Controllers/TrackerController.php b/application/Controllers/TrackerController.php index ec2f2dc..45aa600 100644 --- a/application/Controllers/TrackerController.php +++ b/application/Controllers/TrackerController.php @@ -57,11 +57,13 @@ public function actionIndex() try { // Block NON-GET requests (Though non-GET request will not match this Route ) - if (!app()->request->isGet()) + if (!app()->request->isGet()) { throw new TrackerException(110, [':method' => app()->request->method()]); + } - if (!config('base.enable_tracker_system')) + if (!config('base.enable_tracker_system')) { throw new TrackerException(100); + } $this->blockClient(); @@ -74,7 +76,9 @@ public function actionIndex() // Tracker Protocol Extension: Scrape - http://www.bittorrent.org/beps/bep_0048.html case 'scrape': { - if (!config('tracker.enable_scrape')) throw new TrackerException(101); + if (!config('tracker.enable_scrape')) { + throw new TrackerException(101); + } $this->checkScrapeFields($info_hash_array); $this->generateScrapeResponse($info_hash_array, $rep_dict); @@ -84,7 +88,9 @@ public function actionIndex() case 'announce': { - if (!config('tracker.enable_announce')) throw new TrackerException(102); + if (!config('tracker.enable_announce')) { + throw new TrackerException(102); + } $this->checkAnnounceFields($queries); @@ -120,8 +126,9 @@ public function actionIndex() * */ $role = ($queries['left'] == 0) ? 'yes' : 'no'; - if ($queries['event'] == 'paused') + if ($queries['event'] == 'paused') { $role = 'partial'; + } /** Check if user can open this session */ $this->checkSession($queries, $role, $userInfo, $torrentInfo); @@ -177,8 +184,9 @@ protected function logException(\Exception $exception, $userInfo = null, $torren private function blockClient() { // Miss Header User-Agent is not allowed. - if (!app()->request->header('user-agent')) + if (!app()->request->header('user-agent')) { throw new TrackerException(120); + } // Block Other Browser, Crawler (, May Cheater or Faker Client) by check Requests headers if (app()->request->header('accept-language') || app()->request->header('referer') @@ -207,14 +215,16 @@ private function blockClient() * */ //|| app()->request->header('cookie') - ) + ) { throw new TrackerException(122); + } $ua = app()->request->header('user-agent'); // Should also Block those too long User-Agent. ( For Database reason - if (strlen($ua) > 64) + if (strlen($ua) > 64) { throw new TrackerException(123); + } // Block Browser by check it's User-Agent if (preg_match('/(Mozilla|Browser|Chrome|Safari|AppleWebKit|Opera|Links|Lynx|Bot|Unknown)/i', $ua)) { @@ -234,12 +244,14 @@ private function checkUserAgent(bool $onlyCheckUA = false) $client_identity = $userAgent . ($onlyCheckUA ? '' : ':' . $peer_id); // if this user-agent and peer_id already checked valid or not ? - if (app()->redis->zScore(Constant::trackerValidClientZset, $client_identity) > 0) return; + if (app()->redis->zScore(Constant::trackerValidClientZset, $client_identity) > 0) { + return; + } // Get Client White List From Database and cache it if (false === $allowedFamily = app()->redis->get(Constant::trackerAllowedClientList)) { $allowedFamily = app()->pdo->createCommand("SELECT * FROM `agent_allowed_family` WHERE `enabled` = 'yes' ORDER BY `hits` DESC")->queryAll(); - app()->redis->set(Constant::trackerAllowedClientList, $allowedFamily,86400); + app()->redis->set(Constant::trackerAllowedClientList, $allowedFamily, 86400); } $agentAccepted = null; @@ -256,8 +268,9 @@ private function checkUserAgent(bool $onlyCheckUA = false) // Check User-Agent if ($allowedItem['agent_pattern'] != '') { - if (!preg_match($allowedItem['agent_pattern'], $allowedItem['agent_start'], $agentShould)) + if (!preg_match($allowedItem['agent_pattern'], $allowedItem['agent_start'], $agentShould)) { throw new TrackerException(124, [':pattern' => "User-Agent", ':start' => $allowedItem['start_name']]); + } if (preg_match($allowedItem['agent_pattern'], $userAgent, $agentMatched)) { if ($allowedItem['agent_match_num'] > 0) { @@ -273,8 +286,9 @@ private function checkUserAgent(bool $onlyCheckUA = false) break; } // Below requirement - if ($agentMatched[$i + 1] < $agentShould[$i + 1]) + if ($agentMatched[$i + 1] < $agentShould[$i + 1]) { throw new TrackerException(125, [":start" => $allowedItem['start_name']]); + } // Continue to loop. Unless the last bit is equal. if ($agentMatched[$i + 1] == $agentShould[$i + 1] && $i + 1 == $allowedItem['agent_match_num']) { $agentAccepted = true; @@ -289,13 +303,18 @@ private function checkUserAgent(bool $onlyCheckUA = false) } if ($onlyCheckUA) { - if ($agentAccepted) break; else continue; + if ($agentAccepted) { + break; + } else { + continue; + } } // Check Peer_id if ($allowedItem['peer_id_pattern'] != '') { - if (!preg_match($allowedItem['peer_id_pattern'], $allowedItem['peer_id_start'], $peerIdShould)) + if (!preg_match($allowedItem['peer_id_pattern'], $allowedItem['peer_id_start'], $peerIdShould)) { throw new TrackerException(124, [':pattern' => 'peer_id', ':start' => $allowedItem['start_name']]); + } if (preg_match($allowedItem['peer_id_pattern'], $peer_id, $peerIdMatched)) { if ($allowedItem['peer_id_match_num'] > 0) { @@ -311,8 +330,9 @@ private function checkUserAgent(bool $onlyCheckUA = false) break; } // Below requirement - if ($peerIdMatched[$i + 1] < $peerIdShould[$i + 1]) + if ($peerIdMatched[$i + 1] < $peerIdShould[$i + 1]) { throw new TrackerException(114, [':start' => $allowedItem['start_name']]); + } // Continue to loop. Unless the last bit is equal. if ($peerIdMatched[$i + 1] == $peerIdShould[$i + 1] && $i + 1 == $allowedItem['agent_match_num']) { $peerIdAccepted = true; @@ -335,7 +355,9 @@ private function checkUserAgent(bool $onlyCheckUA = false) } if ($onlyCheckUA) { - if (!$agentAccepted) throw new TrackerException(126, [':ua' => $userAgent]); + if (!$agentAccepted) { + throw new TrackerException(126, [':ua' => $userAgent]); + } app()->redis->zAdd(Constant::trackerValidClientZset, time() + rand(7200, 18000), $client_identity); return; } @@ -353,8 +375,9 @@ private function checkUserAgent(bool $onlyCheckUA = false) if ($exceptionItem['family_id'] == $acceptedAgentFamilyId && preg_match($exceptionItem['peer_id'], $peer_id) && ($userAgent == $exceptionItem['agent'] || !$exceptionItem['agent']) - ) + ) { throw new TrackerException(127, [':ua' => $userAgent, ':comment' => $exceptionItem['comment']]); + } } app()->redis->zAdd(Constant::trackerValidClientZset, time() + rand(7200, 18000), $client_identity); // app()->redis->rawCommand('bf.add', [Constant::trackerValidClientZset, $client_identity]); @@ -373,12 +396,15 @@ private function checkPasskey(&$userInfo) $passkey = app()->request->get('passkey'); // First Check The param `passkey` is exist and valid - if (is_null($passkey)) + if (is_null($passkey)) { throw new TrackerException(130, [':attribute' => 'passkey']); - if (strlen($passkey) != 32) + } + if (strlen($passkey) != 32) { throw new TrackerException(132, [':attribute' => 'passkey', ':rule' => 32]); - if (strspn(strtolower($passkey), 'abcdef0123456789') != 32) // MD5 char limit + } + if (strspn(strtolower($passkey), 'abcdef0123456789') != 32) { // MD5 char limit throw new TrackerException(131, [':attribute' => 'passkey', ':reason' => 'The format of passkey isn\'t correct']); + } // Get userInfo from RedisConnection Cache and then Database if (false === $userInfo = app()->redis->get(Constant::userBaseContentByPasskey($passkey))) { @@ -396,9 +422,15 @@ private function checkPasskey(&$userInfo) * - The user's status is not `confirmed` * - The user's download Permission is disabled. */ - if (empty($userInfo)) throw new TrackerException(140); - if ($userInfo['status'] != 'confirmed') throw new TrackerException(141, [':status' => $userInfo['status']]); - if ($userInfo['downloadpos'] == 'no') throw new TrackerException(142); + if (empty($userInfo)) { + throw new TrackerException(140); + } + if ($userInfo['status'] != 'confirmed') { + throw new TrackerException(141, [':status' => $userInfo['status']]); + } + if ($userInfo['downloadpos'] == 'no') { + throw new TrackerException(142); + } } /** @@ -424,7 +456,9 @@ private function getTorrentInfoByHash($hash, bool $scrape = false) } // Return false when this info_hash is invalid (Not exist in our database or this status is 'deleted' - if (empty($torrentInfo)) return false; + if (empty($torrentInfo)) { + return false; + } // Return limit field when in scrape model return $scrape ? array_intersect_key($torrentInfo, array_flip(['incomplete', 'complete', 'downloaded'])) : $torrentInfo; @@ -443,8 +477,9 @@ private function checkScrapeFields(&$info_hash_array) throw new TrackerException(130, [':attribute' => 'info_hash']); } else { foreach ($info_hash_array as $item) { - if (strlen($item) != 20) + if (strlen($item) != 20) { throw new TrackerException(133, [':attribute' => 'info_hash', ':rule' => 20]); + } } } } @@ -454,7 +489,9 @@ private function generateScrapeResponse($info_hash_array, &$rep_dict) $torrent_details = []; foreach ($info_hash_array as $item) { $metadata = $this->getTorrentInfoByHash($item, true); - if ($metadata !== false) $torrent_details[$item] = $metadata; // Append it to tmp array only it exist. + if ($metadata !== false) { + $torrent_details[$item] = $metadata; + } // Append it to tmp array only it exist. } $rep_dict = ['files' => $torrent_details]; @@ -478,14 +515,16 @@ private function checkAnnounceFields(&$queries = []) } foreach (['info_hash', 'peer_id'] as $item) { - if (strlen($queries[$item]) != 20) + if (strlen($queries[$item]) != 20) { throw new TrackerException(133, [':attribute' => $item, ':rule' => 20]); + } } foreach (['uploaded', 'downloaded', 'left'] as $item) { $item_data = $queries[$item]; - if (!is_numeric($item_data) || $item_data < 0) + if (!is_numeric($item_data) || $item_data < 0) { throw new TrackerException(134, [':attribute' => $item]); + } } // Part.2 check Announce **Option** Fields @@ -498,12 +537,14 @@ private function checkAnnounceFields(&$queries = []) } foreach (['numwant', 'corrupt', 'no_peer_id', 'compact'] as $item) { - if (!is_numeric($queries[$item]) || $queries[$item] < 0) + if (!is_numeric($queries[$item]) || $queries[$item] < 0) { throw new TrackerException(134, [":attribute" => $item]); + } } - if (!in_array(strtolower($queries['event']), ['started', 'completed', 'stopped', 'paused', ''])) + if (!in_array(strtolower($queries['event']), ['started', 'completed', 'stopped', 'paused', ''])) { throw new TrackerException(136, [":event" => strtolower($queries['event'])]); + } $queries['user-agent'] = app()->request->header('user-agent'); @@ -554,7 +595,9 @@ private function checkAnnounceFields(&$queries = []) } elseif (IpUtils::isValidIPv6($remote_ip)) { $queries['ipv6'] = $remote_ip; } - if ($queries['ipv6']) $queries['ipv6_port'] = $queries['port']; + if ($queries['ipv6']) { + $queries['ipv6_port'] = $queries['port']; + } } // Clean $queries['ip'] field and then store ipv4 data in it to make sure this field is IPv4-Only @@ -581,10 +624,12 @@ private function checkAnnounceFields(&$queries = []) // Part.4 check Port Fields is Valid and Allowed $this->checkPortFields($queries['port']); - if (isset($queries['ipv6_port']) && $queries['port'] != $queries['ipv6_port']) + if (isset($queries['ipv6_port']) && $queries['port'] != $queries['ipv6_port']) { $this->checkPortFields($queries['ipv6_port']); - if ($queries['port'] == 0 && strtolower($queries['event']) != 'stopped') + } + if ($queries['port'] == 0 && strtolower($queries['event']) != 'stopped') { throw new TrackerException(137, [":event" => strtolower($queries['event'])]); + } } /** Check Port @@ -596,8 +641,9 @@ private function checkAnnounceFields(&$queries = []) */ private function checkPortFields($port) { - if (!is_numeric($port) || $port < 0 || $port > 0xffff || in_array($port, self::portBlacklist)) + if (!is_numeric($port) || $port < 0 || $port > 0xffff || in_array($port, self::portBlacklist)) { throw new TrackerException(135, [':port' => $port]); + } } /** @@ -609,24 +655,28 @@ private function checkPortFields($port) private function getTorrentInfo($queries, $userInfo, &$torrentInfo) { $torrentInfo = $this->getTorrentInfoByHash($queries['info_hash']); - if ($torrentInfo === false) throw new TrackerException(150); + if ($torrentInfo === false) { + throw new TrackerException(150); + } switch ($torrentInfo['status']) { - case 'confirmed' : + case 'confirmed': return; // Do nothing , just break torrent status check when it is a confirmed torrent - case 'pending' : + case 'pending': { // For Pending torrent , we just allow it's owner and other user who's class great than your config set to connect if ($torrentInfo['owner_id'] != $userInfo['id'] - || $userInfo['class'] < config('authority.see_pending_torrent')) + || $userInfo['class'] < config('authority.see_pending_torrent')) { throw new TrackerException(151, [':status' => $torrentInfo['status']]); + } break; } - case 'banned' : + case 'banned': { // For Banned Torrent , we just allow the user who's class great than your config set to connect - if ($userInfo['class'] < config('authority.see_banned_torrent')) + if ($userInfo['class'] < config('authority.see_banned_torrent')) { throw new TrackerException(151, [':status' => $torrentInfo['status']]); + } break; } default: @@ -714,11 +764,13 @@ private function checkSession($queries, $seeder, $userInfo, $torrentInfo) // Ban one torrent seeding/leech at multi-location due to your site config if ($seeder == 'yes') { // if this peer's role is seeder - if ($selfCount >= (config('tracker.user_max_seed'))) + if ($selfCount >= (config('tracker.user_max_seed'))) { throw new TrackerException(160, [':count' => config('tracker.user_max_seed')]); + } } else { - if ($selfCount >= (config('tracker.user_max_leech'))) + if ($selfCount >= (config('tracker.user_max_leech'))) { throw new TrackerException(161, [':count' => config('tracker.user_max_leech')]); + } } if ($userInfo['class'] < UserRole::VIP) { @@ -728,15 +780,22 @@ private function checkSession($queries, $seeder, $userInfo, $torrentInfo) // Wait System if (config('tracker.enable_waitsystem')) { if ($gigs > 10) { - if ($ratio < 0.4) $wait = 24; - elseif ($ratio < 0.5) $wait = 12; - elseif ($ratio < 0.6) $wait = 6; - elseif ($ratio < 0.8) $wait = 3; - else $wait = 0; + if ($ratio < 0.4) { + $wait = 24; + } elseif ($ratio < 0.5) { + $wait = 12; + } elseif ($ratio < 0.6) { + $wait = 6; + } elseif ($ratio < 0.8) { + $wait = 3; + } else { + $wait = 0; + } $elapsed = time() - $torrentInfo['added_at']; - if ($elapsed < $wait) + if ($elapsed < $wait) { throw new TrackerException(163, [':sec' => $wait * 3600 - $elapsed]); + } } } @@ -744,17 +803,23 @@ private function checkSession($queries, $seeder, $userInfo, $torrentInfo) if (config('tracker.enable_maxdlsystem')) { $max = 0; if ($gigs > 10) { - if ($ratio < 0.5) $max = 1; - elseif ($ratio < 0.65) $max = 2; - elseif ($ratio < 0.8) $max = 3; - elseif ($ratio < 0.95) $max = 4; + if ($ratio < 0.5) { + $max = 1; + } elseif ($ratio < 0.65) { + $max = 2; + } elseif ($ratio < 0.8) { + $max = 3; + } elseif ($ratio < 0.95) { + $max = 4; + } } if ($max > 0) { $count = app()->pdo->createCommand("SELECT COUNT(`id`) FROM `peers` WHERE `user_id` = :uid AND `seeder` = 'no';")->bindParams([ 'uid' => $userInfo['id'] ])->queryScalar(); - if ($count >= $max) + if ($count >= $max) { throw new TrackerException(164, [':max' => $max]); + } } } } @@ -762,7 +827,6 @@ private function checkSession($queries, $seeder, $userInfo, $torrentInfo) // All Check Passed app()->redis->zAdd(Constant::trackerValidPeerZset, $this->timenow + config('tracker.interval') * 2, $identity); } - } private function sendToTaskWorker($queries, $role, $userInfo, $torrentInfo) @@ -803,8 +867,9 @@ private function generateAnnounceResponse($queries, $role, $torrentInfo, &$rep_d if ($compact) { $queries['no_peer_id'] = 1; // force `no_peer_id` when `compact` mode is enable $rep_dict['peers'] = ''; // Change `peers` from array to string - if ($queries['ipv6']) // If peer has IPv6 address , we should add packed string in `peers6` + if ($queries['ipv6']) { // If peer has IPv6 address , we should add packed string in `peers6` $rep_dict['peers6'] = ''; + } } $no_peer_id = (bool) ($queries['no_peer_id'] == 1 || config('tracker.force_no_peer_id_model')); @@ -826,7 +891,9 @@ private function generateAnnounceResponse($queries, $role, $torrentInfo, &$rep_d foreach ($peers as $peer) { $exchange_peer = []; - if (!$no_peer_id) $exchange_peer['peer_id'] = $peer['peer_id']; + if (!$no_peer_id) { + $exchange_peer['peer_id'] = $peer['peer_id']; + } if ($queries['ip'] && $peer['ip']) { if ($compact) { diff --git a/application/Controllers/UserController.php b/application/Controllers/UserController.php index 5ea3332..01e6e9a 100644 --- a/application/Controllers/UserController.php +++ b/application/Controllers/UserController.php @@ -14,7 +14,6 @@ class UserController extends Controller { - public function actionIndex() { return $this->actionDetails(); diff --git a/application/Entity/Torrent.php b/application/Entity/Torrent.php index ac52ce5..a6332b1 100644 --- a/application/Entity/Torrent.php +++ b/application/Entity/Torrent.php @@ -176,7 +176,9 @@ public function getTeamId() public function getTeam() { - if ($this->team == 0) return false; + if ($this->team == 0) { + return false; + } return app()->site->ruleTeam()[$this->team]; } @@ -187,7 +189,9 @@ public function getQualityId(string $quality): int public function getQuality(string $quality) { - if ($this->getQualityId($quality) == 0) return false; + if ($this->getQualityId($quality) == 0) { + return false; + } return app()->site->ruleQuality($quality)[$this->getQualityId($quality)]; } @@ -201,7 +205,9 @@ public function getDescr(): string */ public function getTags(): array { - if (is_string($this->tags)) $this->tags = json_decode($this->tags, true); + if (is_string($this->tags)) { + $this->tags = json_decode($this->tags, true); + } return $this->tags ?? []; } @@ -214,7 +220,9 @@ public function getPinnedTags(): array $tags = $this->getTags(); $rule_pinned_tags = app()->site->rulePinnedTags(); foreach ($rule_pinned_tags as $tag_name => $tag_class) { - if (in_array($tag_name, $tags)) $pinned_tags[$tag_name] = $tag_class; + if (in_array($tag_name, $tags)) { + $pinned_tags[$tag_name] = $tag_class; + } } return $pinned_tags; } @@ -241,7 +249,9 @@ public function hasNfo(): bool */ public function getNfo($convert = true, $swedishmagic = false) { - if ($convert) return self::nfoConvert($this->nfo, $swedishmagic); + if ($convert) { + return self::nfoConvert($this->nfo, $swedishmagic); + } return $this->nfo; } @@ -275,7 +285,8 @@ protected static function nfoConvert($ibm_437, $swedishmagic = false) $s = preg_replace( ["/([ -~])\305([ -~])/", "/([ -~])\304([ -~])/", "/([ -~])\326([ -~])/"], ["\\1\217\\2", "\\1\216\\2", "\\1\231\\2"], - $s); // ? + $s + ); // ? } return $s; } @@ -290,5 +301,4 @@ public function getLastCommentsDetails() ])->queryAll(); }); } - } diff --git a/application/Entity/User.php b/application/Entity/User.php index 5095219..a7cc6b7 100644 --- a/application/Entity/User.php +++ b/application/Entity/User.php @@ -63,7 +63,9 @@ public function __construct($id = null) } } - if ($self === false) return false; + if ($self === false) { + return false; + } $this->importAttributes($self); } @@ -273,10 +275,10 @@ public function getTempInvitesSum() public function getTempInviteDetails() { return $this->getCacheValue('temp_invites_details', function () { - return app()->pdo->createCommand('SELECT * FROM `user_invitations` WHERE `user_id` = :uid AND (`total`-`used`) > 0 AND `expire_at` > NOW() ORDER BY `expire_at` ASC')->bindParams([ + return app()->pdo->createCommand('SELECT * FROM `user_invitations` WHERE `user_id` = :uid AND (`total`-`used`) > 0 AND `expire_at` > NOW() ORDER BY `expire_at` ASC')->bindParams([ "uid" => app()->auth->getCurUser()->getId() ])->queryAll() ?: []; - }) ?? []; + }) ?? []; } public function getPendingInvites() diff --git a/application/Libraries/Bencode/Bencode.php b/application/Libraries/Bencode/Bencode.php index 85304a0..40504b8 100644 --- a/application/Libraries/Bencode/Bencode.php +++ b/application/Libraries/Bencode/Bencode.php @@ -11,7 +11,6 @@ namespace App\Libraries\Bencode; - class Bencode { /** diff --git a/application/Libraries/Bencode/ParseErrorException.php b/application/Libraries/Bencode/ParseErrorException.php index 01ee6f0..b46f2d7 100644 --- a/application/Libraries/Bencode/ParseErrorException.php +++ b/application/Libraries/Bencode/ParseErrorException.php @@ -8,7 +8,6 @@ namespace App\Libraries\Bencode; - class ParseErrorException extends \RuntimeException { } diff --git a/application/Libraries/Bonus.php b/application/Libraries/Bonus.php index b516c80..c36c850 100644 --- a/application/Libraries/Bonus.php +++ b/application/Libraries/Bonus.php @@ -8,14 +8,10 @@ namespace App\Libraries; - class Bonus { - - public function __construct() { - } public function calculate($uid): float diff --git a/application/Libraries/Constant.php b/application/Libraries/Constant.php index 40e8571..9b7156b 100644 --- a/application/Libraries/Constant.php +++ b/application/Libraries/Constant.php @@ -8,7 +8,6 @@ namespace App\Libraries; - class Constant { const cookie_name = 'rid'; diff --git a/application/Libraries/GeoIP/GeoIPInterface.php b/application/Libraries/GeoIP/GeoIPInterface.php index f315a86..613bde5 100644 --- a/application/Libraries/GeoIP/GeoIPInterface.php +++ b/application/Libraries/GeoIP/GeoIPInterface.php @@ -8,7 +8,6 @@ namespace App\Libraries\GeoIP; - interface GeoIPInterface { public static function getLocation(); diff --git a/application/Libraries/Mailer.php b/application/Libraries/Mailer.php index d26897c..de255bd 100644 --- a/application/Libraries/Mailer.php +++ b/application/Libraries/Mailer.php @@ -48,7 +48,6 @@ public function onInitialize() $mail->Port = $this->port; // TCP port to connect to $this->_mailer = $mail; - } public function send(array $receivers, string $subject, string $body) diff --git a/application/Middleware/ApiMiddleware.php b/application/Middleware/ApiMiddleware.php index f624a5f..040e443 100644 --- a/application/Middleware/ApiMiddleware.php +++ b/application/Middleware/ApiMiddleware.php @@ -8,7 +8,6 @@ namespace App\Middleware; - class ApiMiddleware { public function handle($callable, \Closure $next) @@ -22,7 +21,7 @@ public function handle($callable, \Closure $next) app()->response->setHeader('Pragma', 'no-cache'); if (env('APP_DEBUG')) { - app()->response->setHeader('access-control-allow-origin','*'); + app()->response->setHeader('access-control-allow-origin', '*'); } return $next(); diff --git a/application/Middleware/AuthMiddleware.php b/application/Middleware/AuthMiddleware.php index 1168686..14d0c48 100644 --- a/application/Middleware/AuthMiddleware.php +++ b/application/Middleware/AuthMiddleware.php @@ -39,19 +39,24 @@ public function handle($callable, \Closure $next) } // Check if Site in Maintenance status, and only let `bypass_maintenance` user access - if (config('base.maintenance') && ($curuser === false || !$curuser->isPrivilege('bypass_maintenance'))) + if (config('base.maintenance') && ($curuser === false || !$curuser->isPrivilege('bypass_maintenance'))) { return app()->response->redirect('/maintenance'); + } // Deal with Anonymous Visitor if ($curuser === false) { // Check if Site in Abnormal status - if (config('base.prevent_anonymous')) return app()->response->setStatusCode(403); + if (config('base.prevent_anonymous')) { + return app()->response->setStatusCode(403); + } if (app()->auth->getGrant() == 'passkey') { return 'invalid Passkey'; } else { // app()->auth->getGrant() == 'cookies' // If visitor want to auth himself - if ($controllerName === Controllers\AuthController::class && $action !== 'actionLogout') return $next(); + if ($controllerName === Controllers\AuthController::class && $action !== 'actionLogout') { + return $next(); + } // Prevent Other Route app()->cookie->delete(Constant::cookie_name); // Delete exist cookies @@ -78,10 +83,12 @@ public function handle($callable, \Closure $next) * /admin -> AdminController::actionIndex -> route.admin_index * /admin/service -> AdminController::actionService -> route.admin_service */ - $route = strtolower(str_replace( - ['App\\Controllers\\', 'Controller', 'action'], '', - $controllerName . '_' . $action - ) + $route = strtolower( + str_replace( + ['App\\Controllers\\', 'Controller', 'action'], + '', + $controllerName . '_' . $action + ) ); $required_class = config('route.' . $route) ?: 1; diff --git a/application/Middleware/IpBanMiddleware.php b/application/Middleware/IpBanMiddleware.php index 385ea59..9c2d802 100644 --- a/application/Middleware/IpBanMiddleware.php +++ b/application/Middleware/IpBanMiddleware.php @@ -24,5 +24,4 @@ public function handle($callable, \Closure $next) return $next(); } - } diff --git a/application/Models/Api/v1/Form/TorrentsForm.php b/application/Models/Api/v1/Form/TorrentsForm.php index 667bb00..9095246 100644 --- a/application/Models/Api/v1/Form/TorrentsForm.php +++ b/application/Models/Api/v1/Form/TorrentsForm.php @@ -16,7 +16,8 @@ class TorrentsForm extends Validator { use isValidTorrentTrait; - public function updateRecord() { + public function updateRecord() + { $bookmark_exist = app()->pdo->createCommand('SELECT `id` FROM `bookmarks` WHERE `uid` = :uid AND `tid` = :tid ')->bindParams([ 'uid' => app()->auth->getCurUser()->getId(), 'tid' => $this->getInput('id') diff --git a/application/Models/Form/Auth/UserConfirmForm.php b/application/Models/Form/Auth/UserConfirmForm.php index 8778710..3cbd4d8 100644 --- a/application/Models/Form/Auth/UserConfirmForm.php +++ b/application/Models/Form/Auth/UserConfirmForm.php @@ -13,10 +13,8 @@ use Rid\Helpers\StringHelper; use Rid\Validators\Validator; - class UserConfirmForm extends Validator { - public $action; const ACTION_REGISTER = 'register'; @@ -54,7 +52,8 @@ protected function validConfirmSecret() $record = app()->pdo->createCommand( 'SELECT `user_confirm`.`id`,`user_confirm`.`uid`,`users`.`status`,`users`.`username`,`users`.`email` FROM `user_confirm` LEFT JOIN `users` ON `users`.`id` = `user_confirm`.`uid` - WHERE `secret` = :secret AND `action` = :action AND used = 0 LIMIT 1;')->bindParams([ + WHERE `secret` = :secret AND `action` = :action AND used = 0 LIMIT 1;' + )->bindParams([ 'secret' => $this->getInput('secret'), 'action' => $this->getInput('action') ])->queryOne(); @@ -105,11 +104,15 @@ private function flush_recover() $this->update_confirm_status(); // Send user email to tell his new password. - app()->site->sendEmail([$this->email], 'New Password', - 'email/user_new_password', [ + app()->site->sendEmail( + [$this->email], + 'New Password', + 'email/user_new_password', + [ 'username' => $this->username, 'password' => $new_password, - ]); + ] + ); return true; } @@ -123,7 +126,8 @@ public function flush() } } - public function getConfirmMsg() { + public function getConfirmMsg() + { if ($this->action == self::ACTION_REGISTER) { return 'Your account is success Confirmed.'; // FIXME i18n } elseif ($this->action == self::ACTION_RECOVER) { diff --git a/application/Models/Form/Auth/UserLoginForm.php b/application/Models/Form/Auth/UserLoginForm.php index 2768835..750a042 100644 --- a/application/Models/Form/Auth/UserLoginForm.php +++ b/application/Models/Form/Auth/UserLoginForm.php @@ -16,7 +16,6 @@ use Rid\Validators\CaptchaTrait; use Rid\Validators\Validator; - class UserLoginForm extends Validator { use CaptchaTrait; @@ -170,8 +169,9 @@ private function createUserSession() $payload['ip'] = sprintf('%08x', crc32($login_ip)); // Store User Login IP ( in CRC32 format ) } - if ($this->ssl || config('security.ssl_login') > 1) - $payload['ssl'] = true; // Store User want full ssl protect + if ($this->ssl || config('security.ssl_login') > 1) { + $payload['ssl'] = true; + } // Store User want full ssl protect // Generate JWT content $this->jwt_payload = $payload; diff --git a/application/Models/Form/Auth/UserLogoutForm.php b/application/Models/Form/Auth/UserLogoutForm.php index b729a64..ef20cc8 100644 --- a/application/Models/Form/Auth/UserLogoutForm.php +++ b/application/Models/Form/Auth/UserLogoutForm.php @@ -8,7 +8,6 @@ namespace App\Models\Form\Auth; - use App\Libraries\Constant; use Rid\Helpers\JWTHelper; use Rid\Validators\CsrfTrait; @@ -43,16 +42,17 @@ public static function callbackRules(): array } /** @noinspection PhpUnused */ - protected function getUserSessionId() { + protected function getUserSessionId() + { $session = app()->request->cookie(Constant::cookie_name); if (is_null($session)) { - $this->buildCallbackFailMsg('session','How can you hit here without cookies?'); + $this->buildCallbackFailMsg('session', 'How can you hit here without cookies?'); return; } $payload = JWTHelper::decode($session); if ($payload === false || !isset($payload['jti'])) { - $this->buildCallbackFailMsg('jwt','Fail to get $jti information'); + $this->buildCallbackFailMsg('jwt', 'Fail to get $jti information'); return; } @@ -67,7 +67,7 @@ public function flush() private function invalidSession() { app()->cookie->delete(Constant::cookie_name); // Clean cookie - app()->redis->zAdd(Constant::mapUserSessionToId, 0, $this->sid); // Quick Mark this invalid in cache + app()->redis->zAdd(Constant::mapUserSessionToId, 0, $this->sid); // Quick Mark this invalid in cache // Set this session expired app()->pdo->createCommand('UPDATE sessions SET `expired` = 1 WHERE session = :sid')->bindParams([ diff --git a/application/Models/Form/Auth/UserRecoverForm.php b/application/Models/Form/Auth/UserRecoverForm.php index 8bef988..6c62a1d 100644 --- a/application/Models/Form/Auth/UserRecoverForm.php +++ b/application/Models/Form/Auth/UserRecoverForm.php @@ -43,7 +43,8 @@ public static function callbackRules(): array * @return bool|string bool(true) means flush success , * any other value (string) performs like error msg */ - public function flush() { + public function flush() + { // Check this email is in our database or not? $user_info = app()->pdo->createCommand('SELECT `id`,`username`,`status` FROM `users` WHERE `email` = :email;')->bindParams([ 'email' => $this->email @@ -63,14 +64,16 @@ public function flush() { 'action' => $this->_action ]); - app()->site->sendEmail([$this->email], 'Please confirm your action to recover your password', - 'email/user_recover', [ + app()->site->sendEmail( + [$this->email], + 'Please confirm your action to recover your password', + 'email/user_recover', + [ 'username' => $user_info['username'], 'confirm_url' => $confirm_url, - ]); + ] + ); } return true; } - - } diff --git a/application/Models/Form/Auth/UserRegisterForm.php b/application/Models/Form/Auth/UserRegisterForm.php index d36aaa9..29731c1 100644 --- a/application/Models/Form/Auth/UserRegisterForm.php +++ b/application/Models/Form/Auth/UserRegisterForm.php @@ -125,12 +125,12 @@ public function getConfirmWay(): string protected function isRegisterSystemOpen() { if (config('base.enable_register_system') != true) { - $this->buildCallbackFailMsg('RegisterSystemOpen','The register isn\'t open in this site.'); + $this->buildCallbackFailMsg('RegisterSystemOpen', 'The register isn\'t open in this site.'); return; } if (config('register.by_' . $this->getInput('type')) != true) { - $this->buildCallbackFailMsg('RegisterSystemOpen',"The register by {$this->getInput('type')} ways isn't open in this site."); + $this->buildCallbackFailMsg('RegisterSystemOpen', "The register by {$this->getInput('type')} ways isn't open in this site."); return; } } @@ -138,8 +138,9 @@ protected function isRegisterSystemOpen() protected function isMaxUserReached() { if (config('register.check_max_user') && - app()->site::fetchUserCount() >= config('base.max_user')) - $this->buildCallbackFailMsg('MaxUserReached','Max user limit Reached'); + app()->site::fetchUserCount() >= config('base.max_user')) { + $this->buildCallbackFailMsg('MaxUserReached', 'Max user limit Reached'); + } } protected function isMaxRegisterIpReached() @@ -153,7 +154,7 @@ protected function isMaxRegisterIpReached() ])->queryScalar(); if ($user_ip_count > $max_user_per_ip) { - $this->buildCallbackFailMsg('MaxRegisterIpReached',"The register member count in this ip `$client_ip` is reached"); + $this->buildCallbackFailMsg('MaxRegisterIpReached', "The register member count in this ip `$client_ip` is reached"); } } } @@ -318,14 +319,18 @@ public function flush() 'action' => $this->_action ]); - app()->site->sendEmail([$this->email], 'Please confirm your accent', - 'email/user_register', [ + app()->site->sendEmail( + [$this->email], + 'Please confirm your accent', + 'email/user_register', + [ 'username' => $this->username, 'confirm_url' => $confirm_url, - ]); + ] + ); } // Add Site log for user signup - app()->site->writeLog($log_text, app()->site::LOG_LEVEL_MOD); + app()->site->writeLog($log_text, app()->site::LOG_LEVEL_MOD); } } diff --git a/application/Models/Form/Links/ApplyForm.php b/application/Models/Form/Links/ApplyForm.php index c3e608b..247f749 100644 --- a/application/Models/Form/Links/ApplyForm.php +++ b/application/Models/Form/Links/ApplyForm.php @@ -8,7 +8,6 @@ namespace App\Models\Form\Links; - use Rid\Validators\CaptchaTrait; use Rid\Validators\Validator; diff --git a/application/Models/Form/Links/EditForm.php b/application/Models/Form/Links/EditForm.php index c7be18c..11c319b 100644 --- a/application/Models/Form/Links/EditForm.php +++ b/application/Models/Form/Links/EditForm.php @@ -8,7 +8,6 @@ namespace App\Models\Form\Links; - class EditForm extends ApplyForm { public $link_id; @@ -82,7 +81,7 @@ public function flush() app()->auth->getCurUser()->getUsername() . '(' . app()->auth->getCurUser()->getId() . ').', app()->site::LOG_LEVEL_MOD); } else { // to new a links app()->pdo->insert('links', $this->link_new_data)->execute(); - app()->site->writeLog('The links data of ' . $this->link_new_data['name'] . '( ' . $this->link_new_data['url'] . ' ) is update by ' . + app()->site->writeLog('The links data of ' . $this->link_new_data['name'] . '( ' . $this->link_new_data['url'] . ' ) is update by ' . app()->auth->getCurUser()->getUsername() . '(' . app()->auth->getCurUser()->getId() . ').', app()->site::LOG_LEVEL_MOD); } app()->redis->del('Site:links'); diff --git a/application/Models/Form/Links/RemoveForm.php b/application/Models/Form/Links/RemoveForm.php index 1569124..c8ad174 100644 --- a/application/Models/Form/Links/RemoveForm.php +++ b/application/Models/Form/Links/RemoveForm.php @@ -8,7 +8,6 @@ namespace App\Models\Form\Links; - use Rid\Validators\Validator; class RemoveForm extends Validator diff --git a/application/Models/Form/Manage/Categories/EditForm.php b/application/Models/Form/Manage/Categories/EditForm.php index fda6f44..0731a87 100644 --- a/application/Models/Form/Manage/Categories/EditForm.php +++ b/application/Models/Form/Manage/Categories/EditForm.php @@ -8,7 +8,6 @@ namespace App\Models\Form\Manage\Categories; - use Rid\Validators\Validator; class EditForm extends Validator @@ -91,7 +90,9 @@ protected function checkCategoryData() $this->buildCallbackFailMsg('Category:update', 'No data update'); return; } - if (!isset($this->cat_data_diff['full_path'])) $flag_check_full_path = false; // It means full path key not update, We shouldn't check anymore. + if (!isset($this->cat_data_diff['full_path'])) { + $flag_check_full_path = false; + } // It means full path key not update, We shouldn't check anymore. } if ($flag_check_full_path) { // Check if full path key is duplicate or not. diff --git a/application/Models/Form/Manage/Categories/RemoveForm.php b/application/Models/Form/Manage/Categories/RemoveForm.php index 3fee366..fdb6fb6 100644 --- a/application/Models/Form/Manage/Categories/RemoveForm.php +++ b/application/Models/Form/Manage/Categories/RemoveForm.php @@ -8,7 +8,6 @@ namespace App\Models\Form\Manage\Categories; - use Rid\Validators\Validator; class RemoveForm extends Validator diff --git a/application/Models/Form/News/EditForm.php b/application/Models/Form/News/EditForm.php index bb08bc2..b7609e7 100644 --- a/application/Models/Form/News/EditForm.php +++ b/application/Models/Form/News/EditForm.php @@ -57,6 +57,4 @@ public function flush() // Clean News Cache app()->redis->del('Site:recent_news'); } - - } diff --git a/application/Models/Form/News/SearchForm.php b/application/Models/Form/News/SearchForm.php index e4317b7..269cfb1 100644 --- a/application/Models/Form/News/SearchForm.php +++ b/application/Models/Form/News/SearchForm.php @@ -8,12 +8,10 @@ namespace App\Models\Form\News; - use Rid\Validators\Pagination; class SearchForm extends Pagination { - public $query; public $search; diff --git a/application/Models/Form/Rss/FeedForm.php b/application/Models/Form/Rss/FeedForm.php index 3dd92bd..e7b0ba7 100644 --- a/application/Models/Form/Rss/FeedForm.php +++ b/application/Models/Form/Rss/FeedForm.php @@ -12,5 +12,4 @@ class FeedForm extends SearchForm { - } diff --git a/application/Models/Form/Site/Logs.php b/application/Models/Form/Site/Logs.php index e8e499c..b193139 100644 --- a/application/Models/Form/Site/Logs.php +++ b/application/Models/Form/Site/Logs.php @@ -8,12 +8,10 @@ namespace App\Models\Form\Site; - use Rid\Validators\Pagination; class Logs extends Pagination { - protected $_levels; public static $MAX_LIMIT = 100; @@ -33,8 +31,12 @@ public static function defaultData(): array public static function inputRules(): array { $level_list = ['all', 'normal']; - if (app()->auth->getCurUser()->isPrivilege('see_site_log_mod')) $level_list[] = 'mod'; - if (app()->auth->getCurUser()->isPrivilege('see_site_log_leader')) $level_list[] = 'leader'; + if (app()->auth->getCurUser()->isPrivilege('see_site_log_mod')) { + $level_list[] = 'mod'; + } + if (app()->auth->getCurUser()->isPrivilege('see_site_log_leader')) { + $level_list[] = 'leader'; + } return [ 'page' => 'Integer', 'limit' => 'Integer', @@ -45,14 +47,21 @@ public static function inputRules(): array ]; } - private function getLevels() { - if (!is_null($this->_levels)) return $this->_levels; + private function getLevels() + { + if (!is_null($this->_levels)) { + return $this->_levels; + } $input_level = $this->getInput('level'); if ($input_level == 'all') { $levels = ['normal']; - if (app()->auth->getCurUser()->isPrivilege('see_site_log_mod')) $levels[] = 'mod'; - if (app()->auth->getCurUser()->isPrivilege('see_site_log_leader')) $levels[] = 'leader'; + if (app()->auth->getCurUser()->isPrivilege('see_site_log_mod')) { + $levels[] = 'mod'; + } + if (app()->auth->getCurUser()->isPrivilege('see_site_log_leader')) { + $levels[] = 'leader'; + } } else { $levels = [$input_level]; } diff --git a/application/Models/Form/Subtitles/DeleteForm.php b/application/Models/Form/Subtitles/DeleteForm.php index 3e39627..4ebb94b 100644 --- a/application/Models/Form/Subtitles/DeleteForm.php +++ b/application/Models/Form/Subtitles/DeleteForm.php @@ -15,7 +15,6 @@ class DeleteForm extends Validator { - use isValidSubtitleTrait; public $reason; @@ -60,7 +59,7 @@ public function flush() // TODO Delete uploader bonus if ($this->subtitle['uppd_by'] != app()->auth->getCurUser()->getId()) { - app()->site->sendPM(0,$this->subtitle['uppd_by'],'msg_your_sub_deleted','msg_deleted_your_sub'); + app()->site->sendPM(0, $this->subtitle['uppd_by'], 'msg_your_sub_deleted', 'msg_deleted_your_sub'); } // TODO add user detail diff --git a/application/Models/Form/Subtitles/SearchForm.php b/application/Models/Form/Subtitles/SearchForm.php index 981d74c..36922a4 100644 --- a/application/Models/Form/Subtitles/SearchForm.php +++ b/application/Models/Form/Subtitles/SearchForm.php @@ -14,7 +14,6 @@ class SearchForm extends Pagination { - public $search; public $letter; @@ -69,5 +68,4 @@ public function getSubsSizeSum() } return $size; } - } diff --git a/application/Models/Form/Subtitles/UploadForm.php b/application/Models/Form/Subtitles/UploadForm.php index d3ea445..8c8b565 100644 --- a/application/Models/Form/Subtitles/UploadForm.php +++ b/application/Models/Form/Subtitles/UploadForm.php @@ -99,7 +99,9 @@ public function flush() $this->file->saveAs($file_loc); app()->pdo->commit(); } catch (\Exception $e) { - if (isset($file_loc)) unlink($file_loc); + if (isset($file_loc)) { + unlink($file_loc); + } app()->pdo->rollback(); throw $e; } diff --git a/application/Models/Form/Torrent/CommentsForm.php b/application/Models/Form/Torrent/CommentsForm.php index 999f464..b0f07fc 100644 --- a/application/Models/Form/Torrent/CommentsForm.php +++ b/application/Models/Form/Torrent/CommentsForm.php @@ -8,7 +8,6 @@ namespace App\Models\Form\Torrent; - use Rid\Validators\PaginationTrait; class CommentsForm extends DetailsForm diff --git a/application/Models/Form/Torrent/DetailsForm.php b/application/Models/Form/Torrent/DetailsForm.php index 71b60dc..c1d5ea1 100644 --- a/application/Models/Form/Torrent/DetailsForm.php +++ b/application/Models/Form/Torrent/DetailsForm.php @@ -14,10 +14,8 @@ class DetailsForm extends Validator { - protected $_autoload = true; protected $_autoload_from = ['get']; use isValidTorrentTrait; - } diff --git a/application/Models/Form/Torrent/DownloadForm.php b/application/Models/Form/Torrent/DownloadForm.php index e20db66..5b0f1df 100644 --- a/application/Models/Form/Torrent/DownloadForm.php +++ b/application/Models/Form/Torrent/DownloadForm.php @@ -39,8 +39,9 @@ protected function getRateLimitRules(): array protected function checkDownloadPos() { - if (!app()->auth->getCurUser()->getDownloadpos()) - $this->buildCallbackFailMsg('pos','your download pos is disabled'); + if (!app()->auth->getCurUser()->getDownloadpos()) { + $this->buildCallbackFailMsg('pos', 'your download pos is disabled'); + } } public function getSendFileContent() diff --git a/application/Models/Form/Torrent/EditForm.php b/application/Models/Form/Torrent/EditForm.php index c450669..b27f65c 100644 --- a/application/Models/Form/Torrent/EditForm.php +++ b/application/Models/Form/Torrent/EditForm.php @@ -8,7 +8,6 @@ namespace App\Models\Form\Torrent; - use App\Libraries\Constant; use App\Models\Form\Traits\isValidTorrentTrait; use App\Entity\Torrent; @@ -56,9 +55,11 @@ public static function baseTorrentRules(): array 'title' => 'required', 'category' => [ ['required'], ['Integer'], - ['InList', ['list' => array_map(function ($cat) { + ['InList', ['list' => array_map( + function ($cat) { return $cat['id']; - }, app()->site->ruleCanUsedCategory() + }, + app()->site->ruleCanUsedCategory() )]] ], 'descr' => 'required', @@ -158,7 +159,8 @@ public function checkUserPermission() // Get Torrent if not in validate if ($this->torrent === null) { $this->isExistTorrent(); - if ($this->getError()) { return false; + if ($this->getError()) { + return false; } } @@ -250,5 +252,4 @@ protected function updateTagsTable(array $tags) ])->execute(); } } - } diff --git a/application/Models/Form/Torrent/StructureForm.php b/application/Models/Form/Torrent/StructureForm.php index a517ac0..d030428 100644 --- a/application/Models/Form/Torrent/StructureForm.php +++ b/application/Models/Form/Torrent/StructureForm.php @@ -13,12 +13,10 @@ class StructureForm extends DetailsForm { - public function getTorrentFileContentDict() { $file_loc = Constant::getTorrentFileLoc($this->id); $content = Bencode::load($file_loc); return $content; } - } diff --git a/application/Models/Form/Torrent/UploadForm.php b/application/Models/Form/Torrent/UploadForm.php index e01c110..6c09eab 100644 --- a/application/Models/Form/Torrent/UploadForm.php +++ b/application/Models/Form/Torrent/UploadForm.php @@ -82,8 +82,9 @@ public static function callbackRules(): array /** @noinspection PhpUnused */ protected function checkUploadPos() { - if (!app()->auth->getCurUser()->getUploadpos()) - $this->buildCallbackFailMsg('pos','your upload pos is disabled'); + if (!app()->auth->getCurUser()->getUploadpos()) { + $this->buildCallbackFailMsg('pos', 'your upload pos is disabled'); + } } /** @noinspection PhpUnused */ @@ -98,7 +99,9 @@ protected function isValidTorrentFile() $dname = $this->checkTorrentDict($info, 'name', 'string'); $pieces = $this->checkTorrentDict($info, 'pieces', 'string'); - if (strlen($pieces) % 20 != 0) throw new ParseErrorException('std_invalid_pieces'); + if (strlen($pieces) % 20 != 0) { + throw new ParseErrorException('std_invalid_pieces'); + } if (isset($info['length'])) { $this->torrent_size = $info['length']; @@ -106,8 +109,12 @@ protected function isValidTorrentFile() $this->torrent_type = 'single'; } else { $f_list = $this->checkTorrentDict($info, 'files', 'array'); - if (!isset($f_list)) throw new ParseErrorException('std_missing_length_and_files'); - if (!count($f_list)) throw new ParseErrorException('no files'); + if (!isset($f_list)) { + throw new ParseErrorException('std_missing_length_and_files'); + } + if (!count($f_list)) { + throw new ParseErrorException('no files'); + } $this->torrent_size = 0; foreach ($f_list as $fn) { @@ -117,10 +124,14 @@ protected function isValidTorrentFile() $this->torrent_size += $ll; $ffa = []; foreach ($ff as $ffe) { - if (!is_string($ffe)) throw new ParseErrorException('std_filename_errors'); + if (!is_string($ffe)) { + throw new ParseErrorException('std_filename_errors'); + } $ffa[] = $ffe; } - if (!count($ffa)) throw new ParseErrorException('std_filename_errors'); + if (!count($ffa)) { + throw new ParseErrorException('std_filename_errors'); + } $this->checkFileName($ffa); $ffe = implode('/', $ffa); $this->torrent_list[] = ['filename' => $ffe, 'size' => $ll]; @@ -168,8 +179,12 @@ protected function makePrivateTorrent() unset($this->torrent_dict['nodes']); // remove cached peers (Bitcomet & Azareus) // Rewrite `commit` and `created by` if enabled this config - if (config('torrent_upload.rewrite_commit_to')) $this->torrent_dict['commit'] = config('torrent_upload.rewrite_commit_to'); - if (config('torrent_upload.rewrite_createdby_to')) $this->torrent_dict['created by'] = config('torrent_upload.rewrite_createdby_to'); + if (config('torrent_upload.rewrite_commit_to')) { + $this->torrent_dict['commit'] = config('torrent_upload.rewrite_commit_to'); + } + if (config('torrent_upload.rewrite_createdby_to')) { + $this->torrent_dict['created by'] = config('torrent_upload.rewrite_createdby_to'); + } /** * The following line requires uploader to re-download torrents after uploading **Since info_hash change** @@ -201,7 +216,9 @@ protected function makePrivateTorrent() ])->queryScalar(); // TODO redirect user to exist torrent details page when this torrent exist. - if ($count > 0) $this->buildCallbackFailMsg('Torrent','std_torrent_existed'); + if ($count > 0) { + $this->buildCallbackFailMsg('Torrent', 'std_torrent_existed'); + } } /** @@ -262,25 +279,26 @@ public function flush() throw $e; } - app()->site->writeLog("Torrent {$this->id} ({$this->title}) was uploaded by " . ($this->anonymous ? 'Anonymous' : app()->auth->getCurUser()->getUsername())); + app()->site->writeLog("Torrent {$this->id} ({$this->title}) was uploaded by " . ($this->anonymous ? 'Anonymous' : app()->auth->getCurUser()->getUsername())); } // TODO update torrent status based on user class or their owned torrents count - private function determineTorrentStatus() { + private function determineTorrentStatus() + { $this->status = TorrentStatus::CONFIRMED; } // TODO sep to Traits private function setTorrentBuff($operator_id = 0, $beneficiary_id = 0, $buff_type = 'mod', $ratio_type = 'Normal', $upload_ratio = 1, $download_ratio = 1) { - } // TODO it may take long time to get link details , so when torrent upload, we just push it to task worker private function getExternalLinkInfo() { - if ($this->links) + if ($this->links) { app()->redis->lPush('queue:external_link_via_torrent_upload', ['tid' => $this->id, 'links' => $this->links]); + } } private function setBuff() @@ -294,7 +312,6 @@ private function setBuff() } // TODO set uploader (or you can say torrents owner) buff - } /** @@ -329,7 +346,9 @@ private function getFileTree() private static function makeFileTree(array $array, $delimiter = '/') { - if (!is_array($array)) return []; + if (!is_array($array)) { + return []; + } $splitRE = '/' . preg_quote($delimiter, '/') . '/'; $returnArr = []; @@ -367,10 +386,14 @@ private static function makeFileTree(array $array, $delimiter = '/') */ private function checkTorrentDict($dict, $key, $type = null) { - if (!is_array($dict)) throw new ParseErrorException("std_not_a_dictionary"); + if (!is_array($dict)) { + throw new ParseErrorException("std_not_a_dictionary"); + } $value = $dict[$key]; - if (!isset($value)) throw new ParseErrorException("std_dictionary_is_missing_key"); + if (!isset($value)) { + throw new ParseErrorException("std_dictionary_is_missing_key"); + } if (!is_null($type)) { $isFunction = 'is_' . $type; @@ -380,6 +403,4 @@ private function checkTorrentDict($dict, $key, $type = null) } return $value; } - - } diff --git a/application/Models/Form/Torrents/SearchForm.php b/application/Models/Form/Torrents/SearchForm.php index 5583ac3..d11bab3 100644 --- a/application/Models/Form/Torrents/SearchForm.php +++ b/application/Models/Form/Torrents/SearchForm.php @@ -12,7 +12,6 @@ class SearchForm extends Pagination { - public static $MAX_LIMIT = 100; private $_tags; @@ -35,8 +34,8 @@ public static function inputRules(): array $quality_id_list = []; if (config('torrent_upload.enable_quality_' . $quality)) { $quality_id_list = [0] + array_map(function ($cat) { - return $cat['id']; - }, app()->site->ruleQuality($quality)); + return $cat['id']; + }, app()->site->ruleQuality($quality)); } $rules[$quality . '[*]'] = [ @@ -81,7 +80,9 @@ private function getTagsArray() if (is_null($this->_tags)) { $tags = $this->getInput('tags') ?? []; - if (is_string($tags)) $tags = explode(',', $tags); + if (is_string($tags)) { + $tags = explode(',', $tags); + } $this->_tags = array_map('trim', $tags); } @@ -90,7 +91,9 @@ private function getTagsArray() private function getSearchField(): array { - if (!is_null($this->_field)) return $this->_field; // return cached search field + if (!is_null($this->_field)) { + return $this->_field; + } // return cached search field $fields = []; @@ -98,14 +101,18 @@ private function getSearchField(): array foreach (app()->site->getQualityTableList() as $quality => $title) { if (config('torrent_upload.enable_quality_' . $quality)) { $value = $this->getInput($quality); - if (is_array($value)) $fields[] = ["AND `quality_$quality` IN (:quality) ", 'params' => ['quality' => array_map('intval', $value)]]; + if (is_array($value)) { + $fields[] = ["AND `quality_$quality` IN (:quality) ", 'params' => ['quality' => array_map('intval', $value)]]; + } } } // Teams if (config('torrent_upload.enable_teams')) { $value = $this->getInput('team'); - if (is_array($value)) $fields[] = ['AND `team` IN (:team) ', 'params' => ['team' => array_map('intval', $value)]]; + if (is_array($value)) { + $fields[] = ['AND `team` IN (:team) ', 'params' => ['team' => array_map('intval', $value)]]; + } } // TODO we may not use `&search_area=` to search in non-title/subtitle/descr field, Use sep `&ownerid=` , `&doubanid=` instead. @@ -129,7 +136,9 @@ private function getSearchField(): array $searchstr_exploded_count++; $searchstr_exploded[] = $value; } - if ($searchstr_exploded_count > 10) break; + if ($searchstr_exploded_count > 10) { + break; + } } } diff --git a/application/Models/Form/Torrents/TagsForm.php b/application/Models/Form/Torrents/TagsForm.php index 6684900..49de5f2 100644 --- a/application/Models/Form/Torrents/TagsForm.php +++ b/application/Models/Form/Torrents/TagsForm.php @@ -8,7 +8,6 @@ namespace App\Models\Form\Torrents; - use Rid\Validators\Pagination; class TagsForm extends Pagination @@ -36,5 +35,4 @@ public function getRemoteData(): array ['LIMIT :offset, :rows', 'params' => ['offset' => $this->offset, 'rows' => $this->limit]], ])->queryAll(); } - } diff --git a/application/Models/Form/Traits/FileSentTrait.php b/application/Models/Form/Traits/FileSentTrait.php index 855eb33..67d5a68 100644 --- a/application/Models/Form/Traits/FileSentTrait.php +++ b/application/Models/Form/Traits/FileSentTrait.php @@ -8,10 +8,8 @@ namespace App\Models\Form\Traits; - trait FileSentTrait { - use actionRateLimitCheckTrait; protected function getSendFileName(): string @@ -43,8 +41,9 @@ final private function setRespHeaders() } app()->response->setHeader('Content-Type', $this->getSendFileContentType()); - if ($this->getSendFileContentLength() != 0) + if ($this->getSendFileContentLength() != 0) { app()->response->setHeader('Content-Length', $this->getSendFileContentLength()); + } $filename = $this->getSendFileName(); if (strpos(app()->request->header('user-agent'), 'IE')) { diff --git a/application/Models/Form/Traits/actionRateLimitCheckTrait.php b/application/Models/Form/Traits/actionRateLimitCheckTrait.php index 8f459f7..9e7cde0 100644 --- a/application/Models/Form/Traits/actionRateLimitCheckTrait.php +++ b/application/Models/Form/Traits/actionRateLimitCheckTrait.php @@ -8,13 +8,11 @@ namespace App\Models\Form\Traits; - use App\Libraries\Constant; use Redis; trait actionRateLimitCheckTrait { - protected static function getRateLimitRules(): array { /** @noinspection PhpUnusedLocalVariableInspection */ @@ -52,7 +50,9 @@ protected function hookRateLimitCheckFailed($limit_status, $count) /** @noinspection PhpUnused */ protected function rateLimitCheck() { - if (empty($this::getRateLimitRules())) return; // It seems we don't need rate limit + if (empty($this::getRateLimitRules())) { + return; + } // It seems we don't need rate limit foreach ($this::getRateLimitRules() as $limit_status) { list($vary, $count) = $this->isRateLimitHit($limit_status); diff --git a/application/Models/Form/Traits/isValidSubtitleTrait.php b/application/Models/Form/Traits/isValidSubtitleTrait.php index 4ee9913..6c0b1be 100644 --- a/application/Models/Form/Traits/isValidSubtitleTrait.php +++ b/application/Models/Form/Traits/isValidSubtitleTrait.php @@ -8,7 +8,6 @@ namespace App\Models\Form\Traits; - trait isValidSubtitleTrait { public $id; // Subtitle Id diff --git a/application/Models/Form/Traits/isValidTorrentTrait.php b/application/Models/Form/Traits/isValidTorrentTrait.php index e904e05..434b076 100644 --- a/application/Models/Form/Traits/isValidTorrentTrait.php +++ b/application/Models/Form/Traits/isValidTorrentTrait.php @@ -8,7 +8,6 @@ namespace App\Models\Form\Traits; - use App\Entity\Torrent; trait isValidTorrentTrait diff --git a/application/Models/Form/Traits/isValidUserTrait.php b/application/Models/Form/Traits/isValidUserTrait.php index 716dfd7..eb5847f 100644 --- a/application/Models/Form/Traits/isValidUserTrait.php +++ b/application/Models/Form/Traits/isValidUserTrait.php @@ -52,5 +52,4 @@ public function getUserData($key = null, $default = null) { return is_null($key) ? $this->user_data : ($this->user_data[$key] ?? $default); } - } diff --git a/application/Models/Form/User/InviteActionForm.php b/application/Models/Form/User/InviteActionForm.php index 18b0ac6..98d2dcb 100644 --- a/application/Models/Form/User/InviteActionForm.php +++ b/application/Models/Form/User/InviteActionForm.php @@ -60,7 +60,8 @@ public static function callbackRules(): array ]; } - protected function checkActionPrivilege() { + protected function checkActionPrivilege() + { $action = $this->getInput('action'); if ($action == self::ACTION_CONFIRM) { if (!app()->auth->getCurUser()->isPrivilege('invite_manual_confirm')) { @@ -74,18 +75,20 @@ protected function checkActionPrivilege() { } } - protected function checkConfirmInfo() { + protected function checkConfirmInfo() + { if ($this->getInput('action') == self::ACTION_CONFIRM) { $this->confirm_info = app()->pdo->createCommand('SELECT `status` FROM users WHERE id= :invitee_id')->bindParams([ 'invitee_id' => $this->getInput('invitee_id') ])->queryScalar(); if ($this->confirm_info === false || $this->confirm_info !== UserStatus::PENDING) { - $this->buildCallbackFailMsg('user:confirm','The user to confirm is not exist or already confirmed'); + $this->buildCallbackFailMsg('user:confirm', 'The user to confirm is not exist or already confirmed'); } } } - protected function checkRecycleInfo() { + protected function checkRecycleInfo() + { if ($this->getInput('action') == self::ACTION_RECYCLE) { // Get unused invite info $this->invite_info = app()->pdo->createCommand('SELECT * FROM `invite` WHERE `id` = :invite_id AND `inviter_id` = :inviter_id AND `used` = 0')->bindParams([ @@ -100,14 +103,15 @@ protected function checkRecycleInfo() { // TODO Add recycle limit so that user can't make a temporarily invite like 'permanent' if ($this->invite_info['invite_type'] == InviteForm::INVITE_TYPE_TEMPORARILY) { if (app()->redis->get('invite_recycle_limit:user_' . $this->invite_info['inviter_id']) !== false) { - $this->buildCallbackFailMsg('invite_recycle_limit','Hit recycle limit'); + $this->buildCallbackFailMsg('invite_recycle_limit', 'Hit recycle limit'); return; }; } } } - private function flush_confirm() { + private function flush_confirm() + { app()->pdo->createCommand('UPDATE `users` SET `status` = :new_status WHERE `id` = :invitee_id')->bindParams([ 'new_status' => UserStatus::CONFIRMED, 'invitee_id' => $this->invitee_id ])->execute(); @@ -118,7 +122,8 @@ private function flush_confirm() { } } - private function flush_recycle() { + private function flush_recycle() + { app()->pdo->beginTransaction(); try { // Set this invite record's status as recycled @@ -140,7 +145,7 @@ private function flush_recycle() { 'life_time' => config('invite.recycle_invite_lifetime') ])->execute(); $msg .= ' And return you a temporarily invite with ' . config('invite.recycle_invite_lifetime') . ' seconds lifetime.'; - app()->redis->hDel( 'User:' . $this->invite_info['inviter_id'] . ':base_content','temp_invite'); + app()->redis->hDel('User:' . $this->invite_info['inviter_id'] . ':base_content', 'temp_invite'); } } app()->pdo->commit(); @@ -159,5 +164,4 @@ public function flush() return $this->flush_recycle(); } } - } diff --git a/application/Models/Form/User/InviteForm.php b/application/Models/Form/User/InviteForm.php index 98924f8..7070c3a 100644 --- a/application/Models/Form/User/InviteForm.php +++ b/application/Models/Form/User/InviteForm.php @@ -150,11 +150,15 @@ public function flush() } if ($invite_status === true) { // TODO use email queue - app()->site->sendEmail([$this->email], 'Invite To ' . config('base.site_name'), - 'email/user_invite', [ + app()->site->sendEmail( + [$this->email], + 'Invite To ' . config('base.site_name'), + 'email/user_invite', + [ 'username' => $this->username, 'invite_link' => $this->invite_link, - ]); + ] + ); } return $invite_status; } diff --git a/application/Models/Form/User/SessionsListForm.php b/application/Models/Form/User/SessionsListForm.php index c7ec11f..83ab0b2 100644 --- a/application/Models/Form/User/SessionsListForm.php +++ b/application/Models/Form/User/SessionsListForm.php @@ -8,7 +8,6 @@ namespace App\Models\Form\User; - use Rid\Validators\Pagination; class SessionsListForm extends Pagination diff --git a/application/Models/Form/User/UserDetailsForm.php b/application/Models/Form/User/UserDetailsForm.php index aad3963..840c129 100644 --- a/application/Models/Form/User/UserDetailsForm.php +++ b/application/Models/Form/User/UserDetailsForm.php @@ -8,7 +8,6 @@ namespace App\Models\Form\User; - use App\Models\Form\Traits\isValidUserTrait; use Rid\Validators\Validator; diff --git a/application/Process/CronTabProcess.php b/application/Process/CronTabProcess.php index 8c4a2e7..7cfb5c7 100644 --- a/application/Process/CronTabProcess.php +++ b/application/Process/CronTabProcess.php @@ -13,10 +13,8 @@ use Rid\Base\Process; - final class CronTabProcess extends Process { - private $_print_flag = 1; // FIXME debug model on private $_none_exist_job = []; @@ -55,7 +53,8 @@ public function run() app()->pdo->createCommand('UPDATE `site_crontab` set last_run_at = FROM_UNIXTIME(:last_run_at) , next_run_at = FROM_UNIXTIME(:next_run_at) WHERE id=:id')->bindParams([ 'id' => $job['id'], 'last_run_at' => $job_end_time, 'next_run_at' => $next_run_at ])->execute(); - $this->print_log('The run job : ' . $job['job'] . ' Finished. ' . + $this->print_log( + 'The run job : ' . $job['job'] . ' Finished. ' . 'Cost time: ' . number_format($job_end_time - $job_start_time, 10) . 's, ' . 'Next run at : ' . $next_run_at ); @@ -73,11 +72,14 @@ public function run() } } $end_time = time(); - if ($hit > 0) $this->print_log('This Cron Work period Start At ' . $start_time . ', Cost Time: ' . number_format($end_time - $start_time, 10) . 's, With ' . $hit . ' Jobs hits.'); + if ($hit > 0) { + $this->print_log('This Cron Work period Start At ' . $start_time . ', Cost Time: ' . number_format($end_time - $start_time, 10) . 's, With ' . $hit . ' Jobs hits.'); + } } /** @noinspection PhpUnused */ - protected function clean_expired_zset_cache() { + protected function clean_expired_zset_cache() + { $timenow = time(); $clean_list = [ @@ -96,7 +98,9 @@ protected function clean_expired_zset_cache() { foreach ($clean_list as $item) { [$field, $msg] = $item; $clean_count = app()->redis->zRemRangeByScore($field, 0, $timenow); - if ($clean_count > 0) $this->print_log(sprintf($msg, $clean_count)); + if ($clean_count > 0) { + $this->print_log(sprintf($msg, $clean_count)); + } } } @@ -112,7 +116,8 @@ protected function clean_dead_peer() } /** @noinspection PhpUnused */ - protected function clean_expired_items_database() { + protected function clean_expired_items_database() + { $clean_sqls = [ [ // expired session 'UPDATE `sessions` SET `expired` = 1 WHERE `expired` = 0 AND `login_at` < DATE_SUB(NOW(), INTERVAL 15 MINUTE)', @@ -128,7 +133,9 @@ protected function clean_expired_items_database() { [$clean_sql, $msg] = $item; app()->pdo->createCommand($clean_sql)->execute(); $clean_count = app()->pdo->getRowCount(); - if ($clean_count > 0) $this->print_log(sprintf($msg, $clean_count)); + if ($clean_count > 0) { + $this->print_log(sprintf($msg, $clean_count)); + } } } @@ -190,7 +197,8 @@ protected function sync_torrents_status() } /** @noinspection PhpUnused */ - protected function sync_ban_list() { + protected function sync_ban_list() + { // Sync Banned Emails list $ban_email_list = app()->pdo->createCommand('SELECT `email` from `ban_emails`')->queryColumn() ?: []; app()->redis->sAddArray(Constant::siteBannedEmailSet, $ban_email_list); diff --git a/application/Process/TrackerAnnounceProcess.php b/application/Process/TrackerAnnounceProcess.php index 0a39ff1..6e15deb 100644 --- a/application/Process/TrackerAnnounceProcess.php +++ b/application/Process/TrackerAnnounceProcess.php @@ -112,8 +112,9 @@ private function processAnnounceRequest($timenow, $queries, $seeder, $userInfo, $upSpeed = (($trueUploaded > 0 && $duration > 0) ? $trueUploaded / $duration : 0); if (config('tracker.enable_upspeed_check')) { - if ($userInfo['class'] < config('authority.pass_tracker_upspeed_check') && $duration > 0) + if ($userInfo['class'] < config('authority.pass_tracker_upspeed_check') && $duration > 0) { $this->checkUpspeed($userInfo, $torrentInfo, $trueUploaded, $trueDownloaded, $duration, $upSpeed); + } } $this->getTorrentBuff($userInfo['id'], $torrentInfo['id'], $trueUploaded, $trueDownloaded, $upSpeed, $thisUploaded, $thisDownloaded); @@ -189,7 +190,6 @@ private function processAnnounceRequest($timenow, $queries, $seeder, $userInfo, */ private function checkUpspeed($userInfo, $torrentInfo, $trueUploaded, $trueDownloaded, $duration, $upspeed) { - $logCheater = function ($commit) use ($userInfo, $torrentInfo, $trueUploaded, $trueDownloaded, $duration) { app()->pdo->createCommand("INSERT INTO `cheaters`(`added_at`,`userid`, `torrentid`, `uploaded`, `downloaded`, `anctime`, `seeders`, `leechers`, `hit`, `commit`, `reviewed`, `reviewed_by`) VALUES (CURRENT_TIMESTAMP, :uid, :tid, :uploaded, :downloaded, :anctime, :seeders, :leechers, :hit, :msg, :reviewed, :reviewed_by) @@ -214,19 +214,22 @@ private function checkUpspeed($userInfo, $torrentInfo, $trueUploaded, $trueDownl } // Uploaded more than 1 GB with uploading rate higher than 25 MByte/S (For Consertive level). This is likely cheating. - if ($trueUploaded > 1 * (1024 ** 3) && $upspeed > 25 * (1024 ** 2)) + if ($trueUploaded > 1 * (1024 ** 3) && $upspeed > 25 * (1024 ** 2)) { $logCheater('Abnormally high uploading rate'); + } // Uploaded more than 1 GB with uploading rate higher than 1 MByte/S when there is less than 8 leechers (For Consertive level). This is likely cheating. - if ($trueUploaded > 1 * (1024 ** 3) && $upspeed > 1 * (1024 ** 2)) + if ($trueUploaded > 1 * (1024 ** 3) && $upspeed > 1 * (1024 ** 2)) { $logCheater('User is uploading fast when there is few leechers'); + } //Uploaded more than 10 MB with uploading speed faster than 100 KByte/S when there is no leecher. This is likely cheating. - if ($trueUploaded > 10 * (1024 ** 2) && $upspeed > 100 * 1024 && $torrentInfo['incomplete'] <= 0) + if ($trueUploaded > 10 * (1024 ** 2) && $upspeed > 100 * 1024 && $torrentInfo['incomplete'] <= 0) { $logCheater('User is uploading when there is no leecher'); + } } - private function getTorrentBuff($userid, $torrentid, $trueUploaded, $trueDownloaded,$upspeed, &$thisUploaded, &$thisDownloaded) + private function getTorrentBuff($userid, $torrentid, $trueUploaded, $trueDownloaded, $upspeed, &$thisUploaded, &$thisDownloaded) { $buff = app()->redis->get("TRACKER:user_" . $userid . "_torrent_" . $torrentid . "_buff"); if ($buff === false) { diff --git a/application/Repository/Torrent/TorrentStatus.php b/application/Repository/Torrent/TorrentStatus.php index 91bf773..6ccadc7 100644 --- a/application/Repository/Torrent/TorrentStatus.php +++ b/application/Repository/Torrent/TorrentStatus.php @@ -10,7 +10,6 @@ namespace App\Repository\Torrent; - class TorrentStatus { const DELETED = 'deleted'; diff --git a/application/Repository/Torrent/TorrentType.php b/application/Repository/Torrent/TorrentType.php index 42b2a47..3f50411 100644 --- a/application/Repository/Torrent/TorrentType.php +++ b/application/Repository/Torrent/TorrentType.php @@ -10,7 +10,6 @@ namespace App\Repository\Torrent; - class TorrentType { const SINGLE = 'single'; diff --git a/application/Repository/User/UserRole.php b/application/Repository/User/UserRole.php index bbc5416..13b5f0b 100644 --- a/application/Repository/User/UserRole.php +++ b/application/Repository/User/UserRole.php @@ -10,7 +10,6 @@ namespace App\Repository\User; - class UserRole { // User class diff --git a/application/Repository/User/UserStatus.php b/application/Repository/User/UserStatus.php index 1dff3a3..0fb6e43 100644 --- a/application/Repository/User/UserStatus.php +++ b/application/Repository/User/UserStatus.php @@ -10,7 +10,6 @@ namespace App\Repository\User; - class UserStatus { // User Status diff --git a/composer.json b/composer.json index 019be9b..45ce5da 100644 --- a/composer.json +++ b/composer.json @@ -44,6 +44,10 @@ "require-dev": { "eaglewu/swoole-ide-helper": "dev-master" }, + "config": { + "preferred-install": "dist", + "optimize-autoloader": true + }, "autoload": { "psr-4": { "Rid\\": "framework/", @@ -53,5 +57,6 @@ "framework/Rid.php", "framework/functions.php" ] - } + }, + "prefer-stable": true } diff --git a/composer.lock b/composer.lock index bd79bb2..d08940e 100644 --- a/composer.lock +++ b/composer.lock @@ -4,20 +4,20 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "029866c5d960f4eb5ad15a912f6da7a9", + "content-hash": "b21bc34532e02a7faae7628d5344d4c3", "packages": [ { "name": "adhocore/cli", - "version": "0.7.0", + "version": "0.7.3", "source": { "type": "git", "url": "https://github.com/adhocore/php-cli.git", - "reference": "2f4f37c792933680b5cf150243e83718955f4dff" + "reference": "79e9a1ba037e94c66fdf713f1f4dd328c4135759" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/adhocore/php-cli/zipball/2f4f37c792933680b5cf150243e83718955f4dff", - "reference": "2f4f37c792933680b5cf150243e83718955f4dff", + "url": "https://api.github.com/repos/adhocore/php-cli/zipball/79e9a1ba037e94c66fdf713f1f4dd328c4135759", + "reference": "79e9a1ba037e94c66fdf713f1f4dd328c4135759", "shasum": "" }, "require": { @@ -60,7 +60,7 @@ "stream-input", "stream-output" ], - "time": "2019-12-30T14:06:00+00:00" + "time": "2020-01-03T12:41:16+00:00" }, { "name": "firebase/php-jwt", @@ -219,16 +219,16 @@ }, { "name": "phpmailer/phpmailer", - "version": "v6.0.7", + "version": "v6.1.4", "source": { "type": "git", "url": "https://github.com/PHPMailer/PHPMailer.git", - "reference": "0c41a36d4508d470e376498c1c0c527aa36a2d59" + "reference": "c5e61d0729507049cec9673aa1a679f9adefd683" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/0c41a36d4508d470e376498c1c0c527aa36a2d59", - "reference": "0c41a36d4508d470e376498c1c0c527aa36a2d59", + "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/c5e61d0729507049cec9673aa1a679f9adefd683", + "reference": "c5e61d0729507049cec9673aa1a679f9adefd683", "shasum": "" }, "require": { @@ -237,13 +237,9 @@ "php": ">=5.5.0" }, "require-dev": { - "doctrine/annotations": "1.2.*", + "doctrine/annotations": "^1.2", "friendsofphp/php-cs-fixer": "^2.2", - "phpdocumentor/phpdocumentor": "2.*", - "phpunit/phpunit": "^4.8 || ^5.7", - "zendframework/zend-eventmanager": "3.0.*", - "zendframework/zend-i18n": "2.7.3", - "zendframework/zend-serializer": "2.7.*" + "phpunit/phpunit": "^4.8 || ^5.7" }, "suggest": { "ext-mbstring": "Needed to send email in multibyte encoding charset", @@ -261,17 +257,17 @@ }, "notification-url": "https://packagist.org/downloads/", "license": [ - "LGPL-2.1" + "LGPL-2.1-only" ], "authors": [ - { - "name": "Jim Jagielski", - "email": "jimjag@gmail.com" - }, { "name": "Marcus Bointon", "email": "phpmailer@synchromedia.co.uk" }, + { + "name": "Jim Jagielski", + "email": "jimjag@gmail.com" + }, { "name": "Andy Prevost", "email": "codeworxtech@users.sourceforge.net" @@ -281,47 +277,52 @@ } ], "description": "PHPMailer is a full-featured email creation and transfer class for PHP", - "time": "2019-02-01T15:04:28+00:00" + "time": "2019-12-10T11:17:38+00:00" }, { "name": "phpoption/phpoption", - "version": "1.5.0", + "version": "1.7.2", "source": { "type": "git", "url": "https://github.com/schmittjoh/php-option.git", - "reference": "94e644f7d2051a5f0fcf77d81605f152eecff0ed" + "reference": "77f7c4d2e65413aff5b5a8cc8b3caf7a28d81959" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/schmittjoh/php-option/zipball/94e644f7d2051a5f0fcf77d81605f152eecff0ed", - "reference": "94e644f7d2051a5f0fcf77d81605f152eecff0ed", + "url": "https://api.github.com/repos/schmittjoh/php-option/zipball/77f7c4d2e65413aff5b5a8cc8b3caf7a28d81959", + "reference": "77f7c4d2e65413aff5b5a8cc8b3caf7a28d81959", "shasum": "" }, "require": { - "php": ">=5.3.0" + "php": "^5.5.9 || ^7.0" }, "require-dev": { - "phpunit/phpunit": "4.7.*" + "bamarni/composer-bin-plugin": "^1.3", + "phpunit/phpunit": "^4.8.35 || ^5.0 || ^6.0 || ^7.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.3-dev" + "dev-master": "1.7-dev" } }, "autoload": { - "psr-0": { - "PhpOption\\": "src/" + "psr-4": { + "PhpOption\\": "src/PhpOption/" } }, "notification-url": "https://packagist.org/downloads/", "license": [ - "Apache2" + "Apache-2.0" ], "authors": [ { "name": "Johannes M. Schmitt", "email": "schmittjoh@gmail.com" + }, + { + "name": "Graham Campbell", + "email": "graham@alt-three.com" } ], "description": "Option Type for PHP", @@ -331,20 +332,20 @@ "php", "type" ], - "time": "2015-07-25T16:39:46+00:00" + "time": "2019-12-15T19:35:24+00:00" }, { "name": "psr/log", - "version": "1.1.0", + "version": "1.1.2", "source": { "type": "git", "url": "https://github.com/php-fig/log.git", - "reference": "6c001f1daafa3a3ac1d8ff69ee4db8e799a654dd" + "reference": "446d54b4cb6bf489fc9d75f55843658e6f25d801" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-fig/log/zipball/6c001f1daafa3a3ac1d8ff69ee4db8e799a654dd", - "reference": "6c001f1daafa3a3ac1d8ff69ee4db8e799a654dd", + "url": "https://api.github.com/repos/php-fig/log/zipball/446d54b4cb6bf489fc9d75f55843658e6f25d801", + "reference": "446d54b4cb6bf489fc9d75f55843658e6f25d801", "shasum": "" }, "require": { @@ -353,7 +354,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.0.x-dev" + "dev-master": "1.1.x-dev" } }, "autoload": { @@ -378,7 +379,7 @@ "psr", "psr-3" ], - "time": "2018-11-20T15:27:04+00:00" + "time": "2019-11-01T11:05:21+00:00" }, { "name": "siriusphp/validation", @@ -478,32 +479,32 @@ }, { "name": "symfony/config", - "version": "v4.3.4", + "version": "v4.4.2", "source": { "type": "git", "url": "https://github.com/symfony/config.git", - "reference": "07d49c0f823e0bc367c6d84e35b61419188a5ece" + "reference": "6911d432edd5b50822986604fd5a5be3af856d30" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/config/zipball/07d49c0f823e0bc367c6d84e35b61419188a5ece", - "reference": "07d49c0f823e0bc367c6d84e35b61419188a5ece", + "url": "https://api.github.com/repos/symfony/config/zipball/6911d432edd5b50822986604fd5a5be3af856d30", + "reference": "6911d432edd5b50822986604fd5a5be3af856d30", "shasum": "" }, "require": { "php": "^7.1.3", - "symfony/filesystem": "~3.4|~4.0", + "symfony/filesystem": "^3.4|^4.0|^5.0", "symfony/polyfill-ctype": "~1.8" }, "conflict": { "symfony/finder": "<3.4" }, "require-dev": { - "symfony/dependency-injection": "~3.4|~4.0", - "symfony/event-dispatcher": "~3.4|~4.0", - "symfony/finder": "~3.4|~4.0", - "symfony/messenger": "~4.1", - "symfony/yaml": "~3.4|~4.0" + "symfony/event-dispatcher": "^3.4|^4.0|^5.0", + "symfony/finder": "^3.4|^4.0|^5.0", + "symfony/messenger": "^4.1|^5.0", + "symfony/service-contracts": "^1.1|^2", + "symfony/yaml": "^3.4|^4.0|^5.0" }, "suggest": { "symfony/yaml": "To use the yaml reference dumper" @@ -511,7 +512,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "4.3-dev" + "dev-master": "4.4-dev" } }, "autoload": { @@ -538,30 +539,30 @@ ], "description": "Symfony Config Component", "homepage": "https://symfony.com", - "time": "2019-08-26T08:26:39+00:00" + "time": "2019-12-18T12:00:29+00:00" }, { "name": "symfony/filesystem", - "version": "v4.3.4", + "version": "v5.0.2", "source": { "type": "git", "url": "https://github.com/symfony/filesystem.git", - "reference": "9abbb7ef96a51f4d7e69627bc6f63307994e4263" + "reference": "1d71f670bc5a07b9ccc97dc44f932177a322d4e6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/filesystem/zipball/9abbb7ef96a51f4d7e69627bc6f63307994e4263", - "reference": "9abbb7ef96a51f4d7e69627bc6f63307994e4263", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/1d71f670bc5a07b9ccc97dc44f932177a322d4e6", + "reference": "1d71f670bc5a07b9ccc97dc44f932177a322d4e6", "shasum": "" }, "require": { - "php": "^7.1.3", + "php": "^7.2.5", "symfony/polyfill-ctype": "~1.8" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "4.3-dev" + "dev-master": "5.0-dev" } }, "autoload": { @@ -588,20 +589,20 @@ ], "description": "Symfony Filesystem Component", "homepage": "https://symfony.com", - "time": "2019-08-20T14:07:54+00:00" + "time": "2019-11-26T23:25:11+00:00" }, { "name": "symfony/polyfill-ctype", - "version": "v1.12.0", + "version": "v1.13.1", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-ctype.git", - "reference": "550ebaac289296ce228a706d0867afc34687e3f4" + "reference": "f8f0b461be3385e56d6de3dbb5a0df24c0c275e3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/550ebaac289296ce228a706d0867afc34687e3f4", - "reference": "550ebaac289296ce228a706d0867afc34687e3f4", + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/f8f0b461be3385e56d6de3dbb5a0df24c0c275e3", + "reference": "f8f0b461be3385e56d6de3dbb5a0df24c0c275e3", "shasum": "" }, "require": { @@ -613,7 +614,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.12-dev" + "dev-master": "1.13-dev" } }, "autoload": { @@ -646,20 +647,20 @@ "polyfill", "portable" ], - "time": "2019-08-06T08:03:45+00:00" + "time": "2019-11-27T13:56:44+00:00" }, { "name": "symfony/polyfill-mbstring", - "version": "v1.12.0", + "version": "v1.13.1", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-mbstring.git", - "reference": "b42a2f66e8f1b15ccf25652c3424265923eb4f17" + "reference": "7b4aab9743c30be783b73de055d24a39cf4b954f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/b42a2f66e8f1b15ccf25652c3424265923eb4f17", - "reference": "b42a2f66e8f1b15ccf25652c3424265923eb4f17", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/7b4aab9743c30be783b73de055d24a39cf4b954f", + "reference": "7b4aab9743c30be783b73de055d24a39cf4b954f", "shasum": "" }, "require": { @@ -671,7 +672,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.12-dev" + "dev-master": "1.13-dev" } }, "autoload": { @@ -705,30 +706,31 @@ "portable", "shim" ], - "time": "2019-08-06T08:03:45+00:00" + "time": "2019-11-27T14:18:11+00:00" }, { "name": "symfony/translation", - "version": "v4.3.4", + "version": "v4.4.2", "source": { "type": "git", "url": "https://github.com/symfony/translation.git", - "reference": "28498169dd334095fa981827992f3a24d50fed0f" + "reference": "f7669f48a9633bf8139bc026c755e894b7206677" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/translation/zipball/28498169dd334095fa981827992f3a24d50fed0f", - "reference": "28498169dd334095fa981827992f3a24d50fed0f", + "url": "https://api.github.com/repos/symfony/translation/zipball/f7669f48a9633bf8139bc026c755e894b7206677", + "reference": "f7669f48a9633bf8139bc026c755e894b7206677", "shasum": "" }, "require": { "php": "^7.1.3", "symfony/polyfill-mbstring": "~1.0", - "symfony/translation-contracts": "^1.1.6" + "symfony/translation-contracts": "^1.1.6|^2" }, "conflict": { "symfony/config": "<3.4", "symfony/dependency-injection": "<3.4", + "symfony/http-kernel": "<4.4", "symfony/yaml": "<3.4" }, "provide": { @@ -736,15 +738,14 @@ }, "require-dev": { "psr/log": "~1.0", - "symfony/config": "~3.4|~4.0", - "symfony/console": "~3.4|~4.0", - "symfony/dependency-injection": "~3.4|~4.0", - "symfony/finder": "~2.8|~3.0|~4.0", - "symfony/http-kernel": "~3.4|~4.0", - "symfony/intl": "~3.4|~4.0", - "symfony/service-contracts": "^1.1.2", - "symfony/var-dumper": "~3.4|~4.0", - "symfony/yaml": "~3.4|~4.0" + "symfony/config": "^3.4|^4.0|^5.0", + "symfony/console": "^3.4|^4.0|^5.0", + "symfony/dependency-injection": "^3.4|^4.0|^5.0", + "symfony/finder": "~2.8|~3.0|~4.0|^5.0", + "symfony/http-kernel": "^4.4", + "symfony/intl": "^3.4|^4.0|^5.0", + "symfony/service-contracts": "^1.1.2|^2", + "symfony/yaml": "^3.4|^4.0|^5.0" }, "suggest": { "psr/log-implementation": "To use logging capability in translator", @@ -754,7 +755,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "4.3-dev" + "dev-master": "4.4-dev" } }, "autoload": { @@ -781,24 +782,24 @@ ], "description": "Symfony Translation Component", "homepage": "https://symfony.com", - "time": "2019-08-26T08:55:16+00:00" + "time": "2019-12-12T12:53:52+00:00" }, { "name": "symfony/translation-contracts", - "version": "v1.1.6", + "version": "v2.0.1", "source": { "type": "git", "url": "https://github.com/symfony/translation-contracts.git", - "reference": "325b17c24f3ee23cbecfa63ba809c6d89b5fa04a" + "reference": "8cc682ac458d75557203b2f2f14b0b92e1c744ed" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/translation-contracts/zipball/325b17c24f3ee23cbecfa63ba809c6d89b5fa04a", - "reference": "325b17c24f3ee23cbecfa63ba809c6d89b5fa04a", + "url": "https://api.github.com/repos/symfony/translation-contracts/zipball/8cc682ac458d75557203b2f2f14b0b92e1c744ed", + "reference": "8cc682ac458d75557203b2f2f14b0b92e1c744ed", "shasum": "" }, "require": { - "php": "^7.1.3" + "php": "^7.2.5" }, "suggest": { "symfony/translation-implementation": "" @@ -806,7 +807,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.1-dev" + "dev-master": "2.0-dev" } }, "autoload": { @@ -838,7 +839,7 @@ "interoperability", "standards" ], - "time": "2019-08-02T12:15:04+00:00" + "time": "2019-11-18T17:27:11+00:00" }, { "name": "vlucas/phpdotenv", @@ -945,7 +946,7 @@ "stability-flags": { "eaglewu/swoole-ide-helper": 20 }, - "prefer-stable": false, + "prefer-stable": true, "prefer-lowest": false, "platform": { "php": ">=7.3.0", diff --git a/config/httpServer.php b/config/httpServer.php index 2fe9d17..ee21827 100644 --- a/config/httpServer.php +++ b/config/httpServer.php @@ -37,34 +37,44 @@ // 注册回调方法Hook 'hook' => [ // 主进程启动事件(onStart)回调 - 'hook_start' => function (Server $server) { }, + 'hook_start' => function (Server $server) { + }, // 主进程停止事件回调 - 'hook_shutdown' => function (Server $server) { }, + 'hook_shutdown' => function (Server $server) { + }, // 管理进程启动事件回调 - 'hook_manager_start' => function (Server $server) { }, + 'hook_manager_start' => function (Server $server) { + }, // 管理进程停止事件回调 - 'hook_manager_stop' => function (Server $server) { }, + 'hook_manager_stop' => function (Server $server) { + }, // 工作进程启动事件回调 - 'hook_worker_start' => function (Server $server, int $worker_id) { }, + 'hook_worker_start' => function (Server $server, int $worker_id) { + }, // 工作进程停止事件回调 - 'hook_worker_stop' => function (Server $server, int $workerId) { }, + 'hook_worker_stop' => function (Server $server, int $workerId) { + }, // 工作进程错误事件(onWorkerError)回调 - 'hook_worker_error' => function (Server $server, int $workerId, int $workerPid, int $exitCode, int $signal) { }, + 'hook_worker_error' => function (Server $server, int $workerId, int $workerPid, int $exitCode, int $signal) { + }, // 工作进程退出事件(onWorkerExit)回调 - 'hook_worker_exit' => function (Server $server, int $workerId) { }, + 'hook_worker_exit' => function (Server $server, int $workerId) { + }, // 请求成功(onRequestSuccess)回调 - 'hook_request_success' => function (Server $server, Request $request) { }, + 'hook_request_success' => function (Server $server, Request $request) { + }, // 请求错误(onRequestException)回调 - 'hook_request_error' => function (Server $server, Request $request) { }, + 'hook_request_error' => function (Server $server, Request $request) { + }, ], // 用户自定义进程 (用于常驻的任务清理,将会使用Server->addProcess添加到Server diff --git a/framework/Base/BaseObject.php b/framework/Base/BaseObject.php index 1f3fa65..2341b4e 100644 --- a/framework/Base/BaseObject.php +++ b/framework/Base/BaseObject.php @@ -7,7 +7,6 @@ */ abstract class BaseObject implements StaticInstanceInterface { - use StaticInstanceTrait; // 构造 @@ -43,5 +42,4 @@ public function onInitialize() public function onDestruct() { } - } diff --git a/framework/Base/Component.php b/framework/Base/Component.php index 0a184b2..e1f8b78 100644 --- a/framework/Base/Component.php +++ b/framework/Base/Component.php @@ -5,7 +5,7 @@ /** * 组件基类 */ -abstract class Component extends BaseObject implements ComponentInterface +abstract class Component extends BaseObject implements ComponentInterface { // 状态 @@ -34,5 +34,4 @@ public function onRequestAfter() { $this->setStatus(ComponentInterface::STATUS_READY); } - } diff --git a/framework/Base/ComponentInterface.php b/framework/Base/ComponentInterface.php index 35fad33..2df4463 100644 --- a/framework/Base/ComponentInterface.php +++ b/framework/Base/ComponentInterface.php @@ -27,5 +27,4 @@ public function onRequestBefore(); // 请求后置事件 public function onRequestAfter(); - } diff --git a/framework/Base/ComponentTrait.php b/framework/Base/ComponentTrait.php index b111adb..baa9fdb 100644 --- a/framework/Base/ComponentTrait.php +++ b/framework/Base/ComponentTrait.php @@ -34,5 +34,4 @@ public function onRequestAfter() { $this->setStatus(ComponentInterface::STATUS_READY); } - } diff --git a/framework/Base/Process.php b/framework/Base/Process.php index 5f15005..1747d85 100644 --- a/framework/Base/Process.php +++ b/framework/Base/Process.php @@ -8,10 +8,8 @@ namespace Rid\Base; - class Process implements StaticInstanceInterface { - use StaticInstanceTrait; private $sleep_time; @@ -19,12 +17,10 @@ class Process implements StaticInstanceInterface public function init() { - } public function run() { - } /** @@ -65,7 +61,11 @@ final public function start($config) private function disablePdoAndRedisRecord() { - if (in_array('pdo', $this->_config['components'])) app()->pdo->setRecordData(false); - if (in_array('redis', $this->_config['components'])) app()->redis->setRecordData(false); + if (in_array('pdo', $this->_config['components'])) { + app()->pdo->setRecordData(false); + } + if (in_array('redis', $this->_config['components'])) { + app()->redis->setRecordData(false); + } } } diff --git a/framework/Base/StaticInstanceInterface.php b/framework/Base/StaticInstanceInterface.php index 84f5ab8..215959a 100644 --- a/framework/Base/StaticInstanceInterface.php +++ b/framework/Base/StaticInstanceInterface.php @@ -21,5 +21,4 @@ public static function new(...$args); * @return $this */ public static function newInstanceByConfig($name); - } diff --git a/framework/Base/StaticInstanceTrait.php b/framework/Base/StaticInstanceTrait.php index b19660c..9829d34 100644 --- a/framework/Base/StaticInstanceTrait.php +++ b/framework/Base/StaticInstanceTrait.php @@ -33,5 +33,4 @@ public static function newInstanceByConfig($name) } return $object; } - } diff --git a/framework/Base/Timer.php b/framework/Base/Timer.php index 6a62e4d..d616a6b 100644 --- a/framework/Base/Timer.php +++ b/framework/Base/Timer.php @@ -8,7 +8,6 @@ namespace Rid\Base; - /** * Class Timer * @package Rid\Core diff --git a/framework/Component/Config.php b/framework/Component/Config.php index bf7042e..6e6eb3d 100644 --- a/framework/Component/Config.php +++ b/framework/Component/Config.php @@ -40,24 +40,33 @@ public function get(string $name) { // First Check config stored in Swoole Table. If it exist , then just return the cached key if (false === $setting_row = $this->cacheTable->get($name)) { - if (strpos($name, 'runtime.') === 0) return false; // Deal with config with prefix `runtime.` - if (strpos($name, 'route.') === 0) return 1; // Deal with config with prefix `route.` + if (strpos($name, 'runtime.') === 0) { + return false; + } // Deal with config with prefix `runtime.` + if (strpos($name, 'route.') === 0) { + return 1; + } // Deal with config with prefix `route.` // Get config From Database $setting_row = app()->pdo->createCommand('SELECT `name`, `value`, `type` from `site_config` WHERE `name` = :name') ->bindParams(['name' => $name])->queryOne(); // In this case (Load config From Database Failed) , A Exception should throw - if ($setting_row === false) + if ($setting_row === false) { throw new ConfigException(sprintf('Dynamic Setting "%s" couldn\'t be found.', $name)); + } $this->load($setting_row); } $setting = $setting_row['value']; // Type String - if ($setting_row['type'] == 'json') $setting = json_decode($setting,true); - elseif ($setting_row['type'] == 'int') $setting = (int) $setting; - elseif ($setting_row['type'] == 'bool') $setting = (bool) $setting; + if ($setting_row['type'] == 'json') { + $setting = json_decode($setting, true); + } elseif ($setting_row['type'] == 'int') { + $setting = (int) $setting; + } elseif ($setting_row['type'] == 'bool') { + $setting = (bool) $setting; + } return $setting; } @@ -66,7 +75,9 @@ public function getSection($prefix = null) { $settings = []; foreach ($this->cacheTable as $k => $v) { - if (!is_null($prefix) && strpos($k, $prefix) !== 0) continue; + if (!is_null($prefix) && strpos($k, $prefix) !== 0) { + continue; + } $settings[$k] = $this->get($k); } return $settings; @@ -97,7 +108,8 @@ public function flush($name) public function setMultiple(array $config_array) { - foreach ($config_array as $key => $value) + foreach ($config_array as $key => $value) { $this->set($key, $value); + } } } diff --git a/framework/Component/I18n.php b/framework/Component/I18n.php index 97c94ba..2dfe367 100644 --- a/framework/Component/I18n.php +++ b/framework/Component/I18n.php @@ -13,7 +13,6 @@ class I18n extends Component { - public $loader = []; public $resources = []; @@ -89,18 +88,22 @@ public function onInitialize() private function getUserLang() { // Return Cache value - if (!is_null($this->_user_lang)) return $this->_user_lang; + if (!is_null($this->_user_lang)) { + return $this->_user_lang; + } // Determine $judged_langs = array(); // 1nd highest priority: GET parameter 'lang' - if (!is_null(app()->request->get('lang'))) + if (!is_null(app()->request->get('lang'))) { $judged_langs[] = app()->request->get('lang'); + } // 2rd highest priority: user setting for login user - if (app()->auth->getCurUser() && !is_null(app()->auth->getCurUser()->getLang())) + if (app()->auth->getCurUser() && !is_null(app()->auth->getCurUser()->getLang())) { $judged_langs[] = app()->auth->getCurUser()->getLang(); + } // 3th highest priority: HTTP_ACCEPT_LANGUAGE if (!is_null(app()->request->header('accept_language'))) { @@ -120,7 +123,9 @@ function ($res, $el) { list($l, $q) = array_merge(explode(';q=', $el), [1]); $res[$l] = (float)$q; return $res; - }, []); + }, + [] + ); arsort($prefLocales); foreach ($prefLocales as $part => $q) { @@ -152,7 +157,6 @@ function ($res, $el) { */ public function trans($string, $args = [], $domain = null, $required_lang = null) { - $local = $this->forcedLang ?? // Highest priority: forced language $required_lang ?? // 1st highest priority: required language diff --git a/framework/Component/Log.php b/framework/Component/Log.php index 5916bcd..e094dc3 100644 --- a/framework/Component/Log.php +++ b/framework/Component/Log.php @@ -109,5 +109,4 @@ protected function getMessage($message, array $context = []) $message = "[time] {$time} [message] {$message}"; return $message; } - } diff --git a/framework/Database/BasePDOConnection.php b/framework/Database/BasePDOConnection.php index cf74306..6544c13 100644 --- a/framework/Database/BasePDOConnection.php +++ b/framework/Database/BasePDOConnection.php @@ -204,7 +204,9 @@ protected function prepare() // 清扫预处理数据 protected function clearPrepare() { - if ($this->_recordData) $this->_sqlExecuteData[] = $this->getRawSql(); + if ($this->_recordData) { + $this->_sqlExecuteData[] = $this->getRawSql(); + } $this->_sql = ''; $this->_params = []; $this->_values = []; @@ -427,7 +429,8 @@ public function getRawSql() return array_shift($sqlPrepareData); } - public function getExecuteData() { + public function getExecuteData() + { return $this->_sqlExecuteData; } diff --git a/framework/Database/MasterSlave/BasePDOConnection.php b/framework/Database/MasterSlave/BasePDOConnection.php index 7cc25e4..c88bb81 100644 --- a/framework/Database/MasterSlave/BasePDOConnection.php +++ b/framework/Database/MasterSlave/BasePDOConnection.php @@ -94,5 +94,4 @@ public function beginTransaction() $this->selectMaster(); parent::beginTransaction(); } - } diff --git a/framework/Database/MasterSlave/PDOConnection.php b/framework/Database/MasterSlave/PDOConnection.php index ffbc2ca..98e4e46 100644 --- a/framework/Database/MasterSlave/PDOConnection.php +++ b/framework/Database/MasterSlave/PDOConnection.php @@ -23,5 +23,4 @@ public function onDestruct() // 关闭连接 $this->disconnect(); } - } diff --git a/framework/Database/PDOConnection.php b/framework/Database/PDOConnection.php index 5348ed3..c61b493 100644 --- a/framework/Database/PDOConnection.php +++ b/framework/Database/PDOConnection.php @@ -23,5 +23,4 @@ public function onDestruct() // 关闭连接 $this->disconnect(); } - } diff --git a/framework/Database/Persistent/BasePDOConnection.php b/framework/Database/Persistent/BasePDOConnection.php index 8dea094..ac710a8 100644 --- a/framework/Database/Persistent/BasePDOConnection.php +++ b/framework/Database/Persistent/BasePDOConnection.php @@ -103,5 +103,4 @@ protected static function isDisconnectException(\Throwable $e) } return false; } - } diff --git a/framework/Database/Persistent/PDOConnection.php b/framework/Database/Persistent/PDOConnection.php index 575a259..cd6dc98 100644 --- a/framework/Database/Persistent/PDOConnection.php +++ b/framework/Database/Persistent/PDOConnection.php @@ -15,5 +15,4 @@ public function onDestruct() // 关闭连接 $this->disconnect(); } - } diff --git a/framework/Exceptions/ErrorException.php b/framework/Exceptions/ErrorException.php index 3e4eef3..4288122 100644 --- a/framework/Exceptions/ErrorException.php +++ b/framework/Exceptions/ErrorException.php @@ -18,5 +18,4 @@ public function __construct($type, $message, $file, $line) // 父类构造 parent::__construct(); } - } diff --git a/framework/Helpers/FileSystemHelper.php b/framework/Helpers/FileSystemHelper.php index aa31d05..26afe1d 100644 --- a/framework/Helpers/FileSystemHelper.php +++ b/framework/Helpers/FileSystemHelper.php @@ -25,5 +25,4 @@ public static function basename($path) } return str_replace('/', '\\', basename(str_replace('\\', '/', $path))); } - } diff --git a/framework/Helpers/JWTHelper.php b/framework/Helpers/JWTHelper.php index 3b9b03d..61942b2 100644 --- a/framework/Helpers/JWTHelper.php +++ b/framework/Helpers/JWTHelper.php @@ -19,7 +19,7 @@ public static function encode($payload, $key = null) return JWT::encode($payload, $key ?? sha1(env('APP_SECRET_KEY'))); } - public static function decode(string $jwt,string $key = null, array $allowed_algs = array(), $allow_exp = false) + public static function decode(string $jwt, string $key = null, array $allowed_algs = array(), $allow_exp = false) { try { $payload = (array) JWT::decode($jwt, $key ?? sha1(env('APP_SECRET_KEY')), $allowed_algs ?: ['HS256']); // jwt data in array diff --git a/framework/Helpers/NameHelper.php b/framework/Helpers/NameHelper.php index 0b0d6c6..8814755 100644 --- a/framework/Helpers/NameHelper.php +++ b/framework/Helpers/NameHelper.php @@ -27,5 +27,4 @@ public static function camelToSnake($name, $separator = '_') } return $name; } - } diff --git a/framework/Helpers/ProcessHelper.php b/framework/Helpers/ProcessHelper.php index 78ffc64..7fb0176 100644 --- a/framework/Helpers/ProcessHelper.php +++ b/framework/Helpers/ProcessHelper.php @@ -67,5 +67,4 @@ public static function readPidFile($pidFile) } return false; } - } diff --git a/framework/Helpers/StringHelper.php b/framework/Helpers/StringHelper.php index af13643..9cc06f2 100644 --- a/framework/Helpers/StringHelper.php +++ b/framework/Helpers/StringHelper.php @@ -13,7 +13,7 @@ class StringHelper * @param string $chars * @return string */ - public static function getRandomString($length , $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz') + public static function getRandomString($length, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz') { $last = 61; $str = ''; diff --git a/framework/Helpers/SystemInfoHelper.php b/framework/Helpers/SystemInfoHelper.php index f728261..6973d9a 100644 --- a/framework/Helpers/SystemInfoHelper.php +++ b/framework/Helpers/SystemInfoHelper.php @@ -81,7 +81,9 @@ public static function getIdlePercent(): float { if (is_readable('/proc/cpuinfo') && is_readable('/proc/uptime')) { $processors = self::getProcessor(); - if ($processors == 0) return 0; + if ($processors == 0) { + return 0; + } [$uptime, $idle] = explode(' ', file_get_contents('/proc/uptime')); return (float)$idle / ((float)$uptime * $processors); diff --git a/framework/Http/Application.php b/framework/Http/Application.php index e4d435b..e08024b 100644 --- a/framework/Http/Application.php +++ b/framework/Http/Application.php @@ -201,5 +201,4 @@ public function setServ(Server $serv): void { $this->_serv = $serv; } - } diff --git a/framework/Http/BaseRequest.php b/framework/Http/BaseRequest.php index 3226cd6..9c54e26 100644 --- a/framework/Http/BaseRequest.php +++ b/framework/Http/BaseRequest.php @@ -7,13 +7,11 @@ use Rid\Utils\HeaderUtils; use Rid\Utils\IpUtils; - /** * Request组件基类 */ class BaseRequest extends Component { - const HEADER_FORWARDED = 0b00001; // When using RFC 7239 const HEADER_X_FORWARDED_FOR = 0b00010; const HEADER_X_FORWARDED_HOST = 0b00100; @@ -222,7 +220,8 @@ public function scheme() * @see getClientIps() * @see http://en.wikipedia.org/wiki/X-Forwarded-For */ - public function getClientIp() { + public function getClientIp() + { $ipAddresses = $this->getClientIps(); return $ipAddresses[0]; } @@ -249,7 +248,6 @@ public function getClientIps() } return $this->getTrustedValues(self::HEADER_X_FORWARDED_FOR, $ip) ?: array($ip); - } public function isFromTrustedProxy() diff --git a/framework/Http/BaseResponse.php b/framework/Http/BaseResponse.php index cd2c7d2..1993d12 100644 --- a/framework/Http/BaseResponse.php +++ b/framework/Http/BaseResponse.php @@ -45,7 +45,8 @@ public function setStatusCode($code) $this->statusCode = $code; } - public function setContent($content) { + public function setContent($content) + { $this->content = $content; } @@ -86,5 +87,4 @@ protected function prepare() } $this->content = $content; } - } diff --git a/framework/Http/Captcha.php b/framework/Http/Captcha.php index e4b0993..448dd9a 100644 --- a/framework/Http/Captcha.php +++ b/framework/Http/Captcha.php @@ -73,5 +73,4 @@ public function getContent() { return $this->_content; } - } diff --git a/framework/Http/Cookie.php b/framework/Http/Cookie.php index bce5ceb..3eb443a 100644 --- a/framework/Http/Cookie.php +++ b/framework/Http/Cookie.php @@ -57,5 +57,4 @@ public function clear() } return true; } - } diff --git a/framework/Http/Error.php b/framework/Http/Error.php index cb8debf..93cf6bc 100644 --- a/framework/Http/Error.php +++ b/framework/Http/Error.php @@ -85,5 +85,4 @@ public function handleException(\Throwable $e) println((PHP_EOL . PHP_EOL) . $message . (PHP_EOL)); } } - } diff --git a/framework/Http/HttpServer.php b/framework/Http/HttpServer.php index b7d25c1..198c2d5 100644 --- a/framework/Http/HttpServer.php +++ b/framework/Http/HttpServer.php @@ -15,7 +15,6 @@ */ class HttpServer { - public $name = 'rid-httpd'; // 运行参数 @@ -150,7 +149,9 @@ public function onWorkerStart(\Swoole\Http\Server $server, int $workerId) { // 刷新OpCode缓存,防止reload重载入时受到影响 foreach (['apc_clear_cache', 'opcache_reset'] as $func) { - if (function_exists($func)) $func(); + if (function_exists($func)) { + $func(); + } } // 进程命名 @@ -248,8 +249,9 @@ private function addCustomProcess() $custom_process = new $process_class(); if ($custom_process instanceof Process) { $process = new \Swoole\Process(function ($process) use ($process_name, $process_config, $custom_process) { - - if ($process_config['title']) ProcessHelper::setTitle('rid-httpd: ' . $process_config['title']); + if ($process_config['title']) { + ProcessHelper::setTitle('rid-httpd: ' . $process_config['title']); + } // FIXME 实例化App $config = require $this->_config['configFile']; @@ -283,5 +285,4 @@ protected function welcome() println('Config File: ' . $this->_config['configFile']); println('───────────────────────────────────────'); } - } diff --git a/framework/Http/Image.php b/framework/Http/Image.php index d3e199d..041d1cd 100644 --- a/framework/Http/Image.php +++ b/framework/Http/Image.php @@ -191,5 +191,4 @@ public function saveAs($filename) $imageSave = $this->switchExecute('SAVE'); $imageSave($this->image, $filename); } - } diff --git a/framework/Http/Request.php b/framework/Http/Request.php index 7d9d2cb..4f700af 100644 --- a/framework/Http/Request.php +++ b/framework/Http/Request.php @@ -33,5 +33,4 @@ public function getRawBody() { return $this->_requester->rawContent(); } - } diff --git a/framework/Http/Response.php b/framework/Http/Response.php index 7a91dcd..d7a3512 100644 --- a/framework/Http/Response.php +++ b/framework/Http/Response.php @@ -84,5 +84,4 @@ public function getResponderStatus() { return isset($this->_responder); } - } diff --git a/framework/Http/Route.php b/framework/Http/Route.php index 64ec1a5..7eb8026 100644 --- a/framework/Http/Route.php +++ b/framework/Http/Route.php @@ -115,5 +115,4 @@ public function match($action) } return $result; } - } diff --git a/framework/Http/Session.php b/framework/Http/Session.php index 9c6fca0..22c24e3 100644 --- a/framework/Http/Session.php +++ b/framework/Http/Session.php @@ -71,7 +71,9 @@ public function loadSessionId() } $this->_sessionKey = $this->saveKeyPrefix . $this->_sessionId; - if (!$this->_isNewSession) app()->redis->expire($this->_sessionKey, $this->maxLifetime); // 延长session有效期 + if (!$this->_isNewSession) { + app()->redis->expire($this->_sessionKey, $this->maxLifetime); + } // 延长session有效期 } // 创建SessionId @@ -118,7 +120,8 @@ public function delete($name) } // 取值后删除 - public function pop($name) { + public function pop($name) + { $value = $this->get($name); $this->delete($name); return $value; diff --git a/framework/Http/UploadFile.php b/framework/Http/UploadFile.php index 9f3c8e5..6c5c9f4 100644 --- a/framework/Http/UploadFile.php +++ b/framework/Http/UploadFile.php @@ -2,7 +2,6 @@ namespace Rid\Http; - /** * UploadFile类 */ @@ -62,7 +61,8 @@ public function getBaseName($suffix = null) return $this->name; } - public function getFileName(){ + public function getFileName() + { return pathinfo($this->name)['filename']; } diff --git a/framework/Redis/BaseRedisConnection.php b/framework/Redis/BaseRedisConnection.php index ea7acc8..2a88188 100644 --- a/framework/Redis/BaseRedisConnection.php +++ b/framework/Redis/BaseRedisConnection.php @@ -289,13 +289,14 @@ protected function autoConnect() // 执行命令 public function __call($name, $arguments) { - $this->autoConnect(); // 自动连接 if ($this->_recordData) { $arg_text = ''; foreach ($arguments as $arg) { - if (!is_string($arg)) $arg = '[Array]'; + if (!is_string($arg)) { + $arg = '[Array]'; + } $arg_text .= ' ' . $arg; } diff --git a/framework/Redis/Persistent/BaseRedisConnection.php b/framework/Redis/Persistent/BaseRedisConnection.php index 6b2d70e..71c567f 100644 --- a/framework/Redis/Persistent/BaseRedisConnection.php +++ b/framework/Redis/Persistent/BaseRedisConnection.php @@ -49,5 +49,4 @@ protected static function isDisconnectException(\Throwable $e) } return false; } - } diff --git a/framework/Redis/Persistent/RedisConnection.php b/framework/Redis/Persistent/RedisConnection.php index 12d1a46..15fd4ca 100644 --- a/framework/Redis/Persistent/RedisConnection.php +++ b/framework/Redis/Persistent/RedisConnection.php @@ -15,5 +15,4 @@ public function onDestruct() // 关闭连接 $this->disconnect(); } - } diff --git a/framework/Redis/RedisConnection.php b/framework/Redis/RedisConnection.php index 36e834f..b1f6562 100644 --- a/framework/Redis/RedisConnection.php +++ b/framework/Redis/RedisConnection.php @@ -23,5 +23,4 @@ public function onDestruct() // 关闭连接 $this->disconnect(); } - } diff --git a/framework/Utils/AttributesImportUtils.php b/framework/Utils/AttributesImportUtils.php index 8d288de..3fed6e7 100644 --- a/framework/Utils/AttributesImportUtils.php +++ b/framework/Utils/AttributesImportUtils.php @@ -8,7 +8,6 @@ namespace Rid\Utils; - trait AttributesImportUtils { public function importAttributes($config) diff --git a/framework/Utils/ClassValueCacheUtils.php b/framework/Utils/ClassValueCacheUtils.php index e2603bc..630779d 100644 --- a/framework/Utils/ClassValueCacheUtils.php +++ b/framework/Utils/ClassValueCacheUtils.php @@ -8,10 +8,8 @@ namespace Rid\Utils; - trait ClassValueCacheUtils { - protected function getCacheNameSpace(): string { return 'Cache:default'; @@ -29,5 +27,4 @@ final protected function getCacheValue($key, $closure) } return $this->$key; } - } diff --git a/framework/Utils/IpUtils.php b/framework/Utils/IpUtils.php index 49fb493..eac084c 100644 --- a/framework/Utils/IpUtils.php +++ b/framework/Utils/IpUtils.php @@ -160,7 +160,9 @@ public static function isEndPoint($raw_ip) if ($data) { $ip = filter_var($data[1], FILTER_VALIDATE_IP | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE); $port = $data[2]; - if ($ip && $port) return ["ip" => $ip, "port" => $port]; + if ($ip && $port) { + return ["ip" => $ip, "port" => $port]; + } } return false; } diff --git a/framework/Validators/CaptchaTrait.php b/framework/Validators/CaptchaTrait.php index 4a645e9..ae5ce54 100644 --- a/framework/Validators/CaptchaTrait.php +++ b/framework/Validators/CaptchaTrait.php @@ -16,7 +16,7 @@ * Trait CaptchaTrait * @package Rid\Validators */ -Trait CaptchaTrait +trait CaptchaTrait { public $captcha; diff --git a/framework/Validators/CsrfTrait.php b/framework/Validators/CsrfTrait.php index c8a686d..efb037d 100644 --- a/framework/Validators/CsrfTrait.php +++ b/framework/Validators/CsrfTrait.php @@ -8,7 +8,6 @@ namespace Rid\Validators; - trait CsrfTrait { public $csrf; diff --git a/framework/Validators/Pagination.php b/framework/Validators/Pagination.php index 09f48ab..8f58e63 100644 --- a/framework/Validators/Pagination.php +++ b/framework/Validators/Pagination.php @@ -8,7 +8,6 @@ namespace Rid\Validators; - class Pagination extends Validator { use PaginationTrait; diff --git a/framework/Validators/PaginationTrait.php b/framework/Validators/PaginationTrait.php index b617e15..d24ced8 100644 --- a/framework/Validators/PaginationTrait.php +++ b/framework/Validators/PaginationTrait.php @@ -8,8 +8,7 @@ namespace Rid\Validators; - -Trait PaginationTrait +trait PaginationTrait { public $page; public $limit; // pecPage @@ -102,8 +101,12 @@ public function getTotal(): int protected function checkPager() { $limit = intval($this->getInput('limit', static::getDefaultLimit())); - if ($limit < static::getMinLimit()) $limit = static::getMinLimit(); - if ($limit > static::getMaxLimit()) $limit = static::getMaxLimit(); + if ($limit < static::getMinLimit()) { + $limit = static::getMinLimit(); + } + if ($limit > static::getMaxLimit()) { + $limit = static::getMaxLimit(); + } $page = intval($this->getInput('page', static::getDefaultPage())); $this->setInput(['limit' => $limit, 'page' => $page]); @@ -112,14 +115,19 @@ protected function checkPager() $this->offset = ($page - 1) * $limit; // Quick return empty array when offset is much bigger than total, So we needn't hit remote or local data - if ($this->offset > $this->total) $this->pager_data = []; + if ($this->offset > $this->total) { + $this->pager_data = []; + } } final private function getDataTotal(): int { if (is_null($this->pager_data_total)) { - if (static::getDataSource() == 'remote') $this->pager_data_total = $this->getRemoteTotal(); - else $this->pager_data_total = count($this->getInput('data', [])); + if (static::getDataSource() == 'remote') { + $this->pager_data_total = $this->getRemoteTotal(); + } else { + $this->pager_data_total = count($this->getInput('data', [])); + } } return $this->pager_data_total; } @@ -132,8 +140,11 @@ protected function getRemoteTotal(): int final public function getPagerData(): array { if (is_null($this->pager_data)) { - if (static::getDataSource() == 'remote') $this->pager_data = $this->getRemoteData(); - else $this->pager_data = array_slice($this->getInput('data', []), $this->offset, $this->limit); + if (static::getDataSource() == 'remote') { + $this->pager_data = $this->getRemoteData(); + } else { + $this->pager_data = array_slice($this->getInput('data', []), $this->offset, $this->limit); + } } return $this->pager_data; } diff --git a/framework/Validators/Validator.php b/framework/Validators/Validator.php index 5514e0a..fb49566 100644 --- a/framework/Validators/Validator.php +++ b/framework/Validators/Validator.php @@ -68,7 +68,9 @@ private function validateCallbackRules() { foreach (static::callbackRules() as $rule) { call_user_func([$this, $rule]); - if (!$this->_success) break; + if (!$this->_success) { + break; + } } } @@ -99,10 +101,13 @@ final public function setFileInput($config) */ final public function getInput($key = null, $default = null) { - if (is_null($key)) return $this->_input; + if (is_null($key)) { + return $this->_input; + } - if (in_array($key, $this->_file_input_name)) + if (in_array($key, $this->_file_input_name)) { return new UploadFile($this->_input[$key]); + } return $this->_input[$key] ?? $default; } @@ -137,9 +142,15 @@ final protected function releaseDataToProperties() private function autoloadDataFromRequests() { if ($this->_autoload) { - if (in_array('get', $this->_autoload_from)) $this->setInput(app()->request->get()); - if (in_array('post', $this->_autoload_from)) $this->setInput(app()->request->post()); - if (in_array('files', $this->_autoload_from)) $this->setFileInput(app()->request->files()); + if (in_array('get', $this->_autoload_from)) { + $this->setInput(app()->request->get()); + } + if (in_array('post', $this->_autoload_from)) { + $this->setInput(app()->request->post()); + } + if (in_array('files', $this->_autoload_from)) { + $this->setFileInput(app()->request->files()); + } } } @@ -153,8 +164,12 @@ public function validate(): bool $this->_success = $this->_validator->validate($this->_input); $this->_errors = $this->_validator->getMessages(); - if ($this->_success) $this->validateCallbackRules(); // Valid callback rules - if ($this->_success) $this->releaseDataToProperties(); // release validate data to class properties which is type if public when valid success + if ($this->_success) { + $this->validateCallbackRules(); + } // Valid callback rules + if ($this->_success) { + $this->releaseDataToProperties(); + } // release validate data to class properties which is type if public when valid success $this->buildDefaultPropAfterValid(); @@ -167,7 +182,9 @@ public function getErrors(): array foreach ($this->_errors as $key => $error) { $msg = ''; if (is_array($error)) { - foreach ($error as $value) $msg .= $value . '; '; + foreach ($error as $value) { + $msg .= $value . '; '; + } } else { $msg = $error; } @@ -189,6 +206,4 @@ public function flush() { throw new \RuntimeException('No flush function exist'); } - - } diff --git a/framework/View/Conversion.php b/framework/View/Conversion.php index 59fe0a1..370e6b3 100644 --- a/framework/View/Conversion.php +++ b/framework/View/Conversion.php @@ -16,7 +16,6 @@ class Conversion implements ExtensionInterface { - public function register(Engine $engine) { $engine->registerFunction('format_bytes', [$this, 'format_bytes']); @@ -28,7 +27,9 @@ public function register(Engine $engine) public static function setDefault(&$array, $defaults) { - if (!is_array($array)) $array = [$array]; + if (!is_array($array)) { + $array = [$array]; + } foreach ($defaults as $key => $default) { if (!array_key_exists($key, $array)) { $array[$key] = $default; @@ -79,7 +80,6 @@ public function format_ubbcode($var) public function sec2hms($sec, $padHours = false) { - $hms = ''; $hours = intval(intval($sec) / 3600); diff --git a/framework/functions.php b/framework/functions.php index 0abf92e..e1f3d33 100644 --- a/framework/functions.php +++ b/framework/functions.php @@ -23,7 +23,9 @@ function app($prefix = null) */ function env($name = null, $default = '') { - if ($name === null) return $_ENV; + if ($name === null) { + return $_ENV; + } return $_ENV[$name] ?? $default; } } @@ -53,7 +55,9 @@ function println($expression) if (!function_exists('array_set_default')) { function array_set_default(&$array, $defaults) { - if (!is_array($array)) $array = [$array]; + if (!is_array($array)) { + $array = [$array]; + } foreach ($defaults as $key => $default) { if (!array_key_exists($key, $array)) { $array[$key] = $default; @@ -63,7 +67,8 @@ function array_set_default(&$array, $defaults) } if (!function_exists('input2array')) { - function input2array($input) { + function input2array($input) + { return is_array($input) ? $input : [$input]; } } diff --git a/templates/auth/login.php b/templates/auth/login.php index 3d79f75..435a2a7 100644 --- a/templates/auth/login.php +++ b/templates/auth/login.php @@ -36,7 +36,7 @@
+ placeholder="" value="e(app()->request->post('username', '')) ?>">
@@ -67,7 +67,7 @@ Advanced Options
- 'disabled' ; 0 - option -> '' ; 1 - option but default checked -> 'checked' ; 2 - force -> 'checked disabled' ?> + 'disabled' ; 0 - option -> '' ; 1 - option but default checked -> 'checked' ; 2 - force -> 'checked disabled'?>
0): ?>checked @@ -78,7 +78,7 @@
0): ?>checked - disabled + disabled >
diff --git a/templates/helper/torrent_table.php b/templates/helper/torrent_table.php index 20a88ad..58a15bf 100644 --- a/templates/helper/torrent_table.php +++ b/templates/helper/torrent_table.php @@ -33,11 +33,11 @@ getCategory(); ?> - tag with classname ?> + tag with classname?> <?= $cat['name'] ?> - tag with classname ?> + tag with classname?>
- + @@ -72,8 +72,8 @@
getComments() ?> - batch($torrent->getTorrentSize(),'format_bytes_compact') ?> - + batch($torrent->getTorrentSize(), 'format_bytes_compact') ?> + getComplete()) ?> getIncomplete()) ?> diff --git a/templates/helper/username.php b/templates/helper/username.php index 8da23c1..a7320ad 100644 --- a/templates/helper/username.php +++ b/templates/helper/username.php @@ -12,9 +12,9 @@ $hide = $hide ?? false; $show_badge = $show_badge ?? false; ?> - + (orphaned) - + Anonymous auth->getCurUser()->isPrivilege('see_anonymous_info')): ?> (insert('helper/username', ['user' => $user, 'hide' => false, 'user_badge' => $show_badge]) ?>) diff --git a/templates/index.php b/templates/index.php index f5fa497..8daef94 100644 --- a/templates/index.php +++ b/templates/index.php @@ -46,7 +46,7 @@
-
batch($new['body'],'format_ubbcode'); ?>
+
batch($new['body'], 'format_ubbcode'); ?>
diff --git a/templates/layout/base.php b/templates/layout/base.php index 3b0f47c..81f7e91 100644 --- a/templates/layout/base.php +++ b/templates/layout/base.php @@ -89,7 +89,7 @@

[ Page created in request->start_at, 6) ?> sec - with e(memory_get_usage(),'format_bytes') ?> ram used, + with e(memory_get_usage(), 'format_bytes') ?> ram used, pdo->getExecuteData()) ?> db queries, redis->getCalledData())?> calls of Redis ] diff --git a/templates/layout/nav_user.php b/templates/layout/nav_user.php index d8e419a..2b3a0a7 100644 --- a/templates/layout/nav_user.php +++ b/templates/layout/nav_user.php @@ -11,6 +11,7 @@ $user = app()->auth->getCurUser(); use App\Repository\User\UserRole; + ?> @@ -72,7 +73,7 @@

- Ratio: getRatio()) ? $user->getRatio() : round($user->getRatio(),3) ?> + Ratio: getRatio()) ? $user->getRatio() : round($user->getRatio(), 3) ?>   Uploaded: e($user->getUploaded(), 'format_bytes') ?> diff --git a/templates/manage/categories.php b/templates/manage/categories.php index 6e0f3a9..b2e8f5c 100644 --- a/templates/manage/categories.php +++ b/templates/manage/categories.php @@ -97,7 +97,7 @@ diff --git a/templates/rss/feed.php b/templates/rss/feed.php index cfd1cf5..06810ff 100644 --- a/templates/rss/feed.php +++ b/templates/rss/feed.php @@ -22,7 +22,7 @@ <?= addslashes($site_name . ' Torrents') ?> - ]]> + ]]> en @@ -49,7 +49,7 @@ getId() . '&cmtpage=0#startcomments' ?>]]> getInfoHash() ?> - getAddedAt())) ?> + getAddedAt())) ?> diff --git a/templates/subtitles/search.php b/templates/subtitles/search.php index d94fc47..c96479d 100644 --- a/templates/subtitles/search.php +++ b/templates/subtitles/search.php @@ -21,7 +21,7 @@
-
Upload Subtitles - total uploaded e($search->getSubsSizeSum(),'format_bytes') ?>
+
Upload Subtitles - total uploaded e($search->getSubsSizeSum(), 'format_bytes') ?>

Rules:

@@ -53,11 +53,13 @@
- +
-
(Maximum file size: e(config('upload.max_subtitle_file_size'),'format_bytes') ?>.)
+
(Maximum file size: e(config('upload.max_subtitle_file_size'), 'format_bytes') ?>.)
@@ -152,7 +154,7 @@ e($datum['torrent_id']) ?> - e($datum['size'],'format_bytes') ?> + e($datum['size'], 'format_bytes') ?> e($datum['hits']) ?> insert('helper/username', ['user' => app()->site->getUser($datum['uppd_by']), 'hide' => $datum['anonymous']]) ?> diff --git a/templates/torrent/details.php b/templates/torrent/details.php index e6aae73..fcc34a5 100644 --- a/templates/torrent/details.php +++ b/templates/torrent/details.php @@ -54,7 +54,7 @@
- batch($torrent->getDescr() ?? '[h4]No description.[/h4]','format_ubbcode') ?> + batch($torrent->getDescr() ?? '[h4]No description.[/h4]', 'format_ubbcode') ?>
@@ -113,7 +113,7 @@ - hasNfo()): // TODO add global config key of NFO ?> + hasNfo()): // TODO add global config key of NFO?> @@ -137,7 +137,7 @@ 0) : ?> getPinnedTags(); ?> - + No tags for this torrent diff --git a/templates/torrent/edit.php b/templates/torrent/edit.php index 2db1f68..a292f07 100644 --- a/templates/torrent/edit.php +++ b/templates/torrent/edit.php @@ -12,6 +12,7 @@ $torrent = $edit->getTorrent(); use App\Repository\Torrent\TorrentStatus; + ?> layout('layout/base') ?> @@ -157,7 +158,7 @@
-
+
getHr() ? ' checked' : '' ?>>
diff --git a/templates/torrent/snatch.php b/templates/torrent/snatch.php index 530b1a1..10cd7cc 100644 --- a/templates/torrent/snatch.php +++ b/templates/torrent/snatch.php @@ -52,8 +52,8 @@ - e($snatchDetail['this_uploaded'],'format_bytes') ?>@e($snatchDetail['this_uploaded'] > 0 ? ($snatchDetail['this_uploaded'] / ($snatchDetail['seed_time'] + $snatchDetail['leech_time'])) : 0,'format_bytes') ?>/s
- e($snatchDetail['this_download'],'format_bytes') ?>@e($snatchDetail['this_download'] > 0 ? ($snatchDetail['this_download'] / $snatchDetail['leech_time']) : 0,'format_bytes') ?>/s
+ e($snatchDetail['this_uploaded'], 'format_bytes') ?>@e($snatchDetail['this_uploaded'] > 0 ? ($snatchDetail['this_uploaded'] / ($snatchDetail['seed_time'] + $snatchDetail['leech_time'])) : 0, 'format_bytes') ?>/s
+ e($snatchDetail['this_download'], 'format_bytes') ?>@e($snatchDetail['this_download'] > 0 ? ($snatchDetail['this_download'] / $snatchDetail['leech_time']) : 0, 'format_bytes') ?>/s
0): ?> diff --git a/templates/torrent/upload.php b/templates/torrent/upload.php index 1b7cdbf..d6ca3d7 100644 --- a/templates/torrent/upload.php +++ b/templates/torrent/upload.php @@ -157,7 +157,7 @@
-
+
diff --git a/templates/user/details.php b/templates/user/details.php index cebc0a9..d98127d 100644 --- a/templates/user/details.php +++ b/templates/user/details.php @@ -56,13 +56,13 @@
BT Transport
- Ratio : getRatio()) ? $user->getRatio() : round($user->getRatio(),3) ?> - ( uploaded : e(app()->auth->getCurUser()->getUploaded(),'format_bytes') ?> and downloaded : e(app()->auth->getCurUser()->getDownloaded(),'format_bytes') ?>)
- Real Ratio : getRealRatio()) ? $user->getRealRatio() : round($user->getRealRatio(),3) ?> - ( uploaded : e(app()->auth->getCurUser()->getRealUploaded(),'format_bytes') ?> and downloaded : e(app()->auth->getCurUser()->getRealDownloaded(),'format_bytes') ?>)
+ Ratio : getRatio()) ? $user->getRatio() : round($user->getRatio(), 3) ?> + ( uploaded : e(app()->auth->getCurUser()->getUploaded(), 'format_bytes') ?> and downloaded : e(app()->auth->getCurUser()->getDownloaded(), 'format_bytes') ?>)
+ Real Ratio : getRealRatio()) ? $user->getRealRatio() : round($user->getRealRatio(), 3) ?> + ( uploaded : e(app()->auth->getCurUser()->getRealUploaded(), 'format_bytes') ?> and downloaded : e(app()->auth->getCurUser()->getRealDownloaded(), 'format_bytes') ?>)
BT Time
-
Ratio : getTimeRatio(),2) ?> ( Seeding Time: getSeedtime() ?> , Leeching Time: getLeechTime() ?>)
+
Ratio : getTimeRatio(), 2) ?> ( Seeding Time: getSeedtime() ?> , Leeching Time: getLeechTime() ?>)
diff --git a/templates/user/invite.php b/templates/user/invite.php index 6f83dd6..2c93718 100644 --- a/templates/user/invite.php +++ b/templates/user/invite.php @@ -10,6 +10,7 @@ */ use App\Repository\User\UserStatus; + ?> layout('layout/base') ?> @@ -19,7 +20,7 @@

getUsername() ?>'s Invite System

- +
@@ -47,9 +48,9 @@ - batch($invitee['uploaded'],'format_bytes') ?> - batch($invitee['downloaded'],'format_bytes') ?> - + batch($invitee['uploaded'], 'format_bytes') ?> + batch($invitee['downloaded'], 'format_bytes') ?> + auth->getCurUser()->isPrivilege('invite_manual_confirm')): ?> @@ -108,7 +109,7 @@
- getId() === app()->auth->getCurUser()->getId()): // Same User, use $user as quick call ?> + getId() === app()->auth->getCurUser()->getId()): // Same User, use $user as quick call?> getInvites() + $user->getTempInvitesSum() > 0); ?>
Invite Warning!!!