diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index f61a35bc..35837542 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -5,7 +5,6 @@ namespace App\Http\Controllers; use Log; use Mail; use View; -use Utils; use Cache; use Cookie; use Option; @@ -44,7 +43,7 @@ class AuthController extends Controller $user = $users->get($identification, $authType); // Require CAPTCHA if user fails to login more than 3 times - $loginFailsCacheKey = sha1('login_fails_'.Utils::getClientIp()); + $loginFailsCacheKey = sha1('login_fails_'.get_client_ip()); $loginFails = (int) Cache::get($loginFailsCacheKey, 0); if ($loginFails > 3) { @@ -135,54 +134,52 @@ class AuthController extends Controller // If amount of registered accounts of IP is more than allowed amounts, // then reject the register. - if (User::where('ip', Utils::getClientIp())->count() < option('regs_per_ip')) - { - // Register a new user. - // If the email is already registered, - // it will return a false value. - $user = User::register( - $request->get('email'), - $request->get('password'), function($user) use ($request) - { - $user->ip = Utils::getClientIp(); - $user->score = option('user_initial_score'); - $user->register_at = Utils::getTimeFormatted(); - $user->last_sign_at = Utils::getTimeFormatted(time() - 86400); - $user->permission = User::NORMAL; - $user->nickname = $request->get( - option('register_with_player_name') ? 'player_name' : 'nickname' - ); - }); - - if (! $user) { - return json(trans('auth.register.registered'), 5); - } - - event(new Events\UserRegistered($user)); - - // Add player with chosen name - if (option('register_with_player_name')) { - $player = new Player; - $player->uid = $user->uid; - $player->player_name = $request->get('player_name'); - $player->preference = 'default'; - $player->last_modified = Utils::getTimeFormatted(); - $player->save(); - - event(new Events\PlayerWasAdded($player)); - } - - return json([ - 'errno' => 0, - 'msg' => trans('auth.register.success'), - 'token' => $user->getToken(), - ]) // Set cookies - ->withCookie('uid', $user->uid, 60) - ->withCookie('token', $user->getToken(), 60); - - } else { + if (User::where('ip', get_client_ip())->count() >= option('regs_per_ip')) { return json(trans('auth.register.max', ['regs' => option('regs_per_ip')]), 7); } + + // Register a new user. + // If the email is already registered, + // it will return a false value. + $user = User::register( + $request->get('email'), + $request->get('password'), function($user) use ($request) + { + $user->ip = get_client_ip(); + $user->score = option('user_initial_score'); + $user->register_at = get_datetime_string(); + $user->last_sign_at = get_datetime_string(time() - 86400); + $user->permission = User::NORMAL; + $user->nickname = $request->get( + option('register_with_player_name') ? 'player_name' : 'nickname' + ); + }); + + if (! $user) { + return json(trans('auth.register.registered'), 5); + } + + event(new Events\UserRegistered($user)); + + // Add player with chosen name + if (option('register_with_player_name')) { + $player = new Player; + $player->uid = $user->uid; + $player->player_name = $request->get('player_name'); + $player->preference = 'default'; + $player->last_modified = get_datetime_string(); + $player->save(); + + event(new Events\PlayerWasAdded($player)); + } + + return json([ + 'errno' => 0, + 'msg' => trans('auth.register.success'), + 'token' => $user->getToken(), + ]) // Set cookies + ->withCookie('uid', $user->uid, 60) + ->withCookie('token', $user->getToken(), 60); } public function forgot() @@ -204,7 +201,7 @@ class AuthController extends Controller } $rateLimit = 180; - $lastMailCacheKey = sha1('last_mail_'.Utils::getClientIp()); + $lastMailCacheKey = sha1('last_mail_'.get_client_ip()); $remain = $rateLimit + Cache::get($lastMailCacheKey, 0) - time(); // Rate limit diff --git a/app/Http/Controllers/PlayerController.php b/app/Http/Controllers/PlayerController.php index ea1236fe..c7b78e58 100644 --- a/app/Http/Controllers/PlayerController.php +++ b/app/Http/Controllers/PlayerController.php @@ -4,7 +4,6 @@ namespace App\Http\Controllers; use View; use Event; -use Utils; use Option; use App\Models\User; use App\Models\Player; @@ -79,7 +78,7 @@ class PlayerController extends Controller $player->uid = $this->user->uid; $player->player_name = $request->input('player_name'); $player->preference = "default"; - $player->last_modified = Utils::getTimeFormatted(); + $player->last_modified = get_datetime_string(); $player->save(); event(new PlayerWasAdded($player)); diff --git a/app/Http/Controllers/SetupController.php b/app/Http/Controllers/SetupController.php index 89933823..7bc94e49 100644 --- a/app/Http/Controllers/SetupController.php +++ b/app/Http/Controllers/SetupController.php @@ -4,7 +4,6 @@ namespace App\Http\Controllers; use Log; use File; -use Utils; use Schema; use Option; use Storage; @@ -101,10 +100,10 @@ class SetupController extends Controller $request->input('email'), $request->input('password'), function ($user) { - $user->ip = Utils::getClientIp(); + $user->ip = get_client_ip(); $user->score = option('user_initial_score'); - $user->register_at = Utils::getTimeFormatted(); - $user->last_sign_at = Utils::getTimeFormatted(time() - 86400); + $user->register_at = get_datetime_string(); + $user->last_sign_at = get_datetime_string(time() - 86400); $user->permission = User::SUPER_ADMIN; }); Log::info("[SetupWizard] Super Admin registered.", ['user' => $user]); diff --git a/app/Http/Controllers/SkinlibController.php b/app/Http/Controllers/SkinlibController.php index f029a3f9..5e4aa914 100644 --- a/app/Http/Controllers/SkinlibController.php +++ b/app/Http/Controllers/SkinlibController.php @@ -3,7 +3,6 @@ namespace App\Http\Controllers; use View; -use Utils; use Option; use Storage; use Session; @@ -20,6 +19,23 @@ class SkinlibController extends Controller { protected $user = null; + /** + * Map error code of file uploading to human-readable text. + * + * @see http://php.net/manual/en/features.file-upload.errors.php + * @var array + */ + public static $phpFileUploadErrors = [ + 0 => 'There is no error, the file uploaded with success', + 1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini', + 2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', + 3 => 'The uploaded file was only partially uploaded', + 4 => 'No file was uploaded', + 6 => 'Missing a temporary folder', + 7 => 'Failed to write file to disk.', + 8 => 'A PHP extension stopped the file upload.', + ]; + public function __construct(UserRepository $users) { // Try to load user by uid stored in session. @@ -167,7 +183,7 @@ class SkinlibController extends Controller $t->size = ceil($request->file('file')->getSize() / 1024); $t->public = ($request->input('public') == 'true') ? "1" : "0"; $t->uploader = $this->user->uid; - $t->upload_at = Utils::getTimeFormatted(); + $t->upload_at = get_datetime_string(); $cost = $t->size * (($t->public == "1") ? Option::get('score_per_storage') : Option::get('private_score_per_storage')); $cost += option('score_per_closet_item'); @@ -334,7 +350,7 @@ class SkinlibController extends Controller { if ($file = $request->files->get('file')) { if ($file->getError() !== UPLOAD_ERR_OK) { - return json(Utils::convertUploadFileError($file->getError()), $file->getError()); + return json(static::$phpFileUploadErrors[$file->getError()], $file->getError()); } } diff --git a/app/Http/Controllers/UserController.php b/app/Http/Controllers/UserController.php index e5573f03..cb8a2cd6 100644 --- a/app/Http/Controllers/UserController.php +++ b/app/Http/Controllers/UserController.php @@ -5,7 +5,6 @@ namespace App\Http\Controllers; use App; use Mail; use View; -use Utils; use Session; use App\Models\User; use App\Models\Texture; diff --git a/app/Models/Player.php b/app/Models/Player.php index b39d0df2..09d4ceb3 100644 --- a/app/Models/Player.php +++ b/app/Models/Player.php @@ -3,7 +3,6 @@ namespace App\Models; use Event; -use Utils; use Response; use App\Models\User; use App\Events\GetPlayerJson; @@ -98,7 +97,7 @@ class Player extends Model } } - $this->last_modified = Utils::getTimeFormatted(); + $this->last_modified = get_datetime_string(); $this->save(); @@ -159,7 +158,7 @@ class Player extends Model { $this->update([ 'preference' => $type, - 'last_modified' => Utils::getTimeFormatted() + 'last_modified' => get_datetime_string() ]); event(new PlayerProfileUpdated($this)); @@ -187,7 +186,7 @@ class Player extends Model { $this->update([ 'player_name' => $newName, - 'last_modified' => Utils::getTimeFormatted() + 'last_modified' => get_datetime_string() ]); $this->player_name = $newName; @@ -272,7 +271,7 @@ class Player extends Model public function updateLastModified() { // @see http://stackoverflow.com/questions/2215354/php-date-format-when-inserting-into-datetime-in-mysql - $this->update(['last_modified' => Utils::getTimeFormatted()]); + $this->update(['last_modified' => get_datetime_string()]); return event(new PlayerProfileUpdated($this)); } } diff --git a/app/Models/User.php b/app/Models/User.php index 6289d8d0..7170a452 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -3,7 +3,6 @@ namespace App\Models; use DB; -use Utils; use Carbon\Carbon; use App\Events\EncryptUserPassword; use Illuminate\Database\Eloquent\Model; @@ -301,7 +300,7 @@ class User extends Model $acquiredScore = rand($scoreLimits[0], $scoreLimits[1]); $this->setScore($acquiredScore, 'plus'); - $this->last_sign_at = Utils::getTimeFormatted(); + $this->last_sign_at = get_datetime_string(); $this->save(); return $acquiredScore; diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index e8df2704..b0ab2178 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -4,7 +4,6 @@ namespace App\Providers; use View; use Event; -use Utils; use Parsedown; use App\Events; use ReflectionException; @@ -62,7 +61,7 @@ class AppServiceProvider extends ServiceProvider } } - if (option('force_ssl') || Utils::isRequestSecure()) { + if (option('force_ssl') || is_request_secure()) { $this->app['url']->forceSchema('https'); } } diff --git a/app/Services/Utils.php b/app/Services/Utils.php index d3f728f9..ed14f4ab 100644 --- a/app/Services/Utils.php +++ b/app/Services/Utils.php @@ -3,10 +3,6 @@ namespace App\Services; use Log; -use Storage; -use Carbon\Carbon; -use Illuminate\Support\Str; -use App\Exceptions\PrettyPageException; class Utils { @@ -16,21 +12,12 @@ class Utils * This method is defined because Symfony's Request::getClientIp() needs "setTrustedProxies()" * which sucks when load balancer is enabled. * + * @deprecated Use the helper function instead. * @return string */ public static function getClientIp() { - if (option('ip_get_method') == "0") { - // Fallback to REMOTE_ADDR - $ip = array_get( - $_SERVER, 'HTTP_X_FORWARDED_FOR', - array_get($_SERVER, 'HTTP_CLIENT_IP', $_SERVER['REMOTE_ADDR']) - ); - } else { - $ip = array_get($_SERVER, 'REMOTE_ADDR'); - } - - return $ip; + return get_client_ip(); } /** @@ -40,20 +27,12 @@ class Utils * This method is defined because Symfony's Request::isSecure() needs "setTrustedProxies()" * which sucks when load balancer is enabled. * + * @deprecated Use the helper function instead. * @return bool */ public static function isRequestSecure() { - if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') - return true; - - if (! empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') - return true; - - if (! empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') - return true; - - return false; + return is_request_secure(); } public static function download($url, $path) @@ -119,46 +98,29 @@ class Utils return strlen(stream_get_contents($fp)); } + /** + * Get date time string in "Y-m-d H:i:s" format. + * + * @deprecated Use the helper function instead. + * @param integer $timestamp + * @return string + */ public static function getTimeFormatted($timestamp = 0) { - return ($timestamp == 0) ? Carbon::now()->toDateTimeString() : Carbon::createFromTimestamp($timestamp)->toDateTimeString(); + return get_datetime_string($timestamp); } /** * Replace content of string according to given rules. * + * @deprecated Use the helper function instead. * @param string $str * @param array $rules * @return string */ public static function getStringReplaced($str, $rules) { - foreach ($rules as $search => $replace) { - $str = str_replace($search, $replace, $str); - } - return $str; - } - - /** - * Convert error number of uploading files to human-readable text. - * - * @param int $errno - * @return string - */ - public static function convertUploadFileError($errno = 0) - { - $phpFileUploadErrors = [ - 0 => 'There is no error, the file uploaded with success', - 1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini', - 2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', - 3 => 'The uploaded file was only partially uploaded', - 4 => 'No file was uploaded', - 6 => 'Missing a temporary folder', - 7 => 'Failed to write file to disk.', - 8 => 'A PHP extension stopped the file upload.', - ]; - - return $phpFileUploadErrors[$errno]; + return get_string_replaced($str, $rules); } } diff --git a/app/helpers.php b/app/helpers.php index 729b3ec0..8d0649ac 100644 --- a/app/helpers.php +++ b/app/helpers.php @@ -258,7 +258,7 @@ if (! function_exists('bs_custom_copyright')) { function bs_custom_copyright() { - return Utils::getStringReplaced(option_localized('copyright_text'), [ + return get_string_replaced(option_localized('copyright_text'), [ '{site_name}' => option_localized('site_name'), '{site_url}' => option('site_url') ]); @@ -546,3 +546,88 @@ if (! function_exists('format_http_date')) { return Carbon::createFromTimestampUTC($timestamp)->format('D, d M Y H:i:s \G\M\T'); } } + +if (! function_exists('get_datetime_string')) { + /** + * Get date time string in "Y-m-d H:i:s" format. + * + * @param integer $timestamp + * @return string + */ + function get_datetime_string($timestamp = 0) { + return $timestamp == 0 ? Carbon::now()->toDateTimeString() : Carbon::createFromTimestamp($timestamp)->toDateTimeString(); + } +} + +if (! function_exists('get_client_ip')) { + /** + * Return the client IP address. + * + * We define this function because Symfony's "Request::getClientIp()" method + * needs "setTrustedProxies()", which sucks when load balancer is enabled. + * + * @return string + */ + function get_client_ip() { + if (option('ip_get_method') == "0") { + // Use `HTTP_X_FORWARDED_FOR` if available first + $ip = array_get( + $_SERVER, + 'HTTP_X_FORWARDED_FOR', + // Fallback to `HTTP_CLIENT_IP` + array_get( + $_SERVER, + 'HTTP_CLIENT_IP', + // Fallback to `REMOTE_ADDR` + array_get($_SERVER, 'REMOTE_ADDR') + ) + ); + } else { + $ip = array_get($_SERVER, 'REMOTE_ADDR'); + } + + return $ip; + } +} + +if (! function_exists('get_string_replaced')) { + /** + * Replace content of string according to given rules. + * + * @param string $str + * @param array $rules + * @return string + */ + function get_string_replaced($str, $rules) + { + foreach ($rules as $search => $replace) { + $str = str_replace($search, $replace, $str); + } + return $str; + } +} + +if (! function_exists('is_request_secure')) { + /** + * Check whether the request is secure or not. + * True is always returned when "X-Forwarded-Proto" header is set. + * + * We define this function because Symfony's "Request::isSecure()" method + * needs "setTrustedProxies()" which sucks when load balancer is enabled. + * + * @return bool + */ + function is_request_secure() + { + if (array_get($_SERVER, 'HTTPS') == 'on') + return true; + + if (array_get($_SERVER, 'HTTP_X_FORWARDED_PROTO') == 'https') + return true; + + if (array_get($_SERVER, 'HTTP_X_FORWARDED_SSL') == 'on') + return true; + + return false; + } +} diff --git a/resources/views/admin/update.tpl b/resources/views/admin/update.tpl index 718a84c1..2cd46a0e 100644 --- a/resources/views/admin/update.tpl +++ b/resources/views/admin/update.tpl @@ -41,7 +41,7 @@