Skip to content
This repository has been archived by the owner on Nov 2, 2020. It is now read-only.

Commit

Permalink
perf(Config): Add quick ref config()
Browse files Browse the repository at this point in the history
Use quick ref `config()`` of `app()->config->get()`

Signed-off-by: Rhilip <rhilipruan@gmail.com>
  • Loading branch information
Rhilip committed Jun 27, 2019
1 parent 22d69bc commit ae2a359
Show file tree
Hide file tree
Showing 27 changed files with 114 additions and 107 deletions.
2 changes: 1 addition & 1 deletion apps/components/User/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public function inBookmarkList($tid = null)
public function isPrivilege($require_class)
{
if (is_string($require_class)) {
$require_class = app()->config->get('authority.' . $require_class, false) ?: 1;
$require_class = config('authority.' . $require_class, false) ?: 1;
}

return $this->class >= $require_class;
Expand Down
2 changes: 1 addition & 1 deletion apps/controllers/AuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public function actionRecover()
public function actionLogin()
{
$test_attempts = app()->redis->hGet('SITE:fail_login_ip_count', app()->request->getClientIp()) ?: 0;
$left_attempts = app()->config->get('security.max_login_attempts') - $test_attempts;
$left_attempts = config('security.max_login_attempts') - $test_attempts;

if (app()->request->isPost()) {
$login = new UserLoginForm();
Expand Down
2 changes: 1 addition & 1 deletion apps/controllers/IndexController.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public function actionIndex()
$news = app()->redis->get('Site:recent_news');
if ($news === false) { // Get news from Database and cache it in redis
$news = app()->pdo->createCommand('SELECT * FROM news ORDER BY create_at DESC LIMIT :max')->bindParams([
'max' => app()->config->get('base.max_news_sum')
'max' => config('base.max_news_sum')
])->queryAll();
app()->redis->set('Site:recent_news', $news, 86400);
}
Expand Down
2 changes: 1 addition & 1 deletion apps/controllers/TorrentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public function actionDownload()
$tid = app()->request->get('id');

$torrent = new Torrent($tid); // If torrent is not exist or can't visit , a notfound exception will throw out........
$filename = '[' . app()->config->get('base.site_name') . ']' . $torrent->getTorrentName() . '.torrent';
$filename = '[' . config('base.site_name') . ']' . $torrent->getTorrentName() . '.torrent';

app()->response->setHeader('Content-Type', 'application/x-bittorrent');
if (strpos(app()->request->header('user-agent'), 'IE')) {
Expand Down
34 changes: 17 additions & 17 deletions apps/controllers/TrackerController.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public function actionIndex()
if (!app()->request->isGet())
throw new TrackerException(110, [":method" => app()->request->method()]);

if (!app()->config->get("base.enable_tracker_system"))
if (!config("base.enable_tracker_system"))
throw new TrackerException(100);

$this->blockClient();
Expand All @@ -69,7 +69,7 @@ public function actionIndex()
// Tracker Protocol Extension: Scrape - http://www.bittorrent.org/beps/bep_0048.html
case 'scrape':
{
if (!app()->config->get("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);
Expand All @@ -79,7 +79,7 @@ public function actionIndex()

case 'announce':
{
if (!app()->config->get("tracker.enable_announce")) throw new TrackerException(102);
if (!config("tracker.enable_announce")) throw new TrackerException(102);

$this->checkAnnounceFields($queries);
if (!env('APP_DEBUG'))
Expand Down Expand Up @@ -595,14 +595,14 @@ private function getTorrentInfo($queries, $userInfo, &$torrentInfo)
{
// 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"] < app()->config->get("authority.see_pending_torrent"))
|| $userInfo["class"] < config("authority.see_pending_torrent"))
throw new TrackerException(151, [":status" => $torrentInfo["status"]]);
break;
}
case 'banned' :
{
// For Banned Torrent , we just allow the user who's class great than your config set to connect
if ($userInfo["class"] < app()->config->get("authority.see_banned_torrent"))
if ($userInfo["class"] < config("authority.see_banned_torrent"))
throw new TrackerException(151, [":status" => $torrentInfo["status"]]);
break;
}
Expand All @@ -616,8 +616,8 @@ private function getTorrentInfo($queries, $userInfo, &$torrentInfo)
private function generateAnnounceResponse($queries, $role, $torrentInfo, &$rep_dict)
{
$rep_dict = [
"interval" => app()->config->get("tracker.interval") + rand(5, 20), // random interval to avoid BOOM
"min interval" => app()->config->get("tracker.min_interval") + rand(1, 10),
"interval" => config("tracker.interval") + rand(5, 20), // random interval to avoid BOOM
"min interval" => config("tracker.min_interval") + rand(1, 10),
"complete" => $torrentInfo["complete"],
"incomplete" => $torrentInfo["incomplete"],
"peers" => [] // By default it is a array object, only when `&compact=1` then it should be a string
Expand Down Expand Up @@ -684,9 +684,9 @@ private function lockAnnounceDuration($queries)
$lock_name = "TRACKER:tracker_announce_" . $queries["passkey"] . "_torrent_" . $queries["info_hash"] . "_peer_" . $queries["peer_id"] . "_lock";
$lock = app()->redis->get($lock_name);
if ($lock === false) {
app()->redis->setex($lock_name, app()->config->get("tracker.min_interval"), true);
app()->redis->setex($lock_name, config("tracker.min_interval"), true);
} else {
throw new TrackerException(162, [":min" => app()->config->get("tracker.min_interval")]);
throw new TrackerException(162, [":min" => config("tracker.min_interval")]);
}
}

Expand All @@ -703,7 +703,7 @@ private function checkSession($queries, $seeder, $userInfo, $torrentInfo)
$peer_unique_cache_key = 'Tracker:peer:unique_' . $userInfo["id"] . '_' . $torrentInfo["id"] . '_' . $queries["peer_id"];
if (app()->redis->exists($peer_unique_cache_key)) {
// this peer is already announce before , just expire cache key lifetime and return.
app()->redis->expire($peer_unique_cache_key, app()->config->get("tracker.interval") * 2);
app()->redis->expire($peer_unique_cache_key, config("tracker.interval") * 2);
return;
} elseif ($queries['event'] != 'stopped') {
// If session is not exist and &event!=stopped, a new session should start
Expand All @@ -713,7 +713,7 @@ private function checkSession($queries, $seeder, $userInfo, $torrentInfo)
"uid" => $userInfo["id"], "tid" => $torrentInfo["id"], "pid" => $queries["peer_id"]
])->queryScalar();
if ($self !== 0) { // True MISS
app()->redis->set($peer_unique_cache_key, true, app()->config->get("tracker.interval") * 2);
app()->redis->set($peer_unique_cache_key, true, config("tracker.interval") * 2);
return;
}

Expand All @@ -725,19 +725,19 @@ private function checkSession($queries, $seeder, $userInfo, $torrentInfo)

// Ban one torrent seeding/leech at muti-location due to your site config
if ($seeder == 'yes') { // if this peer's role is seeder
if ($selfCount >= (app()->config->get('tracker.user_max_seed')))
throw new TrackerException(160, [":count" => app()->config->get('tracker.user_max_seed')]);
if ($selfCount >= (config('tracker.user_max_seed')))
throw new TrackerException(160, [":count" => config('tracker.user_max_seed')]);
} else {
if ($selfCount >= (app()->config->get('tracker.user_max_leech')))
throw new TrackerException(161, [":count" => app()->config->get('tracker.user_max_leech')]);
if ($selfCount >= (config('tracker.user_max_leech')))
throw new TrackerException(161, [":count" => config('tracker.user_max_leech')]);
}

if ($userInfo["class"] < UserInterface::ROLE_VIP) {
$ratio = (($userInfo["downloaded"] > 0) ? ($userInfo["uploaded"] / $userInfo["downloaded"]) : 1);
$gigs = $userInfo["downloaded"] / (1024 * 1024 * 1024);

// FIXME Wait System
if (app()->config->get("tracker.enable_waitsystem")) {
if (config("tracker.enable_waitsystem")) {
if ($gigs > 10) {
if ($ratio < 0.4) $wait = 24;
elseif ($ratio < 0.5) $wait = 12;
Expand All @@ -752,7 +752,7 @@ private function checkSession($queries, $seeder, $userInfo, $torrentInfo)
}

// FIXME Max SLots System
if (app()->config->get("tracker.enable_maxdlsystem")) {
if (config("tracker.enable_maxdlsystem")) {
$max = 0;
if ($gigs > 10) {
if ($ratio < 0.5) $max = 1;
Expand Down
4 changes: 2 additions & 2 deletions apps/middleware/AuthByCookiesMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public function handle($callable, \Closure $next)
} elseif ($action !== "actionLogout") {
if ($action == 'actionLogin') {
$test_count = app()->redis->hGet('SITE:fail_login_ip_count', app()->request->getClientIp()) ?: 0;
if ($test_count > app()->config->get('security.max_login_attempts')) {
if ($test_count > config('security.max_login_attempts')) {
return app()->response->setStatusCode(403);
}
}
Expand Down Expand Up @@ -62,7 +62,7 @@ public function handle($callable, \Closure $next)
*/
$route = strtolower(str_replace(['apps\\controllers\\', 'Controller'], ['', ''], $controllerName)) .
"_" . strtolower(str_replace('action', '', $action));
$required_class = app()->config->get('route.' . $route, false) ?: 1;
$required_class = config('route.' . $route, false) ?: 1;
if (app()->user->getClass(true) < $required_class) {
return app()->response->setStatusCode(403);
}
Expand Down
8 changes: 4 additions & 4 deletions apps/models/Torrent.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public function getId()
*/
public function getOwnerId()
{
if ($this->getUplver() == 'yes' and app()->user->getClass(true) < app()->config->get('authority.see_anonymous_uploader')) {
if ($this->getUplver() == 'yes' and app()->user->getClass(true) < config('authority.see_anonymous_uploader')) {
return 0;
} else {
return $this->owner_id;
Expand Down Expand Up @@ -178,16 +178,16 @@ public function getDownloadDict($encode = true)
$scheme = "https://";

$announce_suffix = "/announce?passkey=" . app()->user->getPasskey();
$dict["announce"] = $scheme . app()->config->get("base.site_tracker_url") . $announce_suffix;
$dict["announce"] = $scheme . config("base.site_tracker_url") . $announce_suffix;

/** BEP 0012 Multitracker Metadata Extension
* See more on : http://www.bittorrent.org/beps/bep_0012.html
*/
if ($muti_tracker = app()->config->get("base.site_muti_tracker_url")) {
if ($muti_tracker = config("base.site_muti_tracker_url")) {
$dict["announce-list"] = [];

// Add our main tracker into muti_tracker_list to avoid lost error....
$muti_tracker = app()->config->get("base.site_tracker_url") . "," . $muti_tracker;
$muti_tracker = config("base.site_tracker_url") . "," . $muti_tracker;

$muti_tracker_list = explode(",", $muti_tracker);
foreach (array_unique($muti_tracker_list) as $tracker) { // use array_unique to remove dupe tracker
Expand Down
10 changes: 5 additions & 5 deletions apps/models/form/TorrentUploadForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public static function inputRules()
['required'],
['Upload\Required'],
['Upload\Extension', ['allowed' => 'torrent']],
['Upload\Size', ['size' => app()->config->get("torrent.max_file_size") . 'B']]
['Upload\Size', ['size' => config("torrent.max_file_size") . 'B']]
],
'descr' => 'required',
'uplver' => [
Expand Down Expand Up @@ -118,7 +118,7 @@ protected function isValidTorrent()

public function makePrivateTorrent()
{
$this->torrent_dict['announce'] = "https://" . app()->config->get("base.site_tracker_url") . "/announce";
$this->torrent_dict['announce'] = "https://" . config("base.site_tracker_url") . "/announce";

// Remove un-need field in private torrents
unset($this->torrent_dict['announce-list']); // remove multi-tracker capability
Expand Down Expand Up @@ -146,7 +146,7 @@ public function makePrivateTorrent()

// Make it private and unique by add our source flag
$this->torrent_dict['info']['private'] = 1; // add private tracker flag
$this->torrent_dict['info']['source'] = "Powered by [" . app()->config->get("base.site_url") . "] " . app()->config->get("base.site_name");
$this->torrent_dict['info']['source'] = "Powered by [" . config("base.site_url") . "] " . config("base.site_name");

// Get info_hash on new torrent content dict['info']
$this->info_hash = pack("H*", sha1(Bencode::encode($this->torrent_dict['info'])));
Expand Down Expand Up @@ -211,9 +211,9 @@ public function flush()
private function setBuff()
{
// Add Large Buff and Random Buff
if (app()->config->get("buff.enable_large") && $this->file->size > app()->config->get("buff.large_size")) {
if (config("buff.enable_large") && $this->file->size > config("buff.large_size")) {
// TODO app()->pdo->createCommand();
} elseif (app()->config->get("buff.enable_random")) {
} elseif (config("buff.enable_random")) {
// TODO app()->pdo->createCommand();
}

Expand Down
6 changes: 3 additions & 3 deletions apps/models/form/UserInviteActionForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ private function flush_recycle() {
$msg = 'Recycle invite success!';

// Recycle or not ?
if (app()->config->get('invite.recycle_return_invite')) {
if (config('invite.recycle_return_invite')) {
if ($this->invite_info['invite_type'] == UserInviteForm::INVITE_TYPE_PERMANENT) {
app()->pdo->createCommand('UPDATE `users` SET `invites` = `invites` + 1 WHERE id = :uid')->bindParams([
'uid' => $this->invite_info['inviter_id']
Expand All @@ -135,9 +135,9 @@ private function flush_recycle() {
} elseif ($this->invite_info['invite_type'] == UserInviteForm::INVITE_TYPE_TEMPORARILY) {
app()->pdo->createCommand('INSERT INTO `user_invitations` (`user_id`,`total`,`create_at`,`expire_at`) VALUES (:uid,:total,CURRENT_TIMESTAMP,DATE_ADD(NOW(),INTERVAL :life_time SECOND ))')->bindParams([
'uid' => $this->invite_info['inviter_id'], 'total' => 1,
'life_time' => app()->config->get('invite.recycle_invite_lifetime')
'life_time' => config('invite.recycle_invite_lifetime')
])->execute();
$msg .= ' And return you a temporarily invite with ' . app()->config->get('invite.recycle_invite_lifetime') . ' seconds lifetime.';
$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');
}
}
Expand Down
8 changes: 4 additions & 4 deletions apps/models/form/UserInviteForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public static function callbackRules()

protected function isInviteSystemOpen()
{
if (app()->config->get('base.enable_invite_system') != true) {
if (config('base.enable_invite_system') != true) {
$this->buildCallbackFailMsg('InviteSystemOpen', 'The invite system isn\'t open in this site.');
}
}
Expand Down Expand Up @@ -91,8 +91,8 @@ protected function checkInviteInterval()
{
if (!app()->user->isPrivilege('pass_invite_interval_check')) {
$count = app()->pdo->createCommand([
['SELECT COUNT(`id`) FROM `invite` WHERE `create_at` > DATE_SUB(NOW(),INTERVAL :wait_second SECOND) ', 'params' => ['wait_second' => app()->config->get('invite.interval')]],
['AND `used` = 0', 'if' => !app()->config->get('invite.force_interval')]
['SELECT COUNT(`id`) FROM `invite` WHERE `create_at` > DATE_SUB(NOW(),INTERVAL :wait_second SECOND) ', 'params' => ['wait_second' => config('invite.interval')]],
['AND `used` = 0', 'if' => !config('invite.force_interval')]
])->queryScalar();
if ($count > 0) {
$this->buildCallbackFailMsg('Invitation interval', 'Hit invitation interval, please wait');
Expand All @@ -117,7 +117,7 @@ private function insertInviteRecord()

app()->pdo->createCommand('INSERT INTO `invite` (`inviter_id`,`username`,`invite_type`, `hash`, `create_at`, `expire_at`) VALUES (:inviter_id,:username,:invite_type,:hash,NOW(),DATE_ADD(NOW(),INTERVAL :timeout SECOND))')->bindParams([
'inviter_id' => app()->user->getId(), 'username' => $this->username, 'invite_type' => $this->invite_type,
'hash' => $invite_hash, 'timeout' => app()->config->get('invite.timeout')
'hash' => $invite_hash, 'timeout' => config('invite.timeout')
])->execute();
}

Expand Down
6 changes: 3 additions & 3 deletions apps/models/form/UserLoginForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ protected function loadUserFromPdo()
// User enable 2FA but it's code is wrong
if ($this->self["opt"]) {
try {
$tfa = new TwoFactorAuth(app()->config->get("base.site_name"));
$tfa = new TwoFactorAuth(config("base.site_name"));
if ($tfa->verifyCode($this->self["opt"], $this->opt) == false) {
$this->buildCallbackFailMsg('2FA', '2FA Validation failed. Check your device time.');
return;
Expand All @@ -113,7 +113,7 @@ protected function loadUserFromPdo()
protected function isMaxLoginIpReached()
{
$test_count = app()->redis->hGet('SITE:fail_login_ip_count', app()->request->getClientIp()) ?: 0;
if ($test_count > app()->config->get('security.max_login_attempts')) {
if ($test_count > config('security.max_login_attempts')) {
$this->buildCallbackFailMsg('Login Attempts', 'User Max Login Attempts Archived.');
return;
}
Expand All @@ -130,7 +130,7 @@ public function createUserSession()
$userId = $this->self['id'];

$exist_session_count = app()->redis->zCount($this->sessionSaveKey, $userId, $userId);
if ($exist_session_count < app()->config->get('base.max_per_user_session')) {
if ($exist_session_count < config('base.max_per_user_session')) {
/**
* SessionId Format:
* /^(?P<secure_login_flag>[01])\$(?P<ip_or_random_crc>[a-z0-9]{8})\$\w+$/
Expand Down
Loading

0 comments on commit ae2a359

Please sign in to comment.